diff --git a/src/Common/Common.vcxproj b/src/Common/Common.vcxproj index a36b85aa06a..a87d5eaae82 100644 --- a/src/Common/Common.vcxproj +++ b/src/Common/Common.vcxproj @@ -76,6 +76,7 @@ + diff --git a/src/Common/Common.vcxproj.filters b/src/Common/Common.vcxproj.filters index 96a3b808832..1668e17bcc4 100644 --- a/src/Common/Common.vcxproj.filters +++ b/src/Common/Common.vcxproj.filters @@ -92,6 +92,7 @@ Externals + diff --git a/src/Common/LevelGameDef.h b/src/Common/LevelGameDef.h index 9f750f14d3e..a3041d62e3d 100644 --- a/src/Common/LevelGameDef.h +++ b/src/Common/LevelGameDef.h @@ -22,6 +22,7 @@ enum ERPpointType rptActorSpawn = 0, rptArtefactSpawn, rptItemSpawn, + rptTeamBaseParticle = rptItemSpawn, rptLast = 0xff }; @@ -35,14 +36,9 @@ enum EEnvModUsedParams eHemiColor = (1 << 5) }; -/* // XXX: find better place for this (need cpp) -xr_token rpoint_type[] = { - {"Actor Spawn", rptActorSpawn}, - {"Artefact Spawn", rptArtefactSpawn}, - {"Item Spawn", rptItemSpawn}, - {nullptr, rptLast} -}; -*/ +extern xr_token rpoint_type[]; +extern xr_token rpoint_type_soc[]; +extern const xr_token rpoint_game_type[]; // BASE offset #define WAY_BASE 0x1000 diff --git a/src/Common/RDevice.h b/src/Common/RDevice.h new file mode 100644 index 00000000000..b6cb31708fb --- /dev/null +++ b/src/Common/RDevice.h @@ -0,0 +1,7 @@ +#pragma once + +#ifndef _EDITOR +#define RDEVICE Device +#else +#define RDEVICE EDevice +#endif diff --git a/src/Include/xrAPI/xrAPI.h b/src/Include/xrAPI/xrAPI.h index 4699f6e6f2c..a1bdc71513f 100644 --- a/src/Include/xrAPI/xrAPI.h +++ b/src/Include/xrAPI/xrAPI.h @@ -22,16 +22,16 @@ class UICore; class XRAPI_API EngineGlobalEnvironment { public: - IRender* Render; IDebugRender* DRender; CDUInterface* DU; IUIRender* UIRender; - IRenderFactory* RenderFactory; CScriptEngine* ScriptEngine; - AISpaceBase* AISpace; - ISoundManager* Sound; + AISpaceBase* AISpace; UICore* UI; + ISoundManager* Sound; + IRender* Render; + IRenderFactory* RenderFactory; bool isDedicatedServer; }; diff --git a/src/Include/xrRender/FactoryPtr.h b/src/Include/xrRender/FactoryPtr.h index 85e38815e1e..71f279cda3a 100644 --- a/src/Include/xrRender/FactoryPtr.h +++ b/src/Include/xrRender/FactoryPtr.h @@ -79,6 +79,7 @@ FACTORY_PTR_INSTANCIATE(EnvironmentRender) FACTORY_PTR_INSTANCIATE(EnvDescriptorRender) #endif // _EDITOR FACTORY_PTR_INSTANCIATE(FontRender) + /* void FactoryPtr::CreateObject(void) { diff --git a/src/Include/xrRender/RenderFactory.h b/src/Include/xrRender/RenderFactory.h index b16ff0c2463..b592a199fc9 100644 --- a/src/Include/xrRender/RenderFactory.h +++ b/src/Include/xrRender/RenderFactory.h @@ -62,6 +62,7 @@ class IRenderFactory RENDER_FACTORY_INTERFACE(FlareRender) #endif // _EDITOR RENDER_FACTORY_INTERFACE(FontRender) + protected: // virtual IEnvDescriptorRender *CreateEnvDescriptorRender() = 0; // virtual void DestroyEnvDescriptorRender(IEnvDescriptorRender *pObject) = 0; diff --git a/src/Layers/xrRender/Blender.cpp b/src/Layers/xrRender/Blender.cpp index e30df0d4e22..46018b803af 100644 --- a/src/Layers/xrRender/Blender.cpp +++ b/src/Layers/xrRender/Blender.cpp @@ -19,15 +19,11 @@ void CBlender_DESC::Setup(LPCSTR N) xr_strlwr(cName); xr_strcpy(cComputer, Core.CompName); // Computer -#ifndef _EDITOR + #if defined(XR_PLATFORM_WINDOWS) // TODO Implement for Linux _tzset(); _time32((__time32_t*)&cTime); // Time #endif -#else - _tzset(); - time((long*)&cTime); // Time -#endif }; ////////////////////////////////////////////////////////////////////// @@ -84,6 +80,7 @@ void IBlender::Compile(CBlender_Compile& C) C.SetParams(oPriority.value, oStrictSorting.value ? true : false); } +#ifndef _EDITOR IBlender* IBlender::Create(CLASS_ID cls) { return ::RImplementation.blender_create(cls); @@ -93,3 +90,49 @@ void IBlender::Destroy(IBlender*& B) { ::RImplementation.blender_destroy(B); } +#else + +// Editor +#include "blenders/BlenderDefault.h" +#include "blenders/Blender_default_aref.h" +#include "blenders/Blender_Vertex.h" +#include "blenders/Blender_Vertex_aref.h" +#include "blenders/Blender_Screen_SET.h" +#include "blenders/Blender_Screen_GRAY.h" +#include "blenders/Blender_Editor_Wire.h" +#include "blenders/Blender_Editor_Selection.h" +#include "blenders/Blender_LaEmB.h" +#include "blenders/Blender_Lm(EbB).h" +#include "blenders/Blender_BmmD.h" +#include "blenders/Blender_Model.h" +#include "blenders/Blender_Model_EbB.h" +#include "blenders/Blender_detail_still.h" +#include "blenders/Blender_tree.h" +#include "blenders/Blender_Particle.h" + +IBlender* IBlender::Create(CLASS_ID cls) +{ + switch (cls) + { + case B_DEFAULT: return xr_new(); + case B_DEFAULT_AREF: return xr_new(); + case B_VERT: return xr_new(); + case B_VERT_AREF: return xr_new(); + case B_SCREEN_SET: return xr_new(); + case B_SCREEN_GRAY: return xr_new(); + case B_EDITOR_WIRE: return xr_new(); + case B_EDITOR_SEL: return xr_new(); + case B_LaEmB: return xr_new(); + case B_LmEbB: return xr_new(); + case B_BmmD: return xr_new(); + case B_MODEL: return xr_new(); + case B_MODEL_EbB: return xr_new(); + case B_DETAIL: return xr_new(); + case B_TREE: return xr_new(); + case B_PARTICLE: return xr_new(); + } + return 0; +} +void IBlender::Destroy(IBlender*& B) { xr_delete(B); } + +#endif diff --git a/src/Layers/xrRender/Blender.h b/src/Layers/xrRender/Blender.h index 535502259a9..1d4eef5aa5f 100644 --- a/src/Layers/xrRender/Blender.h +++ b/src/Layers/xrRender/Blender.h @@ -49,6 +49,7 @@ class ECORE_API IBlender : public CPropertyBase public: static IBlender* Create(CLASS_ID cls); static void Destroy(IBlender*& B); + static void CreatePalette(xr_vector& palette); CBlender_DESC& getDescription() { return description; } virtual LPCSTR getName() { return description.cName; } diff --git a/src/Layers/xrRender/Blender_Palette.cpp b/src/Layers/xrRender/Blender_Palette.cpp new file mode 100644 index 00000000000..de1e8ffb10c --- /dev/null +++ b/src/Layers/xrRender/Blender_Palette.cpp @@ -0,0 +1,59 @@ +#include "stdafx.h" +#include "Blender.h" +#include "blender_clsid.h" + +IC bool p_sort(IBlender *A, IBlender *B) +{ + return stricmp(A->getComment(), B->getComment()) < 0; +} + +#define TYPES_EQUAL(A, B) (typeid(A).raw_name() == typeid(B).raw_name()) + +void IBlender::CreatePalette(xr_vector &palette) +{ + // Create palette itself + R_ASSERT(palette.empty()); + palette.push_back(Create(B_DEFAULT)); + palette.push_back(Create(B_DEFAULT_AREF)); + palette.push_back(Create(B_VERT)); + palette.push_back(Create(B_VERT_AREF)); + palette.push_back(Create(B_SCREEN_SET)); + palette.push_back(Create(B_SCREEN_GRAY)); + palette.push_back(Create(B_EDITOR_WIRE)); + palette.push_back(Create(B_EDITOR_SEL)); + palette.push_back(Create(B_LIGHT)); + palette.push_back(Create(B_LaEmB)); + palette.push_back(Create(B_LmEbB)); + palette.push_back(Create(B_BmmD)); + palette.push_back(Create(B_B)); + palette.push_back(Create(B_SHADOW_WORLD)); + palette.push_back(Create(B_BLUR)); + palette.push_back(Create(B_MODEL)); + palette.push_back(Create(B_MODEL_EbB)); + palette.push_back(Create(B_DETAIL)); + palette.push_back(Create(B_TREE)); + palette.push_back(Create(B_PARTICLE)); + + // Remove duplicated classes (some of them are really the same in different renderers) + for (u32 i = 0; i < palette.size(); i++) + { + IBlender *A = palette[i]; + for (u32 j = i + 1; j < palette.size(); j++) + { + IBlender *B = palette[j]; + if ((A && B) && TYPES_EQUAL(*A, *B)) + { + xr_delete(palette[j]); + j--; + } + } + } + for (u32 i = palette.size(); i != 0; i--) + { + u32 real_i = i - 1; + if (!palette[real_i]) + palette.erase(palette.begin() + real_i); + } + // Sort by desc and return + std::sort(palette.begin(), palette.end(), p_sort); +} diff --git a/src/Layers/xrRender/Blender_Recorder_StandartBinding.cpp b/src/Layers/xrRender/Blender_Recorder_StandartBinding.cpp index b69b3f14338..cc1ab98dc94 100644 --- a/src/Layers/xrRender/Blender_Recorder_StandartBinding.cpp +++ b/src/Layers/xrRender/Blender_Recorder_StandartBinding.cpp @@ -6,7 +6,12 @@ #include "Blender.h" #include "xrEngine/IGame_Persistent.h" + +#ifndef _EDITOR #include "xrEngine/Environment.h" +#endif + +#include "Common/RDevice.h" // matrices #define BIND_DECLARE(xf)\ @@ -67,8 +72,8 @@ class cl_texgen : public R_constant_setup Fmatrix mTexgen; #if defined(USE_DX9) - float _w = float(Device.dwWidth); - float _h = float(Device.dwHeight); + float _w = float(RDEVICE.dwWidth); + float _h = float(RDEVICE.dwHeight); float o_w = (.5f / _w); float o_h = (.5f / _h); Fmatrix mTexelAdjust = @@ -111,8 +116,8 @@ class cl_VPtexgen : public R_constant_setup Fmatrix mTexgen; #if defined(USE_DX9) - float _w = float(Device.dwWidth); - float _h = float(Device.dwHeight); + float _w = float(RDEVICE.dwWidth); + float _h = float(RDEVICE.dwHeight); float o_w = (.5f / _w); float o_h = (.5f / _h); Fmatrix mTexelAdjust = @@ -221,7 +226,7 @@ class cl_times : public R_constant_setup { void setup(CBackend& cmd_list, R_constant* C) override { - float t = Device.fTimeGlobal; + float t = RDEVICE.fTimeGlobal; cmd_list.set_c(C, t, t * 10, t / 10, _sin(t)); } }; @@ -232,7 +237,7 @@ class cl_eye_P : public R_constant_setup { void setup(CBackend& cmd_list, R_constant* C) override { - Fvector& V = Device.vCameraPosition; + Fvector& V = RDEVICE.vCameraPosition; cmd_list.set_c(C, V.x, V.y, V.z, 1.f); } }; @@ -243,7 +248,7 @@ class cl_eye_D : public R_constant_setup { void setup(CBackend& cmd_list, R_constant* C) override { - Fvector& V = Device.vCameraDirection; + Fvector& V = RDEVICE.vCameraDirection; cmd_list.set_c(C, V.x, V.y, V.z, 0.f); } }; @@ -254,7 +259,7 @@ class cl_eye_N : public R_constant_setup { void setup(CBackend& cmd_list, R_constant* C) override { - Fvector& V = Device.vCameraTop; + Fvector& V = RDEVICE.vCameraTop; cmd_list.set_c(C, V.x, V.y, V.z, 0.f); } }; @@ -348,8 +353,8 @@ static class cl_screen_res : public R_constant_setup { void setup(CBackend& cmd_list, R_constant* C) override { - cmd_list.set_c(C, (float)Device.dwWidth, (float)Device.dwHeight, 1.0f / (float)Device.dwWidth, - 1.0f / (float)Device.dwHeight); + cmd_list.set_c(C, (float)RDEVICE.dwWidth, (float)RDEVICE.dwHeight, 1.0f / (float)RDEVICE.dwWidth, + 1.0f / (float)RDEVICE.dwHeight); } } binder_screen_res; diff --git a/src/Layers/xrRender/DetailFormat.h b/src/Layers/xrRender/DetailFormat.h index c48fee4ec99..070729cc0d2 100644 --- a/src/Layers/xrRender/DetailFormat.h +++ b/src/Layers/xrRender/DetailFormat.h @@ -54,6 +54,7 @@ u16* indices; */ +class EDetailManager; #define DO_NO_WAVING 0x0001 class DetailHeader @@ -115,6 +116,8 @@ class DetailHeader u32 slot_count() const { return size_x * size_z; } float slot_min_x(int _x) const { return (int(_x) - int(offs_x)) * DETAIL_SLOT_SIZE; } float slot_min_z(int _z) const { return (int(_z) - int(offs_z)) * DETAIL_SLOT_SIZE; } + + friend class EDetailManager; }; struct DetailPalette diff --git a/src/Layers/xrRender/DetailManager.cpp b/src/Layers/xrRender/DetailManager.cpp index f8f283c8f5d..969241d6f73 100644 --- a/src/Layers/xrRender/DetailManager.cpp +++ b/src/Layers/xrRender/DetailManager.cpp @@ -1,20 +1,9 @@ // DetailManager.cpp: implementation of the CDetailManager class. -// -////////////////////////////////////////////////////////////////////// - #include "stdafx.h" -#pragma hdrstop - #include "DetailManager.h" #include "xrCDB/Intersect.hpp" -#ifdef _EDITOR -#include "ESceneClassList.h" -#include "Scene.h" -#include "SceneObject.h" -#include "IGame_Persistent.h" -#include "Environment.h" -#else +#ifndef _EDITOR #include "xrEngine/IGame_Persistent.h" #include "xrEngine/Environment.h" #if defined(XR_ARCHITECTURE_X86) || defined(XR_ARCHITECTURE_X64) || defined(XR_ARCHITECTURE_E2K) @@ -80,7 +69,10 @@ void CDetailManager::SSwingValue::lerp(const SSwingValue& A, const SSwingValue& // Construction/Destruction ////////////////////////////////////////////////////////////////////// // XXX stats: add to statistics -CDetailManager::CDetailManager() : xrc("detail manager") +CDetailManager::CDetailManager() + #ifndef _EDITOR + : xrc("detail manager") + #endif { dtFS = nullptr; dtSlots = nullptr; @@ -245,7 +237,7 @@ void CDetailManager::UpdateVisibleM() vis.clear(); CFrustum View; - View.CreateFromMatrix(Device.mFullTransformSaved, FRUSTUM_P_LRTB + FRUSTUM_P_FAR); + View.CreateFromMatrix(RDEVICE.mFullTransformSaved, FRUSTUM_P_LRTB + FRUSTUM_P_FAR); float fade_limit = dm_fade; fade_limit = fade_limit * fade_limit; @@ -307,7 +299,7 @@ void CDetailManager::UpdateVisibleM() } #endif // Add to visibility structures - if (Device.dwFrame > S.frame) + if (RDEVICE.dwFrame > S.frame) { // Calc fade factor (per slot) float dist_sq = EYE.distance_to_sqr(S.vis.sphere.P); @@ -317,7 +309,7 @@ void CDetailManager::UpdateVisibleM() float alpha_i = 1.f - alpha; float dist_sq_rcp = 1.f / dist_sq; - S.frame = Device.dwFrame + Random.randI(15, 30); + S.frame = RDEVICE.dwFrame + Random.randI(15, 30); for (int sp_id = 0; sp_id < dm_obj_in_slot; sp_id++) { SlotPart& sp = S.G[sp_id]; @@ -392,9 +384,9 @@ void CDetailManager::Render(CBackend& cmd_list) MT_SYNC(); RImplementation.BasicStats.DetailRender.Begin(); - g_pGamePersistent->m_pGShaderConstants->m_blender_mode.w = 1.0f; //--#SM+#-- Флаг начала рендера травы [begin of grass render] #ifndef _EDITOR + g_pGamePersistent->m_pGShaderConstants->m_blender_mode.w = 1.0f; //--#SM+#-- Флаг начала рендера травы [begin of grass render] float factor = g_pGamePersistent->Environment().wind_strength_factor; #else float factor = 0.3f; @@ -409,9 +401,12 @@ void CDetailManager::Render(CBackend& cmd_list) soft_Render(); cmd_list.set_CullMode(CULL_CCW); +#ifndef _EDITOR g_pGamePersistent->m_pGShaderConstants->m_blender_mode.w = 0.0f; //--#SM+#-- Флаг конца рендера травы [end of grass render] +#endif + RImplementation.BasicStats.DetailRender.End(); - m_frame_rendered = Device.dwFrame; + m_frame_rendered = RDEVICE.dwFrame; } void CDetailManager::MT_CALC() @@ -425,11 +420,11 @@ void CDetailManager::MT_CALC() return; #endif - EYE = Device.vCameraPosition; + EYE = RDEVICE.vCameraPosition; MT.Enter(); - if (m_frame_calc != Device.dwFrame) - if ((m_frame_rendered + 1) == Device.dwFrame) // already rendered + if (m_frame_calc != RDEVICE.dwFrame) + if ((m_frame_rendered + 1) == RDEVICE.dwFrame) // already rendered { int s_x = iFloor(EYE.x / dm_slot_size + .5f); int s_z = iFloor(EYE.z / dm_slot_size + .5f); @@ -439,7 +434,7 @@ void CDetailManager::MT_CALC() RImplementation.BasicStats.DetailCache.End(); UpdateVisibleM(); - m_frame_calc = Device.dwFrame; + m_frame_calc = RDEVICE.dwFrame; } MT.Leave(); } diff --git a/src/Layers/xrRender/DetailManager.h b/src/Layers/xrRender/DetailManager.h index 5e9bc3a0999..edd033fa334 100644 --- a/src/Layers/xrRender/DetailManager.h +++ b/src/Layers/xrRender/DetailManager.h @@ -23,6 +23,7 @@ typedef ObjectMap::iterator ObjectPairIt; #else const int dm_max_decompress = 7; +#include "Common/RDevice.h" #endif //const int dm_size = 24; const int dm_cache1_count = 4; @@ -50,7 +51,13 @@ extern float dm_current_fade;// = float(2*dm_current_size)-.5f; extern float ps_current_detail_density; extern float ps_current_detail_height; -class ECORE_API CDetailManager +#ifdef _EDITOR +#define DET_MANAGER_API +#else +#define DET_MANAGER_API ECORE_API +#endif + +class DET_MANAGER_API CDetailManager { public: struct SlotItem @@ -232,7 +239,7 @@ class ECORE_API CDetailManager void MT_CALC(); ICF void MT_SYNC() { - if (m_frame_calc == Device.dwFrame) + if (m_frame_calc == RDEVICE.dwFrame) return; MT_CALC(); diff --git a/src/Layers/xrRender/DetailManager_Decompress.cpp b/src/Layers/xrRender/DetailManager_Decompress.cpp index 97448a8ae96..2d763e13ee1 100644 --- a/src/Layers/xrRender/DetailManager_Decompress.cpp +++ b/src/Layers/xrRender/DetailManager_Decompress.cpp @@ -1,10 +1,9 @@ #include "stdafx.h" -#pragma hdrstop #include "DetailManager.h" #include "xrCDB/Intersect.hpp" + #ifdef _EDITOR -#include "scene.h" -#include "sceneobject.h" +#include "editors/LevelEditor/Scene/scene.h" #include "utils/ETools/ETools.h" #endif @@ -83,10 +82,18 @@ void CDetailManager::cache_Decompress(Slot* S) Fvector bC, bD; D.vis.box.get_CD(bC, bD); +#ifdef _EDITOR + ETOOLS::box_options(CDB::OPT_FULL_TEST); + // Select polygons + SBoxPickInfoVec pinf; + Scene->BoxPickObjects(D.vis.box, pinf, GetSnapList()); + u32 triCount = pinf.size(); +#else xrc.box_query(CDB::OPT_FULL_TEST, g_pGameLevel->ObjectSpace.GetStaticModel(), bC, bD); const auto triCount = xrc.r_count(); CDB::TRI* tris = g_pGameLevel->ObjectSpace.GetStaticTris(); Fvector* verts = g_pGameLevel->ObjectSpace.GetStaticVerts(); +#endif if (0 == triCount) return; @@ -193,6 +200,27 @@ void CDetailManager::cache_Decompress(Slot* S) float r_u, r_v, r_range; for (size_t tid = 0; tid < triCount; tid++) { +#ifdef _EDITOR + Fvector verts[3]; + SBoxPickInfo& I = pinf[tid]; + + for (int k = 0; k < (int)I.inf.size(); k++) + { + VERIFY(I.s_obj); + RDEVICE.Statistic->TEST0.Begin(); + I.e_obj->GetFaceWorld(I.s_obj->_Transform(), I.e_mesh, I.inf[k].id, verts); + RDEVICE.Statistic->TEST0.End(); + if (CDB::TestRayTri(Item_P, dir, verts, r_u, r_v, r_range, TRUE)) + { + if (r_range >= 0) + { + float y_test = Item_P.y - r_range; + if (y_test > y) + y = y_test; + } + } + } +#else CDB::TRI& T = tris[xrc.r_begin()[tid].id]; SGameMtl* mtl = GMLib.GetMaterialByIdx(T.material); if (mtl->Flags.test(SGameMtl::flPassable)) @@ -208,6 +236,7 @@ void CDetailManager::cache_Decompress(Slot* S) y = y_test; } } +#endif } if (y < D.vis.box.vMin.y) continue; diff --git a/src/Layers/xrRender/DetailManager_VS.cpp b/src/Layers/xrRender/DetailManager_VS.cpp index 8ee7cc7e01f..e67db7c4093 100644 --- a/src/Layers/xrRender/DetailManager_VS.cpp +++ b/src/Layers/xrRender/DetailManager_VS.cpp @@ -1,7 +1,12 @@ #include "stdafx.h" -#pragma hdrstop #include "DetailManager.h" +#ifndef _EDITOR +#include "xrEngine/IGame_Persistent.h" +#include "xrEngine/Environment.h" +#endif +#include "Layers/xrRender/BufferUtils.h" + namespace detail_manager { extern const int quant = 16384; diff --git a/src/Layers/xrRender/DetailManager_soft.cpp b/src/Layers/xrRender/DetailManager_soft.cpp index da412633f39..852607957b6 100644 --- a/src/Layers/xrRender/DetailManager_soft.cpp +++ b/src/Layers/xrRender/DetailManager_soft.cpp @@ -13,7 +13,11 @@ void CDetailManager::soft_Load() soft_Geom.create(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1, RImplementation.Vertex.Buffer(), RImplementation.Index.Buffer()); } -void CDetailManager::soft_Unload() { soft_Geom.destroy(); } +void CDetailManager::soft_Unload() +{ + soft_Geom.destroy(); +} + void CDetailManager::soft_Render() { // Render itself diff --git a/src/Layers/xrRender/ETextureParams.cpp b/src/Layers/xrRender/ETextureParams.cpp index c317e601a8f..f663f213e57 100644 --- a/src/Layers/xrRender/ETextureParams.cpp +++ b/src/Layers/xrRender/ETextureParams.cpp @@ -4,7 +4,7 @@ #include "ETextureParams.h" #include "xrCore/xr_token.h" -const xr_token tparam_token[] = {{"Advanced", STextureParams::kMIPFilterAdvanced}, +xr_token tparam_token[] = {{"Advanced", STextureParams::kMIPFilterAdvanced}, {"Point", STextureParams::kMIPFilterPoint}, {"Box", STextureParams::kMIPFilterBox}, {"Triangle", STextureParams::kMIPFilterTriangle}, {"Quadratic", STextureParams::kMIPFilterQuadratic}, @@ -18,21 +18,21 @@ const xr_token tparam_token[] = {{"Advanced", STextureParams::kMIPFilterAdvanced {"Hanning", STextureParams::kMIPFilterHanning}, {"Hamming", STextureParams::kMIPFilterHamming}, {"Blackman", STextureParams::kMIPFilterBlackman}, {"Kaiser", STextureParams::kMIPFilterKaiser}, {nullptr, 0}}; -const xr_token ttype_token[] = {{"2D Texture", STextureParams::ttImage}, {"Cube Map", STextureParams::ttCubeMap}, +xr_token ttype_token[] = {{"2D Texture", STextureParams::ttImage}, {"Cube Map", STextureParams::ttCubeMap}, {"Bump Map", STextureParams::ttBumpMap}, {"Normal Map", STextureParams::ttNormalMap}, {"Terrain", STextureParams::ttTerrain}, {nullptr, 0}}; -const xr_token tfmt_token[] = {{"DXT1", STextureParams::tfDXT1}, {"DXT1 Alpha", STextureParams::tfADXT1}, +xr_token tfmt_token[] = {{"DXT1", STextureParams::tfDXT1}, {"DXT1 Alpha", STextureParams::tfADXT1}, {"DXT3", STextureParams::tfDXT3}, {"DXT5", STextureParams::tfDXT5}, {"16 bit (1:5:5:5)", STextureParams::tf1555}, {"16 bit (5:6:5)", STextureParams::tf565}, {"32 bit (8:8:8:8)", STextureParams::tfRGBA}, {"8 bit (alpha)", STextureParams::tfA8}, {"8 bit (luminance)", STextureParams::tfL8}, {"16 bit (alpha:luminance)", STextureParams::tfA8L8}, {nullptr, 0}}; -const xr_token tmtl_token[] = {{"OrenNayar <-> Blin", STextureParams::tmOrenNayar_Blin}, +xr_token tmtl_token[] = {{"OrenNayar <-> Blin", STextureParams::tmOrenNayar_Blin}, {"Blin <-> Phong", STextureParams::tmBlin_Phong}, {"Phong <-> Metal", STextureParams::tmPhong_Metal}, {"Metal <-> OrenNayar", STextureParams::tmMetal_OrenNayar}, {nullptr, 0}}; -const xr_token tbmode_token[] = {{"None", STextureParams::tbmNone}, {"Use", STextureParams::tbmUse}, +xr_token tbmode_token[] = {{"None", STextureParams::tbmNone}, {"Use", STextureParams::tbmUse}, {"Use parallax", STextureParams::tbmUseParallax}, {nullptr, 0}}; void STextureParams::Load(IReader& F) @@ -173,7 +173,7 @@ void STextureParams::FillProp(LPCSTR base_name, PropItemVec& items, PropValue::T P->OnChangeEvent.bind(this, &STextureParams::OnTypeChange); if (tbmUse == bump_mode || tbmUseParallax == bump_mode) { - AnsiString path; + xr_string path; path = base_name; PHelper().CreateChoose(items, "Bump" DELIMITER "Texture", &bump_name, smTexture, path.c_str()); } @@ -231,16 +231,16 @@ void STextureParams::FillProp(LPCSTR base_name, PropItemVec& items, PropValue::T } } -BOOL STextureParams::similar(STextureParams& tp1, xr_vector& sel_params) +BOOL STextureParams::similar(STextureParams& tp1, xr_vector& sel_params) { BOOL res = TRUE; - xr_vector::iterator it = sel_params.begin(); - xr_vector::iterator it_e = sel_params.end(); + auto it = sel_params.begin(); + auto it_e = sel_params.end(); for (; it != it_e; ++it) { - const AnsiString& par_name = *it; + const xr_string& par_name = *it; if (par_name == "Type") { res = (type == tp1.type); diff --git a/src/Layers/xrRender/ETextureParams.h b/src/Layers/xrRender/ETextureParams.h index 05eff53ee2f..6c16d69b71c 100644 --- a/src/Layers/xrRender/ETextureParams.h +++ b/src/Layers/xrRender/ETextureParams.h @@ -162,20 +162,19 @@ struct ECORE_API STextureParams void Save(IWriter& F); #ifdef _EDITOR PropValue::TOnChange OnTypeChangeEvent; - void __stdcall OnTypeChange(PropValue* v); + void OnTypeChange(PropValue* v); void FillProp(LPCSTR base_name, PropItemVec& items, PropValue::TOnChange OnChangeEvent); LPCSTR FormatString(); u32 MemoryUsage(LPCSTR base_name); - BOOL similar(STextureParams& tp1, xr_vector& sel_params); - + BOOL similar(STextureParams& tp1, xr_vector& sel_params); #endif }; #pragma pack(pop) struct xr_token; -extern const xr_token tparam_token[]; -extern const xr_token tfmt_token[]; -extern const xr_token ttype_token[]; +extern xr_token tparam_token[]; +extern xr_token tfmt_token[]; +extern xr_token ttype_token[]; //---------------------------------------------------- #define THM_CHUNK_VERSION 0x0810 diff --git a/src/Layers/xrRender/FVF.h b/src/Layers/xrRender/FVF.h index 048c6a86f2c..2a665ab3b78 100644 --- a/src/Layers/xrRender/FVF.h +++ b/src/Layers/xrRender/FVF.h @@ -85,6 +85,32 @@ struct LIT }; const u32 F_LIT = D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1; +struct TL0uv +{ + Fvector4 p; + u32 color; + IC void set(const TL0uv& src) { *this = src; }; + IC void set(float x, float y, u32 c) { set(x, y, .0001f, .9999f, c); }; + IC void set(int x, int y, u32 c) { set(float(x), float(y), .0001f, .9999f, c); }; + IC void set(float x, float y, float z, float w, u32 c) + { + p.set(x, y, z, w); + color = c; + }; + IC void transform(const Fvector& v, const Fmatrix& matSet) + { + // Transform it through the matrix set. Takes in mean projection. + // Finally, scale the vertices to screen coords. + // Note 1: device coords range from -1 to +1 in the viewport. + // Note 2: the p.z-coordinate will be used in the z-buffer. + p.w = matSet._14 * v.x + matSet._24 * v.y + matSet._34 * v.z + matSet._44; + p.x = (matSet._11 * v.x + matSet._21 * v.y + matSet._31 * v.z + matSet._41) / p.w; + p.y = -(matSet._12 * v.x + matSet._22 * v.y + matSet._32 * v.z + matSet._42) / p.w; + p.z = (matSet._13 * v.x + matSet._23 * v.y + matSet._33 * v.z + matSet._43) / p.w; + }; +}; +const u32 F_TL0uv = D3DFVF_XYZRHW | D3DFVF_DIFFUSE; + struct TL { Fvector4 p; diff --git a/src/Layers/xrRender/FVisual.cpp b/src/Layers/xrRender/FVisual.cpp index cceb663da5d..5b46382a2d4 100644 --- a/src/Layers/xrRender/FVisual.cpp +++ b/src/Layers/xrRender/FVisual.cpp @@ -25,9 +25,9 @@ void Fvisual::Load(const char* N, IReader* data, u32 dwFlags) dwPrimitives = 0; BOOL loaded_v = false; +#ifndef _EDITOR if (data->find_chunk(OGF_GCONTAINER)) { -#ifndef _EDITOR // verts u32 ID = data->r_u32(); vBase = data->r_u32(); @@ -49,7 +49,7 @@ void Fvisual::Load(const char* N, IReader* data, u32 dwFlags) VERIFY(nullptr == p_rm_Indices); p_rm_Indices = RImplementation.getIB(ID); p_rm_Indices->AddRef(); -#endif + // check for fast-vertices #if RENDER == R_R1 if (data->find_chunk(OGF_FASTPATH) && ps_r1_force_geomx) @@ -89,6 +89,7 @@ void Fvisual::Load(const char* N, IReader* data, u32 dwFlags) m_fast->rm_geom.create(fmt, *m_fast->p_rm_Vertices, *m_fast->p_rm_Indices); } } +#endif // read vertices if (!loaded_v && (dwFlags & VLOAD_NOVERTICES) == 0) diff --git a/src/Layers/xrRender/LightTrack.h b/src/Layers/xrRender/LightTrack.h index 976553ed7b4..8fa7a76eaab 100644 --- a/src/Layers/xrRender/LightTrack.h +++ b/src/Layers/xrRender/LightTrack.h @@ -6,10 +6,14 @@ #define AFX_LIGHTTRACK_H__89914D61_AC0B_4C7C_BA8C_D7D810738CE7__INCLUDED_ #pragma once +#include "xrCDB/xr_collide_defs.h" + const float lt_inc = 4.f; const float lt_dec = 2.f; const int lt_hemisamples = 26; +class light; + class CROS_impl : public IRender_ObjectSpecific { public: @@ -94,26 +98,26 @@ class CROS_impl : public IRender_ObjectSpecific ICF float get_hemi() { - if (dwFrameSmooth != Device.dwFrame) + if (dwFrameSmooth != RDEVICE.dwFrame) update_smooth(); return hemi_smooth; } ICF float get_sun() { - if (dwFrameSmooth != Device.dwFrame) + if (dwFrameSmooth != RDEVICE.dwFrame) update_smooth(); return sun_smooth; } ICF Fvector3& get_approximate() { - if (dwFrameSmooth != Device.dwFrame) + if (dwFrameSmooth != RDEVICE.dwFrame) update_smooth(); return approximate; } const float* get_hemi_cube() { - if (dwFrameSmooth != Device.dwFrame) + if (dwFrameSmooth != RDEVICE.dwFrame) update_smooth(); return hemi_cube_smooth; } diff --git a/src/Layers/xrRender/ModelPool.cpp b/src/Layers/xrRender/ModelPool.cpp index bbe342faeba..4ba5d21aca6 100644 --- a/src/Layers/xrRender/ModelPool.cpp +++ b/src/Layers/xrRender/ModelPool.cpp @@ -2,7 +2,7 @@ #include "ModelPool.h" -#ifndef _EDITOR + #include "xrEngine/IGame_Persistent.h" #include "xrCore/FMesh.hpp" #include "FHierrarhyVisual.h" @@ -10,20 +10,12 @@ #include "FVisual.h" #include "FProgressive.h" #include "FSkinned.h" -#include "FLOD.h" -#include "FTreeVisual.h" #include "ParticleGroup.h" #include "ParticleEffect.h" -#else -#include "FMesh.h" -#include "FVisual.h" -#include "FProgressive.h" -#include "ParticleEffect.h" -#include "ParticleGroup.h" -#include "FSkinned.h" -#include "FHierrarhyVisual.h" -#include "SkeletonAnimated.h" -#include "IGame_Persistent.h" + +#ifndef _EDITOR +#include "FLOD.h" +#include "FTreeVisual.h" #endif dxRender_Visual* CModelPool::Instance_Create(u32 type) @@ -517,7 +509,7 @@ void CModelPool::Render( { RCache.set_Shader(pV->m_lod->shader ? pV->m_lod->shader : EDevice.m_WireShader); RCache.set_xform_world(mTransform); - pV->m_lod->Render(1.f); + pV->m_lod->Render(RCache, 1.f, false); } } else @@ -530,7 +522,7 @@ void CModelPool::Render( { RCache.set_Shader((*I)->shader ? (*I)->shader : EDevice.m_WireShader); RCache.set_xform_world(mTransform); - (*I)->Render(m_fLOD); + (*I)->Render(RCache, m_fLOD, false); } } } @@ -551,7 +543,7 @@ void CModelPool::Render( { RCache.set_Shader((*I)->shader ? (*I)->shader : EDevice.m_WireShader); RCache.set_xform_world(mTransform); - (*I)->Render(m_fLOD); + (*I)->Render(RCache, m_fLOD, false); } } } @@ -564,7 +556,7 @@ void CModelPool::Render( // if (_IsBoxVisible(m_pVisual,mTransform)) { RCache.set_xform_world(mTransform); - for (PS::CParticleGroup::SItemVecIt i_it = pG->items.begin(); i_it != pG->items.end(); i_it++) + for (auto i_it = pG->items.begin(); i_it != pG->items.end(); i_it++) { xr_vector visuals; i_it->GetVisuals(visuals); @@ -582,7 +574,7 @@ void CModelPool::Render( { RCache.set_Shader(m_pVisual->shader ? m_pVisual->shader : EDevice.m_WireShader); RCache.set_xform_world(mTransform); - m_pVisual->Render(m_fLOD); + m_pVisual->Render(RCache, m_fLOD, false); } } } @@ -594,7 +586,7 @@ void CModelPool::Render( { RCache.set_Shader(m_pVisual->shader ? m_pVisual->shader : EDevice.m_WireShader); RCache.set_xform_world(mTransform); - m_pVisual->Render(m_fLOD); + m_pVisual->Render(RCache, m_fLOD, false); } } break; diff --git a/src/Layers/xrRender/PSLibrary.cpp b/src/Layers/xrRender/PSLibrary.cpp index d4897ab8b3f..d1a74aec203 100644 --- a/src/Layers/xrRender/PSLibrary.cpp +++ b/src/Layers/xrRender/PSLibrary.cpp @@ -3,9 +3,10 @@ #include "PSLibrary.h" #include "ParticleEffect.h" #include "ParticleGroup.h" + #ifdef _EDITOR -#include "ParticleEffectActions.h" -#include "editors/ECore/Editor/ui_main.h" +#include "Editor/ParticleEffectActions.h" +#include "Editor/ui_main.h" #endif bool ped_sort_pred(const PS::CPEDef* a, const PS::CPEDef* b) { return xr_strcmp(a->Name(), b->Name()) < 0; } @@ -14,7 +15,7 @@ bool pgd_sort_pred(const PS::CPGDef* a, const PS::CPGDef* b) { return xr_strcmp( void CPSLibrary::OnCreate() { #ifdef _EDITOR - if (pCreateEAction) + if (pCreateEAction && !Core.SocSdk) { Load2(); } @@ -136,7 +137,7 @@ bool CPSLibrary::Load2() #ifdef _EDITOR SPBItem* pb = nullptr; if (UI->m_bReady) - pb = UI->ProgressStart(files.size(), "Loading particles..."); + pb = UI->ProgressStart(static_cast(files.size()), "Loading particles..."); #endif FS_FileSet::iterator it = files.begin(); FS_FileSet::iterator it_e = files.end(); diff --git a/src/Layers/xrRender/PSLibrary.h b/src/Layers/xrRender/PSLibrary.h index 350a3df0429..dc0821e2d7f 100644 --- a/src/Layers/xrRender/PSLibrary.h +++ b/src/Layers/xrRender/PSLibrary.h @@ -18,13 +18,19 @@ using PGDIt = PGDVec::iterator; } // namespace PS -class ECORE_API CPSLibrary : public particles_systems::library_interface +#ifdef _PARTICLE_EDITOR +#define PSLib_API +#else +#define PSLib_API ECORE_API +#endif + +class PSLib_API CPSLibrary : public particles_systems::library_interface { PS::PEDVec m_PEDs; PS::PGDVec m_PGDs; #ifdef _EDITOR - AnsiString m_CurrentParticles; + xr_string m_CurrentParticles; public: void __stdcall FindByName(LPCSTR new_name, bool& res); diff --git a/src/Layers/xrRender/ParticleEffect.cpp b/src/Layers/xrRender/ParticleEffect.cpp index 09205adae7e..20dd7a4ed0e 100644 --- a/src/Layers/xrRender/ParticleEffect.cpp +++ b/src/Layers/xrRender/ParticleEffect.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #pragma hdrstop #include "ParticleEffect.h" +#include "Common/RDevice.h" #include "xrCore/Threading/ParallelFor.hpp" @@ -33,8 +34,8 @@ static void ApplyTexgen(CBackend& cmd_list, const Fmatrix& mVP) Fmatrix mTexgen; #if defined(USE_DX9) - float _w = float(Device.dwWidth); - float _h = float(Device.dwHeight); + float _w = float(RDEVICE.dwWidth); + float _h = float(RDEVICE.dwHeight); float o_w = (.5f / _w); float o_h = (.5f / _h); Fmatrix mTexelAdjust = @@ -318,7 +319,7 @@ IC void FillSprite_fpu(FVF::LIT*& pv, const Fvector& pos, const Fvector& dir, co const Fvector& T = dir; Fvector R; - R.crossproduct(T, Device.vCameraDirection).normalize_safe(); + R.crossproduct(T, RDEVICE.vCameraDirection).normalize_safe(); Fvector Vr, Vt; @@ -728,7 +729,7 @@ IC void FillSprite(FVF::LIT*& pv, const Fvector& pos, const Fvector& dir, const } extern ENGINE_API float psHUD_FOV; -void CParticleEffect::Render(float, bool) +void CParticleEffect::Render(CBackend& cmd_list, float, bool) { u32 dwOffset, dwCount; // Get a pointer to the particles in gp memory @@ -829,12 +830,12 @@ void CParticleEffect::Render(float, bool) { Fvector p; m_XFORM.transform_tiny(p, m.pos); - FillSprite(pv, Device.vCameraTop, Device.vCameraRight, p, lt, rb, r_x, r_y, m.color, m.rot.x); + FillSprite(pv, RDEVICE.vCameraTop, RDEVICE.vCameraRight, p, lt, rb, r_x, r_y, m.color, m.rot.x); } else { FillSprite( - pv, Device.vCameraTop, Device.vCameraRight, m.pos, lt, rb, r_x, r_y, m.color, m.rot.x); + pv, RDEVICE.vCameraTop, RDEVICE.vCameraRight, m.pos, lt, rb, r_x, r_y, m.color, m.rot.x); } } } @@ -851,27 +852,27 @@ void CParticleEffect::Render(float, bool) g_pGamePersistent->Environment().CurrentEnv.far_plane); Device.mFullTransform.mul(Device.mProject, Device.mView); - RCache.set_xform_project(Device.mProject); + cmd_list.set_xform_project(Device.mProject); RImplementation.rmNear(); ApplyTexgen(Device.mFullTransform); } #endif - RCache.set_xform_world(Fidentity); - RCache.set_Geometry(geom); + cmd_list.set_xform_world(Fidentity); + cmd_list.set_Geometry(geom); - RCache.set_CullMode(m_Def->m_Flags.is(CPEDef::dfCulling) ? + cmd_list.set_CullMode(m_Def->m_Flags.is(CPEDef::dfCulling) ? (m_Def->m_Flags.is(CPEDef::dfCullCCW) ? CULL_CCW : CULL_CW) : CULL_NONE); - RCache.Render(D3DPT_TRIANGLELIST, dwOffset, 0, dwCount, 0, dwCount / 2); - RCache.set_CullMode(CULL_CCW); + cmd_list.Render(D3DPT_TRIANGLELIST, dwOffset, 0, dwCount, 0, dwCount / 2); + cmd_list.set_CullMode(CULL_CCW); #ifndef _EDITOR if (GetHudMode()) { RImplementation.rmNormal(); Device.mProject = Pold; Device.mFullTransform = FTold; - RCache.set_xform_project(Device.mProject); + cmd_list.set_xform_project(Device.mProject); ApplyTexgen(Device.mFullTransform); } #endif diff --git a/src/Layers/xrRender/ParticleEffectDef.cpp b/src/Layers/xrRender/ParticleEffectDef.cpp index 4c2a4ea2a28..d9bc99244bb 100644 --- a/src/Layers/xrRender/ParticleEffectDef.cpp +++ b/src/Layers/xrRender/ParticleEffectDef.cpp @@ -3,9 +3,10 @@ #include "ParticleEffectDef.h" #include "ParticleEffect.h" + #ifdef _EDITOR -#include "UI_ToolsCustom.h" -#include "ParticleEffectActions.h" +#include "Editor/UI_ToolsCustom.h" +#include "Editor/ParticleEffectActions.h" #else #endif diff --git a/src/Layers/xrRender/ParticleEffectDef.h b/src/Layers/xrRender/ParticleEffectDef.h index 60edaba64a9..2a1b20d3670 100644 --- a/src/Layers/xrRender/ParticleEffectDef.h +++ b/src/Layers/xrRender/ParticleEffectDef.h @@ -48,7 +48,13 @@ struct SFrame } }; -class ECORE_API CPEDef +#ifdef _PARTICLE_EDITOR +#define PSDEF_API +#else +#define PSDEF_API ECORE_API +#endif + +class PSDEF_API CPEDef { public: enum @@ -114,6 +120,7 @@ class ECORE_API CPEDef public: DEFINE_VECTOR(EParticleAction*, EPAVec, EPAVecIt); EPAVec m_EActionList; + bool m_EditChoose; public: void __stdcall FindActionByName(LPCSTR new_name, bool& res); @@ -139,6 +146,7 @@ class ECORE_API CPEDef void __stdcall FillActionList(ChooseItemVec& items, void* param); bool Validate(bool bMsg); void Compile(EPAVec& v); + void OnDrawUI(); #endif }; }; diff --git a/src/Layers/xrRender/ParticleGroup.cpp b/src/Layers/xrRender/ParticleGroup.cpp index 67c0bba3bf2..1de9771e210 100644 --- a/src/Layers/xrRender/ParticleGroup.cpp +++ b/src/Layers/xrRender/ParticleGroup.cpp @@ -35,7 +35,7 @@ void CPGDef::Clone(CPGDef* source) m_fTimeLimit = source->m_fTimeLimit; m_Effects.resize(source->m_Effects.size(), 0); - for (EffectIt d_it = m_Effects.begin(), s_it = source->m_Effects.begin(); s_it != source->m_Effects.end(); + for (auto d_it = m_Effects.begin(), s_it = source->m_Effects.begin(); s_it != source->m_Effects.end(); s_it++, d_it++) *d_it = xr_new(**s_it); } diff --git a/src/Layers/xrRender/ParticleGroup.h b/src/Layers/xrRender/ParticleGroup.h index 2e29cf912de..93a2e27e3e3 100644 --- a/src/Layers/xrRender/ParticleGroup.h +++ b/src/Layers/xrRender/ParticleGroup.h @@ -6,7 +6,13 @@ namespace PS { class CParticleEffect; -class ECORE_API CPGDef +#ifdef _PARTICLE_EDITOR +#define PGROUP_API +#else +#define PGROUP_API ECORE_API +#endif + +class PGROUP_API CPGDef { public: shared_str m_Name; diff --git a/src/Layers/xrRender/R_Backend.cpp b/src/Layers/xrRender/R_Backend.cpp index 2c7fab159c2..993a32e601d 100644 --- a/src/Layers/xrRender/R_Backend.cpp +++ b/src/Layers/xrRender/R_Backend.cpp @@ -1,7 +1,11 @@ #include "stdafx.h" #pragma hdrstop +#ifdef _EDITOR +void CRender::CreateQuadIB() +#else void D3DXRenderBase::CreateQuadIB() +#endif { constexpr auto triCount = 4 * 1024; constexpr auto idxCount = triCount * 2 * 3; diff --git a/src/Layers/xrRender/R_Backend.h b/src/Layers/xrRender/R_Backend.h index d985475ff08..1f0d6b552cc 100644 --- a/src/Layers/xrRender/R_Backend.h +++ b/src/Layers/xrRender/R_Backend.h @@ -78,7 +78,7 @@ class ECORE_API CBackend #if defined(USE_DX11) ref_cbuffer m_aVertexConstants[MaxCBuffers]; ref_cbuffer m_aPixelConstants[MaxCBuffers]; - + ref_cbuffer m_aGeometryConstants[MaxCBuffers]; ref_cbuffer m_aComputeConstants[MaxCBuffers]; @@ -87,9 +87,9 @@ class ECORE_API CBackend D3D_PRIMITIVE_TOPOLOGY m_PrimitiveTopology; ID3DInputLayout* m_pInputLayout; - u32 dummy0; // Padding to avoid warning - u32 dummy1; // Padding to avoid warning - u32 dummy2; // Padding to avoid warning + u32 dummy0; // Padding to avoid warning + u32 dummy1; // Padding to avoid warning + u32 dummy2; // Padding to avoid warning #endif private: // Render-targets @@ -623,6 +623,10 @@ class ECORE_API CBackend }; #pragma warning(pop) -#define RCache RImplementation.get_imm_context().cmd_list +#ifdef _EDITOR +# define RCache RImplementation.get_imm_command_list() +#else +# define RCache RImplementation.get_imm_context().cmd_list +#endif #endif diff --git a/src/Layers/xrRender/R_Backend_DBG.cpp b/src/Layers/xrRender/R_Backend_DBG.cpp index 4d117f569f0..74b14d77c54 100644 --- a/src/Layers/xrRender/R_Backend_DBG.cpp +++ b/src/Layers/xrRender/R_Backend_DBG.cpp @@ -1,4 +1,5 @@ #include "stdafx.h" +#include "Common/RDevice.h" #pragma hdrstop #if defined(USE_DX11) || defined(USE_OGL) @@ -271,10 +272,10 @@ void CBackend::dbg_OverdrawEnd() u32 c = color_xrgb(_c, _c, _c); #ifdef USE_DX9 FVF::TL pv[4]; - pv[0].set(float(0), float(Device.dwHeight), c, 0, 0); + pv[0].set(float(0), float(RDEVICE.dwHeight), c, 0, 0); pv[1].set(float(0), float(0), c, 0, 0); - pv[2].set(float(Device.dwWidth), float(Device.dwHeight), c, 0, 0); - pv[3].set(float(Device.dwWidth), float(0), c, 0, 0); + pv[2].set(float(RDEVICE.dwWidth), float(RDEVICE.dwHeight), c, 0, 0); + pv[3].set(float(RDEVICE.dwWidth), float(0), c, 0, 0); CHK_DX(HW.pDevice->SetRenderState(D3DRS_STENCILREF, I)); CHK_DX(HW.pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, pv, sizeof(FVF::TL))); #elif defined(USE_DX11) || defined(USE_OGL) diff --git a/src/Layers/xrRender/R_Backend_Runtime.cpp b/src/Layers/xrRender/R_Backend_Runtime.cpp index af7445d829a..1e7cfd77d70 100644 --- a/src/Layers/xrRender/R_Backend_Runtime.cpp +++ b/src/Layers/xrRender/R_Backend_Runtime.cpp @@ -1,10 +1,13 @@ #include "stdafx.h" #pragma hdrstop +#include "Common/RDevice.h" #if defined(USE_DX9) || defined(USE_DX11) #include #endif +#include "LightTrack.h" + void CBackend::OnFrameEnd() { if (!GEnv.isDedicatedServer) @@ -27,7 +30,7 @@ void CBackend::OnFrameBegin() { if (!GEnv.isDedicatedServer) { - PGO(Msg("PGO:*****frame[%d]*****", Device.dwFrame)); + PGO(Msg("PGO:*****frame[%d]*****", RDEVICE.dwFrame)); #ifndef USE_DX9 Invalidate(); @@ -156,7 +159,7 @@ void CBackend::set_ClipPlanes(u32 _enable, Fplane* _planes /*=NULL */, u32 count using namespace DirectX; - const XMMATRIX transform = XMLoadFloat4x4(reinterpret_cast(&Device.mFullTransform)); + const XMMATRIX transform = XMLoadFloat4x4(reinterpret_cast(&RDEVICE.mFullTransform)); XMMATRIX worldToClipMatrixIT = XMMatrixInverse(nullptr, transform); worldToClipMatrixIT = XMMatrixTranspose(worldToClipMatrixIT); @@ -574,9 +577,6 @@ void CBackend::OnDeviceDestroy() #endif } -#include "LightTrack.h" -#include "xrEngine/IRenderable.h" - void CBackend::apply_lmaterial() { R_constant* C = get_c(c_sbase)._get(); // get sampler diff --git a/src/Layers/xrRender/R_DStreams.h b/src/Layers/xrRender/R_DStreams.h index ebf12aa5e93..4747663244e 100644 --- a/src/Layers/xrRender/R_DStreams.h +++ b/src/Layers/xrRender/R_DStreams.h @@ -16,7 +16,10 @@ class ECORE_API _VertexStream VertexBufferHandle old_pVB{}; public: - _VertexStream() = default; + _VertexStream() + { + _clear(); + } ~_VertexStream() = default; void Create(); diff --git a/src/Layers/xrRender/ResourceManager.cpp b/src/Layers/xrRender/ResourceManager.cpp index 2028bcdf5ad..d55db5db0af 100644 --- a/src/Layers/xrRender/ResourceManager.cpp +++ b/src/Layers/xrRender/ResourceManager.cpp @@ -11,6 +11,7 @@ #include "tss.h" #include "Blender.h" #include "Blender_Recorder.h" +#include "Common/RDevice.h" // Already defined in Texture.cpp void fix_texture_name(pstr fn); @@ -313,9 +314,11 @@ Shader* CResourceManager::Create(LPCSTR s_shader, LPCSTR s_textures, LPCSTR s_co if (!GEnv.isDedicatedServer) { #if defined(USE_DX9) + #ifndef _EDITOR const bool useCppBlender = RImplementation.o.ffp && _GetBlender(s_shader); if (!useCppBlender && _lua_HasShader(s_shader)) return _lua_Create(s_shader, s_textures); + #endif return _cpp_Create(s_shader, s_textures, s_constants, s_matrices); #else // TODO: DX11: When all shaders are ready switch to common path if (_lua_HasShader(s_shader)) @@ -352,7 +355,7 @@ void CResourceManager::Delete(const Shader* S) void CResourceManager::DeferredUpload() { - if (!Device.b_is_Ready) + if (!RDEVICE.b_is_Ready) return; #if defined(USE_DX9) || defined(USE_DX11) @@ -367,7 +370,7 @@ void CResourceManager::DeferredUpload() void CResourceManager::DeferredUnload() { - if (!Device.b_is_Ready) + if (!RDEVICE.b_is_Ready) return; #if defined(USE_DX9) || defined(USE_DX11) @@ -388,14 +391,14 @@ void CResourceManager::ED_UpdateTextures(AStringVec* names) { for (u32 nid = 0; nid < names->size(); nid++) { - map_TextureIt I = m_textures.find((*names)[nid].c_str()); + auto I = m_textures.find((*names)[nid].c_str()); if (I != m_textures.end()) I->second->Unload(); } } else { - for (map_TextureIt t = m_textures.begin(); t != m_textures.end(); t++) + for (auto t = m_textures.begin(); t != m_textures.end(); t++) t->second->Unload(); } diff --git a/src/Layers/xrRender/ResourceManager_Loader.cpp b/src/Layers/xrRender/ResourceManager_Loader.cpp index d747f322a58..f7ae5f2262b 100644 --- a/src/Layers/xrRender/ResourceManager_Loader.cpp +++ b/src/Layers/xrRender/ResourceManager_Loader.cpp @@ -3,10 +3,11 @@ #include "ResourceManager.h" #include "Blender.h" +#include "Common/RDevice.h" void CResourceManager::OnDeviceDestroy(BOOL) { - if (Device.b_is_Ready) + if (RDEVICE.b_is_Ready) return; m_textures_description.UnLoad(); @@ -49,7 +50,7 @@ void CResourceManager::OnDeviceDestroy(BOOL) void CResourceManager::OnDeviceCreate(IReader* F) { - if (!Device.b_is_Ready) + if (!RDEVICE.b_is_Ready) return; string256 name; diff --git a/src/Layers/xrRender/ResourceManager_Resources.cpp b/src/Layers/xrRender/ResourceManager_Resources.cpp index c6ad81bf624..227508aa0ef 100644 --- a/src/Layers/xrRender/ResourceManager_Resources.cpp +++ b/src/Layers/xrRender/ResourceManager_Resources.cpp @@ -1,4 +1,5 @@ #include "stdafx.h" +#include "Common/RDevice.h" void fix_texture_name(pstr fn); @@ -108,7 +109,7 @@ CRT* CResourceManager::_CreateRT(LPCSTR Name, u32 w, u32 h, D3DFORMAT f, u32 sam CRT* RT = xr_new(); RT->dwFlags |= xr_resource_flagged::RF_REGISTERED; m_rtargets.emplace(RT->set_name(Name), RT); - if (Device.b_is_Ready) + if (RDEVICE.b_is_Ready) RT->create(Name, w, h, f, sampleCount, slices_num, flags); return RT; } @@ -214,7 +215,7 @@ CTexture* CResourceManager::_CreateTexture(LPCSTR _Name) T->dwFlags |= xr_resource_flagged::RF_REGISTERED; m_textures.emplace(T->set_name(Name), T); T->Preload(); - if (Device.b_is_Ready && !bDeferredLoad) + if (RDEVICE.b_is_Ready && !bDeferredLoad) T->Load(); return T; } diff --git a/src/Layers/xrRender/SH_Constant.cpp b/src/Layers/xrRender/SH_Constant.cpp index aa97b39949a..dca35e68a57 100644 --- a/src/Layers/xrRender/SH_Constant.cpp +++ b/src/Layers/xrRender/SH_Constant.cpp @@ -1,5 +1,5 @@ #include "stdafx.h" - +#include "Common/RDevice.h" #include "SH_Constant.h" /* @@ -26,13 +26,13 @@ BOOL AAA_test () void CConstant::Calculate() { - if (dwFrame == Device.dwFrame) + if (dwFrame == RDEVICE.dwFrame) return; - dwFrame = Device.dwFrame; + dwFrame = RDEVICE.dwFrame; if (modeProgrammable == dwMode) return; - float t = Device.fTimeGlobal; + float t = RDEVICE.fTimeGlobal; set_float(_R.Calculate(t), _G.Calculate(t), _B.Calculate(t), _A.Calculate(t)); } diff --git a/src/Layers/xrRender/SH_Matrix.cpp b/src/Layers/xrRender/SH_Matrix.cpp index 449c91adac8..b960d667708 100644 --- a/src/Layers/xrRender/SH_Matrix.cpp +++ b/src/Layers/xrRender/SH_Matrix.cpp @@ -1,12 +1,12 @@ #include "stdafx.h" - +#include "Common/RDevice.h" #include "SH_Matrix.h" void CMatrix::Calculate() { - if (dwFrame == Device.dwFrame) + if (dwFrame == RDEVICE.dwFrame) return; - dwFrame = Device.dwFrame; + dwFrame = RDEVICE.dwFrame; // Switch on mode switch (dwMode) @@ -16,7 +16,7 @@ void CMatrix::Calculate() case modeTCM: { Fmatrix T; - float sU = 1, sV = 1, t = Device.fTimeGlobal; + float sU = 1, sV = 1, t = RDEVICE.fTimeGlobal; tc_trans(xform, .5f, .5f); if (tcm & tcmRotate) { @@ -45,8 +45,8 @@ void CMatrix::Calculate() return; case modeS_refl: { - float Ux = .5f * Device.mView._11, Uy = .5f * Device.mView._21, Uz = .5f * Device.mView._31, Uw = .5f; - float Vx = -.5f * Device.mView._12, Vy = -.5f * Device.mView._22, Vz = -.5f * Device.mView._32, Vw = .5f; + float Ux = .5f * RDEVICE.mView._11, Uy = .5f * RDEVICE.mView._21, Uz = .5f * RDEVICE.mView._31, Uw = .5f; + float Vx = -.5f * RDEVICE.mView._12, Vy = -.5f * RDEVICE.mView._22, Vz = -.5f * RDEVICE.mView._32, Vw = .5f; xform._11 = Ux; xform._12 = Vx; @@ -68,7 +68,7 @@ void CMatrix::Calculate() return; case modeC_refl: { - Fmatrix M = Device.mView; + Fmatrix M = RDEVICE.mView; M._41 = 0.f; M._42 = 0.f; M._43 = 0.f; diff --git a/src/Layers/xrRender/SH_Texture.cpp b/src/Layers/xrRender/SH_Texture.cpp index 56f12564bc5..eb754c2370a 100644 --- a/src/Layers/xrRender/SH_Texture.cpp +++ b/src/Layers/xrRender/SH_Texture.cpp @@ -5,6 +5,7 @@ #include "xrEngine/tntQAVI.h" #include "xrEngine/xrTheora_Surface.h" +#include "Common/RDevice.h" #define PRIORITY_HIGH 12 #define PRIORITY_NORMAL 8 @@ -82,7 +83,7 @@ void CTexture::apply_load(CBackend& cmd_list, u32 dwStage) void CTexture::apply_theora(CBackend& cmd_list, u32 dwStage) { - if (pTheora->Update(m_play_time != 0xFFFFFFFF ? m_play_time : Device.dwTimeContinual)) + if (pTheora->Update(m_play_time != 0xFFFFFFFF ? m_play_time : RDEVICE.dwTimeContinual)) { R_ASSERT(D3DRTYPE_TEXTURE == pSurface->GetType()); ID3DTexture2D* T2D = (ID3DTexture2D*)pSurface; @@ -128,7 +129,7 @@ void CTexture::apply_avi(CBackend& cmd_list, u32 dwStage) const void CTexture::apply_seq(CBackend& cmd_list, u32 dwStage) { // SEQ - u32 frame = Device.dwTimeContinual / seqMSPF; // Device.dwTimeGlobal + u32 frame = RDEVICE.dwTimeContinual / seqMSPF; // Device.dwTimeGlobal u32 frame_data = seqDATA.size(); if (flags.seqCycles) { @@ -194,7 +195,7 @@ void CTexture::Load() { flags.MemoryUsage = pTheora->Width(true) * pTheora->Height(true) * 4; BOOL bstop_at_end = (nullptr != strstr(cName.c_str(), "intro" DELIMITER)) || (nullptr != strstr(cName.c_str(), "outro" DELIMITER)); - pTheora->Play(!bstop_at_end, Device.dwTimeContinual); + pTheora->Play(!bstop_at_end, RDEVICE.dwTimeContinual); // Now create texture ID3DTexture2D* pTexture = nullptr; @@ -341,7 +342,7 @@ void CTexture::desc_update() void CTexture::video_Play(BOOL looped, u32 _time) { if (pTheora) - pTheora->Play(looped, (_time != 0xFFFFFFFF) ? (m_play_time = _time) : Device.dwTimeContinual); + pTheora->Play(looped, (_time != 0xFFFFFFFF) ? (m_play_time = _time) : RDEVICE.dwTimeContinual); } void CTexture::video_Pause(BOOL state) const diff --git a/src/Layers/xrRender/ShaderResourceTraits.h b/src/Layers/xrRender/ShaderResourceTraits.h index c2db29805d8..47672371e2c 100644 --- a/src/Layers/xrRender/ShaderResourceTraits.h +++ b/src/Layers/xrRender/ShaderResourceTraits.h @@ -640,7 +640,7 @@ T* CResourceManager::CreateShader(cpcstr name, pcstr filename /*= nullptr*/, u32 sh->dwFlags |= xr_resource_flagged::RF_REGISTERED; sh_map.insert(std::make_pair(sh->set_name(name), sh)); - if (0 == xr_stricmp(name, "null")) + if (0 == strncmp(name, "null", strlen("null"))) { sh->sh = 0; return sh; diff --git a/src/Layers/xrRender/SkeletonAnimated.cpp b/src/Layers/xrRender/SkeletonAnimated.cpp index 90603f61103..742e106c4bd 100644 --- a/src/Layers/xrRender/SkeletonAnimated.cpp +++ b/src/Layers/xrRender/SkeletonAnimated.cpp @@ -8,6 +8,8 @@ #include "SkeletonX.h" #include "xrCore/FMesh.hpp" #include "xrCore/xr_token.h" +#include "Common/RDevice.h" + #ifdef DEBUG #include "xrCore/dump_string.h" #endif @@ -521,9 +523,9 @@ void CKinematicsAnimated::LL_UpdateTracks(float dt, bool b_force, bool leave_ble for (; I != E; I++) { CBlend& B = *(*I); - if (!b_force && B.dwFrame == Device.dwFrame) + if (!b_force && B.dwFrame == RDEVICE.dwFrame) continue; - B.dwFrame = Device.dwFrame; + B.dwFrame = RDEVICE.dwFrame; if (B.update(dt, B.Callback) && !leave_blends) { DestroyCycle(B); @@ -596,20 +598,20 @@ void CKinematicsAnimated::LL_UpdateFxTracks(float dt) void CKinematicsAnimated::UpdateTracks() { _DBG_SINGLE_USE_MARKER; - if (Update_LastTime == Device.dwTimeGlobal) + if (Update_LastTime == RDEVICE.dwTimeGlobal) return; - u32 DT = Device.dwTimeGlobal - Update_LastTime; + u32 DT = RDEVICE.dwTimeGlobal - Update_LastTime; if (DT > 66) DT = 66; float dt = float(DT) / 1000.f; if (GetUpdateTracksCalback()) { - if ((*GetUpdateTracksCalback())(float(Device.dwTimeGlobal - Update_LastTime) / 1000.f, *this)) - Update_LastTime = Device.dwTimeGlobal; + if ((*GetUpdateTracksCalback())(float(RDEVICE.dwTimeGlobal - Update_LastTime) / 1000.f, *this)) + Update_LastTime = RDEVICE.dwTimeGlobal; return; } - Update_LastTime = Device.dwTimeGlobal; + Update_LastTime = RDEVICE.dwTimeGlobal; LL_UpdateTracks(dt, false, false); } diff --git a/src/Layers/xrRender/SkeletonCustom.cpp b/src/Layers/xrRender/SkeletonCustom.cpp index b09fc81649a..2157e0695c4 100644 --- a/src/Layers/xrRender/SkeletonCustom.cpp +++ b/src/Layers/xrRender/SkeletonCustom.cpp @@ -5,6 +5,8 @@ #include "SkeletonCustom.h" #include "SkeletonX.h" #include "xrCore/FMesh.hpp" +#include "Common/RDevice.h" + int psSkeletonUpdate = 32; Lock UCalc_Mutex #ifdef CONFIG_PROFILE_LOCKS @@ -703,7 +705,8 @@ void CKinematics::AddWallmark( } // ok. allocate wallmark - intrusive_ptr wm = xr_new(this, parent_xform, shader, cp, Device.fTimeGlobal); + intrusive_ptr wm = + xr_new(this, parent_xform, shader, cp, RDEVICE.fTimeGlobal); wm->m_LocalBounds.set(cp, size * 2.f); wm->XFORM()->transform_tiny(wm->m_Bounds.P, cp); wm->m_Bounds.R = wm->m_LocalBounds.R; @@ -731,14 +734,14 @@ void CKinematics::AddWallmark( void CKinematics::CalculateWallmarks(bool hud) { - if (!wallmarks.empty() && (wm_frame != Device.dwFrame)) + if (!wallmarks.empty() && (wm_frame != RDEVICE.dwFrame)) { - wm_frame = Device.dwFrame; + wm_frame = RDEVICE.dwFrame; bool need_remove = false; for (auto it = wallmarks.begin(); it != wallmarks.end(); ++it) { intrusive_ptr& wm = *it; - float w = (Device.fTimeGlobal - wm->TimeStart()) / ps_r__WallmarkTTL; + float w = (RDEVICE.fTimeGlobal - wm->TimeStart()) / ps_r__WallmarkTTL; if (w < 1.f) { // append wm to WallmarkEngine @@ -777,7 +780,7 @@ void CKinematics::RenderWallmark(intrusive_ptr wm, FVF::LIT*& for (u32 f_idx = 0; f_idx < wm->m_Faces.size(); f_idx++) { CSkeletonWallmark::WMFace F = wm->m_Faces[f_idx]; - float w = (Device.fTimeGlobal - wm->TimeStart()) / ps_r__WallmarkTTL; + float w = (RDEVICE.fTimeGlobal - wm->TimeStart()) / ps_r__WallmarkTTL; for (u32 k = 0; k < 3; k++) { Fvector P; diff --git a/src/Layers/xrRender/SkeletonRigid.cpp b/src/Layers/xrRender/SkeletonRigid.cpp index b04c093742c..6b1f8abbb74 100644 --- a/src/Layers/xrRender/SkeletonRigid.cpp +++ b/src/Layers/xrRender/SkeletonRigid.cpp @@ -2,6 +2,7 @@ #include "stdafx.h" #pragma hdrstop +#include "Common/RDevice.h" #include "SkeletonCustom.h" extern int psSkeletonUpdate; @@ -15,11 +16,11 @@ void CKinematics::CalculateBones(BOOL bForceExact) // early out. // check if the info is still relevant // skip all the computations - assume nothing changes in a small period of time :) - if (Device.dwTimeGlobal == UCalc_Time) + if (RDEVICE.dwTimeGlobal == UCalc_Time) return; // early out for "fast" update UCalc_mtlock lock; OnCalculateBones(); - if (!bForceExact && (Device.dwTimeGlobal < (UCalc_Time + UCalc_Interval))) + if (!bForceExact && (RDEVICE.dwTimeGlobal < (UCalc_Time + UCalc_Interval))) return; // early out for "slow" update if (Update_Visibility) Visibility_Update(); @@ -28,7 +29,7 @@ void CKinematics::CalculateBones(BOOL bForceExact) // here we have either: // 1: timeout elapsed // 2: exact computation required - UCalc_Time = Device.dwTimeGlobal; + UCalc_Time = RDEVICE.dwTimeGlobal; // exact computation // Calculate bones diff --git a/src/Layers/xrRender/blenders/Blender_tree.cpp b/src/Layers/xrRender/blenders/Blender_tree.cpp index 3dc0e15b147..c9939a1d05d 100644 --- a/src/Layers/xrRender/blenders/Blender_tree.cpp +++ b/src/Layers/xrRender/blenders/Blender_tree.cpp @@ -71,10 +71,12 @@ void CBlender_Tree::CompileFFP(CBlender_Compile& C) const } else*/ { + #ifndef _EDITOR if (oNotAnTree.value) C.PassSET_Shaders("tree_s", "null"); else C.PassSET_Shaders("tree_wave", "null"); + #endif switch (C.iElement) { diff --git a/src/Layers/xrRender/dxEnvironmentRender.cpp b/src/Layers/xrRender/dxEnvironmentRender.cpp index ae73e1b0d97..9d2d1bd6c8f 100644 --- a/src/Layers/xrRender/dxEnvironmentRender.cpp +++ b/src/Layers/xrRender/dxEnvironmentRender.cpp @@ -7,6 +7,11 @@ #include "xrEngine/Environment.h" #include "xrEngine/xr_efflensflare.h" +#include "Common/RDevice.h" + +#ifdef _EDITOR +#include "Layers/xrRender_R2/r2_types.h" +#endif ////////////////////////////////////////////////////////////////////////// // half box def @@ -173,9 +178,16 @@ void dxEnvironmentRender::lerp(CEnvDescriptorMixer& currentEnv, IEnvDescriptorRe _RELEASE(e1); #endif // USE_OGL +#ifndef _EDITOR const bool menu_pp = g_pGamePersistent->OnRenderPPUI_query(); e0 = menu_pp ? 0 : pA->sky_texture_env->surface_get(); e1 = menu_pp ? 0 : pB->sky_texture_env->surface_get(); +#else + e0 = 0; + e1 = 0; +#endif + + # ifdef USE_OGL t_envmap_0->surface_set(GL_TEXTURE_CUBE_MAP, e0); t_envmap_1->surface_set(GL_TEXTURE_CUBE_MAP, e1); @@ -209,7 +221,7 @@ void dxEnvironmentRender::RenderSky(CEnvironment& env) // draw sky box Fmatrix mSky; mSky.rotateY(env.CurrentEnv.sky_rotation); - mSky.translate_over(Device.vCameraPosition); + mSky.translate_over(RDEVICE.vCameraPosition); u32 i_offset, v_offset; u32 C = color_rgba(iFloor(env.CurrentEnv.sky_color.x * 255.f), iFloor(env.CurrentEnv.sky_color.y * 255.f), @@ -284,7 +296,7 @@ void dxEnvironmentRender::RenderClouds(CEnvironment& env) mScale.scale(10, 0.4f, 10); mXFORM.rotateY(env.CurrentEnv.clouds_rotation); mXFORM.mulB_43(mScale); - mXFORM.translate_over(Device.vCameraPosition); + mXFORM.translate_over(RDEVICE.vCameraPosition); Fvector wd0, wd1; Fvector4 wind_dir; diff --git a/src/Layers/xrRender/dxFontRender.cpp b/src/Layers/xrRender/dxFontRender.cpp index 63b2ca3df91..44c4f019a73 100644 --- a/src/Layers/xrRender/dxFontRender.cpp +++ b/src/Layers/xrRender/dxFontRender.cpp @@ -5,6 +5,13 @@ #include "xrEngine/GameFont.h" #include "xrCore/Text/StringConversion.hpp" +#ifdef _EDITOR +#include "xrEngine/xr_level_controller.h" + +// fake, remove me +pcstr GetActionBinding(EGameActions action) { return ""; } +#endif + dxFontRender::~dxFontRender() { pShader.destroy(); @@ -29,8 +36,14 @@ void dxFontRender::OnRender(CGameFont& owner) if (!(owner.uFlags & CGameFont::fsValid)) { R_ASSERT(pShader); + +#ifdef _EDITOR + CTexture* T = RCache.get_ActiveTexture(0); +#else R_constant* C = RCache.get_c(c_sbase)._get(); // get sampler CTexture* T = RCache.get_ActiveTexture(C ? C->samp.index : 0); +#endif // _EDITOR + R_ASSERT(T); owner.vTS.set((int)T->get_Width(), (int)T->get_Height()); owner.fTCHeight = owner.fHeight / float(owner.vTS.y); diff --git a/src/Layers/xrRender/dxRenderFactory.cpp b/src/Layers/xrRender/dxRenderFactory.cpp index 1281fc0be2d..b43b1af8317 100644 --- a/src/Layers/xrRender/dxRenderFactory.cpp +++ b/src/Layers/xrRender/dxRenderFactory.cpp @@ -1,17 +1,15 @@ #include "stdafx.h" #include "dxRenderFactory.h" -#include "dxStatGraphRender.h" #ifndef _EDITOR +#include "dxStatGraphRender.h" #include "dxLensFlareRender.h" #include "dxImGuiRender.h" -#endif -#ifndef _EDITOR +#include "dxEnvironmentRender.h" #include "dxThunderboltRender.h" #include "dxThunderboltDescRender.h" #include "dxRainRender.h" #include "dxLensFlareRender.h" -#include "dxEnvironmentRender.h" #include "dxObjectSpaceRender.h" #endif // _EDITOR @@ -44,8 +42,8 @@ RENDER_FACTORY_IMPLEMENT(ThunderboltDescRender) RENDER_FACTORY_IMPLEMENT(RainRender) RENDER_FACTORY_IMPLEMENT(LensFlareRender) RENDER_FACTORY_IMPLEMENT(ImGuiRender) +RENDER_FACTORY_IMPLEMENT(FlareRender) RENDER_FACTORY_IMPLEMENT(EnvironmentRender) RENDER_FACTORY_IMPLEMENT(EnvDescriptorRender) -RENDER_FACTORY_IMPLEMENT(FlareRender) #endif RENDER_FACTORY_IMPLEMENT(FontRender) diff --git a/src/Layers/xrRender/dxStatGraphRender.cpp b/src/Layers/xrRender/dxStatGraphRender.cpp index 769365f2211..6bf1e3f4f43 100644 --- a/src/Layers/xrRender/dxStatGraphRender.cpp +++ b/src/Layers/xrRender/dxStatGraphRender.cpp @@ -1,5 +1,10 @@ #include "stdafx.h" #include "dxStatGraphRender.h" +#include "Common/RDevice.h" + +#ifdef _EDITOR +#include "Debug/dxPixEventWrapper.h" +#endif void dxStatGraphRender::Copy(IStatGraphRender& _in) { *this = *((dxStatGraphRender*)&_in); } void dxStatGraphRender::OnDeviceCreate() @@ -20,8 +25,8 @@ void dxStatGraphRender::OnRender(CStatGraph& owner) Fmatrix ViewM; ViewM.identity(); - ViewM._11 = 1.f / Device.dwWidth; - ViewM._22 = -1.f / Device.dwHeight; + ViewM._11 = 1.f / RDEVICE.dwWidth; + ViewM._22 = -1.f / RDEVICE.dwHeight; RCache.set_xform_world(Fidentity); RCache.set_xform_view(ViewM); diff --git a/src/Layers/xrRender/xrRender_console.cpp b/src/Layers/xrRender/xrRender_console.cpp index de42183c28b..e42393c32b4 100644 --- a/src/Layers/xrRender/xrRender_console.cpp +++ b/src/Layers/xrRender/xrRender_console.cpp @@ -125,7 +125,12 @@ float ps_r__tf_Mipbias = 0.0f; // R1 float ps_r1_ssaLOD_A = 64.f; float ps_r1_ssaLOD_B = 48.f; + +#ifdef _EDITOR +Flags32 ps_r1_flags = {R1FLAG_FFP}; // r1-only +#else Flags32 ps_r1_flags = {R1FLAG_DLIGHTS}; // r1-only +#endif float ps_r1_lmodel_lerp = 0.1f; float ps_r1_dlights_clip = 40.f; float ps_r1_pps_u = 0.f; diff --git a/src/Layers/xrRenderDX9/dx9DetailManager_VS.cpp b/src/Layers/xrRenderDX9/dx9DetailManager_VS.cpp index f669e8120e5..fb5471f2603 100644 --- a/src/Layers/xrRenderDX9/dx9DetailManager_VS.cpp +++ b/src/Layers/xrRenderDX9/dx9DetailManager_VS.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #pragma hdrstop #include "Layers/xrRender/DetailManager.h" +#include "Common/RDevice.h" namespace detail_manager { @@ -31,10 +32,10 @@ void CDetailManager::hw_Render(CBackend& cmd_list) // Render-prepare // Update timer // Can't use Device.fTimeDelta since it is smoothed! Don't know why, but smoothed value looks more choppy! - float fDelta = Device.fTimeGlobal - m_global_time_old; + float fDelta = RDEVICE.fTimeGlobal - m_global_time_old; if ((fDelta < 0) || (fDelta > 1)) fDelta = 0.03f; - m_global_time_old = Device.fTimeGlobal; + m_global_time_old = RDEVICE.fTimeGlobal; m_time_rot_1 += (PI_MUL_2 * fDelta / swing_current.rot1); m_time_rot_2 += (PI_MUL_2 * fDelta / swing_current.rot2); @@ -71,7 +72,7 @@ void CDetailManager::hw_Render(CBackend& cmd_list) // Still cmd_list.set_c(&*hwc_s_consts, scale, scale, scale, 1.f); - cmd_list.set_c(&*hwc_s_xform, Device.mFullTransform); + cmd_list.set_c(&*hwc_s_xform, RDEVICE.mFullTransform); hw_Render_dump(cmd_list, &*hwc_s_array, 0, 1, c_hdr); } diff --git a/src/Layers/xrRenderDX9/dx9HW.cpp b/src/Layers/xrRenderDX9/dx9HW.cpp index a4bb7e92525..204c97579a2 100644 --- a/src/Layers/xrRenderDX9/dx9HW.cpp +++ b/src/Layers/xrRenderDX9/dx9HW.cpp @@ -1,5 +1,5 @@ #include "stdafx.h" - +#include "Common/RDevice.h" #include "dx9HW.h" CHW HW; @@ -9,8 +9,10 @@ CHW::CHW() if (!ThisInstanceIsGlobal()) return; +#ifndef _EDITOR Device.seqAppActivate.Add(this); Device.seqAppDeactivate.Add(this); +#endif } CHW::~CHW() @@ -18,8 +20,10 @@ CHW::~CHW() if (!ThisInstanceIsGlobal()) return; +#ifndef _EDITOR Device.seqAppActivate.Remove(this); Device.seqAppDeactivate.Remove(this); +#endif } void CHW::OnAppActivate() @@ -62,10 +66,36 @@ void CHW::DestroyD3D() } void CHW::CreateDevice(SDL_Window* m_sdlWnd) +{ + HWND deviceWindow = nullptr; + + SDL_SysWMinfo info; + SDL_VERSION(&info.version); + if (SDL_GetWindowWMInfo(m_sdlWnd, &info)) + { + switch (info.subsystem) + { + case SDL_SYSWM_WINDOWS: + deviceWindow = info.info.win.window; + break; + default: break; + } + } + else + Log("! Couldn't get window information: ", SDL_GetError()); + + CreateDevice(deviceWindow); +} + +void CHW::CreateDevice(HWND hWnd) { CreateD3D(); +#ifdef _EDITOR + const bool bWindowed = true; +#else const bool bWindowed = ThisInstanceIsGlobal() ? psDeviceMode.WindowStyle != rsFullscreen : true; +#endif m_DriverType = Caps.bForceGPU_REF ? D3DDEVTYPE_REF : D3DDEVTYPE_HAL; @@ -146,8 +176,8 @@ void CHW::CreateDevice(SDL_Window* m_sdlWnd) D3DPRESENT_PARAMETERS& P = DevPP; ZeroMemory(&P, sizeof(P)); - P.BackBufferWidth = Device.dwWidth; - P.BackBufferHeight = Device.dwHeight; + P.BackBufferWidth = RDEVICE.dwWidth; + P.BackBufferHeight = RDEVICE.dwHeight; // Back buffer BackBufferCount = 1; @@ -160,22 +190,7 @@ void CHW::CreateDevice(SDL_Window* m_sdlWnd) // Windoze P.SwapEffect = bWindowed ? D3DSWAPEFFECT_COPY : D3DSWAPEFFECT_DISCARD; - - SDL_SysWMinfo info; - SDL_VERSION(&info.version); - if (SDL_GetWindowWMInfo(m_sdlWnd, &info)) - { - switch (info.subsystem) - { - case SDL_SYSWM_WINDOWS: - P.hDeviceWindow = info.info.win.window; - break; - default: break; - } - } - else - Log("! Couldn't get window information: ", SDL_GetError()); - + P.hDeviceWindow = hWnd; P.Windowed = bWindowed; // Depth/stencil @@ -234,6 +249,12 @@ void CHW::CreateDevice(SDL_Window* m_sdlWnd) #ifdef DEBUG R_CHK(pDevice->CreateStateBlock(D3DSBT_ALL, &dwDebugSB)); #endif + +#ifdef _EDITOR + R_CHK(pDevice->GetRenderTarget(0, &pBaseRT)); + R_CHK(pDevice->GetDepthStencilSurface(&pBaseZB)); +#endif + const u32 memory = pDevice->GetAvailableTextureMem(); Msg("* Texture memory: %d M", memory / (1024 * 1024)); } @@ -244,6 +265,15 @@ void CHW::DestroyDevice() _SHOW_REF("refCount:dwDebugSB", dwDebugSB); _RELEASE(dwDebugSB); #endif + +#ifdef _EDITOR + _SHOW_REF("refCount:pBaseZB", pBaseZB); + _RELEASE(pBaseZB); + + _SHOW_REF("refCount:pBaseRT", pBaseRT); + _RELEASE(pBaseRT); +#endif + _SHOW_REF("DeviceREF:", pDevice); _RELEASE(pDevice); @@ -258,6 +288,11 @@ void CHW::Reset() #ifdef DEBUG _RELEASE(dwDebugSB); #endif + +#ifdef _EDITOR + _RELEASE(pBaseZB); + _RELEASE(pBaseRT); +#else DevPP.BackBufferWidth = Device.dwWidth; DevPP.BackBufferHeight = Device.dwHeight; @@ -275,6 +310,7 @@ void CHW::Reset() DevPP.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; DevPP.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; } +#endif while (true) { @@ -286,6 +322,12 @@ void CHW::Reset() Msg("! ERROR: [%dx%d]: %s", DevPP.BackBufferWidth, DevPP.BackBufferHeight, xrDebug::ErrorToString(result)); Sleep(100); } + +#ifdef _EDITOR + R_CHK(pDevice->GetRenderTarget(0, &pBaseRT)); + R_CHK(pDevice->GetDepthStencilSurface(&pBaseZB)); +#endif + #ifdef DEBUG R_CHK(pDevice->CreateStateBlock(D3DSBT_ALL, &dwDebugSB)); #endif @@ -302,8 +344,11 @@ D3DFORMAT CHW::selectDepthStencil(D3DFORMAT fTarget) const { // R2 hack #pragma todo("R2 need to specify depth format") + +#ifndef _EDITOR if (GEnv.Render->GenerationIsR2()) return D3DFMT_D24S8; +#endif // R1 usual constexpr D3DFORMAT formats[] = @@ -465,6 +510,7 @@ void CHW::Present() CurrentBackBuffer = (CurrentBackBuffer + 1) % BackBufferCount; } +#ifndef _EDITOR DeviceState CHW::GetDeviceState() const { const auto result = pDevice->TestCooperativeLevel(); @@ -482,3 +528,4 @@ DeviceState CHW::GetDeviceState() const return DeviceState::Normal; } +#endif diff --git a/src/Layers/xrRenderDX9/dx9HW.h b/src/Layers/xrRenderDX9/dx9HW.h index 818aad924f3..30c4f729986 100644 --- a/src/Layers/xrRenderDX9/dx9HW.h +++ b/src/Layers/xrRenderDX9/dx9HW.h @@ -20,6 +20,7 @@ class CHW void DestroyD3D(); void CreateDevice(SDL_Window* sdlWnd); + void CreateDevice(HWND hWnd); void DestroyDevice(); void Reset(); @@ -30,7 +31,10 @@ class CHW static bool GivenGPUIsIntelGMA(u32 id_vendor, u32 id_device); std::pair GetSurfaceSize() const; + +#ifndef _EDITOR DeviceState GetDeviceState() const; +#endif public: void BeginScene(); @@ -50,6 +54,7 @@ class CHW u32 selectGPU() const; D3DFORMAT selectDepthStencil(D3DFORMAT) const; bool ThisInstanceIsGlobal() const; + void CreateDeviceInternal(); public: static constexpr auto IMM_CTX_ID = 0; @@ -67,6 +72,11 @@ class CHW IDirect3DStateBlock9* dwDebugSB = nullptr; #endif +#ifdef _EDITOR + IDirect3DSurface9* pBaseRT; + IDirect3DSurface9* pBaseZB; +#endif + IDirect3D9* pD3D = nullptr; // D3D u32 DevAdapter; @@ -78,6 +88,11 @@ class CHW stats_manager stats_manager; #endif + u32 GetBackBufferWidth() { return DevPP.BackBufferWidth; } + u32 GetBackBufferHeight() { return DevPP.BackBufferHeight; } + void SetBackBufferWidth(u32 val) { DevPP.BackBufferWidth = val; } + void SetBackBufferHeight(u32 val) { DevPP.BackBufferHeight = val; } + private: D3DPRESENT_PARAMETERS DevPP; XRay::Module hD3D = nullptr; diff --git a/src/Layers/xrRenderDX9/dx9ResourceManager_Resources.cpp b/src/Layers/xrRenderDX9/dx9ResourceManager_Resources.cpp index ac327a2786a..5cb1cf8b6d3 100644 --- a/src/Layers/xrRenderDX9/dx9ResourceManager_Resources.cpp +++ b/src/Layers/xrRenderDX9/dx9ResourceManager_Resources.cpp @@ -115,7 +115,7 @@ SGeometry* CResourceManager::CreateGeom(u32 FVF, VertexBufferHandle vb, IndexBuf return g; } -#ifdef _EDITOR +#if 0 //def _EDITOR //-------------------------------------------------------------------------------------------------------------- class includer : public ID3DXInclude { diff --git a/src/Layers/xrRenderPC_R1/FStaticRender.h b/src/Layers/xrRenderPC_R1/FStaticRender.h index 9b12acfc9e0..09b373a7582 100644 --- a/src/Layers/xrRenderPC_R1/FStaticRender.h +++ b/src/Layers/xrRenderPC_R1/FStaticRender.h @@ -16,7 +16,7 @@ class dxRender_Visual; -class CRender : public D3DXRenderBase +class CRender final : public D3DXRenderBase { public: enum @@ -101,75 +101,75 @@ class CRender : public D3DXRenderBase public: // feature level - virtual GenerationLevel GetGeneration() const override { return IRender::GENERATION_R1; } - virtual BackendAPI GetBackendAPI() const override { return IRender::BackendAPI::D3D9; } - virtual u32 get_dx_level() override { return 0x00090000; } - virtual bool is_sun_static() override { return true; } + GenerationLevel GetGeneration() const override { return IRender::GENERATION_R1; } + BackendAPI GetBackendAPI() const override { return IRender::BackendAPI::D3D9; } + u32 get_dx_level() override { return 0x00090000; } + bool is_sun_static() override { return true; } // Loading / Unloading - virtual void create() override; - virtual void destroy() override; - virtual void reset_begin() override; - virtual void reset_end() override; - virtual void level_Load(IReader* fs) override; - virtual void level_Unload() override; + void create() override; + void destroy() override; + void reset_begin() override; + void reset_end() override; + void level_Load(IReader* fs) override; + void level_Unload() override; ID3DBaseTexture* texture_load(LPCSTR fname, u32& msize); - virtual HRESULT shader_compile(pcstr name, IReader* fs, pcstr pFunctionName, pcstr pTarget, u32 Flags, + HRESULT shader_compile(pcstr name, IReader* fs, pcstr pFunctionName, pcstr pTarget, u32 Flags, void*& result) override; // Information - virtual void DumpStatistics(class IGameFont& font, class IPerformanceAlert* alert) override; - virtual LPCSTR getShaderPath() override { return "r1" DELIMITER ""; } - virtual ref_shader getShader(int id); - virtual IRenderVisual* getVisual(int id) override; - virtual IRender_Target* getTarget() override; + void DumpStatistics(class IGameFont& font, class IPerformanceAlert* alert) override; + LPCSTR getShaderPath() override { return "r1" DELIMITER ""; } + ref_shader getShader(int id); + IRenderVisual* getVisual(int id) override; + IRender_Target* getTarget() override; // Main void set_Object(IRenderable* O, u32 phase); void add_Visual(u32 context_id, IRenderable* root, IRenderVisual* V, Fmatrix& m) override; // add visual leaf (no culling performed at all) // wallmarks - virtual void add_StaticWallmark(ref_shader& S, const Fvector& P, float s, CDB::TRI* T, Fvector* V); - virtual void add_StaticWallmark( + void add_StaticWallmark(ref_shader& S, const Fvector& P, float s, CDB::TRI* T, Fvector* V); + void add_StaticWallmark( IWallMarkArray* pArray, const Fvector& P, float s, CDB::TRI* T, Fvector* V) override; - virtual void add_StaticWallmark(const wm_shader& S, const Fvector& P, float s, CDB::TRI* T, Fvector* V) override; - virtual void clear_static_wallmarks() override; - virtual void add_SkeletonWallmark(intrusive_ptr wm); - virtual void add_SkeletonWallmark( + void add_StaticWallmark(const wm_shader& S, const Fvector& P, float s, CDB::TRI* T, Fvector* V) override; + void clear_static_wallmarks() override; + void add_SkeletonWallmark(intrusive_ptr wm); + void add_SkeletonWallmark( const Fmatrix* xf, CKinematics* obj, ref_shader& sh, const Fvector& start, const Fvector& dir, float size); - virtual void add_SkeletonWallmark(const Fmatrix* xf, IKinematics* obj, IWallMarkArray* pArray, const Fvector& start, + void add_SkeletonWallmark(const Fmatrix* xf, IKinematics* obj, IWallMarkArray* pArray, const Fvector& start, const Fvector& dir, float size) override; // - virtual IBlender* blender_create(CLASS_ID cls); - virtual void blender_destroy(IBlender*&); + IBlender* blender_create(CLASS_ID cls); + void blender_destroy(IBlender*&); // - virtual IRender_ObjectSpecific* ros_create(IRenderable* parent) override; - virtual void ros_destroy(IRender_ObjectSpecific*&) override; + IRender_ObjectSpecific* ros_create(IRenderable* parent) override; + void ros_destroy(IRender_ObjectSpecific*&) override; // Particle library - virtual CPSLibrary* ps_library() { return &PSLibrary; } + CPSLibrary* ps_library() { return &PSLibrary; } // Lighting - virtual IRender_Light* light_create() override; - virtual IRender_Glow* glow_create() override; + IRender_Light* light_create() override; + IRender_Glow* glow_create() override; // Models - virtual IRenderVisual* model_CreateParticles(LPCSTR name) override; - virtual IRender_DetailModel* model_CreateDM(IReader* F); - virtual IRenderVisual* model_Create(LPCSTR name, IReader* data = nullptr) override; - virtual IRenderVisual* model_CreateChild(LPCSTR name, IReader* data) override; - virtual IRenderVisual* model_Duplicate(IRenderVisual* V) override; - virtual void model_Delete(IRenderVisual*& V, bool bDiscard) override; - virtual void model_Delete(IRender_DetailModel*& F); - virtual void model_Logging(bool bEnable) override { Models->Logging(bEnable); } - virtual void models_Prefetch() override; - virtual void models_Clear(bool b_complete) override; + IRenderVisual* model_CreateParticles(LPCSTR name) override; + IRender_DetailModel* model_CreateDM(IReader* F); + IRenderVisual* model_Create(LPCSTR name, IReader* data = nullptr) override; + IRenderVisual* model_CreateChild(LPCSTR name, IReader* data) override; + IRenderVisual* model_Duplicate(IRenderVisual* V) override; + void model_Delete(IRenderVisual*& V, bool bDiscard) override; + void model_Delete(IRender_DetailModel*& F); + void model_Logging(bool bEnable) override { Models->Logging(bEnable); } + void models_Prefetch() override; + void models_Clear(bool b_complete) override; // Occlusion culling - virtual bool occ_visible(vis_data& V) override; - virtual bool occ_visible(Fbox& B) override; - virtual bool occ_visible(sPoly& P) override; + bool occ_visible(vis_data& V) override; + bool occ_visible(Fbox& B) override; + bool occ_visible(sPoly& P) override; // Main void BeforeRender() override; @@ -178,11 +178,11 @@ class CRender : public D3DXRenderBase void Render() override; void RenderMenu() override; - virtual void Screenshot(ScreenshotMode mode = SM_NORMAL, LPCSTR name = nullptr) override; - virtual void Screenshot(ScreenshotMode mode, CMemoryWriter& memory_writer) override; - virtual void ScreenshotAsyncBegin() override; - virtual void ScreenshotAsyncEnd(CMemoryWriter& memory_writer) override; - virtual void OnFrame() override; + void Screenshot(ScreenshotMode mode = SM_NORMAL, LPCSTR name = nullptr) override; + void Screenshot(ScreenshotMode mode, CMemoryWriter& memory_writer) override; + void ScreenshotAsyncBegin() override; + void ScreenshotAsyncEnd(CMemoryWriter& memory_writer) override; + void OnFrame() override; void BeforeWorldRender() override; //--#SM+#-- +SecondVP+ Вызывается перед началом рендера мира и пост-эффектов void AfterWorldRender() override; //--#SM+#-- +SecondVP+ Вызывается после рендера мира и перед UI @@ -194,10 +194,10 @@ class CRender : public D3DXRenderBase // Constructor/destructor/loader CRender(); - virtual ~CRender(); + ~CRender() override; protected: - virtual void ScreenshotImpl(ScreenshotMode mode, LPCSTR name, CMemoryWriter* memory_writer) override; + void ScreenshotImpl(ScreenshotMode mode, LPCSTR name, CMemoryWriter* memory_writer) override; }; extern CRender RImplementation; diff --git a/src/editors/ActorEditor/ActorEditor.cpp b/src/editors/ActorEditor/ActorEditor.cpp new file mode 100644 index 00000000000..b0115721a9d --- /dev/null +++ b/src/editors/ActorEditor/ActorEditor.cpp @@ -0,0 +1,29 @@ +// ActorEditor.cpp : Определяет точку входа для приложения. + +#include "stdafx.h" + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow) +{ + if (!IsDebuggerPresent()) + xrDebug::Initialize(pCmdLine); + + Core.Initialize("actor", pCmdLine, LogCallback(ELogCallback, nullptr), true, "fs.ltx", false, true); + + ATools = xr_new(); + Tools = ATools; + + UI = xr_new(); + UI->RegisterCommands(); + + UIMainForm *MainForm = xr_new(); + ::MainForm = MainForm; + UI->Push(MainForm, false); + + while (MainForm->Frame()) + { + } + + xr_delete(MainForm); + Core._destroy(); + return 0; +} diff --git a/src/editors/ActorEditor/ActorEditor.vcxproj b/src/editors/ActorEditor/ActorEditor.vcxproj new file mode 100644 index 00000000000..47503ff872b --- /dev/null +++ b/src/editors/ActorEditor/ActorEditor.vcxproj @@ -0,0 +1,104 @@ + + + + + + + {3145D38A-574B-4841-8AA9-CCD160B95124} + ActorEditor + + + + + + + Application + + + + + + + + + + + + + + _EDITOR;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + $(xrExternals)ode/include;%(AdditionalIncludeDirectories) + + + + + + + + + + + + + + + + + + + + {1daec516-e52c-4a3c-a4da-ae3553e6e0f8} + + + {7885cf3c-ee04-4c67-9467-1fbf9a36b037} + + + {a0f7d1fb-59a7-4717-a7e4-96f37e91998e} + + + {98d24a3d-7666-4c11-9d6e-b10393ce8cba} + + + {ccca7859-eb86-493e-9b53-c4235f45b3c5} + + + {9187be98-531a-4276-b78e-dba3c8ab8447} + + + {6d47afc7-0557-4bbf-8902-b248f3621419} + + + {7e28883c-db86-4ee8-813a-991ba20c68c9} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/editors/ActorEditor/ActorEditor.vcxproj.filters b/src/editors/ActorEditor/ActorEditor.vcxproj.filters new file mode 100644 index 00000000000..1aa4c0a1d59 --- /dev/null +++ b/src/editors/ActorEditor/ActorEditor.vcxproj.filters @@ -0,0 +1,109 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы ресурсов + + + + + Файлы ресурсов + + + + + Файлы ресурсов + + + Файлы ресурсов + + + + + + \ No newline at end of file diff --git a/src/editors/ActorEditor/UIBoneForm.cpp b/src/editors/ActorEditor/UIBoneForm.cpp new file mode 100644 index 00000000000..7bd0633bef4 --- /dev/null +++ b/src/editors/ActorEditor/UIBoneForm.cpp @@ -0,0 +1,329 @@ +#include "stdafx.h" +UIBoneForm *UIBoneForm::Form = nullptr; +UIBoneForm::UIBoneForm() +{ +} + +UIBoneForm::~UIBoneForm() +{ +} + +void UIBoneForm::Draw() +{ + if (!ImGui::BeginPopupModal("BoneForm", &bOpen, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize, true)) + { + bOpen = false; + ImGui::CloseCurrentPopup(); + return; + } + else + { + ImGui::Text("Total bone:%d", m_EditObject->BoneCount()); + { + ImGui::BeginChild("Part1", ImVec2(300, 300)); + ImGui::AlignTextToFramePadding(); + ImGui::Text("Part #1:(%d B)", m_List[0].size()); + ImGui::SameLine(); + ImGui::SetNextItemWidth(-50); + ImGui::InputText("##name", m_Name[0], sizeof(m_Name[0])); + ImGui::SameLine(); + if (ImGui::Button("set", ImVec2(-1, 0))) + Move(0); + { + ImGui::BeginChild("List", ImVec2(0, 0), true, ImGuiWindowFlags_None); + for (int n = 0; n < m_List[0].size(); n++) + ImGui::Checkbox(m_List[0][n].name.c_str(), &m_List[0][n].select); + ImGui::EndChild(); + } + ImGui::EndChild(); + } + ImGui::SameLine(); + { + ImGui::BeginChild("Part2", ImVec2(300, 300)); + ImGui::AlignTextToFramePadding(); + ImGui::Text("Part #2:(%d B)", m_List[1].size()); + ImGui::SameLine(); + ImGui::SetNextItemWidth(-50); + ImGui::InputText("##name", m_Name[1], sizeof(m_Name[1])); + ImGui::SameLine(); + if (ImGui::Button("set", ImVec2(-1, 0))) + Move(1); + { + ImGui::BeginChild("List", ImVec2(0, 0), true, ImGuiWindowFlags_None); + for (int n = 0; n < m_List[1].size(); n++) + ImGui::Checkbox(m_List[1][n].name.c_str(), &m_List[1][n].select); + ImGui::EndChild(); + } + ImGui::EndChild(); + } + + { + ImGui::BeginChild("Part3", ImVec2(300, 300)); + ImGui::AlignTextToFramePadding(); + ImGui::Text("Part #3:(%d B)", m_List[2].size()); + ImGui::SameLine(); + ImGui::SetNextItemWidth(-50); + ImGui::InputText("##name", m_Name[2], sizeof(m_Name[2])); + ImGui::SameLine(); + if (ImGui::Button("set", ImVec2(-1, 0))) + Move(2); + { + ImGui::BeginChild("List", ImVec2(0, 0), true, ImGuiWindowFlags_None); + for (int n = 0; n < m_List[2].size(); n++) + ImGui::Checkbox(m_List[2][n].name.c_str(), &m_List[2][n].select); + ImGui::EndChild(); + } + ImGui::EndChild(); + } + ImGui::SameLine(); + { + ImGui::BeginChild("Part4", ImVec2(300, 300)); + ImGui::AlignTextToFramePadding(); + ImGui::Text("Part #4:(%d B)", m_List[3].size()); + ImGui::SameLine(); + ImGui::SetNextItemWidth(-50); + ImGui::InputText("##name", m_Name[3], sizeof(m_Name[3])); + ImGui::SameLine(); + if (ImGui::Button("set", ImVec2(-1, 0))) + Move(3); + { + ImGui::BeginChild("List", ImVec2(0, 0), true, ImGuiWindowFlags_None); + for (int n = 0; n < m_List[3].size(); n++) + ImGui::Checkbox(m_List[3][n].name.c_str(), &m_List[3][n].select); + ImGui::EndChild(); + } + ImGui::EndChild(); + } + + if (ImGui::Button("Ok", ImVec2(70, 0))) + { + Save(); + } + ImGui::SameLine(); + if (ImGui::Button("Cancel", ImVec2(70, 0))) + { + bOpen = false; + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(0, 20); + if (ImGui::Button("Reset To Default")) + { + ToDefault(); + } + ImGui::SameLine(0, 20); + if (ImGui::Button("Load From")) + { + LoadFrom(); + } + ImGui::SameLine(); + if (ImGui::Button("Save To")) + { + SaveTo(); + } + ImGui::EndPopup(); + } +} + +void UIBoneForm::Update() +{ + if (Form) + { + if (Form->IsClosed()) + { + xr_delete(Form); + } + else + { + Form->Draw(); + } + } +} + +void UIBoneForm::Show() +{ + if (!ATools->CurrentObject()) + { + ELog.DlgMsg(mtError, "Scene empty. Load object first."); + return; + } + VERIFY(!Form); + Form = xr_new(); + Form->m_EditObject = ATools->CurrentObject(); + if (Form->m_EditObject) + { + Form->m_BoneParts = &Form->m_EditObject->BoneParts(); + Form->FillBoneParts(); + } +} + +void UIBoneForm::Move(int to) +{ + if (!Form->m_EditObject) + return; + auto &to_vector = m_List[to]; + for (int i = 0; i < 4; i++) + { + if (i == to) + continue; + for (auto b = m_List[i].begin(), e = m_List[i].end(); b != e; b++) + { + if (b->select) + { + b->select = false; + to_vector.push_back(*b); + m_List[i].erase(b); + b = m_List[i].begin(); + } + } + } +} + +void UIBoneForm::FillBoneParts() +{ + if (!Form->m_EditObject) + return; + + for (int k = 0; k < 4; k++) + { + m_List[k].clear(); + m_Name[k][0] = 0; + } + for (BPIt it = m_BoneParts->begin(); it != m_BoneParts->end(); it++) + { + xr_strcpy(m_Name[it - m_BoneParts->begin()], it->alias.c_str()); + // E[it - m_BoneParts->begin()]->Text = it->alias.c_str(); + for (RStringVecIt w_it = it->bones.begin(); w_it != it->bones.end(); w_it++) + m_List[it - m_BoneParts->begin()].push_back(*w_it); + } +} + +void UIBoneForm::Save() +{ + for (int k = 0; k < 4; k++) + { + if (m_List[k].size() && !xr_strlen(m_Name[k])) + { + ELog.DlgMsg(mtError, "Verify parts name."); + return; + } + for (int i = 0; i < 4; i++) + { + if (i == k) + continue; + if (!m_List[k].size()) + continue; + string_path Name[2]; + xr_strcpy(Name[0], m_Name[k]); + xr_strcpy(Name[1], m_Name[i]); + _strupr_s(Name[0]); + _strupr_s(Name[1]); + if (xr_strcmp(Name[0], Name[1]) == 0) + { + ELog.DlgMsg(mtError, "Unique name required."); + return; + } + } + } + + // verify + U8Vec b_use(m_EditObject->BoneCount(), 0); + for (int k = 0; k < 4; k++) + { + if (m_List[k].size()) + { + for (auto node : m_List[k]) + { + b_use[m_EditObject->FindBoneByNameIdx(node.name.c_str())]++; + } + } + } + for (U8It u_it = b_use.begin(); u_it != b_use.end(); u_it++) + { + if (*u_it != 1) + { + ELog.DlgMsg(mtError, "Invalid bone part found (missing or duplicate bones)."); + return; + } + } + // save + m_BoneParts->clear(); + for (int k = 0; k < 4; k++) + { + if (m_List[k].size()) + { + m_BoneParts->push_back(SBonePart()); + SBonePart &BP = m_BoneParts->back(); + BP.alias = m_Name[k]; + for (auto node : m_List[k]) + { + BP.bones.push_back(node.name); + } + } + } + ATools->OnMotionDefsModified(); + bOpen = false; + ImGui::CloseCurrentPopup(); +} + +void UIBoneForm::SaveTo() +{ + xr_string temp_fn; + if (EFS.GetSaveName(_import_, temp_fn)) + { + CInifile ini(temp_fn.c_str(), FALSE, FALSE, TRUE); + string64 buff; + for (int i = 0; i < 4; ++i) + { + sprintf(buff, "part_%d", i); + ini.w_string(buff, "partition_name", m_Name[i]); + for (auto node : m_List[i]) + { + ini.w_string(buff, node.name.c_str(), NULL); + } + } + } +} + +void UIBoneForm::LoadFrom() +{ + xr_string temp_fn; + if (EFS.GetOpenName(EDevice.m_hWnd, _import_, temp_fn, false, NULL, 0)) + { + for (int k = 0; k < 4; k++) + { + m_List[k].clear(); + m_Name[k][0] = 0; + } + CInifile ini(temp_fn.c_str(), TRUE, TRUE, FALSE); + string64 buff; + for (int i = 0; i < 4; ++i) + { + sprintf(buff, "part_%d", i); + xr_strcpy(m_Name[i], ini.r_string(buff, "partition_name")); + CInifile::Sect &S = ini.r_section(buff); + auto it = S.Data.begin(); + auto e = S.Data.end(); + for (; it != e; ++it) + { + if (0 != stricmp(it->first.c_str(), "partition_name")) + { + m_List[i].push_back(it->first); + } + } + } + } +} + +void UIBoneForm::ToDefault() +{ + for (int k = 0; k < 4; k++) + { + m_List[k].clear(); + m_Name[k][0] = 0; + } + xr_strcpy(m_Name[0], "default"); + for (BoneIt it = m_EditObject->FirstBone(); it != m_EditObject->LastBone(); it++) + { + m_List[0].push_back((*it)->Name()); + } +} diff --git a/src/editors/ActorEditor/UIBoneForm.h b/src/editors/ActorEditor/UIBoneForm.h new file mode 100644 index 00000000000..d66a7d33f42 --- /dev/null +++ b/src/editors/ActorEditor/UIBoneForm.h @@ -0,0 +1,38 @@ +#pragma once +class UIBoneForm : public xrUI +{ +public: + UIBoneForm(); + virtual ~UIBoneForm(); + virtual void Draw(); + +public: + static void Update(); + static void Show(); + +private: + static UIBoneForm *Form; + +private: + BPVec *m_BoneParts; + +private: + struct ItemList + { + ItemList(shared_str Name) : name(Name), select(false) {} + ItemList() : select(false) {} + shared_str name; + bool select; + }; + xr_vector m_List[4]; + string_path m_Name[4]; + CEditableObject *m_EditObject; + +private: + void Move(int to); + void FillBoneParts(); + void Save(); + void SaveTo(); + void LoadFrom(); + void ToDefault(); +}; diff --git a/src/editors/ActorEditor/UIKeyForm.cpp b/src/editors/ActorEditor/UIKeyForm.cpp new file mode 100644 index 00000000000..c68e5bbc790 --- /dev/null +++ b/src/editors/ActorEditor/UIKeyForm.cpp @@ -0,0 +1,255 @@ +#include "stdafx.h" + +UIKeyForm::UIKeyForm() : m_AutoChange(true), m_TimeFactor(1), m_Position(0), m_currentEditMotion(nullptr) +{ +} + +UIKeyForm::~UIKeyForm() +{ +} + +void UIKeyForm::Draw() +{ + m_currentEditMotion = ATools->GetCurrentMotion(); + + bool bMarksPresent12 = (m_currentEditMotion && m_currentEditMotion->marks.size() >= 2); + bool bMarksPresent34 = (m_currentEditMotion && m_currentEditMotion->marks.size() == 4); + + bool Mark1 = bMarksPresent12 || ((CAEPreferences *)EPrefs)->bAlwaysShowKeyBar12 || ((CAEPreferences *)EPrefs)->bAlwaysShowKeyBar34; + bool Mark2 = bMarksPresent12 || ((CAEPreferences *)EPrefs)->bAlwaysShowKeyBar12 || ((CAEPreferences *)EPrefs)->bAlwaysShowKeyBar34; + bool Mark3 = bMarksPresent34 || ((CAEPreferences *)EPrefs)->bAlwaysShowKeyBar34; + bool Mark4 = bMarksPresent34 || ((CAEPreferences *)EPrefs)->bAlwaysShowKeyBar34; + + ImGui::Begin("KeyForm"); + { + + float a, b, c; + ATools->GetStatTime(a, b, c); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::BeginChild("Left", ImVec2(60, 0)); + { + + ImGui::Checkbox("Auto", &m_AutoChange); + ImGui::Text("Left1"); + ImGui::Text("Right1"); + ImGui::Text("Left2"); + ImGui::Text("Right2"); + ImGui::EndChild(); + } + ImGui::SameLine(); + ImGui::BeginChild("Midle", ImVec2(-120, 0)); + { + ImGui::SetNextItemWidth(-1); + if (AutoChange()) + m_Position = c; + ImGui::SliderFloat("##key1", &m_Position, a, b, "%.4f"); + ImGui::SetNextItemWidth(-1); + ImVec2 size = ImGui::GetItemRectSize(); + static float Zero = 0; + if (size.x != m_TempForPlotHistogram.size()) + { + m_TempForPlotHistogram.resize(static_cast(size.x)); + } + if (Mark1) + DrawMark(0); + ImGui::PlotHistogram("##left1", Mark1 ? m_TempForPlotHistogram.data() : &Zero, Mark1 ? m_TempForPlotHistogram.size() : 1, 0, NULL, 0.0f, 1.0f, size); + if (Mark2) + DrawMark(1); + ImGui::PlotHistogram("##right1", Mark2 ? m_TempForPlotHistogram.data() : &Zero, Mark2 ? m_TempForPlotHistogram.size() : 1, 0, NULL, 0.0f, 1.0f, size); + if (Mark3) + DrawMark(2); + ImGui::PlotHistogram("##left2", Mark3 ? m_TempForPlotHistogram.data() : &Zero, Mark3 ? m_TempForPlotHistogram.size() : 1, 0, NULL, 0.0f, 1.0f, size); + if (Mark4) + DrawMark(3); + ImGui::PlotHistogram("##right2", Mark4 ? m_TempForPlotHistogram.data() : &Zero, Mark4 ? m_TempForPlotHistogram.size() : 1, 0, NULL, 0.0f, 1.0f, size); + + ImGui::EndChild(); + } + ImGui::SameLine(); + ImGui::BeginChild("Back", ImVec2(120, 0)); + { + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 0)); + { + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + ImGui::Text("LOD:"); + ImGui::SameLine(); + ImGui::PopStyleVar(); + } + ImGui::SetNextItemWidth(-1); + float LOD_TimeFactor[2] = {ATools->m_RenderObject.m_fLOD, m_TimeFactor}; + ImGui::SliderFloat2("##lod", LOD_TimeFactor, 0, 1); + ATools->m_RenderObject.m_fLOD = LOD_TimeFactor[0]; + if (m_TimeFactor != LOD_TimeFactor[1]) + { + m_TimeFactor = LOD_TimeFactor[1]; + EDevice.time_factor(m_TimeFactor); + } + + ImGui::PushID("left1"); + if (ImGui::Button("Del") && Mark1) + { + SetMark(0, 3); + } + ImGui::SameLine(); + if (ImGui::Button("Up") && Mark1) + { + SetMark(0, 2); + } + ImGui::SameLine(); + if (ImGui::Button("Down", ImVec2(-1, 0)) && Mark1) + { + SetMark(0, 1); + } + ImGui::PopID(); + ImGui::PushID("right1"); + if (ImGui::Button("Del") && Mark2) + { + SetMark(1, 3); + } + ImGui::SameLine(); + if (ImGui::Button("Up") && Mark2) + { + SetMark(1, 2); + } + ImGui::SameLine(); + if (ImGui::Button("Down", ImVec2(-1, 0)) && Mark2) + { + SetMark(1, 1); + } + ImGui::PopID(); + ImGui::PushID("left2"); + if (ImGui::Button("Del") && Mark3) + { + SetMark(2, 3); + } + ImGui::SameLine(); + if (ImGui::Button("Up") && Mark3) + { + SetMark(2, 2); + } + ImGui::SameLine(); + if (ImGui::Button("Down", ImVec2(-1, 0)) && Mark3) + { + SetMark(2, 1); + } + ImGui::PopID(); + ImGui::PushID("right2"); + if (ImGui::Button("Del") && Mark4) + { + SetMark(3, 3); + } + ImGui::SameLine(); + if (ImGui::Button("Up") && Mark4) + { + SetMark(3, 2); + } + ImGui::SameLine(); + if (ImGui::Button("Down", ImVec2(-1, 0)) && Mark4) + { + SetMark(3, 1); + } + ImGui::PopID(); + + ImGui::PopStyleVar(); + ImGui::EndChild(); + } + ImGui::PopStyleVar(); + } + ImGui::End(); +} +inline bool interval_comparer(const motion_marks::interval &i1, const motion_marks::interval &i2) +{ + return (i1.first < i2.first); +} +void UIKeyForm::SetMark(int id, int action) +{ + if (!m_currentEditMotion) + return; + + if (m_currentEditMotion->marks.size() == 0) + return; + + motion_marks &M = m_currentEditMotion->marks[id]; + float a, b, c; + ATools->GetStatTime(a, b, c); + float cur_time = c - a; + + motion_marks::ITERATOR it = M.intervals.begin(); + motion_marks::ITERATOR it_e = M.intervals.end(); + + if (action == 3) + { // del current + + for (; it != it_e; ++it) + { + motion_marks::interval &iv = *it; + if (iv.first < cur_time && iv.second > cur_time) + { + M.intervals.erase(it); + break; + } + } + } + else if (action == 2) + { // up + for (; it != it_e; ++it) + { + motion_marks::interval &iv = *it; + if (iv.first < cur_time && iv.second > cur_time) + { + iv.second = cur_time; + break; + } + } + } + else if (action == 1) + { // down + for (; it != it_e; ++it) + { + motion_marks::interval &iv = *it; + if (iv.first < cur_time && iv.second > cur_time) + { + iv.first = cur_time; + break; + } + } + if (it == it_e) + { // insert new + M.intervals.push_back(motion_marks::interval(cur_time, b - a)); + } + } + + std::sort(M.intervals.begin(), M.intervals.end(), interval_comparer); +} + +void UIKeyForm::DrawMark(int id) +{ + for (int i = 0; i < m_TempForPlotHistogram.size(); i++) + { + m_TempForPlotHistogram[i] = 0; + } + if (!m_currentEditMotion) + return; + motion_marks &M = m_currentEditMotion->marks[id]; + + float a, b, c; + ATools->GetStatTime(a, b, c); + float motion_length = b - a; + + float k_len = m_TempForPlotHistogram.size() / motion_length; + + motion_marks::C_ITERATOR it = M.intervals.begin(); + motion_marks::C_ITERATOR it_e = M.intervals.end(); + + for (; it != it_e; ++it) + { + const motion_marks::interval &iv = *it; + Ivector2 posLT, posRB; + for (int i = static_cast(iv.first * k_len); i < iv.second * k_len; i++) + { + m_TempForPlotHistogram[i] = 1; + } + } +} diff --git a/src/editors/ActorEditor/UIKeyForm.h b/src/editors/ActorEditor/UIKeyForm.h new file mode 100644 index 00000000000..46cb779792d --- /dev/null +++ b/src/editors/ActorEditor/UIKeyForm.h @@ -0,0 +1,19 @@ +#pragma once +class UIKeyForm : public xrUI +{ +public: + UIKeyForm(); + virtual ~UIKeyForm(); + virtual void Draw(); + IC bool AutoChange() const { return m_AutoChange; } + IC float Position() const { return m_Position; }; + +private: + void SetMark(int id, int action); + void DrawMark(int id); + xr_vector m_TempForPlotHistogram; + float m_Position; + bool m_AutoChange; + float m_TimeFactor; + CSMotion *m_currentEditMotion; +}; diff --git a/src/editors/ActorEditor/UILeftBarForm.cpp b/src/editors/ActorEditor/UILeftBarForm.cpp new file mode 100644 index 00000000000..2210c891dcb --- /dev/null +++ b/src/editors/ActorEditor/UILeftBarForm.cpp @@ -0,0 +1,79 @@ +#include "stdafx.h" + +UILeftBarForm::UILeftBarForm() +{ + m_RenderMode = Render_Editor; + m_PickMode = 0; +} + +UILeftBarForm::~UILeftBarForm() +{ +} + +void UILeftBarForm::Draw() +{ + ImGui::Begin("LeftBar", 0); + + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Model")) + { + ImGui::AlignTextToFramePadding(); + ImGui::Text("Render Style:"); + ImGui::SameLine(); + if (ImGui::RadioButton("Editor", m_RenderMode == Render_Editor)) + { + ATools->PhysicsStopSimulate(); + m_RenderMode = Render_Editor; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + UI->RedrawScene(); + } + ImGui::SameLine(); + if (ImGui::RadioButton("Engine", m_RenderMode == Render_Engine)) + { + ATools->PhysicsStopSimulate(); + m_RenderMode = Render_Engine; + if (!ATools->IsVisualPresent()) + ExecCommand(COMMAND_MAKE_PREVIEW); + if (!ATools->IsVisualPresent()) + SetRenderMode(false); + else + SetRenderMode(true); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + UI->RedrawScene(); + } + ImGui::SameLine(0, 10); + if (ImGui::Button("Clip Maker")) + { + UIBoneForm::Show(); + } + static const char *PickModeList[] = {"None", "Surface", "Bone"}; + ImGui::Combo("Pick mode", &m_PickMode, PickModeList, 3, -1); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Object Items")) + { + ImGui::BeginGroup(); + ATools->m_ObjectItems->Draw(); + ImGui::EndGroup(); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Item Properties")) + { + ImGui::BeginGroup(); + ATools->m_Props->Draw(); + ImGui::EndGroup(); + ImGui::TreePop(); + } + ImGui::End(); +} + +void UILeftBarForm::SetRenderMode(bool bEngineMode) +{ + if (ATools->IsVisualPresent() && bEngineMode) + m_RenderMode = Render_Engine; + else + m_RenderMode = Render_Editor; + ATools->PlayMotion(); +} diff --git a/src/editors/ActorEditor/UILeftBarForm.h b/src/editors/ActorEditor/UILeftBarForm.h new file mode 100644 index 00000000000..8b95e24cef9 --- /dev/null +++ b/src/editors/ActorEditor/UILeftBarForm.h @@ -0,0 +1,20 @@ +#pragma once +class UILeftBarForm : public xrUI +{ +public: + enum RenderMode + { + Render_Editor, + Render_Engine + }; + UILeftBarForm(); + virtual ~UILeftBarForm(); + virtual void Draw(); + IC RenderMode GetRenderMode() { return m_RenderMode; } + void SetRenderMode(bool bEngineNode); + IC int GetPickMode() const { return m_PickMode; } + +private: + int m_PickMode; + RenderMode m_RenderMode; +}; diff --git a/src/editors/ActorEditor/UIMainForm.cpp b/src/editors/ActorEditor/UIMainForm.cpp new file mode 100644 index 00000000000..4ca7bd0ebb9 --- /dev/null +++ b/src/editors/ActorEditor/UIMainForm.cpp @@ -0,0 +1,52 @@ +#include "stdafx.h" +#include "../xrECore/Editor/EditorChooseEvents.h" + +void resptrcode_texture::create(LPCSTR _name) { _set(RImplementation.Resources->_CreateTexture(_name)); } + +UIMainForm *MainForm = nullptr; + +UIMainForm::UIMainForm() +{ + EnableReceiveCommands(); + if (!ExecCommand(COMMAND_INITIALIZE, (u32)0, (u32)0)) + { + FlushLog(); + exit(-1); + } + ExecCommand(COMMAND_UPDATE_GRID); + ExecCommand(COMMAND_RENDER_FOCUS); + FillChooseEvents(); + m_TopBar = xr_new(); + m_Render = xr_new(); + m_MainMenu = xr_new(); + m_LeftBar = xr_new(); + m_KeyForm = xr_new(); +} + +UIMainForm::~UIMainForm() +{ + ClearChooseEvents(); + xr_delete(m_KeyForm); + xr_delete(m_LeftBar); + xr_delete(m_MainMenu); + xr_delete(m_Render); + xr_delete(m_TopBar); + ExecCommand(COMMAND_DESTROY, (u32)0, (u32)0); +} + +void UIMainForm::Draw() +{ + m_MainMenu->Draw(); + m_TopBar->Draw(); + m_LeftBar->Draw(); + m_KeyForm->Draw(); + // ImGui::ShowDemoWindow(&bOpen); + m_Render->Draw(); +} + +bool UIMainForm::Frame() +{ + if (UI) + return UI->Idle(); + return false; +} diff --git a/src/editors/ActorEditor/UIMainForm.h b/src/editors/ActorEditor/UIMainForm.h new file mode 100644 index 00000000000..88d45976341 --- /dev/null +++ b/src/editors/ActorEditor/UIMainForm.h @@ -0,0 +1,22 @@ +#pragma once +class UIMainForm : public xrUI +{ +public: + UIMainForm(); + virtual ~UIMainForm(); + virtual void Draw(); + bool Frame(); + IC UILeftBarForm *GetLeftBarForm() { return m_LeftBar; } + IC UITopBarForm *GetTopBarForm() { return m_TopBar; } + IC UIKeyForm *GetKeyForm() { return m_KeyForm; } + + IC UIRenderForm *GetRenderForm() { return m_Render; } + +private: + UITopBarForm *m_TopBar; + UIRenderForm *m_Render; + UIMainMenuForm *m_MainMenu; + UILeftBarForm *m_LeftBar; + UIKeyForm *m_KeyForm; +}; +extern UIMainForm *MainForm; diff --git a/src/editors/ActorEditor/UIMainMenuForm.cpp b/src/editors/ActorEditor/UIMainMenuForm.cpp new file mode 100644 index 00000000000..627fc334f30 --- /dev/null +++ b/src/editors/ActorEditor/UIMainMenuForm.cpp @@ -0,0 +1,336 @@ +#include "stdafx.h" + +UIMainMenuForm::UIMainMenuForm() +{ +} + +UIMainMenuForm::~UIMainMenuForm() +{ +} + +void UIMainMenuForm::Draw() +{ + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Clear", "")) + { + ExecCommand(COMMAND_CLEAR); + } + if (ImGui::MenuItem("Load", "")) + { + ExecCommand(COMMAND_LOAD); + } + if (ImGui::MenuItem("Save", "")) + { + ExecCommand(COMMAND_SAVE, xr_string(ATools->m_LastFileName.c_str()), 0); + } + if (ImGui::MenuItem("Save as ...", "")) + { + ExecCommand(COMMAND_SAVE, 0, 1); + } + ImGui::Separator(); + if (ImGui::BeginMenu("Open Recent", "")) + { + for (auto &str : EPrefs->scene_recent_list) + { + if (ImGui::MenuItem(str.c_str(), "")) + { + ExecCommand(COMMAND_LOAD, str); + } + } + ImGui::EndMenu(); + } + ImGui::Separator(); + if (ImGui::MenuItem("Import...", "")) + { + ExecCommand(COMMAND_IMPORT); + } + ImGui::Separator(); + if (ImGui::MenuItem("Optimize Motions", "")) + { + ExecCommand(COMMAND_OPTIMIZE_MOTIONS); + } + ImGui::Separator(); + if (ImGui::MenuItem("Batch Convert...", "")) + { + ExecCommand(COMMAND_BATCH_CONVERT); + } + ImGui::Separator(); + if (ImGui::BeginMenu("Export")) + { + if (ImGui::MenuItem("Export OGF...", "")) + { + ExecCommand(COMMAND_EXPORT_OGF); + } + if (ImGui::MenuItem("Export OMF...", "")) + { + ExecCommand(COMMAND_EXPORT_OMF); + } + if (ImGui::MenuItem("Export OBJ...", "")) + { + ExecCommand(COMMAND_EXPORT_OBJ); + } + if (ImGui::MenuItem("Export DM...", "")) + { + ExecCommand(COMMAND_EXPORT_DM); + } + if (ImGui::MenuItem("Export C++...", "")) + { + ExecCommand(COMMAND_EXPORT_CPP); + } + ImGui::EndMenu(); + } + ImGui::Separator(); + if (ImGui::MenuItem("Quit", "")) + { + ExecCommand(COMMAND_QUIT); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Preview Object")) + { + if (ImGui::MenuItem("Custom...", "")) + { + ExecCommand(COMMAND_SELECT_PREVIEW_OBJ, false); + } + if (ImGui::MenuItem("Clear", "")) + { + ExecCommand(COMMAND_SELECT_PREVIEW_OBJ, true); + } + ImGui::Separator(); + if (ImGui::MenuItem("Preferences", "")) + { + ExecCommand(COMMAND_PREVIEW_OBJ_PREF); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Editors")) + { + if (ImGui::BeginMenu("Image")) + { + if (ImGui::MenuItem("Image Editor", "")) + { + ExecCommand(COMMAND_IMAGE_EDITOR); + } + ImGui::Separator(); + if (ImGui::MenuItem("Synchronize Textures", "")) + { + ExecCommand(COMMAND_REFRESH_TEXTURES); + } + if (ImGui::MenuItem("Check New Textures", "")) + { + ExecCommand(COMMAND_CHECK_TEXTURES); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Sounds")) + { + if (ImGui::MenuItem("Sound Editor", "")) + { + ExecCommand(COMMAND_SOUND_EDITOR); + } + ImGui::Separator(); + if (ImGui::MenuItem("Synchronize Sounds", "")) + { + ExecCommand(COMMAND_SYNC_SOUNDS); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Light Anim Editor", "")) + { + ExecCommand(COMMAND_LIGHTANIM_EDITOR); + } + if (ImGui::MenuItem("Minimap Editor", "")) + { + ExecCommand(COMMAND_MINIMAP_EDITOR); + } + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu("Options")) + { + if (ImGui::BeginMenu("Render")) + { + if (ImGui::BeginMenu("Quality")) + { + static bool selected[4] = {false, false, true, false}; + if (ImGui::MenuItem("25%", "", &selected[0])) + { + selected[1] = selected[2] = selected[3] = false; + UI->SetRenderQuality(1 / 4.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("50%", "", &selected[1])) + { + selected[0] = selected[2] = selected[3] = false; + UI->SetRenderQuality(1 / 2.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("100%", "", &selected[2])) + { + selected[1] = selected[0] = selected[3] = false; + UI->SetRenderQuality(1.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("200%", "", &selected[3])) + { + selected[1] = selected[2] = selected[0] = false; + UI->SetRenderQuality(2.f); + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Fill Mode")) + { + bool selected[3] = {EDevice.dwFillMode == D3DFILL_POINT, EDevice.dwFillMode == D3DFILL_WIREFRAME, EDevice.dwFillMode == D3DFILL_SOLID}; + if (ImGui::MenuItem("Point", "", &selected[0])) + { + EDevice.dwFillMode = D3DFILL_POINT; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Wireframe", "", &selected[1])) + { + EDevice.dwFillMode = D3DFILL_WIREFRAME; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Solid", "", &selected[2])) + { + EDevice.dwFillMode = D3DFILL_SOLID; + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Shader Mode")) + { + bool selected[2] = {EDevice.dwShadeMode == D3DSHADE_FLAT, EDevice.dwShadeMode == D3DSHADE_GOURAUD}; + if (ImGui::MenuItem("Flat", "", &selected[0])) + { + EDevice.dwShadeMode = D3DSHADE_FLAT; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Gouraud", "", &selected[1])) + { + EDevice.dwShadeMode = D3DSHADE_GOURAUD; + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + { + bool selected = psDeviceFlags.test(rsEdgedFaces); + if (ImGui::MenuItem("Edged Faces", "", &selected)) + { + psDeviceFlags.set(rsEdgedFaces, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = !HW.Caps.bForceGPU_SW; + if (ImGui::MenuItem("RenderHW", "", &selected)) + { + HW.Caps.bForceGPU_SW = !selected; + UI->Resize(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsFilterLinear); + if (ImGui::MenuItem("Filter Linear", "", &selected)) + { + psDeviceFlags.set(rsFilterLinear, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsRenderTextures); + if (ImGui::MenuItem("Textures", "", &selected)) + { + psDeviceFlags.set(rsRenderTextures, selected); + UI->RedrawScene(); + } + } + ImGui::EndMenu(); + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsDrawSafeRect); + if (ImGui::MenuItem("Draw Safe Rect", "", &selected)) + { + psDeviceFlags.set(rsDrawSafeRect, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsDrawGrid); + if (ImGui::MenuItem("Draw Grid", "", &selected)) + { + psDeviceFlags.set(rsDrawGrid, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsFog); + if (ImGui::MenuItem("Fog", "", &selected)) + { + psDeviceFlags.set(rsFog, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsLighting); + ; + if (ImGui::MenuItem("Lighting", "", &selected)) + { + psDeviceFlags.set(rsLighting, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsMuteSounds); + if (ImGui::MenuItem("Mute Sounds", "", &selected)) + { + psDeviceFlags.set(rsMuteSounds, selected); + } + } + { + bool selected = psDeviceFlags.test(rsRenderRealTime); + if (ImGui::MenuItem("Real Time", "", &selected)) + { + psDeviceFlags.set(rsRenderRealTime, selected); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsStatistic); + if (ImGui::MenuItem("Stats", "", &selected)) + { + psDeviceFlags.set(rsStatistic, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + if (ImGui::MenuItem("Preferences", "")) + { + ExecCommand(COMMAND_EDITOR_PREF); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Windows")) + { + { + bool selected = AllowLogCommands(); + + if (ImGui::MenuItem("Log", "", &selected)) + { + ExecCommand(COMMAND_LOG_COMMANDS); + } + } + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } +} diff --git a/src/editors/ActorEditor/UIMainMenuForm.h b/src/editors/ActorEditor/UIMainMenuForm.h new file mode 100644 index 00000000000..a44b6606609 --- /dev/null +++ b/src/editors/ActorEditor/UIMainMenuForm.h @@ -0,0 +1,8 @@ +#pragma once +class UIMainMenuForm : public xrUI +{ +public: + UIMainMenuForm(); + virtual ~UIMainMenuForm(); + virtual void Draw(); +}; diff --git a/src/editors/ActorEditor/UITest.cpp b/src/editors/ActorEditor/UITest.cpp new file mode 100644 index 00000000000..148687d2602 --- /dev/null +++ b/src/editors/ActorEditor/UITest.cpp @@ -0,0 +1,16 @@ +#include "UITest.h" + +UITest::UITest() +{ + out[0] = 0; +} + +UITest::~UITest() +{ +} + +void UITest::Draw() +{ + + // ImGui::BeginChild("1234"); +} diff --git a/src/editors/ActorEditor/UITest.h b/src/editors/ActorEditor/UITest.h new file mode 100644 index 00000000000..6a74cb82632 --- /dev/null +++ b/src/editors/ActorEditor/UITest.h @@ -0,0 +1,12 @@ +#pragma once +#include "..\xrEUI\stdafx.h" +class UITest : public xrUI +{ +public: + UITest(); + virtual ~UITest(); + virtual void Draw(); + +private: + string1024 out; +}; diff --git a/src/editors/ActorEditor/UITopBarForm.cpp b/src/editors/ActorEditor/UITopBarForm.cpp new file mode 100644 index 00000000000..cb8b16ab90f --- /dev/null +++ b/src/editors/ActorEditor/UITopBarForm.cpp @@ -0,0 +1,321 @@ +#include "stdafx.h" + +UITopBarForm::UITopBarForm() +{ + +#define ADD_BUTTON_IMAGE_T1(Class, Name) +#define ADD_BUTTON_IMAGE_T2(Class, Name) +#define ADD_BUTTON_IMAGE_S(Name) \ + m_t##Name = EDevice.Resources->_CreateTexture("ed\\bar\\" #Name); \ + m_t##Name->Load(); \ + m_time##Name = 0; +#define ADD_BUTTON_IMAGE_D(Name) \ + m_t##Name = EDevice.Resources->_CreateTexture("ed\\bar\\" #Name); \ + m_t##Name->Load(); \ + m_b##Name = false; +#include "UITopBarForm_ButtonList.h" + RefreshBar(); +} + +UITopBarForm::~UITopBarForm() +{ +} + +void UITopBarForm::Draw() +{ + ImGuiViewport *viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + UI->GetMenuBarHeight())); + ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, UIToolBarSize)); + ImGui::SetNextWindowViewport(viewport->ID); + + ImGuiWindowFlags window_flags = 0 | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings; + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(2, 2)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(2, 2)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 2)); + ImGui::Begin("TOOLBAR", NULL, window_flags); + { +#define ADD_BUTTON_IMAGE_S(Name) \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_time##Name > EDevice.TimerAsync() ? 0.5 : 0, 0), ImVec2(m_time##Name > EDevice.TimerAsync() ? 1 : 0.5, 1), 0)) \ + { \ + m_time##Name = EDevice.TimerAsync() + 130; \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_D(Name) \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_b##Name ? 0.5 : 0, 0), ImVec2(m_b##Name ? 1 : 0.5, 1), 0)) \ + { \ + m_b##Name = !m_b##Name; \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_P(Name) \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_b##Name ? 0.5 : 0, 0), ImVec2(m_b##Name ? 1 : 0.5, 1), 0)) \ + { \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_T1(Class, Name) \ + ImGui::PushStyleColor(ImGuiCol_Text, (ImVec4)ImColor::HSV(0, 0, 0)); \ + if (ImGui::Button("" #Name, ImVec2(20, 20))) \ + { \ + Click##Class##Name(); \ + } \ + ImGui::SameLine(); \ + ImGui::PopStyleColor(1); +//#define ADD_BUTTON_IMAGE_T1(Class, Name) \ +// ImGui::PushID("" #Class); \ +// ImGui::PushStyleColor(ImGuiCol_Text, (ImVec4)ImColor::HSV(0, 0, 0)); \ +// if (ImGui::Button("" #Name, ImVec2(20, 20))) \ +// { \ +// Click##Class##Name(); \ +// } \ +// ImGui::SameLine(); \ +// ImGui::PopStyleColor(1); \ +// ImGui::PopID(); +#define ADD_BUTTON_IMAGE_T2(Class, Name) \ + ImGui::PushID("" #Class); \ + if (ImGui::Button("" #Name, ImVec2(20, 20))) \ + { \ + Click##Class##Name(); \ + } \ + ImGui::SameLine(); \ + ImGui::PopID(); +#include "UITopBarForm_ButtonList.h" + bool Simulate = ATools->IsPhysics(); + + if (ImGui::Checkbox("Simulate", &Simulate)) + { + if (Simulate) + ATools->PhysicsSimulate(); + else + ATools->PhysicsStopSimulate(); + } + } + ImGui::End(); + ImGui::PopStyleVar(5); +} +void UITopBarForm::RefreshBar() +{ + { + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = false; + + switch (Tools->GetAction()) + { + case etaSelect: + m_bSelect = true; + break; + case etaAdd: + m_bAdd = true; + break; + case etaMove: + m_bMove = true; + break; + case etaRotate: + m_bRotate = true; + break; + case etaScale: + m_bScale = true; + break; + default: + THROW; + } + } + { + m_bX = false; + m_bY = false; + m_bZ = false; + m_bZX = false; + // axis + switch (Tools->GetAxis()) + { + case etAxisX: + m_bX = true; + break; + case etAxisY: + m_bY = true; + break; + case etAxisZ: + m_bZ = true; + break; + case etAxisZX: + m_bZX = true; + break; + default: + THROW; + } + } + // settings + m_bCsLocal = Tools->GetSettings(etfCSParent); + m_bNuScale = Tools->GetSettings(etfNUScale); + m_bNSnap = Tools->GetSettings(etfNormalAlign); + m_bGSnap = Tools->GetSettings(etfGSnap); + m_bOSnap = Tools->GetSettings(etfOSnap); + m_bMoveToSnap = Tools->GetSettings(etfMTSnap); + m_bVSnap = Tools->GetSettings(etfVSnap); + m_bASnap = Tools->GetSettings(etfASnap); + m_bMSnap = Tools->GetSettings(etfMSnap); +} + +void UITopBarForm::ClickUndo() +{ + ExecCommand(COMMAND_UNDO); +} + +void UITopBarForm::ClickRedo() +{ + ExecCommand(COMMAND_REDO); +} +void UITopBarForm::ClickZoom() +{ + ExecCommand(COMMAND_ZOOM_EXTENTS, FALSE); +} + +void UITopBarForm::ClickZoomSel() +{ + ExecCommand(COMMAND_ZOOM_EXTENTS, TRUE); +} +void UITopBarForm::ClickSelect() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + m_bSelect = true; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickAdd() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaAdd); + m_bSelect = false; + m_bAdd = true; + m_bMove = false; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickMove() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaMove); + m_bSelect = false; + m_bAdd = false; + m_bMove = true; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickRotate() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaRotate); + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = true; + m_bScale = false; +} +void UITopBarForm::ClickScale() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaScale); + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = true; +} +void UITopBarForm::ClickX() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisX); + m_bX = true; + m_bY = false; + m_bZ = false; + m_bZX = false; +} +void UITopBarForm::ClickY() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisY); + m_bX = false; + m_bY = true; + m_bZ = false; + m_bZX = false; +} +void UITopBarForm::ClickZ() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisZ); + m_bX = false; + m_bY = false; + m_bZ = true; + m_bZX = false; +} +void UITopBarForm::ClickZX() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisZX); + m_bX = false; + m_bY = false; + m_bZ = false; + m_bZX = true; +} + +void UITopBarForm::ClickCsLocal() { ExecCommand(COMMAND_SET_SETTINGS, etfCSParent, m_bCsLocal); } +void UITopBarForm::ClickNuScale() { ExecCommand(COMMAND_SET_SETTINGS, etfNUScale, m_bNuScale); } +void UITopBarForm::ClickGSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfGSnap, m_bGSnap); } +void UITopBarForm::ClickOSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfOSnap, m_bOSnap); } +void UITopBarForm::ClickMoveToSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfMTSnap, m_bMoveToSnap); } +void UITopBarForm::ClickNSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfNormalAlign, m_bNSnap); } +void UITopBarForm::ClickVSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfVSnap, m_bVSnap); } +void UITopBarForm::ClickASnap() { ExecCommand(COMMAND_SET_SETTINGS, etfASnap, m_bASnap); } +void UITopBarForm::ClickMSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfMSnap, m_bMSnap); } + +void UITopBarForm::ClickCameraP() +{ + EDevice.m_Camera.SetStyle(csPlaneMove); + UI->RedrawScene(); +} +void UITopBarForm::ClickCameraA() +{ + EDevice.m_Camera.SetStyle(cs3DArcBall); + UI->RedrawScene(); +} +void UITopBarForm::ClickCameraF() +{ + EDevice.m_Camera.SetStyle(csFreeFly); + UI->RedrawScene(); +} + +void UITopBarForm::ClickViewB1() +{ + EDevice.m_Camera.ViewBack(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewB2() +{ + EDevice.m_Camera.ViewBottom(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewF() +{ + EDevice.m_Camera.ViewFront(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewL() +{ + EDevice.m_Camera.ViewLeft(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewR() +{ + EDevice.m_Camera.ViewRight(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewT() +{ + EDevice.m_Camera.ViewTop(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewX() +{ + EDevice.m_Camera.ViewReset(); + UI->RedrawScene(); +} diff --git a/src/editors/ActorEditor/UITopBarForm.h b/src/editors/ActorEditor/UITopBarForm.h new file mode 100644 index 00000000000..d03033bf987 --- /dev/null +++ b/src/editors/ActorEditor/UITopBarForm.h @@ -0,0 +1,26 @@ +#pragma once +class UITopBarForm : public xrUI +{ +public: + UITopBarForm(); + virtual ~UITopBarForm(); + virtual void Draw(); + void RefreshBar(); + +private: +#define ADD_BUTTON_IMAGE_T1(Class, Name) void Click##Class##Name(); +#define ADD_BUTTON_IMAGE_T2(Class, Name) void Click##Class##Name(); +#define ADD_BUTTON_IMAGE_S(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + u32 m_time##Name; +#define ADD_BUTTON_IMAGE_D(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + bool m_b##Name; +#define ADD_BUTTON_IMAGE_P(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + bool m_b##Name; +#include "UITopBarForm_ButtonList.h" +}; \ No newline at end of file diff --git a/src/editors/ActorEditor/UITopBarForm_ButtonList.h b/src/editors/ActorEditor/UITopBarForm_ButtonList.h new file mode 100644 index 00000000000..526ba68bbf2 --- /dev/null +++ b/src/editors/ActorEditor/UITopBarForm_ButtonList.h @@ -0,0 +1,50 @@ +#ifndef ADD_BUTTON_IMAGE_P +#define ADD_BUTTON_IMAGE_P(Name) ADD_BUTTON_IMAGE_D(Name) +#endif +#ifndef ADD_BUTTON_IMAGE_T1_1 +#define ADD_BUTTON_IMAGE_T1_1(Class, Name, T) ADD_BUTTON_IMAGE_T1(Class, Name) +#endif +ADD_BUTTON_IMAGE_S(Undo) +ADD_BUTTON_IMAGE_S(Redo) + +ADD_BUTTON_IMAGE_P(Select) +ADD_BUTTON_IMAGE_P(Add) +ADD_BUTTON_IMAGE_P(Move) +ADD_BUTTON_IMAGE_P(Rotate) +ADD_BUTTON_IMAGE_P(Scale) + +ADD_BUTTON_IMAGE_P(X) +ADD_BUTTON_IMAGE_P(Y) +ADD_BUTTON_IMAGE_P(Z) +ADD_BUTTON_IMAGE_P(ZX) + +ADD_BUTTON_IMAGE_D(CsLocal) +ADD_BUTTON_IMAGE_D(NuScale) +ADD_BUTTON_IMAGE_D(GSnap) +ADD_BUTTON_IMAGE_D(OSnap) +ADD_BUTTON_IMAGE_D(MoveToSnap) +ADD_BUTTON_IMAGE_D(NSnap) +ADD_BUTTON_IMAGE_D(VSnap) +ADD_BUTTON_IMAGE_D(ASnap) +ADD_BUTTON_IMAGE_D(MSnap) + +ADD_BUTTON_IMAGE_S(Zoom) +ADD_BUTTON_IMAGE_S(ZoomSel) + +ADD_BUTTON_IMAGE_T1(View, F) +ADD_BUTTON_IMAGE_T1_1(View, B1, B) +ADD_BUTTON_IMAGE_T1(View, L) +ADD_BUTTON_IMAGE_T1(View, R) +ADD_BUTTON_IMAGE_T1(View, T) +ADD_BUTTON_IMAGE_T1_1(View, B2, B) +ADD_BUTTON_IMAGE_T1(View, X) + +ADD_BUTTON_IMAGE_T2(Camera, P) +ADD_BUTTON_IMAGE_T2(Camera, A) +ADD_BUTTON_IMAGE_T2(Camera, F) + +#undef ADD_BUTTON_IMAGE_D +#undef ADD_BUTTON_IMAGE_S +#undef ADD_BUTTON_IMAGE_P +#undef ADD_BUTTON_IMAGE_T1 +#undef ADD_BUTTON_IMAGE_T2 diff --git a/src/editors/ActorEditor/UI_ActorMain.cpp b/src/editors/ActorEditor/UI_ActorMain.cpp new file mode 100644 index 00000000000..fc46fe8417f --- /dev/null +++ b/src/editors/ActorEditor/UI_ActorMain.cpp @@ -0,0 +1,565 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "UI_ActorMain.h" + +//--------------------------------------------------------------------------- +CActorMain *AUI = (CActorMain *)UI; +//--------------------------------------------------------------------------- +/* +CActorMain::CActorMain() +{ + EPrefs = xr_new(); +} +//--------------------------------------------------------------------------- + +CActorMain::~CActorMain() +{ + xr_delete (EPrefs); +} +//--------------------------------------------------------------------------- +*/ +//--------------------------------------------------------------------------- +// actor commands +//--------------------------------------------------------------------------- + +CCommandVar CActorTools::CommandSaveBackup(CCommandVar p1, CCommandVar p2) +{ + string_path fn; + strconcat(sizeof(fn), fn, Core.UserName, "_backup.object"); + FS.update_path(fn, "$objects$", fn); + ExecCommand(COMMAND_SAVE, xr_string(fn)); + return TRUE; +} +CCommandVar CActorTools::CommandSave(CCommandVar p1, CCommandVar p2) +{ + if (p2 == 1) + { + xr_string temp_fn = ATools->m_LastFileName.c_str(); + if (EFS.GetSaveName(_objects_, temp_fn)) + { + temp_fn = EFS.ChangeFileExt(temp_fn, ".object"); + return ExecCommand(COMMAND_SAVE, temp_fn, 0); + } + } + else + { + if (p1.IsInteger()) + return ExecCommand(COMMAND_SAVE, xr_string(ATools->m_LastFileName.c_str()), 0); + xr_string temp_fn = xr_string(p1); + if (temp_fn.empty()) + { + return ExecCommand(COMMAND_SAVE, temp_fn, 1); + } + else + { + xr_strlwr(temp_fn); + CTimer T; + T.Start(); + CCommandVar res; + if (Tools->Save(temp_fn.c_str())) + { + ELog.Msg(mtInformation, "Object '%s' successfully saved. Saving time - %3.2f(s).", m_LastFileName.c_str(), T.GetElapsed_sec()); + m_LastFileName = temp_fn.c_str(); + EPrefs->AppendRecentFile(m_LastFileName.c_str()); + ExecCommand(COMMAND_UPDATE_CAPTION); + res = TRUE; + } + else + { + res = FALSE; + } + return res; + } + } + return FALSE; +} +CCommandVar CActorTools::CommandImport(CCommandVar p1, CCommandVar p2) +{ + xr_string temp_fn = p1.IsString() ? xr_string(p1) : xr_string(""); + if (p1.IsString() || EFS.GetOpenName(EDevice.m_hWnd, _import_, temp_fn)) + { + FS_Path *pp = FS.get_path(_import_); + + if (temp_fn.npos != temp_fn.find(pp->m_Path)) + { + xr_strlwr(temp_fn); + if (!Tools->IfModified()) + return FALSE; + + ExecCommand(COMMAND_CLEAR); + CTimer T; + T.Start(); + if (!ATools->Import(NULL, temp_fn.c_str())) + return FALSE; + + m_LastFileName = temp_fn.c_str(); + ELog.Msg(mtInformation, "Object '%s' successfully imported. Loading time - %3.2f(s).", m_LastFileName.c_str(), T.GetElapsed_sec()); + if (ExecCommand(COMMAND_SAVE, temp_fn, 1)) + { + xr_string mfn; + mfn = temp_fn; + EFS.MarkFile(mfn.c_str(), true); + } + else + { + ExecCommand(COMMAND_CLEAR); + } + return TRUE; + } + else + { + ELog.Msg(mtError, "Invalid file path. "); + } + } + return FALSE; +} +CCommandVar CActorTools::CommandExportDM(CCommandVar p1, CCommandVar p2) +{ + CCommandVar res = FALSE; + xr_string fn = p1.IsString() ? xr_string(p1) : xr_string(""); + if (p1.IsString() || EFS.GetSaveName("$game_dm$", fn)) + { + if (0 != (res = ExportDM(fn.c_str()))) + ELog.Msg(mtInformation, "Export complete."); + else + ELog.Msg(mtError, "Export failed."); + } + return res; +} +CCommandVar CActorTools::CommandExportOBJ(CCommandVar p1, CCommandVar p2) +{ + CCommandVar res = FALSE; + xr_string fn = p1.IsString() ? xr_string(p1) : xr_string(""); + + if (p1.IsString() || EFS.GetSaveName("$import$", fn, 0, 5)) + { + if (0 != (res = ExportOBJ(fn.c_str()))) + ELog.Msg(mtInformation, "Export complete."); + else + ELog.Msg(mtError, "Export failed."); + } + return res; +} +CCommandVar CActorTools::CommandExportOGF(CCommandVar p1, CCommandVar p2) +{ + CCommandVar res = FALSE; + xr_string fn = p1.IsString() ? xr_string(p1) : xr_string(""); + if (p1.IsString() || EFS.GetSaveName("$game_meshes$", fn, 0, 0)) + { + if (0 != (res = ATools->ExportOGF(fn.c_str()))) + ELog.Msg(mtInformation, "Export complete."); + else + ELog.Msg(mtError, "Export failed."); + } + return res; +} +CCommandVar CActorTools::CommandExportOMF(CCommandVar p1, CCommandVar p2) +{ + CCommandVar res = FALSE; + xr_string fn = p1.IsString() ? xr_string(p1) : xr_string(""); + + if (p1.IsString() || EFS.GetSaveName("$game_meshes$", fn, 0, 1)) + { + if (0 != (res = ExportOMF(fn.c_str()))) + ELog.Msg(mtInformation, "Export complete."); + else + ELog.Msg(mtError, "Export failed."); + } + return res; +} +CCommandVar CActorTools::CommandExportCPP(CCommandVar p1, CCommandVar p2) +{ + CCommandVar res = FALSE; + xr_string fn = p1.IsString() ? xr_string(p1) : xr_string(""); + if (p1.IsString() || EFS.GetSaveName(_import_, fn, 0, 7)) + { + if (0 != (res = ExportCPP(fn.c_str()))) + ELog.Msg(mtInformation, "Export complete."); + else + ELog.Msg(mtError, "Export failed."); + } + return res; +} + +CCommandVar CActorTools::CommandUndo(CCommandVar p1, CCommandVar p2) +{ + if (!Undo()) + ELog.Msg(mtInformation, "Undo buffer empty"); + else + return ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + + return FALSE; +} +CCommandVar CActorTools::CommandRedo(CCommandVar p1, CCommandVar p2) +{ + if (!Redo()) + ELog.Msg(mtInformation, "Redo buffer empty"); + else + return ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + + return FALSE; +} +CCommandVar CActorTools::CommandOptimizeMotions(CCommandVar p1, CCommandVar p2) +{ + OptimizeMotions(); + return TRUE; +} +CCommandVar CActorTools::CommandMakeThumbnail(CCommandVar p1, CCommandVar p2) +{ + MakeThumbnail(); + return TRUE; +} +CCommandVar CActorTools::CommandBatchConvert(CCommandVar p1, CCommandVar p2) +{ + CCommandVar res = FALSE; + xr_string fn; + if (EFS.GetOpenName(EDevice.m_hWnd, "$import$", fn, false, 0, 6)) + { + if (0 != (res = BatchConvert(fn.c_str()))) + ELog.Msg(mtInformation, "Convert complete."); + else + ELog.Msg(mtError, "Convert failed."); + } + return res; +} + +const char *CActorMain::GetCaption() +{ + return ATools->GetEditFileName().empty() ? "noname" : ATools->GetEditFileName().c_str(); +} + +bool CActorMain::ApplyShortCut(DWORD Key, TShiftState Shift) +{ + return inherited::ApplyShortCut(Key, Shift); +} + +bool CActorMain::ApplyGlobalShortCut(DWORD Key, TShiftState Shift) +{ + return inherited::ApplyGlobalShortCut(Key, Shift); +} + +void CActorMain::RealUpdateScene() +{ + inherited::RealUpdateScene(); +} + +void CActorMain::ResetStatus() +{ + VERIFY(m_bReady); + + /* if (fraBottomBar->paStatus->Caption!=""){ + fraBottomBar->paStatus->Caption=""; fraBottomBar->paStatus->Repaint(); + }*/ +} + +void CActorMain::SetStatus(LPCSTR s, bool bOutLog) +{ + VERIFY(m_bReady); + + /*if (fraBottomBar->paStatus->Caption!=s) + { + fraBottomBar->paStatus->Caption=s; fraBottomBar->paStatus->Repaint(); + if (bOutLog&&s&&s[0]) ELog.Msg(mtInformation,s); + }*/ +} + +void CActorMain::ProgressDraw() +{ + inherited::ProgressDraw(); + /*fraBottomBar->RedrawBar();*/ +} +//--------------------------------------------------------------------------- +void CActorMain::OutCameraPos() +{ + VERIFY(m_bReady); + + /* AnsiString s; + const Fvector& c = EDevice.m_Camera.GetPosition(); + s.sprintf("C: %3.1f, %3.1f, %3.1f",c.x,c.y,c.z); + // const Fvector& hpb = EDevice.m_Camera.GetHPB(); + // s.sprintf(" Cam: %3.1f�, %3.1f�, %3.1f�",rad2deg(hpb.y),rad2deg(hpb.x),rad2deg(hpb.z)); + fraBottomBar->paCamera->Caption=s; fraBottomBar->paCamera->Repaint();*/ +} +//--------------------------------------------------------------------------- +void CActorMain::OutUICursorPos() +{ + + /* VERIFY(fraBottomBar); + AnsiString s; POINT pt; + GetCursorPos(&pt); + s.sprintf("Cur: %d, %d",pt.x,pt.y); + fraBottomBar->paUICursor->Caption=s; fraBottomBar->paUICursor->Repaint();*/ +} +//--------------------------------------------------------------------------- +void CActorMain::OutGridSize() +{ + + /*VERIFY(fraBottomBar); + AnsiString s; + s.sprintf("Grid: %1.1f",EPrefs->grid_cell_size); + fraBottomBar->paGridSquareSize->Caption=s; fraBottomBar->paGridSquareSize->Repaint();*/ +} +//--------------------------------------------------------------------------- +void CActorMain::OutInfo() +{ + + // fraBottomBar->paSel->Caption = Tools->GetInfo(); +} +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- + +void CAEPreferences::Load(CInifile *I) +{ + inherited::Load(I); + + bAlwaysShowKeyBar12 = R_BOOL_SAFE("ae_prefs", "always_show_keybar12", bAlwaysShowKeyBar12); + bAlwaysShowKeyBar34 = R_BOOL_SAFE("ae_prefs", "always_show_keybar34", bAlwaysShowKeyBar34); +} + +void CAEPreferences::Save(CInifile *I) +{ + inherited::Save(I); + + I->w_bool("ae_prefs", "always_show_keybar12", bAlwaysShowKeyBar12); + I->w_bool("ae_prefs", "always_show_keybar34", bAlwaysShowKeyBar34); +} +extern ECORE_API BOOL g_force16BitTransformQuant; +void CAEPreferences::FillProp(PropItemVec &props) +{ + inherited::FillProp(props); + + PHelper().CreateBOOL(props, "Keybar\\show footsteps 12", &bAlwaysShowKeyBar12); + PHelper().CreateBOOL(props, "Keybar\\show footsteps 34", &bAlwaysShowKeyBar34); + + PHelper().CreateBOOL(props, "Tools\\MotionExport\\Force 16bit MotionT", &g_force16BitTransformQuant); +} + +CActorMain::CActorMain() +{ + EPrefs = xr_new(); +} + +CActorMain::~CActorMain() +{ + xr_delete(EPrefs); +} + +//--------------------------------------------------------------------------- +// Common command +//--------------------------------------------------------------------------- +CCommandVar CommandShowClipMaker(CCommandVar p1, CCommandVar p2) +{ + ATools->ShowClipMaker(); + return TRUE; +} +CCommandVar CommandMakePreview(CCommandVar p1, CCommandVar p2) +{ + ATools->MakePreview(); + return TRUE; +} +CCommandVar CommandPreviewObjPref(CCommandVar p1, CCommandVar p2) +{ + ATools->SetPreviewObjectPrefs(); + return TRUE; +} +CCommandVar CommandSelectPreviewObj(CCommandVar p1, CCommandVar p2) +{ + ATools->SelectPreviewObject(p1); + return TRUE; +} +CCommandVar CommandLoadFirstRecent(CCommandVar p1, CCommandVar p2) +{ + if (EPrefs->FirstRecentFile()) + return ExecCommand(COMMAND_LOAD, xr_string(EPrefs->FirstRecentFile())); + + return FALSE; +} +CCommandVar CommandFileMenu(CCommandVar p1, CCommandVar p2) +{ + // FHelper.ShowPPMenu(fraLeftBar->pmSceneFile, 0); + return TRUE; +} +CCommandVar CommandRefreshUIBar(CCommandVar p1, CCommandVar p2) +{ + // not_implemented(); + /* fraTopBar->RefreshBar(); + fraLeftBar->RefreshBar(); + fraBottomBar->RefreshBar();*/ + return TRUE; +} +CCommandVar CommandRestoreUIBar(CCommandVar p1, CCommandVar p2) +{ + // not_implemented(); + /* fraTopBar->fsStorage->RestoreFormPlacement(); + fraLeftBar->fsStorage->RestoreFormPlacement(); + fraBottomBar->fsStorage->RestoreFormPlacement();*/ + return TRUE; +} +CCommandVar CommandSaveUIBar(CCommandVar p1, CCommandVar p2) +{ + return TRUE; +} +CCommandVar CommandUpdateToolBar(CCommandVar p1, CCommandVar p2) +{ + // not_implemented(); + // fraLeftBar->UpdateBar(); + return TRUE; +} +CCommandVar CommandUpdateCaption(CCommandVar p1, CCommandVar p2) +{ + // not_implemented(); + // frmMain->UpdateCaption(); + return TRUE; +} + +CCommandVar CommandChangeTarget(CCommandVar p1, CCommandVar p2) +{ + if (p1.IsString()) + { + ATools->SelectListItem(xr_string(p1).c_str(), 0, true, false, true); + } + else + { + switch (p1) + { + case 0: + ATools->SelectListItem(BONES_PREFIX, 0, true, false, true); + break; + case 1: + ATools->SelectListItem(MOTIONS_PREFIX, 0, true, false, true); + break; + case 2: + ATools->SelectListItem(OBJECT_PREFIX, 0, true, false, true); + break; + case 3: + ATools->SelectListItem(SURFACES_PREFIX, 0, true, false, true); + break; + } + } + return TRUE; +} +CCommandVar CActorTools::CommandClear(CCommandVar p1, CCommandVar p2) +{ + if (!IfModified()) + return FALSE; + + m_LastFileName = ""; + EDevice.m_Camera.Reset(); + Clear(); + ExecCommand(COMMAND_UPDATE_CAPTION); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + UndoClear(); + return TRUE; +} + +CCommandVar CActorTools::CommandLoad(CCommandVar p1, CCommandVar p2) +{ + xr_string temp_fn = p1.IsString() ? xr_string(p1) : xr_string(""); + if (!p1.IsString()) + { + temp_fn = EFS.ChangeFileExt(m_LastFileName.c_str(), ""); + if (!EFS.GetOpenName(EDevice.m_hWnd, _objects_, temp_fn)) + return FALSE; + } + if (temp_fn.size()) + { + xr_strlwr(temp_fn); + if (!IfModified()) + return FALSE; + + if (!FS.exist(temp_fn.c_str())) + { + Msg("#!Can't load file: %s", temp_fn.c_str()); + return FALSE; + } + + ExecCommand(COMMAND_CLEAR); + + BOOL bReadOnly = !FS.can_modify_file(temp_fn.c_str()); + m_Flags.set(flReadOnlyMode, bReadOnly); + + // set enable ... + // m_Props->SetReadOnly(bReadOnly); + + // fraLeftBar->SetReadOnly(bReadOnly); + + CTimer T; + T.Start(); + if (!Load(temp_fn.c_str())) + { + return FALSE; + } + m_LastFileName = temp_fn.c_str(); + ELog.Msg(mtInformation, "Object '%s' successfully loaded. Loading time - %3.2f(s).", m_LastFileName.c_str(), T.GetElapsed_sec()); + EPrefs->AppendRecentFile(m_LastFileName.c_str()); + ExecCommand(COMMAND_UPDATE_CAPTION); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + + UndoClear(); + UndoSave(); + } + return TRUE; +} + +void CActorMain::RegisterCommands() +{ + inherited::RegisterCommands(); + // tools + REGISTER_CMD_CE(COMMAND_CLEAR, "File\\Clear Scene", ATools, CActorTools::CommandClear, true); + REGISTER_CMD_CE(COMMAND_LOAD, "File\\Load", ATools, CActorTools::CommandLoad, true); + REGISTER_CMD_C(COMMAND_SAVE_BACKUP, ATools, CActorTools::CommandSaveBackup); + REGISTER_SUB_CMD_CE(COMMAND_SAVE, "File", ATools, CActorTools::CommandSave, true); + APPEND_SUB_CMD("Save", 0, 0); + APPEND_SUB_CMD("Save As", 0, 1); + REGISTER_SUB_CMD_END; + REGISTER_CMD_CE(COMMAND_IMPORT, "File\\Import", ATools, CActorTools::CommandImport, true); + REGISTER_CMD_CE(COMMAND_EXPORT_DM, "File\\Export DM", ATools, CActorTools::CommandExportDM, true); + REGISTER_CMD_CE(COMMAND_EXPORT_OBJ, "File\\Export OBJ", ATools, CActorTools::CommandExportOBJ, true); + REGISTER_CMD_CE(COMMAND_EXPORT_OGF, "File\\Export OGF", ATools, CActorTools::CommandExportOGF, true); + REGISTER_CMD_CE(COMMAND_EXPORT_OMF, "File\\Export OMF", ATools, CActorTools::CommandExportOMF, true); + REGISTER_CMD_CE(COMMAND_EXPORT_CPP, "File\\Export CPP", ATools, CActorTools::CommandExportCPP, true); + REGISTER_CMD_CE(COMMAND_UNDO, "Edit\\Undo", ATools, CActorTools::CommandUndo, false); + REGISTER_CMD_CE(COMMAND_REDO, "Edit\\Redo", ATools, CActorTools::CommandRedo, false); + REGISTER_CMD_C(COMMAND_OPTIMIZE_MOTIONS, ATools, CActorTools::CommandOptimizeMotions); + REGISTER_CMD_CE(COMMAND_MAKE_THUMBNAIL, "Make Thumbnail", ATools, CActorTools::CommandMakeThumbnail, false); + REGISTER_CMD_CE(COMMAND_BATCH_CONVERT, "File\\Batch Convert", ATools, CActorTools::CommandBatchConvert, false); + // ui + REGISTER_CMD_S(COMMAND_SHOW_CLIPMAKER, CommandShowClipMaker); + REGISTER_CMD_S(COMMAND_MAKE_PREVIEW, CommandMakePreview); + REGISTER_CMD_S(COMMAND_PREVIEW_OBJ_PREF, CommandPreviewObjPref); + REGISTER_CMD_S(COMMAND_SELECT_PREVIEW_OBJ, CommandSelectPreviewObj); + REGISTER_CMD_SE(COMMAND_LOAD_FIRSTRECENT, "File\\Load First Recent", CommandLoadFirstRecent, true); + REGISTER_CMD_SE(COMMAND_FILE_MENU, "File Menu", CommandFileMenu, true); + REGISTER_CMD_S(COMMAND_REFRESH_UI_BAR, CommandRefreshUIBar); + REGISTER_CMD_S(COMMAND_RESTORE_UI_BAR, CommandRestoreUIBar); + REGISTER_CMD_S(COMMAND_SAVE_UI_BAR, CommandSaveUIBar); + REGISTER_CMD_S(COMMAND_UPDATE_TOOLBAR, CommandUpdateToolBar); + REGISTER_CMD_S(COMMAND_UPDATE_CAPTION, CommandUpdateCaption); + REGISTER_SUB_CMD_SE(COMMAND_CHANGE_TARGET, "Change Target", CommandChangeTarget, true); + APPEND_SUB_CMD(BONES_PREFIX, xr_string(BONES_PREFIX), 0); + APPEND_SUB_CMD(MOTIONS_PREFIX, xr_string(MOTIONS_PREFIX), 0); + APPEND_SUB_CMD(OBJECT_PREFIX, xr_string(OBJECT_PREFIX), 0); + APPEND_SUB_CMD(SURFACES_PREFIX, xr_string(SURFACES_PREFIX), 0); + REGISTER_SUB_CMD_END; +} + +void CActorMain::OnDrawUI() +{ + TUI::OnDrawUI(); + UIBoneForm::Update(); +} + +Ivector2 CActorMain::GetRenderMousePosition() const +{ + return MainForm->GetRenderForm()->GetMousePos(); +} + +#include "Resources\resource.h" + +HICON CActorMain::EditorIcon() +{ + return LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(MAINICON)); +} diff --git a/src/editors/ActorEditor/UI_ActorMain.h b/src/editors/ActorEditor/UI_ActorMain.h new file mode 100644 index 00000000000..3be3c27d108 --- /dev/null +++ b/src/editors/ActorEditor/UI_ActorMain.h @@ -0,0 +1,75 @@ +#pragma once + +enum +{ + COMMAND_EXTFIRST_EXT = COMMAND_MAIN_LAST - 1, + + COMMAND_MAKE_PREVIEW, + COMMAND_IMPORT, + COMMAND_EXPORT_OGF, + COMMAND_EXPORT_OMF, + COMMAND_EXPORT_DM, + COMMAND_EXPORT_OBJ, + COMMAND_EXPORT_CPP, + COMMAND_BATCH_CONVERT, + COMMAND_PREVIEW_OBJ_PREF, + COMMAND_SELECT_PREVIEW_OBJ, + COMMAND_SHOW_CLIPMAKER, + COMMAND_OPTIMIZE_MOTIONS, + COMMAND_MAKE_THUMBNAIL, + COMMAND_CHANGE_TARGET, + + COMMAND_FILE_MENU, + COMMAND_LOAD_FIRSTRECENT, +}; + +class CActorMain : public TUI +{ + typedef TUI inherited; + + virtual void RealUpdateScene(); + +public: + CActorMain(); + virtual ~CActorMain(); + + virtual const char* GetCaption(); + + virtual void ResetStatus(); + virtual void SetStatus(LPCSTR s, bool bOutLog); + virtual void ProgressDraw(); + virtual void OutCameraPos(); + virtual void OutUICursorPos(); + virtual void OutGridSize(); + virtual void OutInfo(); + + virtual LPCSTR EditorName() { return "actor"; } + virtual LPCSTR EditorDesc() { return "Actor Editor"; } + HICON EditorIcon() override; + + virtual bool ApplyShortCut(DWORD Key, TShiftState Shift); + virtual bool ApplyGlobalShortCut(DWORD Key, TShiftState Shift); + + // commands + virtual void RegisterCommands(); + +protected: + virtual void OnDrawUI(); + + virtual Ivector2 GetRenderMousePosition() const; +}; +extern CActorMain *AUI; + +class CAEPreferences : public CCustomPreferences +{ + typedef CCustomPreferences inherited; + +public: + CAEPreferences() : bAlwaysShowKeyBar12(FALSE), bAlwaysShowKeyBar34(FALSE) {} + BOOL bAlwaysShowKeyBar12; + BOOL bAlwaysShowKeyBar34; + + virtual void Load(CInifile *); + virtual void Save(CInifile *); + virtual void FillProp(PropItemVec &items); +}; diff --git a/src/editors/ActorEditor/UI_ActorTools.cpp b/src/editors/ActorEditor/UI_ActorTools.cpp new file mode 100644 index 00000000000..fc63abe4559 --- /dev/null +++ b/src/editors/ActorEditor/UI_ActorTools.cpp @@ -0,0 +1,1351 @@ +#include "stdafx.h" + +#ifndef dSINGLE +#define dSINGLE +#endif + +#include "include\xrRender\animation_blend.h" +#include "..\..\xrPhysics\Physics.h" +#include "..\xrECore\Editor\EditMesh.h" +#include "Layers\xrRender\KinematicAnimatedDefs.h" +#include "Layers\xrRender\SkeletonAnimated.h" +CActorTools *ATools = (CActorTools *)Tools; + +#define CHECK_SNAP(R, A, C) \ + { \ + R += A; \ + if (fabsf(R) >= C) \ + { \ + A = snapto(R, C); \ + R = 0; \ + } \ + else \ + { \ + A = 0; \ + } \ + } + +void EngineModel::DeleteVisual() +{ + DeletePhysicsShell(); + Render->model_Delete(m_pVisual); + m_pVisual = 0; + m_pBlend = 0; +} + +void EngineModel::OnRender() +{ + Fmatrix temp = Fmatrix(); + UpdateObjectXform(temp); +} + +/* +void PreviewModel::RestoreParams(TFormStorage* s) +{ + m_Props->RestoreParams(s); + m_LastObjectName = s->ReadString ("preview_name",""); + int val; + val = s->ReadInteger("preview_speed",0); m_fSpeed = *((float*)&val); + val = s->ReadInteger("preview_segment",0); m_fSegment = *((float*)&val); + m_Flags.assign (s->ReadInteger("preview_flags",0)); + m_ScrollAxis = (EScrollAxis)s->ReadInteger("preview_scaxis",0); +} + +void PreviewModel::SaveParams(TFormStorage* s) +{ + m_Props->SaveParams(s); + s->WriteString ("preview_name", m_LastObjectName); + s->WriteInteger ("preview_speed", *((int*)&m_fSpeed)); + s->WriteInteger ("preview_segment", *((int*)&m_fSegment)); + s->WriteInteger ("preview_flags", m_Flags.get()); + s->WriteInteger ("preview_scaxis", m_ScrollAxis); +} +*/ +/* +void PreviewModel::OnDestroy() +{ + TProperties::DestroyForm(m_Props); +} + +void PreviewModel::OnCreate() +{ + m_Props = TProperties::CreateForm("Preview prefs",0,alNone); +} + +void PreviewModel::Clear() +{ + Lib.RemoveEditObject(m_pObject); +} +void PreviewModel::SelectObject() +{ + LPCSTR fn; + if (!TfrmChoseItem::SelectItem(smObject,fn,1,m_LastObjectName.c_str())) return; + Lib.RemoveEditObject(m_pObject); + m_pObject = Lib.CreateEditObject(fn); + if (!m_pObject) ELog.DlgMsg(mtError,"Object '%s' can't find in object library.",fn); + else m_LastObjectName = fn; +} + +xr_token sa_token [ ]={ + { "+Z", PreviewModel::saZp }, + { "-Z", PreviewModel::saZn }, + { "+X", PreviewModel::saXp }, + { "-X", PreviewModel::saXn }, + { 0, 0 } +}; + +void PreviewModel::SetPreferences() +{ + PropItemVec items; + PHelper().CreateFlag32 (items, "Scroll", &m_Flags, pmScroll); + PHelper().CreateFloat (items, "Speed (m/c)", &m_fSpeed, -10000.f,10000.f,0.01f,2); + PHelper().CreateFloat (items, "Segment (m)", &m_fSegment, -10000.f,10000.f,0.01f,2); + PHelper().CreateToken32 (items, "Scroll axis", (u32*)&m_ScrollAxis, sa_token); + m_Props->AssignItems (items); + m_Props->ShowProperties (); +} +void PreviewModel::Render() +{ + if (m_pObject){ + float angle; + switch (m_ScrollAxis){ + case saZp: angle = 0; break; + case saZn: angle = PI; break; + case saXp: angle = PI_DIV_2;break; + case saXn: angle =-PI_DIV_2;break; + default: THROW; + } + Fmatrix R,T; + R.rotateY(angle); + T.translate(m_vPosition); + T.mulA_43(R); + m_pObject->RenderSingle(T); + } +} + +void PreviewModel::Update() +{ + if (m_Flags.is(pmScroll)) + { + m_vPosition.z += m_fSpeed*EDevice.fTimeDelta; + if (m_vPosition.z>m_fSegment) m_vPosition.z-=m_fSegment; + } +} + +void _SynchronizeTextures() +{ + FS_FileSet M_THUM; + FS.file_list(M_THUM,_textures_,FS_ListFiles|FS_ClampExt,"*.thm"); + + auto it = M_THUM.begin(); + auto _E = M_THUM.end(); + for (; it!=_E; it++){ + ETextureThumbnail* THM=0; + THM = xr_new(it->name.c_str()); + STextureParams& fmt = THM->_Format(); + if (fmt.material==STextureParams::tmOrenNayar_Blin){ + fmt.material=STextureParams::tmBlin_Phong; + THM->Save(0,0); + } + xr_delete(THM); + } +} + +*/ + +CActorTools::CActorTools() +{ + m_IsPhysics = false; + m_ChooseSkeletonBones = false; + m_Props = 0; + m_pEditObject = 0; + m_bObjectModified = false; + m_ObjectItems = 0; + m_Flags.zero(); + m_EditMode = emObject; + fFogness = 0.9f; + dwFogColor = 0xffffffff; +} + +CActorTools::~CActorTools() +{ +} + +#include "..\xrECore\editor\d3dutils.h" + +const u32 color_bone_sel_color = 0xFFFFFFFF; +const u32 color_bone_norm_color = 0xFFFFFF00; +const u32 color_bone_link_color = 0xFFA0A000; +const u32 color_bone_sel_cm = 0xFFFF0000; +const u32 color_bone_norm_cm = 0xFF700000; +const float joint_size = 0.025f; + +void CActorTools::Render() +{ + if (!m_bReady) + return; + PrepareLighting(); + m_PreviewObject.Render(); + if (m_pEditObject) + { + Fmatrix World = Fidentity; + { + m_pEditObject->UpdateObjectXform(World); + } + m_RenderObject.OnRender(); + if (m_RenderObject.IsRenderable() && MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine) + { + ::Render->model_RenderSingle(m_RenderObject.m_pVisual, m_RenderObject.ObjectXFORM(), m_RenderObject.m_fLOD); + RCache.set_xform_world(World); + if (EPrefs->object_flags.is(epoDrawJoints)) + { + CKinematics *K = dynamic_cast(m_RenderObject.m_pVisual); + if (K) + { + u16 bcnt = K->LL_BoneCount(); + for (u16 bidx = 0; bidx < bcnt; ++bidx) + { + EDevice.SetShader(EDevice.m_WireShader); + + Fmatrix M = Fmatrix().mul(m_RenderObject.ObjectXFORM(), K->LL_GetTransform(bidx)); + + Fvector p1 = M.c; + u32 c_joint = color_bone_norm_color; + DU_impl.DrawJoint(p1, joint_size, c_joint); + + if (EPrefs->object_flags.is(epoDrawBoneAxis)) + { + DU_impl.DrawObjectAxis(M, 0.03f, false); + } + } + } + } + } + else + { + // update transform matrix + if (!IsPhysics()) + World = m_AVTransform; + m_pEditObject->RenderSkeletonSingle(World); + } + } + + inherited::Render(); +} + +void CActorTools::RenderEnvironment() +{ +} + +void CActorTools::OnFrame() +{ + if (!m_bReady) + return; + //. if (m_KeyBar) m_KeyBar->UpdateBar(); + m_PreviewObject.Update(); + if (m_pEditObject) + { + // update matrix + Fmatrix mTranslate, mRotate, mScale; + mRotate.setHPB(m_pEditObject->a_vRotate.y, m_pEditObject->a_vRotate.x, m_pEditObject->a_vRotate.z); + mTranslate.translate(m_pEditObject->a_vPosition); + mScale.scale(m_pEditObject->t_vScale); + m_AVTransform.mul(mTranslate, mRotate); + m_AVTransform.mulB_43(mScale); + + if (!MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine) + m_pEditObject->OnFrame(); + + if (!MainForm->GetKeyForm()->AutoChange()) + { + m_pEditObject->m_SMParam.t_current = float(MainForm->GetKeyForm()->Position()); + } + // CKinematicsAnimated* KA = dynamic_cast(m_RenderObject.m_pVisual); + if (m_RenderObject.IsRenderable() && m_pEditObject->IsSkeleton() && m_RenderObject.m_pVisual) + { + + CKinematicsAnimated *KA = dynamic_cast(m_RenderObject.m_pVisual); + if (KA && !MainForm->GetKeyForm()->AutoChange() && m_RenderObject.m_pBlend) + { + float tm = float(MainForm->GetKeyForm()->Position()); + for (int k = 0; k < MAX_PARTS; k++) + { + if (KA->LL_PartBlendsCount(k)) + { + CBlend *B = KA->LL_PartBlend(k, 0); + B->timeCurrent = tm; + } + } + } + + IKinematics *K = m_RenderObject.m_pVisual->dcast_PKinematics(); + VERIFY(K); + // K->Bone_Calculate (&K->LL_GetData(K->LL_GetBoneRoot()),&Fidentity); + if (!MainForm->GetKeyForm()->AutoChange()) + K->Bone_Calculate(&K->LL_GetData(K->LL_GetBoneRoot()), &Fidentity); + else + K->CalculateBones(TRUE); + } + } + if (m_Flags.is(flRefreshShaders)) + { + m_Flags.set(flRefreshShaders, FALSE); + m_pEditObject->OnDeviceDestroy(); + } + if (m_Flags.is(flMakeThumbnail)) + { + m_Flags.set(flMakeThumbnail, FALSE); + RealMakeThumbnail(); + } + if (m_Flags.is(flGenerateLODHQ) || m_Flags.is(flGenerateLODLQ)) + { + RealGenerateLOD(m_Flags.is(flGenerateLODHQ)); + m_Flags.set(flGenerateLODHQ, FALSE); + m_Flags.set(flGenerateLODLQ, FALSE); + } + if (m_Flags.is(flRefreshSubProps)) + { + m_Flags.set(flRefreshSubProps, FALSE); + + xr_vector items; + m_ObjectItems->GetSelected(0, items, false); + OnObjectItemsFocused(items); + } + + if (m_Flags.is(flRefreshProps)) + RealUpdateProperties(); + + /*if (fraLeftBar->ebRenderEditorStyle->Down && !m_CurrentMotion.IsEmpty() && NULL == m_pEditObject->GetActiveSMotion()) + { + AnsiString tmp = m_CurrentMotion; + m_CurrentMotion = ""; + + SetCurrentMotion(tmp.c_str(), m_CurrentSlot); + }*/ +} + +bool CActorTools::OnCreate() +{ + + inherited::OnCreate(); + m_ObjectItems = xr_new(); + m_ObjectItems->m_Flags.set(UIItemListForm::fMultiSelect, true); + m_Props = xr_new(); + m_ObjectItems->SetOnItemsFocusedEvent(TOnILItemsFocused(this, &CActorTools::OnObjectItemsFocused)); + m_PreviewObject.OnCreate(); + + // key bar + + OnDeviceCreate(); + return true; +} + +void CActorTools::OnDestroy() +{ + inherited::OnDestroy(); + + xr_delete(m_Props); + xr_delete(m_ObjectItems); + m_PreviewObject.OnDestroy(); + + m_PreviewObject.Clear(); + m_RenderObject.Clear(); + xr_delete(m_pEditObject); +} + +bool CActorTools::IfModified() +{ + if (IsModified()) + { + int mr = ELog.DlgMsg(mtConfirmation, "The '%s' has been modified.\nDo you want to save your changes?", GetEditFileName().c_str()); + switch (mr) + { + case mrYes: + if (!ExecCommand(COMMAND_SAVE)) + return false; + else + { + m_bObjectModified = false; + } + break; + case mrNo: + m_bObjectModified = false; + break; + case mrCancel: + return false; + } + } + return true; +} + +void CActorTools::Modified() +{ + m_bObjectModified = true; + ExecCommand(COMMAND_UPDATE_CAPTION); +} +void CActorTools::OnBoneModified(void) +{ + Modified(); + RefreshSubProperties(); + UndoSave(); +} +void CActorTools::OnItemModified(void) +{ + switch (m_EditMode) + { + case emObject: + OnObjectModified(); + break; + case emMotion: + OnMotionDefsModified(); + break; + case emBone: + OnBoneModified(); + break; + case emSurface: + OnObjectModified(); + break; + case emMesh: + break; + } +} + +LPCSTR CActorTools::GetInfo() +{ + return 0; +} + +void CActorTools::ZoomObject(BOOL bSelOnly) +{ + VERIFY(m_bReady); + if (m_pEditObject) + { + Fbox BB; + switch (m_EditMode) + { + case emBone: + { + BoneVec lst; + if (m_pEditObject->GetSelectedBones(lst)) + { + BB.invalidate(); + for (BoneIt b_it = lst.begin(); b_it != lst.end(); b_it++) + { + Fvector C = {0, 0, 0}; + float r = 0.5f; + switch ((*b_it)->shape.type) + { + case SBoneShape::stBox: + r = _max(_max((*b_it)->shape.box.m_halfsize.x, (*b_it)->shape.box.m_halfsize.y), (*b_it)->shape.box.m_halfsize.z); + C = (*b_it)->shape.box.m_translate; + break; + case SBoneShape::stSphere: + r = (*b_it)->shape.sphere.R; + C = (*b_it)->shape.sphere.P; + break; + case SBoneShape::stCylinder: + r = _max((*b_it)->shape.cylinder.m_height, (*b_it)->shape.cylinder.m_radius); + C = (*b_it)->shape.cylinder.m_center; + break; + } + (*b_it)->LTransform().transform_tiny(C); + m_AVTransform.transform_tiny(C); + Fbox bb; + bb.set(C, C); + bb.grow(r); + BB.merge(bb); + } + } + } + break; + default: + BB = m_pEditObject->GetBox(); + } + EDevice.m_Camera.ZoomExtents(BB); + } +} + +bool CActorTools::Load(LPCSTR obj_name) +{ + xr_string full_name; + full_name = obj_name; + + VERIFY(m_bReady); + CEditableObject *O = xr_new(obj_name); + if (FS.exist(full_name.c_str()) && O->Load(full_name.c_str())) + { + xr_delete(m_pEditObject); + m_pEditObject = O; + /// m_pEditObject->Optimize (); + // delete visual + m_RenderObject.Clear(); + + MainForm->GetLeftBarForm()->SetRenderMode(false); + + UpdateProperties(); + return true; + } + else + { + ELog.DlgMsg(mtError, "Can't load object file '%s'.", obj_name); + } + xr_delete(O); + return false; +} + +bool CActorTools::Save(LPCSTR obj_name, bool bInternal) +{ + xr_string full_name; + full_name = obj_name; + VERIFY(m_bReady); + if (m_pEditObject) + { + EFS.MarkFile(full_name.c_str(), true); + if (m_pEditObject->Save(full_name.c_str())) + { + if (!bInternal) + m_bObjectModified = false; + return true; + } + } + return false; +} + +void CActorTools::Reload() +{ + VERIFY(m_bReady); + // visual part +} + +void CActorTools::OnDeviceCreate() +{ + if (m_pEditObject) + { + m_pEditObject->OnDeviceCreate(); + MakePreview(); + } +} + +void CActorTools::OnDeviceDestroy() +{ + if (m_pEditObject) + { + m_pEditObject->OnDeviceDestroy(); + m_RenderObject.DeleteVisual(); + } +} + +void CActorTools::Clear() +{ + PhysicsStopSimulate(); + inherited::Clear(); + m_CurrentMotion = ""; + m_CurrentSlot = 0; + // delete visuals + if (m_pEditObject) + m_pEditObject->DeletePhysicsShell(); + xr_delete(m_pEditObject); + m_RenderObject.Clear(); + // m_PreviewObject.Clear(); + m_ObjectItems->ClearList(); + m_Props->ClearProperties(); + + m_bObjectModified = false; + m_Flags.set(flUpdateGeometry | flUpdateMotionDefs | flUpdateMotionKeys | flReadOnlyMode, FALSE); + m_EditMode = emObject; + + UI->RedrawScene(); +} + +void CActorTools::OnShowHint(AStringVec &SS) +{ +} +extern xr_string MakeFullBoneName(CBone *bone); +bool CActorTools::MouseStart(TShiftState Shift) +{ + inherited::MouseStart(Shift); + switch (m_Action) + { + case etaSelect: + switch (MainForm->GetLeftBarForm()->GetPickMode()) + { + case 2: + { + CBone *B = m_pEditObject->PickBone(UI->m_CurrentRStart, UI->m_CurrentRDir, m_AVTransform); + bool bVal = B ? (Shift | ssAlt) ? false : ((Shift | ssCtrl) ? !B->Selected() : true) : false; + if (B) + SelectListItem(BONES_PREFIX, B ? MakeFullBoneName(B).c_str() : 0, bVal, (Shift | ssCtrl) || (Shift | ssAlt), true); + } + break; + case 1: + { + SRayPickInfo pinf; + float dis = UI->ZFar(); + Fmatrix iTransform; + iTransform.invert(m_AVTransform); + if (m_pEditObject->RayPick(dis, UI->m_CurrentRStart, UI->m_CurrentRDir, iTransform, &pinf)) + { + CSurface *surf = pinf.e_mesh->GetSurfaceByFaceID(pinf.inf.id); + xr_string s_name = xr_string("Surfaces\\") + xr_string(surf->_Name()); + m_ObjectItems->SelectItem(s_name.c_str()); + } + } + break; + } + + break; + case etaAdd: + break; + case etaMove: + break; + case etaRotate: + break; + } + return m_bHiddenMode; +} + +bool CActorTools::MouseEnd(TShiftState Shift) +{ + inherited::MouseEnd(Shift); + switch (m_Action) + { + case etaSelect: + break; + case etaAdd: + break; + case etaMove: + { + switch (m_EditMode) + { + case emObject: + if (Shift | ssCtrl) + OnMotionKeysModified(); + break; + + case emBone: + if (Shift | ssCtrl) + OnBoneModified(); + + if (Shift | ssAlt) + OnBoneModified(); + break; + } + } + break; + case etaRotate: + { + switch (m_EditMode) + { + case emObject: + if (Shift | ssCtrl) + OnMotionKeysModified(); + break; + + case emBone: + if (Shift | ssCtrl) + OnBoneModified(); + + if (Shift | ssAlt) + OnBoneModified(); + break; + } + } + break; + case etaScale: + { + switch (m_EditMode) + { + case emBone: + if (Shift | ssCtrl) + OnBoneModified(); + break; + } + } + break; + } + return true; +} + +void CActorTools::MouseMove(TShiftState Shift) +{ + inherited::MouseMove(Shift); + if (!m_pEditObject) + return; + + switch (m_Action) + { + case etaSelect: + break; + case etaAdd: + break; + case etaMove: + { + switch (m_EditMode) + { + case emObject: + if (true || Shift | ssCtrl) + m_pEditObject->a_vPosition.add(m_MovedAmount); + break; + + case emBone: + BoneVec lst; + if (m_pEditObject->GetSelectedBones(lst)) + { + if (Shift | ssCtrl) + { + for (BoneIt b_it = lst.begin(); b_it != lst.end(); ++b_it) + (*b_it)->ShapeMove(m_MovedAmount); + } + else if (Shift | ssAlt) + { + for (BoneIt b_it = lst.begin(); b_it != lst.end(); ++b_it) + (*b_it)->BindMove(m_MovedAmount); + + m_pEditObject->OnBindTransformChange(); + RefreshSubProperties(); + } + else + { + for (BoneIt b_it = lst.begin(); b_it != lst.end(); ++b_it) + (*b_it)->BoneMove(m_MovedAmount); + + RefreshSubProperties(); + } + } + break; + } + } + break; + case etaRotate: + { + switch (m_EditMode) + { + case emObject: + if (Shift | ssCtrl) + m_pEditObject->a_vRotate.mad(m_RotateVector, m_RotateAmount); + break; + + case emBone: + { + BoneVec lst; + Fvector rot; + rot.mul(m_RotateVector, m_RotateAmount); + if (m_pEditObject->GetSelectedBones(lst)) + { + if (Shift | ssCtrl) + { + for (BoneIt b_it = lst.begin(); b_it != lst.end(); ++b_it) + (*b_it)->ShapeRotate(rot); + } + else if (Shift | ssAlt) + { + for (BoneIt b_it = lst.begin(); b_it != lst.end(); ++b_it) + (*b_it)->BindRotate(rot); + + m_pEditObject->OnBindTransformChange(); + RefreshSubProperties(); + } + else + { + for (BoneIt b_it = lst.begin(); b_it != lst.end(); ++b_it) + (*b_it)->BoneRotate(m_RotateVector, m_RotateAmount); + + RefreshSubProperties(); + } + } + } + break; + } + } + break; + case etaScale: + { + switch (m_EditMode) + { + case emBone: + if (Shift | ssCtrl) + { + BoneVec lst; + if (m_pEditObject->GetSelectedBones(lst)) + for (BoneIt b_it = lst.begin(); b_it != lst.end(); ++b_it) + (*b_it)->ShapeScale(m_ScaleAmount); + } + break; + } + } + break; + } +} + +bool CActorTools::Pick(TShiftState Shift) +{ + return false; +} + +bool CActorTools::RayPick(const Fvector &start, const Fvector &dir, float &dist, Fvector *pt, Fvector *n) +{ + if (m_PreviewObject.m_pObject) + { + SRayPickInfo pinf; + if (m_PreviewObject.m_pObject->RayPick(dist, start, dir, Fidentity, &pinf)) + { + if (pt) + pt->set(pinf.pt); + if (n) + { + const Fvector *PT[3]; + pinf.e_mesh->GetFacePT(pinf.inf.id, PT); + n->mknormal(*PT[0], *PT[1], *PT[2]); + } + return true; + } + else + return false; + } + else + { + Fvector np; + np.mad(start, dir, dist); + if ((start.y > 0) && (np.y < 0.f)) + { + if (pt) + pt->set(start); + if (n) + n->set(0.f, 1.f, 0.f); + return true; + } + else + return false; + } +} + +void CActorTools::GetStatTime(float &a, float &b, float &c) +{ + if (m_RenderObject.IsRenderable() && MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine && m_RenderObject.m_pBlend) + { + a = 0; + b = m_RenderObject.m_pBlend->timeTotal / m_RenderObject.m_pBlend->speed; + c = m_RenderObject.m_pBlend->timeCurrent / m_RenderObject.m_pBlend->speed; + if (c > b) + { + int cnt = iFloor(c / b); + c -= (cnt * b); + } + } + else + { + if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Editor && m_pEditObject && m_pEditObject->GetActiveSMotion()) + { + SAnimParams &P = m_pEditObject->m_SMParam; + a = P.min_t; + b = P.max_t; + c = P.t_current; + } + else + { + a = 0; + b = 0; + c = 0; + } + } +} + +bool CActorTools::IsEngineMode() +{ + + return MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine; +} + +void CActorTools::SelectPreviewObject(bool bClear) +{ + if (bClear) + { + m_PreviewObject.Clear(); + return; + } + m_PreviewObject.SelectObject(); +} + +void CActorTools::SetPreviewObjectPrefs() +{ + m_PreviewObject.SetPreferences(); +} + +void CActorTools::OnObjectModified(void) +{ + m_Flags.set(flUpdateGeometry, TRUE); + OnGeometryModified(); +} + +void CActorTools::ShowClipMaker() +{ +} + +bool CActorTools::Import(LPCSTR initial, LPCSTR obj_name) +{ + string_path full_name; + if (initial) + FS.update_path(full_name, initial, obj_name); + else + strcpy(full_name, obj_name); + + VERIFY(m_bReady); + CEditableObject *O = xr_new(obj_name); + if (O->Load(full_name)) + { + O->m_objectFlags.set(CEditableObject::eoDynamic, TRUE); + O->m_objectFlags.set(CEditableObject::eoProgressive, TRUE); + xr_delete(m_pEditObject); + m_pEditObject = O; + // delete visual + m_RenderObject.Clear(); + MainForm->GetLeftBarForm()->SetRenderMode(false); + + UpdateProperties(); + return true; + } + else + { + ELog.DlgMsg(mtError, "Can't load object file '%s'.", obj_name); + } + xr_delete(O); + + return false; +} + +bool CActorTools::ExportOGF(LPCSTR name) +{ + VERIFY(m_bReady); + if (m_pEditObject && m_pEditObject->ExportOGF(name, 4)) + return true; + return false; +} + +bool CActorTools::ExportOMF(LPCSTR name) +{ + VERIFY(m_bReady); + if (m_pEditObject && m_pEditObject->ExportOMF(name)) + return true; + return false; +} + +bool CActorTools::ExportOBJ(LPCSTR name) +{ + VERIFY(m_bReady); + if (m_pEditObject && m_pEditObject->ExportOBJ(name)) + return true; + return false; +} + +bool CActorTools::ExportCPP(LPCSTR name) +{ + if (m_pEditObject) + { + EditMeshVec &meshes = m_pEditObject->Meshes(); + string128 tmp; + IWriter *W = FS.w_open(name); + + for (EditMeshIt m_it = meshes.begin(); m_it != meshes.end(); m_it++) + { + CEditableMesh *mesh = *m_it; + const st_Face *faces = mesh->GetFaces(); + const Fvector *verts = mesh->GetVertices(); + sprintf(tmp, "MESH %s {", mesh->Name().c_str()); + W->w_string(tmp); + sprintf(tmp, "\tVERTEX_COUNT %d", mesh->GetVCount()); + W->w_string(tmp); + sprintf(tmp, "\tFACE_COUNT %d", mesh->GetFCount()); + W->w_string(tmp); + W->w_string("\tconst Fvector vertices[VERTEX_COUNT] = {"); + for (u32 v_id = 0; v_id < mesh->GetVCount(); v_id++) + { + sprintf(tmp, "\t\t{% 3.6f,\t% 3.6f,\t% 3.6f},", VPUSH(verts[v_id])); + W->w_string(tmp); + } + W->w_string("\t}"); + W->w_string("\tconst u16 faces[FACE_COUNT*3] = {"); + for (u32 f_id = 0; f_id < mesh->GetFCount(); f_id++) + { + sprintf(tmp, "\t\t%-d,\t\t%-d,\t\t%-d,", faces[f_id].pv[0].pindex, faces[f_id].pv[1].pindex, faces[f_id].pv[2].pindex); + W->w_string(tmp); + } + W->w_string("\t}"); + W->w_string("}"); + } + FS.w_close(W); + return true; + } + return false; +} + +#include "../xrECore/Editor/EDetailModel.h" +bool CActorTools::ExportDM(LPCSTR name) +{ + VERIFY(m_bReady); + if (m_pEditObject) + { + EDetail DM; + if (!DM.Update(m_pEditObject->GetName())) + return false; + DM.Export(name); + return true; + } + return false; +} + +void CActorTools::WorldMotionRotate(const Fvector &R) +{ + R_ASSERT(m_pEditObject && (!m_CurrentMotion.empty())); + CSMotion *M = m_pEditObject->FindSMotionByName(m_CurrentMotion.c_str()); + int rootId = m_pEditObject->GetRootBoneID(); + M->WorldRotate(rootId, R.y, R.x, R.z); + OnMotionKeysModified(); +} + +void CActorTools::SetCurrentMotion(LPCSTR name, u16 slot) +{ + if (m_pEditObject) + { + if ((m_CurrentMotion != name) || (m_CurrentSlot != slot)) + { + m_CurrentMotion = name; + m_CurrentSlot = slot; + CSMotion *M = m_pEditObject->FindSMotionByName(name); + if (M) + { + m_pEditObject->SetActiveSMotion(M); + } + PlayMotion(); + } + } +} + +CSMotion *CActorTools::GetCurrentMotion() +{ + return m_pEditObject ? m_pEditObject->FindSMotionByName(m_CurrentMotion.c_str()) : 0; +} + +CSMotion *CActorTools::FindMotion(LPCSTR name) +{ + return m_pEditObject ? m_pEditObject->FindSMotionByName(name) : 0; +} + +LPCSTR CActorTools::ExtractMotionName(LPCSTR full_name, LPCSTR prefix) +{ + LPCSTR _templ = "\\Slot "; + if (0 == strstr(full_name, _templ)) + return full_name + xr_strlen(prefix) + 1; + else + { + LPCSTR mot_nm = strstr(full_name, _templ); + mot_nm += xr_strlen(_templ); + while (isdigit(*mot_nm)) + { + ++mot_nm; + } + return mot_nm + 1; + } + // return full_name + xr_strlen(prefix) + 1 + xr_strlen(_templ) + 1; +} + +u16 CActorTools::ExtractMotionSlot(LPCSTR full_name, LPCSTR prefix) +{ + LPCSTR _templ = "\\Slot "; + u16 slot = 0; + LPCSTR slot_nm = strstr(full_name, _templ); + if (0 != slot_nm) + { + string16 tmp; + slot_nm += xr_strlen(_templ); + u32 ii = 0; + while (isdigit(*slot_nm)) + { + tmp[ii] = slot_nm[0]; + ++slot_nm; + ++ii; + } + tmp[ii] = 0; + slot = u16(atoi(tmp) - 1); + } + return slot; +} + +xr_string CActorTools::BuildMotionPref(u16 slot, LPCSTR prefix) +{ + VERIFY(slot < MAX_ANIM_SLOT); + string32 slot_nm; + sprintf(slot_nm, "Slot %1d", slot + 1); + return PrepareKey(prefix, slot_nm).c_str(); +} + +void CActorTools::OptimizeMotions() +{ + if (m_pEditObject) + { + m_pEditObject->OptimizeSMotions(); + Modified(); + UndoSave(); + } +} + +void CActorTools::RealMakeThumbnail() +{ + if (CurrentObject()) + { + CEditableObject *obj = CurrentObject(); + xr_string tex_name, obj_name; + tex_name = ChangeFileExt(obj->GetName(), ".thm"); + obj_name = ChangeFileExt(obj->GetName(), ".object"); + FS_File F; + string_path fname; + //. FS.update_path(fname,_objects_,obj_name.c_str()); + //. R_ASSERT (FS.file_find(fname,F)); + R_ASSERT(FS.file_find(obj_name.c_str(), F)); + + if (ImageLib.CreateOBJThumbnail(tex_name.c_str(), obj, F.time_write)) + { + ELog.Msg(mtInformation, "Thumbnail successfully created."); + } + else + { + ELog.Msg(mtError, "Making thumbnail failed."); + } + } + else + { + ELog.DlgMsg(mtError, "Can't create thumbnail. Empty scene."); + } +} + +void CActorTools::RealGenerateLOD(bool hq) +{ + if (m_pEditObject) + { + bool engine_render = MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine; + MainForm->GetLeftBarForm()->SetRenderMode(false); + CEditableObject *O = m_pEditObject; + + if (O && O->IsMUStatic()) + { + BOOL bLod = O->m_objectFlags.is(CEditableObject::eoUsingLOD); + O->m_objectFlags.set(CEditableObject::eoUsingLOD, FALSE); + xr_string tex_name; + tex_name = EFS.ChangeFileExt(O->GetName(), ""); + + string_path fname; + FS.update_path(fname, _objects_, ""); + + if (tex_name.find(fname) == 0) + { + tex_name.erase(0, xr_strlen(fname)); + } + + string_path tmp; + strcpy(tmp, tex_name.c_str()); + _ChangeSymbol(tmp, '\\', '_'); + _ChangeSymbol(tmp, ':', '_'); + tex_name = xr_string("lod_") + tmp; + tex_name = ImageLib.UpdateFileName(tex_name); + ImageLib.CreateLODTexture(O, tex_name.c_str(), LOD_IMAGE_SIZE, LOD_IMAGE_SIZE, LOD_SAMPLE_COUNT, O->Version(), hq ? 4 /*7*/ : 1); + O->OnDeviceDestroy(); + O->m_objectFlags.set(CEditableObject::eoUsingLOD, bLod); + ELog.Msg(mtInformation, "LOD for object '%s' successfully created.", O->GetName()); + } + else + { + ELog.Msg(mtError, "Can't create LOD texture from non 'Multiple Usage' object.", O->GetName()); + } + MainForm->GetLeftBarForm()->SetRenderMode(engine_render); + } +} + +bool CActorTools::BatchConvert(LPCSTR fn) +{ + bool bRes = true; + CInifile *ini = CInifile::Create(fn); + VERIFY(ini); + if (ini->section_exist("ogf")) + { + CInifile::Sect § = ini->r_section("ogf"); + Msg("Start converting %d items...", sect.Data.size()); + for (auto it = sect.Data.begin(); it != sect.Data.end(); it++) + { + string_path src_name; + string_path tgt_name; + FS.update_path(src_name, _objects_, it->first.c_str()); + FS.update_path(tgt_name, _game_meshes_, it->second.c_str()); + strcpy(src_name, EFS.ChangeFileExt(src_name, ".object").c_str()); + strcpy(tgt_name, EFS.ChangeFileExt(tgt_name, ".ogf").c_str()); + if (FS.exist(src_name)) + { + Msg(".Converting '%s' <-> '%s'", it->first.c_str(), it->second.c_str()); + CEditableObject *O = xr_new("convert"); + BOOL res = O->Load(src_name); + if (res) + res = O->ExportOGF(tgt_name, 4); + Log(res ? ".OK" : "!.FAILED"); + xr_delete(O); + } + else + { + Log("!Invalid source file name:", it->first.c_str()); + bRes = false; + } + if (UI->NeedAbort()) + break; + } + } + if (ini->section_exist("omf")) + { + CInifile::Sect § = ini->r_section("omf"); + Msg("Start converting %d items...", sect.Data.size()); + for (auto it = sect.Data.begin(); it != sect.Data.end(); ++it) + { + string_path src_name; + string_path tgt_name; + FS.update_path(src_name, _objects_, it->first.c_str()); + FS.update_path(tgt_name, _game_meshes_, it->second.c_str()); + strcpy(src_name, EFS.ChangeFileExt(src_name, ".object").c_str()); + strcpy(tgt_name, EFS.ChangeFileExt(tgt_name, ".omf").c_str()); + if (FS.exist(src_name)) + { + Msg(".Converting '%s' <-> '%s'", it->first.c_str(), it->second.c_str()); + CEditableObject *O = xr_new("convert"); + BOOL res = O->Load(src_name); + if (res) + res = O->ExportOMF(tgt_name); + Log(res ? ".OK" : "!.FAILED"); + xr_delete(O); + } + else + { + Log("!Invalid source file name:", it->first.c_str()); + bRes = false; + } + if (UI->NeedAbort()) + break; + } + } + return bRes; +} + +void CActorTools::PhysicsSimulate() +{ + if (!m_pEditObject) + return; + m_IsPhysics = true; + CreatePhysicsWorld(); + if (MainForm->GetLeftBarForm()->GetRenderMode() != UILeftBarForm::Render_Editor) + m_RenderObject.CreatePhysicsShell(&m_AVTransform); + else + m_pEditObject->CreatePhysicsShell(&m_AVTransform); +} + +void CActorTools::PhysicsStopSimulate() +{ + if (m_IsPhysics) + { + m_IsPhysics = false; + m_RenderObject.DeletePhysicsShell(); + m_pEditObject->DeletePhysicsShell(); + DestroyPhysicsWorld(); + } +} + +CObjectSpace *os = 0; +void CActorTools::CreatePhysicsWorld() +{ + VERIFY(!os); + VERIFY(!physics_world()); + + #pragma TODO("check why it was here") + //set_mtl_lib(&GMLib); + + os = create_object_space(); + create_physics_world(false, os, 0); +} + +void CActorTools::DestroyPhysicsWorld() +{ + if (physics_world()) + destroy_physics_world(); + destroy_object_space(os); +} + +bool CActorTools::GetSelectionPosition(Fmatrix &result) +{ + result = m_AVTransform; + return true; +} + +void PreviewModel::OnCreate() +{ +} + +void PreviewModel::OnDestroy() +{ +} + +void PreviewModel::Clear() +{ +} + +void PreviewModel::SelectObject() +{ +} + +void PreviewModel::SetPreferences() +{ +} + +void PreviewModel::Render() +{ +} + +void PreviewModel::Update() +{ +} + +void CActorTools::PrepareLighting() +{ + // add directional light + Flight L; + ZeroMemory(&L, sizeof(Flight)); + L.type = Flight::Type::Directional; + + L.diffuse.set(1, 1, 1, 1); + L.direction.set(1, -1, 1); + L.direction.normalize(); + EDevice.SetLight(0, L); + EDevice.LightEnable(0, true); + + L.diffuse.set(0.2, 0.2, 0.2, 1); + L.direction.set(-1, -1, -1); + L.direction.normalize(); + EDevice.SetLight(1, L); + EDevice.LightEnable(1, true); + + L.diffuse.set(0.2, 0.2, 0.2, 1); + L.direction.set(1, -1, -1); + L.direction.normalize(); + EDevice.SetLight(2, L); + EDevice.LightEnable(2, true); + + L.diffuse.set(0.2, 0.2, 0.2, 1); + L.direction.set(-1, -1, 1); + L.direction.normalize(); + EDevice.SetLight(3, L); + EDevice.LightEnable(3, true); + + L.diffuse.set(1.0, 0.4, 0.3, 1); + L.direction.set(0, 1, 0); + L.direction.normalize(); + EDevice.SetLight(4, L); + EDevice.LightEnable(4, true); + + L.diffuse.set(0.3, 1.0, 0.4, 1); + L.direction.set(-1, -1, -1); + L.direction.normalize(); + EDevice.SetLight(5, L); + EDevice.LightEnable(5, true); +} diff --git a/src/editors/ActorEditor/UI_ActorTools.h b/src/editors/ActorEditor/UI_ActorTools.h new file mode 100644 index 00000000000..6ddf566a786 --- /dev/null +++ b/src/editors/ActorEditor/UI_ActorTools.h @@ -0,0 +1,391 @@ +#pragma once +#include "include/xrRender/animation_motion.h" +#include "xrCommon/xr_deque.h" + +// refs +class UIPropertiesForm; +class CEditableObject; +class PropValue; +class CBlend; +class CMotionDef; +class CMotion; + +enum EEditMode +{ + emObject, + emMotion, + emBone, + emSurface, + emMesh +}; + +// refs +class CSMotion; +static Fmatrix xform = Fidentity; +class EngineModel : public CPhysicsShellHolderEditorBase +{ + CMemoryWriter m_GeometryStream; + CMemoryWriter m_MotionKeysStream; + CMemoryWriter m_MotionDefsStream; + bool UpdateGeometryStream(CEditableObject *source); + bool UpdateMotionKeysStream(CEditableObject *source); + bool UpdateMotionDefsStream(CEditableObject *source); + +public: + float m_fLOD; + IRenderVisual *m_pVisual; + + // Fmatrix m_pobject_matrix; + CBlend *m_pBlend; + struct BPPlayItem + { + xr_string name; + u16 slot; + }; + BPPlayItem m_BPPlayItems[4]; + +public: + EngineModel() + { + m_pVisual = 0; + m_fLOD = 1.f; + m_pBlend = 0; /* m_pobject_matrix = Fidentity;*/ + } + + void DeleteVisual(); + + void Clear() + { + DeletePhysicsShell(); + DeleteVisual(); + m_GeometryStream.clear(); + m_MotionKeysStream.clear(); + m_MotionDefsStream.clear(); + } + bool UpdateVisual(CEditableObject *source, bool bUpdGeom, bool bUpdKeys, bool bUpdDefs); + bool IsRenderable() { return !!m_pVisual; } + void PlayMotion(LPCSTR name, u16 slot); + /* void RestoreParams (TFormStorage* s); + void SaveParams (TFormStorage* s);*/ + void OnRender(); + //. void PlayCycle (LPCSTR name, int part, u16 slot); + //. void PlayFX (LPCSTR name, float power, u16 slot); + void StopAnimation(); + void FillMotionList(LPCSTR pref, ListItemsVec &items, int modeID); + MotionID FindMotionID(LPCSTR name, u16 slot); + CMotionDef *FindMotionDef(LPCSTR name, u16 slot); + CMotion *FindMotionKeys(LPCSTR name, u16 slot); + + IGameObject* IObject() override { R_ASSERT(false); return nullptr; } + bool IsCollideWithBullets() override { R_ASSERT(false); return false; } + bool IsCollideWithActorCamera() { R_ASSERT(false); return false; } + +private: + // virtual Fmatrix& ObjectXFORM () { return m_pobject_matrix; } + // virtual Fvector& ObjectPosition () { return m_pobject_matrix.c; } + // virtual IRenderVisual* ObjectVisual () { return m_pVisual;} + virtual IKinematics *ObjectKinematics() + { + if (!m_pVisual) + return 0; + return m_pVisual->dcast_PKinematics(); + } +}; + +class PreviewModel +{ + UIPropertiesForm *m_Props; + float m_fSpeed; + float m_fSegment; + Flags32 m_Flags; + Fvector m_vPosition; + xr_string m_LastObjectName; + +public: + CEditableObject *m_pObject; + +public: + enum + { + pmScroll = (1 << 0), + force_dword = u32(-1) + }; + enum EScrollAxis + { + saZp, + saZn, + saXp, + saXn, + saforceDWORD = u32(-1) + }; + EScrollAxis m_ScrollAxis; + +public: + PreviewModel() + { + m_pObject = 0; + m_fSpeed = 5.f; + m_fSegment = 50.f; + m_Flags.zero(); + m_Props = 0; + m_vPosition.set(0, 0, 0); + m_ScrollAxis = saZp; + } + void OnCreate(); + void OnDestroy(); + void Clear(); + void SelectObject(); + void SetPreferences(); + void Render(); + void Update(); + /* void RestoreParams (TFormStorage* s); + void SaveParams (TFormStorage* s);*/ +}; + +class CActorTools : public CToolCustom +{ + typedef CToolCustom inherited; + + bool m_ChooseSkeletonBones; + + Fmatrix m_AVTransform; + CEditableObject *m_pEditObject; + u32 m_pEditObjectType; + bool m_bObjectModified; + shared_str m_tmp_mot_refs; + EEditMode m_EditMode; + xr_string m_CurrentMotion; + u16 m_CurrentSlot; + + RTokenVec m_BoneParts; + + void OnMotionTypeChange(PropValue *sender); + + void OnChangeTransform(PropValue *sender); + void OnMotionNameChange(PropValue *sender); + + void OnBoxAxisClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnCylinderAxisClick(ButtonValue *sender, bool &bModif, bool &bSafe); + + void OnMotionEditClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnMotionControlClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnExportImportRefsClick(ButtonValue *sender, bool &bModif, bool &bSafe); + + void OnMarksControlClick12(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnMarksControlClick34(ButtonValue *sender, bool &bModif, bool &bSafe); + + void OnObjectItemsFocused(xr_vector &items); + + void OnBoneShapeClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnBoneCreateDeleteClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnBoneEditClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnBoneFileClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnBoneLimitsChange(PropValue *sender); + + void OnJointTypeChange(PropValue *sender); + void OnShapeTypeChange(PropValue *sender); + + void OnMotionRefsChange(PropValue *sender); + + void OnBindTransformChange(PropValue *V); + + void OnTypeChange(PropValue *V); + + void OnUsingLodFlagChange(PropValue *V); + + void OnMakeThumbnailClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnMakeLODClick(ButtonValue *sender, bool &bModif, bool &bSafe); + SMotionVec appended_motions; + +protected: + // flags + enum + { + flRefreshProps = (1 << 0), + flRefreshSubProps = (1 << 1), + flRefreshShaders = (1 << 2), + flUpdateGeometry = (1 << 3), + flUpdateMotionKeys = (1 << 4), + flUpdateMotionDefs = (1 << 5), + flReadOnlyMode = (1 << 6), + flMakeThumbnail = (1 << 7), + flGenerateLODLQ = (1 << 8), + flGenerateLODHQ = (1 << 9), + }; + Flags32 m_Flags; + + void RefreshSubProperties() { m_Flags.set(flRefreshSubProps, TRUE); } + void RefreshShaders() { m_Flags.set(flRefreshShaders, TRUE); } + void MakeThumbnail() { m_Flags.set(flMakeThumbnail, TRUE); } + void GenerateLOD(bool hq) { m_Flags.set(hq ? flGenerateLODHQ : flGenerateLODLQ, TRUE); } + // void PMMotionItemClick (TObject *Sender); + + void RealUpdateProperties(); + + void PrepareLighting(); + +public: + EngineModel m_RenderObject; + PreviewModel m_PreviewObject; + + UIPropertiesForm *m_Props; + UIItemListForm *m_ObjectItems; + + // undo part +protected: +#pragma pack(push, 1) + struct UndoItem + { + char m_FileName[MAX_PATH]; + }; +#pragma pack(pop) + xr_deque m_UndoStack; + xr_deque m_RedoStack; + +public: + void UndoClear(); + void UndoSave(); + bool Undo(); + bool Redo(); + +public: + CActorTools(); + virtual ~CActorTools(); + + virtual void Render(); + virtual void RenderEnvironment(); + virtual void OnFrame(); + + virtual bool OnCreate(); + virtual void OnDestroy(); + + ICF bool ReadOnly() { return m_Flags.is(flReadOnlyMode); } + + virtual bool IfModified(); + virtual bool IsModified() { return m_bObjectModified; } + virtual void Modified(); + void OnItemModified(void); + + virtual LPCSTR GetInfo(); + + virtual void ZoomObject(BOOL bSelOnly); + + virtual bool Load(LPCSTR name); + virtual bool Save(LPCSTR name, bool bInternal = false); + virtual void Reload(); + + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + + virtual void Clear(); + + virtual void OnShowHint(AStringVec &SS); + + virtual bool MouseStart(TShiftState Shift); + virtual bool MouseEnd(TShiftState Shift); + virtual void MouseMove(TShiftState Shift); + + virtual bool Pick(TShiftState Shift); + virtual bool RayPick(const Fvector &start, const Fvector &dir, float &dist, Fvector *pt, Fvector *n); + + virtual void ShowProperties(LPCSTR focused_item) { ; } + virtual void UpdateProperties(BOOL bForced = FALSE) + { + m_Flags.set(flRefreshProps, TRUE); + if (bForced) + RealUpdateProperties(); + } + virtual void RefreshProperties() { ; } + + void GetStatTime(float &a, float &b, float &c); + + bool IsEngineMode(); + void SelectPreviewObject(bool bClear); + void SetPreviewObjectPrefs(); + + void SelectListItem(LPCSTR pref, LPCSTR name, bool bVal, bool bLeaveSel, bool bExpand); + + void ShowClipMaker(); + bool Import(LPCSTR path, LPCSTR name); + bool ExportOBJ(LPCSTR name); + bool ExportOGF(LPCSTR name); + bool ExportOMF(LPCSTR name); + bool ExportDM(LPCSTR name); + bool ExportCPP(LPCSTR name); + bool SaveMotions(LPCSTR name, bool bSelOnly); + bool AppendMotion(LPCSTR fn); + bool RemoveMotion(LPCSTR name); + void WorldMotionRotate(const Fvector &R); + void MakePreview(); + + bool OnBoneNameAfterEdit(PropValue *sender, shared_str &edit_val); + void OnBoneNameChangeEvent(PropValue *sender); + + void OnBoneModified(void); + void OnObjectModified(void); + void OnMotionDefsModified(void); + void OnMotionKeysModified(void); + void OnGeometryModified(void); + + bool IsVisualPresent() { return m_RenderObject.IsRenderable(); } + + CEditableObject *CurrentObject() { return m_pEditObject; } + void SetCurrentMotion(LPCSTR name, u16 slot); + CSMotion *GetCurrentMotion(); + CSMotion *FindMotion(LPCSTR name); + LPCSTR ExtractMotionName(LPCSTR full_name, LPCSTR prefix = MOTIONS_PREFIX); + u16 ExtractMotionSlot(LPCSTR full_name, LPCSTR prefix = MOTIONS_PREFIX); + xr_string BuildMotionPref(u16 slot, LPCSTR prefix = MOTIONS_PREFIX); + void FillObjectProperties(PropItemVec &items, LPCSTR pref, ListItem *sender); + void FillSurfaceProperties(PropItemVec &items, LPCSTR pref, ListItem *sender); + void FillMotionProperties(PropItemVec &items, LPCSTR pref, ListItem *sender); + void FillBoneProperties(PropItemVec &items, LPCSTR pref, ListItem *sender); + void PlayMotion(); + void StopMotion(); + void PauseMotion(); + bool RenameMotion(LPCSTR old_name, LPCSTR new_name); + void RemoveMarksChannel(bool b12); + void AddMarksChannel(bool b12); + void OptimizeMotions(); + void RealMakeThumbnail(); + void RealGenerateLOD(bool hq); + bool BatchConvert(LPCSTR fn); + + void PhysicsSimulate(); + void PhysicsStopSimulate(); + void CreatePhysicsWorld(); + void DestroyPhysicsWorld(); + + virtual bool GetSelectionPosition(Fmatrix &result); + + // commands + CCommandVar CommandClear(CCommandVar p1, CCommandVar p2); + CCommandVar CommandLoad(CCommandVar p1, CCommandVar p2); + CCommandVar CommandSaveBackup(CCommandVar p1, CCommandVar p2); + CCommandVar CommandSave(CCommandVar p1, CCommandVar p2); + CCommandVar CommandImport(CCommandVar p1, CCommandVar p2); + CCommandVar CommandExportDM(CCommandVar p1, CCommandVar p2); + CCommandVar CommandExportOBJ(CCommandVar p1, CCommandVar p2); + CCommandVar CommandExportOGF(CCommandVar p1, CCommandVar p2); + CCommandVar CommandExportOMF(CCommandVar p1, CCommandVar p2); + CCommandVar CommandExportCPP(CCommandVar p1, CCommandVar p2); + CCommandVar CommandUndo(CCommandVar p1, CCommandVar p2); + CCommandVar CommandRedo(CCommandVar p1, CCommandVar p2); + CCommandVar CommandOptimizeMotions(CCommandVar p1, CCommandVar p2); + CCommandVar CommandMakeThumbnail(CCommandVar p1, CCommandVar p2); + CCommandVar CommandBatchConvert(CCommandVar p1, CCommandVar p2); + +public: + void OnDrawUI(); + inline bool IsPhysics() const { return m_IsPhysics; } + +private: + bool m_IsPhysics; +}; + +extern CActorTools *ATools; + +#define SURFACES_PREFIX "Surfaces" +#define BONES_PREFIX "Bones" +#define MOTIONS_PREFIX "Motions" +#define OBJECT_PREFIX "Object" diff --git a/src/editors/ActorEditor/UI_ActorToolsMotions.cpp b/src/editors/ActorEditor/UI_ActorToolsMotions.cpp new file mode 100644 index 00000000000..dfc75eb8ec0 --- /dev/null +++ b/src/editors/ActorEditor/UI_ActorToolsMotions.cpp @@ -0,0 +1,513 @@ +#include "stdafx.h" +#include "UI_ActorTools.h" +#include "../xrECore/Editor/UI_Main.h" +#include "../xrECore/Editor/EditObject.h" +#include "xrCore/Animation/motion.hpp" +#include "xrCore/Animation/bone.hpp" +#include "Layers/xrRender/SkeletonAnimated.h" +#include "../../xrphysics/physicsshell.h" + +MotionID EngineModel::FindMotionID(LPCSTR name, u16 slot) +{ + MotionID M; + CKinematicsAnimated *VA = PKinematicsAnimated(m_pVisual); + if (VA) + M = VA->ID_Motion(name, slot); + return M; +} + +CMotionDef *EngineModel::FindMotionDef(LPCSTR name, u16 slot) +{ + CKinematicsAnimated *VA = PKinematicsAnimated(m_pVisual); + if (VA) + { + MotionID M = FindMotionID(name, slot); + if (M.valid()) + return VA->LL_GetMotionDef(M); + } + return 0; +} + +CMotion *EngineModel::FindMotionKeys(LPCSTR name, u16 slot) +{ + CKinematicsAnimated *VA = PKinematicsAnimated(m_pVisual); + if (VA) + { + MotionID M = FindMotionID(name, slot); + if (M.valid()) + return VA->LL_GetMotion(M, VA->LL_GetBoneRoot()); + } + return 0; +} + +void EngineModel::FillMotionList(LPCSTR pref, ListItemsVec &items, int modeID) +{ + LHelper().CreateItem(items, pref, modeID, 0); + if (IsRenderable() && MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine) + { + CKinematicsAnimated *SA = PKinematicsAnimated(m_pVisual); + if (SA) + { + for (int k = SA->m_Motions.size() - 1; k >= 0; --k) + { + xr_string slot_pref = ATools->BuildMotionPref((u16)k, pref); + LHelper().CreateItem(items, slot_pref.c_str(), modeID, ListItem::flSorted); + // cycles + accel_map::const_iterator I, E; + I = SA->m_Motions[k].motions.cycle()->begin(); + E = SA->m_Motions[k].motions.cycle()->end(); + for (; I != E; ++I) + { + shared_str tmp = PrepareKey(slot_pref.c_str(), *(*I).first); + + #pragma TODO("TSMP: Seems that here is error with MotionID object lifetime") + MotionID id((u16)k, I->second); + LHelper().CreateItem(items, tmp.c_str(), modeID, 0, &id); + } + // fxs + I = SA->m_Motions[k].motions.fx()->begin(); + E = SA->m_Motions[k].motions.fx()->end(); + for (; I != E; ++I) + { + shared_str tmp = PrepareKey(slot_pref.c_str(), *(*I).first); + MotionID id((u16)k, I->second); + LHelper().CreateItem(items, tmp.c_str(), modeID, 0, &id); + } + } + } + } +} +/* +void EngineModel::PlayCycle(LPCSTR name, int part, u16 slot) +{ + MotionID D = PKinematicsAnimated(m_pVisual)->ID_Motion(name,slot); + if (D.valid()) + PKinematicsAnimated(m_pVisual)->LL_PlayCycle((u16)part,D,TRUE,0,0); +} + +void EngineModel::PlayFX(LPCSTR name, float power, u16 slot) +{ + MotionID D = PKinematicsAnimated(m_pVisual)->ID_Motion(name,slot); + if (D.valid()) + PKinematicsAnimated(m_pVisual)->PlayFX(D,power); +} +*/ + +void EngineModel::StopAnimation() +{ + if (m_pVisual && PKinematicsAnimated(m_pVisual)) + { + PKinematicsAnimated(m_pVisual)->LL_CloseCycle(0); + PKinematicsAnimated(m_pVisual)->LL_CloseCycle(1); + PKinematicsAnimated(m_pVisual)->LL_CloseCycle(2); + PKinematicsAnimated(m_pVisual)->LL_CloseCycle(3); + } +} + +bool EngineModel::UpdateGeometryStream(CEditableObject *source) +{ + m_GeometryStream.clear(); + if (!source) + return false; + if (source->IsSkeleton()) + return (source->PrepareSVGeometry(m_GeometryStream, 4)); + else + return (source->PrepareOGF(m_GeometryStream, 4, true, NULL)); +} + +bool EngineModel::UpdateMotionDefsStream(CEditableObject *source) +{ + m_MotionDefsStream.clear(); + return (source && source->PrepareSVDefs(m_MotionDefsStream)); +} + +bool EngineModel::UpdateMotionKeysStream(CEditableObject *source) +{ + m_MotionKeysStream.clear(); + return (source && source->PrepareSVKeys(m_MotionKeysStream)); +} + +bool EngineModel::UpdateVisual(CEditableObject *source, bool bUpdGeom, bool bUpdKeys, bool bUpdDefs) +{ + bool bRes = true; + CMemoryWriter F; + destroy_physics_shell(m_physics_shell); + if (source->IsSkeleton()) + { + if (bUpdGeom) + bRes = UpdateGeometryStream(source); + if (!bRes || !m_GeometryStream.size()) + { + ELog.Msg(mtError, "Can't create preview geometry."); + return false; + } + F.w(m_GeometryStream.pointer(), m_GeometryStream.size()); + if (bUpdKeys) + UpdateMotionKeysStream(source); + if (bUpdDefs) + UpdateMotionDefsStream(source); + if (m_MotionKeysStream.size()) + F.w(m_MotionKeysStream.pointer(), m_MotionKeysStream.size()); + if (m_MotionDefsStream.size()) + F.w(m_MotionDefsStream.pointer(), m_MotionDefsStream.size()); + } + else + { + bool bRes = true; + if (bUpdGeom) + bRes = UpdateGeometryStream(source); + if (!bRes) + { + ELog.Msg(mtError, "Can't create preview geometry."); + return false; + } + if (!m_GeometryStream.size()) + return false; + F.w(m_GeometryStream.pointer(), m_GeometryStream.size()); + } + IReader R(F.pointer(), F.size()); + ::Render->model_Delete(m_pVisual, TRUE); + g_pMotionsContainer->clean(false); + m_pVisual = ::Render->model_Create(ChangeFileExt(source->GetName(), "").c_str(), &R); + m_pBlend = 0; + return bRes; +} + +//--------------------------------------------------------------------------- + +void EngineModel::PlayMotion(LPCSTR name, u16 slot) +{ + for (int k = 0; k < MAX_PARTS; k++) + m_BPPlayItems[k].name = ""; + + StopAnimation(); + + CKinematicsAnimated *SA = PKinematicsAnimated(m_pVisual); + if (IsRenderable() && SA) + { + MotionID motion_ID = FindMotionID(name, slot); + if (motion_ID.valid()) + { + CMotionDef *mdef = SA->LL_GetMotionDef(motion_ID); + VERIFY(mdef); + if (mdef->flags & esmFX) + { + for (int k = 0; k < MAX_PARTS; k++) + { + if (!m_BPPlayItems[k].name.empty()) + { + MotionID D = SA->ID_Motion(m_BPPlayItems[k].name.c_str(), m_BPPlayItems[k].slot); + if (D.valid()) + SA->LL_PlayCycle((u16)k, D, false, 0, 0); + } + } + m_pBlend = SA->PlayFX(motion_ID, 1.f); + } + else + { + u16 idx = mdef->bone_or_part; + R_ASSERT((idx == BI_NONE) || (idx < MAX_PARTS)); + if (BI_NONE == idx) + { + for (int k = 0; k < MAX_PARTS; k++) + { + m_BPPlayItems[k].name = name; + m_BPPlayItems[k].slot = slot; + } + } + else + { + m_BPPlayItems[idx].name = name; + m_BPPlayItems[idx].slot = slot; + } + m_pBlend = 0; + + for (int k = 0; k < MAX_PARTS; k++) + { + if (!m_BPPlayItems[k].name.empty()) + { + MotionID D = SA->ID_Motion(m_BPPlayItems[k].name.c_str(), m_BPPlayItems[k].slot); + CBlend *B = 0; + if (D.valid()) + { + B = SA->LL_PlayCycle((u16)k, D, false, 0, 0); + if (B && (idx == k || idx == BI_NONE)) + m_pBlend = B; + } + } + } + } + } + } + /* + if (M&&IsRenderable()){ + if (M->flags&esmFX){ + for (int k=0; kID_Cycle_Safe(m_BPPlayCache[k].c_str()); + if (D) D->PlayCycle(PSkeletonAnimated(m_pVisual),k,false,0,0); + } + } + m_pBlend = PSkeletonAnimated(m_pVisual)->PlayFX(M->Name(),1.f); + }else{ + R_ASSERT((M->m_BoneOrPart==BI_NONE)||(M->m_BoneOrPartm_BoneOrPart; + if (BI_NONE==idx)for (int k=0; kName(); + else m_BPPlayCache[idx] = M->Name(); + m_pBlend = 0; + + for (int k=0; kID_Cycle_Safe(m_BPPlayCache[k].c_str()); + CBlend* B=0; + if (D){ + B = D->PlayCycle(PSkeletonAnimated(m_pVisual),k,(idx==k)?!(D->flags&esmNoMix):FALSE,0,0); + if (idx==k) m_pBlend = B; + } + } + } + } + } + */ +} /* + void EngineModel::RestoreParams(TFormStorage* s) + { + for (u16 k=0; kReadString("bp_cache_name_"+AnsiString(k),""); + m_BPPlayItems[k].slot = (u16)s->ReadInteger("bp_cache_slot_"+AnsiString(k),0); + } + } + + void EngineModel::SaveParams(TFormStorage* s) + { + for (int k=0; kWriteString ("bp_cache_name_"+AnsiString(k), m_BPPlayItems[k].name); + s->WriteString ("bp_cache_slot_"+AnsiString(k), m_BPPlayItems[k].slot); + } + }*/ + +//--------------------------------------------------------------------------- + +void CActorTools::OnMotionKeysModified() +{ + Modified(); + m_Flags.set(flUpdateMotionKeys, TRUE); + if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine) + { + m_Flags.set(flUpdateMotionKeys, FALSE); + if (m_RenderObject.UpdateVisual(m_pEditObject, false, true, false)) + { + PlayMotion(); + } + else + { + m_RenderObject.DeleteVisual(); + MainForm->GetLeftBarForm()->SetRenderMode(false); + } + } + OnMotionDefsModified(); +} + +void CActorTools::OnMotionDefsModified() +{ + Modified(); + m_Flags.set(flUpdateMotionDefs, TRUE); + if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine) + { + m_Flags.set(flUpdateMotionDefs, FALSE); + if (m_RenderObject.UpdateVisual(m_pEditObject, false, false, true)) + { + PlayMotion(); + } + else + { + m_RenderObject.DeleteVisual(); + MainForm->GetLeftBarForm()->SetRenderMode(false); + } + } + UndoSave(); +} + +void CActorTools::OnGeometryModified() +{ + Modified(); + if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine) + { + m_Flags.set(flUpdateGeometry, FALSE); + if (m_RenderObject.UpdateVisual(m_pEditObject, true, false, false)) + { + PlayMotion(); + } + else + { + m_RenderObject.DeleteVisual(); + MainForm->GetLeftBarForm()->SetRenderMode(false); + } + } + UndoSave(); +} +//--------------------------------------------------------------------------- + +bool CActorTools::AppendMotion(LPCSTR fn) +{ + VERIFY(m_pEditObject); + bool bRes = m_pEditObject->AppendSMotion(fn, &appended_motions); + return bRes; +} + +bool CActorTools::RemoveMotion(LPCSTR name) +{ + VERIFY(m_pEditObject); + return m_pEditObject->RemoveSMotion(name); +} + +bool CActorTools::SaveMotions(LPCSTR name, bool bSelOnly) +{ + VERIFY(m_pEditObject); + ListItemsVec items; + if (bSelOnly) + { + if (m_ObjectItems->GetSelected(MOTIONS_PREFIX, items, true)) + { + CMemoryWriter F; + F.w_u32(items.size()); + for (ListItemsIt it = items.begin(); it != items.end(); it++) + ((CSMotion *)(*it)->m_Object)->Save(F); + return F.save_to(name); + } + } + else + { + return m_pEditObject->SaveSMotions(name); + } + return false; +} + +void CActorTools::MakePreview() +{ + if (m_pEditObject) + { + CMemoryWriter F; + m_Flags.set(flUpdateGeometry | flUpdateMotionDefs | flUpdateMotionKeys, FALSE); + if (m_RenderObject.UpdateVisual(m_pEditObject, true, true, true)) + { + PlayMotion(); + } + else + { + m_RenderObject.DeleteVisual(); + MainForm->GetLeftBarForm()->SetRenderMode(false); + } + } + else + { + ELog.DlgMsg(mtError, "Scene empty. Load object first."); + } +} + +void CActorTools::PlayMotion() +{ + if (m_pEditObject) + { + //. m_ClipMaker->Stop(); + if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Editor) + m_pEditObject->SkeletonPlay(); + else if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine) + { + if (m_Flags.is(flUpdateMotionKeys)) + { + OnMotionKeysModified(); + } + if (m_Flags.is(flUpdateMotionDefs)) + { + OnMotionDefsModified(); + } + if (m_Flags.is(flUpdateGeometry)) + { + OnGeometryModified(); + } + m_RenderObject.PlayMotion(m_CurrentMotion.c_str(), m_CurrentSlot); + } + } +} + +void CActorTools::StopMotion() +{ + if (m_pEditObject) + if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Editor) + m_pEditObject->SkeletonStop(); + else if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine && m_RenderObject.m_pBlend) + { + m_RenderObject.m_pBlend->playing = false; + m_RenderObject.m_pBlend->timeCurrent = 0; + } +} + +void CActorTools::PauseMotion() +{ + if (m_pEditObject) + if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Editor) + m_pEditObject->SkeletonPause(true); + else if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine && m_RenderObject.m_pBlend) + { + m_RenderObject.m_pBlend->playing = !m_RenderObject.m_pBlend->playing; + } +} + +bool CActorTools::RenameMotion(LPCSTR old_name, LPCSTR new_name) +{ + R_ASSERT(m_pEditObject); + CSMotion *M = m_pEditObject->FindSMotionByName(old_name); + R_ASSERT(M); + CSMotion *MN = m_pEditObject->FindSMotionByName(new_name); + R_ASSERT(!MN); + M->SetName(new_name); + return true; +} + +void CActorTools::AddMarksChannel(bool b12) +{ + CSMotion *M = m_pEditObject->GetActiveSMotion(); + if (M) + { + if (b12) + { + M->marks.resize(2); + M->marks[0].name = "Left"; + M->marks[1].name = "Right"; + } + else + { + M->marks.resize(4); + M->marks[0].name = "Left"; + M->marks[1].name = "Right"; + M->marks[2].name = "Left2"; + M->marks[3].name = "Right2"; + } + m_pEditObject->SetActiveSMotion(M); + } +} + +void CActorTools::RemoveMarksChannel(bool b12) +{ + CSMotion *M = m_pEditObject->GetActiveSMotion(); + if (M) + { + if (b12) + M->marks.clear(); + else + { + if (M->marks.size() == 4) + { + M->marks.pop_back(); + M->marks.pop_back(); + } + else + { + R_ASSERT(M->marks.size() == 0 || M->marks.size() == 2); + } + } + + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } +} diff --git a/src/editors/ActorEditor/UI_ActorToolsProps.cpp b/src/editors/ActorEditor/UI_ActorToolsProps.cpp new file mode 100644 index 00000000000..0b6660eac8e --- /dev/null +++ b/src/editors/ActorEditor/UI_ActorToolsProps.cpp @@ -0,0 +1,996 @@ +#include "stdafx.h" +#include "Layers/xrRender/KinematicAnimatedDefs.h" +#include "Layers/xrRender/SkeletonAnimated.h" +#include "xrCore/Animation/envelope.hpp" + +void CActorTools::OnObjectItemsFocused(xr_vector &items) +{ + PropItemVec props; + m_EditMode = emObject; + + // unselect + if (m_pEditObject) + { + m_pEditObject->ResetSAnimation(false); + m_pEditObject->SelectBones(false); + } + for (ListItem *prop : items) + { + + if (prop) + { + m_EditMode = EEditMode(prop->Type()); + switch (m_EditMode) + { + case emObject: + FillObjectProperties(props, OBJECT_PREFIX, prop); + break; + case emMotion: + { + LPCSTR m_name = ExtractMotionName(prop->Key()); + u16 slot = ExtractMotionSlot(prop->Key()); + FillMotionProperties(props, MOTIONS_PREFIX, prop); + SetCurrentMotion(m_name, slot); + } + break; + case emBone: + { + FillBoneProperties(props, BONES_PREFIX, prop); + CBone *BONE = (CBone *)prop->m_Object; + if (BONE) + BONE->Select(TRUE); + } + break; + case emSurface: + FillSurfaceProperties(props, SURFACES_PREFIX, prop); + break; + case emMesh: + break; + } + } + } + + m_Props->AssignItems(props); + UI->RedrawScene(); +} +//------------------------------------------------------------------------------ + +void CActorTools::OnChangeTransform(PropValue *sender) +{ + OnMotionKeysModified(); + UI->RedrawScene(); +} +//------------------------------------------------------------------------------ +void CActorTools::OnExportImportRefsClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + switch (V->btn_num) + { + case 0: + { // export + xr_string fname; + if (EFS.GetSaveName(_import_, fname)) + { + CInifile ini(fname.c_str(), FALSE, FALSE, FALSE); + xr_vector::iterator it = m_pEditObject->m_SMotionRefs.begin(); + xr_vector::iterator it_e = m_pEditObject->m_SMotionRefs.end(); + string64 buff; + for (u32 i = 0; it != it_e; ++it, ++i) + { + sprintf(buff, "%06d", i); + ini.w_string("refs", buff, (*it).c_str()); + } + ini.save_as(fname.c_str()); + bModif = false; + } + } + break; + case 1: + { // import + xr_string fname; + if (EFS.GetOpenName(EDevice.m_hWnd, _import_, fname, false)) + { + CInifile ini(fname.c_str(), TRUE, TRUE, FALSE); + m_pEditObject->m_SMotionRefs.clear(); + CInifile::Sect &S = ini.r_section("refs"); + auto it = S.Data.begin(); + auto it_e = S.Data.end(); + for (; it != it_e; ++it) + { + m_pEditObject->m_SMotionRefs.push_back(it->second); + } + + OnMotionKeysModified(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + bModif = true; + } + else + bModif = false; + } + break; + }; +} + +void CActorTools::OnMotionEditClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + R_ASSERT(m_pEditObject); + xr_string fn; + switch (V->btn_num) + { + case 0: + { // append + xr_string folder, nm, full_name; + xr_string fnames; + if (EFS.GetOpenName(EDevice.m_hWnd, _smotion_, fnames, true)) + { + AStringVec lst; + _SequenceToList(lst, fnames.c_str()); + bool bRes = false; + for (AStringIt it = lst.begin(); it != lst.end(); it++) + if (AppendMotion(it->c_str())) + bRes = true; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + if (bRes) + OnMotionKeysModified(); + else + ELog.DlgMsg(mtError, "Append not completed."); + bModif = false; + } + else + bModif = false; + } + break; + case 1: + { // delete + ListItemsVec items; + if (m_ObjectItems->GetSelected(MOTIONS_PREFIX, items, true)) + { + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Delete selected %d item(s)?", items.size()) == mrYes) + { + for (ListItemsIt it = items.begin(); it != items.end(); it++) + { + VERIFY((*it)->m_Object); + RemoveMotion(((CSMotion *)(*it)->m_Object)->Name()); + } + SelectListItem(MOTIONS_PREFIX, 0, true, false, false); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + OnMotionKeysModified(); + bModif = false; + } + else + { + bModif = false; + } + } + else + ELog.DlgMsg(mtInformation, "Select at least one motion."); + } + break; + case 2: + { // save + int mr = ELog.DlgMsg(mtConfirmation, "Save selected motions only?"); + if (mr != mrCancel) + { + if (EFS.GetSaveName(_smotion_, fn, 0, 1)) + { + switch (mr) + { + case mrYes: + SaveMotions(fn.c_str(), true); + break; + case mrNo: + SaveMotions(fn.c_str(), false); + break; + } + } + } + bModif = false; + } + break; + } +} + +void CActorTools::RealUpdateProperties() +{ + m_Flags.set(flRefreshProps, FALSE); + ListItemsVec items; + if (m_pEditObject) + { + LHelper().CreateItem(items, OBJECT_PREFIX, 0, emObject); + m_pEditObject->FillSurfaceList(SURFACES_PREFIX, items, emSurface); + // skin + if (m_pEditObject->IsSkeleton()) + { + if (m_pEditObject->m_SMotionRefs.size()) + { + m_RenderObject.FillMotionList(MOTIONS_PREFIX, items, emMotion); + } + else + { + m_pEditObject->FillMotionList(MOTIONS_PREFIX, items, emMotion); + } + m_pEditObject->FillBoneList(BONES_PREFIX, items, emBone); + } + } + + m_ObjectItems->AssignItems(items, nullptr, true, true); //,"",true); + // if appended motions exist - select it + if (!appended_motions.empty()) + { + SelectListItem(MOTIONS_PREFIX, 0, true, false, true); + for (SMotionIt m_it = appended_motions.begin(); m_it != appended_motions.end(); m_it++) + SelectListItem(MOTIONS_PREFIX, (*m_it)->Name(), true, true, true); + appended_motions.clear(); + } +} +//------------------------------------------------------------------------------ + +void CActorTools::OnMotionTypeChange(PropValue *sender) +{ + RefreshSubProperties(); +} +//------------------------------------------------------------------------------ + +void CActorTools::OnMotionNameChange(PropValue *V) +{ + OnMotionKeysModified(); + UpdateProperties(); +} +//------------------------------------------------------------------------------ + +void CActorTools::OnMotionControlClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + switch (V->btn_num) + { + case 0: + PlayMotion(); + break; + case 1: + StopMotion(); + break; + case 2: + PauseMotion(); + break; + } + bModif = false; +} +//------------------------------------------------------------------------------ +void CActorTools::OnMarksControlClick12(ButtonValue *V, bool &bModif, bool &bSafe) +{ + switch (V->btn_num) + { + case 0: + AddMarksChannel(true); + break; + case 1: + RemoveMarksChannel(true); + break; + } + bModif = true; +} +//------------------------------------------------------------------------------ + +void CActorTools::OnMarksControlClick34(ButtonValue *V, bool &bModif, bool &bSafe) +{ + switch (V->btn_num) + { + case 0: + AddMarksChannel(false); + break; + case 1: + RemoveMarksChannel(false); + break; + } + bModif = true; +} +//------------------------------------------------------------------------------ + +void CActorTools::OnMotionRefsChange(PropValue *sender) +{ + u32 set_cnt = _GetItemCount(m_tmp_mot_refs.c_str()); + + m_pEditObject->m_SMotionRefs.clear(); + m_pEditObject->m_SMotionRefs.reserve(set_cnt); + + string_path nm; + for (u32 k = 0; k < set_cnt; ++k) + { + _GetItem(m_tmp_mot_refs.c_str(), k, nm); + m_pEditObject->m_SMotionRefs.push_back(nm); + } + + OnMotionKeysModified(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CActorTools::OnBoxAxisClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + CBone *BONE = (CBone *)V->tag; + switch (V->btn_num) + { + case 0: + BONE->shape.box.m_rotate.k.set(1, 0, 0); + break; + case 1: + BONE->shape.box.m_rotate.k.set(0, 1, 0); + break; + case 2: + BONE->shape.box.m_rotate.k.set(0, 0, 1); + break; + } + Fvector::generate_orthonormal_basis_normalized(BONE->shape.box.m_rotate.k, BONE->shape.box.m_rotate.j, BONE->shape.box.m_rotate.i); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CActorTools::OnCylinderAxisClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + CBone *BONE = (CBone *)V->tag; + switch (V->btn_num) + { + case 0: + BONE->shape.cylinder.m_direction.set(1, 0, 0); + break; + case 1: + BONE->shape.cylinder.m_direction.set(0, 1, 0); + break; + case 2: + BONE->shape.cylinder.m_direction.set(0, 0, 1); + break; + } + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +Fvector StartMotionPoint, EndMotionPoint; + +void CActorTools::FillMotionProperties(PropItemVec &items, LPCSTR pref, ListItem *sender) +{ + R_ASSERT(m_pEditObject); + CSMotion *SM = m_pEditObject->m_SMotionRefs.size() ? 0 : (CSMotion *)sender->m_Object; + PropValue *V; + + xr_string m_cnt; + if (m_pEditObject->m_SMotionRefs.size()) + { + if (MainForm->GetLeftBarForm()->GetRenderMode() == UILeftBarForm::Render_Engine) + { + CKinematicsAnimated *V = PKinematicsAnimated(m_RenderObject.m_pVisual); + if (V) + m_cnt = V->LL_CycleCount() + V->LL_FXCount(); + } + else + { + m_cnt = make_string("%d (Inaccessible)", m_pEditObject->SMotionCount()); + } + } + else + { + m_cnt = m_pEditObject->SMotionCount(); + } + + PHelper().CreateCaption(items, PrepareKey(pref, "Global\\Motion count"), m_cnt.c_str()); + + xr_string tmp; + for (u32 i = 0; i < m_pEditObject->m_SMotionRefs.size(); ++i) + { + if (i != 0) + tmp += ','; + tmp += m_pEditObject->m_SMotionRefs[i].c_str(); + } + m_tmp_mot_refs = tmp.c_str(); + V = PHelper().CreateChoose(items, PrepareKey(pref, "Global\\Motion reference"), &m_tmp_mot_refs, smGameSMotions, 0, 0, MAX_ANIM_SLOT); + // m_pEditObject->m_SMotionRefs + V->OnChangeEvent.bind(this, &CActorTools::OnMotionRefsChange); + ButtonValue *B; + + B = PHelper().CreateButton(items, PrepareKey(pref, "Export Import"), "ExportRefs,ImportRefs", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &CActorTools::OnExportImportRefsClick); + + if (m_pEditObject->m_SMotionRefs.size() == 0) + { + B = PHelper().CreateButton(items, PrepareKey(pref, "Global\\Edit"), "Append,Delete,Save", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &CActorTools::OnMotionEditClick); + } + if (SM) + { + B = PHelper().CreateButton(items, PrepareKey(pref, "Motion\\Control"), "Play,Stop,Pause", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &CActorTools::OnMotionControlClick); + PHelper().CreateCaption(items, PrepareKey(pref, "Motion\\Frame\\Start"), shared_str().printf("%d", SM->FrameStart())); + PHelper().CreateCaption(items, PrepareKey(pref, "Motion\\Frame\\End"), shared_str().printf("%d", SM->FrameEnd())); + PHelper().CreateCaption(items, PrepareKey(pref, "Motion\\Frame\\Length"), shared_str().printf("%d", SM->Length())); + PropValue *P = 0; + P = PHelper().CreateName(items, PrepareKey(pref, "Motion\\Name"), &SM->name, sender); + P->OnChangeEvent.bind(this, &CActorTools::OnMotionNameChange); + PHelper().CreateFloat(items, PrepareKey(pref, "Motion\\Speed"), &SM->fSpeed, 0.f, 10.f, 0.01f, 2); + PHelper().CreateFloat(items, PrepareKey(pref, "Motion\\Accrue"), &SM->fAccrue, 0.f, 10.f, 0.01f, 2); + PHelper().CreateFloat(items, PrepareKey(pref, "Motion\\Falloff"), &SM->fFalloff, 0.f, 10.f, 0.01f, 2); + + PropValue /**C=0,*/ *TV = 0; + TV = PHelper().CreateFlag8(items, PrepareKey(pref, "Motion\\Type FX"), &SM->m_Flags, esmFX); + TV->OnChangeEvent.bind(this, &CActorTools::OnMotionTypeChange); + m_BoneParts.clear(); + if (SM->m_Flags.is(esmFX)) + { + for (BoneIt it = m_pEditObject->FirstBone(); it != m_pEditObject->LastBone(); it++) + m_BoneParts.push_back(xr_rtoken((*it)->Name().c_str(), (*it)->SelfID)); + PHelper().CreateRToken16(items, PrepareKey(pref, "Motion\\FX\\Start bone"), (u16 *)&SM->m_BoneOrPart, &*m_BoneParts.begin(), m_BoneParts.size()); + + PHelper().CreateFloat(items, PrepareKey(pref, "Motion\\FX\\Power"), &SM->fPower, 0.f, 10.f, 0.01f, 2); + } + else + { + m_BoneParts.push_back(xr_rtoken("--all bones--", BI_NONE)); + for (BPIt it = m_pEditObject->FirstBonePart(); it != m_pEditObject->LastBonePart(); it++) + m_BoneParts.push_back(xr_rtoken(it->alias.c_str(), it - m_pEditObject->FirstBonePart())); + PHelper().CreateRToken16(items, PrepareKey(pref, "Motion\\Cycle\\Bone part"), &SM->m_BoneOrPart, &*m_BoneParts.begin(), m_BoneParts.size()); + PHelper().CreateFlag8(items, PrepareKey(pref, "Motion\\Cycle\\Stop at end"), &SM->m_Flags, esmStopAtEnd); + PHelper().CreateFlag8(items, PrepareKey(pref, "Motion\\Cycle\\No mix"), &SM->m_Flags, esmNoMix); + PHelper().CreateFlag8(items, PrepareKey(pref, "Motion\\Cycle\\Sync part"), &SM->m_Flags, esmSyncPart); + + PHelper().CreateFlag8(items, PrepareKey(pref, "Motion\\Cycle\\UseFootSteps"), &SM->m_Flags, esmUseFootSteps); + PHelper().CreateFlag8(items, PrepareKey(pref, "Motion\\Cycle\\Move XForm"), &SM->m_Flags, esmRootMover); + PHelper().CreateFlag8(items, PrepareKey(pref, "Motion\\Cycle\\Idle"), &SM->m_Flags, esmIdle); + PHelper().CreateFlag8(items, PrepareKey(pref, "Motion\\Cycle\\UseWeaponBone"), &SM->m_Flags, esmUseWeaponBone); + } + + B = PHelper().CreateButton(items, PrepareKey(pref, "Marks\\Control-12"), "Add,Remove", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &CActorTools::OnMarksControlClick12); + + B = PHelper().CreateButton(items, PrepareKey(pref, "Marks\\Control-34"), "Add,Remove", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &CActorTools::OnMarksControlClick34); + + for (u32 i = 0; i < SM->marks.size(); ++i) + { + string128 buff; + sprintf(buff, "Marks\\%d", i); + P = PHelper().CreateCaption(items, PrepareKey(pref, buff), SM->marks[i].name); + } + + { + int bidx = 0; + BoneMotionVec &BMV = SM->BoneMotions(); + st_BoneMotion &BM = BMV[bidx]; + StartMotionPoint.x = BM.envs[ctPositionX]->keys.size() ? BM.envs[ctPositionX]->keys.front()->value : -1; + StartMotionPoint.y = BM.envs[ctPositionY]->keys.size() ? BM.envs[ctPositionY]->keys.front()->value : -1; + StartMotionPoint.z = BM.envs[ctPositionZ]->keys.size() ? BM.envs[ctPositionZ]->keys.front()->value : -1; + + PHelper().CreateVector(items, PrepareKey(pref, "Motion\\RootStartTransform"), &StartMotionPoint, -10000, 10000, 0.001, 4); + + EndMotionPoint.x = BM.envs[ctPositionX]->keys.size() ? BM.envs[ctPositionX]->keys.back()->value : -1; + EndMotionPoint.y = BM.envs[ctPositionY]->keys.size() ? BM.envs[ctPositionY]->keys.back()->value : -1; + EndMotionPoint.z = BM.envs[ctPositionZ]->keys.size() ? BM.envs[ctPositionZ]->keys.back()->value : -1; + + PHelper().CreateVector(items, PrepareKey(pref, "Motion\\RootEndTransform"), &EndMotionPoint, -10000, 10000, 0.001, 4); + } + } +} +//------------------------------------------------------------------------------ + +xr_token joint_types[] = { + {"Rigid", jtRigid}, + {"Cloth", jtCloth}, + {"Joint", jtJoint}, + {"Wheel [Steer-X/Roll-Z]", jtWheel}, + {"Slider", jtSlider}, + // { "Wheel [Steer-X/Roll-Z]", jtWheelXZ }, + // { "Wheel [Steer-X/Roll-Y]", jtWheelXY }, + // { "Wheel [Steer-Y/Roll-X]", jtWheelYX }, + // { "Wheel [Steer-Y/Roll-Z]", jtWheelYZ }, + // { "Wheel [Steer-Z/Roll-X]", jtWheelZX }, + // { "Wheel [Steer-Z/Roll-Y]", jtWheelZY }, + {0, 0}}; + +xr_token shape_types[] = { + {"None", SBoneShape::stNone}, + {"Box", SBoneShape::stBox}, + {"Sphere", SBoneShape::stSphere}, + {"Cylinder", SBoneShape::stCylinder}, + {0, 0}}; + +static const LPCSTR axis[3] = + {"Axis X", "Axis Y", "Axis Z"}; + +void CActorTools::OnJointTypeChange(PropValue *V) +{ + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} +void CActorTools::OnShapeTypeChange(PropValue *V) +{ + UI->RedrawScene(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} +void CActorTools::OnBindTransformChange(PropValue *V) +{ + R_ASSERT(m_pEditObject); + m_pEditObject->OnBindTransformChange(); + UI->RedrawScene(); +} + +void CActorTools::OnTypeChange(PropValue *V) +{ + u32 current_type = m_pEditObject->m_objectFlags.flags & (CEditableObject::eoDynamic | CEditableObject::eoHOM | CEditableObject::eoSoundOccluder | CEditableObject::eoMultipleUsage); + m_pEditObject->m_objectFlags.flags = m_pEditObjectType; + + if (current_type != m_pEditObjectType) + { + if (m_pEditObjectType == CEditableObject::eoMultipleUsage) + { + m_pEditObject->m_objectFlags.flags |= CEditableObject::eoUsingLOD; + } + } + RefreshSubProperties(); +} + +void CActorTools::OnUsingLodFlagChange(PropValue *V) +{ + RefreshSubProperties(); +} + +void CActorTools::OnMakeThumbnailClick(ButtonValue *sender, bool &bModif, bool &bSafe) +{ + R_ASSERT(m_pEditObject); + switch (sender->btn_num) + { + case 0: + { + MakeThumbnail(); + } + break; + } +} + +void CActorTools::OnMakeLODClick(ButtonValue *sender, bool &bModif, bool &bSafe) +{ + R_ASSERT(m_pEditObject); + switch (sender->btn_num) + { + case 0: + { + GenerateLOD(true); + } + case 1: + { + GenerateLOD(false); + } + break; + } +} + +void CActorTools::OnBoneShapeClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + R_ASSERT(m_pEditObject); + switch (V->btn_num) + { + case 0: + m_pEditObject->GenerateBoneShape(false); + break; + case 1: + m_pEditObject->GenerateBoneShape(true); + break; + } +} + +void GetBindAbsolutePosition(CBone *B, Fmatrix &dest) +{ + + if (B->Parent()) + GetBindAbsolutePosition(B->Parent(), dest); + + { + Fmatrix M; + M.setXYZi(B->RestRotate()); + M.c.set(B->RestOffset()); + M.mulA_43(dest); + dest.set(M); + } +} + +void CActorTools::OnBoneCreateDeleteClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + R_ASSERT(m_pEditObject); + BoneVec sel_bones; + m_pEditObject->GetSelectedBones(sel_bones); + switch (V->btn_num) + { + case 0: + { // create + CBone *B = sel_bones.size() ? sel_bones[0] : NULL; + m_pEditObject->AddBone(B); + bModif = true; + } + break; + case 1: + { // deleet + if (sel_bones.size() != 1) + { + Msg("! Select 1 bone please."); + return; + } + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Delete selected bone?") == mrYes) + { + m_pEditObject->DeleteBone(sel_bones[0]); + bModif = true; + } + } + break; + case 2: + { + if (sel_bones.size() != 1) + { + Msg("! Select 1 bone please."); + return; + } + LPCSTR _bone_name = 0; + UIChooseForm::SelectItem(smSkeletonBonesInObject, 1, 0, 0, m_pEditObject); + m_ChooseSkeletonBones = true; + } + break; + } + if (bModif) + { + bSafe = false; + m_Flags.set(flRefreshProps, TRUE); + } +} + +void CActorTools::OnDrawUI() +{ + if (m_ChooseSkeletonBones) + { + + xr_string str; + bool ok; + if (UIChooseForm::GetResult(ok, str)) + { + if (ok) + { + + BoneVec sel_bones; + m_pEditObject->GetSelectedBones(sel_bones); + Msg("selected bone %s", str.c_str()); + CBone *BSelected = m_pEditObject->FindBoneByName(str.c_str()); + R_ASSERT(BSelected); + + CBone *BEditable = sel_bones[0]; + Fmatrix matrix1, matrix2; + Fvector offset, rotate1, rotate2, rotate; + float length = 0.01f; + + m_pEditObject->GotoBindPose(); + + matrix1.identity(); + matrix2.identity(); + GetBindAbsolutePosition(BEditable, matrix1); + GetBindAbsolutePosition(BSelected, matrix2); + + Fmatrix R; + R.mul(matrix1.invert(), matrix2).getXYZi(rotate); + offset.set(R.c); + + BEditable->SetRestParams(length, offset, rotate); + + m_pEditObject->GotoBindPose(); + } + m_ChooseSkeletonBones = false; + UIChooseForm::Update(); + } + } +} +bool CActorTools::OnBoneNameAfterEdit(PropValue *sender, shared_str &edit_val) +{ + R_ASSERT(m_pEditObject); + BoneVec sel_bones; + m_pEditObject->GetSelectedBones(sel_bones); + CBone *B = sel_bones.size() ? sel_bones[0] : NULL; + R_ASSERT(B); + for (auto &bone : m_pEditObject->Bones()) + { + if (bone->Name() == edit_val) + return false; + } + m_pEditObject->RenameBone(B, edit_val.c_str()); + return true; +} + +void CActorTools::OnBoneNameChangeEvent(PropValue *sender) +{ + UpdateProperties(); +} + +void CActorTools::OnBoneEditClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + R_ASSERT(m_pEditObject); + switch (V->btn_num) + { + case 0: + m_pEditObject->GotoBindPose(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + bModif = false; + break; + case 1: + if (ELog.DlgMsg(mtConfirmation, "Are you sure to reset IK data?") == mrYes) + m_pEditObject->ResetBones(); + bModif = true; + break; + case 2: + m_pEditObject->ClampByLimits(false); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + bModif = false; + break; + } +} + +void CActorTools::OnBoneFileClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + R_ASSERT(m_pEditObject); + switch (V->btn_num) + { + case 0: + { + xr_string fn; + if (EFS.GetOpenName(EDevice.m_hWnd, "$sbones$", fn)) + { + IReader *R = FS.r_open(fn.c_str()); + if (m_pEditObject->LoadBoneData(*R)) + ELog.DlgMsg(mtInformation, "Bone data succesfully loaded."); + else + ELog.DlgMsg(mtError, "Failed to load bone data."); + FS.r_close(R); + } + else + { + bModif = false; + } + } + break; + case 1: + { + xr_string fn; + if (EFS.GetSaveName("$sbones$", fn)) + { + IWriter *W = FS.w_open(fn.c_str()); + if (W) + { + m_pEditObject->SaveBoneData(*W); + FS.w_close(W); + } + else + { + Log("!Can't save skeleton bones:", fn.c_str()); + } + bModif = false; + } + } + break; + } +} + +void CActorTools::OnBoneLimitsChange(PropValue *sender) +{ + m_pEditObject->ClampByLimits(true); +} + +void CActorTools::FillBoneProperties(PropItemVec &items, LPCSTR pref, ListItem *sender) +{ + R_ASSERT(m_pEditObject); + CBone *BONE = (CBone *)sender->m_Object; + + PHelper().CreateCaption(items, PrepareKey(pref, "Global\\Bone count"), shared_str().printf("%d", m_pEditObject->BoneCount())); + ButtonValue *B; + B = PHelper().CreateButton(items, PrepareKey(pref, "Global\\File"), "Load,Save", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &CActorTools::OnBoneFileClick); + B = PHelper().CreateButton(items, PrepareKey(pref, "Global\\Edit"), "Bind pose,Reset IK,Clamp limits", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &CActorTools::OnBoneEditClick); + B = PHelper().CreateButton(items, PrepareKey(pref, "Global\\Generate Shape"), "All, Selected", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &CActorTools::OnBoneShapeClick); + //--- + B = PHelper().CreateButton(items, PrepareKey(pref, "Global\\Bone"), "Create, Delete, Orient", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &CActorTools::OnBoneCreateDeleteClick); + //--- + + if (BONE) + { + PropValue *V; + PHelper().CreateCaption(items, PrepareKey(pref, "Bone\\Name"), BONE->Name()); + + PHelper().CreateNameCB(items, PrepareKey(pref, "Bone\\NameEditable"), &BONE->NameRef(), 0, 0, RTextValue::TOnAfterEditEvent(this, &CActorTools::OnBoneNameAfterEdit))->OnChangeEvent.bind(this, &CActorTools::OnBoneNameChangeEvent); + + //. PHelper().CreateCaption (items, PrepareKey(pref,"Bone\\Influence"), shared_str().sprintf("%d vertices",0)); + PHelper().CreateChoose(items, PrepareKey(pref, "Bone\\Game Material"), &BONE->game_mtl, smGameMaterial); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Mass"), &BONE->mass, 0.f, 10000.f); + PHelper().CreateVector(items, PrepareKey(pref, "Bone\\Center Of Mass"), &BONE->center_of_mass, -10000.f, 10000.f); + V = PHelper().CreateVector(items, PrepareKey(pref, "Bone\\Bind Position"), &BONE->RestOffset(), -10000.f, 10000.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBindTransformChange); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Bone\\Bind Rotation"), &BONE->RestRotate()); + V->OnChangeEvent.bind(this, &CActorTools::OnBindTransformChange); + PHelper().CreateFlag16(items, PrepareKey(pref, "Bone\\Shape\\Flags\\No Pickable"), &BONE->shape.flags, SBoneShape::sfNoPickable); + PHelper().CreateFlag16(items, PrepareKey(pref, "Bone\\Shape\\Flags\\No Physics"), &BONE->shape.flags, SBoneShape::sfNoPhysics); + PHelper().CreateFlag16(items, PrepareKey(pref, "Bone\\Shape\\Flags\\Remove After Break"), &BONE->shape.flags, SBoneShape::sfRemoveAfterBreak); + PHelper().CreateFlag16(items, PrepareKey(pref, "Bone\\Shape\\Flags\\No Fog Collider"), &BONE->shape.flags, SBoneShape::sfNoFogCollider); + + V = PHelper().CreateToken16(items, PrepareKey(pref, "Bone\\Shape\\Type"), &BONE->shape.type, shape_types); + V->OnChangeEvent.bind(this, &CActorTools::OnShapeTypeChange); + switch (BONE->shape.type) + { + case SBoneShape::stBox: + PHelper().CreateVector(items, PrepareKey(pref, "Bone\\Shape\\Box\\Center"), &BONE->shape.box.m_translate, -10000.f, 10000.f); + B = PHelper().CreateButton(items, PrepareKey(pref, "Bone\\Shape\\Box\\Align Axis"), "X,Y,Z", 0); + B->OnBtnClickEvent.bind(this, &CActorTools::OnBoxAxisClick); + B->tag = (size_t)BONE; + PHelper().CreateVector(items, PrepareKey(pref, "Bone\\Shape\\Box\\Half Size"), &BONE->shape.box.m_halfsize, 0.f, 1000.f); + break; + case SBoneShape::stSphere: + PHelper().CreateVector(items, PrepareKey(pref, "Bone\\Shape\\Sphere\\Position"), &BONE->shape.sphere.P, -10000.f, 10000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Shape\\Sphere\\Radius"), &BONE->shape.sphere.R, 0.f, 1000.f); + break; + case SBoneShape::stCylinder: + PHelper().CreateVector(items, PrepareKey(pref, "Bone\\Shape\\Cylinder\\Center"), &BONE->shape.cylinder.m_center, -10000.f, 10000.f); + B = PHelper().CreateButton(items, PrepareKey(pref, "Bone\\Shape\\Cylinder\\Align Axis"), "X,Y,Z", 0); + B->OnBtnClickEvent.bind(this, &CActorTools::OnCylinderAxisClick); + B->tag = (size_t)BONE; + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Shape\\Cylinder\\Height"), &BONE->shape.cylinder.m_height, 0.f, 1000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Shape\\Cylinder\\Radius"), &BONE->shape.cylinder.m_radius, 0.f, 1000.f); + break; + } + + Fvector lim_rot; + Fmatrix mLocal, mBind, mBindI; + mBind.setXYZi(BONE->RestRotate().x, BONE->RestRotate().y, BONE->RestRotate().z); + mBindI.invert(mBind); + mLocal.setXYZi(BONE->Rotate().x, BONE->Rotate().y, BONE->Rotate().z); + mLocal.mulA_43(mBindI); + mLocal.getXYZi(lim_rot); + lim_rot.x = rad2deg(lim_rot.x); + lim_rot.y = rad2deg(lim_rot.y); + lim_rot.z = rad2deg(lim_rot.z); + + PHelper().CreateCaption(items, PrepareKey(pref, "Bone\\Joint\\Current Rotation"), shared_str().printf("{%3.2f, %3.2f, %3.2f}", VPUSH(lim_rot))); + SJointIKData &data = BONE->IK_data; + V = PHelper().CreateFlag32(items, PrepareKey(pref, "Bone\\Joint\\Breakable"), &data.ik_flags, SJointIKData::flBreakable); + V->OnChangeEvent.bind(this, &CActorTools::OnJointTypeChange); + if (data.ik_flags.is(SJointIKData::flBreakable)) + { + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Break Force"), &data.break_force, 0.f, 1000000000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Break Torque"), &data.break_torque, 0.f, 1000000000.f); + } + V = PHelper().CreateToken32(items, PrepareKey(pref, "Bone\\Joint\\Type"), (u32 *)&data.type, joint_types); + V->OnChangeEvent.bind(this, &CActorTools::OnJointTypeChange); + switch (data.type) + { + case jtRigid: + break; + case jtCloth: + { + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Friction"), &data.friction, 0.f, 1000000000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Spring Factor"), &data.spring_factor, 0.f, 1000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Damping Factor"), &data.damping_factor, 0.f, 1000.f); + } + break; + case jtJoint: + { + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Friction"), &data.friction, 0.f, 1000000000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Spring Factor"), &data.spring_factor, 0.f, 1000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Damping Factor"), &data.damping_factor, 0.f, 1000.f); + for (int k = 0; k < 3; k++) + { + V = PHelper().CreateAngle(items, PrepareKey(pref, "Bone\\Joint\\Limits", axis[k], "Min"), &data.limits[k].limit.x, -M_PI, 0.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + V = PHelper().CreateAngle(items, PrepareKey(pref, "Bone\\Joint\\Limits", axis[k], "Max"), &data.limits[k].limit.y, 0.f, M_PI); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Limits", axis[k], "Spring Factor"), &data.limits[k].spring_factor, 0.f, 1000.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Limits", axis[k], "Damping Factor"), &data.limits[k].damping_factor, 0.f, 1000.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + } + } + break; + case jtWheel: + { + // int idx = (data.type-jtWheelXZ)/2; + int idx = (data.type - jtWheel) / 2; + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Friction"), &data.friction, 0.f, 1000000000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Spring Factor"), &data.spring_factor, 0.f, 1000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Damping Factor"), &data.damping_factor, 0.f, 1000.f); + V = PHelper().CreateAngle(items, PrepareKey(pref, "Bone\\Joint\\Steer\\Limits Min"), &data.limits[idx].limit.x, -PI_DIV_2, 0.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + V = PHelper().CreateAngle(items, PrepareKey(pref, "Bone\\Joint\\Steer\\Limits Max"), &data.limits[idx].limit.y, 0, PI_DIV_2); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + } + break; + case jtSlider: + { + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Friction"), &data.friction, 0.f, 1000000000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Spring Factor"), &data.spring_factor, 0.f, 1000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Damping Factor"), &data.damping_factor, 0.f, 1000.f); + { // slider + V = PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Slide (Axis Z)\\Limits Min"), &data.limits[0].limit[0], -100.f, 0.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Slide (Axis Z)\\Limits Max"), &data.limits[0].limit[1], 0.f, 100.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Slide (Axis Z)\\Spring Factor"), &data.limits[0].spring_factor, 0.f, 1000.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Slide (Axis Z)\\Damping Factor"), &data.limits[0].damping_factor, 0.f, 1000.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + } + { // rotate + V = PHelper().CreateAngle(items, PrepareKey(pref, "Bone\\Joint\\Rotate (Axis Z)\\Limits Min"), &data.limits[1].limit[0], -M_PI, 0.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + V = PHelper().CreateAngle(items, PrepareKey(pref, "Bone\\Joint\\Rotate (Axis Z)\\Limits Max"), &data.limits[1].limit[1], 0.f, M_PI); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Rotate (Axis Z)\\Spring Factor"), &data.limits[1].spring_factor, 0.f, 1000.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Bone\\Joint\\Rotate (Axis Z)\\Damping Factor"), &data.limits[1].damping_factor, 0.f, 1000.f); + V->OnChangeEvent.bind(this, &CActorTools::OnBoneLimitsChange); + } + } + break; + } + } +} +//------------------------------------------------------------------------------ + +void CActorTools::FillSurfaceProperties(PropItemVec &items, LPCSTR pref, ListItem *sender) +{ + R_ASSERT(m_pEditObject); + CSurface *SURF = (CSurface *)sender->m_Object; + PHelper().CreateCaption(items, PrepareKey(pref, "Statistic\\Count"), shared_str().printf("%d", m_pEditObject->SurfaceCount())); + if (SURF) + { + PHelper().CreateCaption(items, PrepareKey(pref, "Surface\\Name"), SURF->_Name()); + xr_string _pref = PrepareKey(pref, "Surface").c_str(); + m_pEditObject->FillSurfaceProps(SURF, _pref.c_str(), items); + } +} +//------------------------------------------------------------------------------ +xr_token eo_type_token[] = { + {"Static", 0}, + {"Dynamic", CEditableObject::eoDynamic}, + {"HOM", CEditableObject::eoHOM}, + {"Multiple Usage", CEditableObject::eoMultipleUsage}, + {"Sound Occluder", CEditableObject::eoSoundOccluder}, + {0, 0}}; + +void CActorTools::FillObjectProperties(PropItemVec &items, LPCSTR pref, ListItem *sender) +{ + R_ASSERT(m_pEditObject); + PropValue *V = 0; + m_pEditObjectType = m_pEditObject->m_objectFlags.flags & (CEditableObject::eoDynamic | CEditableObject::eoHOM | CEditableObject::eoSoundOccluder | CEditableObject::eoMultipleUsage); + PHelper().CreateToken32(items, "Object\\Object Type", &m_pEditObjectType, eo_type_token)->OnChangeEvent.bind(this, &CActorTools::OnTypeChange); + + if (m_pEditObjectType & CEditableObject::eoDynamic) + { + PHelper().CreateFlag32(items, "Object\\Flags\\Make Progressive", &m_pEditObject->m_objectFlags, CEditableObject::eoProgressive); + PHelper().CreateFlag32(items, "Object\\Flags\\HQ Geometry", &m_pEditObject->m_objectFlags, CEditableObject::eoHQExport); + } + else if (m_pEditObjectType & CEditableObject::eoMultipleUsage) + { + PHelper().CreateFlag32(items, "Object\\Flags\\Using LOD", &m_pEditObject->m_objectFlags, CEditableObject::eoUsingLOD)->OnChangeEvent.bind(this, &CActorTools::OnUsingLodFlagChange); + } + + V = PHelper().CreateVector(items, "Object\\Transform\\Position", &m_pEditObject->a_vPosition, -10000, 10000, 0.01, 2); + V->OnChangeEvent.bind(this, &CActorTools::OnChangeTransform); + V = PHelper().CreateAngle3(items, "Object\\Transform\\Rotation", &m_pEditObject->a_vRotate, -10000, 10000, 0.1, 1); + V->OnChangeEvent.bind(this, &CActorTools::OnChangeTransform); + V = PHelper().CreateVector(items, "Object\\Transform\\Scale", &m_pEditObject->t_vScale, -10000, 10000, 0.1, 1); + V->OnChangeEvent.bind(this, &CActorTools::OnChangeTransform); + V = PHelper().CreateCaption(items, "Object\\Transform\\BBox Min", shared_str().printf("{%3.2f, %3.2f, %3.2f}", VPUSH(m_pEditObject->GetBox().vMin))); + V = PHelper().CreateCaption(items, "Object\\Transform\\BBox Max", shared_str().printf("{%3.2f, %3.2f, %3.2f}", VPUSH(m_pEditObject->GetBox().vMax))); + + //. PHelper().CreateChoose (items, "Object\\LOD\\Reference", &m_pEditObject->m_LODs, smObject); + PHelper().CreateChoose(items, "Object\\LOD\\Reference", &m_pEditObject->m_LODs, smVisual); + if (m_pEditObject->m_objectFlags.flags & CEditableObject::eoUsingLOD) + { + PHelper().CreateButton(items, "Object\\LOD\\Action", "Make HQ,Make LQ", ButtonValue::flFirstOnly)->OnBtnClickEvent.bind(this, &CActorTools::OnMakeLODClick); + } + PHelper().CreateButton(items, "Object\\Action", "Make Thumbnail", ButtonValue::flFirstOnly)->OnBtnClickEvent.bind(this, &CActorTools::OnMakeThumbnailClick); + m_pEditObject->FillSummaryProps("Object\\Summary", items); +} +//------------------------------------------------------------------------------ + +void CActorTools::SelectListItem(LPCSTR pref, LPCSTR name, bool bVal, bool bLeaveSel, bool bExpand) +{ + xr_string nm = (name && name[0]) ? PrepareKey(pref, name).c_str() : xr_string(pref).c_str(); + m_ObjectItems->SelectItem(nm.c_str()); + /*if (pref){ + m_ObjectItems->SelectItem(pref); + }*/ +} +//------------------------------------------------------------------------------ diff --git a/src/editors/ActorEditor/UI_ActorToolsUndo.cpp b/src/editors/ActorEditor/UI_ActorToolsUndo.cpp new file mode 100644 index 00000000000..48434ae819a --- /dev/null +++ b/src/editors/ActorEditor/UI_ActorToolsUndo.cpp @@ -0,0 +1,96 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "UI_ActorTools.h" + +void CActorTools::UndoClear() +{ + while (!m_RedoStack.empty()) + { + unlink(m_RedoStack.back().m_FileName); + m_RedoStack.pop_back(); + } + while (!m_UndoStack.empty()) + { + unlink(m_UndoStack.back().m_FileName); + m_UndoStack.pop_back(); + } +} + +void CActorTools::UndoSave() +{ + UI->RedrawScene(); + if (0 == EPrefs->scene_undo_level) + return; + + UndoItem item; + item.m_FileName[0] = 0; + GetTempFileName(FS.get_path(_temp_)->m_Path, "undo", 0, item.m_FileName); + + Save(item.m_FileName, true); + m_UndoStack.push_back(item); + + while (!m_RedoStack.empty()) + { + unlink(m_RedoStack.back().m_FileName); + m_RedoStack.pop_back(); + } + + if (m_UndoStack.size() > EPrefs->scene_undo_level) + { + unlink(m_UndoStack.front().m_FileName); + m_UndoStack.pop_front(); + } +} + +bool CActorTools::Undo() +{ + // if( !m_UndoStack.empty() ){ + if (m_UndoStack.size() > 1) + { + m_RedoStack.push_back(m_UndoStack.back()); + m_UndoStack.pop_back(); + + if (m_RedoStack.size() > EPrefs->scene_undo_level) + { + unlink(m_RedoStack.front().m_FileName); + m_RedoStack.pop_front(); + } + + if (!m_UndoStack.empty()) + { + Clear(); + Load(m_UndoStack.back().m_FileName); + } + + Modified(); + + return true; + } + return false; +} + +bool CActorTools::Redo() +{ + if (!m_RedoStack.empty()) + { + Clear(); + Load(m_RedoStack.back().m_FileName); + + m_UndoStack.push_back(m_RedoStack.back()); + m_RedoStack.pop_back(); + + if (m_UndoStack.size() > EPrefs->scene_undo_level) + { + unlink(m_UndoStack.front().m_FileName); + m_UndoStack.pop_front(); + } + + Modified(); + + return true; + } + return false; +} + +//---------------------------------------------------- diff --git a/src/editors/ActorEditor/imgui.ini b/src/editors/ActorEditor/imgui.ini new file mode 100644 index 00000000000..f5b94e9afcc --- /dev/null +++ b/src/editors/ActorEditor/imgui.ini @@ -0,0 +1,120 @@ +[Window][DockSpaceViewport_11111111] +Pos=0,22 +Size=1920,995 +Collapsed=0 + +[Window][Debug##Default] +Pos=60,60 +Size=400,400 +Collapsed=0 + +[Window][MainBar] +Pos=0,22 +Size=1511,34 +Collapsed=0 +DockId=0x00000003,0 + +[Window][LeftBar] +Pos=17,43 +Size=15,9 +Collapsed=0 +DockId=0x00000002,1 + +[Window][Dear ImGui Demo] +Pos=17,43 +Size=15,9 +Collapsed=0 +DockId=0x00000002,0 + +[Window][Render] +Pos=0,43 +Size=15,9 +Collapsed=0 +DockId=0x00000001,0 + +[Window][test] +Pos=961,54 +Size=403,707 +Collapsed=0 +DockId=0x00000003,1 + +[Window][Example: Console] +Pos=-394,453 +Size=1920,303 +Collapsed=0 + +[Window][Example: Log] +Pos=1371,57 +Size=549,960 +Collapsed=0 +DockId=0x8B93E3BD,2 + +[Window][Example: Property editor] +Pos=526,91 +Size=380,707 +Collapsed=0 + +[Window][Example: Long text display] +Pos=60,60 +Size=519,600 +Collapsed=0 + +[Window][Example: Custom rendering] +Pos=404,178 +Size=466,391 +Collapsed=0 + +[Window][DockSpace Demo] +Pos=0,22 +Size=1920,995 +Collapsed=0 + +[Window][Example: Documents] +Pos=60,60 +Size=621,755 +Collapsed=0 + +[Window][Log] +Pos=0,853 +Size=1920,164 +Collapsed=0 +DockId=0x00000006,0 + +[Window][Editor Preferences] +Pos=645,202 +Size=466,288 +Collapsed=0 + +[Window][Master DockSpace] +Pos=0,24 +Size=32,32 +Collapsed=0 + +[Window][Example: Simple layout] +Pos=60,60 +Size=500,440 +Collapsed=0 + +[Window][Example: Auto-resizing window] +Pos=60,60 +Size=361,512 +Collapsed=0 + +[Window][KeyForm] +Pos=0,54 +Size=32,2 +Collapsed=0 +DockId=0x00000009,0 + +[Docking][Data] +DockSpace ID=0x785F377C Window=0xF9A24255 Pos=0,43 Size=32,13 Split=Y Selected=0x93F09C5C + DockNode ID=0x00000007 Parent=0x785F377C SizeRef=1920,832 Split=Y + DockNode ID=0x00000005 Parent=0x00000007 SizeRef=1920,805 Split=X + DockNode ID=0x00000001 Parent=0x00000005 SizeRef=1550,971 CentralNode=1 Selected=0x93F09C5C + DockNode ID=0x00000002 Parent=0x00000005 SizeRef=368,971 Selected=0xE927CF2F + DockNode ID=0x00000006 Parent=0x00000007 SizeRef=1920,164 Selected=0xB7722E25 + DockNode ID=0x00000009 Parent=0x785F377C SizeRef=1920,137 Selected=0xA4656FC7 +DockSpace ID=0x8B93E3BD Pos=0,22 Size=1920,995 Split=Y Selected=0xE927CF2F + DockNode ID=0x00000003 Parent=0x8B93E3BD SizeRef=1270,34 HiddenTabBar=1 Selected=0x8530916C + DockNode ID=0x00000004 Parent=0x8B93E3BD SizeRef=1270,767 CentralNode=1 Selected=0x93F09C5C + diff --git a/src/editors/ActorEditor/imgui_impl_dx9.cpp b/src/editors/ActorEditor/imgui_impl_dx9.cpp new file mode 100644 index 00000000000..c2f83dc8d8c --- /dev/null +++ b/src/editors/ActorEditor/imgui_impl_dx9.cpp @@ -0,0 +1,306 @@ +// dear imgui: Renderer for DirectX9 +// This needs to be used along with a Platform Binding (e.g. Win32) + +// Implemented features: +// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. +// https://github.com/ocornut/imgui + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. +// 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. +// 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). +// 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288. +// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. +// 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example. +// 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. +// 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud. +// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself. +// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. + +#include "imgui_impl_dx9.h" + +// DirectX +#include +#define DIRECTINPUT_VERSION 0x0800 +#include + +// DirectX data +static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; +static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; +static LPDIRECT3DINDEXBUFFER9 g_pIB = NULL; +static LPDIRECT3DTEXTURE9 g_FontTexture = NULL; +static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000; + +struct CUSTOMVERTEX +{ + float pos[3]; + D3DCOLOR col; + float uv[2]; +}; +#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1) + +static void ImGui_ImplDX9_SetupRenderState(ImDrawData *draw_data) +{ + // Setup viewport + D3DVIEWPORT9 vp; + vp.X = vp.Y = 0; + vp.Width = (DWORD)draw_data->DisplaySize.x; + vp.Height = (DWORD)draw_data->DisplaySize.y; + vp.MinZ = 0.0f; + vp.MaxZ = 1.0f; + g_pd3dDevice->SetViewport(&vp); + + // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient) + g_pd3dDevice->SetPixelShader(NULL); + g_pd3dDevice->SetVertexShader(NULL); + g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); + g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE); + g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE); + g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); + g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); + g_pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); + g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); + g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); + g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE); + g_pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); + g_pd3dDevice->SetRenderState(D3DRS_FOGENABLE, FALSE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); + g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); + g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); + + // Setup orthographic projection matrix + // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. + // Being agnostic of whether or can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH() + { + float L = draw_data->DisplayPos.x + 0.5f; + float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f; + float T = draw_data->DisplayPos.y + 0.5f; + float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f; + D3DMATRIX mat_identity = {{{1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}}}; + D3DMATRIX mat_projection = + {{{2.0f / (R - L), 0.0f, 0.0f, 0.0f, + 0.0f, 2.0f / (T - B), 0.0f, 0.0f, + 0.0f, 0.0f, 0.5f, 0.0f, + (L + R) / (L - R), (T + B) / (B - T), 0.5f, 1.0f}}}; + g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity); + g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity); + g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection); + } +} + +// Render function. +// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) +void ImGui_ImplDX9_RenderDrawData(ImDrawData *draw_data) +{ + // Avoid rendering when minimized + if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) + return; + + // Create and grow buffers if needed + if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount) + { + if (g_pVB) + { + g_pVB->Release(); + g_pVB = NULL; + } + g_VertexBufferSize = draw_data->TotalVtxCount + 5000; + if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0) + return; + } + if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount) + { + if (g_pIB) + { + g_pIB->Release(); + g_pIB = NULL; + } + g_IndexBufferSize = draw_data->TotalIdxCount + 10000; + if (g_pd3dDevice->CreateIndexBuffer(g_IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &g_pIB, NULL) < 0) + return; + } + + // Backup the DX9 state + IDirect3DStateBlock9 *d3d9_state_block = NULL; + if (g_pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0) + return; + + // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to) + D3DMATRIX last_world, last_view, last_projection; + g_pd3dDevice->GetTransform(D3DTS_WORLD, &last_world); + g_pd3dDevice->GetTransform(D3DTS_VIEW, &last_view); + g_pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection); + + // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format. + // FIXME-OPT: This is a waste of resource, the ideal is to use imconfig.h and + // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR + // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; } + CUSTOMVERTEX *vtx_dst; + ImDrawIdx *idx_dst; + if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void **)&vtx_dst, D3DLOCK_DISCARD) < 0) + return; + if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void **)&idx_dst, D3DLOCK_DISCARD) < 0) + return; + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList *cmd_list = draw_data->CmdLists[n]; + const ImDrawVert *vtx_src = cmd_list->VtxBuffer.Data; + for (int i = 0; i < cmd_list->VtxBuffer.Size; i++) + { + vtx_dst->pos[0] = vtx_src->pos.x; + vtx_dst->pos[1] = vtx_src->pos.y; + vtx_dst->pos[2] = 0.0f; + vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000) >> 16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9 + vtx_dst->uv[0] = vtx_src->uv.x; + vtx_dst->uv[1] = vtx_src->uv.y; + vtx_dst++; + vtx_src++; + } + memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + idx_dst += cmd_list->IdxBuffer.Size; + } + g_pVB->Unlock(); + g_pIB->Unlock(); + g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX)); + g_pd3dDevice->SetIndices(g_pIB); + g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX); + + // Setup desired DX state + ImGui_ImplDX9_SetupRenderState(draw_data); + + // Render command lists + // (Because we merged all buffers into a single one, we maintain our own offset into them) + int global_vtx_offset = 0; + int global_idx_offset = 0; + ImVec2 clip_off = draw_data->DisplayPos; + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList *cmd_list = draw_data->CmdLists[n]; + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd *pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback != NULL) + { + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplDX9_SetupRenderState(draw_data); + else + pcmd->UserCallback(cmd_list, pcmd); + } + else + { + const RECT r = {(LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y)}; + const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->TextureId; + g_pd3dDevice->SetTexture(0, texture); + g_pd3dDevice->SetScissorRect(&r); + g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3); + } + } + global_idx_offset += cmd_list->IdxBuffer.Size; + global_vtx_offset += cmd_list->VtxBuffer.Size; + } + + // Restore the DX9 transform + g_pd3dDevice->SetTransform(D3DTS_WORLD, &last_world); + g_pd3dDevice->SetTransform(D3DTS_VIEW, &last_view); + g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection); + + // Restore the DX9 state + d3d9_state_block->Apply(); + d3d9_state_block->Release(); +} + +bool ImGui_ImplDX9_Init(IDirect3DDevice9 *device) +{ + // Setup back-end capabilities flags + ImGuiIO &io = ImGui::GetIO(); + io.BackendRendererName = "imgui_impl_dx9"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + + g_pd3dDevice = device; + g_pd3dDevice->AddRef(); + return true; +} + +void ImGui_ImplDX9_Shutdown() +{ + ImGui_ImplDX9_InvalidateDeviceObjects(); + if (g_pd3dDevice) + { + g_pd3dDevice->Release(); + g_pd3dDevice = NULL; + } +} + +static bool ImGui_ImplDX9_CreateFontsTexture() +{ + // Build texture atlas + ImGuiIO &io = ImGui::GetIO(); + unsigned char *pixels; + int width, height, bytes_per_pixel; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel); + + // Upload texture to graphics system + g_FontTexture = NULL; + if (g_pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_FontTexture, NULL) < 0) + return false; + D3DLOCKED_RECT tex_locked_rect; + if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK) + return false; + for (int y = 0; y < height; y++) + memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel)); + g_FontTexture->UnlockRect(0); + + // Store our identifier + io.Fonts->TexID = (ImTextureID)g_FontTexture; + + return true; +} + +bool ImGui_ImplDX9_CreateDeviceObjects() +{ + if (!g_pd3dDevice) + return false; + if (!ImGui_ImplDX9_CreateFontsTexture()) + return false; + return true; +} + +void ImGui_ImplDX9_InvalidateDeviceObjects() +{ + if (!g_pd3dDevice) + return; + if (g_pVB) + { + g_pVB->Release(); + g_pVB = NULL; + } + if (g_pIB) + { + g_pIB->Release(); + g_pIB = NULL; + } + if (g_FontTexture) + { + g_FontTexture->Release(); + g_FontTexture = NULL; + ImGui::GetIO().Fonts->TexID = NULL; + } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. +} + +void ImGui_ImplDX9_NewFrame() +{ + if (!g_FontTexture) + ImGui_ImplDX9_CreateDeviceObjects(); +} diff --git a/src/editors/ActorEditor/imgui_impl_dx9.h b/src/editors/ActorEditor/imgui_impl_dx9.h new file mode 100644 index 00000000000..23018c683ef --- /dev/null +++ b/src/editors/ActorEditor/imgui_impl_dx9.h @@ -0,0 +1,24 @@ +// dear imgui: Renderer for DirectX9 +// This needs to be used along with a Platform Binding (e.g. Win32) + +// Implemented features: +// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. +// https://github.com/ocornut/imgui + +#pragma once +#include "..\xrEUI\stdafx.h" // IMGUI_IMPL_API + +struct IDirect3DDevice9; + +IMGUI_IMPL_API bool ImGui_ImplDX9_Init(IDirect3DDevice9 *device); +IMGUI_IMPL_API void ImGui_ImplDX9_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplDX9_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData *draw_data); + +// Use if you want to reset your rendering device without losing Dear ImGui state. +IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); diff --git a/src/editors/ActorEditor/imgui_log.txt b/src/editors/ActorEditor/imgui_log.txt new file mode 100644 index 00000000000..23b023ee33c --- /dev/null +++ b/src/editors/ActorEditor/imgui_log.txt @@ -0,0 +1,33 @@ +You can also call ImGui::LogText() to output directly to the log without a visual output. +Copy "Hello, world!" to clipboard + +## Window options ## + +## Widgets ## + +## Layout ## + +## Popups & Modal windows ## + +## Columns ## + +## Filtering ## + +## Inputs, Navigation & Focus ## +You can also call ImGui::LogText() to output directly to the log without a visual output. +Copy "Hello, world!" to clipboard + +## Window options ## + +## Widgets ## + +## Layout ## + +## Popups & Modal windows ## + +## Columns ## + +## Filtering ## + +## Inputs, Navigation & Focus ## test +hello world! diff --git a/src/editors/ActorEditor/main.cpp b/src/editors/ActorEditor/main.cpp new file mode 100644 index 00000000000..f432d285a42 --- /dev/null +++ b/src/editors/ActorEditor/main.cpp @@ -0,0 +1,231 @@ +// dear imgui: standalone example application for DirectX 9 +// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +#include "..\xrEProps\stdafx.h" +#include "imgui_impl_dx9.h" +#include "imgui_impl_win32.h" +#include +#define DIRECTINPUT_VERSION 0x0800 +#include +#include +#include "UITest.h" +// Data +static LPDIRECT3D9 g_pD3D = NULL; +static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; +static D3DPRESENT_PARAMETERS g_d3dpp = {}; + +// Forward declarations of helper functions +bool CreateDeviceD3D(HWND hWnd); +void CleanupDeviceD3D(); +void ResetDevice(); +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +// Main code + +// Create application window +/* WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; + ::RegisterClassEx(&wc); + HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX9 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); + + // Initialize Direct3D + if (!CreateDeviceD3D(hwnd)) + { + CleanupDeviceD3D(); + ::UnregisterClass(wc.lpszClassName, wc.hInstance); + return 1; + } + + // Show the window + ::ShowWindow(hwnd, SW_SHOWDEFAULT); + ::UpdateWindow(hwnd); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls +//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking + io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsClassic(); + + // Setup Platform/Renderer bindings + ImGui_ImplWin32_Init(hwnd); + ImGui_ImplDX9_Init(g_pd3dDevice); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Read 'docs/FONTS.txt' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != NULL); + + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + xrUIManager UIManager; + UIManager.Push(xr_new()); + /* + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + // Main loop + MSG msg; + xr_string test; + UIManager.Push(xr_new< UITextForm>(&test)); + + Fvector Temp, Min, Max; + Min.set(-10, -10, -10); + Max.set(10, 10, 10); + UIManager.Push(xr_new< UINumericVectorForm>("test vector",&Temp, &Temp,5,&Min,&Max)); + + UIPropertiesListForm PropertiesList("test"); + UIManager.Push(&PropertiesList, false); + PropItemVec props; + u32 test1=0; + float test2=10.f; + PHelper().CreateU32(props, "Keybar\\show footsteps 12", &test1,-90,1000); + PHelper().CreateFloat(props, "Keybar\\show footsteps 34", &test2,-1,900); + PropertiesList.AssignItems(props); + ZeroMemory(&msg, sizeof(msg)); + while (msg.message != WM_QUIT) + { + // Poll and handle messages (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) + { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + continue; + } + + // Start the Dear ImGui frame + ImGui_ImplDX9_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); + + ImGui::DockSpaceOverViewport(); + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + UIManager.Draw(); + + // Rendering + ImGui::EndFrame(); + g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE); + g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); + g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE); + D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f)); + g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); + if (g_pd3dDevice->BeginScene() >= 0) + { + ImGui::Render(); + ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData()); + g_pd3dDevice->EndScene(); + } + HRESULT result = g_pd3dDevice->Present(NULL, NULL, NULL, NULL); + + // Handle loss of D3D9 device + if (result == D3DERR_DEVICELOST && g_pd3dDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET) + ResetDevice(); + } + + ImGui_ImplDX9_Shutdown(); + ImGui_ImplWin32_Shutdown(); + ImGui::DestroyContext(); + + CleanupDeviceD3D(); + ::DestroyWindow(hwnd); + ::UnregisterClass(wc.lpszClassName, wc.hInstance); + */ + +// Helper functions + +bool CreateDeviceD3D(HWND hWnd) +{ + if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) + return false; + + // Create the D3DDevice + ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); + g_d3dpp.Windowed = TRUE; + g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; + g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; + g_d3dpp.EnableAutoDepthStencil = TRUE; + g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; + g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync + // g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate + if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) + return false; + + return true; +} + +void CleanupDeviceD3D() +{ + if (g_pd3dDevice) + { + g_pd3dDevice->Release(); + g_pd3dDevice = NULL; + } + if (g_pD3D) + { + g_pD3D->Release(); + g_pD3D = NULL; + } +} + +void ResetDevice() +{ + ImGui_ImplDX9_InvalidateDeviceObjects(); + HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); + if (hr == D3DERR_INVALIDCALL) + IM_ASSERT(0); + ImGui_ImplDX9_CreateDeviceObjects(); +} + +// Forward declare message handler from imgui_impl_win32.cpp +extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +// Win32 message handler +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + switch (msg) + { + case WM_SIZE: + if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) + { + g_d3dpp.BackBufferWidth = LOWORD(lParam); + g_d3dpp.BackBufferHeight = HIWORD(lParam); + ResetDevice(); + } + return 0; + case WM_SYSCOMMAND: + if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu + return 0; + break; + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; + } + return ::DefWindowProc(hWnd, msg, wParam, lParam); +} diff --git a/src/editors/ActorEditor/resources/ActorEditor.rc b/src/editors/ActorEditor/resources/ActorEditor.rc new file mode 100644 index 00000000000..95d2c4986f2 --- /dev/null +++ b/src/editors/ActorEditor/resources/ActorEditor.rc @@ -0,0 +1,71 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// () resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_RUS) +LANGUAGE LANG_RUSSIAN, SUBLANG_DEFAULT +#pragma code_page(1251) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +MAINICON ICON "ae.ico" + +#endif // () resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/editors/ActorEditor/resources/ae.ico b/src/editors/ActorEditor/resources/ae.ico new file mode 100644 index 00000000000..3d8dbe8c981 Binary files /dev/null and b/src/editors/ActorEditor/resources/ae.ico differ diff --git a/src/editors/ActorEditor/resources/resource.h b/src/editors/ActorEditor/resources/resource.h new file mode 100644 index 00000000000..7b44dacdff1 --- /dev/null +++ b/src/editors/ActorEditor/resources/resource.h @@ -0,0 +1,17 @@ +//{{NO_DEPENDENCIES}} +// , Microsoft Visual C++. +// ActorEditor.rc +// +#define IDI_ICON1 101 +#define MAINICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/editors/ActorEditor/stdafx.h b/src/editors/ActorEditor/stdafx.h new file mode 100644 index 00000000000..968af200c4d --- /dev/null +++ b/src/editors/ActorEditor/stdafx.h @@ -0,0 +1,18 @@ +#pragma once +#include "..\xrECore\stdafx.h" +#include "..\xrECore\Editor\device.h" +#include "..\xrECore\Editor\UI_MainCommand.h" +#include "..\xrECore\Editor\UI_ToolsCustom.h" +#include "..\xrECore\Editor\ui_main.h" +#include "..\xrECore\Editor\EditorPreferences.h" +#include "..\xrECore\Editor\render.h" +#include "..\xrECore\Editor\UIRenderForm.h" +#include "..\xrECore\Editor\ELog.h" +#include "UITopBarForm.h" +#include "UIMainMenuForm.h" +#include "UILeftBarForm.h" +#include "UIKeyForm.h" +#include "UIBoneForm.h" +#include "UIMainForm.h" +#include "UI_ActorMain.h" +#include "UI_ActorTools.h" diff --git a/src/editors/FreeMagic/FreeMagic.vcxproj b/src/editors/FreeMagic/FreeMagic.vcxproj new file mode 100644 index 00000000000..c5e82085ec9 --- /dev/null +++ b/src/editors/FreeMagic/FreeMagic.vcxproj @@ -0,0 +1,110 @@ + + + + + + + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340} + FreeMagic + + + + + + + StaticLibrary + + + + + + + + + + + + NotUsing + FREEMAGIC_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/editors/FreeMagic/FreeMagic.vcxproj.filters b/src/editors/FreeMagic/FreeMagic.vcxproj.filters new file mode 100644 index 00000000000..98aefcf1a12 --- /dev/null +++ b/src/editors/FreeMagic/FreeMagic.vcxproj.filters @@ -0,0 +1,224 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + \ No newline at end of file diff --git a/src/editors/FreeMagic/MagicFMLibType.h b/src/editors/FreeMagic/MagicFMLibType.h new file mode 100644 index 00000000000..c444dd7e86d --- /dev/null +++ b/src/editors/FreeMagic/MagicFMLibType.h @@ -0,0 +1,87 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MAGICFMLIBTYPE_H +#define MAGICFMLIBTYPE_H + +// Windows platform +#ifdef WIN32 + +// For the DLL library. +#ifdef MAGICFMDLL_EXPORTS +#define MAGICFM __declspec(dllexport) + +// For a client of the DLL library. +#else +#ifdef MAGICFMDLL_IMPORTS +#define MAGICFM __declspec(dllimport) + +// For the static library. +#else +#define MAGICFM + +#endif +#endif + +// Disable warning C4251. Template classes cannot be exported for the obvious +// reason that the code is not generated until an instance of the class is +// declared. With this warning enabled, you get many complaints about class +// data members that are of template type. +// +// When developing the DLL code, you should enable the warning to catch places +// where you should have used MAGICFM. For example, nested classes and friend +// functions should be tagged with this macro. +#pragma warning(disable : 4251) + +// Disable warning C4275: "non dll-interface class 'someClass' used as base +// for dll-interface class 'anotherClass'. The only time this warning occurs +// in the DLL projects is when compiling MgcBinary2D, a class derived from +// a template class. The DLL library works fine, so I disabled the warning. +// You might want to enable it if you want to catch base classes that are +// non-template and non-dll-interface when the derived class is dll-interface. +#pragma warning(disable : 4275) + +// Disable warning C4514. "unreferenced inline function has been removed" +// This occurs a lot when you increase the warning level to 4. +#pragma warning(disable : 4514) + +// Disable warning C4127: "conditional expression is constant" +// A few loops are controlled by "while (true) { 'break' somewhere }". +#pragma warning(disable : 4127) + +// Disable warning C4097: "typedef-name 'someType' used as synonym for +// class-name 'someTemplateType'. Occurs when a base class for a derived +// class is a typedef'd name for a template type. This only occurs when +// compiling MgcBinary2D. +#pragma warning(disable : 4097) + +// Disable the warning about truncating the debug names to 255 characters. +// This warning shows up often with STL code. +#pragma warning(disable : 4786) + +// Warning C4702: "unreachable code". This is incorrectly generated at +// Level 4 warnings in Release builds in the following situation: +// +// ret_type Function () +// { +// if ( condition ) +// return a_value; +// else +// return another_value; +// } <-- line at which the compiler complains + +// Linux platform +#else +#define MAGICFM +#endif + +#endif diff --git a/src/editors/FreeMagic/MgcAppr3DGaussPointsFit.cpp b/src/editors/FreeMagic/MgcAppr3DGaussPointsFit.cpp new file mode 100644 index 00000000000..addf07d3d72 --- /dev/null +++ b/src/editors/FreeMagic/MgcAppr3DGaussPointsFit.cpp @@ -0,0 +1,150 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +#pragma hdrstop +#include "MgcEigen.h" +#include "MgcAppr3DGaussPointsFit.h" +using namespace Mgc; + +//---------------------------------------------------------------------------- +void Mgc::GaussPointsFit(int iQuantity, const Vector3 *akPoint, + Vector3 &rkCenter, Vector3 akAxis[3], Real afExtent[3]) +{ + // compute mean of points + rkCenter = akPoint[0]; + int i; + for (i = 1; i < iQuantity; i++) + rkCenter += akPoint[i]; + Real fInvQuantity = 1.0f / iQuantity; + rkCenter *= fInvQuantity; + + // compute covariances of points + Real fSumXX = 0.0f, fSumXY = 0.0f, fSumXZ = 0.0f; + Real fSumYY = 0.0f, fSumYZ = 0.0f, fSumZZ = 0.0f; + for (i = 0; i < iQuantity; i++) + { + Vector3 kDiff = akPoint[i] - rkCenter; + fSumXX += kDiff.x * kDiff.x; + fSumXY += kDiff.x * kDiff.y; + fSumXZ += kDiff.x * kDiff.z; + fSumYY += kDiff.y * kDiff.y; + fSumYZ += kDiff.y * kDiff.z; + fSumZZ += kDiff.z * kDiff.z; + } + fSumXX *= fInvQuantity; + fSumXY *= fInvQuantity; + fSumXZ *= fInvQuantity; + fSumYY *= fInvQuantity; + fSumYZ *= fInvQuantity; + fSumZZ *= fInvQuantity; + + // compute eigenvectors for covariance matrix + Eigen kES(3); + kES.Matrix(0, 0) = fSumXX; + kES.Matrix(0, 1) = fSumXY; + kES.Matrix(0, 2) = fSumXZ; + kES.Matrix(1, 0) = fSumXY; + kES.Matrix(1, 1) = fSumYY; + kES.Matrix(1, 2) = fSumYZ; + kES.Matrix(2, 0) = fSumXZ; + kES.Matrix(2, 1) = fSumYZ; + kES.Matrix(2, 2) = fSumZZ; + kES.IncrSortEigenStuff3(); + + akAxis[0].x = kES.GetEigenvector(0, 0); + akAxis[0].y = kES.GetEigenvector(1, 0); + akAxis[0].z = kES.GetEigenvector(2, 0); + akAxis[1].x = kES.GetEigenvector(0, 1); + akAxis[1].y = kES.GetEigenvector(1, 1); + akAxis[1].z = kES.GetEigenvector(2, 1); + akAxis[2].x = kES.GetEigenvector(0, 2); + akAxis[2].y = kES.GetEigenvector(1, 2); + akAxis[2].z = kES.GetEigenvector(2, 2); + + afExtent[0] = kES.GetEigenvalue(0); + afExtent[1] = kES.GetEigenvalue(1); + afExtent[2] = kES.GetEigenvalue(2); +} +//---------------------------------------------------------------------------- +bool Mgc::GaussPointsFit(int iQuantity, const Vector3 *akPoint, + const bool *abValid, Vector3 &rkCenter, Vector3 akAxis[3], + Real afExtent[3]) +{ + // compute mean of points + rkCenter = Vector3::ZERO; + int i, iValidQuantity = 0; + for (i = 0; i < iQuantity; i++) + { + if (abValid[i]) + { + rkCenter += akPoint[i]; + iValidQuantity++; + } + } + if (iValidQuantity == 0) + return false; + + Real fInvQuantity = 1.0f / iValidQuantity; + rkCenter *= fInvQuantity; + + // compute covariances of points + Real fSumXX = 0.0f, fSumXY = 0.0f, fSumXZ = 0.0f; + Real fSumYY = 0.0f, fSumYZ = 0.0f, fSumZZ = 0.0f; + for (i = 0; i < iQuantity; i++) + { + if (abValid[i]) + { + Vector3 kDiff = akPoint[i] - rkCenter; + fSumXX += kDiff.x * kDiff.x; + fSumXY += kDiff.x * kDiff.y; + fSumXZ += kDiff.x * kDiff.z; + fSumYY += kDiff.y * kDiff.y; + fSumYZ += kDiff.y * kDiff.z; + fSumZZ += kDiff.z * kDiff.z; + } + } + fSumXX *= fInvQuantity; + fSumXY *= fInvQuantity; + fSumXZ *= fInvQuantity; + fSumYY *= fInvQuantity; + fSumYZ *= fInvQuantity; + fSumZZ *= fInvQuantity; + + // compute eigenvectors for covariance matrix + Eigen kES(3); + kES.Matrix(0, 0) = fSumXX; + kES.Matrix(0, 1) = fSumXY; + kES.Matrix(0, 2) = fSumXZ; + kES.Matrix(1, 0) = fSumXY; + kES.Matrix(1, 1) = fSumYY; + kES.Matrix(1, 2) = fSumYZ; + kES.Matrix(2, 0) = fSumXZ; + kES.Matrix(2, 1) = fSumYZ; + kES.Matrix(2, 2) = fSumZZ; + kES.IncrSortEigenStuff3(); + + akAxis[0].x = kES.GetEigenvector(0, 0); + akAxis[0].y = kES.GetEigenvector(1, 0); + akAxis[0].z = kES.GetEigenvector(2, 0); + akAxis[1].x = kES.GetEigenvector(0, 1); + akAxis[1].y = kES.GetEigenvector(1, 1); + akAxis[1].z = kES.GetEigenvector(2, 1); + akAxis[2].x = kES.GetEigenvector(0, 2); + akAxis[2].y = kES.GetEigenvector(1, 2); + akAxis[2].z = kES.GetEigenvector(2, 2); + + afExtent[0] = kES.GetEigenvalue(0); + afExtent[1] = kES.GetEigenvalue(1); + afExtent[2] = kES.GetEigenvalue(2); + + return true; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcAppr3DGaussPointsFit.h b/src/editors/FreeMagic/MgcAppr3DGaussPointsFit.h new file mode 100644 index 00000000000..f088c3bb74b --- /dev/null +++ b/src/editors/FreeMagic/MgcAppr3DGaussPointsFit.h @@ -0,0 +1,37 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCAPPR3DGAUSSPOINTSFIT_H +#define MGCAPPR3DGAUSSPOINTSFIT_H + +// Fit points with a Gaussian distribution. The center is the mean of the +// points, the axes are the eigenvectors of the covariance matrix, and the +// extents are the eigenvalues of the covariance matrix and are returned in +// increasing order. The last function allows selection of valid vertices +// from a pool. The return value is 'true' if and only if at least one +// vertex was valid. + +#include "MgcVector3.h" + +namespace Mgc +{ + + MAGICFM void GaussPointsFit(int iQuantity, const Vector3 *akPoint, + Vector3 &rkCenter, Vector3 akAxis[3], Real afExtent[3]); + + MAGICFM bool GaussPointsFit(int iQuantity, const Vector3 *akPoint, + const bool *abValid, Vector3 &rkCenter, Vector3 akAxis[3], + Real afExtent[3]); + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcAppr3DLineFit.cpp b/src/editors/FreeMagic/MgcAppr3DLineFit.cpp new file mode 100644 index 00000000000..4856996101a --- /dev/null +++ b/src/editors/FreeMagic/MgcAppr3DLineFit.cpp @@ -0,0 +1,123 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#include "MgcEigen.h" +#include "MgcAppr3DLineFit.h" +using namespace Mgc; + +//---------------------------------------------------------------------------- +void Mgc::OrthogonalLineFit(int iQuantity, const Vector3 *akPoint, + Vector3 &rkOffset, Vector3 &rkDirection) +{ + // compute average of points + rkOffset = akPoint[0]; + int i; + for (i = 1; i < iQuantity; i++) + rkOffset += akPoint[i]; + Real fInvQuantity = 1.0f / iQuantity; + rkOffset *= fInvQuantity; + + // compute sums of products + Real fSumXX = 0.0f, fSumXY = 0.0f, fSumXZ = 0.0f; + Real fSumYY = 0.0f, fSumYZ = 0.0f, fSumZZ = 0.0f; + for (i = 0; i < iQuantity; i++) + { + Vector3 kDiff = akPoint[i] - rkOffset; + fSumXX += kDiff.x * kDiff.x; + fSumXY += kDiff.x * kDiff.y; + fSumXZ += kDiff.x * kDiff.z; + fSumYY += kDiff.y * kDiff.y; + fSumYZ += kDiff.y * kDiff.z; + fSumZZ += kDiff.z * kDiff.z; + } + + // setup the eigensolver + Eigen kES(3); + kES.Matrix(0, 0) = fSumYY + fSumZZ; + kES.Matrix(0, 1) = -fSumXY; + kES.Matrix(0, 2) = -fSumXZ; + kES.Matrix(1, 0) = kES.Matrix(0, 1); + kES.Matrix(1, 1) = fSumXX + fSumZZ; + kES.Matrix(1, 2) = -fSumYZ; + kES.Matrix(2, 0) = kES.Matrix(0, 2); + kES.Matrix(2, 1) = kES.Matrix(1, 2); + kES.Matrix(2, 2) = fSumXX + fSumYY; + + // compute eigenstuff, smallest eigenvalue is in last position + kES.DecrSortEigenStuff3(); + + // unit-length direction for best-fit line + rkDirection.x = kES.GetEigenvector(0, 2); + rkDirection.y = kES.GetEigenvector(1, 2); + rkDirection.z = kES.GetEigenvector(2, 2); +} +//---------------------------------------------------------------------------- +bool Mgc::OrthogonalLineFit(int iQuantity, const Vector3 *akPoint, + const bool *abValid, Vector3 &rkOffset, Vector3 &rkDirection) +{ + // compute average of points + rkOffset = Vector3::ZERO; + int i, iValidQuantity = 0; + for (i = 0; i < iQuantity; i++) + { + if (abValid[i]) + { + rkOffset += akPoint[i]; + iValidQuantity++; + } + } + if (iValidQuantity == 0) + return false; + + Real fInvQuantity = 1.0f / iQuantity; + rkOffset *= fInvQuantity; + + // compute sums of products + Real fSumXX = 0.0f, fSumXY = 0.0f, fSumXZ = 0.0f; + Real fSumYY = 0.0f, fSumYZ = 0.0f, fSumZZ = 0.0f; + for (i = 0; i < iQuantity; i++) + { + if (abValid[i]) + { + Vector3 kDiff = akPoint[i] - rkOffset; + fSumXX += kDiff.x * kDiff.x; + fSumXY += kDiff.x * kDiff.y; + fSumXZ += kDiff.x * kDiff.z; + fSumYY += kDiff.y * kDiff.y; + fSumYZ += kDiff.y * kDiff.z; + fSumZZ += kDiff.z * kDiff.z; + } + } + + // setup the eigensolver + Eigen kES(3); + kES.Matrix(0, 0) = fSumYY + fSumZZ; + kES.Matrix(0, 1) = -fSumXY; + kES.Matrix(0, 2) = -fSumXZ; + kES.Matrix(1, 0) = kES.Matrix(0, 1); + kES.Matrix(1, 1) = fSumXX + fSumZZ; + kES.Matrix(1, 2) = -fSumYZ; + kES.Matrix(2, 0) = kES.Matrix(0, 2); + kES.Matrix(2, 1) = kES.Matrix(1, 2); + kES.Matrix(2, 2) = fSumXX + fSumYY; + + // compute eigenstuff, smallest eigenvalue is in last position + kES.DecrSortEigenStuff3(); + + // unit-length direction for best-fit line + rkDirection.x = kES.GetEigenvector(0, 2); + rkDirection.y = kES.GetEigenvector(1, 2); + rkDirection.z = kES.GetEigenvector(2, 2); + + return true; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcAppr3DLineFit.h b/src/editors/FreeMagic/MgcAppr3DLineFit.h new file mode 100644 index 00000000000..f7fd73e7885 --- /dev/null +++ b/src/editors/FreeMagic/MgcAppr3DLineFit.h @@ -0,0 +1,36 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCAPPR3DLINEFIT_H +#define MGCAPPR3DLINEFIT_H + +#include "MgcVector3.h" + +namespace Mgc +{ + + // Least-squares fit of a line to (x,y,z) data by using distance measurements + // orthogonal to the proposed line. The resulting line is represented by + // Offset + t*Direction where the returned direction is a unit-length vector. + + MAGICFM void OrthogonalLineFit(int iQuantity, const Vector3 *akPoint, + Vector3 &rkOffset, Vector3 &rkDirection); + + // This function allows for selection of vertices from a pool. The return + // value is 'true' if and only if at least one vertex is valid. + + MAGICFM bool OrthogonalLineFit(int iQuantity, const Vector3 *akPoint, + const bool *abValid, Vector3 &rkOffset, Vector3 &rkDirection); + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcAppr3DPlaneFit.cpp b/src/editors/FreeMagic/MgcAppr3DPlaneFit.cpp new file mode 100644 index 00000000000..c8d334808b9 --- /dev/null +++ b/src/editors/FreeMagic/MgcAppr3DPlaneFit.cpp @@ -0,0 +1,126 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +//#include "stdafx.h" +#pragma hdrstop + +#include "MgcAppr3DPlaneFit.h" +#include "MgcEigen.h" +#include "MgcLinearSystem.h" +using namespace Mgc; + +//---------------------------------------------------------------------------- +bool Mgc::HeightPlaneFit(int iQuantity, Vector3 *akPoint, Real &rfA, + Real &rfB, Real &rfC) +{ + // You need at least three points to determine the plane. Even so, if + // the points are on a vertical plane, there is no least-squares fit in + // the 'height' sense. This will be trapped by the determinant of the + // coefficient matrix. + if (iQuantity < 3) + return false; + + // compute sums for linear system + Real fSumX = 0.0f, fSumY = 0.0f, fSumZ = 0.0f; + Real fSumXX = 0.0f, fSumXY = 0.0f, fSumXZ = 0.0f; + Real fSumYY = 0.0f, fSumYZ = 0.0f; + for (int i = 0; i < iQuantity; i++) + { + fSumX += akPoint[i].x; + fSumY += akPoint[i].y; + fSumZ += akPoint[i].z; + fSumXX += akPoint[i].x * akPoint[i].x; + fSumXY += akPoint[i].x * akPoint[i].y; + fSumXZ += akPoint[i].x * akPoint[i].z; + fSumYY += akPoint[i].y * akPoint[i].y; + fSumYZ += akPoint[i].y * akPoint[i].z; + } + + Real aafA[3][3] = + { + fSumXX, fSumXY, fSumX, + fSumXY, fSumYY, fSumY, + fSumX, fSumY, Real(iQuantity)}; + + Real afB[3] = + { + fSumXZ, + fSumYZ, + fSumZ}; + + Real afX[3]; + + bool bNonsingular = LinearSystem::Solve3(aafA, afB, afX); + if (bNonsingular) + { + rfA = afX[0]; + rfB = afX[1]; + rfC = afX[2]; + } + else + { + rfA = Math::MAX_REAL; + rfB = Math::MAX_REAL; + rfC = Math::MAX_REAL; + } + + return bNonsingular; +} +//---------------------------------------------------------------------------- +Real Mgc::OrthogonalPlaneFit(int iQuantity, Vector3 *akPoint, + Vector3 &rkOffset, Vector3 &rkNormal) +{ + // compute average of points + rkOffset = akPoint[0]; + int i; + for (i = 1; i < iQuantity; i++) + rkOffset += akPoint[i]; + Real fInvQuantity = 1.0f / iQuantity; + rkOffset *= fInvQuantity; + + // compute sums of products + Real fSumXX = 0.0f, fSumXY = 0.0f, fSumXZ = 0.0f; + Real fSumYY = 0.0f, fSumYZ = 0.0f, fSumZZ = 0.0f; + for (i = 0; i < iQuantity; i++) + { + Vector3 kDiff = akPoint[i] - rkOffset; + fSumXX += kDiff.x * kDiff.x; + fSumXY += kDiff.x * kDiff.y; + fSumXZ += kDiff.x * kDiff.z; + fSumYY += kDiff.y * kDiff.y; + fSumYZ += kDiff.y * kDiff.z; + fSumZZ += kDiff.z * kDiff.z; + } + + // setup the eigensolver + Eigen kES(3); + kES.Matrix(0, 0) = fSumXX; + kES.Matrix(0, 1) = fSumXY; + kES.Matrix(0, 2) = fSumXZ; + kES.Matrix(1, 0) = kES.Matrix(0, 1); + kES.Matrix(1, 1) = fSumYY; + kES.Matrix(1, 2) = fSumYZ; + kES.Matrix(2, 0) = kES.Matrix(0, 2); + kES.Matrix(2, 1) = kES.Matrix(1, 2); + kES.Matrix(2, 2) = fSumZZ; + + // compute eigenstuff, smallest eigenvalue is in last position + kES.DecrSortEigenStuff3(); + + // unit-length direction for best-fit line + rkNormal.x = kES.GetEigenvector(0, 2); + rkNormal.y = kES.GetEigenvector(1, 2); + rkNormal.z = kES.GetEigenvector(2, 2); + + // the minimum energy + return kES.GetEigenvalue(2); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcAppr3DPlaneFit.h b/src/editors/FreeMagic/MgcAppr3DPlaneFit.h new file mode 100644 index 00000000000..5a430c97c99 --- /dev/null +++ b/src/editors/FreeMagic/MgcAppr3DPlaneFit.h @@ -0,0 +1,39 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCAPPR3DPLANEFIT_H +#define MGCAPPR3DPLANEFIT_H + +#include "MgcVector3.h" + +namespace Mgc +{ + + // Least-squares fit of a plane to (x,y,f(x,y)) data by using distance + // measurements in the z-direction. The resulting plane is represented by + // z = A*x + B*y + C. The return value is 'false' if the 3x3 coefficient + // matrix in the linear system that defines A, B, and C is nearly singular. + + MAGICFM bool HeightPlaneFit(int iQuantity, Vector3 *akPoint, + Real &rfA, Real &rfB, Real &rfC); + + // Least-squares fit of a plane to (x,y,z) data by using distance measurements + // orthogonal to the proposed plane. The resulting plane is represented by + // Normal.Dot(X - Offset) = 0. The return value of the function is the + // associated minimum in the function that was minimized. + + MAGICFM Real OrthogonalPlaneFit(int iQuantity, Vector3 *akPoint, + Vector3 &rkOffset, Vector3 &rkNormal); + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcBox3.cpp b/src/editors/FreeMagic/MgcBox3.cpp new file mode 100644 index 00000000000..ef5b9b2811b --- /dev/null +++ b/src/editors/FreeMagic/MgcBox3.cpp @@ -0,0 +1,34 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +#pragma hdrstop +#include "MgcBox3.h" +using namespace Mgc; + +//---------------------------------------------------------------------------- +void Box3::ComputeVertices(Vector3 akVertex[8]) const +{ + Vector3 akEAxis[3] = + { + m_afExtent[0] * m_akAxis[0], + m_afExtent[1] * m_akAxis[1], + m_afExtent[2] * m_akAxis[2]}; + + akVertex[0] = m_kCenter - akEAxis[0] - akEAxis[1] - akEAxis[2]; + akVertex[1] = m_kCenter + akEAxis[0] - akEAxis[1] - akEAxis[2]; + akVertex[2] = m_kCenter + akEAxis[0] + akEAxis[1] - akEAxis[2]; + akVertex[3] = m_kCenter - akEAxis[0] + akEAxis[1] - akEAxis[2]; + akVertex[4] = m_kCenter - akEAxis[0] - akEAxis[1] + akEAxis[2]; + akVertex[5] = m_kCenter + akEAxis[0] - akEAxis[1] + akEAxis[2]; + akVertex[6] = m_kCenter + akEAxis[0] + akEAxis[1] + akEAxis[2]; + akVertex[7] = m_kCenter - akEAxis[0] + akEAxis[1] + akEAxis[2]; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcBox3.h b/src/editors/FreeMagic/MgcBox3.h new file mode 100644 index 00000000000..0f5170492e2 --- /dev/null +++ b/src/editors/FreeMagic/MgcBox3.h @@ -0,0 +1,51 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCBOX3_H +#define MGCBOX3_H + +#include "MgcVector3.h" + +namespace Mgc +{ + + class MAGICFM Box3 + { + public: + Box3(); + + Vector3 &Center(); + const Vector3 &Center() const; + + Vector3 &Axis(int i); + const Vector3 &Axis(int i) const; + Vector3 *Axes(); + const Vector3 *Axes() const; + + Real &Extent(int i); + const Real &Extent(int i) const; + Real *Extents(); + const Real *Extents() const; + + void ComputeVertices(Vector3 akVertex[8]) const; + + protected: + Vector3 m_kCenter; + Vector3 m_akAxis[3]; + Real m_afExtent[3]; + }; + +#include "MgcBox3.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcBox3.inl b/src/editors/FreeMagic/MgcBox3.inl new file mode 100644 index 00000000000..90199395d57 --- /dev/null +++ b/src/editors/FreeMagic/MgcBox3.inl @@ -0,0 +1,72 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Box3::Box3() +{ + // no initialization for efficiency +} +//---------------------------------------------------------------------------- +inline Vector3 &Box3::Center() +{ + return m_kCenter; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Box3::Center() const +{ + return m_kCenter; +} +//---------------------------------------------------------------------------- +inline Vector3 &Box3::Axis(int i) +{ + assert(0 <= i && i < 3); + return m_akAxis[i]; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Box3::Axis(int i) const +{ + assert(0 <= i && i < 3); + return m_akAxis[i]; +} +//---------------------------------------------------------------------------- +inline Vector3 *Box3::Axes() +{ + return m_akAxis; +} +//---------------------------------------------------------------------------- +inline const Vector3 *Box3::Axes() const +{ + return m_akAxis; +} +//---------------------------------------------------------------------------- +inline Real &Box3::Extent(int i) +{ + assert(0 <= i && i < 3); + return m_afExtent[i]; +} +//---------------------------------------------------------------------------- +inline const Real &Box3::Extent(int i) const +{ + assert(0 <= i && i < 3); + return m_afExtent[i]; +} +//---------------------------------------------------------------------------- +inline Real *Box3::Extents() +{ + return m_afExtent; +} +//---------------------------------------------------------------------------- +inline const Real *Box3::Extents() const +{ + return m_afExtent; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcCont3DBox.cpp b/src/editors/FreeMagic/MgcCont3DBox.cpp new file mode 100644 index 00000000000..0d68cf47486 --- /dev/null +++ b/src/editors/FreeMagic/MgcCont3DBox.cpp @@ -0,0 +1,230 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +#pragma hdrstop +#include "MgcAppr3DGaussPointsFit.h" +#include "MgcCont3DBox.h" +#include "MgcQuaternion.h" +using namespace Mgc; + +//---------------------------------------------------------------------------- +void Mgc::ContAlignedBox(int iQuantity, const Vector3 *akPoint, + Vector3 &rkMin, Vector3 &rkMax) +{ + rkMin = akPoint[0]; + rkMax = rkMin; + + for (int i = 1; i < iQuantity; i++) + { + if (akPoint[i].x < rkMin.x) + rkMin.x = akPoint[i].x; + else if (akPoint[i].x > rkMax.x) + rkMax.x = akPoint[i].x; + + if (akPoint[i].y < rkMin.y) + rkMin.y = akPoint[i].y; + else if (akPoint[i].y > rkMax.y) + rkMax.y = akPoint[i].y; + + if (akPoint[i].z < rkMin.z) + rkMin.z = akPoint[i].z; + else if (akPoint[i].z > rkMax.z) + rkMax.z = akPoint[i].z; + } +} +//---------------------------------------------------------------------------- +Box3 Mgc::ContOrientedBox(int iQuantity, const Vector3 *akPoint) +{ + Box3 kBox; + + GaussPointsFit(iQuantity, akPoint, kBox.Center(), kBox.Axes(), + kBox.Extents()); + + // Let C be the box center and let U0, U1, and U2 be the box axes. Each + // input point is of the form X = C + y0*U0 + y1*U1 + y2*U2. The + // following code computes min(y0), max(y0), min(y1), max(y1), min(y2), + // and max(y2). The box center is then adjusted to be + // C' = C + 0.5*(min(y0)+max(y0))*U0 + 0.5*(min(y1)+max(y1))*U1 + + // 0.5*(min(y2)+max(y2))*U2 + + Vector3 kDiff = akPoint[0] - kBox.Center(); + Real fY0Min = kDiff.Dot(kBox.Axis(0)), fY0Max = fY0Min; + Real fY1Min = kDiff.Dot(kBox.Axis(1)), fY1Max = fY1Min; + Real fY2Min = kDiff.Dot(kBox.Axis(2)), fY2Max = fY2Min; + + for (int i = 1; i < iQuantity; i++) + { + kDiff = akPoint[i] - kBox.Center(); + + Real fY0 = kDiff.Dot(kBox.Axis(0)); + if (fY0 < fY0Min) + fY0Min = fY0; + else if (fY0 > fY0Max) + fY0Max = fY0; + + Real fY1 = kDiff.Dot(kBox.Axis(1)); + if (fY1 < fY1Min) + fY1Min = fY1; + else if (fY1 > fY1Max) + fY1Max = fY1; + + Real fY2 = kDiff.Dot(kBox.Axis(2)); + if (fY2 < fY2Min) + fY2Min = fY2; + else if (fY2 > fY2Max) + fY2Max = fY2; + } + + kBox.Center() += (0.5f * (fY0Min + fY0Max)) * kBox.Axis(0) + + (0.5f * (fY1Min + fY1Max)) * kBox.Axis(1) + + (0.5f * (fY2Min + fY2Max)) * kBox.Axis(2); + + kBox.Extent(0) = 0.5f * (fY0Max - fY0Min); + kBox.Extent(1) = 0.5f * (fY1Max - fY1Min); + kBox.Extent(2) = 0.5f * (fY2Max - fY2Min); + + return kBox; +} +//---------------------------------------------------------------------------- +bool Mgc::ContOrientedBox(int iQuantity, const Vector3 *akPoint, + const bool *abValid, Box3 &rkBox) +{ + if (!GaussPointsFit(iQuantity, akPoint, abValid, rkBox.Center(), + rkBox.Axes(), rkBox.Extents())) + { + return false; + } + + // Let C be the box center and let U0, U1, and U2 be the box axes. Each + // input point is of the form X = C + y0*U0 + y1*U1 + y2*U2. The + // following code computes min(y0), max(y0), min(y1), max(y1), min(y2), + // and max(y2). The box center is then adjusted to be + // C' = C + 0.5*(min(y0)+max(y0))*U0 + 0.5*(min(y1)+max(y1))*U1 + + // 0.5*(min(y2)+max(y2))*U2 + + // get first valid vertex + Vector3 kDiff; + Real fY0Min, fY0Max, fY1Min, fY1Max, fY2Min, fY2Max; + int i; + for (i = 0; i < iQuantity; i++) + { + if (abValid[i]) + { + kDiff = akPoint[i] - rkBox.Center(); + fY0Min = kDiff.Dot(rkBox.Axis(0)); + fY0Max = fY0Min; + fY1Min = kDiff.Dot(rkBox.Axis(1)); + fY1Max = fY1Min; + fY2Min = kDiff.Dot(rkBox.Axis(2)); + fY2Max = fY2Min; + break; + } + } + + for (i++; i < iQuantity; i++) + { + if (abValid[i]) + { + kDiff = akPoint[i] - rkBox.Center(); + + Real fY0 = kDiff.Dot(rkBox.Axis(0)); + if (fY0 < fY0Min) + fY0Min = fY0; + else if (fY0 > fY0Max) + fY0Max = fY0; + + Real fY1 = kDiff.Dot(rkBox.Axis(1)); + if (fY1 < fY1Min) + fY1Min = fY1; + else if (fY1 > fY1Max) + fY1Max = fY1; + + Real fY2 = kDiff.Dot(rkBox.Axis(2)); + if (fY2 < fY2Min) + fY2Min = fY2; + else if (fY2 > fY2Max) + fY2Max = fY2; + } + } + + rkBox.Center() += (0.5f * (fY0Min + fY0Max)) * rkBox.Axis(0) + (0.5f * (fY1Min + fY1Max)) * rkBox.Axis(1) + + (0.5f * (fY2Min + fY2Max)) * rkBox.Axis(2); + + rkBox.Extent(0) = 0.5f * (fY0Max - fY0Min); + rkBox.Extent(1) = 0.5f * (fY1Max - fY1Min); + rkBox.Extent(2) = 0.5f * (fY2Max - fY2Min); + + return true; +} +//---------------------------------------------------------------------------- +Box3 Mgc::MergeBoxes(const Box3 &rkBox0, const Box3 &rkBox1) +{ + Box3 kBox; + kBox.Center() = 0.5f * (rkBox0.Center() + rkBox1.Center()); + + Quaternion kQ0, kQ1; + kQ0.FromAxes(rkBox0.Axes()); + kQ1.FromAxes(rkBox1.Axes()); + if (kQ0.Dot(kQ1) < 0.0f) + kQ1 = -kQ1; + + Quaternion kQ = kQ0 + kQ1; + Real fInvLength = Math::InvSqrt(kQ.Norm()); + kQ = fInvLength * kQ; + kQ.ToAxes(kBox.Axes()); + + int i, j; + Vector3 akVertex[8], kDiff; + Real fADot; + + kBox.Extent(0) = 0.0f; + kBox.Extent(1) = 0.0f; + kBox.Extent(2) = 0.0f; + + rkBox0.ComputeVertices(akVertex); + for (i = 0; i < 8; i++) + { + kDiff = akVertex[i] - kBox.Center(); + for (j = 0; j < 3; j++) + { + fADot = Math::FAbs(kDiff.Dot(kBox.Axis(j))); + if (fADot > kBox.Extent(j)) + kBox.Extent(j) = fADot; + } + } + + rkBox1.ComputeVertices(akVertex); + for (i = 0; i < 8; i++) + { + kDiff = akVertex[i] - kBox.Center(); + for (j = 0; j < 3; j++) + { + fADot = Math::FAbs(kDiff.Dot(kBox.Axis(j))); + if (fADot > kBox.Extent(j)) + kBox.Extent(j) = fADot; + } + } + + return kBox; +} +//---------------------------------------------------------------------------- +bool Mgc::InBox(const Vector3 &rkPoint, const Box3 &rkBox, Real fEpsilon) +{ + Vector3 kDiff = rkPoint - rkBox.Center(); + for (int i = 0; i < 3; i++) + { + Real fCoeff = kDiff.Dot(rkBox.Axis(i)); + if (Math::FAbs(fCoeff) > rkBox.Extent(i) + fEpsilon) + return false; + } + return true; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcCont3DBox.h b/src/editors/FreeMagic/MgcCont3DBox.h new file mode 100644 index 00000000000..87b7a4e4a4e --- /dev/null +++ b/src/editors/FreeMagic/MgcCont3DBox.h @@ -0,0 +1,42 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCCONT3DBOX_H +#define MGCCONT3DBOX_H + +#include "MgcBox3.h" + +namespace Mgc +{ + + MAGICFM void ContAlignedBox(int iQuantity, const Vector3 *akPoint, + Vector3 &rkMin, Vector3 &rkMax); + + MAGICFM Box3 ContOrientedBox(int iQuantity, const Vector3 *akPoint); + + // This function allows for selection of vertices from a pool. The return + // value is 'true' if and only if at least one vertex is valid. + MAGICFM bool ContOrientedBox(int iQuantity, const Vector3 *akPoint, + const bool *abValid, Box3 &rkBox); + + // Test for containment. Let X = C + y0*U0 + y1*U1 + y2*U2 where C is the + // box center and U0, U1, U2 are the orthonormal axes of the box. X is in + // the box if |y_i| <= E_i for all i where E_i are the extents of the box. + // If an epsilon e is supplied, the tests are |y_i| <= E_i + e. + MAGICFM bool InBox(const Vector3 &rkPoint, const Box3 &rkBox, + Real fEpsilon = 0.0f); + + MAGICFM Box3 MergeBoxes(const Box3 &rkBox0, const Box3 &rkBox1); + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcCont3DCylinder.cpp b/src/editors/FreeMagic/MgcCont3DCylinder.cpp new file mode 100644 index 00000000000..b697060edaf --- /dev/null +++ b/src/editors/FreeMagic/MgcCont3DCylinder.cpp @@ -0,0 +1,55 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +#pragma hdrstop +#include "MgcAppr3DLineFit.h" +#include "MgcCont3DCylinder.h" +#include "MgcDist3DVecLin.h" +using namespace Mgc; + +//---------------------------------------------------------------------------- +Cylinder Mgc::ContCylinder(int iQuantity, const Vector3 *akPoint) +{ + Cylinder kCylinder; + + Line3 kLine; + OrthogonalLineFit(iQuantity, akPoint, kLine.Origin(), kLine.Direction()); + + Real fMaxRadiusSqr = 0.0f; + int i; + for (i = 0; i < iQuantity; i++) + { + Real fRadiusSqr = SqrDistance(akPoint[i], kLine); + if (fRadiusSqr > fMaxRadiusSqr) + fMaxRadiusSqr = fRadiusSqr; + } + + Vector3 kDiff = akPoint[0] - kLine.Origin(); + Real fWMin = kLine.Direction().Dot(kDiff), fWMax = fWMin; + for (i = 1; i < iQuantity; i++) + { + kDiff = akPoint[i] - kLine.Origin(); + Real fW = kLine.Direction().Dot(kDiff); + if (fW < fWMin) + fWMin = fW; + else if (fW > fWMax) + fWMax = fW; + } + + kCylinder.Center() = kLine.Origin() + + (0.5f * (fWMax + fWMin)) * kLine.Direction(); + kCylinder.Direction() = kLine.Direction(); + kCylinder.Radius() = Math::Sqrt(fMaxRadiusSqr); + kCylinder.Height() = fWMax - fWMin; + + return kCylinder; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcCont3DCylinder.h b/src/editors/FreeMagic/MgcCont3DCylinder.h new file mode 100644 index 00000000000..4eeec674321 --- /dev/null +++ b/src/editors/FreeMagic/MgcCont3DCylinder.h @@ -0,0 +1,29 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCCONT3DCYLINDER_H +#define MGCCONT3DCYLINDER_H + +#include "MgcCylinder.h" + +namespace Mgc +{ + + // Compute axis of capsule segment using least-squares fit. Radius is + // maximum distance from points to axis. Height is determined by projection + // of points onto axis and determining the containing interval. + + MAGICFM Cylinder ContCylinder(int iQuantity, const Vector3 *akPoint); + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcCont3DMinBox.cpp b/src/editors/FreeMagic/MgcCont3DMinBox.cpp new file mode 100644 index 00000000000..33df9f50cbd --- /dev/null +++ b/src/editors/FreeMagic/MgcCont3DMinBox.cpp @@ -0,0 +1,166 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +#pragma hdrstop +#include "MgcCont3DMinBox.h" +#include "MgcMatrix3.h" +#include "MgcMinimizeND.h" +using namespace Mgc; + +class PointArray +{ +public: + PointArray(int iQuantity, const Vector3 *akPoint) + : m_akPoint(akPoint) + { + m_iQuantity = iQuantity; + } + + int m_iQuantity; + const Vector3 *m_akPoint; +}; + +//---------------------------------------------------------------------------- +static Real Volume(const Real *afAngle, void *pvUserData) +{ + int iQuantity = ((PointArray *)pvUserData)->m_iQuantity; + const Vector3 *akPoint = ((PointArray *)pvUserData)->m_akPoint; + + Real fCos0 = Math::Cos(afAngle[0]); + Real fSin0 = Math::Sin(afAngle[0]); + Real fCos1 = Math::Cos(afAngle[1]); + Real fSin1 = Math::Sin(afAngle[1]); + Vector3 kAxis(fCos0 * fSin1, fSin0 * fSin1, fCos1); + Matrix3 kRot; + kRot.FromAxisAngle(kAxis, afAngle[2]); + + Vector3 kMin = akPoint[0] * kRot, kMax = kMin; + for (int i = 1; i < iQuantity; i++) + { + Vector3 kTest = akPoint[i] * kRot; + + if (kTest.x < kMin.x) + kMin.x = kTest.x; + else if (kTest.x > kMax.x) + kMax.x = kTest.x; + + if (kTest.y < kMin.y) + kMin.y = kTest.y; + else if (kTest.y > kMax.y) + kMax.y = kTest.y; + + if (kTest.z < kMin.z) + kMin.z = kTest.z; + else if (kTest.z > kMax.z) + kMax.z = kTest.z; + } + + Real fVolume = (kMax.x - kMin.x) * (kMax.y - kMin.y) * (kMax.z - kMin.z); + return fVolume; +} +//---------------------------------------------------------------------------- +static void MinimalBoxForAngles(int iQuantity, const Vector3 *akPoint, + Real afAngle[3], Box3 &rkBox) +{ + Real fCos0 = Math::Cos(afAngle[0]); + Real fSin0 = Math::Sin(afAngle[0]); + Real fCos1 = Math::Cos(afAngle[1]); + Real fSin1 = Math::Sin(afAngle[1]); + Vector3 kAxis(fCos0 * fSin1, fSin0 * fSin1, fCos1); + Matrix3 kRot; + kRot.FromAxisAngle(kAxis, afAngle[2]); + + Vector3 kMin = akPoint[0] * kRot, kMax = kMin; + for (int i = 1; i < iQuantity; i++) + { + Vector3 kTest = akPoint[i] * kRot; + + if (kTest.x < kMin.x) + kMin.x = kTest.x; + else if (kTest.x > kMax.x) + kMax.x = kTest.x; + + if (kTest.y < kMin.y) + kMin.y = kTest.y; + else if (kTest.y > kMax.y) + kMax.y = kTest.y; + + if (kTest.z < kMin.z) + kMin.z = kTest.z; + else if (kTest.z > kMax.z) + kMax.z = kTest.z; + } + + Vector3 kMid = 0.5f * (kMax + kMin); + Vector3 kRng = 0.5f * (kMax - kMin); + + rkBox.Center() = kRot * kMid; + rkBox.Axis(0) = kRot.GetColumn(0); + rkBox.Axis(1) = kRot.GetColumn(1); + rkBox.Axis(2) = kRot.GetColumn(2); + rkBox.Extent(0) = kRng.x; + rkBox.Extent(1) = kRng.y; + rkBox.Extent(2) = kRng.z; +} +//---------------------------------------------------------------------------- +Box3 Mgc::MinBox(int iQuantity, const Vector3 *akPoint) +{ + int iMaxLevel = 8; + int iMaxBracket = 8; + int iMaxIterations = 32; + PointArray kPA(iQuantity, akPoint); + MinimizeND kMinimizer(3, Volume, iMaxLevel, iMaxBracket, iMaxIterations, &kPA); + + Real afA0[3] = + { + 0.0f, + 0.0f, + 0.0f}; + + Real afA1[3] = + { + Math::_PI, + Math::HALF_PI, + Math::_PI}; + + // compute some samples to narrow down the search region + Real fMinVolume = Math::MAX_REAL; + Real afAngle[3], afAInitial[3]; + const int iMax = 3; + for (int i0 = 0; i0 <= iMax; i0++) + { + afAngle[0] = afA0[0] + i0 * (afA1[0] - afA0[0]) / iMax; + for (int i1 = 0; i1 <= iMax; i1++) + { + afAngle[1] = afA0[1] + i1 * (afA1[1] - afA0[1]) / iMax; + for (int i2 = 0; i2 <= iMax; i2++) + { + afAngle[2] = afA0[2] + i2 * (afA1[2] - afA0[2]) / iMax; + Real fVolume = Volume(afAngle, &kPA); + if (fVolume < fMinVolume) + { + fMinVolume = fVolume; + afAInitial[0] = afAngle[0]; + afAInitial[1] = afAngle[1]; + afAInitial[2] = afAngle[2]; + } + } + } + } + + Real afAMin[3], fVMin; + kMinimizer.GetMinimum(afA0, afA1, afAInitial, afAMin, fVMin); + + Box3 kBox; + MinimalBoxForAngles(iQuantity, akPoint, afAMin, kBox); + return kBox; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcCont3DMinBox.h b/src/editors/FreeMagic/MgcCont3DMinBox.h new file mode 100644 index 00000000000..aaf79aca29a --- /dev/null +++ b/src/editors/FreeMagic/MgcCont3DMinBox.h @@ -0,0 +1,27 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCCONT3DMINBOX3_H +#define MGCCONT3DMINBOX3_H + +// Compute minimum volume oriented box containing the specified points. + +#include "MgcBox3.h" + +namespace Mgc +{ + + MAGICFM Box3 MinBox(int iQuantity, const Vector3 *akPoint); + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcCont3DMinSphere.cpp b/src/editors/FreeMagic/MgcCont3DMinSphere.cpp new file mode 100644 index 00000000000..486f7870074 --- /dev/null +++ b/src/editors/FreeMagic/MgcCont3DMinSphere.cpp @@ -0,0 +1,637 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +//#include "stdafx.h" +#pragma hdrstop + +#include "MgcCont3DMinSphere.h" +using namespace Mgc; + +// error checking +static const Real gs_fEpsilon = 1e-03f; +static const Real gs_fOnePlusEpsilon = 1.0f + gs_fEpsilon; + +// indices of points that support current minimum volume sphere +class Support +{ +public: + int m_iQuantity; + int m_aiIndex[4]; + + bool Contains(int iIndex, Vector3 **apkPoint) + { + for (int i = 0; i < m_iQuantity; i++) + { + Vector3 kDiff = *apkPoint[iIndex] - *apkPoint[m_aiIndex[i]]; + if (kDiff.SquaredLength() < gs_fEpsilon) + return true; + } + return false; + } +}; + +// All internal minimal sphere calculations store the squared radius in the +// radius member of Sphere. Only at the end is a sqrt computed. + +//---------------------------------------------------------------------------- +static bool PointInsideSphere(const Vector3 &rkP, const Sphere &rkS) +{ + Vector3 kDiff = rkP - rkS.Center(); + Real fTest = kDiff.SquaredLength(); + return fTest <= gs_fOnePlusEpsilon * rkS.Radius(); // theory: test <= R^2 +} +//---------------------------------------------------------------------------- +static Sphere ExactSphere1(const Vector3 &rkP) +{ + Sphere kMinimal; + kMinimal.Center() = rkP; + kMinimal.Radius() = 0.0f; + return kMinimal; +} +//---------------------------------------------------------------------------- +static Sphere ExactSphere2(const Vector3 &rkP0, const Vector3 &rkP1) +{ + Sphere kMinimal; + kMinimal.Center() = 0.5f * (rkP0 + rkP1); + Vector3 kDiff = rkP1 - rkP0; + kMinimal.Radius() = 0.25f * kDiff.SquaredLength(); + return kMinimal; +} +//---------------------------------------------------------------------------- +static Sphere ExactSphere3(const Vector3 &rkP0, const Vector3 &rkP1, + const Vector3 &rkP2) +{ + // Compute the circle (in 3D) containing p0, p1, and p2. The Center() in + // barycentric coordinates is K = u0*p0+u1*p1+u2*p2 where u0+u1+u2=1. + // The Center() is equidistant from the three points, so |K-p0| = |K-p1| = + // |K-p2| = R where R is the radius of the circle. + // + // From these conditions, + // K-p0 = u0*A + u1*B - A + // K-p1 = u0*A + u1*B - B + // K-p2 = u0*A + u1*B + // where A = p0-p2 and B = p1-p2, which leads to + // r^2 = |u0*A+u1*B|^2 - 2*Dot(A,u0*A+u1*B) + |A|^2 + // r^2 = |u0*A+u1*B|^2 - 2*Dot(B,u0*A+u1*B) + |B|^2 + // r^2 = |u0*A+u1*B|^2 + // Subtracting the last equation from the first two and writing + // the equations as a linear system, + // + // +- -++ -+ +- -+ + // | Dot(A,A) Dot(A,B) || u0 | = 0.5 | Dot(A,A) | + // | Dot(B,A) Dot(B,B) || u1 | | Dot(B,B) | + // +- -++ -+ +- -+ + // + // The following code solves this system for u0 and u1, then + // evaluates the third equation in r^2 to obtain r. + + Vector3 kA = rkP0 - rkP2; + Vector3 kB = rkP1 - rkP2; + Real fAdA = kA.Dot(kA); + Real fAdB = kA.Dot(kB); + Real fBdB = kB.Dot(kB); + Real fDet = fAdA * fBdB - fAdB * fAdB; + + Sphere kMinimal; + + if (::Math::FAbs(fDet) > gs_fEpsilon) + { + Real fHalfInvDet = 0.5f / fDet; + Real fU0 = fHalfInvDet * fBdB * (fAdA - fAdB); + Real fU1 = fHalfInvDet * fAdA * (fBdB - fAdB); + Real fU2 = 1.0f - fU0 - fU1; + kMinimal.Center() = fU0 * rkP0 + fU1 * rkP1 + fU2 * rkP2; + Vector3 kTmp = fU0 * kA + fU1 * kB; + kMinimal.Radius() = kTmp.SquaredLength(); + } + else + { + kMinimal.Center() = Vector3::ZERO; + kMinimal.Radius() = ::Math::MAX_REAL; + } + + return kMinimal; +} +//---------------------------------------------------------------------------- +static Sphere ExactSphere4(const Vector3 &rkP0, const Vector3 &rkP1, + const Vector3 &rkP2, const Vector3 &rkP3) +{ + // Compute the sphere containing p0, p1, p2, and p3. The Center() in + // barycentric coordinates is K = u0*p0+u1*p1+u2*p2+u3*p3 where + // u0+u1+u2+u3=1. The Center() is equidistant from the three points, so + // |K-p0| = |K-p1| = |K-p2| = |K-p3| = R where R is the radius of the + // sphere. + // + // From these conditions, + // K-p0 = u0*A + u1*B + u2*C - A + // K-p1 = u0*A + u1*B + u2*C - B + // K-p2 = u0*A + u1*B + u2*C - C + // K-p3 = u0*A + u1*B + u2*C + // where A = p0-p3, B = p1-p3, and C = p2-p3 which leads to + // r^2 = |u0*A+u1*B+u2*C|^2 - 2*Dot(A,u0*A+u1*B+u2*C) + |A|^2 + // r^2 = |u0*A+u1*B+u2*C|^2 - 2*Dot(B,u0*A+u1*B+u2*C) + |B|^2 + // r^2 = |u0*A+u1*B+u2*C|^2 - 2*Dot(C,u0*A+u1*B+u2*C) + |C|^2 + // r^2 = |u0*A+u1*B+u2*C|^2 + // Subtracting the last equation from the first three and writing + // the equations as a linear system, + // + // +- -++ -+ +- -+ + // | Dot(A,A) Dot(A,B) Dot(A,C) || u0 | = 0.5 | Dot(A,A) | + // | Dot(B,A) Dot(B,B) Dot(B,C) || u1 | | Dot(B,B) | + // | Dot(C,A) Dot(C,B) Dot(C,C) || u2 | | Dot(C,C) | + // +- -++ -+ +- -+ + // + // The following code solves this system for u0, u1, and u2, then + // evaluates the fourth equation in r^2 to obtain r. + + Vector3 kE10 = rkP0 - rkP3; + Vector3 kE20 = rkP1 - rkP3; + Vector3 kE30 = rkP2 - rkP3; + + Real aafA[3][3]; + aafA[0][0] = kE10.Dot(kE10); + aafA[0][1] = kE10.Dot(kE20); + aafA[0][2] = kE10.Dot(kE30); + aafA[1][0] = aafA[0][1]; + aafA[1][1] = kE20.Dot(kE20); + aafA[1][2] = kE20.Dot(kE30); + aafA[2][0] = aafA[0][2]; + aafA[2][1] = aafA[1][2]; + aafA[2][2] = kE30.Dot(kE30); + + Real afB[3]; + afB[0] = 0.5f * aafA[0][0]; + afB[1] = 0.5f * aafA[1][1]; + afB[2] = 0.5f * aafA[2][2]; + + Real aafAInv[3][3]; + aafAInv[0][0] = aafA[1][1] * aafA[2][2] - aafA[1][2] * aafA[2][1]; + aafAInv[0][1] = aafA[0][2] * aafA[2][1] - aafA[0][1] * aafA[2][2]; + aafAInv[0][2] = aafA[0][1] * aafA[1][2] - aafA[0][2] * aafA[1][1]; + aafAInv[1][0] = aafA[1][2] * aafA[2][0] - aafA[1][0] * aafA[2][2]; + aafAInv[1][1] = aafA[0][0] * aafA[2][2] - aafA[0][2] * aafA[2][0]; + aafAInv[1][2] = aafA[0][2] * aafA[1][0] - aafA[0][0] * aafA[1][2]; + aafAInv[2][0] = aafA[1][0] * aafA[2][1] - aafA[1][1] * aafA[2][0]; + aafAInv[2][1] = aafA[0][1] * aafA[2][0] - aafA[0][0] * aafA[2][1]; + aafAInv[2][2] = aafA[0][0] * aafA[1][1] - aafA[0][1] * aafA[1][0]; + Real fDet = aafA[0][0] * aafAInv[0][0] + aafA[0][1] * aafAInv[1][0] + + aafA[0][2] * aafAInv[2][0]; + + Sphere kMinimal; + + if (::Math::FAbs(fDet) > gs_fEpsilon) + { + Real fInvDet = 1.0f / fDet; + int iRow, iCol; + for (iRow = 0; iRow < 3; iRow++) + { + for (iCol = 0; iCol < 3; iCol++) + aafAInv[iRow][iCol] *= fInvDet; + } + + Real afU[4]; + for (iRow = 0; iRow < 3; iRow++) + { + afU[iRow] = 0.0f; + for (iCol = 0; iCol < 3; iCol++) + afU[iRow] += aafAInv[iRow][iCol] * afB[iCol]; + } + afU[3] = 1.0f - afU[0] - afU[1] - afU[2]; + + kMinimal.Center() = afU[0] * rkP0 + afU[1] * rkP1 + afU[2] * rkP2 + + afU[3] * rkP3; + Vector3 kTmp = afU[0] * kE10 + afU[1] * kE20 + afU[2] * kE30; + kMinimal.Radius() = kTmp.SquaredLength(); + } + else + { + kMinimal.Center() = Vector3::ZERO; + kMinimal.Radius() = ::Math::MAX_REAL; + } + + return kMinimal; +} +//---------------------------------------------------------------------------- +static Sphere UpdateSupport1(int i, Vector3 **apkPerm, Support &rkSupp) +{ + const Vector3 &rkP0 = *apkPerm[rkSupp.m_aiIndex[0]]; + const Vector3 &rkP1 = *apkPerm[i]; + + Sphere kMinimal = ExactSphere2(rkP0, rkP1); + rkSupp.m_iQuantity = 2; + rkSupp.m_aiIndex[1] = i; + + return kMinimal; +} +//---------------------------------------------------------------------------- +static Sphere UpdateSupport2(int i, Vector3 **apkPerm, Support &rkSupp) +{ + const Vector3 &rkP0 = *apkPerm[rkSupp.m_aiIndex[0]]; + const Vector3 &rkP1 = *apkPerm[rkSupp.m_aiIndex[1]]; + const Vector3 &rkP2 = *apkPerm[i]; + + Sphere akS[3]; + Real fMinRSqr = ::Math::MAX_REAL; + int iIndex = -1; + + akS[0] = ExactSphere2(rkP0, rkP2); + if (PointInsideSphere(rkP1, akS[0])) + { + fMinRSqr = akS[0].Radius(); + iIndex = 0; + } + + akS[1] = ExactSphere2(rkP1, rkP2); + if (akS[1].Radius() < fMinRSqr) + { + if (PointInsideSphere(rkP0, akS[1])) + { + fMinRSqr = akS[1].Radius(); + iIndex = 1; + } + } + + Sphere kMinimal; + + if (iIndex != -1) + { + kMinimal = akS[iIndex]; + rkSupp.m_aiIndex[1 - iIndex] = i; + } + else + { + kMinimal = ExactSphere3(rkP0, rkP1, rkP2); + assert(kMinimal.Radius() <= fMinRSqr); + rkSupp.m_iQuantity = 3; + rkSupp.m_aiIndex[2] = i; + } + + return kMinimal; +} +//---------------------------------------------------------------------------- +static Sphere UpdateSupport3(int i, Vector3 **apkPerm, Support &rkSupp) +{ + const Vector3 &rkP0 = *apkPerm[rkSupp.m_aiIndex[0]]; + const Vector3 &rkP1 = *apkPerm[rkSupp.m_aiIndex[1]]; + const Vector3 &rkP2 = *apkPerm[rkSupp.m_aiIndex[2]]; + const Vector3 &rkP3 = *apkPerm[i]; + + Sphere akS[6]; + Real fMinRSqr = ::Math::MAX_REAL; + int iIndex = -1; + + akS[0] = ExactSphere2(rkP0, rkP3); + if (PointInsideSphere(rkP1, akS[0]) && PointInsideSphere(rkP2, akS[0])) + { + fMinRSqr = akS[0].Radius(); + iIndex = 0; + } + + akS[1] = ExactSphere2(rkP1, rkP3); + if (akS[1].Radius() < fMinRSqr && PointInsideSphere(rkP0, akS[1]) && PointInsideSphere(rkP2, akS[1])) + { + fMinRSqr = akS[1].Radius(); + iIndex = 1; + } + + akS[2] = ExactSphere2(rkP2, rkP3); + if (akS[2].Radius() < fMinRSqr && PointInsideSphere(rkP0, akS[2]) && PointInsideSphere(rkP1, akS[2])) + { + fMinRSqr = akS[2].Radius(); + iIndex = 2; + } + + akS[3] = ExactSphere3(rkP0, rkP1, rkP3); + if (akS[3].Radius() < fMinRSqr && PointInsideSphere(rkP2, akS[3])) + { + fMinRSqr = akS[3].Radius(); + iIndex = 3; + } + + akS[4] = ExactSphere3(rkP0, rkP2, rkP3); + if (akS[4].Radius() < fMinRSqr && PointInsideSphere(rkP1, akS[4])) + { + fMinRSqr = akS[4].Radius(); + iIndex = 4; + } + + akS[5] = ExactSphere3(rkP1, rkP2, rkP3); + if (akS[5].Radius() < fMinRSqr && PointInsideSphere(rkP0, akS[5])) + { + fMinRSqr = akS[5].Radius(); + iIndex = 5; + } + + Sphere kMinimal; + + switch (iIndex) + { + case 0: + kMinimal = akS[0]; + rkSupp.m_iQuantity = 2; + rkSupp.m_aiIndex[1] = i; + break; + case 1: + kMinimal = akS[1]; + rkSupp.m_iQuantity = 2; + rkSupp.m_aiIndex[0] = i; + break; + case 2: + kMinimal = akS[2]; + rkSupp.m_iQuantity = 2; + rkSupp.m_aiIndex[0] = rkSupp.m_aiIndex[2]; + rkSupp.m_aiIndex[1] = i; + break; + case 3: + kMinimal = akS[3]; + rkSupp.m_aiIndex[2] = i; + break; + case 4: + kMinimal = akS[4]; + rkSupp.m_aiIndex[1] = i; + break; + case 5: + kMinimal = akS[5]; + rkSupp.m_aiIndex[0] = i; + break; + default: + kMinimal = ExactSphere4(rkP0, rkP1, rkP2, rkP3); + assert(kMinimal.Radius() <= fMinRSqr); + rkSupp.m_iQuantity = 4; + rkSupp.m_aiIndex[3] = i; + break; + } + + return kMinimal; +} +//---------------------------------------------------------------------------- +static Sphere UpdateSupport4(int i, Vector3 **apkPerm, Support &rkSupp) +{ + const Vector3 &rkP0 = *apkPerm[rkSupp.m_aiIndex[0]]; + const Vector3 &rkP1 = *apkPerm[rkSupp.m_aiIndex[1]]; + const Vector3 &rkP2 = *apkPerm[rkSupp.m_aiIndex[2]]; + const Vector3 &rkP3 = *apkPerm[rkSupp.m_aiIndex[3]]; + const Vector3 &rkP4 = *apkPerm[i]; + + Sphere akS[14]; + Real fMinRSqr = ::Math::MAX_REAL; + int iIndex = -1; + + akS[0] = ExactSphere2(rkP0, rkP4); + if (PointInsideSphere(rkP1, akS[0]) && PointInsideSphere(rkP2, akS[0]) && PointInsideSphere(rkP3, akS[0])) + { + fMinRSqr = akS[0].Radius(); + iIndex = 0; + } + + akS[1] = ExactSphere2(rkP1, rkP4); + if (akS[1].Radius() < fMinRSqr && PointInsideSphere(rkP0, akS[1]) && PointInsideSphere(rkP2, akS[1]) && PointInsideSphere(rkP3, akS[1])) + { + fMinRSqr = akS[1].Radius(); + iIndex = 1; + } + + akS[2] = ExactSphere2(rkP2, rkP4); + if (akS[2].Radius() < fMinRSqr && PointInsideSphere(rkP0, akS[2]) && PointInsideSphere(rkP1, akS[2]) && PointInsideSphere(rkP3, akS[2])) + { + fMinRSqr = akS[2].Radius(); + iIndex = 2; + } + + akS[3] = ExactSphere2(rkP3, rkP4); + if (akS[3].Radius() < fMinRSqr && PointInsideSphere(rkP0, akS[3]) && PointInsideSphere(rkP1, akS[3]) && PointInsideSphere(rkP2, akS[3])) + { + fMinRSqr = akS[3].Radius(); + iIndex = 3; + } + + akS[4] = ExactSphere3(rkP0, rkP1, rkP4); + if (akS[4].Radius() < fMinRSqr && PointInsideSphere(rkP2, akS[4]) && PointInsideSphere(rkP3, akS[4])) + { + fMinRSqr = akS[4].Radius(); + iIndex = 4; + } + + akS[5] = ExactSphere3(rkP0, rkP2, rkP4); + if (akS[5].Radius() < fMinRSqr && PointInsideSphere(rkP1, akS[5]) && PointInsideSphere(rkP3, akS[5])) + { + fMinRSqr = akS[5].Radius(); + iIndex = 5; + } + + akS[6] = ExactSphere3(rkP0, rkP3, rkP4); + if (akS[6].Radius() < fMinRSqr && PointInsideSphere(rkP1, akS[6]) && PointInsideSphere(rkP2, akS[6])) + { + fMinRSqr = akS[6].Radius(); + iIndex = 6; + } + + akS[7] = ExactSphere3(rkP1, rkP2, rkP4); + if (akS[7].Radius() < fMinRSqr && PointInsideSphere(rkP0, akS[7]) && PointInsideSphere(rkP3, akS[7])) + { + fMinRSqr = akS[7].Radius(); + iIndex = 7; + } + + akS[8] = ExactSphere3(rkP1, rkP3, rkP4); + if (akS[8].Radius() < fMinRSqr && PointInsideSphere(rkP0, akS[8]) && PointInsideSphere(rkP2, akS[8])) + { + fMinRSqr = akS[8].Radius(); + iIndex = 8; + } + + akS[9] = ExactSphere3(rkP2, rkP3, rkP4); + if (akS[9].Radius() < fMinRSqr && PointInsideSphere(rkP0, akS[9]) && PointInsideSphere(rkP1, akS[9])) + { + fMinRSqr = akS[9].Radius(); + iIndex = 9; + } + + akS[10] = ExactSphere4(rkP0, rkP1, rkP2, rkP4); + if (akS[10].Radius() < fMinRSqr && PointInsideSphere(rkP3, akS[10])) + { + fMinRSqr = akS[10].Radius(); + iIndex = 10; + } + + akS[11] = ExactSphere4(rkP0, rkP1, rkP3, rkP4); + if (akS[11].Radius() < fMinRSqr && PointInsideSphere(rkP2, akS[11])) + { + fMinRSqr = akS[11].Radius(); + iIndex = 11; + } + + akS[12] = ExactSphere4(rkP0, rkP2, rkP3, rkP4); + if (akS[12].Radius() < fMinRSqr && PointInsideSphere(rkP1, akS[12])) + { + fMinRSqr = akS[12].Radius(); + iIndex = 12; + } + + akS[13] = ExactSphere4(rkP1, rkP2, rkP3, rkP4); + if (akS[13].Radius() < fMinRSqr && PointInsideSphere(rkP0, akS[13])) + { + fMinRSqr = akS[13].Radius(); + iIndex = 13; + } + + Sphere kMinimal = akS[iIndex]; + + switch (iIndex) + { + case 0: + rkSupp.m_iQuantity = 2; + rkSupp.m_aiIndex[1] = i; + break; + case 1: + rkSupp.m_iQuantity = 2; + rkSupp.m_aiIndex[0] = i; + break; + case 2: + rkSupp.m_iQuantity = 2; + rkSupp.m_aiIndex[0] = rkSupp.m_aiIndex[2]; + rkSupp.m_aiIndex[1] = i; + break; + case 3: + rkSupp.m_iQuantity = 2; + rkSupp.m_aiIndex[0] = rkSupp.m_aiIndex[3]; + rkSupp.m_aiIndex[1] = i; + break; + case 4: + rkSupp.m_iQuantity = 3; + rkSupp.m_aiIndex[2] = i; + break; + case 5: + rkSupp.m_iQuantity = 3; + rkSupp.m_aiIndex[1] = i; + break; + case 6: + rkSupp.m_iQuantity = 3; + rkSupp.m_aiIndex[1] = rkSupp.m_aiIndex[3]; + rkSupp.m_aiIndex[2] = i; + break; + case 7: + rkSupp.m_iQuantity = 3; + rkSupp.m_aiIndex[0] = i; + break; + case 8: + rkSupp.m_iQuantity = 3; + rkSupp.m_aiIndex[0] = rkSupp.m_aiIndex[3]; + rkSupp.m_aiIndex[2] = i; + break; + case 9: + rkSupp.m_iQuantity = 3; + rkSupp.m_aiIndex[0] = rkSupp.m_aiIndex[3]; + rkSupp.m_aiIndex[1] = i; + break; + case 10: + rkSupp.m_aiIndex[3] = i; + break; + case 11: + rkSupp.m_aiIndex[2] = i; + break; + case 12: + rkSupp.m_aiIndex[1] = i; + break; + case 13: + rkSupp.m_aiIndex[0] = i; + break; + default: + rkSupp.m_iQuantity = 5; + } + + return kMinimal; +} +//---------------------------------------------------------------------------- +typedef Sphere (*UpdateFunction)(int, Vector3 **, Support &); +static UpdateFunction gs_aoUpdate[5] = + { + NULL, + UpdateSupport1, + UpdateSupport2, + UpdateSupport3, + UpdateSupport4}; +//---------------------------------------------------------------------------- +Sphere Mgc::MinSphere(int iQuantity, const Vector3 *akPoint) +{ + // initialize random number generator + size_t CountRestart = 0; +restart: + static bool s_bFirstTime = true; + if (s_bFirstTime) + { + srand(367); + s_bFirstTime = false; + } + + Sphere kMinimal; + Support kSupp; + + if (iQuantity >= 1) + { + // create identity permutation (0,1,...,iQuantity-1) + Vector3 **apkPerm = new Vector3 *[iQuantity]; + int i; + for (i = 0; i < iQuantity; i++) + apkPerm[i] = (Vector3 *)&akPoint[i]; + + // generate random permutation + for (i = iQuantity - 1; i > 0; i--) + { + int j = rand() % (i + 1); + if (j != i) + { + Vector3 *pSave = apkPerm[i]; + apkPerm[i] = apkPerm[j]; + apkPerm[j] = pSave; + } + } + + kMinimal = ExactSphere1(*apkPerm[0]); + kSupp.m_iQuantity = 1; + kSupp.m_aiIndex[0] = 0; + i = 1; + while (i < iQuantity) + { + if (!kSupp.Contains(i, apkPerm)) + { + if (!PointInsideSphere(*apkPerm[i], kMinimal)) + { + Sphere kSph = gs_aoUpdate[kSupp.m_iQuantity](i, apkPerm, kSupp); + if (kSupp.m_iQuantity == 5) + { + assert(CountRestart < 1000); + delete[] apkPerm; + CountRestart++; + goto restart; + } + if (kSph.Radius() > kMinimal.Radius()) + { + kMinimal = kSph; + i = 0; + continue; + } + } + } + i++; + } + + delete[] apkPerm; + } + else + { + assert(false); + } + + kMinimal.Radius() = Math::Sqrt(kMinimal.Radius()); + return kMinimal; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcCont3DMinSphere.h b/src/editors/FreeMagic/MgcCont3DMinSphere.h new file mode 100644 index 00000000000..7a4f051e48b --- /dev/null +++ b/src/editors/FreeMagic/MgcCont3DMinSphere.h @@ -0,0 +1,29 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCCONT3DMINSPHERE_H +#define MGCCONT3DMINSPHERE_H + +// Compute the minimum volume sphere containing the input set of points. The +// algorithm randomly permutes the input points so that the construction +// occurs in 'expected' O(N) time. + +#include "MgcSphere.h" + +namespace Mgc +{ + + MAGICFM Sphere MinSphere(int iQuantity, const Vector3 *akPoint); + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcConvexHull2D.cpp b/src/editors/FreeMagic/MgcConvexHull2D.cpp new file mode 100644 index 00000000000..87947804b08 --- /dev/null +++ b/src/editors/FreeMagic/MgcConvexHull2D.cpp @@ -0,0 +1,609 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +//#include "stdafx.h" +#pragma hdrstop + +#include "MgcConvexHull2D.h" +using namespace Mgc; + +#include +#include +#include +using namespace std; + +Real ConvexHull2D::ms_fVeqEpsilon = 0.0f; +Real ConvexHull2D::ms_fColEpsilon = 1e-06f; + +//---------------------------------------------------------------------------- +ConvexHull2D::ConvexHull2D(int iVQuantity, const Vector2 *akVertex) +{ + m_iVQuantity = iVQuantity; + m_akVertex = akVertex; +} +//---------------------------------------------------------------------------- +ConvexHull2D::~ConvexHull2D() +{ + delete[] m_aiHIndex; +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// point-in-convex-polygon +//---------------------------------------------------------------------------- +bool ConvexHull2D::SubContainsPoint(const Vector2 &rkP, int i0, int i1) const +{ + Vector2 kDir, kNormal, kDiff; + + int iDiff = i1 - i0; + if (iDiff == 1 || (iDiff < 0 && iDiff + m_iHQuantity == 1)) + { + const Vector2 &rkV0 = m_akVertex[m_aiHIndex[i0]]; + const Vector2 &rkV1 = m_akVertex[m_aiHIndex[i1]]; + kDir = rkV1 - rkV0; + kNormal = kDir.Cross(); // outer normal + kDiff = rkP - rkV0; + return kNormal.Dot(kDiff) <= 0.0f; + } + + // bisect the index range + int iMid; + if (i0 < i1) + iMid = (i0 + i1) >> 1; + else + iMid = ((i0 + i1 + m_iHQuantity) >> 1) % m_iHQuantity; + + // determine which side of the splitting line contains the point + kDir = m_akVertex[m_aiHIndex[iMid]] - m_akVertex[m_aiHIndex[i0]]; + kNormal = kDir.Cross(); // outer normal + kDiff = rkP - m_akVertex[m_aiHIndex[i0]]; + if (kNormal.Dot(kDiff) > 0.0f) + { + // P potentially in + return SubContainsPoint(rkP, i0, iMid); + } + else + { + // P potentially in + return SubContainsPoint(rkP, iMid, i1); + } +} +//---------------------------------------------------------------------------- +bool ConvexHull2D::ContainsPoint(const Vector2 &rkP) const +{ +#if 0 + // O(N) algorithm + for (int i1 = 0, i0 = m_iHQuantity-1; i1 < m_iHQuantity; i0 = i1++) + { + const Vector2& rkV0 = m_akVertex[m_aiHIndex[i0]]; + const Vector2& rkV1 = m_akVertex[m_aiHIndex[i1]]; + Vector2 kDir = rkV1 - rkV0; + Vector2 kNormal = kDir.Cross(); // outer normal + if ( kNormal.Dot(rkP-rkV0) > 0.0f ) + return false; + } + + return true; +#else + // O(log N) algorithm + if (m_iHQuantity > 2) + { + return SubContainsPoint(rkP, 0, 0); + } + else if (m_iHQuantity == 2) + { + int iTest = CollinearTest(rkP, m_akVertex[m_aiHIndex[0]], + m_akVertex[m_aiHIndex[1]]); + + return (iTest == ORDER_COLLINEAR_CONTAIN); + } + else // assert: m_iHQuantity == 1 + { + return rkP == m_akVertex[0]; + } +#endif +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// support for both hull methods +//---------------------------------------------------------------------------- +bool ConvexHull2D::SortedVertex::operator==(const SortedVertex &rkSV) const +{ + return m_kV == rkSV.m_kV; +} +//---------------------------------------------------------------------------- +bool ConvexHull2D::SortedVertex::operator<(const SortedVertex &rkSV) const +{ + Real fXTmp = rkSV.m_kV.x; + if (Math::FAbs(m_kV.x - fXTmp) <= Vector2::FUZZ) + fXTmp = m_kV.x; + + if (m_kV.x < fXTmp) + return true; + else if (m_kV.x > fXTmp) + return false; + + Real fYTmp = rkSV.m_kV.y; + if (Math::FAbs(m_kV.y - fYTmp) <= Vector2::FUZZ) + fYTmp = m_kV.y; + + return m_kV.y < fYTmp; +} +//---------------------------------------------------------------------------- +int ConvexHull2D::CollinearTest(const Vector2 &rkP, const Vector2 &rkQ0, + const Vector2 &rkQ1) const +{ + Vector2 kD = rkQ1 - rkQ0; + Vector2 kA = rkP - rkQ0; + Real fDdD = kD.Dot(kD); + Real fAdA = kA.Dot(kA); + Real fDet = kD.x * kA.y - kD.y * kA.x; + Real fRelative = fDet * fDet - ms_fColEpsilon * fDdD * fAdA; + + if (fRelative > 0.0f) + { + if (fDet > 0.0f) + { + // points form counterclockwise triangle + return ORDER_POSITIVE; + } + else if (fDet < 0.0f) + { + // points form clockwise triangle + return ORDER_NEGATIVE; + } + } + + // P is on line of + Real fDdA = kD.Dot(kA); + if (fDdA < 0.0f) + { + // order is + return ORDER_COLLINEAR_LEFT; + } + + if (fDdA > fDdD) + { + // order is + return ORDER_COLLINEAR_RIGHT; + } + + // order is + return ORDER_COLLINEAR_CONTAIN; +} +//---------------------------------------------------------------------------- +void ConvexHull2D::RemoveCollinear() +{ + if (m_iHQuantity <= 2) + return; + + Real fSaveFuzz = Vector2::FUZZ; + Vector2::FUZZ = ms_fVeqEpsilon; + + vector kHull; + kHull.reserve(m_iHQuantity); + for (int i0 = m_iHQuantity - 1, i1 = 0, i2 = 1; i1 < m_iHQuantity; /**/) + { + int iCT = CollinearTest(m_akVertex[m_aiHIndex[i0]], + m_akVertex[m_aiHIndex[i1]], m_akVertex[m_aiHIndex[i2]]); + + if (iCT == ORDER_POSITIVE || iCT == ORDER_NEGATIVE) + { + // points are not collinear + kHull.push_back(m_aiHIndex[i1]); + } + + i0 = i1++; + if (++i2 == m_iHQuantity) + i2 = 0; + } + + // construct index array for ordered vertices of convex hull + m_iHQuantity = kHull.size(); + delete[] m_aiHIndex; + m_aiHIndex = new int[m_iHQuantity]; + memcpy(m_aiHIndex, &kHull.front(), m_iHQuantity * sizeof(int)); + + Vector2::FUZZ = fSaveFuzz; +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// divide-and-conquer hull +//---------------------------------------------------------------------------- +void ConvexHull2D::ByDivideAndConquer() +{ + Real fSaveFuzz = Vector2::FUZZ; + Vector2::FUZZ = ms_fVeqEpsilon; + + // Sort by x-component and store in contiguous array. The sort is + // O(N log N). + SVArray kSVArray(m_iVQuantity); + int i; + for (i = 0; i < m_iVQuantity; i++) + { + kSVArray[i].m_kV = m_akVertex[i]; + kSVArray[i].m_iIndex = i; + } + sort(kSVArray.begin(), kSVArray.end()); + + // remove duplicate points + SVArray::iterator pkEnd = unique(kSVArray.begin(), kSVArray.end()); + kSVArray.erase(pkEnd, kSVArray.end()); + + // compute convex hull using divide-and-conquer + SVArray kHull; + kHull.reserve(kSVArray.size()); + m_iHullType = HULL_POINT; + GetHull(0, kSVArray.size() - 1, kSVArray, kHull); + + // construct index array for ordered vertices of convex hull + m_iHQuantity = kHull.size(); + m_aiHIndex = new int[m_iHQuantity]; + for (i = 0; i < m_iHQuantity; i++) + m_aiHIndex[i] = kHull[i].m_iIndex; + + Vector2::FUZZ = fSaveFuzz; +} +//---------------------------------------------------------------------------- +void ConvexHull2D::GetHull(int i0, int i1, const SVArray &rkSVArray, + SVArray &rkHull) +{ + int iQuantity = i1 - i0 + 1; + if (iQuantity > 1) + { + // middle index of input range + int iMid = (i0 + i1) / 2; + + // find hull of subsets (iMid-i0+1 >= i1-iMid) + SVArray kLHull, kRHull; + kLHull.reserve(iMid - i0 + 1); + kRHull.reserve(i1 - iMid); + + GetHull(i0, iMid, rkSVArray, kLHull); + GetHull(iMid + 1, i1, rkSVArray, kRHull); + + // merge the convex hulls into a single convex hull + Merge(kLHull, kRHull, rkHull); + } + else + { + // convex hull is a single point + rkHull.push_back(rkSVArray[i0]); + } +} +//---------------------------------------------------------------------------- +void ConvexHull2D::Merge(SVArray &rkLHull, SVArray &rkRHull, SVArray &rkHull) +{ + // merge small sets, handle cases when sets are collinear + int iLSize = rkLHull.size(), iRSize = rkRHull.size(); + if (iLSize == 1) + { + if (iRSize == 1) + { + rkHull.push_back(rkLHull[0]); + rkHull.push_back(rkRHull[0]); + if (m_iHullType != HULL_PLANAR) + m_iHullType = HULL_LINEAR; + return; + } + else if (iRSize == 2) + { + MergeLinear(rkLHull[0], rkRHull); + rkHull = rkRHull; + return; + } + } + else if (iLSize == 2) + { + if (iRSize == 1) + { + MergeLinear(rkRHull[0], rkLHull); + rkHull = rkLHull; + return; + } + else if (iRSize == 2) + { + MergeLinear(rkRHull[1], rkLHull); + + if (rkLHull.size() == 2) + { + MergeLinear(rkRHull[0], rkLHull); + rkHull = rkLHull; + return; + } + + // fall-through, LHull is a triangle, RHull is a point + iLSize = 3; + iRSize = 1; + rkRHull.pop_back(); + } + } + + // find rightmost point of left hull + Real fMax = rkLHull[0].m_kV.x; + int i, iLMax = 0; + for (i = 1; i < iLSize; i++) + { + if (rkLHull[i].m_kV.x > fMax) + { + fMax = rkLHull[i].m_kV.x; + iLMax = i; + } + } + + // find leftmost point of right hull + Real fMin = rkRHull[0].m_kV.x; + int iRMin = 0; + for (i = 1; i < iRSize; i++) + { + if (rkRHull[i].m_kV.x < fMin) + { + fMin = rkRHull[i].m_kV.x; + iRMin = i; + } + } + + // get lower tangent to hulls (LL = lower left, LR = lower right) + int iLLIndex = iLMax, iLRIndex = iRMin; + GetTangent(rkLHull, rkRHull, iLLIndex, iLRIndex); + + // get upper tangent to hulls (UL = upper left, UR = upper right) + int iULIndex = iLMax, iURIndex = iRMin; + GetTangent(rkRHull, rkLHull, iURIndex, iULIndex); + + // Construct the counterclockwise-ordered merged-hull vertices. + // TO DO. If the hull is stored using linked lists, this block can be + // improved by an O(1) detach, attach, and delete of the appropriate + // sublists. + i = iLRIndex; + while (true) + { + rkHull.push_back(rkRHull[i]); + if (i == iURIndex) + break; + + if (++i == iRSize) + i = 0; + } + + i = iULIndex; + while (true) + { + rkHull.push_back(rkLHull[i]); + if (i == iLLIndex) + break; + + if (++i == iLSize) + i = 0; + } +} +//---------------------------------------------------------------------------- +void ConvexHull2D::MergeLinear(const SortedVertex &rkP, SVArray &rkHull) +{ + // hull = + + switch (CollinearTest(rkP.m_kV, rkHull[0].m_kV, rkHull[1].m_kV)) + { + case ORDER_POSITIVE: + // merged hull is triangle + m_iHullType = HULL_PLANAR; + rkHull.push_back(rkP); + break; + case ORDER_NEGATIVE: + { + // merged hull is triangle + m_iHullType = HULL_PLANAR; + SortedVertex kSave = rkHull[0]; + rkHull[0] = rkHull[1]; + rkHull[1] = kSave; + rkHull.push_back(rkP); + break; + } + case ORDER_COLLINEAR_LEFT: + // collinear order is , merged hull is + rkHull[0] = rkP; + break; + case ORDER_COLLINEAR_RIGHT: + // collinear order is , merged hull is + rkHull[1] = rkP; + break; + // case ORDER_COLLINEAR_CONTAIN: + // collinear order is , merged hull is (no change) + } +} +//---------------------------------------------------------------------------- +void ConvexHull2D::GetTangent(const SVArray &rkLHull, const SVArray &rkRHull, + int &riL, int &riR) +{ + // In theory the loop terminates in a finite number of steps, but the + // upper bound for the loop variable is used to trap problems caused by + // floating point round-off errors that might lead to an infinite loop. + + int iLSize = rkLHull.size(), iRSize = rkRHull.size(); + int iLSizeM1 = iLSize - 1, iRSizeM1 = iRSize - 1; + int i; + for (i = 0; i < iLSize + iRSize; i++) + { + // end points of potential tangent + const Vector2 &rkL1 = rkLHull[riL].m_kV; + const Vector2 &rkR0 = rkRHull[riR].m_kV; + + // walk along left hull to find tangency + int iLm1 = (riL > 0 ? riL - 1 : iLSizeM1); + const Vector2 &rkL0 = rkLHull[iLm1].m_kV; + int iCT = CollinearTest(rkR0, rkL0, rkL1); + if (iCT == ORDER_NEGATIVE || iCT == ORDER_COLLINEAR_LEFT) + { + riL = iLm1; + continue; + } + + // walk along right hull to find tangency + int iRp1 = (riR < iRSizeM1 ? riR + 1 : 0); + const Vector2 &rkR1 = rkRHull[iRp1].m_kV; + iCT = CollinearTest(rkL1, rkR0, rkR1); + if (iCT == ORDER_NEGATIVE || iCT == ORDER_COLLINEAR_RIGHT) + { + riR = iRp1; + continue; + } + + // tangent segment has been found + break; + } + + // detect "infinite loop" caused by floating point round-off errors + // VERIFY( i < iLSize+iRSize ); +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// incremental hull +//---------------------------------------------------------------------------- +void ConvexHull2D::ByIncremental() +{ + Real fSaveFuzz = Vector2::FUZZ; + Vector2::FUZZ = ms_fVeqEpsilon; + + // Sort by x-component and store in contiguous array. The sort is + // O(N log N). + SVArray kSVArray(m_iVQuantity); + int i; + for (i = 0; i < m_iVQuantity; i++) + { + kSVArray[i].m_kV = m_akVertex[i]; + kSVArray[i].m_iIndex = i; + } + sort(kSVArray.begin(), kSVArray.end()); + + // remove duplicate points + SVArray::iterator pkEnd = unique(kSVArray.begin(), kSVArray.end()); + kSVArray.erase(pkEnd, kSVArray.end()); + + int ccc = kSVArray.size(); + + // Compute convex hull incrementally. The first and second vertices in + // the hull are managed separately until at least one triangle is formed. + // At that time an array is used to store the hull in counterclockwise + // order. + m_iHullType = HULL_POINT; + m_kHull.push_back(kSVArray[0]); + for (i = 1; i < (int)kSVArray.size(); i++) + { + switch (m_iHullType) + { + case HULL_POINT: + m_iHullType = HULL_LINEAR; + m_kHull.push_back(kSVArray[i]); + break; + case HULL_LINEAR: + MergeLinear(kSVArray[i]); + break; + case HULL_PLANAR: + MergePlanar(kSVArray[i]); + break; + } + } + + // construct index array for ordered vertices of convex hull + m_iHQuantity = m_kHull.size(); + m_aiHIndex = new int[m_iHQuantity]; + for (i = 0; i < m_iHQuantity; i++) + m_aiHIndex[i] = m_kHull[i].m_iIndex; + + Vector2::FUZZ = fSaveFuzz; +} +//---------------------------------------------------------------------------- +void ConvexHull2D::MergeLinear(const SortedVertex &rkP) +{ + switch (CollinearTest(rkP.m_kV, m_kHull[0].m_kV, m_kHull[1].m_kV)) + { + case ORDER_POSITIVE: + // merged hull is + m_iHullType = HULL_PLANAR; + m_kHull.push_back(m_kHull[1]); + m_kHull[1] = m_kHull[0]; + m_kHull[0] = rkP; + break; + case ORDER_NEGATIVE: + // merged hull is + m_iHullType = HULL_PLANAR; + m_kHull.push_back(m_kHull[0]); + m_kHull[0] = rkP; + break; + case ORDER_COLLINEAR_LEFT: + // linear order is , merged hull is + m_kHull[0] = rkP; + break; + case ORDER_COLLINEAR_RIGHT: + // linear order is , merged hull is + m_kHull[1] = rkP; + break; + // case ORDER_COLLINEAR_CONTAIN: linear order is , no change + } +} +//---------------------------------------------------------------------------- +void ConvexHull2D::MergePlanar(const SortedVertex &rkP) +{ + int iSize = m_kHull.size(); + int i, iU, iL, iCT; + + // search counterclockwise for last visible vertex + for (iU = 0, i = 1; iU < iSize; iU = i++) + { + if (i == iSize) + i = 0; + + iCT = CollinearTest(rkP.m_kV, m_kHull[iU].m_kV, m_kHull[i].m_kV); + if (iCT == ORDER_NEGATIVE) + continue; + if (iCT == ORDER_POSITIVE || iCT == ORDER_COLLINEAR_LEFT) + break; + + // iCT == ORDER_COLLINEAR_CONTAIN || iCT == ORDER_COLLINEAR_RIGHT + return; + } + assert(iU < iSize); + + // search clockwise for last visible vertex + for (iL = 0, i = iSize - 1; i >= 0; iL = i--) + { + iCT = CollinearTest(rkP.m_kV, m_kHull[i].m_kV, m_kHull[iL].m_kV); + if (iCT == ORDER_NEGATIVE) + continue; + if (iCT == ORDER_POSITIVE || iCT == ORDER_COLLINEAR_RIGHT) + break; + + // iCT == ORDER_COLLINEAR_CONTAIN || iCT == ORDER_COLLINEAR_LEFT + return; + } + assert(i >= 0); + + // construct the counterclockwise-ordered merged-hull vertices + SVArray kTmpHull; + kTmpHull.push_back(rkP); + while (true) + { + kTmpHull.push_back(m_kHull[iU]); + if (iU == iL) + break; + + if (++iU == iSize) + iU = 0; + } + if (kTmpHull.size() > 2) + m_kHull = kTmpHull; + else + printf("error in ConvexHull2D::MergePlanar"); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcConvexHull2D.h b/src/editors/FreeMagic/MgcConvexHull2D.h new file mode 100644 index 00000000000..9c02219fbc0 --- /dev/null +++ b/src/editors/FreeMagic/MgcConvexHull2D.h @@ -0,0 +1,135 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCCONVEXHULL2D_H +#define MGCCONVEXHULL2D_H + +#include "MgcVector2.h" +#include + +namespace Mgc +{ + + class MAGICFM ConvexHull2D + { + public: + // Construction and destruction. ConvexHull2D does not take ownership + // of the input array. The application is responsible for deleting it. + ConvexHull2D(int iVQuantity, const Vector2 *akVertex); + ~ConvexHull2D(); + + // two different methods to compute convex hull + void ByDivideAndConquer(); + void ByIncremental(); + + // hull stored in counterclockwise order + int GetQuantity() const; + const int *GetIndices() const; + + // remove collinear points on hull + void RemoveCollinear(); + + // test if point is contained by hull + bool ContainsPoint(const Vector2 &rkP) const; + + // The 'vertex equality' epsilon is used to set Vector2::FUZZ for fuzzy + // equality of vector components. Two vectors (x0,y0) and (x1,y1) are + // considered equal if |x1-x0| <= FUZZ and |y1-y0| <= FUZZ. Observe + // that FUZZ = 0 yields an exact equality test. The default value is 0.0. + static Real &VertexEqualityEpsilon(); + + // The 'collinear epsilon' is used to test if three points P0, P1, and P2 + // are collinear. If A = P1-P0 and B = P2-P0, the points are collinear + // in theory if d = A.x*B.y-A.y*B.x = 0. For numerical robustness, the + // test is implemented as |d|^2 <= e*|A|^2*|B|^2 where e is the collinear + // epsilon. The idea is that d = |Cross((A,0),(B,0))| = |A|*|B|*|sin(t)| + // where t is the angle between A and B. Therefore, the comparison is + // really |sin(t)|^2 <= e, a relative error test. The default e = 1e-06. + static Real &CollinearEpsilon(); + + protected: + // support for O(log N) point-in-hull test + bool SubContainsPoint(const Vector2 &rkP, int i0, int i1) const; + + // for sorting + class SortedVertex + { + public: + bool operator==(const SortedVertex &rkSV) const; + bool operator<(const SortedVertex &rkSV) const; + + // Added to satisfy the SGI Mips Pro CC compiler that appears to be + // instantiating this, but never using it. + bool operator!=(const SortedVertex &rkSV) const + { + return !operator==(rkSV); + } + + Vector2 m_kV; + int m_iIndex; + }; + + typedef std::vector SVArray; + + // hull dimensions + enum + { + HULL_POINT, + HULL_LINEAR, + HULL_PLANAR + }; + + // for collinearity tests + enum + { + ORDER_POSITIVE, + ORDER_NEGATIVE, + ORDER_COLLINEAR_LEFT, + ORDER_COLLINEAR_RIGHT, + ORDER_COLLINEAR_CONTAIN + }; + + int CollinearTest(const Vector2 &rkP, const Vector2 &rkQ0, + const Vector2 &rkQ1) const; + + // construct convex hull using divide-and-conquer + void GetHull(int i0, int i1, const SVArray &rkSVArray, SVArray &rkHull); + void Merge(SVArray &rkLHull, SVArray &rkRHull, SVArray &rkHull); + void MergeLinear(const SortedVertex &rkP, SVArray &rkHull); + void GetTangent(const SVArray &rkLHull, const SVArray &rkRHull, + int &riL, int &riR); + + // construct convex hull incrementally + void MergeLinear(const SortedVertex &rkP); + void MergePlanar(const SortedVertex &rkP); + + // vertex information + int m_iVQuantity; + const Vector2 *m_akVertex; + + // hull information + int m_iHullType; + SVArray m_kHull; + + // indices for ordered vertices of hull + int m_iHQuantity; + int *m_aiHIndex; + + static Real ms_fVeqEpsilon; + static Real ms_fColEpsilon; + }; + +#include "MgcConvexHull2D.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcConvexHull2D.inl b/src/editors/FreeMagic/MgcConvexHull2D.inl new file mode 100644 index 00000000000..b88b9bbb930 --- /dev/null +++ b/src/editors/FreeMagic/MgcConvexHull2D.inl @@ -0,0 +1,33 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline int ConvexHull2D::GetQuantity() const +{ + return m_iHQuantity; +} +//---------------------------------------------------------------------------- +inline const int *ConvexHull2D::GetIndices() const +{ + return m_aiHIndex; +} +//---------------------------------------------------------------------------- +inline Real &ConvexHull2D::VertexEqualityEpsilon() +{ + return ms_fVeqEpsilon; +} +//---------------------------------------------------------------------------- +inline Real &ConvexHull2D::CollinearEpsilon() +{ + return ms_fColEpsilon; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcConvexHull3D.h b/src/editors/FreeMagic/MgcConvexHull3D.h new file mode 100644 index 00000000000..27f12b9b5fa --- /dev/null +++ b/src/editors/FreeMagic/MgcConvexHull3D.h @@ -0,0 +1,174 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCCONVEXHULL3D_H +#define MGCCONVEXHULL3D_H + +#include "MgcTriangleMesh.h" +#include "MgcVector3.h" +#include + +namespace Mgc +{ + + class MAGICFM ConvexHull3D + { + public: + // Construction and destruction. ConvexHull3D does not take ownership + // of the input array. The application is responsible for deleting it. + ConvexHull3D(int iVQuantity, const Vector3 *akVertex); + ~ConvexHull3D(); + + // Construct the hull a point at a time. This is an O(N^2) algorithm. + void ByIncremental(); + + // TO DO. Implement 'void ByDivideAndConquer'. This is an O(N log N) + // algorithm. + + // Hull types. The quantity and indices are interpreted as follows. + enum + { + // Hull is a single point. Quantity is 1, index array has one + // element (index 0). + HULL_POINT, + + // Hull is a line segment. Quantity is 2, index array has two + // elements that are indices to the end points of the segment. + HULL_LINEAR, + + // Hull is a planar convex polygon. Quantity is number of vertices, + // index array has the indices to that number of vertices. The + // indices represent an ordered polygon, but since there is no + // associated normal vector, you need to supply your own and determine + // if the ordering is clockwise or counterclockwise relative to that + // normal. If you want a triangle connectivity array, you will have + // to triangulate the polygon yourself. + HULL_PLANAR, + + // The hull is a convex polyhedron (positive volume). Quantity is + // number of triangles, index array has 3 times that many elements. + // Each triple of indices represents a triangle in the hull. All the + // triangles are counterclockwise ordered as you view the polyhedron + // from the outside. + HULL_SPATIAL + }; + + int GetType() const; + int GetQuantity() const; + const int *GetIndices() const; + + // Remove collinear points in edges of planar hull. Has no effect on + // hulls with positive volume. + void RemoveCollinear(); + + // TO DO. Implement 'void RemoveCoplanar ()'. The result is a convex + // polyhedron whose faces are non-coplanar convex polygons, not + // necessarily triangles. After such a call, GetQuantity() should return + // the number of faces. GetIndices() will return an integer array that + // consists of subarrays, each subarray corresponding to a face. The + // first index of the subarray is number of indices for that face, those + // indices stored in the remainder of the subblock. + + // The 'vertex equality' epsilon is used to set Vector3::FUZZ for fuzzy + // equality of vector components. Two vectors (x0,y0,z0) and (x1,y1,z1) + // are considered equal if |x1-x0| <= FUZZ, |y1-y0| <= FUZZ, and + // |z1-z0| <= FUZZ. Observe that FUZZ = 0 yields an exact equality test. + // The default value is 0.0. + static Real &VertexEqualityEpsilon(); + + // The 'collinear epsilon' is used to test if three points P0, P1, and P2 + // are collinear. This is a relative error test on the sine of the angle + // between P1-P0 and P2-P0. The default value is 1e-06. + static Real &CollinearEpsilon(); + + // The 'coplanar epsilon' is used to test if four points P0, P1, P2, and + // P3 are coplanar. This is a relative error test on the volume of the + // tetrahedron formed by the four points. The default value is 1e-06. + static Real &CoplanarEpsilon(); + + protected: + // for sorting + class SortedVertex + { + public: + bool operator==(const SortedVertex &rkSV) const; + bool operator<(const SortedVertex &rkSV) const; + + // Added to satisfy the SGI Mips Pro CC compiler that appears to be + // instantiating this, but never using it. + bool operator!=(const SortedVertex &rkSV) const + { + return !operator==(rkSV); + } + + Vector3 m_kV; + int m_iIndex; + }; + + typedef std::vector SVArray; + + // for collinearity and coplanaritytests + enum + { + ORDER_TRIANGLE, + ORDER_COLLINEAR_LEFT, + ORDER_COLLINEAR_RIGHT, + ORDER_COLLINEAR_CONTAIN, + ORDER_POSITIVE, + ORDER_NEGATIVE, + ORDER_COPLANAR, + ORDER_COPLANAR_INSIDE, + ORDER_COPLANAR_OUTSIDE + }; + + int CollinearTest(const Vector3 &rkP, const Vector3 &rkQ0, + const Vector3 &rkQ1) const; + + int CoplanarTest(const Vector3 &rkP, const Vector3 &rkQ0, + const Vector3 &rkQ1, const Vector3 &rkQ2) const; + + // test uses the plane defined by m_kPlaneOrigin and m_kPlaneNormal + int CoplanarTest(const Vector3 &rkP) const; + + // construct convex hull incrementally + void MergeLinear(const SortedVertex &rkP); + void MergePlanar(const SortedVertex &rkP); + void MergeSpatial(const SortedVertex &rkP); + + // vertex information + int m_iVQuantity; + const Vector3 *m_akVertex; + + // hull information + int m_iHQuantity; + int *m_aiHIndex; + int m_iHullType; + + // linear or planar hull + SVArray m_kHullP; + Vector3 m_kPlaneOrigin, m_kPlaneNormal; + + // spatial hull + TriangleMesh m_kHullS; + int m_iLastIndex; + + // tweaking parameters + static Real ms_fVertexEqualityEpsilon; + static Real ms_fCollinearEpsilon; + static Real ms_fCoplanarEpsilon; + }; + +#include "MgcConvexHull3D.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcConvexHull3D.inl b/src/editors/FreeMagic/MgcConvexHull3D.inl new file mode 100644 index 00000000000..fda8d0539e2 --- /dev/null +++ b/src/editors/FreeMagic/MgcConvexHull3D.inl @@ -0,0 +1,43 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline int ConvexHull3D::GetType() const +{ + return m_iHullType; +} +//---------------------------------------------------------------------------- +inline int ConvexHull3D::GetQuantity() const +{ + return m_iHQuantity; +} +//---------------------------------------------------------------------------- +inline const int *ConvexHull3D::GetIndices() const +{ + return m_aiHIndex; +} +//---------------------------------------------------------------------------- +inline Real &ConvexHull3D::VertexEqualityEpsilon() +{ + return ms_fVertexEqualityEpsilon; +} +//---------------------------------------------------------------------------- +inline Real &ConvexHull3D::CollinearEpsilon() +{ + return ms_fCollinearEpsilon; +} +//---------------------------------------------------------------------------- +inline Real &ConvexHull3D::CoplanarEpsilon() +{ + return ms_fCoplanarEpsilon; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcCylinder.h b/src/editors/FreeMagic/MgcCylinder.h new file mode 100644 index 00000000000..e2c3d58a9e6 --- /dev/null +++ b/src/editors/FreeMagic/MgcCylinder.h @@ -0,0 +1,74 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCCYLINDER_H +#define MGCCYLINDER_H + +#include "MgcSegment3.h" + +namespace Mgc +{ + + class MAGICFM Cylinder + { + public: + // Cylinder line segment has end points C-(H/2)*D and C+(H/2)*D where + // D is a unit-length vector. H is infinity for infinite cylinder. + + Cylinder(); + + Vector3 &Center(); + const Vector3 &Center() const; + + Vector3 &Direction(); + const Vector3 &Direction() const; + + Real &Height(); + Real Height() const; + + Real &Radius(); + Real Radius() const; + + // A value of 'true' means the cylinder caps (the end disks) are included + // as part of the cylinder. A value of 'false' means treat the cylinder + // as hollow--the end disks are not part of the object. + bool &Capped(); + bool Capped() const; + + Segment3 GetSegment() const; + + // Call this function to generate a coordinate system for the cylinder, + // {U,V,W}, an orthonormal set where W is the unit-length direction of + // the cylinder axis. This is necessary for cylinder-cylinder + // intersection testing to avoid creating U and V for every test. + void GenerateCoordinateSystem(); + Vector3 &U(); + const Vector3 &U() const; + Vector3 &V(); + const Vector3 &V() const; + Vector3 &W(); + const Vector3 &W() const; + + protected: + Vector3 m_kCenter; + Vector3 m_kDirection; // W + Vector3 m_kU, m_kV; // U, V + Real m_fHeight; + Real m_fRadius; + bool m_bCapped; + }; + +#include "MgcCylinder.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcCylinder.inl b/src/editors/FreeMagic/MgcCylinder.inl new file mode 100644 index 00000000000..f60218ca68c --- /dev/null +++ b/src/editors/FreeMagic/MgcCylinder.inl @@ -0,0 +1,111 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Cylinder::Cylinder() +{ + // no initialization for efficiency +} +//---------------------------------------------------------------------------- +inline Vector3 &Cylinder::Center() +{ + return m_kCenter; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Cylinder::Center() const +{ + return m_kCenter; +} +//---------------------------------------------------------------------------- +inline Vector3 &Cylinder::Direction() +{ + return m_kDirection; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Cylinder::Direction() const +{ + return m_kDirection; +} +//---------------------------------------------------------------------------- +inline Real &Cylinder::Height() +{ + return m_fHeight; +} +//---------------------------------------------------------------------------- +inline Real Cylinder::Height() const +{ + return m_fHeight; +} +//---------------------------------------------------------------------------- +inline Real &Cylinder::Radius() +{ + return m_fRadius; +} +//---------------------------------------------------------------------------- +inline Real Cylinder::Radius() const +{ + return m_fRadius; +} +//---------------------------------------------------------------------------- +inline bool &Cylinder::Capped() +{ + return m_bCapped; +} +//---------------------------------------------------------------------------- +inline bool Cylinder::Capped() const +{ + return m_bCapped; +} +//---------------------------------------------------------------------------- +inline Segment3 Cylinder::GetSegment() const +{ + Segment3 kSegment; + kSegment.Direction() = m_fHeight * m_kDirection; + kSegment.Origin() = m_kCenter - 0.5 * kSegment.Direction(); + return kSegment; +} +//---------------------------------------------------------------------------- +inline void Cylinder::GenerateCoordinateSystem() +{ + Vector3::GenerateOrthonormalBasis(m_kU, m_kV, m_kDirection, true); +} +//---------------------------------------------------------------------------- +inline Vector3 &Cylinder::U() +{ + return m_kU; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Cylinder::U() const +{ + return m_kU; +} +//---------------------------------------------------------------------------- +inline Vector3 &Cylinder::V() +{ + return m_kV; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Cylinder::V() const +{ + return m_kV; +} +//---------------------------------------------------------------------------- +inline Vector3 &Cylinder::W() +{ + return m_kDirection; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Cylinder::W() const +{ + return m_kDirection; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcDist3DVecLin.cpp b/src/editors/FreeMagic/MgcDist3DVecLin.cpp new file mode 100644 index 00000000000..2d56ee02f7f --- /dev/null +++ b/src/editors/FreeMagic/MgcDist3DVecLin.cpp @@ -0,0 +1,101 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#include "MgcDist3DVecLin.h" +using namespace Mgc; + +//---------------------------------------------------------------------------- +Real Mgc::SqrDistance(const Vector3 &rkPoint, const Line3 &rkLine, + Real *pfParam) +{ + Vector3 kDiff = rkPoint - rkLine.Origin(); + Real fSqrLen = rkLine.Direction().SquaredLength(); + Real fT = kDiff.Dot(rkLine.Direction()) / fSqrLen; + kDiff -= fT * rkLine.Direction(); + + if (pfParam) + *pfParam = fT; + + return kDiff.SquaredLength(); +} +//---------------------------------------------------------------------------- +Real Mgc::SqrDistance(const Vector3 &rkPoint, const Ray3 &rkRay, + Real *pfParam) +{ + Vector3 kDiff = rkPoint - rkRay.Origin(); + Real fT = kDiff.Dot(rkRay.Direction()); + + if (fT <= 0.0f) + { + fT = 0.0f; + } + else + { + fT /= rkRay.Direction().SquaredLength(); + kDiff -= fT * rkRay.Direction(); + } + + if (pfParam) + *pfParam = fT; + + return kDiff.SquaredLength(); +} +//---------------------------------------------------------------------------- +Real Mgc::SqrDistance(const Vector3 &rkPoint, const Segment3 &rkSegment, + Real *pfParam) +{ + Vector3 kDiff = rkPoint - rkSegment.Origin(); + Real fT = kDiff.Dot(rkSegment.Direction()); + + if (fT <= 0.0f) + { + fT = 0.0f; + } + else + { + Real fSqrLen = rkSegment.Direction().SquaredLength(); + if (fT >= fSqrLen) + { + fT = 1.0f; + kDiff -= rkSegment.Direction(); + } + else + { + fT /= fSqrLen; + kDiff -= fT * rkSegment.Direction(); + } + } + + if (pfParam) + *pfParam = fT; + + return kDiff.SquaredLength(); +} +//---------------------------------------------------------------------------- +Real Mgc::Distance(const Vector3 &rkPoint, const Line3 &rkLine, + Real *pfParam) +{ + return Math::Sqrt(SqrDistance(rkPoint, rkLine, pfParam)); +} +//---------------------------------------------------------------------------- +Real Mgc::Distance(const Vector3 &rkPoint, const Ray3 &rkRay, + Real *pfParam) +{ + return Math::Sqrt(SqrDistance(rkPoint, rkRay, pfParam)); +} +//---------------------------------------------------------------------------- +Real Mgc::Distance(const Vector3 &rkPoint, const Segment3 &rkSegment, + Real *pfParam) +{ + return Math::Sqrt(SqrDistance(rkPoint, rkSegment, pfParam)); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcDist3DVecLin.h b/src/editors/FreeMagic/MgcDist3DVecLin.h new file mode 100644 index 00000000000..d75eb87b933 --- /dev/null +++ b/src/editors/FreeMagic/MgcDist3DVecLin.h @@ -0,0 +1,47 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCDIST3DVECLIN_H +#define MGCDIST3DVECLIN_H + +#include "MgcLine3.h" +#include "MgcRay3.h" +#include "MgcSegment3.h" + +namespace Mgc +{ + + // squared distance measurements + + MAGICFM Real SqrDistance(const Vector3 &rkPoint, const Line3 &rkLine, + Real *pfParam = NULL); + + MAGICFM Real SqrDistance(const Vector3 &rkPoint, const Ray3 &rkRay, + Real *pfParam = NULL); + + MAGICFM Real SqrDistance(const Vector3 &rkPoint, const Segment3 &rkSegment, + Real *pfParam = NULL); + + // distance measurements + + MAGICFM Real Distance(const Vector3 &rkPoint, const Line3 &rkLine, + Real *pfParam = NULL); + + MAGICFM Real Distance(const Vector3 &rkPoint, const Ray3 &rkRay, + Real *pfParam = NULL); + + MAGICFM Real Distance(const Vector3 &rkPoint, const Segment3 &rkSegment, + Real *pfParam = NULL); + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcEigen.cpp b/src/editors/FreeMagic/MgcEigen.cpp new file mode 100644 index 00000000000..ccdbedafee0 --- /dev/null +++ b/src/editors/FreeMagic/MgcEigen.cpp @@ -0,0 +1,669 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +//#include "stdafx.h" +#pragma hdrstop + +#include "MgcEigen.h" +using namespace Mgc; + +//---------------------------------------------------------------------------- +Eigen::Eigen(int iSize) +{ + assert(iSize >= 2); + m_iSize = iSize; + + m_aafMat = new Real *[m_iSize]; + for (int i = 0; i < m_iSize; i++) + m_aafMat[i] = new Real[m_iSize]; + + m_afDiag = new Real[m_iSize]; + m_afSubd = new Real[m_iSize]; +} +//---------------------------------------------------------------------------- +Eigen::~Eigen() +{ + delete[] m_afSubd; + delete[] m_afDiag; + for (int i = 0; i < m_iSize; i++) + delete[] m_aafMat[i]; + delete[] m_aafMat; +} +//---------------------------------------------------------------------------- +void Eigen::Tridiagonal2(Real **m_aafMat, Real *m_afDiag, Real *m_afSubd) +{ + // matrix is already tridiagonal + m_afDiag[0] = m_aafMat[0][0]; + m_afDiag[1] = m_aafMat[1][1]; + m_afSubd[0] = m_aafMat[0][1]; + m_afSubd[1] = 0.0f; + m_aafMat[0][0] = 1.0f; + m_aafMat[0][1] = 0.0f; + m_aafMat[1][0] = 0.0f; + m_aafMat[1][1] = 1.0f; +} +//---------------------------------------------------------------------------- +void Eigen::Tridiagonal3(Real **m_aafMat, Real *m_afDiag, Real *m_afSubd) +{ + Real fM00 = m_aafMat[0][0]; + Real fM01 = m_aafMat[0][1]; + Real fM02 = m_aafMat[0][2]; + Real fM11 = m_aafMat[1][1]; + Real fM12 = m_aafMat[1][2]; + Real fM22 = m_aafMat[2][2]; + + m_afDiag[0] = fM00; + m_afSubd[2] = 0.0f; + if (fM02 != 0.0f) + { + Real fLength = Math::Sqrt(fM01 * fM01 + fM02 * fM02); + Real fInvLength = 1.0f / fLength; + fM01 *= fInvLength; + fM02 *= fInvLength; + Real fQ = 2.0f * fM01 * fM12 + fM02 * (fM22 - fM11); + m_afDiag[1] = fM11 + fM02 * fQ; + m_afDiag[2] = fM22 - fM02 * fQ; + m_afSubd[0] = fLength; + m_afSubd[1] = fM12 - fM01 * fQ; + m_aafMat[0][0] = 1.0f; + m_aafMat[0][1] = 0.0f; + m_aafMat[0][2] = 0.0f; + m_aafMat[1][0] = 0.0f; + m_aafMat[1][1] = fM01; + m_aafMat[1][2] = fM02; + m_aafMat[2][0] = 0.0f; + m_aafMat[2][1] = fM02; + m_aafMat[2][2] = -fM01; + } + else + { + m_afDiag[1] = fM11; + m_afDiag[2] = fM22; + m_afSubd[0] = fM01; + m_afSubd[1] = fM12; + m_aafMat[0][0] = 1.0f; + m_aafMat[0][1] = 0.0f; + m_aafMat[0][2] = 0.0f; + m_aafMat[1][0] = 0.0f; + m_aafMat[1][1] = 1.0f; + m_aafMat[1][2] = 0.0f; + m_aafMat[2][0] = 0.0f; + m_aafMat[2][1] = 0.0f; + m_aafMat[2][2] = 1.0f; + } +} +//---------------------------------------------------------------------------- +void Eigen::Tridiagonal4(Real **m_aafMat, Real *m_afDiag, Real *m_afSubd) +{ + // save matrix M + Real fM00 = m_aafMat[0][0]; + Real fM01 = m_aafMat[0][1]; + Real fM02 = m_aafMat[0][2]; + Real fM03 = m_aafMat[0][3]; + Real fM11 = m_aafMat[1][1]; + Real fM12 = m_aafMat[1][2]; + Real fM13 = m_aafMat[1][3]; + Real fM22 = m_aafMat[2][2]; + Real fM23 = m_aafMat[2][3]; + Real fM33 = m_aafMat[3][3]; + + m_afDiag[0] = fM00; + m_afSubd[3] = 0.0f; + + m_aafMat[0][0] = 1.0f; + m_aafMat[0][1] = 0.0f; + m_aafMat[0][2] = 0.0f; + m_aafMat[0][3] = 0.0f; + m_aafMat[1][0] = 0.0f; + m_aafMat[2][0] = 0.0f; + m_aafMat[3][0] = 0.0f; + + Real fLength, fInvLength; + + if (fM02 != 0.0f || fM03 != 0.0f) + { + Real fQ11, fQ12, fQ13; + Real fQ21, fQ22, fQ23; + Real fQ31, fQ32, fQ33; + + // build column Q1 + fLength = Math::Sqrt(fM01 * fM01 + fM02 * fM02 + fM03 * fM03); + fInvLength = 1.0f / fLength; + fQ11 = fM01 * fInvLength; + fQ21 = fM02 * fInvLength; + fQ31 = fM03 * fInvLength; + + m_afSubd[0] = fLength; + + // compute S*Q1 + Real fV0 = fM11 * fQ11 + fM12 * fQ21 + fM13 * fQ31; + Real fV1 = fM12 * fQ11 + fM22 * fQ21 + fM23 * fQ31; + Real fV2 = fM13 * fQ11 + fM23 * fQ21 + fM33 * fQ31; + + m_afDiag[1] = fQ11 * fV0 + fQ21 * fV1 + fQ31 * fV2; + + // build column Q3 = Q1x(S*Q1) + fQ13 = fQ21 * fV2 - fQ31 * fV1; + fQ23 = fQ31 * fV0 - fQ11 * fV2; + fQ33 = fQ11 * fV1 - fQ21 * fV0; + fLength = Math::Sqrt(fQ13 * fQ13 + fQ23 * fQ23 + fQ33 * fQ33); + if (fLength > 0.0f) + { + fInvLength = 1.0f / fLength; + fQ13 *= fInvLength; + fQ23 *= fInvLength; + fQ33 *= fInvLength; + + // build column Q2 = Q3xQ1 + fQ12 = fQ23 * fQ31 - fQ33 * fQ21; + fQ22 = fQ33 * fQ11 - fQ13 * fQ31; + fQ32 = fQ13 * fQ21 - fQ23 * fQ11; + + fV0 = fQ12 * fM11 + fQ22 * fM12 + fQ32 * fM13; + fV1 = fQ12 * fM12 + fQ22 * fM22 + fQ32 * fM23; + fV2 = fQ12 * fM13 + fQ22 * fM23 + fQ32 * fM33; + m_afSubd[1] = fQ11 * fV0 + fQ21 * fV1 + fQ31 * fV2; + m_afDiag[2] = fQ12 * fV0 + fQ22 * fV1 + fQ32 * fV2; + m_afSubd[2] = fQ13 * fV0 + fQ23 * fV1 + fQ33 * fV2; + + fV0 = fQ13 * fM11 + fQ23 * fM12 + fQ33 * fM13; + fV1 = fQ13 * fM12 + fQ23 * fM22 + fQ33 * fM23; + fV2 = fQ13 * fM13 + fQ23 * fM23 + fQ33 * fM33; + m_afDiag[3] = fQ13 * fV0 + fQ23 * fV1 + fQ33 * fV2; + } + else + { + // S*Q1 parallel to Q1, choose any valid Q2 and Q3 + m_afSubd[1] = 0.0f; + + fLength = fQ21 * fQ21 + fQ31 * fQ31; + if (fLength > 0.0f) + { + fInvLength = 1.0f / fLength; + Real fTmp = fQ11 - 1.0f; + fQ12 = -fQ21; + fQ22 = 1.0f + fTmp * fQ21 * fQ21 * fInvLength; + fQ32 = fTmp * fQ21 * fQ31 * fInvLength; + + fQ13 = -fQ31; + fQ23 = fQ32; + fQ33 = 1.0f + fTmp * fQ31 * fQ31 * fInvLength; + + fV0 = fQ12 * fM11 + fQ22 * fM12 + fQ32 * fM13; + fV1 = fQ12 * fM12 + fQ22 * fM22 + fQ32 * fM23; + fV2 = fQ12 * fM13 + fQ22 * fM23 + fQ32 * fM33; + m_afDiag[2] = fQ12 * fV0 + fQ22 * fV1 + fQ32 * fV2; + m_afSubd[2] = fQ13 * fV0 + fQ23 * fV1 + fQ33 * fV2; + + fV0 = fQ13 * fM11 + fQ23 * fM12 + fQ33 * fM13; + fV1 = fQ13 * fM12 + fQ23 * fM22 + fQ33 * fM23; + fV2 = fQ13 * fM13 + fQ23 * fM23 + fQ33 * fM33; + m_afDiag[3] = fQ13 * fV0 + fQ23 * fV1 + fQ33 * fV2; + } + else + { + // Q1 = (+-1,0,0) + fQ12 = 0.0f; + fQ22 = 1.0f; + fQ32 = 0.0f; + fQ13 = 0.0f; + fQ23 = 0.0f; + fQ33 = 1.0f; + + m_afDiag[2] = fM22; + m_afDiag[3] = fM33; + m_afSubd[2] = fM23; + } + } + + m_aafMat[1][1] = fQ11; + m_aafMat[1][2] = fQ12; + m_aafMat[1][3] = fQ13; + m_aafMat[2][1] = fQ21; + m_aafMat[2][2] = fQ22; + m_aafMat[2][3] = fQ23; + m_aafMat[3][1] = fQ31; + m_aafMat[3][2] = fQ32; + m_aafMat[3][3] = fQ33; + } + else + { + m_afDiag[1] = fM11; + m_afSubd[0] = fM01; + m_aafMat[1][1] = 1.0f; + m_aafMat[2][1] = 0.0f; + m_aafMat[3][1] = 0.0f; + + if (fM13 != 0.0f) + { + fLength = Math::Sqrt(fM12 * fM12 + fM13 * fM13); + fInvLength = 1.0f / fLength; + fM12 *= fInvLength; + fM13 *= fInvLength; + Real fQ = 2.0f * fM12 * fM23 + fM13 * (fM33 - fM22); + + m_afDiag[2] = fM22 + fM13 * fQ; + m_afDiag[3] = fM33 - fM13 * fQ; + m_afSubd[1] = fLength; + m_afSubd[2] = fM23 - fM12 * fQ; + m_aafMat[1][2] = 0.0f; + m_aafMat[1][3] = 0.0f; + m_aafMat[2][2] = fM12; + m_aafMat[2][3] = fM13; + m_aafMat[3][2] = fM13; + m_aafMat[3][3] = -fM12; + } + else + { + m_afDiag[2] = fM22; + m_afDiag[3] = fM33; + m_afSubd[1] = fM12; + m_afSubd[2] = fM23; + m_aafMat[1][2] = 0.0f; + m_aafMat[1][3] = 0.0f; + m_aafMat[2][2] = 1.0f; + m_aafMat[2][3] = 0.0f; + m_aafMat[3][2] = 0.0f; + m_aafMat[3][3] = 1.0f; + } + } +} +//---------------------------------------------------------------------------- +void Eigen::TridiagonalN(int iSize, Real **m_aafMat, Real *m_afDiag, + Real *m_afSubd) +{ + int i0, i1, i2, i3; + + for (i0 = iSize - 1, i3 = iSize - 2; i0 >= 1; i0--, i3--) + { + Real fH = 0.0f, fScale = 0.0f; + + if (i3 > 0) + { + for (i2 = 0; i2 <= i3; i2++) + fScale += Math::FAbs(m_aafMat[i0][i2]); + if (fScale == 0.0f) + { + m_afSubd[i0] = m_aafMat[i0][i3]; + } + else + { + Real fInvScale = 1.0f / fScale; + for (i2 = 0; i2 <= i3; i2++) + { + m_aafMat[i0][i2] *= fInvScale; + fH += m_aafMat[i0][i2] * m_aafMat[i0][i2]; + } + Real fF = m_aafMat[i0][i3]; + Real fG = Math::Sqrt(fH); + if (fF > 0.0f) + fG = -fG; + m_afSubd[i0] = fScale * fG; + fH -= fF * fG; + m_aafMat[i0][i3] = fF - fG; + fF = 0.0f; + Real fInvH = 1.0f / fH; + for (i1 = 0; i1 <= i3; i1++) + { + m_aafMat[i1][i0] = m_aafMat[i0][i1] * fInvH; + fG = 0.0f; + for (i2 = 0; i2 <= i1; i2++) + fG += m_aafMat[i1][i2] * m_aafMat[i0][i2]; + for (i2 = i1 + 1; i2 <= i3; i2++) + fG += m_aafMat[i2][i1] * m_aafMat[i0][i2]; + m_afSubd[i1] = fG * fInvH; + fF += m_afSubd[i1] * m_aafMat[i0][i1]; + } + Real fHalfFdivH = 0.5f * fF * fInvH; + for (i1 = 0; i1 <= i3; i1++) + { + fF = m_aafMat[i0][i1]; + fG = m_afSubd[i1] - fHalfFdivH * fF; + m_afSubd[i1] = fG; + for (i2 = 0; i2 <= i1; i2++) + { + m_aafMat[i1][i2] -= fF * m_afSubd[i2] + + fG * m_aafMat[i0][i2]; + } + } + } + } + else + { + m_afSubd[i0] = m_aafMat[i0][i3]; + } + + m_afDiag[i0] = fH; + } + + m_afDiag[0] = 0.0f; + m_afSubd[0] = 0.0f; + for (i0 = 0, i3 = -1; i0 <= iSize - 1; i0++, i3++) + { + if (m_afDiag[i0] != 0.0f) + { + for (i1 = 0; i1 <= i3; i1++) + { + Real fSum = 0.0f; + for (i2 = 0; i2 <= i3; i2++) + fSum += m_aafMat[i0][i2] * m_aafMat[i2][i1]; + for (i2 = 0; i2 <= i3; i2++) + m_aafMat[i2][i1] -= fSum * m_aafMat[i2][i0]; + } + } + m_afDiag[i0] = m_aafMat[i0][i0]; + m_aafMat[i0][i0] = 1.0f; + for (i1 = 0; i1 <= i3; i1++) + { + m_aafMat[i1][i0] = 0.0f; + m_aafMat[i0][i1] = 0.0f; + } + } + + // re-ordering if Eigen::QLAlgorithm is used subsequently + for (i0 = 1, i3 = 0; i0 < iSize; i0++, i3++) + m_afSubd[i3] = m_afSubd[i0]; + m_afSubd[iSize - 1] = 0.0f; +} +//---------------------------------------------------------------------------- +bool Eigen::QLAlgorithm(int iSize, Real *m_afDiag, Real *m_afSubd, + Real **m_aafMat) +{ + const int iMaxIter = 32; + + for (int i0 = 0; i0 < iSize; i0++) + { + int i1; + for (i1 = 0; i1 < iMaxIter; i1++) + { + int i2; + for (i2 = i0; i2 <= iSize - 2; i2++) + { + Real fTmp = Math::FAbs(m_afDiag[i2]) + + Math::FAbs(m_afDiag[i2 + 1]); + if (Math::FAbs(m_afSubd[i2]) + fTmp == fTmp) + break; + } + if (i2 == i0) + break; + + Real fG = (m_afDiag[i0 + 1] - m_afDiag[i0]) / (2.0f * m_afSubd[i0]); + Real fR = Math::Sqrt(fG * fG + 1.0f); + if (fG < 0.0f) + fG = m_afDiag[i2] - m_afDiag[i0] + m_afSubd[i0] / (fG - fR); + else + fG = m_afDiag[i2] - m_afDiag[i0] + m_afSubd[i0] / (fG + fR); + Real fSin = 1.0f, fCos = 1.0f, fP = 0.0f; + for (int i3 = i2 - 1; i3 >= i0; i3--) + { + Real fF = fSin * m_afSubd[i3]; + Real fB = fCos * m_afSubd[i3]; + if (Math::FAbs(fF) >= Math::FAbs(fG)) + { + fCos = fG / fF; + fR = Math::Sqrt(fCos * fCos + 1.0f); + m_afSubd[i3 + 1] = fF * fR; + fSin = 1.0f / fR; + fCos *= fSin; + } + else + { + fSin = fF / fG; + fR = Math::Sqrt(fSin * fSin + 1.0f); + m_afSubd[i3 + 1] = fG * fR; + fCos = 1.0f / fR; + fSin *= fCos; + } + fG = m_afDiag[i3 + 1] - fP; + fR = (m_afDiag[i3] - fG) * fSin + 2.0f * fB * fCos; + fP = fSin * fR; + m_afDiag[i3 + 1] = fG + fP; + fG = fCos * fR - fB; + + for (int i4 = 0; i4 < iSize; i4++) + { + fF = m_aafMat[i4][i3 + 1]; + m_aafMat[i4][i3 + 1] = fSin * m_aafMat[i4][i3] + fCos * fF; + m_aafMat[i4][i3] = fCos * m_aafMat[i4][i3] - fSin * fF; + } + } + m_afDiag[i0] -= fP; + m_afSubd[i0] = fG; + m_afSubd[i2] = 0.0f; + } + if (i1 == iMaxIter) + return false; + } + + return true; +} +//---------------------------------------------------------------------------- +void Eigen::DecreasingSort(int iSize, Real *afEigval, Real **aafEigvec) +{ + // sort eigenvalues in decreasing order, e[0] >= ... >= e[iSize-1] + for (int i0 = 0, i1; i0 <= iSize - 2; i0++) + { + // locate maximum eigenvalue + i1 = i0; + Real fMax = afEigval[i1]; + int i2; + for (i2 = i0 + 1; i2 < iSize; i2++) + { + if (afEigval[i2] > fMax) + { + i1 = i2; + fMax = afEigval[i1]; + } + } + + if (i1 != i0) + { + // swap eigenvalues + afEigval[i1] = afEigval[i0]; + afEigval[i0] = fMax; + + // swap eigenvectors + for (i2 = 0; i2 < iSize; i2++) + { + Real fTmp = aafEigvec[i2][i0]; + aafEigvec[i2][i0] = aafEigvec[i2][i1]; + aafEigvec[i2][i1] = fTmp; + } + } + } +} +//---------------------------------------------------------------------------- +void Eigen::IncreasingSort(int iSize, Real *afEigval, Real **aafEigvec) +{ + // sort eigenvalues in increasing order, e[0] <= ... <= e[iSize-1] + for (int i0 = 0, i1; i0 <= iSize - 2; i0++) + { + // locate minimum eigenvalue + i1 = i0; + Real fMin = afEigval[i1]; + int i2; + for (i2 = i0 + 1; i2 < iSize; i2++) + { + if (afEigval[i2] < fMin) + { + i1 = i2; + fMin = afEigval[i1]; + } + } + + if (i1 != i0) + { + // swap eigenvalues + afEigval[i1] = afEigval[i0]; + afEigval[i0] = fMin; + + // swap eigenvectors + for (i2 = 0; i2 < iSize; i2++) + { + Real fTmp = aafEigvec[i2][i0]; + aafEigvec[i2][i0] = aafEigvec[i2][i1]; + aafEigvec[i2][i1] = fTmp; + } + } + } +} +//---------------------------------------------------------------------------- +void Eigen::SetMatrix(Real **aafMat) +{ + for (int iRow = 0; iRow < m_iSize; iRow++) + { + for (int iCol = 0; iCol < m_iSize; iCol++) + m_aafMat[iRow][iCol] = aafMat[iRow][iCol]; + } +} +//---------------------------------------------------------------------------- +void Eigen::EigenStuff2() +{ + Tridiagonal2(m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::EigenStuff3() +{ + Tridiagonal3(m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::EigenStuff4() +{ + Tridiagonal4(m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::EigenStuffN() +{ + TridiagonalN(m_iSize, m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::EigenStuff() +{ + switch (m_iSize) + { + case 2: + Tridiagonal2(m_aafMat, m_afDiag, m_afSubd); + break; + case 3: + Tridiagonal3(m_aafMat, m_afDiag, m_afSubd); + break; + case 4: + Tridiagonal4(m_aafMat, m_afDiag, m_afSubd); + break; + default: + TridiagonalN(m_iSize, m_aafMat, m_afDiag, m_afSubd); + break; + } + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::DecrSortEigenStuff2() +{ + Tridiagonal2(m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); + DecreasingSort(m_iSize, m_afDiag, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::DecrSortEigenStuff3() +{ + Tridiagonal3(m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); + DecreasingSort(m_iSize, m_afDiag, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::DecrSortEigenStuff4() +{ + Tridiagonal4(m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); + DecreasingSort(m_iSize, m_afDiag, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::DecrSortEigenStuffN() +{ + TridiagonalN(m_iSize, m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); + DecreasingSort(m_iSize, m_afDiag, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::DecrSortEigenStuff() +{ + switch (m_iSize) + { + case 2: + Tridiagonal2(m_aafMat, m_afDiag, m_afSubd); + break; + case 3: + Tridiagonal3(m_aafMat, m_afDiag, m_afSubd); + break; + case 4: + Tridiagonal4(m_aafMat, m_afDiag, m_afSubd); + break; + default: + TridiagonalN(m_iSize, m_aafMat, m_afDiag, m_afSubd); + break; + } + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); + DecreasingSort(m_iSize, m_afDiag, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::IncrSortEigenStuff2() +{ + Tridiagonal2(m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); + IncreasingSort(m_iSize, m_afDiag, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::IncrSortEigenStuff3() +{ + Tridiagonal3(m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); + IncreasingSort(m_iSize, m_afDiag, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::IncrSortEigenStuff4() +{ + Tridiagonal4(m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); + IncreasingSort(m_iSize, m_afDiag, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::IncrSortEigenStuffN() +{ + TridiagonalN(m_iSize, m_aafMat, m_afDiag, m_afSubd); + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); + IncreasingSort(m_iSize, m_afDiag, m_aafMat); +} +//---------------------------------------------------------------------------- +void Eigen::IncrSortEigenStuff() +{ + switch (m_iSize) + { + case 2: + Tridiagonal2(m_aafMat, m_afDiag, m_afSubd); + break; + case 3: + Tridiagonal3(m_aafMat, m_afDiag, m_afSubd); + break; + case 4: + Tridiagonal4(m_aafMat, m_afDiag, m_afSubd); + break; + default: + TridiagonalN(m_iSize, m_aafMat, m_afDiag, m_afSubd); + break; + } + QLAlgorithm(m_iSize, m_afDiag, m_afSubd, m_aafMat); + IncreasingSort(m_iSize, m_afDiag, m_aafMat); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcEigen.h b/src/editors/FreeMagic/MgcEigen.h new file mode 100644 index 00000000000..4b119abaf87 --- /dev/null +++ b/src/editors/FreeMagic/MgcEigen.h @@ -0,0 +1,88 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCEIGEN_H +#define MGCEIGEN_H + +#include "MgcMath.h" + +namespace Mgc +{ + + class MAGICFM Eigen + { + public: + Eigen(int iSize); + ~Eigen(); + + // set the matrix for eigensolving + Real &Matrix(int iRow, int iCol); + void SetMatrix(Real **aafMat); + + // get the results of eigensolving (eigenvectors are columns of matrix) + Real GetEigenvalue(int i) const; + Real GetEigenvector(int iRow, int iCol) const; + Real *GetEigenvalue(); + Real **GetEigenvector(); + + // solve eigensystem + void EigenStuff2(); + void EigenStuff3(); + void EigenStuff4(); + void EigenStuffN(); + void EigenStuff(); + + // solve eigensystem, use decreasing sort on eigenvalues + void DecrSortEigenStuff2(); + void DecrSortEigenStuff3(); + void DecrSortEigenStuff4(); + void DecrSortEigenStuffN(); + void DecrSortEigenStuff(); + + // solve eigensystem, use increasing sort on eigenvalues + void IncrSortEigenStuff2(); + void IncrSortEigenStuff3(); + void IncrSortEigenStuff4(); + void IncrSortEigenStuffN(); + void IncrSortEigenStuff(); + + protected: + int m_iSize; + Real **m_aafMat; + Real *m_afDiag; + Real *m_afSubd; + + // Householder reduction to tridiagonal form + static void Tridiagonal2(Real **aafMat, Real *afDiag, Real *afSubd); + static void Tridiagonal3(Real **aafMat, Real *afDiag, Real *afSubd); + static void Tridiagonal4(Real **aafMat, Real *afDiag, Real *afSubd); + static void TridiagonalN(int iSize, Real **aafMat, Real *afDiag, + Real *afSubd); + + // QL algorithm with implicit shifting, applies to tridiagonal matrices + static bool QLAlgorithm(int iSize, Real *afDiag, Real *afSubd, + Real **aafMat); + + // sort eigenvalues from largest to smallest + static void DecreasingSort(int iSize, Real *afEigval, + Real **aafEigvec); + + // sort eigenvalues from smallest to largest + static void IncreasingSort(int iSize, Real *afEigval, + Real **aafEigvec); + }; + +#include "MgcEigen.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcEigen.inl b/src/editors/FreeMagic/MgcEigen.inl new file mode 100644 index 00000000000..d8d246e56eb --- /dev/null +++ b/src/editors/FreeMagic/MgcEigen.inl @@ -0,0 +1,38 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Real &Eigen::Matrix(int iRow, int iCol) +{ + return m_aafMat[iRow][iCol]; +} +//---------------------------------------------------------------------------- +inline Real Eigen::GetEigenvalue(int i) const +{ + return m_afDiag[i]; +} +//---------------------------------------------------------------------------- +inline Real Eigen::GetEigenvector(int iRow, int iCol) const +{ + return m_aafMat[iRow][iCol]; +} +//---------------------------------------------------------------------------- +inline Real *Eigen::GetEigenvalue() +{ + return m_afDiag; +} +//---------------------------------------------------------------------------- +inline Real **Eigen::GetEigenvector() +{ + return m_aafMat; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcLine3.h b/src/editors/FreeMagic/MgcLine3.h new file mode 100644 index 00000000000..f1c3e640560 --- /dev/null +++ b/src/editors/FreeMagic/MgcLine3.h @@ -0,0 +1,43 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCLINE3_H +#define MGCLINE3_H + +#include "MgcVector3.h" + +namespace Mgc +{ + + class MAGICFM Line3 + { + public: + // Line is L(t) = P+t*D for any real-valued t. D is not necessarily + // unit length. + Line3(); + + Vector3 &Origin(); + const Vector3 &Origin() const; + + Vector3 &Direction(); + const Vector3 &Direction() const; + + protected: + Vector3 m_kOrigin; // P + Vector3 m_kDirection; // D + }; + +#include "MgcLine3.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcLine3.inl b/src/editors/FreeMagic/MgcLine3.inl new file mode 100644 index 00000000000..caec4748d46 --- /dev/null +++ b/src/editors/FreeMagic/MgcLine3.inl @@ -0,0 +1,38 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Line3::Line3() +{ + // no initialization for efficiency +} +//---------------------------------------------------------------------------- +inline Vector3 &Line3::Origin() +{ + return m_kOrigin; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Line3::Origin() const +{ + return m_kOrigin; +} +//---------------------------------------------------------------------------- +inline Vector3 &Line3::Direction() +{ + return m_kDirection; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Line3::Direction() const +{ + return m_kDirection; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcLinearSystem.cpp b/src/editors/FreeMagic/MgcLinearSystem.cpp new file mode 100644 index 00000000000..182bcbf2f47 --- /dev/null +++ b/src/editors/FreeMagic/MgcLinearSystem.cpp @@ -0,0 +1,505 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#include "MgcLinearSystem.h" +using namespace Mgc; + +Real LinearSystem::ms_fTolerance = 1e-06f; + +//---------------------------------------------------------------------------- +Real **LinearSystem::NewMatrix(int iSize) +{ + Real **aafA = new Real *[iSize]; + assert(aafA); + + for (int iRow = 0; iRow < iSize; iRow++) + { + aafA[iRow] = new Real[iSize]; + memset(aafA[iRow], 0, iSize * sizeof(Real)); + } + + return aafA; +} +//---------------------------------------------------------------------------- +void LinearSystem::DeleteMatrix(int iSize, Real **aafA) +{ + for (int iRow = 0; iRow < iSize; iRow++) + delete[] aafA[iRow]; + delete[] aafA; +} +//---------------------------------------------------------------------------- +Real *LinearSystem::NewVector(int iSize) +{ + Real *afB = new Real[iSize]; + assert(afB); + memset(afB, 0, iSize * sizeof(Real)); + return afB; +} +//---------------------------------------------------------------------------- +void LinearSystem::DeleteVector(Real *afB) +{ + delete[] afB; +} +//---------------------------------------------------------------------------- +bool LinearSystem::Solve2(const Real aafA[2][2], const Real afB[2], + Real afX[2]) +{ + Real fDet = aafA[0][0] * aafA[1][1] - aafA[0][1] * aafA[1][0]; + if (Math::FAbs(fDet) < ms_fTolerance) + return false; + + Real fInvDet = 1.0f / fDet; + afX[0] = (aafA[1][1] * afB[0] - aafA[0][1] * afB[1]) * fInvDet; + afX[1] = (aafA[0][0] * afB[1] - aafA[1][0] * afB[0]) * fInvDet; + return true; +} +//---------------------------------------------------------------------------- +bool LinearSystem::Solve3(const Real aafA[3][3], const Real afB[3], + Real afX[3]) +{ + Real aafAInv[3][3]; + aafAInv[0][0] = aafA[1][1] * aafA[2][2] - aafA[1][2] * aafA[2][1]; + aafAInv[0][1] = aafA[0][2] * aafA[2][1] - aafA[0][1] * aafA[2][2]; + aafAInv[0][2] = aafA[0][1] * aafA[1][2] - aafA[0][2] * aafA[1][1]; + aafAInv[1][0] = aafA[1][2] * aafA[2][0] - aafA[1][0] * aafA[2][2]; + aafAInv[1][1] = aafA[0][0] * aafA[2][2] - aafA[0][2] * aafA[2][0]; + aafAInv[1][2] = aafA[0][2] * aafA[1][0] - aafA[0][0] * aafA[1][2]; + aafAInv[2][0] = aafA[1][0] * aafA[2][1] - aafA[1][1] * aafA[2][0]; + aafAInv[2][1] = aafA[0][1] * aafA[2][0] - aafA[0][0] * aafA[2][1]; + aafAInv[2][2] = aafA[0][0] * aafA[1][1] - aafA[0][1] * aafA[1][0]; + Real fDet = aafA[0][0] * aafAInv[0][0] + aafA[0][1] * aafAInv[1][0] + + aafA[0][2] * aafAInv[2][0]; + if (Math::FAbs(fDet) < ms_fTolerance) + return false; + + Real fInvDet = 1.0f / fDet; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + aafAInv[iRow][iCol] *= fInvDet; + } + + afX[0] = aafAInv[0][0] * afB[0] + aafAInv[0][1] * afB[1] + aafAInv[0][2] * afB[2]; + afX[1] = aafAInv[1][0] * afB[0] + aafAInv[1][1] * afB[1] + aafAInv[1][2] * afB[2]; + afX[2] = aafAInv[2][0] * afB[0] + aafAInv[2][1] * afB[1] + aafAInv[2][2] * afB[2]; + return true; +} +//---------------------------------------------------------------------------- +bool LinearSystem::Inverse(int iSize, Real **aafA) +{ + int *aiColIndex = new int[iSize]; + assert(aiColIndex); + + int *aiRowIndex = new int[iSize]; + assert(aiRowIndex); + + bool *abPivoted = new bool[iSize]; + assert(abPivoted); + memset(abPivoted, 0, iSize * sizeof(bool)); + + int i1, i2, iRow, iCol; + Real fSave; + + // elimination by full pivoting + for (int i0 = 0; i0 < iSize; i0++) + { + // search matrix (excluding pivoted rows) for maximum absolute entry + Real fMax = 0.0f; + for (i1 = 0; i1 < iSize; i1++) + { + if (!abPivoted[i1]) + { + for (i2 = 0; i2 < iSize; i2++) + { + if (!abPivoted[i2]) + { + Real fAbs = Math::FAbs(aafA[i1][i2]); + if (fAbs > fMax) + { + fMax = fAbs; + iRow = i1; + iCol = i2; + } + } + } + } + } + + if (fMax == 0.0f) + { + // matrix is not invertible + delete[] aiColIndex; + delete[] aiRowIndex; + delete[] abPivoted; + return false; + } + + abPivoted[iCol] = true; + + // swap rows so that A[iCol][iCol] contains the pivot entry + if (iRow != iCol) + { + Real *afRowPtr = aafA[iRow]; + aafA[iRow] = aafA[iCol]; + aafA[iCol] = afRowPtr; + } + + // keep track of the permutations of the rows + aiRowIndex[i0] = iRow; + aiColIndex[i0] = iCol; + + // scale the row so that the pivot entry is 1 + Real fInv = 1.0f / aafA[iCol][iCol]; + aafA[iCol][iCol] = 1.0f; + for (i2 = 0; i2 < iSize; i2++) + aafA[iCol][i2] *= fInv; + + // zero out the pivot column locations in the other rows + for (i1 = 0; i1 < iSize; i1++) + { + if (i1 != iCol) + { + fSave = aafA[i1][iCol]; + aafA[i1][iCol] = 0.0f; + for (i2 = 0; i2 < iSize; i2++) + aafA[i1][i2] -= aafA[iCol][i2] * fSave; + } + } + } + + // reorder rows so that A[][] stores the inverse of the original matrix + for (i1 = iSize - 1; i1 >= 0; i1--) + { + if (aiRowIndex[i1] != aiColIndex[i1]) + { + for (i2 = 0; i2 < iSize; i2++) + { + fSave = aafA[i2][aiRowIndex[i1]]; + aafA[i2][aiRowIndex[i1]] = aafA[i2][aiColIndex[i1]]; + aafA[i2][aiColIndex[i1]] = fSave; + } + } + } + + delete[] aiColIndex; + delete[] aiRowIndex; + delete[] abPivoted; + return true; +} +//---------------------------------------------------------------------------- +bool LinearSystem::Solve(int iSize, Real **aafA, Real *afB) +{ + int *aiColIndex = new int[iSize]; + assert(aiColIndex); + + int *aiRowIndex = new int[iSize]; + assert(aiRowIndex); + + bool *abPivoted = new bool[iSize]; + assert(abPivoted); + memset(abPivoted, 0, iSize * sizeof(bool)); + + int i1, i2, iRow, iCol; + Real fSave; + + // elimination by full pivoting + for (int i0 = 0; i0 < iSize; i0++) + { + // search matrix (excluding pivoted rows) for maximum absolute entry + Real fMax = 0.0f; + for (i1 = 0; i1 < iSize; i1++) + { + if (!abPivoted[i1]) + { + for (i2 = 0; i2 < iSize; i2++) + { + if (!abPivoted[i2]) + { + Real fAbs = Math::FAbs(aafA[i1][i2]); + if (fAbs > fMax) + { + fMax = fAbs; + iRow = i1; + iCol = i2; + } + } + } + } + } + + if (fMax == 0.0f) + { + // matrix is not invertible + delete[] aiColIndex; + delete[] aiRowIndex; + delete[] abPivoted; + return false; + } + + abPivoted[iCol] = true; + + // swap rows so that A[iCol][iCol] contains the pivot entry + if (iRow != iCol) + { + Real *afRowPtr = aafA[iRow]; + aafA[iRow] = aafA[iCol]; + aafA[iCol] = afRowPtr; + + fSave = afB[iRow]; + afB[iRow] = afB[iCol]; + afB[iCol] = fSave; + } + + // keep track of the permutations of the rows + aiRowIndex[i0] = iRow; + aiColIndex[i0] = iCol; + + // scale the row so that the pivot entry is 1 + Real fInv = 1.0f / aafA[iCol][iCol]; + aafA[iCol][iCol] = 1.0f; + for (i2 = 0; i2 < iSize; i2++) + aafA[iCol][i2] *= fInv; + afB[iCol] *= fInv; + + // zero out the pivot column locations in the other rows + for (i1 = 0; i1 < iSize; i1++) + { + if (i1 != iCol) + { + fSave = aafA[i1][iCol]; + aafA[i1][iCol] = 0.0f; + for (i2 = 0; i2 < iSize; i2++) + aafA[i1][i2] -= aafA[iCol][i2] * fSave; + afB[i1] -= afB[iCol] * fSave; + } + } + } + + // reorder rows so that A[][] stores the inverse of the original matrix + for (i1 = iSize - 1; i1 >= 0; i1--) + { + if (aiRowIndex[i1] != aiColIndex[i1]) + { + for (i2 = 0; i2 < iSize; i2++) + { + fSave = aafA[i2][aiRowIndex[i1]]; + aafA[i2][aiRowIndex[i1]] = aafA[i2][aiColIndex[i1]]; + aafA[i2][aiColIndex[i1]] = fSave; + } + } + } + + delete[] aiColIndex; + delete[] aiRowIndex; + delete[] abPivoted; + return true; +} +//---------------------------------------------------------------------------- +bool LinearSystem::SolveTri(int iSize, Real *afA, Real *afB, + Real *afC, Real *afR, Real *afU) +{ + if (afB[0] == 0.0f) + return false; + + Real *afD = new Real[iSize - 1]; + assert(afD); + + Real fE = afB[0]; + Real fInvE = 1.0f / fE; + afU[0] = afR[0] * fInvE; + + int i0, i1; + for (i0 = 0, i1 = 1; i1 < iSize; i0++, i1++) + { + afD[i0] = afC[i0] * fInvE; + fE = afB[i1] - afA[i0] * afD[i0]; + if (fE == 0.0f) + { + delete[] afD; + return false; + } + fInvE = 1.0f / fE; + afU[i1] = (afR[i1] - afA[i0] * afU[i0]) * fInvE; + } + + for (i0 = iSize - 1, i1 = iSize - 2; i1 >= 0; i0--, i1--) + afU[i1] -= afD[i1] * afU[i0]; + + delete[] afD; + return true; +} +//---------------------------------------------------------------------------- +bool LinearSystem::SolveConstTri(int iSize, Real fA, Real fB, + Real fC, Real *afR, Real *afU) +{ + if (fB == 0.0f) + return false; + + Real *afD = new Real[iSize - 1]; + assert(afD); + + Real fE = fB; + Real fInvE = 1.0f / fE; + afU[0] = afR[0] * fInvE; + + int i0, i1; + for (i0 = 0, i1 = 1; i1 < iSize; i0++, i1++) + { + afD[i0] = fC * fInvE; + fE = fB - fA * afD[i0]; + if (fE == 0.0f) + { + delete[] afD; + return false; + } + fInvE = 1.0f / fE; + afU[i1] = (afR[i1] - fA * afU[i0]) * fInvE; + } + for (i0 = iSize - 1, i1 = iSize - 2; i1 >= 0; i0--, i1--) + afU[i1] -= afD[i1] * afU[i0]; + + delete[] afD; + return true; +} +//---------------------------------------------------------------------------- +bool LinearSystem::SolveSymmetric(int iSize, Real **aafA, Real *afB) +{ + // A = L D L^t decomposition with diagonal terms of L equal to 1. The + // algorithm stores D terms in A[i][i] and off-diagonal L terms in + // A[i][j] for i > j. (G. Golub and C. Van Loan, Matrix Computations) + + const Real fTolerance = 1e-06f; + + int i0, i1; + Real *afV = new Real[iSize]; + assert(afV); + + for (i1 = 0; i1 < iSize; i1++) + { + for (i0 = 0; i0 < i1; i0++) + afV[i0] = aafA[i1][i0] * aafA[i0][i0]; + + afV[i1] = aafA[i1][i1]; + for (i0 = 0; i0 < i1; i0++) + afV[i1] -= aafA[i1][i0] * afV[i0]; + + aafA[i1][i1] = afV[i1]; + if (Math::FAbs(afV[i1]) <= fTolerance) + { + delete[] afV; + return false; + } + + Real fInv = 1.0f / afV[i1]; + for (i0 = i1 + 1; i0 < iSize; i0++) + { + for (int i2 = 0; i2 < i1; i2++) + aafA[i0][i1] -= aafA[i0][i2] * afV[i2]; + aafA[i0][i1] *= fInv; + } + } + delete[] afV; + + // Solve Ax = B. + + // Forward substitution: Let z = DL^t x, then Lz = B. Algorithm + // stores z terms in B vector. + for (i0 = 0; i0 < iSize; i0++) + { + for (i1 = 0; i1 < i0; i1++) + afB[i0] -= aafA[i0][i1] * afB[i1]; + } + + // Diagonal division: Let y = L^t x, then Dy = z. Algorithm stores + // y terms in B vector. + for (i0 = 0; i0 < iSize; i0++) + { + if (Math::FAbs(aafA[i0][i0]) <= fTolerance) + return false; + afB[i0] /= aafA[i0][i0]; + } + + // Back substitution: Solve L^t x = y. Algorithm stores x terms in + // B vector. + for (i0 = iSize - 2; i0 >= 0; i0--) + { + for (i1 = i0 + 1; i1 < iSize; i1++) + afB[i0] -= aafA[i1][i0] * afB[i1]; + } + + return true; +} +//---------------------------------------------------------------------------- +bool LinearSystem::SymmetricInverse(int iSize, Real **aafA, + Real **aafAInv) +{ + // Same algorithm as SolveSymmetric, but applied simultaneously to + // columns of identity matrix. + + Real *afV = new Real[iSize]; + assert(afV); + + int i0, i1; + for (i0 = 0; i0 < iSize; i0++) + { + for (i1 = 0; i1 < iSize; i1++) + aafAInv[i0][i1] = (i0 != i1 ? 0.0f : 1.0f); + } + + for (i1 = 0; i1 < iSize; i1++) + { + for (i0 = 0; i0 < i1; i0++) + afV[i0] = aafA[i1][i0] * aafA[i0][i0]; + + afV[i1] = aafA[i1][i1]; + for (i0 = 0; i0 < i1; i0++) + afV[i1] -= aafA[i1][i0] * afV[i0]; + + aafA[i1][i1] = afV[i1]; + for (i0 = i1 + 1; i0 < iSize; i0++) + { + for (int i2 = 0; i2 < i1; i2++) + aafA[i0][i1] -= aafA[i0][i2] * afV[i2]; + aafA[i0][i1] /= afV[i1]; + } + } + delete[] afV; + + for (int iCol = 0; iCol < iSize; iCol++) + { + // forward substitution + for (i0 = 0; i0 < iSize; i0++) + { + for (i1 = 0; i1 < i0; i1++) + aafAInv[i0][iCol] -= aafA[i0][i1] * aafAInv[i1][iCol]; + } + + // diagonal division + const Real fTolerance = 1e-06f; + for (i0 = 0; i0 < iSize; i0++) + { + if (fabs(aafA[i0][i0]) <= fTolerance) + return false; + aafAInv[i0][iCol] /= aafA[i0][i0]; + } + + // back substitution + for (i0 = iSize - 2; i0 >= 0; i0--) + { + for (i1 = i0 + 1; i1 < iSize; i1++) + aafAInv[i0][iCol] -= aafA[i1][i0] * aafAInv[i1][iCol]; + } + } + + return true; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcLinearSystem.h b/src/editors/FreeMagic/MgcLinearSystem.h new file mode 100644 index 00000000000..b3195687514 --- /dev/null +++ b/src/editors/FreeMagic/MgcLinearSystem.h @@ -0,0 +1,104 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCLINEARSYSTEM_H +#define MGCLINEARSYSTEM_H + +#include "MgcMath.h" + +namespace Mgc +{ + + class MAGICFM LinearSystem + { + public: + // 2x2 and 3x3 systems (avoids overhead of Gaussian elimination) + static Real &Tolerance(); + static bool Solve2(const Real aafA[2][2], const Real afB[2], + Real afX[2]); + static bool Solve3(const Real aafA[3][3], const Real afB[3], + Real afX[3]); + + // convenience for allocation, memory is zeroed out + static Real **NewMatrix(int iSize); + static void DeleteMatrix(int iSize, Real **aafA); + static Real *NewVector(int iSize); + static void DeleteVector(Real *afB); + + // Input: + // A[iSize][iSize], entries are A[row][col] + // Output: + // return value is TRUE if successful, FALSE if pivoting failed + // A[iSize][iSize], inverse matrix + static bool Inverse(int iSize, Real **aafA); + + // Input: + // A[iSize][iSize] coefficient matrix, entries are A[row][col] + // B[iSize] vector, entries are B[row] + // Output: + // return value is TRUE if successful, FALSE if pivoting failed + // A[iSize][iSize] is inverse matrix + // B[iSize] is solution x to Ax = B + static bool Solve(int iSize, Real **aafA, Real *afB); + + // Input: + // Matrix is tridiagonal. + // Lower diagonal A[iSize-1] + // Main diagonal B[iSize] + // Upper diagonal C[iSize-1] + // Right-hand side R[iSize] + // Output: + // return value is TRUE if successful, FALSE if pivoting failed + // U[iSize] is solution + static bool SolveTri(int iSize, Real *afA, Real *afB, Real *afC, + Real *afR, Real *afU); + + // Input: + // Matrix is tridiagonal. + // Lower diagonal is constant, A + // Main diagonal is constant, B + // Upper diagonal is constant, C + // Right-hand side Rr[iSize] + // Output: + // return value is TRUE if successful, FALSE if pivoting failed + // U[iSize] is solution + static bool SolveConstTri(int iSize, Real fA, Real fB, Real fC, + Real *afR, Real *afU); + + // Input: + // A[iSize][iSize] symmetric matrix, entries are A[row][col] + // B[iSize] vector, entries are B[row] + // Output: + // return value is TRUE if successful, FALSE if (nearly) singular + // decomposition A = L D L^t (diagonal terms of L are all 1) + // A[i][i] = entries of diagonal D + // A[i][j] for i > j = lower triangular part of L + // B[iSize] is solution to x to Ax = B + static bool SolveSymmetric(int iSize, Real **aafA, Real *afB); + + // Input: + // A[iSize][iSize], entries are A[row][col] + // Output: + // return value is TRUE if successful, FALSE if algorithm failed + // AInv[iSize][iSize], inverse matrix + static bool SymmetricInverse(int iSize, Real **aafA, Real **aafAInv); + + protected: + // tolerance for 2x2 and 3x3 system solving + static Real ms_fTolerance; + }; + +#include "MgcLinearSystem.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcLinearSystem.inl b/src/editors/FreeMagic/MgcLinearSystem.inl new file mode 100644 index 00000000000..31ba62cb619 --- /dev/null +++ b/src/editors/FreeMagic/MgcLinearSystem.inl @@ -0,0 +1,18 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Real &LinearSystem::Tolerance() +{ + return ms_fTolerance; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcMath.cpp b/src/editors/FreeMagic/MgcMath.cpp new file mode 100644 index 00000000000..88edab218ed --- /dev/null +++ b/src/editors/FreeMagic/MgcMath.cpp @@ -0,0 +1,213 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +//#include "stdafx.h" +#pragma hdrstop + +#include "MgcMath.h" +using namespace Mgc; + +#ifdef MGC_USE_DOUBLE +const Real Mgc::Math::MAX_REAL = DBL_MAX; +#else +const Real Mgc::Math::MAX_REAL = FLT_MAX; +#endif + +const Real Mgc::Math::_PI = 4.0f * Mgc::Math::ATan(1.0f); +const Real Mgc::Math::TWO_PI = 2.0f * _PI; +const Real Mgc::Math::HALF_PI = 0.5f * _PI; +const Real Mgc::Math::INV_TWO_PI = 1.0f / TWO_PI; +const Real Mgc::Math::DEG_TO_RAD = Mgc::Math::_PI / 180.0f; +const Real Mgc::Math::RAD_TO_DEG = 1.0f / Mgc::Math::DEG_TO_RAD; + +//---------------------------------------------------------------------------- +Real Mgc::Math::UnitRandom(Real fSeed) +{ + if (fSeed > 0.0f) + srand((unsigned int)fSeed); + + return Real(rand()) / Real(RAND_MAX); +} +//---------------------------------------------------------------------------- +Real Mgc::Math::SymmetricRandom(Real fSeed) +{ + if (fSeed > 0.0f) + srand((unsigned int)fSeed); + + return 2.0f * Real(rand()) / Real(RAND_MAX) - 1.0f; +} +//---------------------------------------------------------------------------- +Real Mgc::Math::IntervalRandom(Real fMin, Real fMax, Real fSeed) +{ + if (fSeed > 0.0f) + srand((unsigned int)fSeed); + + return fMin + (fMax - fMin) * Real(rand()) / Real(RAND_MAX); +} +//---------------------------------------------------------------------------- +Real Mgc::Math::FastSin0(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = 7.61e-03f; + fResult *= fASqr; + fResult -= 1.6605e-01f; + fResult *= fASqr; + fResult += 1.0f; + fResult *= fAngle; + return fResult; +} +//---------------------------------------------------------------------------- +Real Mgc::Math::FastSin1(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = -2.39e-08f; + fResult *= fASqr; + fResult += 2.7526e-06f; + fResult *= fASqr; + fResult -= 1.98409e-04f; + fResult *= fASqr; + fResult += 8.3333315e-03f; + fResult *= fASqr; + fResult -= 1.666666664e-01f; + fResult *= fASqr; + fResult += 1.0f; + fResult *= fAngle; + return fResult; +} +//---------------------------------------------------------------------------- +Real Mgc::Math::FastCos0(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = 3.705e-02f; + fResult *= fASqr; + fResult -= 4.967e-01f; + fResult *= fASqr; + fResult += 1.0f; + return fResult; +} +//---------------------------------------------------------------------------- +Real Mgc::Math::FastCos1(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = -2.605e-07f; + fResult *= fASqr; + fResult += 2.47609e-05f; + fResult *= fASqr; + fResult -= 1.3888397e-03f; + fResult *= fASqr; + fResult += 4.16666418e-02f; + fResult *= fASqr; + fResult -= 4.999999963e-01f; + fResult *= fASqr; + fResult += 1.0f; + return fResult; +} +//---------------------------------------------------------------------------- +Real Mgc::Math::FastTan0(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = 2.033e-01f; + fResult *= fASqr; + fResult += 3.1755e-01f; + fResult *= fASqr; + fResult += 1.0f; + fResult *= fAngle; + return fResult; +} +//---------------------------------------------------------------------------- +Real Mgc::Math::FastTan1(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = 9.5168091e-03f; + fResult *= fASqr; + fResult += 2.900525e-03f; + fResult *= fASqr; + fResult += 2.45650893e-02f; + fResult *= fASqr; + fResult += 5.33740603e-02f; + fResult *= fASqr; + fResult += 1.333923995e-01f; + fResult *= fASqr; + fResult += 3.333314036e-01f; + fResult *= fASqr; + fResult += 1.0f; + fResult *= fAngle; + return fResult; +} +//---------------------------------------------------------------------------- +Real Mgc::Math::FastInvSin(Real fValue) +{ + Real fRoot = Mgc::Math::Sqrt(1.0f - fValue); + Real fResult = -0.0187293f; + fResult *= fValue; + fResult += 0.0742610f; + fResult *= fValue; + fResult -= 0.2121144f; + fResult *= fValue; + fResult += 1.5707288f; + fResult = HALF_PI - fRoot * fResult; + return fResult; +} +//---------------------------------------------------------------------------- +Real Mgc::Math::FastInvCos(Real fValue) +{ + Real fRoot = Mgc::Math::Sqrt(1.0f - fValue); + Real fResult = -0.0187293f; + fResult *= fValue; + fResult += 0.0742610f; + fResult *= fValue; + fResult -= 0.2121144f; + fResult *= fValue; + fResult += 1.5707288f; + fResult *= fRoot; + return fResult; +} +//---------------------------------------------------------------------------- +Real Mgc::Math::FastInvTan0(Real fValue) +{ + Real fVSqr = fValue * fValue; + Real fResult = 0.0208351f; + fResult *= fVSqr; + fResult -= 0.085133f; + fResult *= fVSqr; + fResult += 0.180141f; + fResult *= fVSqr; + fResult -= 0.3302995f; + fResult *= fVSqr; + fResult += 0.999866f; + fResult *= fValue; + return fResult; +} +//---------------------------------------------------------------------------- +Real Mgc::Math::FastInvTan1(Real fValue) +{ + Real fVSqr = fValue * fValue; + Real fResult = 0.0028662257f; + fResult *= fVSqr; + fResult -= 0.0161657367f; + fResult *= fVSqr; + fResult += 0.0429096138f; + fResult *= fVSqr; + fResult -= 0.0752896400f; + fResult *= fVSqr; + fResult += 0.1065626393f; + fResult *= fVSqr; + fResult -= 0.1420889944f; + fResult *= fVSqr; + fResult += 0.1999355085f; + fResult *= fVSqr; + fResult -= 0.3333314528f; + fResult *= fVSqr; + fResult += 1.0f; + fResult *= fValue; + return fResult; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcMath.h b/src/editors/FreeMagic/MgcMath.h new file mode 100644 index 00000000000..dc2836e07f2 --- /dev/null +++ b/src/editors/FreeMagic/MgcMath.h @@ -0,0 +1,126 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCMATH_H +#define MGCMATH_H + +#include "MagicFMLibType.h" +#include "MgcRTLib.h" + +namespace Mgc +{ + +#ifdef MGC_USE_DOUBLE + typedef double Real; +#else + typedef float Real; +#endif + + class MAGICFM Math + { + public: + // Return -1 if the input is negative, 0 if the input is zero, and +1 + // if the input is positive. + static int Sign(int iValue); + static Real Sign(Real fValue); + + // Just computes fValue*fValue. + static Real Sqr(Real fValue); + + // Generate a random number in [0,1). The random number generator may + // be seeded by a first call to UnitRandom with a positive seed. + static Real UnitRandom(Real fSeed = 0.0f); + + // Generate a random number in [-1,1). The random number generator may + // be seeded by a first call to SymmetricRandom with a positive seed. + static Real SymmetricRandom(Real fSeed = 0.0f); + + // Generate a random number in [min,max). The random number generator may + // be seeded by a first call to IntervalRandom with a positive seed. + static Real IntervalRandom(Real fMin, Real fMax, Real fSeed = 0.0f); + + // Fast evaluation of sin(angle) by polynomial approximations. The angle + // must be in [0,pi/2]. The maximum absolute error is about 1.7e-04 for + // FastSin0 and about 2.3e-09 for FastSin1. The speed up is about 2 for + // FastSin0 and about 1.5 for FastSin1. + static Real FastSin0(Real fAngle); + static Real FastSin1(Real fAngle); + + // Fast evaluation of cos(angle) by polynomial approximations. The angle + // must be in [0,pi/2]. The maximum absolute error is about 1.2e-03 for + // FastCos0 and about 2.3e-09 for FastCos1. The speed up is about 2 for + // FastCos0 and about 1.5 for FastCos1. + static Real FastCos0(Real fAngle); + static Real FastCos1(Real fAngle); + + // Fast evaluation of tan(angle) by polynomial approximations. The angle + // must be in [0,pi/4]. The maximum absolute error is about 8.1e-04 for + // FastTan0 and about 1.9e-08 for FastTan1. The speed up is about 2.5 for + // FastTan0 and about 1.75 for FastTan1. + static Real FastTan0(Real fAngle); + static Real FastTan1(Real fAngle); + + // Fast evaluation of asin(value) by a sqrt times a polynomial. The value + // must be in [0,1]. The maximum absolute error is about 6.8e-05 and the + // speed up is about 2.5. + static Real FastInvSin(Real fValue); + + // Fast evaluation of acos(value) by a sqrt times a polynomial. The value + // must be in [0,1]. The maximum absolute error is about 6.8e-05 and the + // speed up is about 2.5. + static Real FastInvCos(Real fValue); + + // Fast evaluation of atan(value) by polynomial approximations. The value + // must be in [-1,1]. The maximum absolute error is about 1.2e-05 for + // FastInvTan0 and about 1.43-08 for FastInvTan1. The speed up is about + // 2.2 for FastInvTan0 and about 1.5 for FastInvTan1. + static Real FastInvTan0(Real fValue); + static Real FastInvTan1(Real fValue); + + // Wrappers for acos and asin, but the input value is clamped to [-1,1] + // to avoid silent returns of NaN. + static Real ACos(Real fValue); + static Real ASin(Real fValue); + + // Wrapper for 1/sqrt to allow a fast implementation to replace it at a + // later date. + static Real InvSqrt(Real fValue); + + // Wrappers to hide 'double foo(double)' versus 'float foof(float)'. + static Real ATan(Real fValue); + static Real ATan2(Real fY, Real fX); + static Real Ceil(Real fValue); + static Real Cos(Real fValue); + static Real Exp(Real fValue); + static Real FAbs(Real fValue); + static Real Floor(Real fValue); + static Real Log(Real fValue); + static Real Pow(Real kBase, Real kExponent); + static Real Sin(Real fValue); + static Real Sqrt(Real fValue); + static Real Tan(Real fValue); + + // common constants + static const Real MAX_REAL; + static const Real _PI; + static const Real TWO_PI; + static const Real HALF_PI; + static const Real INV_TWO_PI; + static const Real DEG_TO_RAD; + static const Real RAD_TO_DEG; + }; + +#include "MgcMath.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcMath.inl b/src/editors/FreeMagic/MgcMath.inl new file mode 100644 index 00000000000..3a30685f83e --- /dev/null +++ b/src/editors/FreeMagic/MgcMath.inl @@ -0,0 +1,140 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +#include +//---------------------------------------------------------------------------- + +#ifndef M_PI +#define M_PI 3.14159265358979323846 /* pi */ +#endif + +inline Real Math::ACos(Real fValue) +{ + if (-1.0f < fValue) + { + if (fValue < 1.0f) + return (Real)acos(fValue); + else + return 0.0f; + } + else + { + return M_PI; + } +} +//---------------------------------------------------------------------------- +inline Real Math::ASin(Real fValue) +{ + if (-1.0f < fValue) + { + if (fValue < 1.0f) + return (Real)asin(fValue); + else + return -HALF_PI; + } + else + { + return HALF_PI; + } +} +//---------------------------------------------------------------------------- +inline Real Math::ATan(Real fValue) +{ + return (Real)atan(fValue); +} +//---------------------------------------------------------------------------- +inline Real Math::ATan2(Real fY, Real fX) +{ + return (Real)atan2(fY, fX); +} +//---------------------------------------------------------------------------- +inline Real Math::Ceil(Real fValue) +{ + return (Real)ceil(fValue); +} +//---------------------------------------------------------------------------- +inline Real Math::Cos(Real fValue) +{ + return (Real)cos(fValue); +} +//---------------------------------------------------------------------------- +inline Real Math::Exp(Real fValue) +{ + return (Real)exp(fValue); +} +//---------------------------------------------------------------------------- +inline Real Math::FAbs(Real fValue) +{ + return (Real)fabs(fValue); +} +//---------------------------------------------------------------------------- +inline Real Math::Floor(Real fValue) +{ + return (Real)floor(fValue); +} +//---------------------------------------------------------------------------- +inline Real Math::InvSqrt(Real fValue) +{ + return (Real)(1.0 / sqrt(fValue)); +} +//---------------------------------------------------------------------------- +inline Real Math::Log(Real fValue) +{ + return (Real)log(fValue); +} +//---------------------------------------------------------------------------- +inline Real Math::Pow(Real kBase, Real kExponent) +{ + return (Real)pow(kBase, kExponent); +} +//---------------------------------------------------------------------------- +inline int Math::Sign(int iValue) +{ + if (iValue > 0) + return 1; + + if (iValue < 0) + return -1; + + return 0; +} +//---------------------------------------------------------------------------- +inline Real Math::Sign(Real fValue) +{ + if (fValue > 0.0f) + return 1.0f; + + if (fValue < 0.0f) + return -1.0f; + + return 0.0f; +} +//---------------------------------------------------------------------------- +inline Real Math::Sin(Real fValue) +{ + return (Real)sin(fValue); +} +//---------------------------------------------------------------------------- +inline Real Math::Sqr(Real fValue) +{ + return fValue * fValue; +} +//---------------------------------------------------------------------------- +inline Real Math::Sqrt(Real fValue) +{ + return (Real)sqrt(fValue); +} +//---------------------------------------------------------------------------- +inline Real Math::Tan(Real fValue) +{ + return (Real)tan(fValue); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcMatrix3.cpp b/src/editors/FreeMagic/MgcMatrix3.cpp new file mode 100644 index 00000000000..3182c847fa4 --- /dev/null +++ b/src/editors/FreeMagic/MgcMatrix3.cpp @@ -0,0 +1,1558 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#include "MgcMatrix3.h" +using namespace Mgc; + +const Real Matrix3::EPSILON = 1e-06f; +const Matrix3 Matrix3::ZERO(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f); +const Matrix3 Matrix3::IDENTITY(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); +const Real Matrix3::ms_fSvdEpsilon = 1e-04f; +const int Matrix3::ms_iSvdMaxIterations = 32; + +//---------------------------------------------------------------------------- +Matrix3::Matrix3(const Real aafEntry[3][3]) +{ + memcpy(m_aafEntry, aafEntry, 9 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +Matrix3::Matrix3(const Matrix3 &rkMatrix) +{ + memcpy(m_aafEntry, rkMatrix.m_aafEntry, 9 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +Matrix3::Matrix3(Real fEntry00, Real fEntry01, Real fEntry02, + Real fEntry10, Real fEntry11, Real fEntry12, Real fEntry20, + Real fEntry21, Real fEntry22) +{ + m_aafEntry[0][0] = fEntry00; + m_aafEntry[0][1] = fEntry01; + m_aafEntry[0][2] = fEntry02; + m_aafEntry[1][0] = fEntry10; + m_aafEntry[1][1] = fEntry11; + m_aafEntry[1][2] = fEntry12; + m_aafEntry[2][0] = fEntry20; + m_aafEntry[2][1] = fEntry21; + m_aafEntry[2][2] = fEntry22; +} +//---------------------------------------------------------------------------- +Vector3 Matrix3::GetColumn(int iCol) const +{ + assert(0 <= iCol && iCol < 3); + return Vector3(m_aafEntry[0][iCol], m_aafEntry[1][iCol], + m_aafEntry[2][iCol]); +} +//---------------------------------------------------------------------------- +Matrix3 &Matrix3::operator=(const Matrix3 &rkMatrix) +{ + memcpy(m_aafEntry, rkMatrix.m_aafEntry, 9 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +bool Matrix3::operator==(const Matrix3 &rkMatrix) const +{ + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + { + if (m_aafEntry[iRow][iCol] != rkMatrix.m_aafEntry[iRow][iCol]) + return false; + } + } + + return true; +} +//---------------------------------------------------------------------------- +bool Matrix3::operator!=(const Matrix3 &rkMatrix) const +{ + return !operator==(rkMatrix); +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::operator+(const Matrix3 &rkMatrix) const +{ + Matrix3 kSum; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + { + kSum.m_aafEntry[iRow][iCol] = m_aafEntry[iRow][iCol] + + rkMatrix.m_aafEntry[iRow][iCol]; + } + } + return kSum; +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::operator-(const Matrix3 &rkMatrix) const +{ + Matrix3 kDiff; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + { + kDiff.m_aafEntry[iRow][iCol] = m_aafEntry[iRow][iCol] - + rkMatrix.m_aafEntry[iRow][iCol]; + } + } + return kDiff; +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::operator*(const Matrix3 &rkMatrix) const +{ + Matrix3 kProd; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + { + kProd.m_aafEntry[iRow][iCol] = + m_aafEntry[iRow][0] * rkMatrix.m_aafEntry[0][iCol] + + m_aafEntry[iRow][1] * rkMatrix.m_aafEntry[1][iCol] + + m_aafEntry[iRow][2] * rkMatrix.m_aafEntry[2][iCol]; + } + } + return kProd; +} +//---------------------------------------------------------------------------- +Vector3 Matrix3::operator*(const Vector3 &rkPoint) const +{ + Vector3 kProd; + for (int iRow = 0; iRow < 3; iRow++) + { + kProd[iRow] = + m_aafEntry[iRow][0] * rkPoint[0] + + m_aafEntry[iRow][1] * rkPoint[1] + + m_aafEntry[iRow][2] * rkPoint[2]; + } + return kProd; +} +//---------------------------------------------------------------------------- +Vector3 Mgc::operator*(const Vector3 &rkPoint, const Matrix3 &rkMatrix) +{ + Vector3 kProd; + for (int iRow = 0; iRow < 3; iRow++) + { + kProd[iRow] = + rkPoint[0] * rkMatrix.m_aafEntry[0][iRow] + + rkPoint[1] * rkMatrix.m_aafEntry[1][iRow] + + rkPoint[2] * rkMatrix.m_aafEntry[2][iRow]; + } + return kProd; +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::operator-() const +{ + Matrix3 kNeg; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + kNeg[iRow][iCol] = -m_aafEntry[iRow][iCol]; + } + return kNeg; +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::operator*(Real fScalar) const +{ + Matrix3 kProd; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + kProd[iRow][iCol] = fScalar * m_aafEntry[iRow][iCol]; + } + return kProd; +} +//---------------------------------------------------------------------------- +Matrix3 Mgc::operator*(Real fScalar, const Matrix3 &rkMatrix) +{ + Matrix3 kProd; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + kProd[iRow][iCol] = fScalar * rkMatrix.m_aafEntry[iRow][iCol]; + } + return kProd; +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::TransposeTimes(const Matrix3 &rkM) const +{ + Matrix3 kProd; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + { + kProd[iRow][iCol] = 0.0f; + for (int iMid = 0; iMid < 3; iMid++) + { + kProd[iRow][iCol] += m_aafEntry[iMid][iRow] * + rkM.m_aafEntry[iMid][iCol]; + } + } + } + return kProd; +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::TimesTranspose(const Matrix3 &rkM) const +{ + Matrix3 kProd; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + { + kProd[iRow][iCol] = 0.0f; + for (int iMid = 0; iMid < 3; iMid++) + { + kProd[iRow][iCol] += m_aafEntry[iRow][iMid] * + rkM.m_aafEntry[iCol][iMid]; + } + } + } + return kProd; +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::Transpose() const +{ + Matrix3 kTranspose; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + kTranspose[iRow][iCol] = m_aafEntry[iCol][iRow]; + } + return kTranspose; +} +//---------------------------------------------------------------------------- +bool Matrix3::Inverse(Matrix3 &rkInverse, Real fTolerance) const +{ + // Invert a 3x3 using cofactors. This is about 8 times faster than + // the Numerical Recipes code which uses Gaussian elimination. + + rkInverse[0][0] = m_aafEntry[1][1] * m_aafEntry[2][2] - + m_aafEntry[1][2] * m_aafEntry[2][1]; + rkInverse[0][1] = m_aafEntry[0][2] * m_aafEntry[2][1] - + m_aafEntry[0][1] * m_aafEntry[2][2]; + rkInverse[0][2] = m_aafEntry[0][1] * m_aafEntry[1][2] - + m_aafEntry[0][2] * m_aafEntry[1][1]; + rkInverse[1][0] = m_aafEntry[1][2] * m_aafEntry[2][0] - + m_aafEntry[1][0] * m_aafEntry[2][2]; + rkInverse[1][1] = m_aafEntry[0][0] * m_aafEntry[2][2] - + m_aafEntry[0][2] * m_aafEntry[2][0]; + rkInverse[1][2] = m_aafEntry[0][2] * m_aafEntry[1][0] - + m_aafEntry[0][0] * m_aafEntry[1][2]; + rkInverse[2][0] = m_aafEntry[1][0] * m_aafEntry[2][1] - + m_aafEntry[1][1] * m_aafEntry[2][0]; + rkInverse[2][1] = m_aafEntry[0][1] * m_aafEntry[2][0] - + m_aafEntry[0][0] * m_aafEntry[2][1]; + rkInverse[2][2] = m_aafEntry[0][0] * m_aafEntry[1][1] - + m_aafEntry[0][1] * m_aafEntry[1][0]; + + Real fDet = + m_aafEntry[0][0] * rkInverse[0][0] + + m_aafEntry[0][1] * rkInverse[1][0] + + m_aafEntry[0][2] * rkInverse[2][0]; + + if (Math::FAbs(fDet) <= fTolerance) + return false; + + Real fInvDet = 1.0f / fDet; + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + rkInverse[iRow][iCol] *= fInvDet; + } + + return true; +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::Inverse(Real fTolerance) const +{ + Matrix3 kInverse = Matrix3::ZERO; + Inverse(kInverse, fTolerance); + return kInverse; +} +//---------------------------------------------------------------------------- +Real Matrix3::Determinant() const +{ + Real fCofactor00 = m_aafEntry[1][1] * m_aafEntry[2][2] - + m_aafEntry[1][2] * m_aafEntry[2][1]; + Real fCofactor10 = m_aafEntry[1][2] * m_aafEntry[2][0] - + m_aafEntry[1][0] * m_aafEntry[2][2]; + Real fCofactor20 = m_aafEntry[1][0] * m_aafEntry[2][1] - + m_aafEntry[1][1] * m_aafEntry[2][0]; + + Real fDet = + m_aafEntry[0][0] * fCofactor00 + + m_aafEntry[0][1] * fCofactor10 + + m_aafEntry[0][2] * fCofactor20; + + return fDet; +} +//---------------------------------------------------------------------------- +Matrix3 Matrix3::Slerp(Real fT, const Matrix3 &rkR0, const Matrix3 &rkR1) +{ + Vector3 kAxis; + Real fAngle; + Matrix3 kProd = rkR0.TransposeTimes(rkR1); + kProd.ToAxisAngle(kAxis, fAngle); + + Matrix3 kR; + kR.FromAxisAngle(kAxis, fT * fAngle); + + return kR; +} +//---------------------------------------------------------------------------- +void Matrix3::Bidiagonalize(Matrix3 &kA, Matrix3 &kL, + Matrix3 &kR) +{ + Real afV[3], afW[3]; + Real fLength, fSign, fT1, fInvT1, fT2; + bool bIdentity; + + // map first column to (*,0,0) + fLength = Math::Sqrt(kA[0][0] * kA[0][0] + kA[1][0] * kA[1][0] + + kA[2][0] * kA[2][0]); + if (fLength > 0.0f) + { + fSign = (kA[0][0] > 0.0f ? 1.0f : -1.0f); + fT1 = kA[0][0] + fSign * fLength; + fInvT1 = 1.0f / fT1; + afV[1] = kA[1][0] * fInvT1; + afV[2] = kA[2][0] * fInvT1; + + fT2 = -2.0f / (1.0f + afV[1] * afV[1] + afV[2] * afV[2]); + afW[0] = fT2 * (kA[0][0] + kA[1][0] * afV[1] + kA[2][0] * afV[2]); + afW[1] = fT2 * (kA[0][1] + kA[1][1] * afV[1] + kA[2][1] * afV[2]); + afW[2] = fT2 * (kA[0][2] + kA[1][2] * afV[1] + kA[2][2] * afV[2]); + kA[0][0] += afW[0]; + kA[0][1] += afW[1]; + kA[0][2] += afW[2]; + kA[1][1] += afV[1] * afW[1]; + kA[1][2] += afV[1] * afW[2]; + kA[2][1] += afV[2] * afW[1]; + kA[2][2] += afV[2] * afW[2]; + + kL[0][0] = 1.0f + fT2; + kL[0][1] = kL[1][0] = fT2 * afV[1]; + kL[0][2] = kL[2][0] = fT2 * afV[2]; + kL[1][1] = 1.0f + fT2 * afV[1] * afV[1]; + kL[1][2] = kL[2][1] = fT2 * afV[1] * afV[2]; + kL[2][2] = 1.0f + fT2 * afV[2] * afV[2]; + bIdentity = false; + } + else + { + kL = Matrix3::IDENTITY; + bIdentity = true; + } + + // map first row to (*,*,0) + fLength = Math::Sqrt(kA[0][1] * kA[0][1] + kA[0][2] * kA[0][2]); + if (fLength > 0.0f) + { + fSign = (kA[0][1] > 0.0f ? 1.0f : -1.0f); + fT1 = kA[0][1] + fSign * fLength; + afV[2] = kA[0][2] / fT1; + + fT2 = -2.0f / (1.0f + afV[2] * afV[2]); + afW[0] = fT2 * (kA[0][1] + kA[0][2] * afV[2]); + afW[1] = fT2 * (kA[1][1] + kA[1][2] * afV[2]); + afW[2] = fT2 * (kA[2][1] + kA[2][2] * afV[2]); + kA[0][1] += afW[0]; + kA[1][1] += afW[1]; + kA[1][2] += afW[1] * afV[2]; + kA[2][1] += afW[2]; + kA[2][2] += afW[2] * afV[2]; + + kR[0][0] = 1.0f; + kR[0][1] = kR[1][0] = 0.0f; + kR[0][2] = kR[2][0] = 0.0f; + kR[1][1] = 1.0f + fT2; + kR[1][2] = kR[2][1] = fT2 * afV[2]; + kR[2][2] = 1.0f + fT2 * afV[2] * afV[2]; + } + else + { + kR = Matrix3::IDENTITY; + } + + // map second column to (*,*,0) + fLength = Math::Sqrt(kA[1][1] * kA[1][1] + kA[2][1] * kA[2][1]); + if (fLength > 0.0f) + { + fSign = (kA[1][1] > 0.0f ? 1.0f : -1.0f); + fT1 = kA[1][1] + fSign * fLength; + afV[2] = kA[2][1] / fT1; + + fT2 = -2.0f / (1.0f + afV[2] * afV[2]); + afW[1] = fT2 * (kA[1][1] + kA[2][1] * afV[2]); + afW[2] = fT2 * (kA[1][2] + kA[2][2] * afV[2]); + kA[1][1] += afW[1]; + kA[1][2] += afW[2]; + kA[2][2] += afV[2] * afW[2]; + + Real fA = 1.0f + fT2; + Real fB = fT2 * afV[2]; + Real fC = 1.0f + fB * afV[2]; + + if (bIdentity) + { + kL[0][0] = 1.0f; + kL[0][1] = kL[1][0] = 0.0f; + kL[0][2] = kL[2][0] = 0.0f; + kL[1][1] = fA; + kL[1][2] = kL[2][1] = fB; + kL[2][2] = fC; + } + else + { + for (int iRow = 0; iRow < 3; iRow++) + { + Real fTmp0 = kL[iRow][1]; + Real fTmp1 = kL[iRow][2]; + kL[iRow][1] = fA * fTmp0 + fB * fTmp1; + kL[iRow][2] = fB * fTmp0 + fC * fTmp1; + } + } + } +} +//---------------------------------------------------------------------------- +void Matrix3::GolubKahanStep(Matrix3 &kA, Matrix3 &kL, + Matrix3 &kR) +{ + Real fT11 = kA[0][1] * kA[0][1] + kA[1][1] * kA[1][1]; + Real fT22 = kA[1][2] * kA[1][2] + kA[2][2] * kA[2][2]; + Real fT12 = kA[1][1] * kA[1][2]; + Real fTrace = fT11 + fT22; + Real fDiff = fT11 - fT22; + Real fDiscr = Math::Sqrt(fDiff * fDiff + 4.0f * fT12 * fT12); + Real fRoot1 = 0.5f * (fTrace + fDiscr); + Real fRoot2 = 0.5f * (fTrace - fDiscr); + + // adjust right + Real fY = kA[0][0] - (Math::FAbs(fRoot1 - fT22) <= + Math::FAbs(fRoot2 - fT22) + ? fRoot1 + : fRoot2); + Real fZ = kA[0][1]; + Real fInvLength = Math::InvSqrt(fY * fY + fZ * fZ); + Real fSin = fZ * fInvLength; + Real fCos = -fY * fInvLength; + + Real fTmp0 = kA[0][0]; + Real fTmp1 = kA[0][1]; + kA[0][0] = fCos * fTmp0 - fSin * fTmp1; + kA[0][1] = fSin * fTmp0 + fCos * fTmp1; + kA[1][0] = -fSin * kA[1][1]; + kA[1][1] *= fCos; + + int iRow; + for (iRow = 0; iRow < 3; iRow++) + { + fTmp0 = kR[0][iRow]; + fTmp1 = kR[1][iRow]; + kR[0][iRow] = fCos * fTmp0 - fSin * fTmp1; + kR[1][iRow] = fSin * fTmp0 + fCos * fTmp1; + } + + // adjust left + fY = kA[0][0]; + fZ = kA[1][0]; + fInvLength = Math::InvSqrt(fY * fY + fZ * fZ); + fSin = fZ * fInvLength; + fCos = -fY * fInvLength; + + kA[0][0] = fCos * kA[0][0] - fSin * kA[1][0]; + fTmp0 = kA[0][1]; + fTmp1 = kA[1][1]; + kA[0][1] = fCos * fTmp0 - fSin * fTmp1; + kA[1][1] = fSin * fTmp0 + fCos * fTmp1; + kA[0][2] = -fSin * kA[1][2]; + kA[1][2] *= fCos; + + int iCol; + for (iCol = 0; iCol < 3; iCol++) + { + fTmp0 = kL[iCol][0]; + fTmp1 = kL[iCol][1]; + kL[iCol][0] = fCos * fTmp0 - fSin * fTmp1; + kL[iCol][1] = fSin * fTmp0 + fCos * fTmp1; + } + + // adjust right + fY = kA[0][1]; + fZ = kA[0][2]; + fInvLength = Math::InvSqrt(fY * fY + fZ * fZ); + fSin = fZ * fInvLength; + fCos = -fY * fInvLength; + + kA[0][1] = fCos * kA[0][1] - fSin * kA[0][2]; + fTmp0 = kA[1][1]; + fTmp1 = kA[1][2]; + kA[1][1] = fCos * fTmp0 - fSin * fTmp1; + kA[1][2] = fSin * fTmp0 + fCos * fTmp1; + kA[2][1] = -fSin * kA[2][2]; + kA[2][2] *= fCos; + + for (iRow = 0; iRow < 3; iRow++) + { + fTmp0 = kR[1][iRow]; + fTmp1 = kR[2][iRow]; + kR[1][iRow] = fCos * fTmp0 - fSin * fTmp1; + kR[2][iRow] = fSin * fTmp0 + fCos * fTmp1; + } + + // adjust left + fY = kA[1][1]; + fZ = kA[2][1]; + fInvLength = Math::InvSqrt(fY * fY + fZ * fZ); + fSin = fZ * fInvLength; + fCos = -fY * fInvLength; + + kA[1][1] = fCos * kA[1][1] - fSin * kA[2][1]; + fTmp0 = kA[1][2]; + fTmp1 = kA[2][2]; + kA[1][2] = fCos * fTmp0 - fSin * fTmp1; + kA[2][2] = fSin * fTmp0 + fCos * fTmp1; + + for (iCol = 0; iCol < 3; iCol++) + { + fTmp0 = kL[iCol][1]; + fTmp1 = kL[iCol][2]; + kL[iCol][1] = fCos * fTmp0 - fSin * fTmp1; + kL[iCol][2] = fSin * fTmp0 + fCos * fTmp1; + } +} +//---------------------------------------------------------------------------- +void Matrix3::SingularValueDecomposition(Matrix3 &kL, Vector3 &kS, + Matrix3 &kR) const +{ + int iRow, iCol; + + Matrix3 kA = *this; + Bidiagonalize(kA, kL, kR); + + for (int i = 0; i < ms_iSvdMaxIterations; i++) + { + Real fTmp, fTmp0, fTmp1; + Real fSin0, fCos0, fTan0; + Real fSin1, fCos1, fTan1; + + bool bTest1 = (Math::FAbs(kA[0][1]) <= + ms_fSvdEpsilon * (Math::FAbs(kA[0][0]) + Math::FAbs(kA[1][1]))); + bool bTest2 = (Math::FAbs(kA[1][2]) <= + ms_fSvdEpsilon * (Math::FAbs(kA[1][1]) + Math::FAbs(kA[2][2]))); + if (bTest1) + { + if (bTest2) + { + kS[0] = kA[0][0]; + kS[1] = kA[1][1]; + kS[2] = kA[2][2]; + break; + } + else + { + // 2x2 closed form factorization + fTmp = (kA[1][1] * kA[1][1] - kA[2][2] * kA[2][2] + + kA[1][2] * kA[1][2]) / + (kA[1][2] * kA[2][2]); + fTan0 = 0.5f * (fTmp + Math::Sqrt(fTmp * fTmp + 4.0f)); + fCos0 = Math::InvSqrt(1.0f + fTan0 * fTan0); + fSin0 = fTan0 * fCos0; + + for (iCol = 0; iCol < 3; iCol++) + { + fTmp0 = kL[iCol][1]; + fTmp1 = kL[iCol][2]; + kL[iCol][1] = fCos0 * fTmp0 - fSin0 * fTmp1; + kL[iCol][2] = fSin0 * fTmp0 + fCos0 * fTmp1; + } + + fTan1 = (kA[1][2] - kA[2][2] * fTan0) / kA[1][1]; + fCos1 = Math::InvSqrt(1.0f + fTan1 * fTan1); + fSin1 = -fTan1 * fCos1; + + for (iRow = 0; iRow < 3; iRow++) + { + fTmp0 = kR[1][iRow]; + fTmp1 = kR[2][iRow]; + kR[1][iRow] = fCos1 * fTmp0 - fSin1 * fTmp1; + kR[2][iRow] = fSin1 * fTmp0 + fCos1 * fTmp1; + } + + kS[0] = kA[0][0]; + kS[1] = fCos0 * fCos1 * kA[1][1] - + fSin1 * (fCos0 * kA[1][2] - fSin0 * kA[2][2]); + kS[2] = fSin0 * fSin1 * kA[1][1] + + fCos1 * (fSin0 * kA[1][2] + fCos0 * kA[2][2]); + break; + } + } + else + { + if (bTest2) + { + // 2x2 closed form factorization + fTmp = (kA[0][0] * kA[0][0] + kA[1][1] * kA[1][1] - + kA[0][1] * kA[0][1]) / + (kA[0][1] * kA[1][1]); + fTan0 = 0.5f * (-fTmp + Math::Sqrt(fTmp * fTmp + 4.0f)); + fCos0 = Math::InvSqrt(1.0f + fTan0 * fTan0); + fSin0 = fTan0 * fCos0; + + for (iCol = 0; iCol < 3; iCol++) + { + fTmp0 = kL[iCol][0]; + fTmp1 = kL[iCol][1]; + kL[iCol][0] = fCos0 * fTmp0 - fSin0 * fTmp1; + kL[iCol][1] = fSin0 * fTmp0 + fCos0 * fTmp1; + } + + fTan1 = (kA[0][1] - kA[1][1] * fTan0) / kA[0][0]; + fCos1 = Math::InvSqrt(1.0f + fTan1 * fTan1); + fSin1 = -fTan1 * fCos1; + + for (iRow = 0; iRow < 3; iRow++) + { + fTmp0 = kR[0][iRow]; + fTmp1 = kR[1][iRow]; + kR[0][iRow] = fCos1 * fTmp0 - fSin1 * fTmp1; + kR[1][iRow] = fSin1 * fTmp0 + fCos1 * fTmp1; + } + + kS[0] = fCos0 * fCos1 * kA[0][0] - + fSin1 * (fCos0 * kA[0][1] - fSin0 * kA[1][1]); + kS[1] = fSin0 * fSin1 * kA[0][0] + + fCos1 * (fSin0 * kA[0][1] + fCos0 * kA[1][1]); + kS[2] = kA[2][2]; + break; + } + else + { + GolubKahanStep(kA, kL, kR); + } + } + } + + // positize diagonal + for (iRow = 0; iRow < 3; iRow++) + { + if (kS[iRow] < 0.0f) + { + kS[iRow] = -kS[iRow]; + for (iCol = 0; iCol < 3; iCol++) + kR[iRow][iCol] = -kR[iRow][iCol]; + } + } +} +//---------------------------------------------------------------------------- +void Matrix3::SingularValueComposition(const Matrix3 &kL, + const Vector3 &kS, const Matrix3 &kR) +{ + int iRow, iCol; + Matrix3 kTmp; + + // product S*R + for (iRow = 0; iRow < 3; iRow++) + { + for (iCol = 0; iCol < 3; iCol++) + kTmp[iRow][iCol] = kS[iRow] * kR[iRow][iCol]; + } + + // product L*S*R + for (iRow = 0; iRow < 3; iRow++) + { + for (iCol = 0; iCol < 3; iCol++) + { + m_aafEntry[iRow][iCol] = 0.0f; + for (int iMid = 0; iMid < 3; iMid++) + m_aafEntry[iRow][iCol] += kL[iRow][iMid] * kTmp[iMid][iCol]; + } + } +} +//---------------------------------------------------------------------------- +void Matrix3::Orthonormalize() +{ + // Algorithm uses Gram-Schmidt orthogonalization. If 'this' matrix is + // M = [m0|m1|m2], then orthonormal output matrix is Q = [q0|q1|q2], + // + // q0 = m0/|m0| + // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| + // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| + // + // where |V| indicates length of vector V and A*B indicates dot + // product of vectors A and B. + + // compute q0 + Real fInvLength = Math::InvSqrt(m_aafEntry[0][0] * m_aafEntry[0][0] + m_aafEntry[1][0] * m_aafEntry[1][0] + + m_aafEntry[2][0] * m_aafEntry[2][0]); + + m_aafEntry[0][0] *= fInvLength; + m_aafEntry[1][0] *= fInvLength; + m_aafEntry[2][0] *= fInvLength; + + // compute q1 + Real fDot0 = + m_aafEntry[0][0] * m_aafEntry[0][1] + + m_aafEntry[1][0] * m_aafEntry[1][1] + + m_aafEntry[2][0] * m_aafEntry[2][1]; + + m_aafEntry[0][1] -= fDot0 * m_aafEntry[0][0]; + m_aafEntry[1][1] -= fDot0 * m_aafEntry[1][0]; + m_aafEntry[2][1] -= fDot0 * m_aafEntry[2][0]; + + fInvLength = Math::InvSqrt(m_aafEntry[0][1] * m_aafEntry[0][1] + + m_aafEntry[1][1] * m_aafEntry[1][1] + + m_aafEntry[2][1] * m_aafEntry[2][1]); + + m_aafEntry[0][1] *= fInvLength; + m_aafEntry[1][1] *= fInvLength; + m_aafEntry[2][1] *= fInvLength; + + // compute q2 + Real fDot1 = + m_aafEntry[0][1] * m_aafEntry[0][2] + + m_aafEntry[1][1] * m_aafEntry[1][2] + + m_aafEntry[2][1] * m_aafEntry[2][2]; + + fDot0 = + m_aafEntry[0][0] * m_aafEntry[0][2] + + m_aafEntry[1][0] * m_aafEntry[1][2] + + m_aafEntry[2][0] * m_aafEntry[2][2]; + + m_aafEntry[0][2] -= fDot0 * m_aafEntry[0][0] + fDot1 * m_aafEntry[0][1]; + m_aafEntry[1][2] -= fDot0 * m_aafEntry[1][0] + fDot1 * m_aafEntry[1][1]; + m_aafEntry[2][2] -= fDot0 * m_aafEntry[2][0] + fDot1 * m_aafEntry[2][1]; + + fInvLength = Math::InvSqrt(m_aafEntry[0][2] * m_aafEntry[0][2] + + m_aafEntry[1][2] * m_aafEntry[1][2] + + m_aafEntry[2][2] * m_aafEntry[2][2]); + + m_aafEntry[0][2] *= fInvLength; + m_aafEntry[1][2] *= fInvLength; + m_aafEntry[2][2] *= fInvLength; +} +//---------------------------------------------------------------------------- +void Matrix3::QDUDecomposition(Matrix3 &kQ, + Vector3 &kD, Vector3 &kU) const +{ + // Factor M = QR = QDU where Q is orthogonal, D is diagonal, + // and U is upper triangular with ones on its diagonal. Algorithm uses + // Gram-Schmidt orthogonalization (the QR algorithm). + // + // If M = [ m0 | m1 | m2 ] and Q = [ q0 | q1 | q2 ], then + // + // q0 = m0/|m0| + // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| + // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| + // + // where |V| indicates length of vector V and A*B indicates dot + // product of vectors A and B. The matrix R has entries + // + // r00 = q0*m0 r01 = q0*m1 r02 = q0*m2 + // r10 = 0 r11 = q1*m1 r12 = q1*m2 + // r20 = 0 r21 = 0 r22 = q2*m2 + // + // so D = diag(r00,r11,r22) and U has entries u01 = r01/r00, + // u02 = r02/r00, and u12 = r12/r11. + + // Q = rotation + // D = scaling + // U = shear + + // D stores the three diagonal entries r00, r11, r22 + // U stores the entries U[0] = u01, U[1] = u02, U[2] = u12 + + // build orthogonal matrix Q + Real fInvLength = Math::InvSqrt(m_aafEntry[0][0] * m_aafEntry[0][0] + m_aafEntry[1][0] * m_aafEntry[1][0] + + m_aafEntry[2][0] * m_aafEntry[2][0]); + kQ[0][0] = m_aafEntry[0][0] * fInvLength; + kQ[1][0] = m_aafEntry[1][0] * fInvLength; + kQ[2][0] = m_aafEntry[2][0] * fInvLength; + + Real fDot = kQ[0][0] * m_aafEntry[0][1] + kQ[1][0] * m_aafEntry[1][1] + + kQ[2][0] * m_aafEntry[2][1]; + kQ[0][1] = m_aafEntry[0][1] - fDot * kQ[0][0]; + kQ[1][1] = m_aafEntry[1][1] - fDot * kQ[1][0]; + kQ[2][1] = m_aafEntry[2][1] - fDot * kQ[2][0]; + fInvLength = Math::InvSqrt(kQ[0][1] * kQ[0][1] + kQ[1][1] * kQ[1][1] + + kQ[2][1] * kQ[2][1]); + kQ[0][1] *= fInvLength; + kQ[1][1] *= fInvLength; + kQ[2][1] *= fInvLength; + + fDot = kQ[0][0] * m_aafEntry[0][2] + kQ[1][0] * m_aafEntry[1][2] + + kQ[2][0] * m_aafEntry[2][2]; + kQ[0][2] = m_aafEntry[0][2] - fDot * kQ[0][0]; + kQ[1][2] = m_aafEntry[1][2] - fDot * kQ[1][0]; + kQ[2][2] = m_aafEntry[2][2] - fDot * kQ[2][0]; + fDot = kQ[0][1] * m_aafEntry[0][2] + kQ[1][1] * m_aafEntry[1][2] + + kQ[2][1] * m_aafEntry[2][2]; + kQ[0][2] -= fDot * kQ[0][1]; + kQ[1][2] -= fDot * kQ[1][1]; + kQ[2][2] -= fDot * kQ[2][1]; + fInvLength = Math::InvSqrt(kQ[0][2] * kQ[0][2] + kQ[1][2] * kQ[1][2] + + kQ[2][2] * kQ[2][2]); + kQ[0][2] *= fInvLength; + kQ[1][2] *= fInvLength; + kQ[2][2] *= fInvLength; + + // guarantee that orthogonal matrix has determinant 1 (no reflections) + Real fDet = kQ[0][0] * kQ[1][1] * kQ[2][2] + kQ[0][1] * kQ[1][2] * kQ[2][0] + + kQ[0][2] * kQ[1][0] * kQ[2][1] - kQ[0][2] * kQ[1][1] * kQ[2][0] - + kQ[0][1] * kQ[1][0] * kQ[2][2] - kQ[0][0] * kQ[1][2] * kQ[2][1]; + + if (fDet < 0.0f) + { + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + kQ[iRow][iCol] = -kQ[iRow][iCol]; + } + } + + // build "right" matrix R + Matrix3 kR; + kR[0][0] = kQ[0][0] * m_aafEntry[0][0] + kQ[1][0] * m_aafEntry[1][0] + + kQ[2][0] * m_aafEntry[2][0]; + kR[0][1] = kQ[0][0] * m_aafEntry[0][1] + kQ[1][0] * m_aafEntry[1][1] + + kQ[2][0] * m_aafEntry[2][1]; + kR[1][1] = kQ[0][1] * m_aafEntry[0][1] + kQ[1][1] * m_aafEntry[1][1] + + kQ[2][1] * m_aafEntry[2][1]; + kR[0][2] = kQ[0][0] * m_aafEntry[0][2] + kQ[1][0] * m_aafEntry[1][2] + + kQ[2][0] * m_aafEntry[2][2]; + kR[1][2] = kQ[0][1] * m_aafEntry[0][2] + kQ[1][1] * m_aafEntry[1][2] + + kQ[2][1] * m_aafEntry[2][2]; + kR[2][2] = kQ[0][2] * m_aafEntry[0][2] + kQ[1][2] * m_aafEntry[1][2] + + kQ[2][2] * m_aafEntry[2][2]; + + // the scaling component + kD[0] = kR[0][0]; + kD[1] = kR[1][1]; + kD[2] = kR[2][2]; + + // the shear component + Real fInvD0 = 1.0f / kD[0]; + kU[0] = kR[0][1] * fInvD0; + kU[1] = kR[0][2] * fInvD0; + kU[2] = kR[1][2] / kD[1]; +} +//---------------------------------------------------------------------------- +Real Matrix3::MaxCubicRoot(Real afCoeff[3]) +{ + // Spectral norm is for A^T*A, so characteristic polynomial + // P(x) = c[0]+c[1]*x+c[2]*x^2+x^3 has three positive real roots. + // This yields the assertions c[0] < 0 and c[2]*c[2] >= 3*c[1]. + + // quick out for uniform scale (triple root) + const Real fOneThird = 1.0f / 3.0f; + const Real fEpsilon = 1e-06f; + Real fDiscr = afCoeff[2] * afCoeff[2] - 3.0f * afCoeff[1]; + if (fDiscr <= fEpsilon) + return -fOneThird * afCoeff[2]; + + // Compute an upper bound on roots of P(x). This assumes that A^T*A + // has been scaled by its largest entry. + Real fX = 1.0f; + Real fPoly = afCoeff[0] + fX * (afCoeff[1] + fX * (afCoeff[2] + fX)); + if (fPoly < 0.0f) + { + // uses a matrix norm to find an upper bound on maximum root + fX = Math::FAbs(afCoeff[0]); + Real fTmp = 1.0f + Math::FAbs(afCoeff[1]); + if (fTmp > fX) + fX = fTmp; + fTmp = 1.0f + Math::FAbs(afCoeff[2]); + if (fTmp > fX) + fX = fTmp; + } + + // Newton's method to find root + Real fTwoC2 = 2.0f * afCoeff[2]; + for (int i = 0; i < 16; i++) + { + fPoly = afCoeff[0] + fX * (afCoeff[1] + fX * (afCoeff[2] + fX)); + if (Math::FAbs(fPoly) <= fEpsilon) + return fX; + + Real fDeriv = afCoeff[1] + fX * (fTwoC2 + 3.0f * fX); + fX -= fPoly / fDeriv; + } + + return fX; +} +//---------------------------------------------------------------------------- +Real Matrix3::SpectralNorm() const +{ + Matrix3 kP; + int iRow, iCol; + Real fPmax = 0.0f; + for (iRow = 0; iRow < 3; iRow++) + { + for (iCol = 0; iCol < 3; iCol++) + { + kP[iRow][iCol] = 0.0f; + for (int iMid = 0; iMid < 3; iMid++) + { + kP[iRow][iCol] += + m_aafEntry[iMid][iRow] * m_aafEntry[iMid][iCol]; + } + if (kP[iRow][iCol] > fPmax) + fPmax = kP[iRow][iCol]; + } + } + + Real fInvPmax = 1.0f / fPmax; + for (iRow = 0; iRow < 3; iRow++) + { + for (iCol = 0; iCol < 3; iCol++) + kP[iRow][iCol] *= fInvPmax; + } + + Real afCoeff[3]; + afCoeff[0] = -(kP[0][0] * (kP[1][1] * kP[2][2] - kP[1][2] * kP[2][1]) + + kP[0][1] * (kP[2][0] * kP[1][2] - kP[1][0] * kP[2][2]) + + kP[0][2] * (kP[1][0] * kP[2][1] - kP[2][0] * kP[1][1])); + afCoeff[1] = kP[0][0] * kP[1][1] - kP[0][1] * kP[1][0] + + kP[0][0] * kP[2][2] - kP[0][2] * kP[2][0] + + kP[1][1] * kP[2][2] - kP[1][2] * kP[2][1]; + afCoeff[2] = -(kP[0][0] + kP[1][1] + kP[2][2]); + + Real fRoot = MaxCubicRoot(afCoeff); + Real fNorm = Math::Sqrt(fPmax * fRoot); + return fNorm; +} +//---------------------------------------------------------------------------- +void Matrix3::ToAxisAngle(Vector3 &rkAxis, Real &rfRadians) const +{ + // Let (x,y,z) be the unit-length axis and let A be an angle of rotation. + // The rotation matrix is R = I + sin(A)*P + (1-cos(A))*P^2 where + // I is the identity and + // + // +- -+ + // P = | 0 -z +y | + // | +z 0 -x | + // | -y +x 0 | + // +- -+ + // + // If A > 0, R represents a counterclockwise rotation about the axis in + // the sense of looking from the tip of the axis vector towards the + // origin. Some algebra will show that + // + // cos(A) = (trace(R)-1)/2 and R - R^t = 2*sin(A)*P + // + // In the event that A = pi, R-R^t = 0 which prevents us from extracting + // the axis through P. Instead note that R = I+2*P^2 when A = pi, so + // P^2 = (R-I)/2. The diagonal entries of P^2 are x^2-1, y^2-1, and + // z^2-1. We can solve these for axis (x,y,z). Because the angle is pi, + // it does not matter which sign you choose on the square roots. + + Real fTrace = m_aafEntry[0][0] + m_aafEntry[1][1] + m_aafEntry[2][2]; + Real fCos = 0.5f * (fTrace - 1.0f); + rfRadians = Math::ACos(fCos); // in [0,PI] + + if (rfRadians > 0.0f) + { + if (rfRadians < Math::_PI) + { + rkAxis.x = m_aafEntry[2][1] - m_aafEntry[1][2]; + rkAxis.y = m_aafEntry[0][2] - m_aafEntry[2][0]; + rkAxis.z = m_aafEntry[1][0] - m_aafEntry[0][1]; + rkAxis.Unitize(); + } + else + { + // angle is PI + Real fHalfInverse; + if (m_aafEntry[0][0] >= m_aafEntry[1][1]) + { + // r00 >= r11 + if (m_aafEntry[0][0] >= m_aafEntry[2][2]) + { + // r00 is maximum diagonal term + rkAxis.x = 0.5f * Math::Sqrt(m_aafEntry[0][0] - + m_aafEntry[1][1] - m_aafEntry[2][2] + 1.0f); + fHalfInverse = 0.5f / rkAxis.x; + rkAxis.y = fHalfInverse * m_aafEntry[0][1]; + rkAxis.z = fHalfInverse * m_aafEntry[0][2]; + } + else + { + // r22 is maximum diagonal term + rkAxis.z = 0.5f * Math::Sqrt(m_aafEntry[2][2] - + m_aafEntry[0][0] - m_aafEntry[1][1] + 1.0f); + fHalfInverse = 0.5f / rkAxis.z; + rkAxis.x = fHalfInverse * m_aafEntry[0][2]; + rkAxis.y = fHalfInverse * m_aafEntry[1][2]; + } + } + else + { + // r11 > r00 + if (m_aafEntry[1][1] >= m_aafEntry[2][2]) + { + // r11 is maximum diagonal term + rkAxis.y = 0.5f * Math::Sqrt(m_aafEntry[1][1] - + m_aafEntry[0][0] - m_aafEntry[2][2] + 1.0f); + fHalfInverse = 0.5f / rkAxis.y; + rkAxis.x = fHalfInverse * m_aafEntry[0][1]; + rkAxis.z = fHalfInverse * m_aafEntry[1][2]; + } + else + { + // r22 is maximum diagonal term + rkAxis.z = 0.5f * Math::Sqrt(m_aafEntry[2][2] - + m_aafEntry[0][0] - m_aafEntry[1][1] + 1.0f); + fHalfInverse = 0.5f / rkAxis.z; + rkAxis.x = fHalfInverse * m_aafEntry[0][2]; + rkAxis.y = fHalfInverse * m_aafEntry[1][2]; + } + } + } + } + else + { + // The angle is 0 and the matrix is the identity. Any axis will + // work, so just use the x-axis. + rkAxis.x = 1.0f; + rkAxis.y = 0.0f; + rkAxis.z = 0.0f; + } +} +//---------------------------------------------------------------------------- +void Matrix3::FromAxisAngle(const Vector3 &rkAxis, Real fRadians) +{ + Real fCos = Math::Cos(fRadians); + Real fSin = Math::Sin(fRadians); + Real fOneMinusCos = 1.0f - fCos; + Real fX2 = rkAxis.x * rkAxis.x; + Real fY2 = rkAxis.y * rkAxis.y; + Real fZ2 = rkAxis.z * rkAxis.z; + Real fXYM = rkAxis.x * rkAxis.y * fOneMinusCos; + Real fXZM = rkAxis.x * rkAxis.z * fOneMinusCos; + Real fYZM = rkAxis.y * rkAxis.z * fOneMinusCos; + Real fXSin = rkAxis.x * fSin; + Real fYSin = rkAxis.y * fSin; + Real fZSin = rkAxis.z * fSin; + + m_aafEntry[0][0] = fX2 * fOneMinusCos + fCos; + m_aafEntry[0][1] = fXYM - fZSin; + m_aafEntry[0][2] = fXZM + fYSin; + m_aafEntry[1][0] = fXYM + fZSin; + m_aafEntry[1][1] = fY2 * fOneMinusCos + fCos; + m_aafEntry[1][2] = fYZM - fXSin; + m_aafEntry[2][0] = fXZM - fYSin; + m_aafEntry[2][1] = fYZM + fXSin; + m_aafEntry[2][2] = fZ2 * fOneMinusCos + fCos; +} +//---------------------------------------------------------------------------- +bool Matrix3::ToEulerAnglesXYZ(Real &rfXAngle, Real &rfYAngle, + Real &rfZAngle) const +{ + // rot = cy*cz -cy*sz sy + // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx + // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy + + if (m_aafEntry[0][2] < 1.0f) + { + if (m_aafEntry[0][2] > -1.0f) + { + rfXAngle = Math::ATan2(-m_aafEntry[1][2], m_aafEntry[2][2]); + rfYAngle = (Real)asin(m_aafEntry[0][2]); + rfZAngle = Math::ATan2(-m_aafEntry[0][1], m_aafEntry[0][0]); + return true; + } + else + { + // WARNING. Not unique. XA - ZA = -atan2(r10,r11) + rfXAngle = -Math::ATan2(m_aafEntry[1][0], m_aafEntry[1][1]); + rfYAngle = -Math::HALF_PI; + rfZAngle = 0.0f; + return false; + } + } + else + { + // WARNING. Not unique. XAngle + ZAngle = atan2(r10,r11) + rfXAngle = Math::ATan2(m_aafEntry[1][0], m_aafEntry[1][1]); + rfYAngle = Math::HALF_PI; + rfZAngle = 0.0f; + return false; + } +} +//---------------------------------------------------------------------------- +bool Matrix3::ToEulerAnglesXZY(Real &rfXAngle, Real &rfZAngle, + Real &rfYAngle) const +{ + // rot = cy*cz -sz cz*sy + // sx*sy+cx*cy*sz cx*cz -cy*sx+cx*sy*sz + // -cx*sy+cy*sx*sz cz*sx cx*cy+sx*sy*sz + + if (m_aafEntry[0][1] < 1.0f) + { + if (m_aafEntry[0][1] > -1.0f) + { + rfXAngle = Math::ATan2(m_aafEntry[2][1], m_aafEntry[1][1]); + rfZAngle = (Real)asin(-m_aafEntry[0][1]); + rfYAngle = Math::ATan2(m_aafEntry[0][2], m_aafEntry[0][0]); + return true; + } + else + { + // WARNING. Not unique. XA - YA = atan2(r20,r22) + rfXAngle = Math::ATan2(m_aafEntry[2][0], m_aafEntry[2][2]); + rfZAngle = Math::HALF_PI; + rfYAngle = 0.0f; + return false; + } + } + else + { + // WARNING. Not unique. XA + YA = atan2(-r20,r22) + rfXAngle = Math::ATan2(-m_aafEntry[2][0], m_aafEntry[2][2]); + rfZAngle = -Math::HALF_PI; + rfYAngle = 0.0f; + return false; + } +} +//---------------------------------------------------------------------------- +bool Matrix3::ToEulerAnglesYXZ(Real &rfYAngle, Real &rfXAngle, + Real &rfZAngle) const +{ + // rot = cy*cz+sx*sy*sz cz*sx*sy-cy*sz cx*sy + // cx*sz cx*cz -sx + // -cz*sy+cy*sx*sz cy*cz*sx+sy*sz cx*cy + + if (m_aafEntry[1][2] < 1.0f) + { + if (m_aafEntry[1][2] > -1.0f) + { + rfYAngle = Math::ATan2(m_aafEntry[0][2], m_aafEntry[2][2]); + rfXAngle = (Real)asin(-m_aafEntry[1][2]); + rfZAngle = Math::ATan2(m_aafEntry[1][0], m_aafEntry[1][1]); + return true; + } + else + { + // WARNING. Not unique. YA - ZA = atan2(r01,r00) + rfYAngle = Math::ATan2(m_aafEntry[0][1], m_aafEntry[0][0]); + rfXAngle = Math::HALF_PI; + rfZAngle = 0.0f; + return false; + } + } + else + { + // WARNING. Not unique. YA + ZA = atan2(-r01,r00) + rfYAngle = Math::ATan2(-m_aafEntry[0][1], m_aafEntry[0][0]); + rfXAngle = -Math::HALF_PI; + rfZAngle = 0.0f; + return false; + } +} +//---------------------------------------------------------------------------- +bool Matrix3::ToEulerAnglesYZX(Real &rfYAngle, Real &rfZAngle, + Real &rfXAngle) const +{ + // rot = cy*cz sx*sy-cx*cy*sz cx*sy+cy*sx*sz + // sz cx*cz -cz*sx + // -cz*sy cy*sx+cx*sy*sz cx*cy-sx*sy*sz + + if (m_aafEntry[1][0] < 1.0f) + { + if (m_aafEntry[1][0] > -1.0f) + { + rfYAngle = Math::ATan2(-m_aafEntry[2][0], m_aafEntry[0][0]); + rfZAngle = (Real)asin(m_aafEntry[1][0]); + rfXAngle = Math::ATan2(-m_aafEntry[1][2], m_aafEntry[1][1]); + return true; + } + else + { + // WARNING. Not unique. YA - XA = -atan2(r21,r22); + rfYAngle = -Math::ATan2(m_aafEntry[2][1], m_aafEntry[2][2]); + rfZAngle = -Math::HALF_PI; + rfXAngle = 0.0f; + return false; + } + } + else + { + // WARNING. Not unique. YA + XA = atan2(r21,r22) + rfYAngle = Math::ATan2(m_aafEntry[2][1], m_aafEntry[2][2]); + rfZAngle = Math::HALF_PI; + rfXAngle = 0.0f; + return false; + } +} +//---------------------------------------------------------------------------- +bool Matrix3::ToEulerAnglesZXY(Real &rfZAngle, Real &rfXAngle, + Real &rfYAngle) const +{ + // rot = cy*cz-sx*sy*sz -cx*sz cz*sy+cy*sx*sz + // cz*sx*sy+cy*sz cx*cz -cy*cz*sx+sy*sz + // -cx*sy sx cx*cy + + if (m_aafEntry[2][1] < 1.0f) + { + if (m_aafEntry[2][1] > -1.0f) + { + rfZAngle = Math::ATan2(-m_aafEntry[0][1], m_aafEntry[1][1]); + rfXAngle = (Real)asin(m_aafEntry[2][1]); + rfYAngle = Math::ATan2(-m_aafEntry[2][0], m_aafEntry[2][2]); + return true; + } + else + { + // WARNING. Not unique. ZA - YA = -atan(r02,r00) + rfZAngle = -Math::ATan2(m_aafEntry[0][2], m_aafEntry[0][0]); + rfXAngle = -Math::HALF_PI; + rfYAngle = 0.0f; + return false; + } + } + else + { + // WARNING. Not unique. ZA + YA = atan2(r02,r00) + rfZAngle = Math::ATan2(m_aafEntry[0][2], m_aafEntry[0][0]); + rfXAngle = Math::HALF_PI; + rfYAngle = 0.0f; + return false; + } +} +//---------------------------------------------------------------------------- +bool Matrix3::ToEulerAnglesZYX(Real &rfZAngle, Real &rfYAngle, + Real &rfXAngle) const +{ + // rot = cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz + // cy*sz cx*cz+sx*sy*sz -cz*sx+cx*sy*sz + // -sy cy*sx cx*cy + + if (m_aafEntry[2][0] < 1.0f) + { + if (m_aafEntry[2][0] > -1.0f) + { + rfZAngle = Math::ATan2(m_aafEntry[1][0], m_aafEntry[0][0]); + rfYAngle = (Real)asin(-m_aafEntry[2][0]); + rfXAngle = Math::ATan2(m_aafEntry[2][1], m_aafEntry[2][2]); + return true; + } + else + { + // WARNING. Not unique. ZA - XA = -atan2(r01,r02) + rfZAngle = -Math::ATan2(m_aafEntry[0][1], m_aafEntry[0][2]); + rfYAngle = Math::HALF_PI; + rfXAngle = 0.0f; + return false; + } + } + else + { + // WARNING. Not unique. ZA + XA = atan2(-r01,-r02) + rfZAngle = Math::ATan2(-m_aafEntry[0][1], -m_aafEntry[0][2]); + rfYAngle = -Math::HALF_PI; + rfXAngle = 0.0f; + return false; + } +} +//---------------------------------------------------------------------------- +void Matrix3::FromEulerAnglesXYZ(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0f, fSin, fCos); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); + + *this = kXMat * (kYMat * kZMat); +} +//---------------------------------------------------------------------------- +void Matrix3::FromEulerAnglesXZY(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0f, fSin, fCos); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); + + *this = kXMat * (kZMat * kYMat); +} +//---------------------------------------------------------------------------- +void Matrix3::FromEulerAnglesYXZ(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0f, fSin, fCos); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); + + *this = kYMat * (kXMat * kZMat); +} +//---------------------------------------------------------------------------- +void Matrix3::FromEulerAnglesYZX(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0f, fSin, fCos); + + *this = kYMat * (kZMat * kXMat); +} +//---------------------------------------------------------------------------- +void Matrix3::FromEulerAnglesZXY(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0f, fSin, fCos); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); + + *this = kZMat * (kXMat * kYMat); +} +//---------------------------------------------------------------------------- +void Matrix3::FromEulerAnglesZYX(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kZMat(fCos, -fSin, 0.0f, fSin, fCos, 0.0f, 0.0f, 0.0f, 1.0f); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kYMat(fCos, 0.0f, fSin, 0.0f, 1.0f, 0.0f, -fSin, 0.0f, fCos); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kXMat(1.0f, 0.0f, 0.0f, 0.0f, fCos, -fSin, 0.0f, fSin, fCos); + + *this = kZMat * (kYMat * kXMat); +} +//---------------------------------------------------------------------------- +void Matrix3::Tridiagonal(Real afDiag[3], Real afSubDiag[3]) +{ + // Householder reduction T = Q^t M Q + // Input: + // mat, symmetric 3x3 matrix M + // Output: + // mat, orthogonal matrix Q + // diag, diagonal entries of T + // subd, subdiagonal entries of T (T is symmetric) + + Real fA = m_aafEntry[0][0]; + Real fB = m_aafEntry[0][1]; + Real fC = m_aafEntry[0][2]; + Real fD = m_aafEntry[1][1]; + Real fE = m_aafEntry[1][2]; + Real fF = m_aafEntry[2][2]; + + afDiag[0] = fA; + afSubDiag[2] = 0.0f; + if (Math::FAbs(fC) >= EPSILON) + { + Real fLength = Math::Sqrt(fB * fB + fC * fC); + Real fInvLength = 1.0f / fLength; + fB *= fInvLength; + fC *= fInvLength; + Real fQ = 2.0f * fB * fE + fC * (fF - fD); + afDiag[1] = fD + fC * fQ; + afDiag[2] = fF - fC * fQ; + afSubDiag[0] = fLength; + afSubDiag[1] = fE - fB * fQ; + m_aafEntry[0][0] = 1.0f; + m_aafEntry[0][1] = 0.0f; + m_aafEntry[0][2] = 0.0f; + m_aafEntry[1][0] = 0.0f; + m_aafEntry[1][1] = fB; + m_aafEntry[1][2] = fC; + m_aafEntry[2][0] = 0.0f; + m_aafEntry[2][1] = fC; + m_aafEntry[2][2] = -fB; + } + else + { + afDiag[1] = fD; + afDiag[2] = fF; + afSubDiag[0] = fB; + afSubDiag[1] = fE; + m_aafEntry[0][0] = 1.0f; + m_aafEntry[0][1] = 0.0f; + m_aafEntry[0][2] = 0.0f; + m_aafEntry[1][0] = 0.0f; + m_aafEntry[1][1] = 1.0f; + m_aafEntry[1][2] = 0.0f; + m_aafEntry[2][0] = 0.0f; + m_aafEntry[2][1] = 0.0f; + m_aafEntry[2][2] = 1.0f; + } +} +//---------------------------------------------------------------------------- +bool Matrix3::QLAlgorithm(Real afDiag[3], Real afSubDiag[3]) +{ + // QL iteration with implicit shifting to reduce matrix from tridiagonal + // to diagonal + + for (int i0 = 0; i0 < 3; i0++) + { + const int iMaxIter = 32; + int iIter; + for (iIter = 0; iIter < iMaxIter; iIter++) + { + int i1; + for (i1 = i0; i1 <= 1; i1++) + { + Real fSum = Math::FAbs(afDiag[i1]) + + Math::FAbs(afDiag[i1 + 1]); + if (Math::FAbs(afSubDiag[i1]) + fSum == fSum) + break; + } + if (i1 == i0) + break; + + Real fTmp0 = (afDiag[i0 + 1] - afDiag[i0]) / (2.0f * afSubDiag[i0]); + Real fTmp1 = Math::Sqrt(fTmp0 * fTmp0 + 1.0f); + if (fTmp0 < 0.0f) + fTmp0 = afDiag[i1] - afDiag[i0] + afSubDiag[i0] / (fTmp0 - fTmp1); + else + fTmp0 = afDiag[i1] - afDiag[i0] + afSubDiag[i0] / (fTmp0 + fTmp1); + Real fSin = 1.0f; + Real fCos = 1.0f; + Real fTmp2 = 0.0f; + for (int i2 = i1 - 1; i2 >= i0; i2--) + { + Real fTmp3 = fSin * afSubDiag[i2]; + Real fTmp4 = fCos * afSubDiag[i2]; + if (Math::FAbs(fTmp3) >= Math::FAbs(fTmp0)) + { + fCos = fTmp0 / fTmp3; + fTmp1 = Math::Sqrt(fCos * fCos + 1.0f); + afSubDiag[i2 + 1] = fTmp3 * fTmp1; + fSin = 1.0f / fTmp1; + fCos *= fSin; + } + else + { + fSin = fTmp3 / fTmp0; + fTmp1 = Math::Sqrt(fSin * fSin + 1.0f); + afSubDiag[i2 + 1] = fTmp0 * fTmp1; + fCos = 1.0f / fTmp1; + fSin *= fCos; + } + fTmp0 = afDiag[i2 + 1] - fTmp2; + fTmp1 = (afDiag[i2] - fTmp0) * fSin + 2.0f * fTmp4 * fCos; + fTmp2 = fSin * fTmp1; + afDiag[i2 + 1] = fTmp0 + fTmp2; + fTmp0 = fCos * fTmp1 - fTmp4; + + for (int iRow = 0; iRow < 3; iRow++) + { + fTmp3 = m_aafEntry[iRow][i2 + 1]; + m_aafEntry[iRow][i2 + 1] = fSin * m_aafEntry[iRow][i2] + + fCos * fTmp3; + m_aafEntry[iRow][i2] = fCos * m_aafEntry[iRow][i2] - + fSin * fTmp3; + } + } + afDiag[i0] -= fTmp2; + afSubDiag[i0] = fTmp0; + afSubDiag[i1] = 0.0f; + } + + if (iIter == iMaxIter) + { + // should not get here under normal circumstances + return false; + } + } + + return true; +} +//---------------------------------------------------------------------------- +void Matrix3::EigenSolveSymmetric(Real afEigenvalue[3], + Vector3 akEigenvector[3]) const +{ + Matrix3 kMatrix = *this; + Real afSubDiag[3]; + kMatrix.Tridiagonal(afEigenvalue, afSubDiag); + kMatrix.QLAlgorithm(afEigenvalue, afSubDiag); + + for (int i = 0; i < 3; i++) + { + akEigenvector[i][0] = kMatrix[0][i]; + akEigenvector[i][1] = kMatrix[1][i]; + akEigenvector[i][2] = kMatrix[2][i]; + } + + // make eigenvectors form a right--handed system + Vector3 kCross = akEigenvector[1].Cross(akEigenvector[2]); + Real fDet = akEigenvector[0].Dot(kCross); + if (fDet < 0.0f) + { + akEigenvector[2][0] = -akEigenvector[2][0]; + akEigenvector[2][1] = -akEigenvector[2][1]; + akEigenvector[2][2] = -akEigenvector[2][2]; + } +} +//---------------------------------------------------------------------------- +void Matrix3::TensorProduct(const Vector3 &rkU, const Vector3 &rkV, + Matrix3 &rkProduct) +{ + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + rkProduct[iRow][iCol] = rkU[iRow] * rkV[iCol]; + } +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcMatrix3.h b/src/editors/FreeMagic/MgcMatrix3.h new file mode 100644 index 00000000000..9377ed6a86c --- /dev/null +++ b/src/editors/FreeMagic/MgcMatrix3.h @@ -0,0 +1,166 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCMATRIX3_H +#define MGCMATRIX3_H + +#include "MgcVector3.h" + +namespace Mgc +{ + + // NOTE. The (x,y,z) coordinate system is assumed to be right-handed. + // Coordinate axis rotation matrices are of the form + // RX = 1 0 0 + // 0 cos(t) -sin(t) + // 0 sin(t) cos(t) + // where t > 0 indicates a counterclockwise rotation in the yz-plane + // RY = cos(t) 0 sin(t) + // 0 1 0 + // -sin(t) 0 cos(t) + // where t > 0 indicates a counterclockwise rotation in the zx-plane + // RZ = cos(t) -sin(t) 0 + // sin(t) cos(t) 0 + // 0 0 1 + // where t > 0 indicates a counterclockwise rotation in the xy-plane. + + class MAGICFM Matrix3 + { + public: + // construction + Matrix3(); + Matrix3(const Real aafEntry[3][3]); + Matrix3(const Matrix3 &rkMatrix); + Matrix3(Real fEntry00, Real fEntry01, Real fEntry02, + Real fEntry10, Real fEntry11, Real fEntry12, + Real fEntry20, Real fEntry21, Real fEntry22); + + // member access, allows use of construct mat[r][c] + Real *operator[](int iRow) const; + operator Real *(); + Vector3 GetColumn(int iCol) const; + + // assignment and comparison + Matrix3 &operator=(const Matrix3 &rkMatrix); + bool operator==(const Matrix3 &rkMatrix) const; + bool operator!=(const Matrix3 &rkMatrix) const; + + // arithmetic operations + Matrix3 operator+(const Matrix3 &rkMatrix) const; + Matrix3 operator-(const Matrix3 &rkMatrix) const; + Matrix3 operator*(const Matrix3 &rkMatrix) const; + Matrix3 operator-() const; + + // matrix * vector [3x3 * 3x1 = 3x1] + Vector3 operator*(const Vector3 &rkVector) const; + + // vector * matrix [1x3 * 3x3 = 1x3] + MAGICFM friend Vector3 operator*(const Vector3 &rkVector, + const Matrix3 &rkMatrix); + + // matrix * scalar + Matrix3 operator*(Real fScalar) const; + + // scalar * matrix + MAGICFM friend Matrix3 operator*(Real fScalar, const Matrix3 &rkMatrix); + + // M0.TransposeTimes(M1) = M0^t*M1 where M0^t is the transpose of M0 + Matrix3 TransposeTimes(const Matrix3 &rkM) const; + + // M0.TimesTranspose(M1) = M0*M1^t where M1^t is the transpose of M1 + Matrix3 TimesTranspose(const Matrix3 &rkM) const; + + // utilities + Matrix3 Transpose() const; + bool Inverse(Matrix3 &rkInverse, Real fTolerance = 1e-06f) const; + Matrix3 Inverse(Real fTolerance = 1e-06f) const; + Real Determinant() const; + + // SLERP (spherical linear interpolation) without quaternions. Computes + // R(t) = R0*(Transpose(R0)*R1)^t. If Q is a rotation matrix with + // unit-length axis U and angle A, then Q^t is a rotation matrix with + // unit-length axis U and rotation angle t*A. + static Matrix3 Slerp(Real fT, const Matrix3 &rkR0, const Matrix3 &rkR1); + + // singular value decomposition + void SingularValueDecomposition(Matrix3 &rkL, Vector3 &rkS, + Matrix3 &rkR) const; + void SingularValueComposition(const Matrix3 &rkL, + const Vector3 &rkS, const Matrix3 &rkR); + + // Gram-Schmidt orthonormalization (applied to columns of rotation matrix) + void Orthonormalize(); + + // orthogonal Q, diagonal D, upper triangular U stored as (u01,u02,u12) + void QDUDecomposition(Matrix3 &rkQ, Vector3 &rkD, Vector3 &rkU) const; + + Real SpectralNorm() const; + + // matrix must be orthonormal + void ToAxisAngle(Vector3 &rkAxis, Real &rfRadians) const; + void FromAxisAngle(const Vector3 &rkAxis, Real fRadians); + + // The matrix must be orthonormal. The decomposition is yaw*pitch*roll + // where yaw is rotation about the Up vector, pitch is rotation about the + // Right axis, and roll is rotation about the Direction axis. + bool ToEulerAnglesXYZ(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + bool ToEulerAnglesXZY(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + bool ToEulerAnglesYXZ(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + bool ToEulerAnglesYZX(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + bool ToEulerAnglesZXY(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + bool ToEulerAnglesZYX(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + void FromEulerAnglesXYZ(Real fYAngle, Real fPAngle, Real fRAngle); + void FromEulerAnglesXZY(Real fYAngle, Real fPAngle, Real fRAngle); + void FromEulerAnglesYXZ(Real fYAngle, Real fPAngle, Real fRAngle); + void FromEulerAnglesYZX(Real fYAngle, Real fPAngle, Real fRAngle); + void FromEulerAnglesZXY(Real fYAngle, Real fPAngle, Real fRAngle); + void FromEulerAnglesZYX(Real fYAngle, Real fPAngle, Real fRAngle); + + // eigensolver, matrix must be symmetric + void EigenSolveSymmetric(Real afEigenvalue[3], + Vector3 akEigenvector[3]) const; + + static void TensorProduct(const Vector3 &rkU, const Vector3 &rkV, + Matrix3 &rkProduct); + + static const Real EPSILON; + static const Matrix3 ZERO; + static const Matrix3 IDENTITY; + + protected: + // support for eigensolver + void Tridiagonal(Real afDiag[3], Real afSubDiag[3]); + bool QLAlgorithm(Real afDiag[3], Real afSubDiag[3]); + + // support for singular value decomposition + static const Real ms_fSvdEpsilon; + static const int ms_iSvdMaxIterations; + static void Bidiagonalize(Matrix3 &kA, Matrix3 &kL, Matrix3 &kR); + static void GolubKahanStep(Matrix3 &kA, Matrix3 &kL, Matrix3 &kR); + + // support for spectral norm + static Real MaxCubicRoot(Real afCoeff[3]); + + Real m_aafEntry[3][3]; + }; + +#include "MgcMatrix3.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcMatrix3.inl b/src/editors/FreeMagic/MgcMatrix3.inl new file mode 100644 index 00000000000..4a2cb7127b6 --- /dev/null +++ b/src/editors/FreeMagic/MgcMatrix3.inl @@ -0,0 +1,28 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Matrix3::Matrix3() +{ + // For efficiency reasons, do not initialize matrix. +} +//---------------------------------------------------------------------------- +inline Real *Matrix3::operator[](int iRow) const +{ + return (Real *)&m_aafEntry[iRow][0]; +} +//---------------------------------------------------------------------------- +inline Matrix3::operator Real *() +{ + return &m_aafEntry[0][0]; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcMinimize1D.cpp b/src/editors/FreeMagic/MgcMinimize1D.cpp new file mode 100644 index 00000000000..d5001425ac0 --- /dev/null +++ b/src/editors/FreeMagic/MgcMinimize1D.cpp @@ -0,0 +1,277 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#include "MgcMinimize1D.h" +using namespace Mgc; + +//---------------------------------------------------------------------------- +Minimize1D::Minimize1D(Function oF, int iMaxLevel, int iMaxBracket, + void *pvUserData) +{ + assert(oF); + m_oF = oF; + m_iMaxLevel = iMaxLevel; + m_iMaxBracket = iMaxBracket; + m_pvUserData = pvUserData; +} +//---------------------------------------------------------------------------- +void Minimize1D::GetMinimum(Real fT0, Real fT1, Real fTInitial, + Real &rfTMin, Real &rfFMin) +{ + assert(fT0 <= fTInitial && fTInitial <= fT1); + + m_fTMin = Math::MAX_REAL; + m_fFMin = Math::MAX_REAL; + + Real fF0 = m_oF(fT0, m_pvUserData); + Real fFInitial = m_oF(fTInitial, m_pvUserData); + Real fF1 = m_oF(fT1, m_pvUserData); + + GetMinimum(fT0, fF0, fTInitial, fFInitial, fT1, fF1, m_iMaxLevel); + + rfTMin = m_fTMin; + rfFMin = m_fFMin; +} +//---------------------------------------------------------------------------- +void Minimize1D::GetMinimum(Real fT0, Real fF0, Real fTm, Real fFm, + Real fT1, Real fF1, int iLevel) +{ + if (fF0 < m_fFMin) + { + m_fTMin = fT0; + m_fFMin = fF0; + } + + if (fFm < m_fFMin) + { + m_fTMin = fTm; + m_fFMin = fFm; + } + + if (fF1 < m_fFMin) + { + m_fTMin = fT1; + m_fFMin = fF1; + } + + if (iLevel-- == 0) + return; + + if ((fT1 - fTm) * (fF0 - fFm) > (fTm - fT0) * (fFm - fF1)) + { + // quadratic fit has positive second derivative at midpoint + + if (fF1 > fF0) + { + if (fFm >= fF0) + { + // increasing, repeat on [t0,tm] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + } + else + { + // not monotonic, have a bracket + GetBracketedMinimum(fT0, fF0, fTm, fFm, fT1, fF1, iLevel); + } + } + else if (fF1 < fF0) + { + if (fFm >= fF1) + { + // decreasing, repeat on [tm,t1] + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + else + { + // not monotonic, have a bracket + GetBracketedMinimum(fT0, fF0, fTm, fFm, fT1, fF1, iLevel); + } + } + else + { + // constant, repeat on [t0,tm] and [tm,t1] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + } + else + { + // quadratic fit has nonpositive second derivative at midpoint + + if (fF1 > fF0) + { + // repeat on [t0,tm] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + } + else if (fF1 < fF0) + { + // repeat on [tm,t1] + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + else + { + // repeat on [t0,tm] and [tm,t1] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + } +} +//---------------------------------------------------------------------------- +void Minimize1D::GetMinimum(Real fT0, Real fF0, Real fT1, Real fF1, + int iLevel) +{ + if (fF0 < m_fFMin) + { + m_fTMin = fT0; + m_fFMin = fF0; + } + + if (fF1 < m_fFMin) + { + m_fTMin = fT1; + m_fFMin = fF1; + } + + if (iLevel-- == 0) + return; + + Real fTm = 0.5f * (fT0 + fT1); + Real fFm = m_oF(fTm, m_pvUserData); + + if (fF0 - 2.0f * fFm + fF1 > 0.0f) + { + // quadratic fit has positive second derivative at midpoint + + if (fF1 > fF0) + { + if (fFm >= fF0) + { + // increasing, repeat on [t0,tm] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + } + else + { + // not monotonic, have a bracket + GetBracketedMinimum(fT0, fF0, fTm, fFm, fT1, fF1, iLevel); + } + } + else if (fF1 < fF0) + { + if (fFm >= fF1) + { + // decreasing, repeat on [tm,t1] + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + else + { + // not monotonic, have a bracket + GetBracketedMinimum(fT0, fF0, fTm, fFm, fT1, fF1, iLevel); + } + } + else + { + // constant, repeat on [t0,tm] and [tm,t1] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + } + else + { + // quadratic fit has nonpositive second derivative at midpoint + + if (fF1 > fF0) + { + // repeat on [t0,tm] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + } + else if (fF1 < fF0) + { + // repeat on [tm,t1] + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + else + { + // repeat on [t0,tm] and [tm,t1] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + } +} +//---------------------------------------------------------------------------- +void Minimize1D::GetBracketedMinimum(Real fT0, Real fF0, Real fTm, + Real fFm, Real fT1, Real fF1, int iLevel) +{ + for (int i = 0; i < m_iMaxBracket; i++) + { + // update minimum value + if (fFm < m_fFMin) + { + m_fTMin = fTm; + m_fFMin = fFm; + } + + // test for convergence + const Real fEps = 1e-08f, fTol = 1e-04f; + if (Math::FAbs(fT1 - fT0) <= 2.0f * fTol * Math::FAbs(fTm) + fEps) + break; + + // compute vertex of interpolating parabola + Real fDT0 = fT0 - fTm, fDT1 = fT1 - fTm; + Real fDF0 = fF0 - fFm, fDF1 = fF1 - fFm; + Real fTmp0 = fDT0 * fDF1, fTmp1 = fDT1 * fDF0; + Real fDenom = fTmp1 - fTmp0; + if (Math::FAbs(fDenom) < fEps) + return; + + Real fTv = fTm + 0.5f * (fDT1 * fTmp1 - fDT0 * fTmp0) / fDenom; + assert(fT0 <= fTv && fTv <= fT1); + Real fFv = m_oF(fTv, m_pvUserData); + + if (fTv < fTm) + { + if (fFv < fFm) + { + fT1 = fTm; + fF1 = fFm; + fTm = fTv; + fFm = fFv; + } + else + { + fT0 = fTv; + fF0 = fFv; + } + } + else if (fTv > fTm) + { + if (fFv < fFm) + { + fT0 = fTm; + fF0 = fFm; + fTm = fTv; + fFm = fFv; + } + else + { + fT1 = fTv; + fF1 = fFv; + } + } + else + { + // vertex of parabola is already at middle sample point + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + } +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcMinimize1D.h b/src/editors/FreeMagic/MgcMinimize1D.h new file mode 100644 index 00000000000..167a9387784 --- /dev/null +++ b/src/editors/FreeMagic/MgcMinimize1D.h @@ -0,0 +1,55 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCMINIMIZE1D_H +#define MGCMINIMIZE1D_H + +#include "MgcMath.h" + +namespace Mgc +{ + + class MAGICFM Minimize1D + { + public: + typedef Real (*Function)(Real, void *); + + Minimize1D(Function oF, int iMaxLevel, int iMaxBracket, + void *pvUserData = 0); + + int &MaxLevel(); + int &MaxBracket(); + void *&UserData(); + + void GetMinimum(Real fT0, Real fT1, Real fTInitial, + Real &rfTMin, Real &rfFMin); + + protected: + Function m_oF; + int m_iMaxLevel, m_iMaxBracket; + Real m_fTMin, m_fFMin; + void *m_pvUserData; + + void GetMinimum(Real fT0, Real fF0, Real fT1, Real fF1, int iLevel); + + void GetMinimum(Real fT0, Real fF0, Real fTm, Real fFm, Real fT1, + Real fF1, int iLevel); + + void GetBracketedMinimum(Real fT0, Real fF0, Real fTm, + Real fFm, Real fT1, Real fF1, int iLevel); + }; + +#include "MgcMinimize1D.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcMinimize1D.inl b/src/editors/FreeMagic/MgcMinimize1D.inl new file mode 100644 index 00000000000..34c7263240c --- /dev/null +++ b/src/editors/FreeMagic/MgcMinimize1D.inl @@ -0,0 +1,28 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline int &Minimize1D::MaxLevel() +{ + return m_iMaxLevel; +} +//---------------------------------------------------------------------------- +inline int &Minimize1D::MaxBracket() +{ + return m_iMaxBracket; +} +//---------------------------------------------------------------------------- +inline void *&Minimize1D::UserData() +{ + return m_pvUserData; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcMinimizeND.cpp b/src/editors/FreeMagic/MgcMinimizeND.cpp new file mode 100644 index 00000000000..0f38020da6b --- /dev/null +++ b/src/editors/FreeMagic/MgcMinimizeND.cpp @@ -0,0 +1,175 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#include "MgcMinimizeND.h" +using namespace Mgc; + +//---------------------------------------------------------------------------- +MinimizeND::MinimizeND(int iDimensions, Function oF, int iMaxLevel, + int iMaxBracket, int iMaxIterations, void *pvUserData) + : m_kMinimizer(LineFunction, iMaxLevel, iMaxBracket) +{ + assert(iDimensions >= 1 && oF); + + m_iDimensions = iDimensions; + m_oF = oF; + m_iMaxIterations = iMaxIterations; + m_pvUserData = pvUserData; + + m_afTCurr = new Real[m_iDimensions]; + m_afTSave = new Real[m_iDimensions]; + m_afDirectionStorage = new Real[m_iDimensions * (m_iDimensions + 1)]; + m_aafDirection = new Real *[m_iDimensions + 1]; + for (int i = 0; i <= m_iDimensions; i++) + m_aafDirection[i] = &m_afDirectionStorage[i * m_iDimensions]; + m_afDConj = m_aafDirection[m_iDimensions]; + + m_afLineArg = new Real[m_iDimensions]; +} +//---------------------------------------------------------------------------- +MinimizeND::~MinimizeND() +{ + delete[] m_afTCurr; + delete[] m_afTSave; + delete[] m_afDirectionStorage; + delete[] m_aafDirection; + delete[] m_afLineArg; +} +//---------------------------------------------------------------------------- +void MinimizeND::GetMinimum(const Real *afT0, const Real *afT1, + const Real *afTInitial, Real *afTMin, Real &rfFMin) +{ + // for 1D function callback + m_kMinimizer.UserData() = this; + + // initial guess + int iQuantity = m_iDimensions * sizeof(Real); + m_fFCurr = m_oF(afTInitial, m_pvUserData); + memcpy(m_afTSave, afTInitial, iQuantity); + memcpy(m_afTCurr, afTInitial, iQuantity); + + // initialize direction set to the standard Euclidean basis + memset(m_afDirectionStorage, 0, iQuantity * (m_iDimensions + 1)); + int i; + for (i = 0; i < m_iDimensions; i++) + m_aafDirection[i][i] = 1.0f; + + Real fL0, fL1, fLMin; + for (int iIter = 0; iIter < m_iMaxIterations; iIter++) + { + // find minimum in each direction and update current location + for (i = 0; i < m_iDimensions; i++) + { + m_afDCurr = m_aafDirection[i]; + ComputeDomain(afT0, afT1, fL0, fL1); + m_kMinimizer.GetMinimum(fL0, fL1, 0.0f, fLMin, m_fFCurr); + for (int j = 0; j < m_iDimensions; j++) + m_afTCurr[j] += fLMin * m_afDCurr[j]; + } + + // estimate a unit-length conjugate direction + Real fLength = 0.0f; + for (i = 0; i < m_iDimensions; i++) + { + m_afDConj[i] = m_afTCurr[i] - m_afTSave[i]; + fLength += m_afDConj[i] * m_afDConj[i]; + } + + const Real fEpsilon = 1e-06f; + fLength = Math::Sqrt(fLength); + if (fLength < fEpsilon) + { + // New position did not change significantly from old one. + // Should there be a better convergence criterion here? + break; + } + + Real fInvLength = 1.0f / fLength; + for (i = 0; i < m_iDimensions; i++) + m_afDConj[i] *= fInvLength; + + // minimize in conjugate direction + m_afDCurr = m_afDConj; + ComputeDomain(afT0, afT1, fL0, fL1); + m_kMinimizer.GetMinimum(fL0, fL1, 0.0f, fLMin, m_fFCurr); + for (i = 0; i < m_iDimensions; i++) + m_afTCurr[i] += fLMin * m_afDCurr[i]; + + // cycle the directions and add conjugate direction to set + m_afDConj = m_aafDirection[0]; + for (i = 0; i < m_iDimensions; i++) + m_aafDirection[i] = m_aafDirection[i + 1]; + + // set parameters for next pass + memcpy(m_afTSave, m_afTCurr, iQuantity); + } + + memcpy(afTMin, m_afTCurr, iQuantity); + rfFMin = m_fFCurr; +} +//---------------------------------------------------------------------------- +void MinimizeND::ComputeDomain(const Real *afT0, const Real *afT1, + Real &rfL0, Real &rfL1) +{ + rfL0 = -Math::MAX_REAL; + rfL1 = +Math::MAX_REAL; + + for (int i = 0; i < m_iDimensions; i++) + { + Real fB0 = afT0[i] - m_afTCurr[i]; + Real fB1 = afT1[i] - m_afTCurr[i]; + Real fInv; + if (m_afDCurr[i] > 0.0f) + { + // valid t-interval is [B0,B1] + fInv = 1.0f / m_afDCurr[i]; + fB0 *= fInv; + if (fB0 > rfL0) + rfL0 = fB0; + fB1 *= fInv; + if (fB1 < rfL1) + rfL1 = fB1; + } + else if (m_afDCurr[i] < 0.0f) + { + // valid t-interval is [B1,B0] + fInv = 1.0f / m_afDCurr[i]; + fB0 *= fInv; + if (fB0 < rfL1) + rfL1 = fB0; + fB1 *= fInv; + if (fB1 > rfL0) + rfL0 = fB1; + } + } + + // correction if numerical errors lead to values nearly zero + if (rfL0 > 0.0f) + rfL0 = 0.0f; + if (rfL1 < 0.0f) + rfL1 = 0.0f; +} +//---------------------------------------------------------------------------- +Real MinimizeND::LineFunction(Real fT, void *pvUserData) +{ + MinimizeND *pkThis = (MinimizeND *)pvUserData; + + for (int i = 0; i < pkThis->m_iDimensions; i++) + { + pkThis->m_afLineArg[i] = pkThis->m_afTCurr[i] + + fT * pkThis->m_afDCurr[i]; + } + + Real fResult = pkThis->m_oF(pkThis->m_afLineArg, pkThis->m_pvUserData); + return fResult; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcMinimizeND.h b/src/editors/FreeMagic/MgcMinimizeND.h new file mode 100644 index 00000000000..24e81f4896f --- /dev/null +++ b/src/editors/FreeMagic/MgcMinimizeND.h @@ -0,0 +1,64 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCMINIMIZEND_H +#define MGCMINIMIZEND_H + +#include "MgcMinimize1D.h" + +namespace Mgc +{ + + class MAGICFM MinimizeND + { + public: + typedef Real (*Function)(const Real *, void *); + + MinimizeND(int iDimensions, Function oF, int iMaxLevel, int iMaxBracket, + int iMaxIterations, void *pvUserData = 0); + + ~MinimizeND(); + + int &MaxLevel(); + int &MaxBracket(); + void *&UserData(); + + // find minimum on Cartesian-product domain + void GetMinimum(const Real *afT0, const Real *afT1, + const Real *afTInitial, Real *afTMin, Real &rfFMin); + + protected: + int m_iDimensions; + Function m_oF; + int m_iMaxIterations; + void *m_pvUserData; + Minimize1D m_kMinimizer; + Real *m_afDirectionStorage; + Real **m_aafDirection; + Real *m_afDConj; + Real *m_afDCurr; + Real *m_afTSave; + Real *m_afTCurr; + Real m_fFCurr; + Real *m_afLineArg; + + void ComputeDomain(const Real *afT0, const Real *afT1, + Real &rfL0, Real &rfL1); + + static Real LineFunction(Real fT, void *pvUserData); + }; + +#include "MgcMinimizeND.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcMinimizeND.inl b/src/editors/FreeMagic/MgcMinimizeND.inl new file mode 100644 index 00000000000..0774f8b2776 --- /dev/null +++ b/src/editors/FreeMagic/MgcMinimizeND.inl @@ -0,0 +1,28 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline int &MinimizeND::MaxLevel() +{ + return m_kMinimizer.MaxLevel(); +} +//---------------------------------------------------------------------------- +inline int &MinimizeND::MaxBracket() +{ + return m_kMinimizer.MaxBracket(); +} +//---------------------------------------------------------------------------- +inline void *&MinimizeND::UserData() +{ + return m_pvUserData; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcQuaternion.cpp b/src/editors/FreeMagic/MgcQuaternion.cpp new file mode 100644 index 00000000000..52a463bea37 --- /dev/null +++ b/src/editors/FreeMagic/MgcQuaternion.cpp @@ -0,0 +1,390 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +#pragma hdrstop +#include "MgcQuaternion.h" +using namespace Mgc; + +static Real gs_fEpsilon = 1e-03f; +Quaternion Quaternion::ZERO(0.0f, 0.0f, 0.0f, 0.0f); +Quaternion Quaternion::IDENTITY(1.0f, 0.0f, 0.0f, 0.0f); + +//---------------------------------------------------------------------------- +Quaternion::Quaternion(Real fW, Real fX, Real fY, Real fZ) +{ + w = fW; + x = fX; + y = fY; + z = fZ; +} +//---------------------------------------------------------------------------- +Quaternion::Quaternion(const Quaternion &rkQ) +{ + w = rkQ.w; + x = rkQ.x; + y = rkQ.y; + z = rkQ.z; +} +//---------------------------------------------------------------------------- +void Quaternion::FromRotationMatrix(const Matrix3 &kRot) +{ + // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes + // article "Quaternion Calculus and Fast Animation". + + Real fTrace = kRot[0][0] + kRot[1][1] + kRot[2][2]; + Real fRoot; + + if (fTrace > 0.0f) + { + // |w| > 1/2, may as well choose w > 1/2 + fRoot = Math::Sqrt(fTrace + 1.0f); // 2w + w = 0.5f * fRoot; + fRoot = 0.5f / fRoot; // 1/(4w) + x = (kRot[2][1] - kRot[1][2]) * fRoot; + y = (kRot[0][2] - kRot[2][0]) * fRoot; + z = (kRot[1][0] - kRot[0][1]) * fRoot; + } + else + { + // |w| <= 1/2 + static int s_iNext[3] = {1, 2, 0}; + int i = 0; + if (kRot[1][1] > kRot[0][0]) + i = 1; + if (kRot[2][2] > kRot[i][i]) + i = 2; + int j = s_iNext[i]; + int k = s_iNext[j]; + + fRoot = Math::Sqrt(kRot[i][i] - kRot[j][j] - kRot[k][k] + 1.0f); + Real *apkQuat[3] = {&x, &y, &z}; + *apkQuat[i] = 0.5f * fRoot; + fRoot = 0.5f / fRoot; + w = (kRot[k][j] - kRot[j][k]) * fRoot; + *apkQuat[j] = (kRot[j][i] + kRot[i][j]) * fRoot; + *apkQuat[k] = (kRot[k][i] + kRot[i][k]) * fRoot; + } +} +//---------------------------------------------------------------------------- +void Quaternion::ToRotationMatrix(Matrix3 &kRot) const +{ + Real fTx = 2.0f * x; + Real fTy = 2.0f * y; + Real fTz = 2.0f * z; + Real fTwx = fTx * w; + Real fTwy = fTy * w; + Real fTwz = fTz * w; + Real fTxx = fTx * x; + Real fTxy = fTy * x; + Real fTxz = fTz * x; + Real fTyy = fTy * y; + Real fTyz = fTz * y; + Real fTzz = fTz * z; + + kRot[0][0] = 1.0f - (fTyy + fTzz); + kRot[0][1] = fTxy - fTwz; + kRot[0][2] = fTxz + fTwy; + kRot[1][0] = fTxy + fTwz; + kRot[1][1] = 1.0f - (fTxx + fTzz); + kRot[1][2] = fTyz - fTwx; + kRot[2][0] = fTxz - fTwy; + kRot[2][1] = fTyz + fTwx; + kRot[2][2] = 1.0f - (fTxx + fTyy); +} +//---------------------------------------------------------------------------- +void Quaternion::FromAngleAxis(const Real &rfAngle, const Vector3 &rkAxis) +{ + // assert: axis[] is unit length + // + // The quaternion representing the rotation is + // q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k) + + Real fHalfAngle = 0.5f * rfAngle; + Real fSin = Math::Sin(fHalfAngle); + w = Math::Cos(fHalfAngle); + x = fSin * rkAxis.x; + y = fSin * rkAxis.y; + z = fSin * rkAxis.z; +} +//---------------------------------------------------------------------------- +void Quaternion::ToAngleAxis(Real &rfAngle, Vector3 &rkAxis) const +{ + // The quaternion representing the rotation is + // q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k) + + Real fSqrLength = x * x + y * y + z * z; + if (fSqrLength > 0.0f) + { + rfAngle = 2.0f * Math::ACos(w); + Real fInvLength = Math::InvSqrt(fSqrLength); + rkAxis.x = x * fInvLength; + rkAxis.y = y * fInvLength; + rkAxis.z = z * fInvLength; + } + else + { + // angle is 0 (mod 2*pi), so any axis will do + rfAngle = 0.0f; + rkAxis.x = 1.0f; + rkAxis.y = 0.0f; + rkAxis.z = 0.0f; + } +} +//---------------------------------------------------------------------------- +void Quaternion::FromAxes(const Vector3 *akAxis) +{ + Matrix3 kRot; + + for (int iCol = 0; iCol < 3; iCol++) + { + kRot[0][iCol] = akAxis[iCol].x; + kRot[1][iCol] = akAxis[iCol].y; + kRot[2][iCol] = akAxis[iCol].z; + } + + FromRotationMatrix(kRot); +} +//---------------------------------------------------------------------------- +void Quaternion::ToAxes(Vector3 *akAxis) const +{ + Matrix3 kRot; + + ToRotationMatrix(kRot); + + for (int iCol = 0; iCol < 3; iCol++) + { + akAxis[iCol].x = kRot[0][iCol]; + akAxis[iCol].y = kRot[1][iCol]; + akAxis[iCol].z = kRot[2][iCol]; + } +} +//---------------------------------------------------------------------------- +Quaternion &Quaternion::operator=(const Quaternion &rkQ) +{ + w = rkQ.w; + x = rkQ.x; + y = rkQ.y; + z = rkQ.z; + return *this; +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::operator+(const Quaternion &rkQ) const +{ + return Quaternion(w + rkQ.w, x + rkQ.x, y + rkQ.y, z + rkQ.z); +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::operator-(const Quaternion &rkQ) const +{ + return Quaternion(w - rkQ.w, x - rkQ.x, y - rkQ.y, z - rkQ.z); +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::operator*(const Quaternion &rkQ) const +{ + // NOTE: Multiplication is not generally commutative, so in most + // cases p*q != q*p. + + return Quaternion( + w * rkQ.w - x * rkQ.x - y * rkQ.y - z * rkQ.z, + w * rkQ.x + x * rkQ.w + y * rkQ.z - z * rkQ.y, + w * rkQ.y + y * rkQ.w + z * rkQ.x - x * rkQ.z, + w * rkQ.z + z * rkQ.w + x * rkQ.y - y * rkQ.x); +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::operator*(Real fScalar) const +{ + return Quaternion(fScalar * w, fScalar * x, fScalar * y, fScalar * z); +} +//---------------------------------------------------------------------------- +Quaternion Mgc::operator*(Real fScalar, const Quaternion &rkQ) +{ + return Quaternion(fScalar * rkQ.w, fScalar * rkQ.x, fScalar * rkQ.y, + fScalar * rkQ.z); +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::operator-() const +{ + return Quaternion(-w, -x, -y, -z); +} +//---------------------------------------------------------------------------- +Real Quaternion::Dot(const Quaternion &rkQ) const +{ + return w * rkQ.w + x * rkQ.x + y * rkQ.y + z * rkQ.z; +} +//---------------------------------------------------------------------------- +Real Quaternion::Norm() const +{ + return w * w + x * x + y * y + z * z; +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::Inverse() const +{ + Real fNorm = w * w + x * x + y * y + z * z; + if (fNorm > 0.0f) + { + Real fInvNorm = 1.0f / fNorm; + return Quaternion(w * fInvNorm, -x * fInvNorm, -y * fInvNorm, -z * fInvNorm); + } + else + { + // return an invalid result to flag the error + return ZERO; + } +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::UnitInverse() const +{ + // assert: 'this' is unit length + return Quaternion(w, -x, -y, -z); +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::Exp() const +{ + // If q = A*(x*i+y*j+z*k) where (x,y,z) is unit length, then + // exp(q) = cos(A)+sin(A)*(x*i+y*j+z*k). If sin(A) is near zero, + // use exp(q) = cos(A)+A*(x*i+y*j+z*k) since A/sin(A) has limit 1. + + Real fAngle = Math::Sqrt(x * x + y * y + z * z); + Real fSin = Math::Sin(fAngle); + + Quaternion kResult; + kResult.w = Math::Cos(fAngle); + + if (Math::FAbs(fSin) >= gs_fEpsilon) + { + Real fCoeff = fSin / fAngle; + kResult.x = fCoeff * x; + kResult.y = fCoeff * y; + kResult.z = fCoeff * z; + } + else + { + kResult.x = x; + kResult.y = y; + kResult.z = z; + } + + return kResult; +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::Log() const +{ + // If q = cos(A)+sin(A)*(x*i+y*j+z*k) where (x,y,z) is unit length, then + // log(q) = A*(x*i+y*j+z*k). If sin(A) is near zero, use log(q) = + // sin(A)*(x*i+y*j+z*k) since sin(A)/A has limit 1. + + Quaternion kResult; + kResult.w = 0.0f; + + if (Math::FAbs(w) < 1.0f) + { + Real fAngle = Math::ACos(w); + Real fSin = Math::Sin(fAngle); + if (Math::FAbs(fSin) >= gs_fEpsilon) + { + Real fCoeff = fAngle / fSin; + kResult.x = fCoeff * x; + kResult.y = fCoeff * y; + kResult.z = fCoeff * z; + return kResult; + } + } + + kResult.x = x; + kResult.y = y; + kResult.z = z; + + return kResult; +} +//---------------------------------------------------------------------------- +Vector3 Quaternion::operator*(const Vector3 &rkVector) const +{ + // Given a vector u = (x0,y0,z0) and a unit length quaternion + // q = , the vector v = (x1,y1,z1) which represents the + // rotation of u by q is v = q*u*q^{-1} where * indicates quaternion + // multiplication and where u is treated as the quaternion <0,x0,y0,z0>. + // Note that q^{-1} = , so no real work is required to + // invert q. Now + // + // q*u*q^{-1} = q*<0,x0,y0,z0>*q^{-1} + // = q*(x0*i+y0*j+z0*k)*q^{-1} + // = x0*(q*i*q^{-1})+y0*(q*j*q^{-1})+z0*(q*k*q^{-1}) + // + // As 3-vectors, q*i*q^{-1}, q*j*q^{-1}, and 2*k*q^{-1} are the columns + // of the rotation matrix computed in Quaternion::ToRotationMatrix. + // The vector v is obtained as the product of that rotation matrix with + // vector u. As such, the quaternion representation of a rotation + // matrix requires less space than the matrix and more time to compute + // the rotated vector. Typical space-time tradeoff... + + Matrix3 kRot; + ToRotationMatrix(kRot); + return kRot * rkVector; +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::Slerp(Real fT, const Quaternion &rkP, + const Quaternion &rkQ) +{ + Real fCos = rkP.Dot(rkQ); + Real fAngle = Math::ACos(fCos); + + if (Math::FAbs(fAngle) < gs_fEpsilon) + return rkP; + + Real fSin = Math::Sin(fAngle); + Real fInvSin = 1.0f / fSin; + Real fCoeff0 = Math::Sin((1.0f - fT) * fAngle) * fInvSin; + Real fCoeff1 = Math::Sin(fT * fAngle) * fInvSin; + return fCoeff0 * rkP + fCoeff1 * rkQ; +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::SlerpExtraSpins(Real fT, + const Quaternion &rkP, const Quaternion &rkQ, int iExtraSpins) +{ + Real fCos = rkP.Dot(rkQ); + Real fAngle = Math::ACos(fCos); + + if (Math::FAbs(fAngle) < gs_fEpsilon) + return rkP; + + Real fSin = Math::Sin(fAngle); + Real fPhase = Math::_PI * iExtraSpins * fT; + Real fInvSin = 1.0f / fSin; + Real fCoeff0 = Math::Sin((1.0f - fT) * fAngle - fPhase) * fInvSin; + Real fCoeff1 = Math::Sin(fT * fAngle + fPhase) * fInvSin; + return fCoeff0 * rkP + fCoeff1 * rkQ; +} +//---------------------------------------------------------------------------- +void Quaternion::Intermediate(const Quaternion &rkQ0, + const Quaternion &rkQ1, const Quaternion &rkQ2, Quaternion &rkA, + Quaternion &rkB) +{ + // assert: q0, q1, q2 are unit quaternions + + Quaternion kQ0inv = rkQ0.UnitInverse(); + Quaternion kQ1inv = rkQ1.UnitInverse(); + Quaternion rkP0 = kQ0inv * rkQ1; + Quaternion rkP1 = kQ1inv * rkQ2; + Quaternion kArg = 0.25f * (rkP0.Log() - rkP1.Log()); + Quaternion kMinusArg = -kArg; + + rkA = rkQ1 * kArg.Exp(); + rkB = rkQ1 * kMinusArg.Exp(); +} +//---------------------------------------------------------------------------- +Quaternion Quaternion::Squad(Real fT, const Quaternion &rkP, + const Quaternion &rkA, const Quaternion &rkB, const Quaternion &rkQ) +{ + Real fSlerpT = 2.0f * fT * (1.0f - fT); + Quaternion kSlerpP = Slerp(fT, rkP, rkQ); + Quaternion kSlerpQ = Slerp(fT, rkA, rkB); + return Slerp(fSlerpT, kSlerpP, kSlerpQ); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcQuaternion.h b/src/editors/FreeMagic/MgcQuaternion.h new file mode 100644 index 00000000000..6f44a48b4eb --- /dev/null +++ b/src/editors/FreeMagic/MgcQuaternion.h @@ -0,0 +1,85 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCQUATERNION_H +#define MGCQUATERNION_H + +#include "MgcMatrix3.h" + +namespace Mgc +{ + + class MAGICFM Quaternion + { + public: + Real w, x, y, z; + + // construction and destruction + Quaternion(Real fW = 1.0f, Real fX = 0.0f, Real fY = 0.0f, + Real fZ = 0.0f); + Quaternion(const Quaternion &rkQ); + + // conversion between quaternions, matrices, and angle-axes + void FromRotationMatrix(const Matrix3 &kRot); + void ToRotationMatrix(Matrix3 &kRot) const; + void FromAngleAxis(const Real &rfAngle, const Vector3 &rkAxis); + void ToAngleAxis(Real &rfAngle, Vector3 &rkAxis) const; + void FromAxes(const Vector3 *akAxis); + void ToAxes(Vector3 *akAxis) const; + + // arithmetic operations + Quaternion &operator=(const Quaternion &rkQ); + Quaternion operator+(const Quaternion &rkQ) const; + Quaternion operator-(const Quaternion &rkQ) const; + Quaternion operator*(const Quaternion &rkQ) const; + Quaternion operator*(Real fScalar) const; + MAGICFM friend Quaternion operator*(Real fScalar, + const Quaternion &rkQ); + Quaternion operator-() const; + + // functions of a quaternion + Real Dot(const Quaternion &rkQ) const; // dot product + Real Norm() const; // squared-length + Quaternion Inverse() const; // apply to non-zero quaternion + Quaternion UnitInverse() const; // apply to unit-length quaternion + Quaternion Exp() const; + Quaternion Log() const; + + // rotation of a vector by a quaternion + Vector3 operator*(const Vector3 &rkVector) const; + + // spherical linear interpolation + static Quaternion Slerp(Real fT, const Quaternion &rkP, + const Quaternion &rkQ); + + static Quaternion SlerpExtraSpins(Real fT, + const Quaternion &rkP, const Quaternion &rkQ, + int iExtraSpins); + + // setup for spherical quadratic interpolation + static void Intermediate(const Quaternion &rkQ0, + const Quaternion &rkQ1, const Quaternion &rkQ2, + Quaternion &rka, Quaternion &rkB); + + // spherical quadratic interpolation + static Quaternion Squad(Real fT, const Quaternion &rkP, + const Quaternion &rkA, const Quaternion &rkB, + const Quaternion &rkQ); + + // special values + static Quaternion ZERO; + static Quaternion IDENTITY; + }; + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcRTLib.h b/src/editors/FreeMagic/MgcRTLib.h new file mode 100644 index 00000000000..b1bf3956142 --- /dev/null +++ b/src/editors/FreeMagic/MgcRTLib.h @@ -0,0 +1,34 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCRTLIB_H +#define MGCRTLIB_H + +// A wrapper around some headers for run-time libraries. I added this because +// CodeWarrior 6.1 for the Macintosh uses namespace std for functions exposed +// in cmath, cstring, etc. Windows or Linux does not do this. I do not know +// what the STL standard is for this. + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__MACOS__) && !defined(__MACH__) +using namespace std; +#endif + +#endif diff --git a/src/editors/FreeMagic/MgcRay3.h b/src/editors/FreeMagic/MgcRay3.h new file mode 100644 index 00000000000..8d214c75a23 --- /dev/null +++ b/src/editors/FreeMagic/MgcRay3.h @@ -0,0 +1,42 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCRAY3_H +#define MGCRAY3_H + +#include "MgcVector3.h" + +namespace Mgc +{ + + class MAGICFM Ray3 + { + public: + // Ray is R(t) = P+t*D for t >= 0. D is not necessarily unit length. + Ray3(); + + Vector3 &Origin(); + const Vector3 &Origin() const; + + Vector3 &Direction(); + const Vector3 &Direction() const; + + protected: + Vector3 m_kOrigin; // P + Vector3 m_kDirection; // D + }; + +#include "MgcRay3.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcRay3.inl b/src/editors/FreeMagic/MgcRay3.inl new file mode 100644 index 00000000000..73de6bed9d2 --- /dev/null +++ b/src/editors/FreeMagic/MgcRay3.inl @@ -0,0 +1,38 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Ray3::Ray3() +{ + // no initialization for efficiency +} +//---------------------------------------------------------------------------- +inline Vector3 &Ray3::Origin() +{ + return m_kOrigin; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Ray3::Origin() const +{ + return m_kOrigin; +} +//---------------------------------------------------------------------------- +inline Vector3 &Ray3::Direction() +{ + return m_kDirection; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Ray3::Direction() const +{ + return m_kDirection; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcSegment3.h b/src/editors/FreeMagic/MgcSegment3.h new file mode 100644 index 00000000000..c3638ce3bf2 --- /dev/null +++ b/src/editors/FreeMagic/MgcSegment3.h @@ -0,0 +1,43 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCSEGMENT3_H +#define MGCSEGMENT3_H + +#include "MgcVector3.h" + +namespace Mgc +{ + + class MAGICFM Segment3 + { + public: + // Segment is S(t) = P+t*D for 0 <= t <= 1. D is not necessarily unit + // length. The end points are P and P+D. + Segment3(); + + Vector3 &Origin(); + const Vector3 &Origin() const; + + Vector3 &Direction(); + const Vector3 &Direction() const; + + protected: + Vector3 m_kOrigin; // P + Vector3 m_kDirection; // D + }; + +#include "MgcSegment3.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcSegment3.inl b/src/editors/FreeMagic/MgcSegment3.inl new file mode 100644 index 00000000000..c547e0442c9 --- /dev/null +++ b/src/editors/FreeMagic/MgcSegment3.inl @@ -0,0 +1,38 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Segment3::Segment3() +{ + // no initialization for efficiency +} +//---------------------------------------------------------------------------- +inline Vector3 &Segment3::Origin() +{ + return m_kOrigin; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Segment3::Origin() const +{ + return m_kOrigin; +} +//---------------------------------------------------------------------------- +inline Vector3 &Segment3::Direction() +{ + return m_kDirection; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Segment3::Direction() const +{ + return m_kDirection; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcSmallSet.h b/src/editors/FreeMagic/MgcSmallSet.h new file mode 100644 index 00000000000..d96640f5426 --- /dev/null +++ b/src/editors/FreeMagic/MgcSmallSet.h @@ -0,0 +1,73 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCSMALLSET_H +#define MGCSMALLSET_H + +// This template class is used by Mgc::TriangleMesh to store the edges and +// triangles that share a vertex and to store the triangles that share an +// edge. Before this the 'set' class was used from STL, but the memory +// overhead for the class is enormous. As an example, I used the code to +// build the adjacency information for a level surface that was a collection +// of 825K vertices and 1.6M triangles (mesh had 2.5M edges). The memory +// used by the program that built the adjacency information was 980M. The +// program based on Mgc::SmallSet used 503M. +// +// The idea is that for a typical mesh, the average number of edges sharing +// a vertex is 6 and the average number of triangles sharing a vertex is 6. +// The average number of triangles sharing an edge is 2. Since the sets of +// adjacent objects are small, the Insert method does a linear search to +// check if the element already exists. Reallocation occurs if the current +// set is full to make room for the new element. The Remove method does a +// linear search and, if the requested element is found, removes it and +// shifts the higher-indexed array elements to fill in the gap. Because of +// the linear searches, this class should not be used for large sets. Large +// sets are better handled by a hashed data structure. + +#include "MgcRTLib.h" + +namespace Mgc +{ + + template + class SmallSet + { + public: + SmallSet(); + SmallSet(int iCapacity, int iGrowBy); + SmallSet(const SmallSet &rkSet); + ~SmallSet(); + + SmallSet &operator=(const SmallSet &rkSet); + + int GetCapacity() const; + int GetGrowBy() const; + int GetSize() const; + const T *GetElements() const; + const T &operator[](int i) const; + + bool Insert(const T &rkElement); + void InsertNoCheck(const T &rkElement); + bool Remove(const T &rkElement); + bool Exists(const T &rkElement); + void Clear(int iCapacity, int iGrowBy); + + protected: + int m_iCapacity, m_iGrowBy, m_iSize; + T *m_atElement; + }; + +#include "MgcSmallSet.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcSmallSet.inl b/src/editors/FreeMagic/MgcSmallSet.inl new file mode 100644 index 00000000000..bc223a2145a --- /dev/null +++ b/src/editors/FreeMagic/MgcSmallSet.inl @@ -0,0 +1,176 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +template +SmallSet::SmallSet() +{ + m_iCapacity = 1; + m_iGrowBy = 1; + m_iSize = 0; + m_atElement = new T[1]; +} +//---------------------------------------------------------------------------- +template +SmallSet::SmallSet(int iCapacity, int iGrowBy) +{ + assert(iCapacity > 0 && iGrowBy > 0); + + m_iCapacity = iCapacity; + m_iGrowBy = iGrowBy; + m_iSize = 0; + m_atElement = new T[iCapacity]; +} +//---------------------------------------------------------------------------- +template +SmallSet::SmallSet(const SmallSet &rkSet) +{ + m_iCapacity = rkSet.m_iCapacity; + m_iGrowBy = rkSet.m_iGrowBy; + m_iSize = rkSet.m_iSize; + m_atElement = new T[m_iCapacity]; + memcpy(m_atElement, rkSet.m_atElement, m_iCapacity * sizeof(T)); +} +//---------------------------------------------------------------------------- +template +SmallSet::~SmallSet() +{ + delete[] m_atElement; +} +//---------------------------------------------------------------------------- +template +SmallSet &SmallSet::operator=(const SmallSet &rkSet) +{ + delete[] m_atElement; + m_iCapacity = rkSet.m_iCapacity; + m_iGrowBy = rkSet.m_iGrowBy; + m_iSize = rkSet.m_iSize; + m_atElement = new T[m_iCapacity]; + memcpy(m_atElement, rkSet.m_atElement, m_iCapacity * sizeof(T)); + return *this; +} +//---------------------------------------------------------------------------- +template +int SmallSet::GetCapacity() const +{ + return m_iCapacity; +} +//---------------------------------------------------------------------------- +template +int SmallSet::GetGrowBy() const +{ + return m_iGrowBy; +} +//---------------------------------------------------------------------------- +template +int SmallSet::GetSize() const +{ + return m_iSize; +} +//---------------------------------------------------------------------------- +template +const T *SmallSet::GetElements() const +{ + return m_atElement; +} +//---------------------------------------------------------------------------- +template +const T &SmallSet::operator[](int i) const +{ + assert(0 <= i && i < m_iSize); + return m_atElement[i]; +} +//---------------------------------------------------------------------------- +template +bool SmallSet::Insert(const T &rkElement) +{ + for (int i = 0; i < m_iSize; i++) + { + if (rkElement == m_atElement[i]) + return false; + } + + if (m_iSize == m_iCapacity) + { + // array is full, resize it + int iNewCapacity = m_iCapacity + m_iGrowBy; + T *atNewElement = new T[iNewCapacity]; + memcpy(atNewElement, m_atElement, m_iCapacity * sizeof(T)); + delete[] m_atElement; + m_atElement = atNewElement; + m_iCapacity = iNewCapacity; + } + + m_atElement[m_iSize++] = rkElement; + return true; +} +//---------------------------------------------------------------------------- +template +void SmallSet::InsertNoCheck(const T &rkElement) +{ + if (m_iSize == m_iCapacity) + { + // array is full, resize it + int iNewCapacity = m_iCapacity + m_iGrowBy; + T *atNewElement = new T[iNewCapacity]; + memcpy(atNewElement, m_atElement, m_iCapacity * sizeof(T)); + delete[] m_atElement; + m_atElement = atNewElement; + m_iCapacity = iNewCapacity; + } + + m_atElement[m_iSize++] = rkElement; +} +//---------------------------------------------------------------------------- +template +bool SmallSet::Remove(const T &rkElement) +{ + for (int i = 0; i < m_iSize; i++) + { + if (rkElement == m_atElement[i]) + { + // element exists, shift array to fill in empty slot + for (int j = i + 1; j < m_iSize; j++, i++) + m_atElement[i] = m_atElement[j]; + + m_iSize--; + return true; + } + } + + return false; +} +//---------------------------------------------------------------------------- +template +bool SmallSet::Exists(const T &rkElement) +{ + for (int i = 0; i < m_iSize; i++) + { + if (rkElement == m_atElement[i]) + return true; + } + + return false; +} +//---------------------------------------------------------------------------- +template +void SmallSet::Clear(int iCapacity, int iGrowBy) +{ + assert(iCapacity > 0 && iGrowBy > 0); + + delete[] m_atElement; + m_iCapacity = iCapacity; + m_iGrowBy = iGrowBy; + m_iSize = 0; + m_atElement = new T[iCapacity]; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcSphere.h b/src/editors/FreeMagic/MgcSphere.h new file mode 100644 index 00000000000..03f376ca796 --- /dev/null +++ b/src/editors/FreeMagic/MgcSphere.h @@ -0,0 +1,41 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCSPHERE_H +#define MGCSPHERE_H + +#include "MgcVector3.h" + +namespace Mgc +{ + + class MAGICFM Sphere + { + public: + Sphere(); + + Vector3 &Center(); + const Vector3 &Center() const; + + Real &Radius(); + const Real &Radius() const; + + protected: + Vector3 m_kCenter; + Real m_fRadius; + }; + +#include "MgcSphere.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcSphere.inl b/src/editors/FreeMagic/MgcSphere.inl new file mode 100644 index 00000000000..beeb466819d --- /dev/null +++ b/src/editors/FreeMagic/MgcSphere.inl @@ -0,0 +1,38 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Sphere::Sphere() +{ + // no initialization for efficiency +} +//---------------------------------------------------------------------------- +inline Vector3 &Sphere::Center() +{ + return m_kCenter; +} +//---------------------------------------------------------------------------- +inline const Vector3 &Sphere::Center() const +{ + return m_kCenter; +} +//---------------------------------------------------------------------------- +inline Real &Sphere::Radius() +{ + return m_fRadius; +} +//---------------------------------------------------------------------------- +inline const Real &Sphere::Radius() const +{ + return m_fRadius; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcTriangleMesh.cpp b/src/editors/FreeMagic/MgcTriangleMesh.cpp new file mode 100644 index 00000000000..5c56e79b705 --- /dev/null +++ b/src/editors/FreeMagic/MgcTriangleMesh.cpp @@ -0,0 +1,776 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#include "MgcTriangleMesh.h" +using namespace Mgc; + +#include +#include +#include +using namespace std; + +#ifdef SGI_MIPSPRO +// Instantiations to support dynamic link libraries. This appears to be +// necessary on the SGI running IRIX and using the MIPSPRO CC compiler. +template class Mgc::SmallSet; +template class Mgc::SmallSet; +#endif + +//---------------------------------------------------------------------------- +TriangleMesh::TriangleMesh() +{ +} +//---------------------------------------------------------------------------- +TriangleMesh::~TriangleMesh() +{ +} +//---------------------------------------------------------------------------- +void TriangleMesh::InsertTriangle(int iV0, int iV1, int iV2) +{ + Triangle kT(iV0, iV1, iV2); + Edge kE0(iV0, iV1), kE1(iV1, iV2), kE2(iV2, iV0); + + // insert triangle + pair kRT = m_kTMap.insert(make_pair(kT, TriangleAttribute())); + + // insert vertices + pair kRV0 = m_kVMap.insert(make_pair(iV0, VertexAttribute())); + kRV0.first->second.m_kESet.Insert(kE0); + kRV0.first->second.m_kESet.Insert(kE2); + kRV0.first->second.m_kTSet.Insert(kT); + + pair kRV1 = m_kVMap.insert(make_pair(iV1, VertexAttribute())); + kRV1.first->second.m_kESet.Insert(kE0); + kRV1.first->second.m_kESet.Insert(kE1); + kRV1.first->second.m_kTSet.Insert(kT); + + pair kRV2 = m_kVMap.insert(make_pair(iV2, VertexAttribute())); + kRV2.first->second.m_kESet.Insert(kE1); + kRV2.first->second.m_kESet.Insert(kE2); + kRV2.first->second.m_kTSet.Insert(kT); + + // insert edges + pair kRE0 = m_kEMap.insert(make_pair(kE0, EdgeAttribute())); + kRE0.first->second.m_kTSet.Insert(kT); + + pair kRE1 = m_kEMap.insert(make_pair(kE1, EdgeAttribute())); + kRE1.first->second.m_kTSet.Insert(kT); + + pair kRE2 = m_kEMap.insert(make_pair(kE2, EdgeAttribute())); + kRE2.first->second.m_kTSet.Insert(kT); + + // Notify derived classes that mesh components have been inserted. The + // notification occurs here to make sure the derived classes have access + // to the current state of the mesh after the triangle insertion. + OnVertexInsert(iV0, kRV0.second, kRV0.first->second.m_pvData); + OnVertexInsert(iV1, kRV1.second, kRV1.first->second.m_pvData); + OnVertexInsert(iV2, kRV2.second, kRV2.first->second.m_pvData); + OnEdgeInsert(kE0, kRE0.second, kRE0.first->second.m_pvData); + OnEdgeInsert(kE1, kRE1.second, kRE1.first->second.m_pvData); + OnEdgeInsert(kE2, kRE2.second, kRE2.first->second.m_pvData); + OnTriangleInsert(kT, kRT.second, kRT.first->second.m_pvData); +} +//---------------------------------------------------------------------------- +void TriangleMesh::InsertTriangle(const Triangle &rkT) +{ + InsertTriangle(rkT.m_aiV[0], rkT.m_aiV[1], rkT.m_aiV[2]); +} +//---------------------------------------------------------------------------- +void TriangleMesh::RemoveTriangle(int iV0, int iV1, int iV2) +{ + // remove triangle + Triangle kT(iV0, iV1, iV2); + MTIter pkT = m_kTMap.find(kT); + if (pkT == m_kTMap.end()) + { + // triangle does not exist, nothing to do + return; + } + + // update edges + Edge kE0(iV0, iV1), kE1(iV1, iV2), kE2(iV2, iV0); + + MEIter pkE0 = m_kEMap.find(kE0); + assert(pkE0 != m_kEMap.end()); + pkE0->second.m_kTSet.Remove(kT); + + MEIter pkE1 = m_kEMap.find(kE1); + assert(pkE1 != m_kEMap.end()); + pkE1->second.m_kTSet.Remove(kT); + + MEIter pkE2 = m_kEMap.find(kE2); + assert(pkE2 != m_kEMap.end()); + pkE2->second.m_kTSet.Remove(kT); + + // update vertices + MVIter pkV0 = m_kVMap.find(iV0); + assert(pkV0 != m_kVMap.end()); + pkV0->second.m_kTSet.Remove(kT); + + MVIter pkV1 = m_kVMap.find(iV1); + assert(pkV1 != m_kVMap.end()); + pkV1->second.m_kTSet.Remove(kT); + + MVIter pkV2 = m_kVMap.find(iV2); + assert(pkV2 != m_kVMap.end()); + pkV2->second.m_kTSet.Remove(kT); + + if (pkE0->second.m_kTSet.GetSize() == 0) + { + pkV0->second.m_kESet.Remove(kE0); + pkV1->second.m_kESet.Remove(kE0); + } + + if (pkE1->second.m_kTSet.GetSize() == 0) + { + pkV1->second.m_kESet.Remove(kE1); + pkV2->second.m_kESet.Remove(kE1); + } + + if (pkE2->second.m_kTSet.GetSize() == 0) + { + pkV0->second.m_kESet.Remove(kE2); + pkV2->second.m_kESet.Remove(kE2); + } + + // Notify derived classes that mesh components are about to be destroyed. + // The notification occurs here to make sure the derived classes have + // access to the current state of the mesh before the triangle removal. + + bool bDestroy = pkV0->second.m_kESet.GetSize() == 0 && + pkV0->second.m_kTSet.GetSize() == 0; + OnVertexRemove(iV0, bDestroy, pkV0->second.m_pvData); + if (bDestroy) + m_kVMap.erase(iV0); + + bDestroy = pkV1->second.m_kESet.GetSize() == 0 && + pkV1->second.m_kTSet.GetSize() == 0; + OnVertexRemove(iV1, bDestroy, pkV1->second.m_pvData); + if (bDestroy) + m_kVMap.erase(iV1); + + bDestroy = pkV2->second.m_kESet.GetSize() == 0 && + pkV2->second.m_kTSet.GetSize() == 0; + OnVertexRemove(iV2, bDestroy, pkV2->second.m_pvData); + if (bDestroy) + m_kVMap.erase(iV2); + + bDestroy = pkE0->second.m_kTSet.GetSize() == 0; + OnEdgeRemove(kE0, bDestroy, pkE0->second.m_pvData); + if (bDestroy) + m_kEMap.erase(kE0); + + bDestroy = pkE1->second.m_kTSet.GetSize() == 0; + OnEdgeRemove(kE1, bDestroy, pkE1->second.m_pvData); + if (bDestroy) + m_kEMap.erase(kE1); + + bDestroy = pkE2->second.m_kTSet.GetSize() == 0; + OnEdgeRemove(kE2, bDestroy, pkE2->second.m_pvData); + if (bDestroy) + m_kEMap.erase(kE2); + + OnTriangleRemove(kT, true, pkT->second.m_pvData); + m_kTMap.erase(kT); +} +//---------------------------------------------------------------------------- +void TriangleMesh::RemoveTriangle(const Triangle &rkT) +{ + RemoveTriangle(rkT.m_aiV[0], rkT.m_aiV[1], rkT.m_aiV[2]); +} +//---------------------------------------------------------------------------- +void TriangleMesh::RemoveAllTriangles() +{ + MTIter pkT = m_kTMap.begin(); + while (pkT != m_kTMap.end()) + { + int iV0 = pkT->first.m_aiV[0]; + int iV1 = pkT->first.m_aiV[1]; + int iV2 = pkT->first.m_aiV[2]; + pkT++; + + RemoveTriangle(iV0, iV1, iV2); + } +} +//---------------------------------------------------------------------------- +void TriangleMesh::Print(const char *acFilename) const +{ + ofstream kOStr(acFilename); + int i; + + // print vertices + kOStr << "vertex quantity = " << m_kVMap.size() << endl; + for (MVCIter pkVM = m_kVMap.begin(); pkVM != m_kVMap.end(); pkVM++) + { + kOStr << "v<" << pkVM->first << "> : e "; + + const SmallSet &rkESet = pkVM->second.m_kESet; + for (i = 0; i < rkESet.GetSize(); i++) + { + kOStr << '<' << rkESet[i].m_aiV[0] + << ',' << rkESet[i].m_aiV[1] + << "> "; + } + + kOStr << ": t "; + const SmallSet &rkTSet = pkVM->second.m_kTSet; + for (i = 0; i < rkTSet.GetSize(); i++) + { + kOStr << '<' << rkTSet[i].m_aiV[0] + << ',' << rkTSet[i].m_aiV[1] + << ',' << rkTSet[i].m_aiV[2] + << "> "; + } + kOStr << endl; + } + kOStr << endl; + + // print edges + kOStr << "edge quantity = " << m_kEMap.size() << endl; + for (MECIter pkEM = m_kEMap.begin(); pkEM != m_kEMap.end(); pkEM++) + { + kOStr << "e<" << pkEM->first.m_aiV[0] << ',' << pkEM->first.m_aiV[1]; + kOStr << "> : t "; + const SmallSet &rkTSet = pkEM->second.m_kTSet; + for (i = 0; i < rkTSet.GetSize(); i++) + { + kOStr << '<' << rkTSet[i].m_aiV[0] + << ',' << rkTSet[i].m_aiV[1] + << ',' << rkTSet[i].m_aiV[2] + << "> "; + } + kOStr << endl; + } + kOStr << endl; + + // print triangles + kOStr << "triangle quantity = " << m_kTMap.size() << endl; + for (MTCIter pkTM = m_kTMap.begin(); pkTM != m_kTMap.end(); pkTM++) + { + kOStr << "t<" << pkTM->first.m_aiV[0] << ',' << pkTM->first.m_aiV[1]; + kOStr << ',' << pkTM->first.m_aiV[2] << ">" << endl; + } + kOStr << endl; +} +//---------------------------------------------------------------------------- +void TriangleMesh::GetVertices(set &rkVSet) const +{ + rkVSet.clear(); + for (MVCIter pkV = m_kVMap.begin(); pkV != m_kVMap.end(); pkV++) + rkVSet.insert(pkV->first); +} +//---------------------------------------------------------------------------- +void *TriangleMesh::GetData(int iV) +{ + MVIter pkV = m_kVMap.find(iV); + return (pkV != m_kVMap.end() ? pkV->second.m_pvData : NULL); +} +//---------------------------------------------------------------------------- +const SmallSet *TriangleMesh::GetEdges(int iV) const +{ + MVCIter pkV = m_kVMap.find(iV); + return (pkV != m_kVMap.end() ? &pkV->second.m_kESet : NULL); +} +//---------------------------------------------------------------------------- +const SmallSet *TriangleMesh::GetTriangles(int iV) + const +{ + MVCIter pkV = m_kVMap.find(iV); + return (pkV != m_kVMap.end() ? &pkV->second.m_kTSet : NULL); +} +//---------------------------------------------------------------------------- +void TriangleMesh::GetEdges(set &rkESet) const +{ + rkESet.clear(); + for (MECIter pkE = m_kEMap.begin(); pkE != m_kEMap.end(); pkE++) + rkESet.insert(pkE->first); +} +//---------------------------------------------------------------------------- +void *TriangleMesh::GetData(int iV0, int iV1) +{ + MEIter pkE = m_kEMap.find(Edge(iV0, iV1)); + return (pkE != m_kEMap.end() ? pkE->second.m_pvData : NULL); +} +//---------------------------------------------------------------------------- +void *TriangleMesh::GetData(const Edge &rkE) +{ + return GetData(rkE.m_aiV[0], rkE.m_aiV[1]); +} +//---------------------------------------------------------------------------- +const SmallSet *TriangleMesh::GetTriangles(int iV0, + int iV1) const +{ + MECIter pkE = m_kEMap.find(Edge(iV0, iV1)); + return (pkE != m_kEMap.end() ? &pkE->second.m_kTSet : NULL); +} +//---------------------------------------------------------------------------- +void TriangleMesh::GetTriangles(set &rkTSet) const +{ + rkTSet.clear(); + for (MTCIter pkT = m_kTMap.begin(); pkT != m_kTMap.end(); pkT++) + rkTSet.insert(pkT->first); +} +//---------------------------------------------------------------------------- +void *TriangleMesh::GetData(int iV0, int iV1, int iV2) +{ + MTIter pkT = m_kTMap.find(Triangle(iV0, iV1, iV2)); + return (pkT != m_kTMap.end() ? pkT->second.m_pvData : NULL); +} +//---------------------------------------------------------------------------- +void *TriangleMesh::GetData(const Triangle &rkT) +{ + return GetData(rkT.m_aiV[0], rkT.m_aiV[1], rkT.m_aiV[2]); +} +//---------------------------------------------------------------------------- +bool TriangleMesh::IsManifold() const +{ + for (MECIter pkE = m_kEMap.begin(); pkE != m_kEMap.end(); pkE++) + { + if (pkE->second.m_kTSet.GetSize() > 2) + return false; + } + return true; +} +//---------------------------------------------------------------------------- +bool TriangleMesh::IsClosed() const +{ + for (MECIter pkE = m_kEMap.begin(); pkE != m_kEMap.end(); pkE++) + { + if (pkE->second.m_kTSet.GetSize() != 2) + return false; + } + return true; +} +//---------------------------------------------------------------------------- +bool TriangleMesh::IsConnected() const +{ + // Do a depth-first search of the mesh. It is connected if and only if + // all of the triangles are visited on a single search. + + int iTSize = m_kTMap.size(); + if (iTSize == 0) + return true; + + // for marking visited triangles during the traversal + map kVisitedMap; + MTCIter pkT; + for (pkT = m_kTMap.begin(); pkT != m_kTMap.end(); pkT++) + kVisitedMap.insert(make_pair(pkT->first, false)); + + // start the traversal at any triangle in the mesh + stack kStack; + kStack.push(m_kTMap.begin()->first); + map::iterator pkVI = + kVisitedMap.find(m_kTMap.begin()->first); + assert(pkVI != kVisitedMap.end()); + pkVI->second = true; + iTSize--; + + while (!kStack.empty()) + { + // start at the current triangle + Triangle kT = kStack.top(); + kStack.pop(); + + for (int i = 0; i < 3; i++) + { + // get an edge of the current triangle + MECIter pkE = m_kEMap.find(Edge(kT.m_aiV[i], kT.m_aiV[(i + 1) % 3])); + + // visit each adjacent triangle + const SmallSet &rkTSet = pkE->second.m_kTSet; + for (int j = 0; j < rkTSet.GetSize(); j++) + { + const Triangle &rkTAdj = rkTSet[j]; + pkVI = kVisitedMap.find(rkTAdj); + assert(pkVI != kVisitedMap.end()); + if (pkVI->second == false) + { + // this adjacent triangle not yet visited + kStack.push(rkTAdj); + pkVI->second = true; + iTSize--; + } + } + } + } + + return iTSize == 0; +} +//---------------------------------------------------------------------------- +void TriangleMesh::GetComponents(vector &rkComponents) +{ + // Do a depth-first search of the mesh to find connected components. + int iTSize = m_kTMap.size(); + if (iTSize == 0) + return; + + // for marking visited triangles during the traversal + map kVisitedMap; + MTCIter pkT; + for (pkT = m_kTMap.begin(); pkT != m_kTMap.end(); pkT++) + kVisitedMap.insert(make_pair(pkT->first, false)); + + while (iTSize > 0) + { + // find an unvisited triangle in the mesh + stack kStack; + map::iterator pkVI = kVisitedMap.begin(); + while (pkVI != kVisitedMap.end()) + { + if (pkVI->second == false) + { + kStack.push(pkVI->first); + pkVI->second = true; + iTSize--; + break; + } + pkVI++; + } + + // traverse the connected component of the starting triangle + TriangleMesh *pkComponent = Create(); + while (!kStack.empty()) + { + // start at the current triangle + Triangle kT = kStack.top(); + kStack.pop(); + pkComponent->InsertTriangle(kT); + + for (int i = 0; i < 3; i++) + { + // get an edge of the current triangle + Edge kE(kT.m_aiV[i], kT.m_aiV[(i + 1) % 3]); + MECIter pkE = m_kEMap.find(kE); + + // visit each adjacent triangle + const SmallSet &rkTSet = pkE->second.m_kTSet; + for (int j = 0; j < rkTSet.GetSize(); j++) + { + const Triangle &rkTAdj = rkTSet[i]; + pkVI = kVisitedMap.find(rkTAdj); + assert(pkVI != kVisitedMap.end()); + if (pkVI->second == false) + { + // this adjacent triangle not yet visited + kStack.push(rkTAdj); + pkVI->second = true; + iTSize--; + } + } + } + } + rkComponents.push_back(pkComponent); + } +} +//---------------------------------------------------------------------------- +void TriangleMesh::GetComponents(vector &rkIndex, int *&raiConnect) +{ + rkIndex.clear(); + + // Do a depth-first search of the mesh to find connected components. + int iTSize = m_kTMap.size(); + if (iTSize == 0) + { + raiConnect = NULL; + return; + } + + int iIQuantity = 3 * iTSize; + int iIndex = 0; + raiConnect = new int[iIQuantity]; + + // for marking visited triangles during the traversal + map kVisitedMap; + MTCIter pkT; + for (pkT = m_kTMap.begin(); pkT != m_kTMap.end(); pkT++) + kVisitedMap.insert(make_pair(pkT->first, false)); + + while (iTSize > 0) + { + // find an unvisited triangle in the mesh + stack kStack; + map::iterator pkVI = kVisitedMap.begin(); + while (pkVI != kVisitedMap.end()) + { + if (pkVI->second == false) + { + kStack.push(pkVI->first); + pkVI->second = true; + iTSize--; + break; + } + pkVI++; + } + + // traverse the connected component of the starting triangle + TriangleMesh *pkComponent = Create(); + while (!kStack.empty()) + { + // start at the current triangle + Triangle kT = kStack.top(); + kStack.pop(); + pkComponent->InsertTriangle(kT); + + for (int i = 0; i < 3; i++) + { + // get an edge of the current triangle + Edge kE(kT.m_aiV[i], kT.m_aiV[(i + 1) % 3]); + MECIter pkE = m_kEMap.find(kE); + + // visit each adjacent triangle + const SmallSet &rkTSet = pkE->second.m_kTSet; + for (int j = 0; j < rkTSet.GetSize(); j++) + { + const Triangle &rkTAdj = rkTSet[i]; + pkVI = kVisitedMap.find(rkTAdj); + assert(pkVI != kVisitedMap.end()); + if (pkVI->second == false) + { + // this adjacent triangle not yet visited + kStack.push(rkTAdj); + pkVI->second = true; + iTSize--; + } + } + } + } + + // store the connectivity information for this component + set kTSet; + pkComponent->GetTriangles(kTSet); + delete pkComponent; + + rkIndex.push_back(iIndex); + set::iterator pkTIter; + for (pkTIter = kTSet.begin(); pkTIter != kTSet.end(); pkTIter++) + { + assert(iIndex + 3 <= iIQuantity); + const Triangle &rkT = *pkTIter; + raiConnect[iIndex++] = rkT.m_aiV[0]; + raiConnect[iIndex++] = rkT.m_aiV[1]; + raiConnect[iIndex++] = rkT.m_aiV[2]; + } + } + + rkIndex.push_back(iIQuantity); +} +//---------------------------------------------------------------------------- +void TriangleMesh::RemoveComponent(int &riIQuantity, int *aiConnect) +{ + // Do a depth-first search of the mesh to find connected components. The + // input array is assumed to be large enough to hold the component (see + // the comments in MgcTriangleMesh.h for RemoveComponent). + riIQuantity = 0; + + int iTSize = m_kTMap.size(); + if (iTSize == 0) + return; + + // Find the connected component containing the first triangle in the mesh. + // A set is used instead of a stack to avoid having a large-memory + // 'visited' map. + set kVisited; + kVisited.insert(m_kTMap.begin()->first); + + // traverse the connected component + while (!kVisited.empty()) + { + // start at the current triangle + Triangle kT = *kVisited.begin(); + + // add adjacent triangles to the set for recursive processing + for (int i = 0; i < 3; i++) + { + // get an edge of the current triangle + Edge kE(kT.m_aiV[i], kT.m_aiV[(i + 1) % 3]); + MECIter pkE = m_kEMap.find(kE); + assert(pkE != m_kEMap.end()); + + // visit each adjacent triangle + const SmallSet &rkTSet = pkE->second.m_kTSet; + for (int j = 0; j < rkTSet.GetSize(); j++) + { + Triangle kTAdj = rkTSet[j]; + if (kTAdj != kT) + kVisited.insert(kTAdj); + } + } + + // add triangle to connectivity array + aiConnect[riIQuantity++] = kT.m_aiV[0]; + aiConnect[riIQuantity++] = kT.m_aiV[1]; + aiConnect[riIQuantity++] = kT.m_aiV[2]; + + // remove the current triangle (visited, no longer needed) + kVisited.erase(kT); + RemoveTriangle(kT); + } +} +//---------------------------------------------------------------------------- +bool TriangleMesh::GetConsistentComponents( + vector &rkComponents) +{ + if (!IsManifold()) + return false; + + // Do a depth-first search of the mesh to find connected components. + int iTSize = m_kTMap.size(); + if (iTSize == 0) + return true; + + // for marking visited triangles during the traversal + map kVisitedMap; + MTCIter pkT; + for (pkT = m_kTMap.begin(); pkT != m_kTMap.end(); pkT++) + kVisitedMap.insert(make_pair(pkT->first, false)); + + while (iTSize > 0) + { + // Find an unvisited triangle in the mesh. Any triangle pushed onto + // the stack is considered to have a consistent ordering. + stack kStack; + map::iterator pkVI = kVisitedMap.begin(); + while (pkVI != kVisitedMap.end()) + { + if (pkVI->second == false) + { + kStack.push(pkVI->first); + pkVI->second = true; + iTSize--; + break; + } + pkVI++; + } + + // traverse the connected component of the starting triangle + TriangleMesh *pkComponent = Create(); + while (!kStack.empty()) + { + // start at the current triangle + Triangle kT = kStack.top(); + kStack.pop(); + pkComponent->InsertTriangle(kT); + + for (int i = 0; i < 3; i++) + { + // get an edge of the current triangle + int iV0 = kT.m_aiV[i], iV1 = kT.m_aiV[(i + 1) % 3], iV2; + Edge kE(iV0, iV1); + MECIter pkE = m_kEMap.find(kE); + + int iSize = pkE->second.m_kTSet.GetSize(); + assert(iSize == 1 || iSize == 2); // mesh is manifold + const Triangle *pkTAdj = &pkE->second.m_kTSet[0]; + if (iSize == 2) + { + // get the adjacent triangle to the current one + if (*pkTAdj == kT) + pkTAdj = &pkE->second.m_kTSet[1]; + + pkVI = kVisitedMap.find(*pkTAdj); + assert(pkVI != kVisitedMap.end()); + if (pkVI->second == false) + { + // adjacent triangle not yet visited + if ((pkTAdj->m_aiV[0] == iV0 && pkTAdj->m_aiV[1] == iV1) || (pkTAdj->m_aiV[1] == iV0 && pkTAdj->m_aiV[2] == iV1) || (pkTAdj->m_aiV[2] == iV0 && pkTAdj->m_aiV[0] == iV1)) + { + // adjacent triangle must be reordered + iV0 = pkTAdj->m_aiV[0]; + iV1 = pkTAdj->m_aiV[1]; + iV2 = pkTAdj->m_aiV[2]; + kVisitedMap.erase(*pkTAdj); + RemoveTriangle(iV0, iV1, iV2); + InsertTriangle(iV1, iV0, iV2); + kVisitedMap.insert(make_pair(Triangle(iV1, iV0, + iV2), + false)); + + // refresh the iterators since maps changed + pkE = m_kEMap.find(kE); + pkTAdj = &pkE->second.m_kTSet[0]; + if (*pkTAdj == kT) + pkTAdj = &pkE->second.m_kTSet[1]; + pkVI = kVisitedMap.find(*pkTAdj); + assert(pkVI != kVisitedMap.end()); + } + + kStack.push(*pkTAdj); + pkVI->second = true; + iTSize--; + } + } + } + } + rkComponents.push_back(pkComponent); + } + + return true; +} +//---------------------------------------------------------------------------- +TriangleMesh *TriangleMesh::GetReversedOrderMesh() const +{ + TriangleMesh *pkReversed = Create(); + + for (MTCIter pkT = m_kTMap.begin(); pkT != m_kTMap.end(); pkT++) + { + pkReversed->InsertTriangle(pkT->first.m_aiV[0], pkT->first.m_aiV[2], + pkT->first.m_aiV[1]); + } + + return pkReversed; +} +//---------------------------------------------------------------------------- +void TriangleMesh::GetStatistics(int &riVQuantity, int &riEQuantity, + int &riTQuantity, Real &rfAverageEdgesPerVertex, + Real &rfAverageTrianglesPerVertex, Real &rfAverageTrianglesPerEdge, + int &riMaximumEdgesPerVertex, int &riMaximumTrianglesPerVertex, + int &riMaximumTrianglesPerEdge) +{ + riVQuantity = m_kVMap.size(); + riEQuantity = m_kEMap.size(); + riTQuantity = m_kTMap.size(); + + int iESumForV = 0; + int iTSumForV = 0; + riMaximumEdgesPerVertex = 0; + riMaximumTrianglesPerVertex = 0; + + int iESize, iTSize; + + for (MVCIter pkV = m_kVMap.begin(); pkV != m_kVMap.end(); pkV++) + { + iESize = pkV->second.m_kESet.GetSize(); + iTSize = pkV->second.m_kTSet.GetSize(); + iESumForV += iESize; + iTSumForV += iTSize; + if (iESize > riMaximumEdgesPerVertex) + riMaximumEdgesPerVertex = iESize; + if (iTSize > riMaximumTrianglesPerVertex) + riMaximumTrianglesPerVertex = iTSize; + } + + int iTSumForE = 0; + riMaximumTrianglesPerEdge = 0; + for (MECIter pkE = m_kEMap.begin(); pkE != m_kEMap.end(); pkE++) + { + iTSize = pkE->second.m_kTSet.GetSize(); + iTSumForE += iTSize; + if (iTSize > riMaximumTrianglesPerEdge) + riMaximumTrianglesPerEdge = iTSize; + } + + rfAverageEdgesPerVertex = ((Real)iESumForV) / riVQuantity; + rfAverageTrianglesPerVertex = ((Real)iTSumForV) / riVQuantity; + rfAverageTrianglesPerEdge = ((Real)iTSumForE) / riEQuantity; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcTriangleMesh.h b/src/editors/FreeMagic/MgcTriangleMesh.h new file mode 100644 index 00000000000..49c9faaaab6 --- /dev/null +++ b/src/editors/FreeMagic/MgcTriangleMesh.h @@ -0,0 +1,254 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCTRIANGLEMESH_H +#define MGCTRIANGLEMESH_H + +#include "MagicFMLibType.h" +#include "MgcMath.h" +#include "MgcSmallSet.h" +#include +#include +#include + +namespace Mgc +{ + + class MAGICFM TriangleMesh + { + public: + // vertex is + // edge is where v0 = min(v0,v1) + // triangle is where v0 = min(v0,v1,v2) + + class Edge + { + public: + Edge(); + Edge(int iV0, int iV1); + bool operator<(const Edge &rkE) const; + bool operator==(const Edge &rkE) const; + bool operator!=(const Edge &rkE) const; + + int m_aiV[2]; + }; + + class Triangle + { + public: + Triangle(); + Triangle(int iV0, int iV1, int iV2); + bool operator<(const Triangle &rkT) const; + bool operator==(const Triangle &rkT) const; + bool operator!=(const Triangle &rkT) const; + + int m_aiV[3]; + }; + + class VertexAttribute + { + public: + VertexAttribute() + : m_kESet(8, 8), + m_kTSet(8, 8) + { + m_pvData = NULL; + } + + void *m_pvData; + SmallSet m_kESet; + SmallSet m_kTSet; + }; + + class EdgeAttribute + { + public: + EdgeAttribute() + : m_kTSet(2, 2) + { + m_pvData = NULL; + } + + void *m_pvData; + SmallSet m_kTSet; + }; + + class TriangleAttribute + { + public: + TriangleAttribute() + { + m_pvData = NULL; + } + + void *m_pvData; + }; + + // for readability of the code + typedef std::map VMap; + typedef VMap::iterator MVIter; + typedef VMap::const_iterator MVCIter; + typedef std::map EMap; + typedef EMap::iterator MEIter; + typedef EMap::const_iterator MECIter; + typedef std::map TMap; + typedef TMap::iterator MTIter; + typedef TMap::const_iterator MTCIter; + + // construction and destruction + TriangleMesh(); + virtual ~TriangleMesh(); + + // accessors for sizes + int GetVertexQuantity() const; + int GetEdgeQuantity() const; + int GetTriangleQuantity() const; + + // Used for operations that create new meshes from the current one. This + // allows derived class construction within the base class operations. + virtual TriangleMesh *Create() const; + + // Callbacks that are executed when vertices, edges, or triangles are + // inserted or removed during triangle insertion, triangle removal, or + // edge collapsing. The default behavior for the creation is to return + // NULL pointers. A derived class may override the creation and return + // data to be attached to the specific mesh component. The default + // behavior for the destruction is to do nothing. A derived class may + // override the destruction and handle the data that was detached from + // the specific mesh component before its destruction. + virtual void OnVertexInsert(int iV, bool bCreate, void *&rpvData); + virtual void OnVertexRemove(int iV, bool bDestroy, void *pvData); + virtual void OnEdgeInsert(const Edge &rkE, bool bCreate, void *&rpvData); + virtual void OnEdgeRemove(const Edge &rkE, bool bDestroy, void *pvData); + virtual void OnTriangleInsert(const Triangle &rkT, bool bCreate, + void *&rpvData); + virtual void OnTriangleRemove(const Triangle &rkT, bool bDestroy, + void *pvData); + + // Insert and remove triangles. The functions are virtual in case a + // derived class wants to implement pre- and post-operation semantics. + virtual void InsertTriangle(int iV0, int iV1, int iV2); + virtual void InsertTriangle(const Triangle &rkT); + virtual void RemoveTriangle(int iV0, int iV1, int iV2); + virtual void RemoveTriangle(const Triangle &rkT); + + // This should be called before Mesh destruction if a derived class has + // allocated vertex, edge, or triangle data and attached it to the mesh + // components. Since the creation and destruction callbacks are virtual, + // any insert/remove operations in the base Mesh destructor will only + // call the base virtual callbacks, not any derived-class ones. An + // alternative to calling this is that the derived class maintain enough + // information to know which data objects to destroy during its own + // destructor call. + virtual void RemoveAllTriangles(); + + // write the mesh to an ASCII file + void Print(const char *acFilename) const; + + // vertex attributes + const VMap &GetVertexMap() const; + void GetVertices(std::set &rkVSet) const; + void *GetData(int iV); + const SmallSet *GetEdges(int iV) const; + const SmallSet *GetTriangles(int iV) const; + + // edge attributes + const EMap &GetEdgeMap() const; + void GetEdges(std::set &rkESet) const; + void *GetData(int iV0, int iV1); + void *GetData(const Edge &rkE); + const SmallSet *GetTriangles(int iV0, int iV1) const; + + // triangle attributes + const TMap &GetTriangleMap() const; + void GetTriangles(std::set &rkTSet) const; + void *GetData(int iV0, int iV1, int iV2); + void *GetData(const Triangle &rkT); + + // The mesh is manifold if each edge has at most two adjacent triangles. + // It is possible that the mesh has multiple connected components. + bool IsManifold() const; + + // The mesh is closed if each edge has exactly two adjacent triangles. + // It is possible that the mesh has multiple connected components. + bool IsClosed() const; + + // The mesh is connected if each triangle can be reached from any other + // triangle by a traversal. + bool IsConnected() const; + + // Extract the connected components from the mesh. For large data sets, + // the array of TriangleMesh can use a lot of memory. Instead use the + // second form that just stores a sorted connectivity array. Let N be + // the number of components. The value Index[i] indicates the starting + // index for component i with 0 <= i < N, so it is always the case that + // Index[0] = 0. The value Index[N] is the total number of indices in + // the raiConnect array. The quantity of indices for component i is + // Q(i) = Index[i+1]-Index[i] for 0 <= i < N. The application is + // responsible for deleting raiConnect. + void GetComponents(std::vector &rkComponents); + void GetComponents(std::vector &rkIndex, int *&raiConnect); + + // Extract a connected component from the mesh and remove all the + // triangles of the component from the mesh. This is useful for computing + // the components in a very large mesh that uses a lot of memory. The + // intention is that the function is called until all components are + // found. The typical code is + // + // TriangleMesh kMesh = ; + // int iITotalQuantity = 3*kMesh.GetTriangleQuantity(); + // int* aiConnect = new int[iITotalQuantity]; + // for (int iIQuantity = 0; iIQuantity < iITotalQuantity; /**/ ) + // { + // int iCurrentIQuantity; + // int* aiCurrentConnect = aiConnect + iIQuantity; + // kMesh.RemoveComponent(iCurrentIQuantity,aiCurrentConnect); + // iIQuantity += iCurrentIQuantity; + // } + void RemoveComponent(int &riIQuantity, int *aiConnect); + + // Extract the connected components from the mesh, but each component has + // a consistent ordering across all triangles of that component. The + // mesh must be manifold. The return value is 'true' if and only if the + // mesh is manifold. If the mesh has multiple components, each component + // will have a consistent ordering. However, the mesh knows nothing about + // the mesh geometry, so it is possible that ordering across components is + // not consistent. For example, if the mesh has two disjoint closed + // manifold components, one of them could have an ordering that implies + // outward pointing normals and the other inward pointing normals. + // + // NOTE. It is possible to create a nonorientable mesh such as a Moebius + // strip. In this case, GetConsistentComponents will return connected + // components, but in fact the triangles will not (and can not) be + // consistently ordered. + bool GetConsistentComponents(std::vector &rkComponents); + + // Reverse the ordering of all triangles in the mesh. + TriangleMesh *GetReversedOrderMesh() const; + + // statistics + void GetStatistics(int &riVQuantity, int &riEQuantity, int &riTQuantity, + Real &rfAverageEdgesPerVertex, Real &rfAverageTrianglesPerVertex, + Real &rfAverageTrianglesPerEdge, int &riMaximumEdgesPerVertex, + int &riMaximumTrianglesPerVertex, int &riMaximumTrianglesPerEdge); + + protected: + std::map m_kVMap; + std::map m_kEMap; + std::map m_kTMap; + }; + +#include "MgcTriangleMesh.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcTriangleMesh.inl b/src/editors/FreeMagic/MgcTriangleMesh.inl new file mode 100644 index 00000000000..4e8e3338469 --- /dev/null +++ b/src/editors/FreeMagic/MgcTriangleMesh.inl @@ -0,0 +1,192 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline int TriangleMesh::GetVertexQuantity() const +{ + return m_kVMap.size(); +} +//---------------------------------------------------------------------------- +inline int TriangleMesh::GetEdgeQuantity() const +{ + return m_kEMap.size(); +} +//---------------------------------------------------------------------------- +inline int TriangleMesh::GetTriangleQuantity() const +{ + return m_kTMap.size(); +} +//---------------------------------------------------------------------------- +inline TriangleMesh *TriangleMesh::Create() const +{ + return new TriangleMesh; +} +//---------------------------------------------------------------------------- +inline void TriangleMesh::OnVertexInsert(int, bool, void *&) +{ +} +//---------------------------------------------------------------------------- +inline void TriangleMesh::OnVertexRemove(int, bool, void *) +{ +} +//---------------------------------------------------------------------------- +inline void TriangleMesh::OnEdgeInsert(const Edge &, bool, void *&) +{ +} +//---------------------------------------------------------------------------- +inline void TriangleMesh::OnEdgeRemove(const Edge &, bool, void *) +{ +} +//---------------------------------------------------------------------------- +inline void TriangleMesh::OnTriangleInsert(const Triangle &, bool, void *&) +{ +} +//---------------------------------------------------------------------------- +inline void TriangleMesh::OnTriangleRemove(const Triangle &, bool, void *) +{ +} +//---------------------------------------------------------------------------- +inline const TriangleMesh::VMap &TriangleMesh::GetVertexMap() const +{ + return m_kVMap; +} +//---------------------------------------------------------------------------- +inline const TriangleMesh::EMap &TriangleMesh::GetEdgeMap() const +{ + return m_kEMap; +} +//---------------------------------------------------------------------------- +inline const TriangleMesh::TMap &TriangleMesh::GetTriangleMap() const +{ + return m_kTMap; +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// TriangleMesh::Edge +//---------------------------------------------------------------------------- +inline TriangleMesh::Edge::Edge() +{ +} +//---------------------------------------------------------------------------- +inline TriangleMesh::Edge::Edge(int iV0, int iV1) +{ + if (iV0 < iV1) + { + // v0 is minimum + m_aiV[0] = iV0; + m_aiV[1] = iV1; + } + else + { + // v1 is minimum + m_aiV[0] = iV1; + m_aiV[1] = iV0; + } +} +//---------------------------------------------------------------------------- +inline bool TriangleMesh::Edge::operator<(const Edge &rkE) const +{ + if (m_aiV[1] < rkE.m_aiV[1]) + return true; + + if (m_aiV[1] == rkE.m_aiV[1]) + return m_aiV[0] < rkE.m_aiV[0]; + + return false; +} +//---------------------------------------------------------------------------- +inline bool TriangleMesh::Edge::operator==(const Edge &rkE) const +{ + return m_aiV[0] == rkE.m_aiV[0] && m_aiV[1] == rkE.m_aiV[1]; +} +//---------------------------------------------------------------------------- +inline bool TriangleMesh::Edge::operator!=(const Edge &rkE) const +{ + return !operator==(rkE); +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// TriangleMesh::Triangle +//---------------------------------------------------------------------------- +inline TriangleMesh::Triangle::Triangle() +{ +} +//---------------------------------------------------------------------------- +inline TriangleMesh::Triangle::Triangle(int iV0, int iV1, int iV2) +{ + if (iV0 < iV1) + { + if (iV0 < iV2) + { + // v0 is minimum + m_aiV[0] = iV0; + m_aiV[1] = iV1; + m_aiV[2] = iV2; + } + else + { + // v2 is minimum + m_aiV[0] = iV2; + m_aiV[1] = iV0; + m_aiV[2] = iV1; + } + } + else + { + if (iV1 < iV2) + { + // v1 is minimum + m_aiV[0] = iV1; + m_aiV[1] = iV2; + m_aiV[2] = iV0; + } + else + { + // v2 is minimum + m_aiV[0] = iV2; + m_aiV[1] = iV0; + m_aiV[2] = iV1; + } + } +} +//---------------------------------------------------------------------------- +inline bool TriangleMesh::Triangle::operator<(const Triangle &rkT) const +{ + if (m_aiV[2] < rkT.m_aiV[2]) + return true; + + if (m_aiV[2] == rkT.m_aiV[2]) + { + if (m_aiV[1] < rkT.m_aiV[1]) + return true; + + if (m_aiV[1] == rkT.m_aiV[1]) + return m_aiV[0] < rkT.m_aiV[0]; + } + + return false; +} +//---------------------------------------------------------------------------- +inline bool TriangleMesh::Triangle::operator==(const Triangle &rkT) const +{ + return (m_aiV[0] == rkT.m_aiV[0]) && + ((m_aiV[1] == rkT.m_aiV[1] && m_aiV[2] == rkT.m_aiV[2]) || + (m_aiV[1] == rkT.m_aiV[2] && m_aiV[2] == rkT.m_aiV[1])); +} +//---------------------------------------------------------------------------- +inline bool TriangleMesh::Triangle::operator!=(const Triangle &rkT) const +{ + return !operator==(rkT); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcVector2.cpp b/src/editors/FreeMagic/MgcVector2.cpp new file mode 100644 index 00000000000..208d209bc4f --- /dev/null +++ b/src/editors/FreeMagic/MgcVector2.cpp @@ -0,0 +1,304 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +///#include "stdafx.h" +#pragma hdrstop + +#include "MgcVector2.h" +using namespace Mgc; + +const Vector2 Vector2::ZERO(0.0f, 0.0f); +const Vector2 Vector2::UNIT_X(1.0f, 0.0f); +const Vector2 Vector2::UNIT_Y(0.0f, 1.0f); +Real Vector2::FUZZ = 0.0f; + +//---------------------------------------------------------------------------- +Vector2::Vector2(Real fX, Real fY) +{ + x = fX; + y = fY; +} +//---------------------------------------------------------------------------- +Vector2::Vector2(Real afCoordinate[2]) +{ + x = afCoordinate[0]; + y = afCoordinate[1]; +} +//---------------------------------------------------------------------------- +Vector2::Vector2(const Vector2 &rkVector) +{ + x = rkVector.x; + y = rkVector.y; +} +//---------------------------------------------------------------------------- +Vector2 &Vector2::operator=(const Vector2 &rkVector) +{ + x = rkVector.x; + y = rkVector.y; + return *this; +} +//---------------------------------------------------------------------------- +bool Vector2::operator==(const Vector2 &rkVector) const +{ + if (FUZZ == 0.0f) + return x == rkVector.x && y == rkVector.y; + else + return Math::FAbs(x - rkVector.x) <= FUZZ && Math::FAbs(y - rkVector.y) <= FUZZ; +} +//---------------------------------------------------------------------------- +bool Vector2::operator!=(const Vector2 &rkVector) const +{ + if (FUZZ == 0.0f) + return x != rkVector.x || y != rkVector.y; + else + return Math::FAbs(x - rkVector.x) > FUZZ || Math::FAbs(y - rkVector.y) > FUZZ; +} +//---------------------------------------------------------------------------- +bool Vector2::operator<(const Vector2 &rkVector) const +{ + Real fXTmp = rkVector.x, fYTmp = rkVector.y; + if (FUZZ > 0.0f) + { + if (Math::FAbs(x - fXTmp) <= FUZZ) + fXTmp = x; + if (Math::FAbs(y - fYTmp) <= FUZZ) + fYTmp = y; + } + + // compare y values + unsigned int uiTest0 = *(unsigned int *)&y; + unsigned int uiTest1 = *(unsigned int *)&fYTmp; + if (uiTest0 < uiTest1) + return true; + if (uiTest0 > uiTest1) + return false; + + // compare x values + uiTest0 = *(unsigned int *)&x; + uiTest1 = *(unsigned int *)&fXTmp; + return uiTest0 < uiTest1; +} +//---------------------------------------------------------------------------- +bool Vector2::operator<=(const Vector2 &rkVector) const +{ + Real fXTmp = rkVector.x, fYTmp = rkVector.y; + if (FUZZ > 0.0f) + { + if (Math::FAbs(x - fXTmp) <= FUZZ) + fXTmp = x; + if (Math::FAbs(y - fYTmp) <= FUZZ) + fYTmp = y; + } + + // compare y values + unsigned int uiTest0 = *(unsigned int *)&y; + unsigned int uiTest1 = *(unsigned int *)&fYTmp; + if (uiTest0 < uiTest1) + return true; + if (uiTest0 > uiTest1) + return false; + + // compare x values + uiTest0 = *(unsigned int *)&x; + uiTest1 = *(unsigned int *)&fXTmp; + return uiTest0 <= uiTest1; +} +//---------------------------------------------------------------------------- +bool Vector2::operator>(const Vector2 &rkVector) const +{ + Real fXTmp = rkVector.x, fYTmp = rkVector.y; + if (FUZZ > 0.0f) + { + if (Math::FAbs(x - fXTmp) <= FUZZ) + fXTmp = x; + if (Math::FAbs(y - fYTmp) <= FUZZ) + fYTmp = y; + } + + // compare y values + unsigned int uiTest0 = *(unsigned int *)&y; + unsigned int uiTest1 = *(unsigned int *)&fYTmp; + if (uiTest0 > uiTest1) + return true; + if (uiTest0 < uiTest1) + return false; + + // compare x values + uiTest0 = *(unsigned int *)&x; + uiTest1 = *(unsigned int *)&fXTmp; + return uiTest0 > uiTest1; +} +//---------------------------------------------------------------------------- +bool Vector2::operator>=(const Vector2 &rkVector) const +{ + Real fXTmp = rkVector.x, fYTmp = rkVector.y; + if (FUZZ > 0.0f) + { + if (Math::FAbs(x - fXTmp) <= FUZZ) + fXTmp = x; + if (Math::FAbs(y - fYTmp) <= FUZZ) + fYTmp = y; + } + + // compare y values + unsigned int uiTest0 = *(unsigned int *)&y; + unsigned int uiTest1 = *(unsigned int *)&fYTmp; + if (uiTest0 > uiTest1) + return true; + if (uiTest0 < uiTest1) + return false; + + // compare x values + uiTest0 = *(unsigned int *)&x; + uiTest1 = *(unsigned int *)&fXTmp; + return uiTest0 >= uiTest1; +} +//---------------------------------------------------------------------------- +Vector2 Vector2::operator+(const Vector2 &rkVector) const +{ + return Vector2(x + rkVector.x, y + rkVector.y); +} +//---------------------------------------------------------------------------- +Vector2 Vector2::operator-(const Vector2 &rkVector) const +{ + return Vector2(x - rkVector.x, y - rkVector.y); +} +//---------------------------------------------------------------------------- +Vector2 Vector2::operator*(Real fScalar) const +{ + return Vector2(fScalar * x, fScalar * y); +} +//---------------------------------------------------------------------------- +Vector2 Vector2::operator-() const +{ + return Vector2(-x, -y); +} +//---------------------------------------------------------------------------- +Vector2 Mgc::operator*(Real fScalar, const Vector2 &rkVector) +{ + return Vector2(fScalar * rkVector.x, fScalar * rkVector.y); +} +//---------------------------------------------------------------------------- +Vector2 Vector2::operator/(Real fScalar) const +{ + Vector2 kQuot; + + if (fScalar != 0.0f) + { + Real fInvScalar = 1.0f / fScalar; + kQuot.x = fInvScalar * x; + kQuot.y = fInvScalar * y; + return kQuot; + } + else + { + return Vector2(Math::MAX_REAL, Math::MAX_REAL); + } +} +//---------------------------------------------------------------------------- +Vector2 &Vector2::operator+=(const Vector2 &rkVector) +{ + x += rkVector.x; + y += rkVector.y; + return *this; +} +//---------------------------------------------------------------------------- +Vector2 &Vector2::operator-=(const Vector2 &rkVector) +{ + x -= rkVector.x; + y -= rkVector.y; + return *this; +} +//---------------------------------------------------------------------------- +Vector2 &Vector2::operator*=(Real fScalar) +{ + x *= fScalar; + y *= fScalar; + return *this; +} +//---------------------------------------------------------------------------- +Vector2 &Vector2::operator/=(Real fScalar) +{ + if (fScalar != 0.0f) + { + Real fInvScalar = 1.0f / fScalar; + x *= fInvScalar; + y *= fInvScalar; + } + else + { + x = Math::MAX_REAL; + y = Math::MAX_REAL; + } + + return *this; +} +//---------------------------------------------------------------------------- +Real Vector2::Dot(const Vector2 &rkVector) const +{ + return x * rkVector.x + y * rkVector.y; +} +//---------------------------------------------------------------------------- +Real Vector2::Length() const +{ + return Math::Sqrt(x * x + y * y); +} +//---------------------------------------------------------------------------- +Vector2 Vector2::Cross() const +{ + return Vector2(y, -x); +} +//---------------------------------------------------------------------------- +Vector2 Vector2::UnitCross() const +{ + Vector2 kCross(y, -x); + kCross.Unitize(); + return kCross; +} +//---------------------------------------------------------------------------- +Real Vector2::Unitize(Real fTolerance) +{ + Real fLength = Length(); + + if (fLength > fTolerance) + { + Real fInvLength = 1.0f / fLength; + x *= fInvLength; + y *= fInvLength; + } + else + { + fLength = 0.0f; + } + + return fLength; +} +//---------------------------------------------------------------------------- +void Vector2::Orthonormalize(Vector2 akVector[/*2*/]) +{ + // If the input vectors are v0 and v1, then the Gram-Schmidt + // orthonormalization produces vectors u0 and u1 as follows, + // + // u0 = v0/|v0| + // u1 = (v1-(u0*v1)u0)/|v1-(u0*v1)u0| + // + // where |A| indicates length of vector A and A*B indicates dot + // product of vectors A and B. + + // compute u0 + akVector[0].Unitize(); + + // compute u1 + Real fDot0 = akVector[0].Dot(akVector[1]); + akVector[1] -= fDot0 * akVector[0]; + akVector[1].Unitize(); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcVector2.h b/src/editors/FreeMagic/MgcVector2.h new file mode 100644 index 00000000000..2abfff95637 --- /dev/null +++ b/src/editors/FreeMagic/MgcVector2.h @@ -0,0 +1,90 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCVECTOR2_H +#define MGCVECTOR2_H + +#include "MgcMath.h" + +namespace Mgc +{ + + class MAGICFM Vector2 + { + public: + // construction + Vector2(); + Vector2(Real fX, Real fY); + Vector2(Real afCoordinate[2]); + Vector2(const Vector2 &rkVector); + + // coordinates + Real x, y; + + // access vector V as V[0] = V.x, V[1] = V.y + // + // WARNING. These member functions rely on + // (1) Vector2 not having virtual functions + // (2) the data packed in a 2*sizeof(Real) memory block + Real &operator[](int i) const; + operator Real *(); + + // assignment + Vector2 &operator=(const Vector2 &rkVector); + + // comparison (supports fuzzy arithmetic when FUZZ > 0) + bool operator==(const Vector2 &rkVector) const; + bool operator!=(const Vector2 &rkVector) const; + bool operator<(const Vector2 &rkVector) const; + bool operator<=(const Vector2 &rkVector) const; + bool operator>(const Vector2 &rkVector) const; + bool operator>=(const Vector2 &rkVector) const; + + // arithmetic operations + Vector2 operator+(const Vector2 &rkVector) const; + Vector2 operator-(const Vector2 &rkVector) const; + Vector2 operator*(Real fScalar) const; + Vector2 operator/(Real fScalar) const; + Vector2 operator-() const; + MAGICFM friend Vector2 operator*(Real fScalar, const Vector2 &rkVector); + + // arithmetic updates + Vector2 &operator+=(const Vector2 &rkVector); + Vector2 &operator-=(const Vector2 &rkVector); + Vector2 &operator*=(Real fScalar); + Vector2 &operator/=(Real fScalar); + + // vector operations + Real Length() const; + Real SquaredLength() const; + Real Dot(const Vector2 &rkVector) const; + Real Unitize(Real fTolerance = 1e-06f); + Vector2 Cross() const; // returns (y,-x) + Vector2 UnitCross() const; // returns (y,-x)/sqrt(x*x+y*y) + + // Gram-Schmidt orthonormalization. + static void Orthonormalize(Vector2 akVector[/*2*/]); + + // special points + static const Vector2 ZERO; + static const Vector2 UNIT_X; + static const Vector2 UNIT_Y; + + // fuzzy arithmetic (set FUZZ > 0 to enable) + static Real FUZZ; + }; + +#include "MgcVector2.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcVector2.inl b/src/editors/FreeMagic/MgcVector2.inl new file mode 100644 index 00000000000..6189aa839a2 --- /dev/null +++ b/src/editors/FreeMagic/MgcVector2.inl @@ -0,0 +1,34 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Vector2::Vector2() +{ + // For efficiency in construction of large arrays of vectors, the + // default constructor does not initialize the vector. +} +//---------------------------------------------------------------------------- +inline Real &Vector2::operator[](int i) const +{ + return ((Real *)this)[i]; +} +//---------------------------------------------------------------------------- +inline Vector2::operator Real *() +{ + return (Real *)this; +} +//---------------------------------------------------------------------------- +inline Real Vector2::SquaredLength() const +{ + return x * x + y * y; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcVector3.cpp b/src/editors/FreeMagic/MgcVector3.cpp new file mode 100644 index 00000000000..af3e6426d58 --- /dev/null +++ b/src/editors/FreeMagic/MgcVector3.cpp @@ -0,0 +1,407 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf +//#include "stdafx.h" +#pragma hdrstop + +#include "MgcVector3.h" +using namespace Mgc; + +const Vector3 Vector3::ZERO(0.0f, 0.0f, 0.0f); +const Vector3 Vector3::UNIT_X(1.0f, 0.0f, 0.0f); +const Vector3 Vector3::UNIT_Y(0.0f, 1.0f, 0.0f); +const Vector3 Vector3::UNIT_Z(0.0f, 0.0f, 1.0f); +Real Vector3::FUZZ = 0.0f; + +//---------------------------------------------------------------------------- +Vector3::Vector3(Real fX, Real fY, Real fZ) +{ + x = fX; + y = fY; + z = fZ; +} +//---------------------------------------------------------------------------- +Vector3::Vector3(Real afCoordinate[3]) +{ + x = afCoordinate[0]; + y = afCoordinate[1]; + z = afCoordinate[2]; +} +//---------------------------------------------------------------------------- +Vector3::Vector3(const Vector3 &rkVector) +{ + x = rkVector.x; + y = rkVector.y; + z = rkVector.z; +} +//---------------------------------------------------------------------------- +Vector3 &Vector3::operator=(const Vector3 &rkVector) +{ + x = rkVector.x; + y = rkVector.y; + z = rkVector.z; + return *this; +} +//---------------------------------------------------------------------------- +bool Vector3::operator==(const Vector3 &rkVector) const +{ + if (FUZZ == 0.0f) + { + return x == rkVector.x && y == rkVector.y && z == rkVector.z; + } + else + { + return Math::FAbs(x - rkVector.x) <= FUZZ && Math::FAbs(y - rkVector.y) <= FUZZ && Math::FAbs(z - rkVector.z) <= FUZZ; + } +} +//---------------------------------------------------------------------------- +bool Vector3::operator!=(const Vector3 &rkVector) const +{ + if (FUZZ == 0.0f) + { + return x != rkVector.x || y != rkVector.y || z != rkVector.z; + } + else + { + return Math::FAbs(x - rkVector.x) > FUZZ || Math::FAbs(y - rkVector.y) > FUZZ || Math::FAbs(z - rkVector.z) > FUZZ; + } +} +//---------------------------------------------------------------------------- +bool Vector3::operator<(const Vector3 &rkVector) const +{ + Real fXTmp = rkVector.x, fYTmp = rkVector.y, fZTmp = rkVector.z; + if (FUZZ > 0.0f) + { + if (Math::FAbs(x - fXTmp) <= FUZZ) + fXTmp = x; + if (Math::FAbs(y - fYTmp) <= FUZZ) + fYTmp = y; + if (Math::FAbs(z - fZTmp) <= FUZZ) + fZTmp = z; + } + + // compare z values + unsigned int uiTest0 = *(unsigned int *)&z; + unsigned int uiTest1 = *(unsigned int *)&fZTmp; + if (uiTest0 < uiTest1) + return true; + if (uiTest0 > uiTest1) + return false; + + // compare y values + uiTest0 = *(unsigned int *)&y; + uiTest1 = *(unsigned int *)&fYTmp; + if (uiTest0 < uiTest1) + return true; + if (uiTest0 > uiTest1) + return false; + + // compare x values + uiTest0 = *(unsigned int *)&x; + uiTest1 = *(unsigned int *)&fXTmp; + return uiTest0 < uiTest1; +} +//---------------------------------------------------------------------------- +bool Vector3::operator<=(const Vector3 &rkVector) const +{ + Real fXTmp = rkVector.x, fYTmp = rkVector.y, fZTmp = rkVector.z; + if (FUZZ > 0.0f) + { + if (Math::FAbs(x - fXTmp) <= FUZZ) + fXTmp = x; + if (Math::FAbs(y - fYTmp) <= FUZZ) + fYTmp = y; + if (Math::FAbs(z - fZTmp) <= FUZZ) + fZTmp = z; + } + + // compare z values + unsigned int uiTest0 = *(unsigned int *)&z; + unsigned int uiTest1 = *(unsigned int *)&fZTmp; + if (uiTest0 < uiTest1) + return true; + if (uiTest0 > uiTest1) + return false; + + // compare y values + uiTest0 = *(unsigned int *)&y; + uiTest1 = *(unsigned int *)&fYTmp; + if (uiTest0 < uiTest1) + return true; + if (uiTest0 > uiTest1) + return false; + + // compare x values + uiTest0 = *(unsigned int *)&x; + uiTest1 = *(unsigned int *)&fXTmp; + return uiTest0 <= uiTest1; +} +//---------------------------------------------------------------------------- +bool Vector3::operator>(const Vector3 &rkVector) const +{ + Real fXTmp = rkVector.x, fYTmp = rkVector.y, fZTmp = rkVector.z; + if (FUZZ > 0.0f) + { + if (Math::FAbs(x - fXTmp) <= FUZZ) + fXTmp = x; + if (Math::FAbs(y - fYTmp) <= FUZZ) + fYTmp = y; + if (Math::FAbs(z - fZTmp) <= FUZZ) + fZTmp = z; + } + + // compare z values + unsigned int uiTest0 = *(unsigned int *)&z; + unsigned int uiTest1 = *(unsigned int *)&fZTmp; + if (uiTest0 > uiTest1) + return true; + if (uiTest0 < uiTest1) + return false; + + // compare y values + uiTest0 = *(unsigned int *)&y; + uiTest1 = *(unsigned int *)&fYTmp; + if (uiTest0 > uiTest1) + return true; + if (uiTest0 < uiTest1) + return false; + + // compare x values + uiTest0 = *(unsigned int *)&x; + uiTest1 = *(unsigned int *)&fXTmp; + return uiTest0 > uiTest1; +} +//---------------------------------------------------------------------------- +bool Vector3::operator>=(const Vector3 &rkVector) const +{ + Real fXTmp = rkVector.x, fYTmp = rkVector.y, fZTmp = rkVector.z; + if (FUZZ > 0.0f) + { + if (Math::FAbs(x - fXTmp) <= FUZZ) + fXTmp = x; + if (Math::FAbs(y - fYTmp) <= FUZZ) + fYTmp = y; + if (Math::FAbs(z - fZTmp) <= FUZZ) + fZTmp = z; + } + + // compare z values + unsigned int uiTest0 = *(unsigned int *)&z; + unsigned int uiTest1 = *(unsigned int *)&fZTmp; + if (uiTest0 > uiTest1) + return true; + if (uiTest0 < uiTest1) + return false; + + // compare y values + uiTest0 = *(unsigned int *)&y; + uiTest1 = *(unsigned int *)&fYTmp; + if (uiTest0 > uiTest1) + return true; + if (uiTest0 < uiTest1) + return false; + + // compare x values + uiTest0 = *(unsigned int *)&x; + uiTest1 = *(unsigned int *)&fXTmp; + return uiTest0 >= uiTest1; +} +//---------------------------------------------------------------------------- +Vector3 Vector3::operator+(const Vector3 &rkVector) const +{ + return Vector3(x + rkVector.x, y + rkVector.y, z + rkVector.z); +} +//---------------------------------------------------------------------------- +Vector3 Vector3::operator-(const Vector3 &rkVector) const +{ + return Vector3(x - rkVector.x, y - rkVector.y, z - rkVector.z); +} +//---------------------------------------------------------------------------- +Vector3 Vector3::operator*(Real fScalar) const +{ + return Vector3(fScalar * x, fScalar * y, fScalar * z); +} +//---------------------------------------------------------------------------- +Vector3 Vector3::operator/(Real fScalar) const +{ + Vector3 kQuot; + + if (fScalar != 0.0f) + { + Real fInvScalar = 1.0f / fScalar; + kQuot.x = fInvScalar * x; + kQuot.y = fInvScalar * y; + kQuot.z = fInvScalar * z; + return kQuot; + } + else + { + return Vector3(Math::MAX_REAL, Math::MAX_REAL, Math::MAX_REAL); + } +} +//---------------------------------------------------------------------------- +Vector3 Vector3::operator-() const +{ + return Vector3(-x, -y, -z); +} +//---------------------------------------------------------------------------- +Vector3 Mgc::operator*(Real fScalar, const Vector3 &rkVector) +{ + return Vector3(fScalar * rkVector.x, fScalar * rkVector.y, + fScalar * rkVector.z); +} +//---------------------------------------------------------------------------- +Vector3 &Vector3::operator+=(const Vector3 &rkVector) +{ + x += rkVector.x; + y += rkVector.y; + z += rkVector.z; + return *this; +} +//---------------------------------------------------------------------------- +Vector3 &Vector3::operator-=(const Vector3 &rkVector) +{ + x -= rkVector.x; + y -= rkVector.y; + z -= rkVector.z; + return *this; +} +//---------------------------------------------------------------------------- +Vector3 &Vector3::operator*=(Real fScalar) +{ + x *= fScalar; + y *= fScalar; + z *= fScalar; + return *this; +} +//---------------------------------------------------------------------------- +Vector3 &Vector3::operator/=(Real fScalar) +{ + if (fScalar != 0.0f) + { + Real fInvScalar = 1.0f / fScalar; + x *= fInvScalar; + y *= fInvScalar; + z *= fInvScalar; + } + else + { + x = Math::MAX_REAL; + y = Math::MAX_REAL; + z = Math::MAX_REAL; + } + + return *this; +} +//---------------------------------------------------------------------------- +Real Vector3::SquaredLength() const +{ + return x * x + y * y + z * z; +} +//---------------------------------------------------------------------------- +Real Vector3::Length() const +{ + return Math::Sqrt(x * x + y * y + z * z); +} +//---------------------------------------------------------------------------- +Real Vector3::Dot(const Vector3 &rkVector) const +{ + return x * rkVector.x + y * rkVector.y + z * rkVector.z; +} +//---------------------------------------------------------------------------- +Vector3 Vector3::Cross(const Vector3 &rkVector) const +{ + return Vector3(y * rkVector.z - z * rkVector.y, z * rkVector.x - x * rkVector.z, + x * rkVector.y - y * rkVector.x); +} +//---------------------------------------------------------------------------- +Vector3 Vector3::UnitCross(const Vector3 &rkVector) const +{ + Vector3 kCross(y * rkVector.z - z * rkVector.y, z * rkVector.x - x * rkVector.z, + x * rkVector.y - y * rkVector.x); + kCross.Unitize(); + return kCross; +} +//---------------------------------------------------------------------------- +Real Vector3::Unitize(Real fTolerance) +{ + Real fLength = Length(); + + if (fLength > fTolerance) + { + Real fInvLength = 1.0f / fLength; + x *= fInvLength; + y *= fInvLength; + z *= fInvLength; + } + else + { + fLength = 0.0f; + } + + return fLength; +} +//---------------------------------------------------------------------------- +void Vector3::Orthonormalize(Vector3 akVector[/*3*/]) +{ + // If the input vectors are v0, v1, and v2, then the Gram-Schmidt + // orthonormalization produces vectors u0, u1, and u2 as follows, + // + // u0 = v0/|v0| + // u1 = (v1-(u0*v1)u0)/|v1-(u0*v1)u0| + // u2 = (v2-(u0*v2)u0-(u1*v2)u1)/|v2-(u0*v2)u0-(u1*v2)u1| + // + // where |A| indicates length of vector A and A*B indicates dot + // product of vectors A and B. + + // compute u0 + akVector[0].Unitize(); + + // compute u1 + Real fDot0 = akVector[0].Dot(akVector[1]); + akVector[1] -= fDot0 * akVector[0]; + akVector[1].Unitize(); + + // compute u2 + Real fDot1 = akVector[1].Dot(akVector[2]); + fDot0 = akVector[0].Dot(akVector[2]); + akVector[2] -= fDot0 * akVector[0] + fDot1 * akVector[1]; + akVector[2].Unitize(); +} +//---------------------------------------------------------------------------- +void Vector3::GenerateOrthonormalBasis(Vector3 &rkU, Vector3 &rkV, + Vector3 &rkW, bool bUnitLengthW) +{ + if (!bUnitLengthW) + rkW.Unitize(); + + Real fInvLength; + + if (Math::FAbs(rkW.x) >= Math::FAbs(rkW.y)) + { + // W.x or W.z is the largest magnitude component, swap them + fInvLength = Math::InvSqrt(rkW.x * rkW.x + rkW.z * rkW.z); + rkU.x = -rkW.z * fInvLength; + rkU.y = 0.0f; + rkU.z = +rkW.x * fInvLength; + } + else + { + // W.y or W.z is the largest magnitude component, swap them + fInvLength = Math::InvSqrt(rkW.y * rkW.y + rkW.z * rkW.z); + rkU.x = 0.0f; + rkU.y = +rkW.z * fInvLength; + rkU.z = -rkW.y * fInvLength; + } + + rkV = rkW.Cross(rkU); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/FreeMagic/MgcVector3.h b/src/editors/FreeMagic/MgcVector3.h new file mode 100644 index 00000000000..8daa4cf2893 --- /dev/null +++ b/src/editors/FreeMagic/MgcVector3.h @@ -0,0 +1,97 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +#ifndef MGCVECTOR3_H +#define MGCVECTOR3_H + +#include "MgcMath.h" + +namespace Mgc +{ + + class MAGICFM Vector3 + { + public: + // construction + Vector3(); + Vector3(Real fX, Real fY, Real fZ); + Vector3(Real afCoordinate[3]); + Vector3(const Vector3 &rkVector); + + // coordinates + Real x, y, z; + + // access vector V as V[0] = V.x, V[1] = V.y, V[2] = V.z + // + // WARNING. These member functions rely on + // (1) Vector3 not having virtual functions + // (2) the data packed in a 3*sizeof(Real) memory block + Real &operator[](int i) const; + operator Real *(); + + // assignment + Vector3 &operator=(const Vector3 &rkVector); + + // comparison (supports fuzzy arithmetic when FUZZ > 0) + bool operator==(const Vector3 &rkVector) const; + bool operator!=(const Vector3 &rkVector) const; + bool operator<(const Vector3 &rkVector) const; + bool operator<=(const Vector3 &rkVector) const; + bool operator>(const Vector3 &rkVector) const; + bool operator>=(const Vector3 &rkVector) const; + + // arithmetic operations + Vector3 operator+(const Vector3 &rkVector) const; + Vector3 operator-(const Vector3 &rkVector) const; + Vector3 operator*(Real fScalar) const; + Vector3 operator/(Real fScalar) const; + Vector3 operator-() const; + MAGICFM friend Vector3 operator*(Real fScalar, const Vector3 &rkVector); + + // arithmetic updates + Vector3 &operator+=(const Vector3 &rkVector); + Vector3 &operator-=(const Vector3 &rkVector); + Vector3 &operator*=(Real fScalar); + Vector3 &operator/=(Real fScalar); + + // vector operations + Real Length() const; + Real SquaredLength() const; + Real Dot(const Vector3 &rkVector) const; + Real Unitize(Real fTolerance = 1e-06f); + Vector3 Cross(const Vector3 &rkVector) const; + Vector3 UnitCross(const Vector3 &rkVector) const; + + // Gram-Schmidt orthonormalization. + static void Orthonormalize(Vector3 akVector[/*3*/]); + + // Input W must be initialize to a nonzero vector, output is {U,V,W} + // an orthonormal basis. A hint is provided about whether or not W + // is already unit length. + static void GenerateOrthonormalBasis(Vector3 &rkU, Vector3 &rkV, + Vector3 &rkW, bool bUnitLengthW = true); + + // special points + static const Vector3 ZERO; + static const Vector3 UNIT_X; + static const Vector3 UNIT_Y; + static const Vector3 UNIT_Z; + + // fuzzy arithmetic (set FUZZ > 0 to enable) + static Real FUZZ; + }; + +#include "MgcVector3.inl" + +} // namespace Mgc + +#endif diff --git a/src/editors/FreeMagic/MgcVector3.inl b/src/editors/FreeMagic/MgcVector3.inl new file mode 100644 index 00000000000..83f37092df2 --- /dev/null +++ b/src/editors/FreeMagic/MgcVector3.inl @@ -0,0 +1,29 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// Copyright (c) 2000-2002. All Rights Reserved +// +// Source code from Magic Software is supplied under the terms of a license +// agreement and may not be copied or disclosed except in accordance with the +// terms of that agreement. The various license agreements may be found at +// the Magic Software web site. This file is subject to the license +// +// FREE SOURCE CODE +// http://www.magic-software.com/License/free.pdf + +//---------------------------------------------------------------------------- +inline Vector3::Vector3() +{ + // For efficiency in construction of large arrays of vectors, the + // default constructor does not initialize the vector. +} +//---------------------------------------------------------------------------- +inline Real &Vector3::operator[](int i) const +{ + return ((Real *)this)[i]; +} +//---------------------------------------------------------------------------- +inline Vector3::operator Real *() +{ + return (Real *)this; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/LevelEditor/Builder/Builder.cpp b/src/editors/LevelEditor/Builder/Builder.cpp new file mode 100644 index 00000000000..f4b0da17c65 --- /dev/null +++ b/src/editors/LevelEditor/Builder/Builder.cpp @@ -0,0 +1,286 @@ +#include "stdafx.h" + +SceneBuilder Builder; + +ICF static void simple_hemi_callback(float x, float y, float z, float E, LPVOID P) +{ + SceneBuilder::BLVec *dst = (SceneBuilder::BLVec *)P; + SceneBuilder::SBuildLight T; + T.energy = E; + T.light.direction.set(x, y, z); + dst->push_back(T); +} + +SceneBuilder::SceneBuilder() +{ + m_iDefaultSectorNum = 0; + l_scene_stat = 0; + l_verts = 0; + l_faces = 0; + l_smgroups = 0; + l_vert_cnt = 0; + l_face_cnt = 0; + l_vert_it = 0; + l_face_it = 0; + object_for_render = 0; + m_save_as_object = false; +} + +SceneBuilder::~SceneBuilder() +{ +} + +//------------------------------------------------------------------------------ +#define CHECK_BREAK \ + if (UI->NeedAbort()) \ + break; +#define VERIFY_COMPILE(x, c1, c2) \ + CHECK_BREAK \ + if (!x) \ + { \ + error_text = make_string("ERROR: %s %s", c1, c2); \ + break; \ + } +//------------------------------------------------------------------------------ +BOOL SceneBuilder::Compile(bool b_selected_only) +{ + if (m_save_as_object) + { + EvictResource(); + GetBounding(); + CompileStatic(b_selected_only); + EvictResource(); + return TRUE; + } + + xr_string error_text = ""; + UI->ResetBreak(); + if (UI->ContainEState(esBuildLevel)) + return false; + ELog.Msg(mtInformation, "Building started..."); + + UI->BeginEState(esBuildLevel); + try + { + do + { + // check debug + bool bTestPortal = Scene->ObjCount(OBJCLASS_SECTOR) || Scene->ObjCount(OBJCLASS_PORTAL); + // validate scene + VERIFY_COMPILE(Scene->Validate(false, bTestPortal, true, true, true, true), "Validation failed.", "Invalid scene."); + // fill simple hemi + simple_hemi.clear(); + xrHemisphereBuild(1, 2.f, simple_hemi_callback, &simple_hemi); + // build + VERIFY_COMPILE(PreparePath(), "Failed to prepare level path", ""); + VERIFY_COMPILE(PrepareFolders(), "Failed to prepare level folders", ""); + VERIFY_COMPILE(EvictResource(), "Failed to evict resource", ""); + VERIFY_COMPILE(GetBounding(), "Failed to acquire level bounding volume", ""); + VERIFY_COMPILE(RenumerateSectors(), "Failed to renumerate sectors", ""); + VERIFY_COMPILE(CompileStatic(false), "Failed static remote build", ""); + VERIFY_COMPILE(EvictResource(), "Failed to evict resource", ""); + VERIFY_COMPILE(BuildLTX(), "Failed to build level description", ""); + VERIFY_COMPILE(BuildGame(), "Failed to build game", ""); + VERIFY_COMPILE(BuildSceneStat(), "Failed to build scene statistic", ""); + BuildHOMModel(); + BuildSOMModel(); + // build tools + SceneToolsMapPairIt _I = Scene->FirstTool(); + SceneToolsMapPairIt _E = Scene->LastTool(); + for (; _I != _E; ++_I) + { + if (_I->first != OBJCLASS_DUMMY) + { + if (_I->second->Valid()) + { + VERIFY_COMPILE(_I->second->Export(m_LevelPath), _I->second->ClassDesc(), "export failed."); + ELog.Msg(mtInformation, "Process %s - done.", _I->second->ClassDesc()); + } + else + { + ELog.Msg(mtError, "Process %s - failed.", _I->second->ClassDesc()); + } + } + } + Clear(); + } while (0); + + if (!error_text.empty()) + ELog.DlgMsg(mtError, error_text.c_str()); + else if (UI->NeedAbort()) + ELog.DlgMsg(mtInformation, "Building terminated."); + else + ELog.DlgMsg(mtInformation, "Building OK."); + } + catch (...) + { + ELog.DlgMsg(mtError, "Error has occured in builder routine. Editor aborted."); + abort(); + } + UI->EndEState(); + + return error_text.empty(); +} +//------------------------------------------------------------------------------ + +BOOL SceneBuilder::MakeGame() +{ + xr_string error_text = ""; + UI->ResetBreak(); + if (UI->ContainEState(esBuildLevel)) + return false; + ELog.Msg(mtInformation, "Making started..."); + + UI->BeginEState(esBuildLevel); + try + { + do + { + // clear error + Tools->ClearDebugDraw(); + // validate scene + VERIFY_COMPILE(Scene->Validate(false, false, false, false, false, false), "Validation failed.", "Invalid scene."); + // build + VERIFY_COMPILE(PreparePath(), "Failed to prepare level path.", ""); + VERIFY_COMPILE(GetBounding(), "Failed to acquire level bounding volume.", ""); + VERIFY_COMPILE(RenumerateSectors(), "Failed to renumerate sectors", ""); + VERIFY_COMPILE(BuildLTX(), "Failed to build level description.", ""); + VERIFY_COMPILE(BuildGame(), "Failed to build game.", ""); + } while (0); + + if (!error_text.empty()) + ELog.DlgMsg(mtError, error_text.c_str()); + else if (UI->NeedAbort()) + ELog.DlgMsg(mtInformation, "Making terminated."); + else + ELog.DlgMsg(mtInformation, "Making finished."); + } + catch (...) + { + ELog.DlgMsg(mtError, "Error has occured in builder routine. Editor aborted."); + abort(); + } + UI->EndEState(); + + return error_text.empty(); +} +//------------------------------------------------------------------------------ + +BOOL SceneBuilder::MakeAIMap() +{ + xr_string error_text; + do + { + VERIFY_COMPILE(PreparePath(), "Failed to prepare level path.", ""); + VERIFY_COMPILE(BuildAIMap(), "Failed to build AI-Map.", ""); + } while (0); + if (!error_text.empty()) + ELog.DlgMsg(mtError, error_text.c_str()); + else if (UI->NeedAbort()) + ELog.DlgMsg(mtInformation, "Building terminated."); + else + ELog.DlgMsg(mtInformation, "AI-Map succesfully exported."); + + return error_text.empty(); +} +//------------------------------------------------------------------------------ + +BOOL SceneBuilder::MakeDetails() +{ + xr_string error_text; + do + { + VERIFY_COMPILE(PreparePath(), "Failed to prepare level path.", ""); + // save details + VERIFY_COMPILE(Scene->GetTool(OBJCLASS_DO)->Export(m_LevelPath), "Export failed.", ""); + } while (0); + if (!error_text.empty()) + ELog.DlgMsg(mtError, error_text.c_str()); + else if (UI->NeedAbort()) + ELog.DlgMsg(mtInformation, "Building terminated."); + else + ELog.DlgMsg(mtInformation, "Details succesfully exported."); + + return error_text.empty(); +} +//------------------------------------------------------------------------------ + +BOOL SceneBuilder::MakeHOM() +{ + xr_string error_text = ""; + UI->ResetBreak(); + if (UI->ContainEState(esBuildLevel)) + return false; + ELog.Msg(mtInformation, "Making started..."); + + UI->BeginEState(esBuildLevel); + try + { + do + { + // build + VERIFY_COMPILE(PreparePath(), "Failed to prepare level path.", ""); + VERIFY_COMPILE(BuildHOMModel(), "Failed to build HOM model.", ""); + } while (0); + + if (!error_text.empty()) + ELog.DlgMsg(mtError, error_text.c_str()); + else if (UI->NeedAbort()) + ELog.DlgMsg(mtInformation, "Building terminated..."); + else + ELog.DlgMsg(mtInformation, "Building OK..."); + } + catch (...) + { + ELog.DlgMsg(mtError, "Error has occured in builder routine. Editor aborted."); + abort(); + } + UI->EndEState(); + + return error_text.empty(); +} +//------------------------------------------------------------------------------ + +BOOL SceneBuilder::MakeSOM() +{ + xr_string error_text = ""; + UI->ResetBreak(); + if (UI->ContainEState(esBuildLevel)) + return false; + ELog.Msg(mtInformation, "Making started..."); + + UI->BeginEState(esBuildLevel); + try + { + do + { + // build + VERIFY_COMPILE(PreparePath(), "Failed to prepare level path.", ""); + VERIFY_COMPILE(BuildSOMModel(), "Failed to build SOM model.", ""); + } while (0); + + if (!error_text.empty()) + ELog.DlgMsg(mtError, error_text.c_str()); + else if (UI->NeedAbort()) + ELog.DlgMsg(mtInformation, "Building terminated..."); + else + ELog.DlgMsg(mtInformation, "Building OK..."); + } + catch (...) + { + ELog.DlgMsg(mtError, "Error has occured in builder routine. Editor aborted."); + abort(); + } + UI->EndEState(); + + return error_text.empty(); +} + +void SceneBuilder::OnRender() +{ + if (object_for_render) + { + object_for_render->OnFrame(); + object_for_render->RenderSingle(Fidentity); + } +} diff --git a/src/editors/LevelEditor/Builder/Builder.h b/src/editors/LevelEditor/Builder/Builder.h new file mode 100644 index 00000000000..eb4185be6b7 --- /dev/null +++ b/src/editors/LevelEditor/Builder/Builder.h @@ -0,0 +1,160 @@ +#pragma once + +// refs +class CSceneObject; +class CEditableMesh; +class EScene; +class CLight; +class CGlow; +class CPortal; +struct st_SPData; +class CSurface; +struct st_DPSurface; +class CSceneStat; + +// some types +typedef Fvector b_vnormal; + +struct sb_light_control // controller or "layer", 30fps +{ + string64 name; // empty for base layer + U32Vec data; +}; + +struct e_b_lod +{ + b_lod lod; + U32Vec data; + U32Vec ndata; + shared_str lod_name; +}; + +class SceneBuilder +{ +public: + struct SBuildLight + { + Flight light; + float energy; + }; + DEFINE_VECTOR(SBuildLight, BLVec, BLIt); + +protected: + BLVec simple_hemi; + +public: + CEditableObject *object_for_render; + + int l_vert_cnt, l_vert_it; + int l_face_cnt, l_face_it; + b_vertex *l_verts; + b_face *l_faces; + u32 *l_smgroups; + + xr_vector l_mu_models; + xr_vector l_mu_refs; + xr_vector l_lods; + xr_vector l_light_control; + xr_vector l_light_static; + xr_vector l_light_dynamic; + xr_vector l_textures; + xr_vector l_shaders; + xr_vector l_shaders_xrlc; + xr_vector l_materials; + xr_vector l_vnormals; + xr_vector l_glows; + xr_vector l_portals; + xr_vector l_light_keys; + + CSceneStat *l_scene_stat; + + void GetBBox(u32 st_fid, u32 cnt, Fbox &box); + + BOOL BuildGlow(CGlow *e); + void BuildPortal(b_portal *b, CPortal *e); + BOOL BuildMesh(const Fmatrix &parent, CEditableObject *object, CEditableMesh *mesh, int sector_num, + b_vertex *verts, int &vert_cnt, int &vert_it, + b_face *faces, int &face_cnt, int &face_it, u32 *smooth_groups, const Fmatrix &real_transform, CSceneObject *obj); + BOOL BuildObject(CSceneObject *obj); + BOOL BuildMUObject(CSceneObject *obj); + + void Clear(); + + int BuildLightControl(LPCSTR name); + void BuildHemiLights(u8 quality, LPCSTR lcontrol); + void AppendLight(); + BOOL BuildSun(u8 quality, Fvector2 dir); + BOOL BuildPointLight(b_light *b, const Flags32 &usage, svector *sectors, FvectorVec *soft_points, const Fmatrix *soft_transform = 0); + BOOL BuildLight(CLight *e); + + int FindInLODs(b_lod *s); + int BuildObjectLOD(const Fmatrix &parent, CEditableObject *e, int sector_num); + + int FindInShaders(b_shader *s); + int BuildShader(LPCSTR s); + + int FindInShadersXRLC(b_shader *s); + int BuildShaderXRLC(const char *s); + + int FindInTextures(LPCSTR name); + int BuildTexture(LPCSTR name); + + int FindInMaterials(b_material *m); + int BuildMaterial(CSurface *surf, int sector_num, bool allow_draft); + int BuildMaterial(LPCSTR esh_name, LPCSTR csh_name, LPCSTR tx_name, u32 tx_cnt, int sector_num, bool allow_draft); + + BOOL ParseStaticObjects(ObjectList &lst, LPCSTR prefix, bool b_selected_only); + + int CalculateSector(const Fvector &P, float R); + + void SaveBuild(); + void SaveBuildAsObject(); + +protected: + friend void SaveBuild(); + friend class TfrmBuildProgress; + + Fbox m_LevelBox; + +public: + bool m_save_as_object; + string_path m_LevelPath; + xr_string MakeLevelPath(LPCSTR nm) { return xr_string(m_LevelPath) + xr_string(nm); } + +protected: + bool EvictResource(); + bool PrepareFolders(); + bool PreparePath(); + + bool GetBounding(); + + BOOL ParseLTX(CInifile *pIni, ObjectList &lst, LPCSTR prefix = 0); + BOOL BuildLTX(); + BOOL ParseGAME(IWriter &game, IWriter &spawn, ObjectList &lst, LPCSTR prefix = 0); + BOOL BuildGame(); + + BOOL BuildSceneStat(); + bool BuildHOMModel(); + bool BuildSOMModel(); + bool BuildAIMap(); + bool BuildWallmarks(); + BOOL CompileStatic(bool b_selected_only); + + int m_iDefaultSectorNum; + bool RenumerateSectors(); + +public: + SceneBuilder(); + virtual ~SceneBuilder(); + + BOOL Compile(bool b_selected_only); + BOOL MakeGame(); + BOOL MakeDetails(); + BOOL MakeHOM(); + BOOL MakeSOM(); + BOOL MakeAIMap(); + + void OnRender(); +}; + +extern SceneBuilder Builder; diff --git a/src/editors/LevelEditor/Builder/BuilderCore.cpp b/src/editors/LevelEditor/Builder/BuilderCore.cpp new file mode 100644 index 00000000000..0d34f9b6d42 --- /dev/null +++ b/src/editors/LevelEditor/Builder/BuilderCore.cpp @@ -0,0 +1,82 @@ +#include "stdafx.h" + +bool SceneBuilder::PreparePath() +{ + if (Scene->m_LevelOp.m_FNLevelPath.size() == 0) + return false; + FS.update_path(m_LevelPath, _game_levels_, Scene->m_LevelOp.m_FNLevelPath.c_str()); + strcat(m_LevelPath, "\\"); + return true; +} +//------------------------------------------------------------------------------ + +bool SceneBuilder::PrepareFolders() +{ + FS.dir_delete(m_LevelPath, TRUE); + return true; +} +//------------------------------------------------------------------------------ + +bool SceneBuilder::EvictResource() +{ + ExecCommand(COMMAND_EVICT_OBJECTS); + ExecCommand(COMMAND_EVICT_TEXTURES); + + int objcount = Scene->ObjCount(OBJCLASS_SCENEOBJECT); + if (objcount <= 0) + return true; + + SPBItem *pb = UI->ProgressStart(static_cast(objcount), "Evict objects..."); + // unload cform, point normals + ObjectIt _F = Scene->FirstObj(OBJCLASS_SCENEOBJECT); + ObjectIt _E = Scene->LastObj(OBJCLASS_SCENEOBJECT); + for (; _F != _E; _F++) + { + CSceneObject *O = (CSceneObject *)(*_F); + if (UI->NeedAbort()) + break; // break building + O->EvictObject(); + pb->Inc(); + } + UI->ProgressEnd(pb); + + return true; +} +//------------------------------------------------------------------------------ + +bool SceneBuilder::GetBounding() +{ + Fbox b0; + bool r0 = Scene->GetBox(m_LevelBox, OBJCLASS_SCENEOBJECT); + bool r1 = Scene->GetBox(b0, OBJCLASS_GROUP); + if (r1) + m_LevelBox.merge(b0); + return (r0 || r1); +} +//------------------------------------------------------------------------------ + +bool SceneBuilder::RenumerateSectors() +{ + m_iDefaultSectorNum = -1; + + SPBItem *pb = UI->ProgressStart(static_cast(Scene->ObjCount(OBJCLASS_SECTOR)), "Renumerate sectors..."); + + int sector_num = 0; + ObjectIt _F = Scene->FirstObj(OBJCLASS_SECTOR); + ObjectIt _E = Scene->LastObj(OBJCLASS_SECTOR); + for (; _F != _E; _F++, sector_num++) + { + CSector *_S = (CSector *)(*_F); + _S->m_sector_num = sector_num; + if (_S->IsDefault()) + m_iDefaultSectorNum = sector_num; + pb->Inc(); + } + + UI->ProgressEnd(pb); + + if (m_iDefaultSectorNum < 0) + m_iDefaultSectorNum = Scene->ObjCount(OBJCLASS_SECTOR); + return true; +} +//------------------------------------------------------------------------------ diff --git a/src/editors/LevelEditor/Builder/BuilderGame.cpp b/src/editors/LevelEditor/Builder/BuilderGame.cpp new file mode 100644 index 00000000000..dc1ae2fc5bd --- /dev/null +++ b/src/editors/LevelEditor/Builder/BuilderGame.cpp @@ -0,0 +1,167 @@ +#include "stdafx.h" + +bool sort_fog_vol(EFogVolume *fv1, EFogVolume *fv2) +{ + return (fv1->m_volumeType < fv2->m_volumeType); +} + +BOOL SceneBuilder::BuildGame() +{ + SExportStreams F; + F.envmodif.stream.open_chunk(F.envmodif.chunk++); + F.envmodif.stream.w_u32(u32(SPAWNPOINT_VERSION)); + F.envmodif.stream.close_chunk(); + + if (!Scene->ExportGame(&F)) + return FALSE; + + BOOL bRes = TRUE; + // save spawn + { + xr_string lev_spawn = MakeLevelPath("level.spawn"); + EFS.MarkFile(lev_spawn.c_str(), true); + if (F.spawn.chunk) + if (!F.spawn.stream.save_to(lev_spawn.c_str())) + bRes = FALSE; + + lev_spawn = MakeLevelPath("level_rs.spawn"); + EFS.MarkFile(lev_spawn.c_str(), true); + if (F.spawn_rs.chunk) + if (!F.spawn_rs.stream.save_to(lev_spawn.c_str())) + bRes = FALSE; + } + + // save game + { + CMemoryWriter GAME; + GAME.w_chunk(WAY_PATROLPATH_CHUNK, F.patrolpath.stream.pointer(), F.patrolpath.stream.size()); + GAME.w_chunk(RPOINT_CHUNK, F.rpoint.stream.pointer(), F.rpoint.stream.size()); + xr_string lev_game = MakeLevelPath("level.game"); + EFS.MarkFile(lev_game.c_str(), true); + if (GAME.size()) + if (!GAME.save_to(lev_game.c_str())) + bRes = FALSE; + } + + // save weather env modificator + { + xr_string lev_env_mod = MakeLevelPath("level.env_mod"); + EFS.MarkFile(lev_env_mod.c_str(), true); + if (F.envmodif.chunk) + if (!F.envmodif.stream.save_to(lev_env_mod.c_str())) + bRes = FALSE; + } + + // save static sounds + { + xr_string lev_sound_static = MakeLevelPath("level.snd_static"); + EFS.MarkFile(lev_sound_static.c_str(), true); + if (F.sound_static.chunk) + if (!F.sound_static.stream.save_to(lev_sound_static.c_str())) + bRes = FALSE; + } + /* + // save sound envs + { + xr_string lev_sound_env = MakeLevelPath("level.snd_env"); + EFS.MarkFile (lev_sound_env.c_str(),true); + if (LSndLib->MakeEnvGeometry (F.sound_env_geom.stream,false)) + if (!F.sound_env_geom.stream.save_to(lev_sound_env.c_str())) bRes = FALSE; + } + */ + // save static PG + { + xr_string lev_pe_static = MakeLevelPath("level.ps_static"); + EFS.MarkFile(lev_pe_static.c_str(), true); + if (F.pe_static.chunk) + if (!F.pe_static.stream.save_to(lev_pe_static.c_str())) + bRes = FALSE; + } + + // save fog volumes + if (1) + { + xr_string lev_fog_vol = MakeLevelPath("level.fog_vol"); + EFS.MarkFile(lev_fog_vol.c_str(), true); + + F.fog_vol.stream.w_u16(3); // version + + ObjectList &fogs = Scene->ListObj(OBJCLASS_FOG_VOL); + + typedef xr_vector tfog_group; + typedef xr_map tfog_groups; + + tfog_groups fog_groups; + + for (ObjectIt oit = fogs.begin(); oit != fogs.end(); ++oit) + { + EFogVolume *E = dynamic_cast(*oit); + R_ASSERT(E); + u32 grp_id = E->m_group_id; + fog_groups[grp_id].push_back(E); + } + + F.fog_vol.stream.w_u32(fog_groups.size()); + + tfog_groups::iterator git = fog_groups.begin(); + tfog_groups::iterator git_e = fog_groups.end(); + for (; git != git_e; ++git) + { + tfog_group &one_group = git->second; + std::sort(one_group.begin(), one_group.end(), sort_fog_vol); + + tfog_group::iterator fgit = one_group.begin(); + tfog_group::iterator fgit_e = one_group.end(); + + for (; fgit != fgit_e; ++fgit) + { + EFogVolume *E = *fgit; + if (fgit == one_group.begin()) + { + if (E->m_volumeType != fvEmitter) + { + bRes = FALSE; + Msg("! incorrect fog volumes grouping"); + break; + } + + F.fog_vol.stream.w_string(E->m_volume_profile.c_str()); + } + Fmatrix M = E->_Transform(); + F.fog_vol.stream.w(&M, sizeof(M)); + + if (fgit == one_group.begin()) + { + if (E->m_volumeType != fvEmitter) + { + + bRes = FALSE; + Msg("! incorrect fog volumes grouping"); + break; + } + + F.fog_vol.stream.w_u32(one_group.size() - 1); + } + else + { + + if (E->m_volumeType != fvOcclusion) + { + bRes = FALSE; + Msg("! incorrect fog volumes grouping"); + break; + } + } + if (!bRes) + break; + } + if (!bRes) + break; + } + + if (!F.fog_vol.stream.save_to(lev_fog_vol.c_str())) + bRes = FALSE; + } + + return bRes; +} diff --git a/src/editors/LevelEditor/Builder/BuilderLODs.cpp b/src/editors/LevelEditor/Builder/BuilderLODs.cpp new file mode 100644 index 00000000000..24c4efb2b19 --- /dev/null +++ b/src/editors/LevelEditor/Builder/BuilderLODs.cpp @@ -0,0 +1,263 @@ +#include "stdafx.h" + +#define LEVEL_LODS_TEX_NAME "level_lods" +#define LEVEL_LODS_NRM_NAME "level_lods_nm" + +// lod build functions + +DEFINE_VECTOR(Fvector4, Fvector4Vec, Fvector4It); + +BOOL GetPointColor(SPickQuery::SResult *R, u32 &alpha) +{ + CSurface *surf = R->e_mesh->GetSurfaceByFaceID(R->tag); + VERIFY(surf); + Shader_xrLC *c_sh = EDevice.ShaderXRLC.Get(surf->_ShaderXRLCName()); + if (!c_sh->flags.bRendering) + return FALSE; + const Fvector2 *cuv[3]; + R->e_mesh->GetFaceTC(R->tag, cuv); + + // barycentric coords + // note: W,U,V order + Fvector B; + B.set(1.0f - R->u - R->v, R->u, R->v); + + // calc UV + Fvector2 uv; + uv.x = cuv[0]->x * B.x + cuv[1]->x * B.y + cuv[2]->x * B.z; + uv.y = cuv[0]->y * B.x + cuv[1]->y * B.y + cuv[2]->y * B.z; + + int U = iFloor(uv.x * float(surf->m_ImageData->w) + .5f); + int V = iFloor(uv.y * float(surf->m_ImageData->h) + .5f); + U %= surf->m_ImageData->w; + if (U < 0) + U += surf->m_ImageData->w; + V %= surf->m_ImageData->h; + if (V < 0) + V += surf->m_ImageData->h; + + alpha = color_get_A(surf->m_ImageData->layers.back()[V * surf->m_ImageData->w + U]); + return TRUE; +} + +int SceneBuilder::BuildObjectLOD(const Fmatrix &parent, CEditableObject *E, int sector_num) +{ + if (!E->m_objectFlags.is(CEditableObject::eoUsingLOD)) + return -1; + xr_string lod_name = E->GetLODTextureName(); + + b_material mtl; + mtl.surfidx = (u16)BuildTexture(LEVEL_LODS_TEX_NAME); + mtl.shader = (u16)BuildShader(E->GetLODShaderName()); + mtl.sector = (u16)sector_num; + mtl.shader_xrlc = -1; + if ((u16(-1) == mtl.surfidx) || (u16(-1) == mtl.shader)) + return -2; + + int mtl_idx = FindInMaterials(&mtl); + if (mtl_idx < 0) + { + l_materials.push_back(mtl); + mtl_idx = l_materials.size() - 1; + } + + l_lods.push_back(e_b_lod()); + e_b_lod &b = l_lods.back(); + Fvector p[4]; + Fvector2 t[4]; + for (int frame = 0; frame < LOD_SAMPLE_COUNT; frame++) + { + E->GetLODFrame(frame, p, t, &parent); + for (int k = 0; k < 4; k++) + { + b.lod.faces[frame].v[k].set(p[k]); + b.lod.faces[frame].t[k].set(t[k]); + } + } + b.lod.dwMaterial = mtl_idx; + b.lod_name = lod_name.c_str(); + xr_string l_name = lod_name.c_str(); + u32 w, h; + int age; + if (!ImageLib.LoadTextureData(l_name.c_str(), b.data, w, h, &age)) + { + Msg("!Can't find LOD texture: '%s'", l_name.c_str()); + return -2; + } + /* if (age!=E->Version()){ + Msg("!Invalid LOD texture version: '%s'",l_name.c_str()); + return -2; + }*/ + l_name += "_nm"; + if (!ImageLib.LoadTextureData(l_name.c_str(), b.ndata, w, h, &age)) + { + Msg("!Can't find LOD texture: '%s'", l_name.c_str()); + return -2; + } + /* if (age!=E->Version()){ + Msg("!Invalid LOD texture version: '%s'",l_name.c_str()); + return -2; + }*/ + // b.data + /* + // make lod + Fbox bb = E->GetBox(); + E->m_Flags.set (CEditableObject::eoUsingLOD,FALSE); + object_for_render = E; + ImageLib.CreateLODTexture (bb, b.data, LOD_IMAGE_SIZE,LOD_IMAGE_SIZE,LOD_SAMPLE_COUNT); + E->m_Flags.set (CEditableObject::eoUsingLOD,TRUE); + + // build lod normals + b.ndata.resize (LOD_IMAGE_SIZE*LOD_IMAGE_SIZE*LOD_SAMPLE_COUNT); + U8Vec hemi_temp (LOD_IMAGE_SIZE*LOD_IMAGE_SIZE*LOD_SAMPLE_COUNT,0); + Fvector o_center,o_size; + Fmatrix M,Mi; + bb.getradius (o_size); + bb.getcenter (o_center); + SPBItem* PB = UI->ProgressStart(LOD_SAMPLE_COUNT*LOD_IMAGE_SIZE,lod_name.c_str()); + float dW = _max(o_size.x,o_size.z)/(LOD_IMAGE_SIZE/2); + float dH = o_size.y/(LOD_IMAGE_SIZE/2); + float dR = bb.getradius(); + float d2R = dR*2.f; + XRC.ray_options (CDB::OPT_CULL); + ETOOLS::ray_options (CDB::OPT_CULL); + + float tN=0.f,tH=0.f,tT=0.f,tR=0.f; + + float LOD_CALC_SAMPLES = Scene->m_LevelOp.m_LOD_Quality; + s32 LOD_CALC_SAMPLES_LIM= LOD_CALC_SAMPLES/2; + + // preload textures + for (SurfaceIt surf_it=E->Surfaces().begin(); surf_it!=E->Surfaces().end(); surf_it++){ + CSurface* surf = *surf_it; + Shader_xrLC* c_sh = EDevice.ShaderXRLC.Get(surf->_ShaderXRLCName()); + if (!c_sh->flags.bRendering) continue; + if (0==surf->m_ImageData)surf->CreateImageData(); + } + + // preload CF Model + for (EditMeshIt mesh_it=E->Meshes().begin(); mesh_it!=E->Meshes().end(); mesh_it++) + (*mesh_it)->GenerateCFModel(); + + // calculate + for (u32 sample_idx=0; sample_idxInc (); + float Y = (iH-(LOD_IMAGE_SIZE-1)/2)*dH; + for (s32 iW=0; iWRayQuery (PQ); + if (PQ.r_count()){ + PQ.r_sort(); + Fvector N = {0,0,0}; + for (s32 k=PQ.r_count()-1; k>=0; k--){ + SPickQuery::SResult* R = PQ.r_begin()+k; + u32 uA; + if (!GetPointColor(R,uA)) continue; + float fA = float(uA)/255.f; + if (uA){ + Fvector pt; pt.mad(PQ.m_Start,PQ.m_Direction,R->range-EPS_L); + Fvector4 ptt; ptt.set(pt.x,pt.y,pt.z,fA); + sample_pt_vec.push_back(ptt); + } + // normal + Fvector Nn; + Nn.mknormal (R->verts[0],R->verts[1],R->verts[2]); + Nn.mul (fA); + + N.mul (1.f-fA); + N.add (Nn); + } + float n_mag = N.magnitude(); + if (!fis_zero(n_mag,EPS)) + n_vec.push_back (N.div(n_mag)); + } + } + } + tN+=TT.Stop(); + + TT.Start(); + // light points + float res_transp = 0.f; + for (Fvector4It pt_it=sample_pt_vec.begin(); pt_it!=sample_pt_vec.end(); pt_it++){ + float avg_transp = 0.f; + for (BLIt it=simple_hemi.begin(); it!=simple_hemi.end(); it++){ + TT1.Start(); + Fvector start; + start.mad (Fvector().set(pt_it->x,pt_it->y,pt_it->z),it->light.direction,-dR); + PQ.prepare_rq (start,it->light.direction,dR,CDB::OPT_CULL); + E->RayQuery (PQ); + tR+=TT1.Stop(); + float ray_transp= 1.f; + if (PQ.r_count()){ + for (s32 k=0; kw)+avg_transp*pt_it->w; + } + tH+=TT.Stop(); + + tgt_h = iFloor (res_transp*255.f); + + Fvector N={0,0,0}; + if (!n_vec.empty()){ + for (FvectorIt it=n_vec.begin(); it!=n_vec.end(); it++) N.add(*it); + N.div (n_vec.size()); + N.normalize_safe(); + Mi.transform_dir(N); + } + N.mul (0.5f); + N.add (0.5f); + N.mul (255.f); + tgt_n = color_rgba(iFloor(N.x),iFloor(N.y),iFloor(N.z),src_a); + } + } + } + + Msg("Normal: %3.2fsec, Hemi: %3.2f, PC: %3.2f, RP: %3.2f",tN,tH,tT,tR); + ImageLib.ApplyBorders (b.ndata, LOD_IMAGE_SIZE*LOD_SAMPLE_COUNT,LOD_IMAGE_SIZE); + // fill alpha to N-channel + for (int px_idx=0; px_idxProgressEnd(PB); + */ + + return l_lods.size() - 1; +} +//------------------------------------------------------------------------------ diff --git a/src/editors/LevelEditor/Builder/BuilderLTX.cpp b/src/editors/LevelEditor/Builder/BuilderLTX.cpp new file mode 100644 index 00000000000..a975526d21c --- /dev/null +++ b/src/editors/LevelEditor/Builder/BuilderLTX.cpp @@ -0,0 +1,96 @@ +#include "stdafx.h" + +BOOL SceneBuilder::ParseLTX(CInifile *pIni, ObjectList &lst, LPCSTR prefix) +{ + return TRUE; +} +//---------------------------------------------------- + +BOOL SceneBuilder::BuildLTX() +{ + bool bResult = true; + int objcount = Scene->ObjCount(); + if (objcount <= 0) + return true; + + xr_string ltx_filename = MakeLevelPath("level.ltx"); + + if (FS.exist(ltx_filename.c_str())) + EFS.MarkFile(ltx_filename.c_str(), true); + + // -- defaults -- + IWriter *F = FS.w_open(ltx_filename.c_str()); + + if (F) + { + string256 buff; + F->w_string("[map_usage]"); + sprintf(buff, "ver=%s", Scene->m_LevelOp.m_map_version.c_str()); + F->w_string(buff); + if (Scene->m_LevelOp.m_mapUsage.MatchType(eGameIDDeathmatch)) + F->w_string("deathmatch"); + if (Scene->m_LevelOp.m_mapUsage.MatchType(eGameIDTeamDeathmatch)) + F->w_string("teamdeathmatch"); + if (Scene->m_LevelOp.m_mapUsage.MatchType(eGameIDArtefactHunt)) + F->w_string("artefacthunt"); + if (Scene->m_LevelOp.m_mapUsage.MatchType(eGameIDCaptureTheArtefact)) + F->w_string("capturetheartefact"); + if (Scene->m_LevelOp.m_mapUsage.MatchType(eGameIDDominationZone)) + F->w_string("dominationzone"); + if (Scene->m_LevelOp.m_mapUsage.MatchType(eGameIDTeamDominationZone)) + F->w_string("teamdominationzone"); + + //---- + F->w_string(";"); + + Fbox bb; + Fbox bg; + Scene->GetBox(bb, OBJCLASS_SCENEOBJECT); + bool r1 = Scene->GetBox(bg, OBJCLASS_GROUP); + if (r1) + bb.merge(bg); + + ObjectList &shapes = Scene->ListObj(OBJCLASS_SHAPE); + for (ObjectIt sit = shapes.begin(); sit != shapes.end(); ++sit) + { + CEditShape *E = dynamic_cast(*sit); + R_ASSERT(E); + if (E->m_shape_type == eShapeLevelBound) + { + E->GetBox(bb); + break; + } + } + + F->w_string("[level_map]"); + sprintf(buff, "bound_rect = %f,%f,%f,%f", bb.vMin.x, bb.vMin.z, bb.vMax.x, bb.vMax.z); + F->w_string(buff); + sprintf(buff, "texture = map\\map_%s", Scene->m_LevelOp.m_FNLevelPath.c_str()); + F->w_string(buff); + + F->w_string(";"); + if (Scene->m_LevelOp.m_BOPText.size()) + F->w_stringZ(Scene->m_LevelOp.m_BOPText); + + //---- + ObjectIt _F = Scene->FirstObj(OBJCLASS_SECTOR); + ObjectIt _E = Scene->LastObj(OBJCLASS_SECTOR); + + F->w_string(";"); + F->w_string("[sub_level_map]"); + for (; _F != _E; ++_F) + { + CSector *_S = (CSector *)(*_F); + sprintf(buff, "%d = %d", _S->m_sector_num, _S->m_map_idx); + F->w_string(buff); + } + + FS.w_close(F); + } + else + { + bResult = false; + } + + return bResult; +} diff --git a/src/editors/LevelEditor/Builder/BuilderOGF.cpp b/src/editors/LevelEditor/Builder/BuilderOGF.cpp new file mode 100644 index 00000000000..90a548248ff --- /dev/null +++ b/src/editors/LevelEditor/Builder/BuilderOGF.cpp @@ -0,0 +1,165 @@ +#include "stdafx.h" + +// some types +bool SceneBuilder::BuildHOMModel() +{ + CMemoryWriter F; + + F.open_chunk(0); + F.w_u32(0); + F.close_chunk(); + + F.open_chunk(1); + ObjectList &lst = Scene->ListObj(OBJCLASS_SCENEOBJECT); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + CSceneObject *S = (CSceneObject *)(*it); + CEditableObject *E = S->GetReference(); + R_ASSERT(E); + if (E->m_objectFlags.is(CEditableObject::eoHOM)) + { + Fvector v; + const Fmatrix &parent = S->_Transform(); + for (EditMeshIt m_it = E->FirstMesh(); m_it != E->LastMesh(); ++m_it) + { + for (SurfFacesPairIt sf_it = (*m_it)->m_SurfFaces.begin(); sf_it != (*m_it)->m_SurfFaces.end(); ++sf_it) + { + BOOL b2Sided = sf_it->first->m_Flags.is(CSurface::sf2Sided); + IntVec &i_lst = sf_it->second; + for (IntIt i_it = i_lst.begin(); i_it != i_lst.end(); ++i_it) + { + st_Face &face = (*m_it)->m_Faces[*i_it]; + for (int k = 0; k < 3; ++k) + { + parent.transform_tiny(v, (*m_it)->m_Vertices[face.pv[k].pindex]); + F.w_fvector3(v); + } + F.w_u32(b2Sided); + } + } + } + } + else + { + Fvector v; + const Fmatrix &parent = S->_Transform(); + for (EditMeshIt m_it = E->FirstMesh(); m_it != E->LastMesh(); ++m_it) + { + for (SurfFacesPairIt sf_it = (*m_it)->m_SurfFaces.begin(); sf_it != (*m_it)->m_SurfFaces.end(); ++sf_it) + { + CSurface *S = sf_it->first; + if (S->m_GameMtlName == "materials\\occ") + { + BOOL b2Sided = S->m_Flags.is(CSurface::sf2Sided); + IntVec &i_lst = sf_it->second; + for (IntIt i_it = i_lst.begin(); i_it != i_lst.end(); ++i_it) + { + st_Face &face = (*m_it)->m_Faces[*i_it]; + for (int k = 0; k < 3; ++k) + { + parent.transform_tiny(v, (*m_it)->m_Vertices[face.pv[k].pindex]); + F.w_fvector3(v); + } + F.w_u32(b2Sided); + } + } + } + } + } + } + + BOOL bValid = !!F.chunk_size(); + F.close_chunk(); + if (bValid) + { + xr_string hom_name = MakeLevelPath("level.hom"); + bValid = F.save_to(hom_name.c_str()); + } + return bValid; +} + +bool SceneBuilder::BuildSOMModel() +{ + BOOL bResult = TRUE; + CMemoryWriter F; + + F.open_chunk(0); + F.w_u32(0); + F.close_chunk(); + + F.open_chunk(1); + ObjectList &lst = Scene->ListObj(OBJCLASS_SCENEOBJECT); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + CSceneObject *S = (CSceneObject *)(*it); + CEditableObject *E = S->GetReference(); + R_ASSERT(E); + if (E->m_objectFlags.is(CEditableObject::eoSoundOccluder)) + { + Fvector v; + const Fmatrix &parent = S->_Transform(); + for (EditMeshIt m_it = E->FirstMesh(); m_it != E->LastMesh(); m_it++) + { + for (SurfFacesPairIt sf_it = (*m_it)->m_SurfFaces.begin(); sf_it != (*m_it)->m_SurfFaces.end(); sf_it++) + { + CSurface *surf = sf_it->first; + int gm_id = surf->_GameMtl(); + if (gm_id == GAMEMTL_NONE_ID) + { + ELog.DlgMsg(mtError, "Object '%s', surface '%s' contain invalid game material.", (*m_it)->Parent()->m_LibName.c_str(), surf->_Name()); + bResult = FALSE; + break; + } + SGameMtl *mtl = GMLib.GetMaterialByID(gm_id); + if (0 == mtl) + { + ELog.DlgMsg(mtError, "Object '%s', surface '%s' contain undefined game material.", (*m_it)->Parent()->m_LibName.c_str(), surf->_Name()); + bResult = FALSE; + break; + } + BOOL b2Sided = surf->m_Flags.is(CSurface::sf2Sided); + IntVec &i_lst = sf_it->second; + for (IntIt i_it = i_lst.begin(); i_it != i_lst.end(); i_it++) + { + st_Face &face = (*m_it)->m_Faces[*i_it]; + for (int k = 0; k < 3; k++) + { + parent.transform_tiny(v, (*m_it)->m_Vertices[face.pv[k].pindex]); + F.w_fvector3(v); + } + F.w_u32(b2Sided); + F.w_float(mtl->fSndOcclusionFactor); + } + } + } + } + } + BOOL bValid = !!F.chunk_size() && bResult; + F.close_chunk(); + if (bValid) + { + xr_string som_name = MakeLevelPath("level.som"); + bValid = F.save_to(som_name.c_str()); + } + return bValid; +} + +bool SceneBuilder::BuildAIMap() +{ + // build sky ogf + if (Scene->GetTool(OBJCLASS_AIMAP)->Valid()) + { + return Scene->GetTool(OBJCLASS_AIMAP)->Export(m_LevelPath); + } + return false; +} + +bool SceneBuilder::BuildWallmarks() +{ + // build sky ogf + if (Scene->GetTool(OBJCLASS_WM)->Valid()) + { + return Scene->GetTool(OBJCLASS_WM)->Export(m_LevelPath); + } + return false; +} diff --git a/src/editors/LevelEditor/Builder/BuilderRemote.cpp b/src/editors/LevelEditor/Builder/BuilderRemote.cpp new file mode 100644 index 00000000000..f3499e8afc1 --- /dev/null +++ b/src/editors/LevelEditor/Builder/BuilderRemote.cpp @@ -0,0 +1,1602 @@ +#include "stdafx.h" + +// !!! использовать prefix если нужно имя !!! (Связано с группами) + +#define LEVEL_LODS_TEX_NAME "level_lods" +#define LEVEL_LODS_NRM_NAME "level_lods_nm" +#define LEVEL_DI_TEX_NAME "level_stat" + +class CSceneStat +{ + Fvector bb_min; + u32 bb_sx, bb_sz; + + u32 max_svert; + U32Vec svertices; + u32 &svertex(u32 ix, u32 iz) + { + VERIFY((ix < bb_sx) && (iz < bb_sz)); + return svertices[iz * bb_sx + ix]; + } + + u32 max_muvert; + U32Vec muvertices; + u32 &muvertex(u32 ix, u32 iz) + { + VERIFY((ix < bb_sx) && (iz < bb_sz)); + return muvertices[iz * bb_sx + ix]; + } + +public: + CSceneStat(const Fbox &bb) + { + Fvector sz; + bb.getsize(sz); + bb_sx = iFloor(sz.x + 1.f); + bb_sz = iFloor(sz.z + 1.f); + bb_min.set(bb.vMin); + max_svert = 0; + svertices.resize(bb_sx * bb_sz, 0); + max_muvert = 0; + muvertices.resize(bb_sx * bb_sz, 0); + } + void add_svert(const Fvector &p) + { + u32 ix = clampr((u32)iFloor(p.x - bb_min.x), (u32)0, bb_sx - 1); + u32 iz = clampr((u32)iFloor(p.z - bb_min.z), (u32)0, bb_sz - 1); + u32 &v = svertex(ix, iz); + v++; + if (v > max_svert) + max_svert = v; + } + void add_muvert(const Fmatrix &parent, const Fvector &_p) + { + Fvector p; + parent.transform_tiny(p, _p); + u32 ix = clampr((u32)iFloor(p.x - bb_min.x), (u32)0, bb_sx - 1); + u32 iz = clampr((u32)iFloor(p.z - bb_min.z), (u32)0, bb_sz - 1); + u32 &v = muvertex(ix, iz); + v++; + if (v > max_muvert) + max_muvert = v; + } + bool flush(LPCSTR fn) + { + // flush image + u32 sx = bb_sx, sz = bb_sz; + U32Vec data(sx * sz); + // prepare vertex info + // find max + u32 ix, iz; + u32 total_svert = 0; + u32 total_muvert = 0; + for (ix = 0; ix < bb_sx; ix++) + { + for (iz = 0; iz < bb_sz; iz++) + { + total_svert += svertex(ix, iz); + total_muvert += muvertex(ix, iz); + u8 v_s = (u8)iFloor(float(svertex(ix, iz)) / float(max_svert) * 255.f + 0.5f); + u8 v_mu = (u8)iFloor(float(muvertex(ix, iz)) / float(max_muvert) * 255.f + 0.5f); + data[iz * bb_sx + ix] = color_rgba(v_s, v_mu, 0, 0); + } + } + + xr_string image_name = xr_string(fn) + ".tga"; + CImage *I = xr_new(); + I->Create(sx, sz, data.data()); + I->Vflip(); + I->SaveTGA(image_name.c_str()); + xr_delete(I); + + // flush text + xr_string txt_name = xr_string(fn) + ".txt"; + IWriter *F = FS.w_open(txt_name.c_str()); + if (F) + { + F->w_string(make_string("Map size X x Z: [%d x %d]", bb_sx, bb_sz).c_str()); + F->w_string(make_string("Max static vertex per m^2: %d", max_svert).c_str()); + F->w_string(make_string("Total static vertices: %d", total_svert).c_str()); + F->w_string(make_string("Max mu vertex per m^2: %d", max_muvert).c_str()); + F->w_string(make_string("Total mu vertices: %d", total_muvert).c_str()); + FS.w_close(F); + return true; + } + return false; + } +}; + +void SceneBuilder::SaveBuildAsObject() +{ + string512 tmp, tex_path, tex_name; + xr_string fn, fn_material; + + if (!EFS.GetSaveName(_import_, fn)) + return; + + fn = EFS.ChangeFileExt(fn, ".obj"); + fn_material = EFS.ChangeFileExt(fn, ".mtl"); + + IWriter *Fm = FS.w_open(fn_material.c_str()); + + for (u32 i = 0; i < l_materials.size(); ++i) + { + b_material &m = l_materials[i]; + b_texture_real &t = l_textures[m.surfidx]; + _splitpath(t.name, 0, tex_path, tex_name, 0); + + sprintf(tmp, "newmtl %s", tex_name); + Fm->w_string(tmp); + Fm->w_string("Ka 0 0 0"); + Fm->w_string("Kd 1 1 1"); + Fm->w_string("Ks 0 0 0"); + + sprintf(tmp, "map_Kd %s\\\\%s\\%s%s\n", + "T:", + tex_path, + tex_name, + ".tga"); + Fm->w_string(tmp); + } + FS.w_close(Fm); + + IWriter *F = FS.w_open(fn.c_str()); + CMemoryWriter tmpFaces; + + // writ comment + F->w_string("# This file uses meters as units for non-parametric coordinates."); + _splitpath(fn.c_str(), 0, 0, tex_name, 0); + sprintf(tmp, "mtllib %s.mtl", tex_name); + F->w_string(tmp); + + F->w_string("g default"); + + // vertices + u32 idx; + u32 total_vertices = 0; + u32 total_tcs = 0; + for (idx = 0; idx < l_vert_it; ++idx) + { + const b_vertex &it = l_verts[idx]; + sprintf(tmp, "v %f %f %f", it.x * 100.0f, it.y * 100.0f, it.z * 100.0f); + F->w_string(tmp); + } + + // TC-s + for (idx = 0; idx < l_face_it; ++idx) + { + const b_face &it = l_faces[idx]; + sprintf(tmp, "vt %f %f", it.t[0].x, /*_abs*/ (1.f - it.t[0].y)); + tmpFaces.w_string(tmp); + sprintf(tmp, "vt %f %f", it.t[1].x, /*_abs*/ (1.f - it.t[1].y)); + tmpFaces.w_string(tmp); + sprintf(tmp, "vt %f %f", it.t[2].x, /*_abs*/ (1.f - it.t[2].y)); + tmpFaces.w_string(tmp); + } + total_tcs += idx * 3; + + // faces + b_texture_real *last_texture = NULL; + for (idx = 0; idx < l_face_it; ++idx) + { + const b_face &it = l_faces[idx]; + + b_material &m = l_materials[it.dwMaterial]; + b_texture_real &t = l_textures[m.surfidx]; + if (last_texture != &t) + { + _splitpath(t.name, 0, 0, tex_name, 0); + sprintf(tmp, "usemtl %s", tex_name); + tmpFaces.w_string(tmp); + last_texture = &t; + } + + sprintf(tmp, "f %d/%d %d/%d %d/%d", it.v[0] + 1, idx * 3 + 1, + it.v[1] + 1, idx * 3 + 2, + it.v[2] + 1, idx * 3 + 3); + tmpFaces.w_string(tmp); + } + total_vertices += l_vert_it; + + for (idx = 0; idx < l_mu_models.size(); ++idx) + { + const b_mu_model &m = l_mu_models[idx]; + + for (u32 vi = 0; vi < m.m_iVertexCount; ++vi) + { + const b_vertex &it = m.m_pVertices[vi]; + sprintf(tmp, "v %f %f %f", it.x * 100.0f, it.y * 100.0f, it.z * 100.0f); + F->w_string(tmp); + } + // TC-s + for (u32 fi = 0; fi < m.m_iFaceCount; ++fi) + { + const b_face &it = m.m_pFaces[fi]; + sprintf(tmp, "vt %f %f", it.t[0].x, /*_abs*/ (1.f - it.t[0].y)); + tmpFaces.w_string(tmp); + sprintf(tmp, "vt %f %f", it.t[1].x, /*_abs*/ (1.f - it.t[1].y)); + tmpFaces.w_string(tmp); + sprintf(tmp, "vt %f %f", it.t[2].x, /*_abs*/ (1.f - it.t[2].y)); + tmpFaces.w_string(tmp); + } + // faces + for (int fi = 0; fi < m.m_iFaceCount; ++fi) + { + const b_face &it = m.m_pFaces[fi]; + + b_material &m = l_materials[it.dwMaterial]; + b_texture_real &t = l_textures[m.surfidx]; + if (last_texture != &t) + { + _splitpath(t.name, 0, 0, tex_name, 0); + sprintf(tmp, "usemtl %s", tex_name); + tmpFaces.w_string(tmp); + last_texture = &t; + } + sprintf(tmp, "f %d/%d %d/%d %d/%d", it.v[0] + 1 + total_vertices, fi * 3 + 1 + total_tcs, + it.v[1] + 1 + total_vertices, fi * 3 + 2 + total_tcs, + it.v[2] + 1 + total_vertices, fi * 3 + 3 + total_tcs); + /* + sprintf (tmp,"f %d %d %d", it.v[0]+1+total_vertices, + it.v[1]+1+total_vertices, + it.v[2]+1+total_vertices ); + */ + tmpFaces.w_string(tmp); + } + total_tcs += m.m_iFaceCount * 3; + total_vertices += m.m_iVertexCount; + } + F->w(tmpFaces.pointer(), tmpFaces.size()); + + // uv + // sprintf (tmp,"vt %f %f",v_it->UV.x,_abs(1.f-v_it->UV.y)); F.w_string (tmp); + + // normals + // sprintf (tmp,"vn %f %f %f",mV.x,mV.y,mV.z); F.w_string (tmp); + + // g + // sprintf (tmp,"vg %f %f %f",mV.x,mV.y,mV.z); F.w_string (tmp); + + // b + // sprintf (tmp,"vb %f %f %f",mV.x,mV.y,mV.z); F.w_string (tmp); + + /* + string512 tmp,tex_path,tex_name; + // write mtl + for (SplitIt split_it=m_Splits.begin(); split_it!=m_Splits.end(); split_it++) + { + _splitpath ((*split_it)->m_Surf->_Texture(), 0, 0, tex_name, 0 ); + sprintf (tmp,"newmtl %s",tex_name); + F.w_string (tmp); + + _splitpath ((*split_it)->m_Surf->_Texture(), 0, tex_path, tex_name, 0 ); + strconcat (sizeof(tex_path),tex_path,tex_path,"\\",tex_name,".tga"); + sprintf (tmp,"map_Kd %s",tex_path); + F.w_string (tmp); + } + sprintf (tmp,"mtllib %s",name); + F.w_string (tmp); + + // write mtl + u32 v_offs = 0; + for (split_it=m_Splits.begin(); split_it!=m_Splits.end(); split_it++){ + _splitpath ((*split_it)->m_Surf->_Texture(), 0, 0, tex_name, 0 ); + sprintf (tmp,"g %d",split_it-m_Splits.begin()); F.w_string (tmp); + sprintf (tmp,"usemtl %s",tex_name); F.w_string (tmp); + Fvector mV; + Fmatrix mZ; + mZ.mirrorZ (); + for (COGFCPIt it=(*split_it)->m_Parts.begin(); it!=(*split_it)->m_Parts.end(); it++){ + CObjectOGFCollectorPacked* part = *it; + // vertices + OGFVertVec& VERTS = part->getV_Verts(); + OGFVertIt v_it; + for (v_it=VERTS.begin(); v_it!=VERTS.end(); v_it++){ + mZ.transform_tiny(mV,v_it->P); + sprintf (tmp,"v %f %f %f",mV.x,mV.y,mV.z); F.w_string (tmp); + } + for (v_it=VERTS.begin(); v_it!=VERTS.end(); v_it++){ + sprintf (tmp,"vt %f %f",v_it->UV.x,_abs(1.f-v_it->UV.y)); F.w_string (tmp); + } + for (v_it=VERTS.begin(); v_it!=VERTS.end(); v_it++){ + mZ.transform_dir(mV,v_it->N); + sprintf (tmp,"vn %f %f %f",mV.x,mV.y,mV.z); F.w_string (tmp); + } + for (v_it=VERTS.begin(); v_it!=VERTS.end(); v_it++){ + mZ.transform_dir(mV,v_it->T); + sprintf (tmp,"vg %f %f %f",mV.x,mV.y,mV.z); F.w_string (tmp); + } + for (v_it=VERTS.begin(); v_it!=VERTS.end(); v_it++){ + mZ.transform_dir(mV,v_it->B); + sprintf (tmp,"vb %f %f %f",mV.x,mV.y,mV.z); F.w_string (tmp); + } + // faces + OGFFaceVec& FACES = part->getV_Faces(); + OGFFaceIt f_it; + for (f_it=FACES.begin(); f_it!=FACES.end(); f_it++){ + sprintf (tmp,"f %d/%d/%d %d/%d/%d %d/%d/%d",v_offs+f_it->v[2]+1,v_offs+f_it->v[2]+1,v_offs+f_it->v[2]+1, + v_offs+f_it->v[1]+1,v_offs+f_it->v[1]+1,v_offs+f_it->v[1]+1, + v_offs+f_it->v[0]+1,v_offs+f_it->v[0]+1,v_offs+f_it->v[0]+1); F.w_string (tmp); + } + v_offs += VERTS.size(); + } + } + } + */ + //--- + FS.w_close(F); +} + +void SceneBuilder::SaveBuild() +{ + xr_string fn = MakeLevelPath("build.prj"); + IWriter *F = FS.w_open(fn.c_str()); + + if (!F) + return; + + F->open_chunk(EB_Version); + + if (Core.SocSdk) + F->w_u32(XRCL_CURRENT_VERSION - 1); + else + F->w_u32(XRCL_CURRENT_VERSION); + + F->close_chunk(); + + F->open_chunk(EB_Parameters); + F->w(&Scene->m_LevelOp.m_BuildParams, sizeof(b_params)); + F->close_chunk(); + + F->open_chunk(EB_Vertices); + F->w(l_verts, sizeof(b_vertex) * l_vert_it); //. l_vert_cnt + F->close_chunk(); + + F->open_chunk(EB_Faces); + F->w(l_faces, sizeof(b_face) * l_face_it); //. l_face_cnt + F->close_chunk(); + + if (!Core.SocSdk) + { + F->open_chunk(EB_SmoothGroups); + F->w(l_smgroups, sizeof(u32) * l_face_it); //. l_face_cnt + F->close_chunk(); + } + + F->open_chunk(EB_Materials); + F->w(l_materials.data(), sizeof(b_material) * l_materials.size()); + F->close_chunk(); + + F->open_chunk(EB_Shaders_Render); + F->w(l_shaders.data(), sizeof(b_shader) * l_shaders.size()); + F->close_chunk(); + + F->open_chunk(EB_Shaders_Compile); + F->w(l_shaders_xrlc.data(), sizeof(b_shader) * l_shaders_xrlc.size()); + F->close_chunk(); + + F->open_chunk(EB_Textures); + F->w(l_textures.data(), sizeof(b_texture_real) * l_textures.size()); + F->close_chunk(); + + F->open_chunk(EB_Glows); + F->w(l_glows.data(), sizeof(b_glow) * l_glows.size()); + F->close_chunk(); + + F->open_chunk(EB_Portals); + F->w(l_portals.data(), sizeof(b_portal) * l_portals.size()); + F->close_chunk(); + + F->open_chunk(EB_Light_control); + for (xr_vector::iterator lc_it = l_light_control.begin(); lc_it != l_light_control.end(); lc_it++) + { + F->w(lc_it->name, sizeof(lc_it->name)); + F->w_u32(lc_it->data.size()); + F->w(lc_it->data.data(), sizeof(u32) * lc_it->data.size()); + } + F->close_chunk(); + + F->open_chunk(EB_Light_static); + F->w(l_light_static.data(), sizeof(b_light_static) * l_light_static.size()); + F->close_chunk(); + + F->open_chunk(EB_Light_dynamic); + F->w(l_light_dynamic.data(), sizeof(b_light_dynamic) * l_light_dynamic.size()); + F->close_chunk(); + + F->open_chunk(EB_LOD_models); + for (int k = 0; k < (int)l_lods.size(); ++k) + F->w(&l_lods[k].lod, sizeof(b_lod)); + F->close_chunk(); + + F->open_chunk(EB_MU_models); + + for (int k = 0; k < (int)l_mu_models.size(); ++k) + { + b_mu_model &m = l_mu_models[k]; + // name + F->w_stringZ(m.name); + // vertices + F->w_u32(m.m_iVertexCount); + F->w(m.m_pVertices, sizeof(b_vertex) * m.m_iVertexCount); + // faces + F->w_u32(m.m_iFaceCount); + F->w(m.m_pFaces, sizeof(b_face) * m.m_iFaceCount); + // lod_id + F->w_u16(m.lod_id); + + if (!Core.SocSdk) + F->w(m.m_smgroups, sizeof(int) * m.m_iFaceCount); + } + + F->close_chunk(); + + F->open_chunk(EB_MU_refs); + F->w(l_mu_refs.data(), sizeof(b_mu_reference) * l_mu_refs.size()); + F->close_chunk(); + + FS.w_close(F); +} + +int SceneBuilder::CalculateSector(const Fvector &P, float R) +{ + ObjectIt _F = Scene->FirstObj(OBJCLASS_SECTOR); + ObjectIt _E = Scene->LastObj(OBJCLASS_SECTOR); + for (; _F != _E; _F++) + { + CSector *_S = (CSector *)(*_F); + EVisible vis = _S->Intersect(P, R); + if ((vis == fvPartialInside) || (vis == fvFully)) + if (_S->m_sector_num != m_iDefaultSectorNum) + return _S->m_sector_num; + } + return m_iDefaultSectorNum; // �� ��������� +} + +void SceneBuilder::Clear() +{ + object_for_render = 0; + l_vert_cnt = 0; + l_face_cnt = 0; + l_vert_it = 0; + l_face_it = 0; + xr_free(l_verts); + xr_free(l_faces); + xr_free(l_smgroups); + + for (int k = 0; k < (int)l_mu_models.size(); k++) + { + b_mu_model &m = l_mu_models[k]; + xr_free(m.m_pVertices); + xr_free(m.m_pFaces); + xr_free(m.m_smgroups); + } + l_mu_models.clear(); + l_mu_refs.clear(); + l_lods.clear(); + l_light_static.clear(); + l_light_dynamic.clear(); + l_light_control.clear(); + l_textures.clear(); + l_shaders.clear(); + l_shaders_xrlc.clear(); + l_materials.clear(); + l_vnormals.clear(); + l_glows.clear(); + l_portals.clear(); + l_light_keys.clear(); + xr_delete(l_scene_stat); +} + +//------------------------------------------------------------------------------ +// CEditObject build functions +//------------------------------------------------------------------------------ +float CalcArea(const Fvector &v0, const Fvector &v1, const Fvector &v2) +{ + float e1 = v0.distance_to(v1); + float e2 = v0.distance_to(v2); + float e3 = v1.distance_to(v2); + + float p = (e1 + e2 + e3) / 2.f; + return _sqrt(p * (p - e1) * (p - e2) * (p - e3)); +} + +// const Fmatrix& parent, +BOOL GetStaticCformData(const Fmatrix &parent, CEditableMesh *mesh, CEditableObject *object, Fvector *verts, int &vert_cnt, int &vert_it, CDB::TRI *faces, int &face_cnt, int &face_it) +{ + + if (object->IsDynamic()) + return FALSE; + // Fmatrix parent = object->_Transform(); + + BOOL bResult = TRUE; + int point_offs = vert_it; // save offset + // fill vertices + for (u32 pt_id = 0; pt_id < mesh->GetVCount(); pt_id++) + { + R_ASSERT(vert_it < vert_cnt); + parent.transform_tiny(verts[vert_it++], mesh->Vertices()[pt_id]); + } + for (SurfFacesPairIt sp_it = mesh->Surfaces().begin(); sp_it != mesh->Surfaces().end(); sp_it++) + { + IntVec &face_lst = sp_it->second; + CSurface *surf = sp_it->first; + if (surf->m_GameMtlName == "materials\\occ") + continue; + + u16 game_material_idx = GMLib.GetMaterialIdx(surf->m_GameMtlName.c_str()); + + for (IntIt f_it = face_lst.begin(); f_it != face_lst.end(); ++f_it) + { + st_Face &face = mesh->Faces()[*f_it]; + float _a = CalcArea(mesh->Vertices()[face.pv[0].pindex], mesh->Vertices()[face.pv[1].pindex], mesh->Vertices()[face.pv[2].pindex]); + if (!_valid(_a) || (_a < EPS)) + { + continue; + } + R_ASSERT(face_it < face_cnt); + CDB::TRI &first_face = faces[face_it]; + { + + first_face.material = (u16)game_material_idx; + + for (int k = 0; k < 3; ++k) + { + st_FaceVert &fv = face.pv[k]; + // vertex index + R_ASSERT2((fv.pindex + point_offs) < vert_it, "Index out of range"); + first_face.verts[k] = fv.pindex + point_offs; + // uv maps + } + ++face_it; + if (surf->m_Flags.is(CSurface::sf2Sided)) + { + R_ASSERT(face_it < face_cnt); + CDB::TRI &second_face = faces[face_it]; + second_face.material = first_face.material; + for (int k = 0; k < 3; ++k) + { + st_FaceVert &fv = face.pv[2 - k]; + // vertex index + second_face.verts[k] = fv.pindex + point_offs; + // uv maps + } + ++face_it; + } + } + } + } + return bResult; +} + +BOOL SceneBuilder::BuildMesh(const Fmatrix &parent, + CEditableObject *object, + CEditableMesh *mesh, + int sect_num, + b_vertex *verts, + int &vert_cnt, + int &vert_it, + b_face *faces, + int &face_cnt, + int &face_it, + u32 *smgroups, + const Fmatrix &real_transform, + CSceneObject *obj) +{ + BOOL bResult = TRUE; + int point_offs; + point_offs = vert_it; // save offset + + // fill vertices + for (u32 pt_id = 0; pt_id < mesh->GetVCount(); pt_id++) + { + R_ASSERT(vert_it < vert_cnt); + parent.transform_tiny(verts[vert_it++], mesh->m_Vertices[pt_id]); + } + + if (object->IsDynamic()) + { + // update mesh + mesh->GenerateFNormals(); + mesh->GenerateAdjacency(); + Fvector N; + for (u32 pt = 0; pt < mesh->GetVCount(); pt++) + { + N.set(0, 0, 0); + IntVec &a_lst = (*mesh->m_Adjs)[pt]; + VERIFY(a_lst.size()); + for (IntIt i_it = a_lst.begin(); i_it != a_lst.end(); i_it++) + N.add((*mesh->m_FaceNormals)[*i_it]); + N.normalize_safe(); + parent.transform_dir(N); + l_vnormals.push_back(N); + } + // unload mesh normals + mesh->UnloadAdjacency(); + mesh->UnloadFNormals(); + } + // fill faces + for (SurfFacesPairIt sp_it = mesh->m_SurfFaces.begin(); sp_it != mesh->m_SurfFaces.end(); sp_it++) + { + IntVec &face_lst = sp_it->second; + CSurface *surf = nullptr; + for (size_t i = 0; i < mesh->Parent()->SurfaceCount(); i++) + { + if (mesh->Parent()->Surfaces()[i] == sp_it->first) + { + surf = obj->m_Surfaces[i]; + break; + } + } + VERIFY(surf); + if (surf->m_GameMtlName == "materials\\occ") + continue; + + int m_id = BuildMaterial(surf, sect_num, !object->IsMUStatic()); + int gm_id = surf->_GameMtl(); + if (m_id < 0) + { + bResult = FALSE; + break; + } + if (gm_id < 0) + { + ELog.DlgMsg(mtError, "Surface: '%s' contains bad game material.", surf->_Name()); + bResult = FALSE; + break; + } + SGameMtl *M = GMLib.GetMaterialByID(gm_id); + if (0 == M) + { + ELog.DlgMsg(mtError, "Surface: '%s' contains undefined game material.", surf->_Name()); + bResult = FALSE; + break; + } + if (M->Flags.is(SGameMtl::flBreakable)) + { + ELog.Msg(mtInformation, "Surface: '%s' contains breakable game material.", surf->_Name()); + continue; + } + if (M->Flags.is(SGameMtl::flClimable)) + { + ELog.Msg(mtInformation, "Surface: '%s' contains climable game material.", surf->_Name()); + continue; + } + if (M->Flags.is(SGameMtl::flDynamic)) + { + ELog.DlgMsg(mtError, "Surface: '%s' contains non-static game material.", surf->_Name()); + bResult = FALSE; + break; + } + u32 dwTexCnt = ((surf->_FVF() & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT); + if (dwTexCnt != 1) + { + ELog.DlgMsg(mtError, "Surface: '%s' contains more than 1 texture refs.", surf->_Name()); + bResult = FALSE; + break; + } + u32 dwInvalidFaces = 0; + for (IntIt f_it = face_lst.begin(); f_it != face_lst.end(); ++f_it) + { + st_Face &face = mesh->m_Faces[*f_it]; + Fvector p0, p1, p2; + real_transform.transform_tiny(p0, mesh->m_Vertices[face.pv[0].pindex]); + real_transform.transform_tiny(p1, mesh->m_Vertices[face.pv[1].pindex]); + real_transform.transform_tiny(p2, mesh->m_Vertices[face.pv[2].pindex]); + + float _a = CalcArea(p0, p1, p2); + if (!_valid(_a) || (_a < EPS_S)) + { + LTools->m_DebugDraw.AppendWireFace(p0, p1, p2); + + dwInvalidFaces++; + continue; + } + R_ASSERT(face_it < face_cnt); + b_face &first_face = faces[face_it]; + { + smgroups[face_it] = mesh->m_SmoothGroups[*f_it]; + smgroups[face_it] &= ~(1 << 3); + + first_face.dwMaterial = (u16)m_id; + first_face.dwMaterialGame = gm_id; + for (int k = 0; k < 3; ++k) + { + st_FaceVert &fv = face.pv[k]; + // vertex index + R_ASSERT2((fv.pindex + point_offs) < vert_it, "Index out of range"); + first_face.v[k] = fv.pindex + point_offs; + // uv maps + int offs = 0; + for (u32 t = 0; t < dwTexCnt; ++t) + { + st_VMapPt &vm_pt = mesh->m_VMRefs[fv.vmref].pts[t]; + st_VMap &vmap = *mesh->m_VMaps[vm_pt.vmap_index]; + if (vmap.type != vmtUV) + { + ++offs; + --t; + continue; + } + first_face.t[k].set(vmap.getUV(vm_pt.index)); + } + } + ++face_it; + } + + if (surf->m_Flags.is(CSurface::sf2Sided)) + { + R_ASSERT(face_it < face_cnt); + b_face &second_face = faces[face_it]; + second_face.dwMaterial = first_face.dwMaterial; + second_face.dwMaterialGame = first_face.dwMaterialGame; + smgroups[face_it] = mesh->m_SmoothGroups[*f_it]; + smgroups[face_it] |= (1 << 3); + + for (int k = 0; k < 3; ++k) + { + st_FaceVert &fv = face.pv[2 - k]; + // vertex index + second_face.v[k] = fv.pindex + point_offs; + // uv maps + int offs = 0; + for (u32 t = 0; t < dwTexCnt; t++) + { + st_VMapPt &vm_pt = mesh->m_VMRefs[fv.vmref].pts[t]; + st_VMap &vmap = *mesh->m_VMaps[vm_pt.vmap_index]; + if (vmap.type != vmtUV) + { + ++offs; + --t; + continue; + } + second_face.t[k].set(vmap.getUV(vm_pt.index)); + } + } + ++face_it; + } + } + if (dwInvalidFaces) + Msg("!Object '%s' - '%s' has %d invalid face(s). Removed.", object->GetName(), mesh->Name().c_str(), dwInvalidFaces); + + if (!bResult) + break; + } + return bResult; +} + +BOOL SceneBuilder::BuildObject(CSceneObject *obj) +{ + CEditableObject *O = obj->GetReference(); + auto temp = make_string("Building object: %s", obj->GetName()); + UI->SetStatus(temp.c_str()); + + Fmatrix T = obj->_Transform(); + Fmatrix cv = Fidentity; + + if (m_save_as_object) + { + cv.k.z = -1.f; + + Fmatrix TM; + + TM.mul(Fmatrix().mul(cv, T), cv); + TM.mulB_44(cv); + T = TM; + } + + // parse mesh data + for (EditMeshIt M = O->FirstMesh(); M != O->LastMesh(); M++) + { + CSector *S = PortalUtils.FindSector(obj, *M); + int sect_num = S ? S->m_sector_num : m_iDefaultSectorNum; + if (!BuildMesh(T, O, *M, sect_num, l_verts, l_vert_cnt, l_vert_it, l_faces, l_face_cnt, l_face_it, l_smgroups, obj->_Transform(), obj)) + return FALSE; + // fill DI vertices + for (u32 pt_id = 0; pt_id < (*M)->GetVCount(); pt_id++) + { + Fvector v_res1, v_res2; + const Fvector &v_src = (*M)->m_Vertices[pt_id]; + + Fvector tmp; + cv.transform_tiny(tmp, v_src); + T.transform_tiny(v_res1, tmp); + + l_scene_stat->add_svert(v_res1); + } + } + return TRUE; +} + +int GetModelIdx(LPCSTR model_name) +{ + int model_idx = -1; + + for (int k = 0; k < (int)Builder.l_mu_models.size(); k++) + { + b_mu_model &m = Builder.l_mu_models[k]; + if (0 == strcmp(m.name, model_name)) + { + model_idx = k; + break; + } + } + return model_idx; +} + +// BOOL GetMuStaticCformData( CSceneObject* obj,mesh_build_data &data, bool b_selected_only ) +//{ +// CEditableObject *O = obj->GetReference(); +// int model_idx = GetModelIdx(O->GetName()); +// detect sector +// CSector* S = PortalUtils.FindSector(obj,*O->FirstMesh()); +// int sect_num = S?S->m_sector_num:Builder.m_iDefaultSectorNum; +//} + +BOOL SceneBuilder::BuildMUObject(CSceneObject *obj) +{ + CEditableObject *O = obj->GetReference(); + auto temp = make_string("Building object: %s", obj->GetName()); + UI->SetStatus(temp.c_str()); + + int model_idx = GetModelIdx(O->GetName()); + + // detect sector + CSector *S = PortalUtils.FindSector(obj, *O->FirstMesh()); + int sect_num = S ? S->m_sector_num : m_iDefaultSectorNum; + + // build model + if (-1 == model_idx || m_save_as_object) + { + // build LOD + int lod_id = BuildObjectLOD(Fidentity, O, sect_num); + if (lod_id == -2) + return FALSE; + // build model + model_idx = l_mu_models.size(); + l_mu_models.push_back(b_mu_model()); + b_mu_model &M = l_mu_models.back(); + M.lod_id = (u16)lod_id; + int vert_it = 0, face_it = 0; + + M.m_iFaceCount = obj->GetFaceCount(); + M.m_iVertexCount = obj->GetVertexCount(); + strcpy(M.name, O->GetName()); + + M.m_pFaces = xr_alloc(M.m_iFaceCount); + M.m_pVertices = xr_alloc(M.m_iVertexCount); + M.m_smgroups = xr_alloc(M.m_iFaceCount); + // parse mesh data + Fmatrix T; + T.identity(); + + if (m_save_as_object) + { + T = obj->_Transform(); + + Fmatrix cv = Fidentity; + + cv.k.z = -1.f; + + Fmatrix TM; + + TM.mul(Fmatrix().mul(cv, T), cv); + TM.mulB_44(cv); + T = TM; + } + + for (EditMeshIt MESH = O->FirstMesh(); MESH != O->LastMesh(); ++MESH) + if (!BuildMesh(T, O, *MESH, sect_num, M.m_pVertices, M.m_iVertexCount, vert_it, M.m_pFaces, M.m_iFaceCount, face_it, M.m_smgroups, obj->_Transform(), obj)) + return FALSE; + + M.m_iFaceCount = face_it; + M.m_iVertexCount = vert_it; + } + + l_mu_refs.push_back(b_mu_reference()); + b_mu_reference &R = l_mu_refs.back(); + R.model_index = model_idx; + R.transform = obj->_Transform(); + R.flags.zero(); + R.sector = (u16)sect_num; + + // scene statssm + b_mu_model &M = l_mu_models[model_idx]; + + for (u32 mu_vi = 0; mu_vi < (u32)M.m_iVertexCount; ++mu_vi) + l_scene_stat->add_muvert(obj->_Transform(), M.m_pVertices[mu_vi]); + + return TRUE; +} + +//------------------------------------------------------------------------------ +// light build functions +//------------------------------------------------------------------------------ +int SceneBuilder::BuildLightControl(LPCSTR name) +{ + for (u32 k = 0; k < l_light_control.size(); k++) + { + sb_light_control &b = l_light_control[k]; + if (0 == strcmp(b.name, name)) + return k; + } + l_light_control.push_back(sb_light_control()); + sb_light_control &b = l_light_control.back(); + strcpy(b.name, name); + return l_light_control.size() - 1; +} + +struct SHemiData +{ + SceneBuilder::BLVec *dest; + SceneBuilder::SBuildLight T; +}; +void hemi_callback(float x, float y, float z, float E, LPVOID P) +{ + SHemiData *H = (SHemiData *)P; + H->T.energy = E; + H->T.light.direction.set(x, y, z); + H->dest->push_back(H->T); +} +void SceneBuilder::BuildHemiLights(u8 quality, LPCSTR lcontrol) +{ + BLVec dest; + Flight RL; + // set def params + RL.type = Flight::Type::Directional; + RL.diffuse.set(1.f, 1.f, 1.f, 1.f); + if (quality) + { + SHemiData h_data; + h_data.dest = &dest; + h_data.T.light = RL; + xrHemisphereBuild(quality, 2.f, hemi_callback, &h_data); //. hack + int control_ID = BuildLightControl(lcontrol); + for (BLIt it = dest.begin(); it != dest.end(); it++) + { + l_light_static.push_back(b_light_static()); + b_light_static &sl = l_light_static.back(); + sl.controller_ID = control_ID; + sl.data = it->light; + sl.data.mul(it->energy); + } + } + else + { + int control_ID = BuildLightControl(lcontrol); + l_light_static.push_back(b_light_static()); + b_light_static &sl = l_light_static.back(); + sl.controller_ID = control_ID; + sl.data.type = Flight::Type::Directional; + sl.data.diffuse.set(1.f, 1.f, 1.f, 1.f); + sl.data.direction.set(0.f, -1.f, 0.f); + } +} +BOOL SceneBuilder::BuildSun(u8 quality, Fvector2 dir) +{ + int controller_ID = BuildLightControl(LCONTROL_SUN); + // static + // soft light + int samples; + switch (quality) + { + case 0: + samples = 1; + break; + case 1: + samples = 3; + break; + case 2: + samples = 4; + break; + case 3: + samples = 7; + break; + default: + THROW2("Invalid case."); + } + + Fcolor color; + color.set(1.f, 1.f, 1.f, 1.f); + float sample_energy = 1.f / float(samples * samples); + color.mul_rgb(sample_energy); + + float disp = deg2rad(3.f); // dispersion of sun + float da = disp / float(samples); + float mn_x = dir.x - disp / 2; + float mn_y = dir.y - disp / 2; + for (int x = 0; x < samples; x++) + { + float fx = mn_x + x * da; + for (int y = 0; y < samples; y++) + { + float fy = mn_y + y * da; + l_light_static.push_back(b_light_static()); + b_light_static &sl = l_light_static.back(); + sl.controller_ID = controller_ID; + sl.data.type = Flight::Type::Directional; + sl.data.position.set(0, 0, 0); + sl.data.diffuse.set(color); + sl.data.direction.setHP(fy, fx); + } + } + // dynamic + { + l_light_dynamic.push_back(b_light_dynamic()); + b_light_dynamic &dl = l_light_dynamic.back(); + dl.controller_ID = controller_ID; + dl.data.type = Flight::Type::Directional; + dl.data.position.set(0, 0, 0); + dl.data.diffuse.set(1.f, 1.f, 1.f, 1.f); + dl.data.direction.setHP(dir.y, dir.x); + } + + return TRUE; +} + +BOOL SceneBuilder::BuildPointLight(b_light *b, const Flags32 &usage, svector *sectors, FvectorVec *soft_points, const Fmatrix *soft_transform) +{ + if (usage.is(ELight::flAffectStatic)) + { + if (soft_points && !soft_points->empty()) + { + R_ASSERT(soft_transform); + // make soft light + Fcolor color = b->data.diffuse; + color.normalize_rgb(b->data.diffuse); + float sample_energy = (b->data.diffuse.magnitude_rgb()) / float(soft_points->size()); + color.mul_rgb(sample_energy); + + for (u32 k = 0; k < soft_points->size(); k++) + { + l_light_static.push_back(b_light_static()); + b_light_static &sl = l_light_static.back(); + sl.controller_ID = b->controller_ID; + sl.data = b->data; + sl.data.diffuse.set(color); + soft_transform->transform_tiny(sl.data.position, (*soft_points)[k]); + } + } + else + { + // make single light + l_light_static.push_back(b_light_static()); + b_light_static &sl = l_light_static.back(); + sl.controller_ID = b->controller_ID; + sl.data = b->data; + } + } + if (usage.is(ELight::flAffectDynamic)) + { + R_ASSERT(sectors); + l_light_dynamic.push_back(b_light_dynamic()); + b_light_dynamic &dl = l_light_dynamic.back(); + dl.controller_ID = b->controller_ID; + dl.data = b->data; + dl.sectors = *sectors; + } + + return TRUE; +} + +BOOL SceneBuilder::BuildLight(CLight *e) +{ + if (!e->m_Flags.is_any(ELight::flAffectStatic | ELight::flAffectDynamic)) + return FALSE; + + if (!e->GetLControlName()) + { + ELog.Msg(mtError, "Invalid light control name: light '%s'.", e->GetName()); + return FALSE; + } + + b_light L; + L.data.type = static_cast(e->m_Type); + L.data.diffuse.mul_rgb(e->m_Color, e->m_Brightness); + L.data.position.set(e->GetPosition()); + Fvector dir; + dir.setHP(e->GetRotation().y, e->GetRotation().x); + L.data.direction.set(dir); + L.data.range = e->m_Range; + L.data.attenuation0 = e->m_Attenuation0; + L.data.attenuation1 = e->m_Attenuation1; + L.data.attenuation2 = e->m_Attenuation2; + L.data.phi = e->m_Cone; + + L.controller_ID = BuildLightControl(e->GetLControlName()); // BuildLightControl(LCONTROL_STATIC); + + svector *lpSectors = nullptr; + if (e->m_Flags.is(ELight::flAffectDynamic)) + { + svector sectors; + lpSectors = §ors; + Fvector pos = e->GetPosition(); + float &range = e->m_Range; + if (Scene->ObjCount(OBJCLASS_SECTOR)) + { + // test fully and partial inside + ObjectIt _F = Scene->FirstObj(OBJCLASS_SECTOR); + ObjectIt _E = Scene->LastObj(OBJCLASS_SECTOR); + for (; _F != _E; _F++) + { + if (sectors.size() >= 16) + break; + CSector *_S = (CSector *)(*_F); + EVisible vis = _S->Intersect(pos, range); + if ((vis == fvPartialInside) || (vis == fvFully)) + sectors.push_back((u16)_S->m_sector_num); + } + // test partial outside + _F = Scene->FirstObj(OBJCLASS_SECTOR); + for (; _F != _E; _F++) + { + if (sectors.size() >= 16) + break; + CSector *_S = (CSector *)(*_F); + EVisible vis = _S->Intersect(pos, range); + if (vis == fvPartialOutside) + sectors.push_back((u16)_S->m_sector_num); + } + if (sectors.empty()) + return FALSE; + } + else + { + sectors.push_back((u16)m_iDefaultSectorNum); + } + } + + switch (e->m_Type) + { + case ELight::ltPoint: + return BuildPointLight(&L, e->m_Flags, lpSectors, e->m_FuzzyData ? &e->m_FuzzyData->m_Positions : 0, &e->_Transform()); + default: + THROW2("Invalid light type."); + return FALSE; + } +} +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Glow build functions +//------------------------------------------------------------------------------ +BOOL SceneBuilder::BuildGlow(CGlow *e) +{ + l_glows.push_back(b_glow()); + b_glow &b = l_glows.back(); + // material + b_material mtl; + ZeroMemory(&mtl, sizeof(mtl)); + int mtl_idx; + VERIFY(e->m_ShaderName.size()); + mtl.surfidx = (u16)BuildTexture(*e->m_TexName); + mtl.shader = (u16)BuildShader(*e->m_ShaderName); + mtl.sector = (u16)CalculateSector(e->GetPosition(), e->m_fRadius); + mtl.shader_xrlc = -1; + if ((u16(-1) == mtl.surfidx) || (u16(-1) == mtl.shader)) + return FALSE; + + mtl_idx = FindInMaterials(&mtl); + if (mtl_idx < 0) + { + l_materials.push_back(mtl); + mtl_idx = l_materials.size() - 1; + } + + // fill params + b.P.set(e->GetPosition()); + b.size = e->m_fRadius; + b.dwMaterial = mtl_idx; + b.flags = e->m_Flags.is(CGlow::gfFixedSize) ? 0x01 : 0x00; // 0x01 - non scalable + return TRUE; +} +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Portal build functions +//------------------------------------------------------------------------------ +void SceneBuilder::BuildPortal(b_portal *b, CPortal *e) +{ + b->sector_front = (u16)e->m_SectorFront->m_sector_num; + b->sector_back = (u16)e->m_SectorBack->m_sector_num; + b->vertices.resize(e->m_SimplifyVertices.size()); + CopyMemory(b->vertices.begin(), e->m_SimplifyVertices.data(), e->m_SimplifyVertices.size() * sizeof(Fvector)); +} + +//------------------------------------------------------------------------------ +// shader build functions +//------------------------------------------------------------------------------ +int SceneBuilder::FindInShaders(b_shader *s) +{ + for (u32 i = 0; i < l_shaders.size(); i++) + if (strcmp(l_shaders[i].name, s->name) == 0) + return i; + return -1; +} +//------------------------------------------------------------------------------ + +int SceneBuilder::BuildShader(const char *s) +{ + b_shader sh; + strcpy(sh.name, s); + int sh_id = FindInShaders(&sh); + if (sh_id < 0) + { + if (!EDevice.Resources->_FindBlender(sh.name)) + { + ELog.DlgMsg(mtError, "Can't find engine shader: %s", sh.name); + return -1; + } + l_shaders.push_back(sh); + return l_shaders.size() - 1; + } + return sh_id; +} +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// shader xrlc build functions +//------------------------------------------------------------------------------ +int SceneBuilder::FindInShadersXRLC(b_shader *s) +{ + for (u32 i = 0; i < l_shaders_xrlc.size(); i++) + if (strcmp(l_shaders_xrlc[i].name, s->name) == 0) + return i; + return -1; +} +//------------------------------------------------------------------------------ + +int SceneBuilder::BuildShaderXRLC(const char *s) +{ + b_shader sh; + strcpy(sh.name, s); + int sh_id = FindInShadersXRLC(&sh); + if (sh_id < 0) + { + if (!EDevice.ShaderXRLC.Get(sh.name)) + { + ELog.DlgMsg(mtError, "Can't find compiler shader: %s", sh.name); + return -1; + } + l_shaders_xrlc.push_back(sh); + return l_shaders_xrlc.size() - 1; + } + return sh_id; +} +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// texture build functions +//------------------------------------------------------------------------------ +int SceneBuilder::FindInTextures(const char *name) +{ + for (u32 i = 0; i < l_textures.size(); i++) + if (stricmp(l_textures[i].name, name) == 0) + return i; + return -1; +} +//------------------------------------------------------------------------------ + +int SceneBuilder::BuildTexture(const char *name) +{ + if (!(name && name[0])) + { + ELog.DlgMsg(mtError, "Invalid texture name found."); + return -1; + } + int tex_idx = FindInTextures(name); + if (tex_idx < 0) + { + b_texture_real tex; + ZeroMemory(&tex, sizeof(tex)); + strcpy(tex.name, name); + l_textures.push_back(tex); + tex_idx = l_textures.size() - 1; + } + return tex_idx; +} +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// material build functions +//------------------------------------------------------------------------------ +int SceneBuilder::FindInMaterials(b_material *m) +{ + for (u32 i = 0; i < l_materials.size(); i++) + { + if ((l_materials[i].surfidx == m->surfidx) && + (l_materials[i].shader == m->shader) && + (l_materials[i].shader_xrlc == m->shader_xrlc) && + (l_materials[i].sector == m->sector)) + return i; + } + return -1; +} +//------------------------------------------------------------------------------ + +int SceneBuilder::BuildMaterial(CSurface *surf, int sector_num, bool allow_draft) +{ + return BuildMaterial(surf->_ShaderName(), surf->_ShaderXRLCName(), surf->_Texture(), ((surf->_FVF() & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT), sector_num, allow_draft); +} +int SceneBuilder::BuildMaterial(LPCSTR esh_name, LPCSTR csh_name, LPCSTR tx_name, u32 tx_cnt, int sector_num, bool allow_draft) +{ + b_material mtl; + ZeroMemory(&mtl, sizeof(mtl)); + VERIFY(sector_num >= 0); + int mtl_idx; + VERIFY(tx_cnt == 1); + + if (allow_draft && (Scene->m_LevelOp.m_BuildParams.m_quality == ebqDraft)) + { + Shader_xrLC *c_sh = EDevice.ShaderXRLC.Get(csh_name); + if (c_sh->flags.bRendering) + { + mtl.shader = (u16)BuildShader("def_shaders\\def_vertex"); + mtl.shader_xrlc = (u16)BuildShaderXRLC("def_shaders\\def_vertex"); + } + else + { + mtl.shader = (u16)BuildShader(esh_name); + mtl.shader_xrlc = (u16)BuildShaderXRLC(csh_name); + } + } + else + { + mtl.shader = (u16)BuildShader(esh_name); + mtl.shader_xrlc = (u16)BuildShaderXRLC(csh_name); + } + mtl.sector = (u16)sector_num; + mtl.surfidx = (u16)BuildTexture(tx_name); + if ((u16(-1) == mtl.shader) || (u16(-1) == mtl.shader_xrlc) || (u16(-1) == mtl.surfidx)) + return -1; + + mtl_idx = FindInMaterials(&mtl); + if (mtl_idx < 0) + { + l_materials.push_back(mtl); + mtl_idx = l_materials.size() - 1; + } + return mtl_idx; +} +//------------------------------------------------------------------------------ + +BOOL SceneBuilder::ParseStaticObjects(ObjectList &lst, LPCSTR prefix, bool b_selected_only) +{ + BOOL bResult = TRUE; + SPBItem *pb = UI->ProgressStart(static_cast(lst.size()), "Parse static objects..."); + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + { + pb->Inc((*_F)->GetName()); + if (UI->NeedAbort()) + break; + if (b_selected_only && !(*_F)->Selected()) + continue; + + switch ((*_F)->FClassID) + { + case OBJCLASS_LIGHT: + bResult = BuildLight((CLight *)(*_F)); + break; + case OBJCLASS_GLOW: + bResult = BuildGlow((CGlow *)(*_F)); + break; + case OBJCLASS_PORTAL: + l_portals.push_back(b_portal()); + BuildPortal(&l_portals.back(), (CPortal *)(*_F)); + break; + case OBJCLASS_SCENEOBJECT: + { + CSceneObject *obj = (CSceneObject *)(*_F); + if (obj->IsStatic()) + bResult = BuildObject(obj); + else if (obj->IsMUStatic()) + bResult = BuildMUObject(obj); + } + break; + /* case OBJCLASS_GROUP:{ + CGroupObject* group = (CGroupObject*)(*_F); + + ObjectList grp_lst; + group->GetObjects (grp_lst); + + bResult = ParseStaticObjects(grp_lst, group->Name, b_selected_only); + }break; */ + } // end switch + if (!bResult) + { + ELog.DlgMsg(mtError, "Failed to build object: '%s'", (*_F)->GetName()); + break; + } + } + UI->ProgressEnd(pb); + return bResult; +} +//------------------------------------------------------------------------------ + +BOOL SceneBuilder::CompileStatic(bool b_selected_only) +{ + ObjClassID cls = LTools->CurrentClassID(); + if (cls == OBJCLASS_DUMMY) + return FALSE; + ESceneToolBase *pCurrentTool = Scene->GetOTool(cls); + + BOOL bResult = TRUE; + + Clear(); + + SceneToolsMapPairIt t_it = Scene->FirstTool(); + SceneToolsMapPairIt t_end = Scene->LastTool(); + + if (b_selected_only) + { + if (pCurrentTool) + pCurrentTool->CompileStaticStart(); + } + else + { + for (; t_it != t_end; ++t_it) + { + ESceneToolBase *mt = t_it->second; + if (mt) + mt->CompileStaticStart(); + } + } + int objcount = Scene->ObjCount(); + if (objcount <= 0) + return FALSE; + + // compute vertex/face count + l_vert_cnt = 0; + l_face_cnt = 0; + l_vert_it = 0; + l_face_it = 0; + + if (b_selected_only) + { + if (pCurrentTool) + pCurrentTool->GetStaticDesc(l_vert_cnt, l_face_cnt, b_selected_only, false); + } + else + { + t_it = Scene->FirstTool(); + t_end = Scene->LastTool(); + for (; t_it != t_end; ++t_it) + { + ESceneToolBase *mt = t_it->second; + if (mt) + mt->GetStaticDesc(l_vert_cnt, l_face_cnt, b_selected_only, false); + } + } + l_faces = xr_alloc(l_face_cnt); + l_smgroups = xr_alloc(l_face_cnt); + l_verts = xr_alloc(l_vert_cnt); + + l_scene_stat = xr_new(m_LevelBox); + + // make hemisphere + ESceneLightTool *lt = dynamic_cast(Scene->GetOTool(OBJCLASS_LIGHT)); + LPCSTR h_control = *lt->FindLightControl(lt->m_HemiControl)->name; + BuildHemiLights(Scene->m_LevelOp.m_LightHemiQuality, h_control); + if (0 != strcmp(LCONTROL_HEMI, h_control)) + BuildHemiLights(Scene->m_LevelOp.m_LightHemiQuality, LCONTROL_HEMI); + // make sun + BuildSun(Scene->m_LevelOp.m_LightSunQuality, lt->m_SunShadowDir); + // parse scene + SPBItem *pb = UI->ProgressStart(static_cast(Scene->ObjCount()), "Parse scene objects..."); + + if (b_selected_only) + { + if (pCurrentTool) + if (!pCurrentTool->ExportStatic(this, b_selected_only)) + { + bResult = FALSE; + } + } + else + { + t_it = Scene->FirstTool(); + t_end = Scene->LastTool(); + for (; t_it != t_end; ++t_it) + { + ESceneToolBase *mt = t_it->second; + if (mt) + if (!mt->ExportStatic(this, b_selected_only)) + { + bResult = FALSE; + break; + } + } + } + UI->ProgressEnd(pb); + // process lods + if (bResult && !l_lods.empty()) + { + SPBItem *pb = UI->ProgressStart(static_cast(l_lods.size() * 2), "Merge LOD textures..."); + Fvector2Vec offsets; + Fvector2Vec scales; + boolVec rotated; + U32Vec remap; + SSimpleImageVec images; + for (int k = 0; k < (int)l_lods.size(); ++k) + { + images.push_back(SSimpleImage()); + SSimpleImage &I = images.back(); + I.name = l_lods[k].lod_name; + I.layers.push_back(l_lods[k].data); + I.layers.push_back(l_lods[k].ndata); + I.w = LOD_IMAGE_SIZE * LOD_SAMPLE_COUNT; + I.h = LOD_IMAGE_SIZE; + pb->Inc(); + } + + SSimpleImage merged_image; + xr_string fn_color = ChangeFileExt(MakeLevelPath(LEVEL_LODS_TEX_NAME).c_str(), ".dds").c_str(); + xr_string fn_normal = ChangeFileExt(MakeLevelPath(LEVEL_LODS_NRM_NAME).c_str(), ".dds").c_str(); + if (1 == ImageLib.CreateMergedTexture(2, images, merged_image, 512, 4096, 64, 4096, offsets, scales, rotated, remap)) + { + // all right, make texture + STextureParams tp; + tp.width = merged_image.w; + tp.height = merged_image.h; + tp.fmt = STextureParams::tfDXT5; + tp.type = STextureParams::ttImage; + tp.mip_filter = STextureParams::kMIPFilterAdvanced; + tp.flags.assign(STextureParams::flDitherColor); + ImageLib.MakeGameTexture(fn_color.c_str(), merged_image.layers[0].data(), tp); + ImageLib.MakeGameTexture(fn_normal.c_str(), merged_image.layers[1].data(), tp); + for (int k = 0; k < (int)l_lods.size(); k++) + { + e_b_lod &l = l_lods[k]; + for (u32 f = 0; f < 8; f++) + { + for (u32 t = 0; t < 4; t++) + { + Fvector2 &uv = l.lod.faces[f].t[t]; + u32 id = remap[k]; + ImageLib.MergedTextureRemapUV(uv.x, uv.y, uv.x, uv.y, offsets[id], scales[id], rotated[id]); + } + } + pb->Inc(); + } + } + else + { + ELog.DlgMsg(mtError, "Failed to build merged LOD texture. Merged texture more than [4096x4096]."); + bResult = FALSE; + } + UI->ProgressEnd(pb); + } + + // save build + if (bResult && !UI->NeedAbort()) + { + if (m_save_as_object) + SaveBuildAsObject(); + else + SaveBuild(); + } + + if (b_selected_only) + { + if (pCurrentTool) + pCurrentTool->CompileStaticEnd(); + } + else + { + t_it = Scene->FirstTool(); + t_end = Scene->LastTool(); + for (; t_it != t_end; ++t_it) + { + ESceneToolBase *mt = t_it->second; + if (mt) + mt->CompileStaticEnd(); + } + } + return bResult; +} + +BOOL SceneBuilder::BuildSceneStat() +{ + xr_string dest_name = MakeLevelPath(LEVEL_DI_TEX_NAME); + return l_scene_stat->flush(dest_name.c_str()); +} diff --git a/src/editors/LevelEditor/Engine/ShapeData.h b/src/editors/LevelEditor/Engine/ShapeData.h new file mode 100644 index 00000000000..5d47a26aba7 --- /dev/null +++ b/src/editors/LevelEditor/Engine/ShapeData.h @@ -0,0 +1,25 @@ +#ifndef ShapeDataH +#define ShapeDataH + +struct CShapeData +{ + enum + { + cfSphere = 0, + cfBox + }; + union shape_data + { + Fsphere sphere; + Fmatrix box; + }; + struct shape_def + { + u8 type; + shape_data data; + }; + DEFINE_VECTOR(shape_def, ShapeVec, ShapeIt); + ShapeVec shapes; +}; + +#endif \ No newline at end of file diff --git a/src/editors/LevelEditor/Engine/communicate.h b/src/editors/LevelEditor/Engine/communicate.h new file mode 100644 index 00000000000..ba99e9cfd70 --- /dev/null +++ b/src/editors/LevelEditor/Engine/communicate.h @@ -0,0 +1,246 @@ +#pragma once + +#pragma pack(push, 4) + +const u32 XR_MAX_PORTAL_VERTS = 6; + +// internal use +struct b_rc_face +{ + u16 dwMaterial; + u32 dwMaterialGame; + Fvector2 t[3]; // TC + u16 reserved; +}; +// All types to interact with xrLC +typedef Fvector b_vertex; + +struct b_face +{ + u32 v[3]; // vertices + Fvector2 t[3]; // TC + u16 dwMaterial; // index of material + u32 dwMaterialGame; // unique-ID of game material +}; + +struct b_material +{ + u16 surfidx; // indices of texture surface + u16 shader; // index of shader that combine them + u16 shader_xrlc; // compiler options + u16 sector; // *** + u16 reserved; // + u32 internal_max_area; // +}; + +struct b_shader +{ + string128 name; +}; +struct b_texture_real +{ + string128 name; + u32 dwWidth; + u32 dwHeight; + BOOL bHasAlpha; + u32 RESERVE; +}; + +struct b_texture +{ + string128 name; + u32 dwWidth; + u32 dwHeight; + BOOL bHasAlpha; +#ifndef _EDITOR + BearImage pSurface; +#endif +}; + +struct b_light_control // controller or "layer", 30fps +{ + string64 name; // empty for base layer + u32 count; // 0 for base layer + // u32 data[]; +}; + +struct b_light +{ + u32 controller_ID; // 0 = base layer + Flight data; +}; + +struct b_light_static : public b_light // For static lighting +{ +}; + +struct b_light_dynamic : public b_light // For dynamic models +{ + svector sectors; +}; + +struct b_glow +{ + Fvector P; + float size; + u32 flags; // 0x01 = non scalable + u32 dwMaterial; // index of material +}; + +struct b_portal +{ + u16 sector_front; + u16 sector_back; + svector vertices; +}; + +struct b_lod_face +{ + Fvector v[4]; + Fvector2 t[4]; +}; + +struct b_lod +{ + b_lod_face faces[8]; + u32 dwMaterial; +}; + +/* + u32 NUMBER-OF-OBJECTS + + stringZ name + u32 vert_count + b_vertex vertices[] + u32 face_count + b_faces faces[] + u16 lod_id; // u16(-1) = no lod, just static geometry +*/ +struct b_mu_model +{ + string128 name; + int m_iVertexCount; + b_vertex *m_pVertices; + int m_iFaceCount; + b_face *m_pFaces; + u32 *m_smgroups; + u16 lod_id; // u16(-1) = no lod, just static geometry +}; + +/* + self-describing +*/ +struct b_mu_reference +{ + u32 model_index; + Fmatrix transform; + Flags32 flags; + u16 sector; + u32 reserved[8]; +}; + +struct b_params +{ + // Normals & optimization + float m_sm_angle; // normal smooth angle - 89.0 + float m_weld_distance; // by default 0.005f - 5mm + + // Light maps + float m_lm_pixels_per_meter; // LM - by default: 4 ppm + u32 m_lm_jitter_samples; // 1/4/9 - by default - 4 + u32 m_lm_rms_zero; // RMS - after what the lightmap will be shrinked to ZERO pixels + u32 m_lm_rms; // RMS - shrink and recalc + + // build quality + u16 m_quality; + u16 u_reserved; + + // Progressive + float f_reserved[6]; + + void SaveLTX(CInifile &ini) + { + LPCSTR section = "build_params"; + ini.w_float(section, "smooth_angle", m_sm_angle); + ini.w_float(section, "weld_distance", m_weld_distance); + ini.w_float(section, "light_pixel_per_meter", m_lm_pixels_per_meter); + ini.w_u32(section, "light_jitter_samples", m_lm_jitter_samples); + ini.w_u32(section, "light_rms_zero", m_lm_rms_zero); + ini.w_u32(section, "light_rms", m_lm_rms); + ini.w_u16(section, "light_quality", m_quality); + ini.w_u16(section, "light_quality_reserved", u_reserved); + for (u32 i = 0; i < 6; ++i) + { + string128 buff; + xr_sprintf(buff, sizeof(buff), "reserved_%d", i); + ini.w_float(section, buff, f_reserved[i]); + } + } + void LoadLTX(CInifile &ini) + { + LPCSTR section = "build_params"; + m_sm_angle = ini.r_float(section, "smooth_angle"); + m_weld_distance = ini.r_float(section, "weld_distance"); + m_lm_pixels_per_meter = ini.r_float(section, "light_pixel_per_meter"); + m_lm_jitter_samples = ini.r_u32(section, "light_jitter_samples"); + m_lm_rms_zero = ini.r_u32(section, "light_rms_zero"); + m_lm_rms = ini.r_u32(section, "light_rms"); + m_quality = ini.r_u16(section, "light_quality"); + u_reserved = ini.r_u16(section, "light_quality_reserved"); + for (u32 i = 0; i < 6; ++i) + { + string128 buff; + xr_sprintf(buff, sizeof(buff), "reserved_%d", i); + f_reserved[i] = ini.r_float(section, buff); + } + } + + void Init() + { + // Normals & optimization + m_sm_angle = 75.f; + m_weld_distance = 0.005f; + + // Light maps + m_lm_rms_zero = 4; + m_lm_rms = 4; + + setHighQuality(); + } + void setDraftQuality() + { + m_quality = ebqDraft; + m_lm_pixels_per_meter = 0.1f; + m_lm_jitter_samples = 1; + } + void setHighQuality() + { + m_quality = ebqHigh; + m_lm_pixels_per_meter = 10; + m_lm_jitter_samples = 9; + } +}; +#pragma pack(pop) + +enum EBUILD_CHUNKS +{ + EB_Version = 0, // XRCLC_CURRENT_VERSION + EB_Parameters, + EB_Vertices, + EB_Faces, + EB_Materials, + EB_Shaders_Render, + EB_Shaders_Compile, + EB_Textures, + EB_Glows, + EB_Portals, + EB_Light_control, + EB_Light_static, + EB_Light_dynamic, + EB_LOD_models, + EB_MU_models, + EB_MU_refs, + EB_SmoothGroups, + + EB_FORCE_DWORD = u32(-1) +}; diff --git a/src/editors/LevelEditor/Entry/CustomObject.cpp b/src/editors/LevelEditor/Entry/CustomObject.cpp new file mode 100644 index 00000000000..b356636231d --- /dev/null +++ b/src/editors/LevelEditor/Entry/CustomObject.cpp @@ -0,0 +1,314 @@ +#include "stdafx.h" + +#define CUSTOMOBJECT_CHUNK_PARAMS 0xF900 +#define CUSTOMOBJECT_CHUNK_LOCK 0xF902 +#define CUSTOMOBJECT_CHUNK_TRANSFORM 0xF903 +#define CUSTOMOBJECT_CHUNK_GROUP 0xF904 +#define CUSTOMOBJECT_CHUNK_MOTION 0xF905 +#define CUSTOMOBJECT_CHUNK_FLAGS 0xF906 +#define CUSTOMOBJECT_CHUNK_NAME 0xF907 +#define CUSTOMOBJECT_CHUNK_MOTION_PARAM 0xF908 + +enum class SocFlags : u32 +{ + flSelected = (1 << 0), + flVisible = (1 << 1), + flLocked = (1 << 2), + flMotion = (1 << 3), + + flAutoKey = (1 << 30), + flCameraView = (1ul << 31), +}; + +CCustomObject::CCustomObject(LPVOID data, LPCSTR name) +{ + save_id = 0; + FClassID = OBJCLASS_DUMMY; + + FParentTools = nullptr; + + if (name) + FName = name; + + m_CO_Flags.assign(0); + m_RT_Flags.assign(flRT_Valid | flRT_Visible); + m_pOwnerObject = 0; + ResetTransform(); + m_RT_Flags.set(flRT_UpdateTransform, TRUE); + m_Motion = nullptr; + m_MotionParams = nullptr; + + FPosition.set(0, 0, 0); + FScale.set(1, 1, 1); + FRotation.set(0, 0, 0); +} + +CCustomObject::~CCustomObject() +{ + xr_delete(m_Motion); + xr_delete(m_MotionParams); +} + +bool CCustomObject::IsRender() +{ + Fbox bb; + GetBox(bb); + + float distance = 0.f; + Fvector center; + + bb.getcenter(center); + distance = center.distance_to(EDevice.vCameraPosition); + + if (distance > bb.getradius() + EDevice.RadiusRender) + return false; + + return ::Render->occ_visible(bb) || (Selected() && m_CO_Flags.is_any(flRenderAnyWayIfSelected | flMotion)); +} + +void CCustomObject::OnUpdateTransform() +{ + m_RT_Flags.set(flRT_UpdateTransform, FALSE); + + // update transform matrix + FTransformR.setXYZi(-GetRotation().x, -GetRotation().y, -GetRotation().z); + + FTransformS.scale(GetScale()); + FTransformP.translate(GetPosition()); + FTransformRP.mul(FTransformP, FTransformR); + FTransform.mul(FTransformRP, FTransformS); + FITransformRP.invert(FTransformRP); + FITransform.invert(FTransform); + + if (Motionable() && Visible() && Selected() && m_CO_Flags.is(flAutoKey)) + AnimationCreateKey(m_MotionParams->Frame()); +} + +void CCustomObject::Select(int flag) +{ + if (m_RT_Flags.is(flRT_Visible) && (!!m_RT_Flags.is(flRT_Selected) != flag)) + { + m_RT_Flags.set(flRT_Selected, (flag == -1) ? (m_RT_Flags.is(flRT_Selected) ? FALSE : TRUE) : flag); + UI->RedrawScene(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + FParentTools->OnSelected(this); + } +} + +void CCustomObject::Show(BOOL flag) +{ + m_RT_Flags.set(flRT_Visible, flag); + + if (!m_RT_Flags.is(flRT_Visible)) + m_RT_Flags.set(flRT_Selected, FALSE); + + UI->RedrawScene(); +} + +BOOL CCustomObject::Editable() const +{ + BOOL b1 = m_CO_Flags.is(flObjectInGroup); + BOOL b2 = m_CO_Flags.is(flObjectInGroupUnique); + return !b1 || (b1 && b2); +} + +bool CCustomObject::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + m_CO_Flags.assign(ini.r_u32(sect_name, "co_flags")); + + FName = ini.r_string(sect_name, "name"); + FPosition = ini.r_fvector3(sect_name, "position"); + VERIFY2(_valid(FPosition), sect_name); + FRotation = ini.r_fvector3(sect_name, "rotation"); + VERIFY2(_valid(FRotation), sect_name); + FScale = ini.r_fvector3(sect_name, "scale"); + VERIFY2(_valid(FScale), sect_name); + + // object motion + if (m_CO_Flags.is(flMotion)) + m_CO_Flags.set(flMotion, FALSE); + + return true; +} + +bool CCustomObject::LoadStream(IReader &F) +{ + R_ASSERT(F.find_chunk(CUSTOMOBJECT_CHUNK_FLAGS)); + + if (!Core.SocSdk) + m_CO_Flags.assign(F.r_u32()); + else + { + Flags32 tempFlags; + tempFlags.assign(F.r_u32()); + + m_RT_Flags.set(flRT_Selected, tempFlags.is((u32)SocFlags::flSelected)); + m_RT_Flags.set(flRT_Visible, tempFlags.is((u32)SocFlags::flVisible)); + m_RT_Flags.set(flRT_Visible, tempFlags.is((u32)SocFlags::flVisible)); + m_CO_Flags.set(flMotion, tempFlags.is((u32)SocFlags::flMotion)); + m_CO_Flags.set(flAutoKey, tempFlags.is((u32)SocFlags::flAutoKey)); + m_CO_Flags.set(flCameraView, tempFlags.is((u32)SocFlags::flCameraView)); + } + + R_ASSERT(F.find_chunk(CUSTOMOBJECT_CHUNK_NAME)); + F.r_stringZ(FName); + + if (F.find_chunk(CUSTOMOBJECT_CHUNK_TRANSFORM)) + { + F.r_fvector3(FPosition); + F.r_fvector3(FRotation); + VERIFY(_valid(FRotation)); + F.r_fvector3(FScale); + } + + // object motion + if (F.find_chunk(CUSTOMOBJECT_CHUNK_MOTION)) + { + m_Motion = xr_new(); + + if (!m_Motion->Load(F)) + { + ELog.Msg(mtError, "CustomObject: '%s' - motion has different version. Load failed.", GetName()); + xr_delete(m_Motion); + } + + m_MotionParams = xr_new(); + m_MotionParams->Set(m_Motion); + AnimationUpdate(m_MotionParams->Frame()); + } + + if (F.find_chunk(CUSTOMOBJECT_CHUNK_MOTION_PARAM)) + { + m_MotionParams->t_current = F.r_float(); + AnimationUpdate(m_MotionParams->Frame()); + } + + UpdateTransform(); + return true; +} + +void CCustomObject::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + ini.w_u32(sect_name, "co_flags", m_CO_Flags.get()); + ini.w_string(sect_name, "name", FName.c_str()); + + ini.w_fvector3(sect_name, "position", FPosition); + ini.w_fvector3(sect_name, "rotation", FRotation); + ini.w_fvector3(sect_name, "scale", FScale); +} + +void CCustomObject::SaveStream(IWriter &F) +{ + F.open_chunk(CUSTOMOBJECT_CHUNK_FLAGS); + + if (!Core.SocSdk) + F.w_u32(m_CO_Flags.get()); + else + { + Flags32 tempFlags; + tempFlags.set((u32)SocFlags::flSelected, m_RT_Flags.is(flRT_Selected)); + tempFlags.set((u32)SocFlags::flVisible, m_RT_Flags.is(flRT_Visible)); + tempFlags.set((u32)SocFlags::flLocked, false); + tempFlags.set((u32)SocFlags::flMotion, m_CO_Flags.is(flMotion)); + tempFlags.set((u32)SocFlags::flAutoKey, m_CO_Flags.is(flAutoKey)); + tempFlags.set((u32)SocFlags::flCameraView, m_CO_Flags.is(flCameraView)); + F.w_u32(tempFlags.get()); + } + + F.close_chunk(); + + F.open_chunk(CUSTOMOBJECT_CHUNK_NAME); + F.w_stringZ(FName); + F.close_chunk(); + + F.open_chunk(CUSTOMOBJECT_CHUNK_TRANSFORM); + F.w_fvector3(FPosition); + F.w_fvector3(FRotation); + F.w_fvector3(FScale); + F.close_chunk(); + + // object motion + if (m_CO_Flags.is(flMotion)) + { + VERIFY(m_Motion); + F.open_chunk(CUSTOMOBJECT_CHUNK_MOTION); + m_Motion->Save(F); + F.close_chunk(); + + F.open_chunk(CUSTOMOBJECT_CHUNK_MOTION_PARAM); + F.w_float(m_MotionParams->t_current); + F.close_chunk(); + } +} + +void CCustomObject::OnFrame() +{ + if (m_Motion) + AnimationOnFrame(); + + if (m_RT_Flags.is(flRT_UpdateTransform)) + OnUpdateTransform(); + + if (m_CO_Flags.test(flObjectInGroup) && m_pOwnerObject == NULL) + m_CO_Flags.set(flObjectInGroup, FALSE); +} + +void CCustomObject::RenderRoot(int priority, bool strictB2F) +{ + if (FParentTools->IsVisible()) + Render(priority, strictB2F); +} + +void CCustomObject::Render(int priority, bool strictB2F) +{ + if ((1 == priority) && (false == strictB2F)) + { + if (EPrefs->object_flags.is(epoDrawPivot) && Selected()) + DU_impl.DrawObjectAxis(FTransformRP, 0.1f, Selected()); + + if (m_Motion && Visible() && Selected()) + AnimationDrawPath(); + } +} + +bool CCustomObject::RaySelect(int flag, const Fvector &start, const Fvector &dir, bool bRayTest) +{ + float dist = UI->ZFar(); + + if ((bRayTest && RayPick(dist, start, dir)) || !bRayTest) + { + Select(flag); + return true; + } + + return false; +} + +bool CCustomObject::FrustumSelect(int flag, const CFrustum &frustum) +{ + if (FrustumPick(frustum)) + { + Select(flag); + return true; + } + + return false; +} + +bool CCustomObject::GetSummaryInfo(SSceneSummary *inf) +{ + Fbox bb; + + if (GetBox(bb)) + { + inf->bbox.modify(bb.vMin); + inf->bbox.modify(bb.vMax); + } + + return true; +} + +void CCustomObject::OnSynchronize() +{ + OnFrame(); +} diff --git a/src/editors/LevelEditor/Entry/CustomObject.h b/src/editors/LevelEditor/Entry/CustomObject.h new file mode 100644 index 00000000000..205096193e8 --- /dev/null +++ b/src/editors/LevelEditor/Entry/CustomObject.h @@ -0,0 +1,273 @@ +#pragma once + +#define CHUNK_OBJECT_BODY 0x7777 + +struct SRayPickInfo; +struct FSChunkDef; +class CFrustum; +class IReader; +class IWriter; +class COMotion; +class CCustomMotion; +struct SAnimParams; +class SSceneSummary; +class ESceneCustomOTool; + +struct SExportStreamItem +{ + int chunk; + CMemoryWriter stream; + SExportStreamItem() : chunk(0) { ; } +}; + +struct SExportStreams +{ + SExportStreamItem spawn; + SExportStreamItem spawn_rs; + SExportStreamItem patrolpath; + SExportStreamItem rpoint; + SExportStreamItem sound_static; + SExportStreamItem sound_env_geom; + SExportStreamItem pe_static; + SExportStreamItem envmodif; + SExportStreamItem fog_vol; +}; + +class CCustomObject : private pureDrawUI +{ +protected: + shared_str EName; + +private: + // orientation + Fvector EPosition; + Fvector EScale; + Fvector ERotation; + SAnimParams *m_MotionParams; + COMotion *m_Motion; + + // private animation methods + void AnimationOnFrame(); + void AnimationDrawPath(); + void AnimationCreateKey(float t); + void AnimationDeleteKey(float t); + void AnimationUpdate(float t); + +public: + enum + { + flSelected_notused = (1 << 0), + flVisible_notused = (1 << 1), + flLocked_notused = (1 << 2), + flMotion = (1 << 3), + flRenderAnyWayIfSelected = (1 << 4), + flObjectInGroup = (1 << 5), + flObjectInGroupUnique = (1 << 6), + + flAutoKey = (1 << 30), + flCameraView = (1 << 31), + }; + + Flags32 m_CO_Flags; + + enum + { + flRT_Valid = (1 << 0), + flRT_UpdateTransform = (1 << 1), + flRT_NeedSelfDelete = (1 << 2), + flRT_Selected = (1 << 3), + flRT_Visible = (1 << 4), + flRT_SelectedLast = (1 << 5) + }; + + Flags32 m_RT_Flags; + +public: + shared_str FName; + int save_id; + // orientation + Fvector FPosition; + Fvector FScale; + Fvector FRotation; + Fmatrix FTransformP; + Fmatrix FTransformR; + Fmatrix FTransformS; + Fmatrix FTransformRP; + Fmatrix FTransform; + Fmatrix FITransformRP; + Fmatrix FITransform; + + CCustomObject *m_pOwnerObject; + bool OnObjectNameAfterEdit(PropValue *sender, shared_str &edit_val); + void OnTransformChange(PropValue *value); + void OnMotionableChange(PropValue *sender); + void OnMotionCommandsClick(ButtonValue *value, bool &bModif, bool &bSafe); + void OnMotionFilesClick(ButtonValue *value, bool &bModif, bool &bSafe); + void OnMotionControlClick(ButtonValue *value, bool &bModif, bool &bSafe); + void OnMotionFrameChange(PropValue *value); + void OnMotionKeyTimeChange(PropValue *value); + + void OnMotionCurrentFrameChange(PropValue *value); + void OnMotionCameraViewChange(PropValue *value); + +public: + LPCSTR GetName() const { return *FName; } + void SetName(LPCSTR N) + { + string256 tmp; + strcpy(tmp, N); + strlwr(tmp); + FName = tmp; + } + + virtual const Fvector &GetPosition() const { return FPosition; } + virtual const Fvector &GetRotation() const { return FRotation; } + virtual const Fvector &GetScale() const { return FScale; } + + virtual void SetPosition(const Fvector &pos) + { + FPosition.set(pos); + UpdateTransform(); + } + virtual void SetRotation(const Fvector &rot) + { + FRotation.set(rot); + VERIFY(_valid(FRotation)); + UpdateTransform(); + } + virtual void SetScale(const Fvector &scale) + { + FScale.set(scale); + UpdateTransform(); + } + + void OnNameChange(PropValue *sender); + void OnChangeIngroupUnique(PropValue *sender); + + void OnNumChangePosition(PropValue *sender); + void OnNumChangeRotation(PropValue *sender); + void OnNumChangeScale(PropValue *sender); + + virtual void DeleteThis() { m_RT_Flags.set(flRT_NeedSelfDelete, TRUE); } + +public: + CCustomObject(LPVOID data, LPCSTR name); + virtual ~CCustomObject(); + + BOOL Editable() const; + + IC BOOL Motionable() const { return m_CO_Flags.is(flMotion); } + IC BOOL Visible() const { return m_RT_Flags.is(flRT_Visible); } + IC BOOL Selected() const { return m_RT_Flags.is(flRT_Selected); } + IC BOOL Valid() const { return m_RT_Flags.is(flRT_Valid); } + IC BOOL IsDeleted() const { return m_RT_Flags.is(flRT_NeedSelfDelete); } + + // editor integration + virtual bool Validate(bool bMsg) { return true; } + virtual void FillProp(LPCSTR pref, PropItemVec &items); + void AnimationFillProp(LPCSTR pref, PropItemVec &items); + virtual bool GetSummaryInfo(SSceneSummary *inf); + + virtual void Select(int flag); + virtual void Show(BOOL flag); + void SetValid(BOOL flag) { m_RT_Flags.set(flRT_Valid, flag); } + void SetRenderIfSelected(BOOL flag) { m_CO_Flags.set(flRenderAnyWayIfSelected, flag); } + + virtual bool IsRender(); + virtual void Render(int priority, bool strictB2F); + void RenderRoot(int priority, bool strictB2F); + virtual void OnFrame(); + virtual void OnUpdateTransform(); + + virtual void OnSceneRemove(){}; + + virtual bool RaySelect(int flag, const Fvector &start, const Fvector &dir, bool bRayTest = false); // flag 1,0,-1 (-1 invert) + virtual bool FrustumSelect(int flag, const CFrustum &frustum); + virtual bool RayPick(float &dist, const Fvector &start, const Fvector &dir, SRayPickInfo *pinf = NULL) { return false; }; + virtual bool FrustumPick(const CFrustum &frustum) { return false; }; + virtual bool SpherePick(const Fvector ¢er, float radius) { return false; }; + + void ResetTransform() + { + FScale.set(1, 1, 1); + FRotation.set(0, 0, 0); + FPosition.set(0, 0, 0); + FTransform.identity(); + FTransformRP.identity(); + FITransform.identity(); + FITransformRP.identity(); + } + virtual void ResetAnimation(bool upd_t = true) { ; } + virtual void UpdateTransform(bool bForced = false) + { + m_RT_Flags.set(flRT_UpdateTransform, TRUE); + if (bForced) + OnUpdateTransform(); + } + + // animation methods + + // grouping methods + virtual void OnDetach(); + virtual void OnAttach(CCustomObject *owner); + CCustomObject *GetOwner() { return m_pOwnerObject; } + virtual bool CanAttach() = 0; + + virtual bool OnChooseQuery(LPCSTR specific) { return true; } + + // change position/orientation methods + virtual void NumSetPosition(const Fvector &pos) { SetPosition(pos); } + virtual void NumSetRotation(const Fvector &rot) { SetRotation(rot); } + virtual void NumSetScale(const Fvector &scale) { SetScale(scale); } + virtual void MoveTo(const Fvector &pos, const Fvector &up); + virtual void Move(Fvector &amount); + virtual void RotateParent(Fvector &axis, float angle); + virtual void RotateLocal(Fvector &axis, float angle); + virtual void RotatePivot(const Fmatrix &prev_inv, const Fmatrix ¤t); + virtual void Scale(Fvector &amount); + virtual void ScalePivot(const Fmatrix &prev_inv, const Fmatrix ¤t, Fvector &amount); + + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual bool ExportGame(SExportStreams *data) { return true; } + + virtual bool GetBox(Fbox &box) { return false; } + virtual bool GetUTBox(Fbox &box) { return false; } + virtual void OnSceneUpdate() { ; } + virtual void OnObjectRemove(const CCustomObject *object) { ; } + virtual bool OnSelectionRemove() { return true; } // ���������� ����� �� ��� ������� ������ + + virtual void OnDeviceCreate() { ; } + virtual void OnDeviceDestroy() { ; } + + virtual void OnSynchronize(); + virtual void OnShowHint(AStringVec &dest); + + virtual LPCSTR RefName() { return 0; } + + IC const Fmatrix &_ITransform() { return FITransform; } + IC const Fmatrix &_Transform() { return FTransform; } + IC const Fvector &_Position() { return FPosition; } + IC const Fvector &_Rotation() { return FRotation; } + IC const Fvector &_Scale() { return FScale; } + + ObjClassID FClassID; + ESceneCustomOTool *FParentTools; + +public: + static void SnapMove(Fvector &pos, Fvector &rot, const Fmatrix &rotRP, const Fvector &amount); + static void NormalAlign(Fvector &rot, const Fvector &up, const Fvector &dir); + +private: + virtual void OnDrawUI(); + +private: + int m_ButtonId; + float m_FromTime; + float m_ToTime; + float m_ScaleFactor; + float m_Speed; +}; diff --git a/src/editors/LevelEditor/Entry/CustomObjectAnimation.cpp b/src/editors/LevelEditor/Entry/CustomObjectAnimation.cpp new file mode 100644 index 00000000000..d3a62cdf9cd --- /dev/null +++ b/src/editors/LevelEditor/Entry/CustomObjectAnimation.cpp @@ -0,0 +1,370 @@ +#include "stdafx.h" + +void CCustomObject::OnMotionableChange(PropValue *sender) +{ + if (m_CO_Flags.is(flMotion)) + { + m_Motion = xr_new(); + m_MotionParams = xr_new(); + } + else + { + xr_delete(m_Motion); + xr_delete(m_MotionParams); + } + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CCustomObject::AnimationCreateKey(float t) +{ + Fvector R; + R.set(-GetRotation().x, -GetRotation().y, -GetRotation().z); + m_Motion->CreateKey(t, GetPosition(), R); +} + +void CCustomObject::AnimationDeleteKey(float t) +{ + m_Motion->DeleteKey(t); +} + +// float speed = 0.f; +void CCustomObject::AnimationUpdate(float t) +{ + Fvector R, P, r; + m_Motion->_Evaluate(t, P, r); + R.set(-r.x, -r.y, -r.z); + + // speed = speed*0.9f+(P.distance_to(GetPosition())/EDevice.fTimeDelta)*0.1f; + // Log("speed: ",speed); + SetPosition(P); + SetRotation(R); + BOOL bAK = m_CO_Flags.is(flAutoKey); + m_CO_Flags.set(flAutoKey, FALSE); + UpdateTransform(true); + m_CO_Flags.set(flAutoKey, bAK); + if (m_CO_Flags.is(flCameraView)) + EDevice.m_Camera.Set(-r.y, -r.x, -r.z, P.x, P.y, P.z); +} + +void CCustomObject::AnimationOnFrame() +{ + VERIFY(m_Motion); + + if (Selected() && m_MotionParams->bPlay) + { + AnimationUpdate(m_MotionParams->Frame()); + m_MotionParams->Update(EDevice.fTimeDelta, 1.f, true); + } +} + +static FvectorVec path_points; +void CCustomObject::AnimationDrawPath() +{ + // motion path + VERIFY(m_Motion); +#ifdef _EDITOR + if (EPrefs->object_flags.is(epoDrawAnimPath)) + { + float fps = m_Motion->FPS(); + float min_t = (float)m_Motion->FrameStart() / fps; + float max_t = (float)m_Motion->FrameEnd() / fps; + + Fvector T, r; + u32 clr = 0xffffffff; + path_points.clear(); + for (float t = min_t; (t < max_t) || fsimilar(t, max_t, EPS_L); t += 1 / 30.f) + { + m_Motion->_Evaluate(t, T, r); + path_points.push_back(T); + } + + EDevice.SetShader(EDevice.m_WireShader); + RCache.set_xform_world(Fidentity); + if (!path_points.empty()) + DU_impl.DrawPrimitiveL(D3DPT_LINESTRIP, path_points.size() - 1, path_points.data(), path_points.size(), clr, true, false); + CEnvelope *E = m_Motion->Envelope(); + for (KeyIt k_it = E->keys.begin(); k_it != E->keys.end(); k_it++) + { + m_Motion->_Evaluate((*k_it)->time, T, r); + if (EDevice.m_Camera.GetPosition().distance_to_sqr(T) < 50.f * 50.f) + { + DU_impl.DrawCross(T, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, clr, false); + DU_impl.OutText(T, make_string("K: %3.3f", (*k_it)->time).c_str(), 0xffffffff, 0x00000000); + } + } + } +#endif +} + +void CCustomObject::OnMotionControlClick(ButtonValue *value, bool &bModif, bool &bSafe) +{ + ButtonValue *B = dynamic_cast(value); + R_ASSERT(B); + switch (B->btn_num) + { + case 0: + { + m_MotionParams->t_current = m_MotionParams->min_t; + m_MotionParams->tmp = m_MotionParams->t_current; + + m_MotionParams->bPlay = FALSE; + } + break; + case 1: + { + float min_k; + float max_k; + m_Motion->FindNearestKey(m_MotionParams->t_current, min_k, max_k); + m_MotionParams->t_current = min_k; + m_MotionParams->tmp = m_MotionParams->t_current; + m_MotionParams->bPlay = FALSE; + } + break; + case 2: + { + m_MotionParams->t_current -= 1.f / 30.f; + m_MotionParams->tmp = m_MotionParams->t_current; + m_MotionParams->bPlay = FALSE; + } + break; + case 3: + { + m_MotionParams->bPlay = TRUE; + } + break; + case 4: + { + m_MotionParams->bPlay = FALSE; + } + break; + case 5: + { + m_MotionParams->t_current += 1.f / 30.f; + m_MotionParams->tmp = m_MotionParams->t_current; + m_MotionParams->bPlay = FALSE; + } + break; + case 6: + { + float min_k; + float max_k; + m_Motion->FindNearestKey(m_MotionParams->t_current, min_k, max_k); + m_MotionParams->t_current = max_k; + m_MotionParams->tmp = m_MotionParams->t_current; + m_MotionParams->bPlay = FALSE; + } + break; + case 7: + { + m_MotionParams->t_current = m_MotionParams->max_t; + m_MotionParams->tmp = m_MotionParams->t_current; + m_MotionParams->bPlay = FALSE; + } + break; + } + AnimationUpdate(m_MotionParams->Frame()); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + bModif = false; +} +void CCustomObject::OnDrawUI() +{ + switch (m_ButtonId) + { + case 2: + { + bool ok = false; + if (UIPropertiesModal::GetResult(ok)) + { + if (ok) + { + m_Motion->ScaleKeys(m_FromTime, m_ToTime, m_ScaleFactor); + } + float mx; + m_Motion->GetLength(0, &mx); + if (m_MotionParams->max_t < mx) + { + m_MotionParams->max_t = mx; + m_Motion->SetParam(static_cast(m_MotionParams->min_t * 30.f), static_cast(m_MotionParams->max_t * 30.f), 30.f); + } + EDevice.seqDrawUI.Remove(this); + m_ButtonId = 0; + } + UIPropertiesModal::Update(); + } + break; + case 3: + { + bool ok = false; + if (UIPropertiesModal::GetResult(ok)) + { + if (ok) + { + m_Motion->NormalizeKeys(m_FromTime, m_ToTime, m_Speed); + } + float mx; + m_Motion->GetLength(0, &mx); + if (m_MotionParams->max_t < mx) + { + m_MotionParams->max_t = mx; + m_Motion->SetParam(static_cast(m_MotionParams->min_t * 30.f), static_cast(m_MotionParams->max_t * 30.f), 30.f); + } + EDevice.seqDrawUI.Remove(this); + m_ButtonId = 0; + } + UIPropertiesModal::Update(); + } + break; + } +} +void CCustomObject::OnMotionCommandsClick(ButtonValue *value, bool &bModif, bool &bSafe) +{ + ButtonValue *B = dynamic_cast(value); + R_ASSERT(B); + switch (B->btn_num) + { + case 0: + AnimationCreateKey(m_MotionParams->t_current); + break; + case 1: + AnimationDeleteKey(m_MotionParams->t_current); + break; + case 2: + { + PropItemVec items; + m_FromTime = m_MotionParams->min_t; + m_ToTime = m_MotionParams->max_t; + m_ScaleFactor = 1.f; + PHelper().CreateFloat(items, "From Time", &m_FromTime, m_FromTime, m_ToTime, 1.f / 30.f, 3); + PHelper().CreateFloat(items, "To Time", &m_ToTime, m_FromTime, m_ToTime, 1.f / 30.f, 3); + PHelper().CreateFloat(items, "Scale", &m_ScaleFactor, -1000.f, 1000.f); + UIPropertiesModal::Show(items); + m_ButtonId = 2; + EDevice.seqDrawUI.Add(this); + } + break; + case 3: + { + m_ButtonId = 3; + PropItemVec items; + m_FromTime = m_MotionParams->min_t; + m_ToTime = m_MotionParams->max_t; + m_Speed = 5.f; + PHelper().CreateFloat(items, "From Time", &m_FromTime, m_FromTime, m_ToTime, 1.f / 30.f, 3); + PHelper().CreateFloat(items, "To Time", &m_ToTime, m_FromTime, m_ToTime, 1.f / 30.f, 3); + PHelper().CreateFloat(items, "Speed (m/sec)", &m_Speed, 0.f, 100.f); + UIPropertiesModal::Show(items); + m_ButtonId = 3; + EDevice.seqDrawUI.Add(this); + } + break; + case 4: + { + float mn, mx; + m_Motion->GetLength(&mn, &mx); + m_MotionParams->min_t = mn; + m_MotionParams->max_t = mx; + m_Motion->SetParam(static_cast(mn * 30.f), static_cast(mx * 30.f), 30.f); + } + break; + } + AnimationUpdate(m_MotionParams->Frame()); + bModif = true; +} + +void CCustomObject::OnMotionFilesClick(ButtonValue *value, bool &bModif, bool &bSafe) +{ + ButtonValue *B = dynamic_cast(value); + R_ASSERT(B); + bModif = false; + xr_string fn; + switch (B->btn_num) + { + case 0: + if (EFS.GetOpenName(EDevice.m_hWnd, "$game_anims$", fn)) + { + m_Motion->LoadMotion(fn.c_str()); + m_MotionParams->Set(m_Motion); + AnimationUpdate(m_MotionParams->Frame()); + bModif = true; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + break; + case 1: + if (EFS.GetSaveName("$game_anims$", fn)) + m_Motion->SaveMotion(fn.c_str()); + break; + } +} + +void CCustomObject::OnMotionFrameChange(PropValue *value) +{ + m_Motion->SetParam(static_cast(m_MotionParams->min_t * 30.f), static_cast(m_MotionParams->max_t * 30.f), 30.f); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CCustomObject::OnMotionKeyTimeChange(PropValue *value) +{ + float t = m_MotionParams->tmp; + Fvector P, R; + + m_Motion->_Evaluate(m_MotionParams->t_current, P, R); + + m_Motion->DeleteKey(m_MotionParams->t_current); + m_Motion->CreateKey(t, P, R); +} + +void CCustomObject::OnMotionCurrentFrameChange(PropValue *value) +{ + if (m_MotionParams->t_current < m_MotionParams->min_t) + m_MotionParams->min_t = m_MotionParams->t_current; + + else if (m_MotionParams->t_current > m_MotionParams->max_t) + m_MotionParams->max_t = m_MotionParams->t_current; + + m_Motion->SetParam(static_cast(m_MotionParams->min_t * 30.f), static_cast(m_MotionParams->max_t * 30.f), 30.f); + m_MotionParams->bPlay = FALSE; + AnimationUpdate(m_MotionParams->Frame()); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CCustomObject::OnMotionCameraViewChange(PropValue *value) +{ + if (m_CO_Flags.is(flCameraView)) + AnimationUpdate(m_MotionParams->Frame()); +} + +void CCustomObject::OnTransformChange(PropValue *value) +{ + UpdateTransform(); +} + +void CCustomObject::AnimationFillProp(LPCSTR pref, PropItemVec &items) +{ + PropValue *V = PHelper().CreateFlag32(items, PrepareKey(pref, "Flags\\Motionable"), &m_CO_Flags, flMotion); + V->OnChangeEvent.bind(this, &CCustomObject::OnMotionableChange); + if (Motionable()) + { + PHelper().CreateCaption(items, PrepareKey(pref, "Motion\\Hint"), "Make KEY only on Parent CS"); + ButtonValue *B = PHelper().CreateButton(items, PrepareKey(pref, "Motion\\Files"), "Import,Export", 0); + B->OnBtnClickEvent.bind(this, &CCustomObject::OnMotionFilesClick); + B = PHelper().CreateButton(items, PrepareKey(pref, "Motion\\Commands"), "+ K,- K,Scale,Norm,Clamp", 0); + B->OnBtnClickEvent.bind(this, &CCustomObject::OnMotionCommandsClick); + B = PHelper().CreateButton(items, PrepareKey(pref, "Motion\\Controls"), " |<<, +<<, <<, >, ||, >>, >>+, >>|", 0); + B->OnBtnClickEvent.bind(this, &CCustomObject::OnMotionControlClick); + PHelper().CreateFlag32(items, PrepareKey(pref, "Motion\\Flags\\Auto Key"), &m_CO_Flags, flAutoKey); + V = PHelper().CreateFlag32(items, PrepareKey(pref, "Motion\\Flags\\Camera View"), &m_CO_Flags, flCameraView); + V->OnChangeEvent.bind(this, &CCustomObject::OnMotionCameraViewChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Motion\\Start Frame (sec)"), &m_MotionParams->min_t, -10000.f, m_MotionParams->max_t, 1.f / 30.f, 3); + V->OnChangeEvent.bind(this, &CCustomObject::OnMotionFrameChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Motion\\End Frame (sec)"), &m_MotionParams->max_t, m_MotionParams->min_t, 10000.f, 1.f / 30.f, 3); + V->OnChangeEvent.bind(this, &CCustomObject::OnMotionFrameChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Motion\\Current Frame (sec)"), &m_MotionParams->t_current, -10000.f, 10000.f, 1.f / 30.f, 3); + V->OnChangeEvent.bind(this, &CCustomObject::OnMotionCurrentFrameChange); + + V = PHelper().CreateFloat(items, PrepareKey(pref, "Motion\\ChangeKeyTime(sec)"), &m_MotionParams->tmp, -10000.f, 10000.f, 1.f / 30.f, 3); + V->OnChangeEvent.bind(this, &CCustomObject::OnMotionKeyTimeChange); + + PHelper().CreateCaption(items, PrepareKey(pref, "Motion\\Key Count"), shared_str().printf("%d", m_Motion->KeyCount())); + PHelper().CreateCaption(items, PrepareKey(pref, "Motion\\Length (sec)"), shared_str().printf("%3.2f", m_Motion->GetLength())); + } +} diff --git a/src/editors/LevelEditor/Entry/CustomObjectLE.cpp b/src/editors/LevelEditor/Entry/CustomObjectLE.cpp new file mode 100644 index 00000000000..7bcc69ba51e --- /dev/null +++ b/src/editors/LevelEditor/Entry/CustomObjectLE.cpp @@ -0,0 +1,258 @@ +#include "stdafx.h" + +// static part +void CCustomObject::SnapMove(Fvector &pos, Fvector &rot, const Fmatrix &rotRP, const Fvector &amount) +{ + // !!! Hide object before test + SRayPickInfo pinf; + Fvector up, dn = {0, -1, 0}; + rotRP.transform_dir(dn); + up.invert(dn); + Fvector s2, s1 = pos; + s1.add(amount); + s2.mad(s1, up, EPrefs->snap_moveto); + + pinf.inf.range = EPrefs->snap_moveto; + if (Scene->RayPickObject(pinf.inf.range, s1, dn, OBJCLASS_SCENEOBJECT, &pinf, Scene->GetSnapList(false)) || Scene->RayPickObject(pinf.inf.range, s2, dn, OBJCLASS_SCENEOBJECT, &pinf, Scene->GetSnapList(false))) + { + pos.set(pinf.pt); + if (Tools->GetSettings(etfNormalAlign)) + { + Fvector verts[3]; + pinf.e_obj->GetFaceWorld(pinf.s_obj->_Transform(), pinf.e_mesh, pinf.inf.id, verts); + Fvector vR, vD, vN; + vN.mknormal(verts[0], verts[1], verts[2]); + + vD.set(rotRP.k); + vR.crossproduct(vN, vD); + vR.normalize(); + vD.crossproduct(vR, vN); + vD.normalize(); + + Fmatrix M; + M.set(vR, vN, vD, vR); + M.getXYZ(rot); + } + } + else + pos.add(amount); +} +void CCustomObject::NormalAlign(Fvector &rot, const Fvector &up, const Fvector &dir) +{ + Fmatrix mR; + Fvector vR, vD, vN; + vN.set(up); + // vD.set(0,0,1); + vD.set(dir); + if (fabsf(vN.z) > 0.99f) + vD.set(1, 0, 0); + vR.crossproduct(vN, vD); + vR.normalize(); + vD.crossproduct(vR, vN); + vD.normalize(); + mR.set(vR, vN, vD, vR); + mR.getXYZ(rot); +} + +//------------------------------------------------------------------------------ + +void CCustomObject::OnDetach() +{ + if (m_pOwnerObject) + { + m_pOwnerObject = 0; + //. string64 new_name; + //. Scene->GenObjectName(ClassID,new_name,Name); + //. Name = new_name; + //. Scene->AppendObject (this,false); + } + m_CO_Flags.set(flObjectInGroup, FALSE); + Select(true); + FParentTools->SetChanged(TRUE); +} + +void CCustomObject::OnAttach(CCustomObject *owner) +{ + R_ASSERT(owner); + R_ASSERT2(((!m_pOwnerObject) || (m_pOwnerObject == owner)), "Object already has owner!"); + m_pOwnerObject = owner; + //. Scene->RemoveObject (this,false,false); + if (owner->FClassID == OBJCLASS_GROUP) + m_CO_Flags.set(flObjectInGroup, TRUE); + + Select(false); + FParentTools->SetChanged(TRUE); +} + +void CCustomObject::Move(Fvector &amount) +{ + UI->UpdateScene(); + Fvector v = GetPosition(); + Fvector r = FRotation; + if (Tools->GetSettings(etfMTSnap)) + { + BOOL bVis = Visible(); + BOOL bSel = Selected(); + Show(FALSE); + Select(FALSE); + SnapMove(v, r, FTransformRP, amount); + Show(bVis); + Select(bSel); + } + else + { + v.add(amount); + } + SetPosition(v); + FRotation = r; +} + +void CCustomObject::MoveTo(const Fvector &pos, const Fvector &up) +{ + UI->UpdateScene(); + Fvector v = GetPosition(); + v.set(pos); + if (Tools->GetSettings(etfNormalAlign)) + { + Fmatrix M; + M.setXYZ(FRotation); + Fvector ret_rot = FRotation; + NormalAlign(ret_rot, up, M.k); + FRotation = ret_rot; + } + SetPosition(v); +} + +void CCustomObject::RotatePivot(const Fmatrix &prev_inv, const Fmatrix ¤t) +{ + Fmatrix Ol, On; + Ol.mul(prev_inv, FTransformRP); + On.mul(current, Ol); + Fvector xyz; + On.getXYZ(xyz); + FRotation = xyz; + SetPosition(On.c); +} + +void CCustomObject::RotateParent(Fvector &axis, float angle) +{ + UI->UpdateScene(); + Fvector r = FRotation; + r.mad(axis, angle); + FRotation = r; +} + +void CCustomObject::RotateLocal(Fvector &axis, float angle) +{ + Fmatrix m; + Fvector r; + m.rotation(axis, angle); + FTransformRP.mulB_43(m); + FTransformRP.getXYZ(r); + SetRotation(r); +} + +void CCustomObject::ScalePivot(const Fmatrix &prev_inv, const Fmatrix ¤t, Fvector &amount) +{ + UI->UpdateScene(); + Fvector p = GetPosition(); + Fvector s = GetScale(); + ; + s.add(amount); + if (s.x < EPS) + s.x = EPS; + if (s.y < EPS) + s.y = EPS; + if (s.z < EPS) + s.z = EPS; + SetScale(s); + + // translate position + prev_inv.transform_tiny(p); + current.transform_tiny(p); + + SetPosition(p); +} + +void CCustomObject::Scale(Fvector &amount) +{ + UI->UpdateScene(); + Fvector s = GetScale(); + s.add(amount); + if (s.x < EPS) + s.x = EPS; + if (s.y < EPS) + s.y = EPS; + if (s.z < EPS) + s.z = EPS; + SetScale(s); +} + +bool CCustomObject::OnObjectNameAfterEdit(PropValue *sender, shared_str &edit_val) +{ + RTextValue *V = dynamic_cast(sender); + VERIFY(V); + if (0 == edit_val.size()) + return false; + xr_string temp = edit_val.c_str(); + xr_strlwr(temp); + + edit_val = temp.c_str(); + return !Scene->FindObjectByName(edit_val.c_str(), (CCustomObject *)0); +} + +void CCustomObject::OnNumChangePosition(PropValue *sender) +{ + NumSetPosition(EPosition); +} +void CCustomObject::OnNumChangeRotation(PropValue *sender) +{ + NumSetRotation(ERotation); +} +void CCustomObject::OnNumChangeScale(PropValue *sender) +{ + NumSetScale(EScale); +} +void CCustomObject::OnNameChange(PropValue *sender) +{ + SetName(EName.c_str()); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CCustomObject::FillProp(LPCSTR pref, PropItemVec &items) +{ + PropValue *V; + EName = GetName(); + V = PHelper().CreateNameCB(items, PrepareKey(pref, "Name"), &EName, NULL, NULL, RTextValue::TOnAfterEditEvent(this, &CCustomObject::OnObjectNameAfterEdit)); + V->OnChangeEvent.bind(this, &CCustomObject::OnNameChange); + EPosition = GetPosition(); + V = PHelper().CreateVector(items, PrepareKey(pref, "Transform\\Position"), &EPosition, -10000, 10000, 0.01, 2); + V->OnChangeEvent.bind(this, &CCustomObject::OnNumChangePosition); + ERotation = GetRotation(); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Transform\\Rotation"), &ERotation, -10000, 10000, 0.1, 1); + V->OnChangeEvent.bind(this, &CCustomObject::OnNumChangeRotation); + EScale = GetScale(); + V = PHelper().CreateVector(items, PrepareKey(pref, "Transform\\Scale"), &EScale, 0.01, 10000, 0.01, 2); + V->OnChangeEvent.bind(this, &CCustomObject::OnNumChangeScale); + + if (m_CO_Flags.test(flObjectInGroup)) + { + V = PHelper().CreateFlag32(items, PrepareKey(pref, "In group editable"), &m_CO_Flags, flObjectInGroupUnique); + V->OnChangeEvent.bind(this, &CCustomObject::OnChangeIngroupUnique); + } +} + +void CCustomObject::OnChangeIngroupUnique(PropValue *sender) +{ + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +//---------------------------------------------------- + +void CCustomObject::OnShowHint(AStringVec &dest) +{ + // dest.push_back(xr_string("Class: ")+xr_string(ParentTools->ClassDesc())); + dest.push_back(xr_string("Name: ") + xr_string(GetName())); + dest.push_back(xr_string("-------")); +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Entry/Glow/Glow.cpp b/src/editors/LevelEditor/Entry/Glow/Glow.cpp new file mode 100644 index 00000000000..5b100602905 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Glow/Glow.cpp @@ -0,0 +1,276 @@ +#include "stdafx.h" + +#define GLOW_VERSION 0x0012 + +#define GLOW_CHUNK_VERSION 0xC411 +#define GLOW_CHUNK_PARAMS 0xC413 +#define GLOW_CHUNK_SHADER 0xC414 +#define GLOW_CHUNK_TEXTURE 0xC415 +#define GLOW_CHUNK_FLAGS 0xC416 + +#define VIS_RADIUS 0.25f + +CGlow::CGlow(LPVOID data, LPCSTR name) : CCustomObject(data, name) +{ + Construct(data); +} + +void CGlow::Construct(LPVOID data) +{ + FClassID = OBJCLASS_GLOW; + m_GShader = 0; + m_fRadius = 0.5f; + m_bDefLoad = false; + m_Flags.zero(); + m_ShaderName = "effects\\glow"; +} + +CGlow::~CGlow() +{ + OnDeviceDestroy(); +} + +void CGlow::OnDeviceCreate() +{ + if (m_bDefLoad) + return; + // создать заново shaders + if (m_TexName.size() && m_ShaderName.size()) + m_GShader.create(*m_ShaderName, *m_TexName); + m_bDefLoad = true; +} + +void CGlow::OnDeviceDestroy() +{ + m_bDefLoad = false; + // удалить shaders + m_GShader.destroy(); +} + +void CGlow::ShaderChange(PropValue *value) +{ + OnDeviceDestroy(); +} + +bool CGlow::GetBox(Fbox &box) +{ + box.set(GetPosition(), GetPosition()); + box.vMin.sub(m_fRadius); + box.vMax.add(m_fRadius); + return true; +} + +void CGlow::Render(int priority, bool strictB2F) +{ + if ((1 == priority) && (true == strictB2F)) + { + if (!m_bDefLoad) + OnDeviceCreate(); + ESceneGlowTool *gt = dynamic_cast(FParentTools); + VERIFY(gt); + RCache.set_xform_world(Fidentity); + + if (gt->m_Flags.is(ESceneGlowTool::flTestVisibility)) + { + Fvector D; + D.sub(EDevice.vCameraPosition, GetPosition()); + float dist = D.normalize_magn(); + if (!Scene->RayPickObject(dist, GetPosition(), D, OBJCLASS_SCENEOBJECT, 0, 0)) + { + if (m_GShader) + { + EDevice.SetShader(m_GShader); + } + else + { + EDevice.SetShader(EDevice.m_WireShader); + } + Fvector p = GetPosition(); + m_RenderSprite.Render(p, m_fRadius, m_Flags.is(gfFixedSize)); + DU_impl.DrawRomboid(p, VIS_RADIUS, 0x00FF8507); + } + else + { + // рендерим bounding sphere + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawRomboid(GetPosition(), VIS_RADIUS, 0x00FF8507); + } + } + else + { + if (m_GShader) + { + EDevice.SetShader(m_GShader); + } + else + { + EDevice.SetShader(EDevice.m_WireShader); + } + Fvector p = GetPosition(); + m_RenderSprite.Render(p, m_fRadius, m_Flags.is(gfFixedSize)); + } + if (Selected()) + { + Fbox bb; + GetBox(bb); + u32 clr = 0xFFFFFFFF; + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawSelectionBoxB(bb, &clr); + if (gt->m_Flags.is(ESceneGlowTool::flDrawCross)) + { + Fvector sz; + bb.getradius(sz); + DU_impl.DrawCross(GetPosition(), sz.x, sz.y, sz.z, sz.x, sz.y, sz.z, 0xFFFFFFFF, false); + } + } + } +} + +bool CGlow::FrustumPick(const CFrustum &frustum) +{ + return (frustum.testSphere_dirty(GetPosition(), m_fRadius)) ? true : false; +} + +bool CGlow::RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf) +{ + Fvector ray2; + ray2.sub(GetPosition(), start); + + float d = ray2.dotproduct(direction); + if (d > 0) + { + float d2 = ray2.magnitude(); + if (((d2 * d2 - d * d) < (m_fRadius * m_fRadius)) && (d > m_fRadius)) + { + if (d < distance) + { + distance = d; + return true; + } + } + } + return false; +} + +bool CGlow::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 version = ini.r_u32(sect_name, "version"); + + if (version != GLOW_VERSION) + { + ELog.DlgMsg(mtError, "CGlow: Unsupported version."); + return false; + } + + CCustomObject::LoadLTX(ini, sect_name); + + m_ShaderName = ini.r_string(sect_name, "shader_name"); + + m_TexName = ini.r_string(sect_name, "texture_name"); + + m_fRadius = ini.r_float(sect_name, "radius"); + + m_Flags.assign(ini.r_u32(sect_name, "flags")); + + return true; +} + +void CGlow::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + CCustomObject::SaveLTX(ini, sect_name); + + ini.w_u16(sect_name, "version", GLOW_VERSION); + + ini.w_float(sect_name, "radius", m_fRadius); + + ini.w_string(sect_name, "shader_name", m_ShaderName.c_str()); + + ini.w_string(sect_name, "texture_name", m_TexName.c_str()); + + ini.w_u16(sect_name, "flags", m_Flags.get()); +} + +bool CGlow::LoadStream(IReader &F) +{ + u16 version = 0; + + R_ASSERT(F.r_chunk(GLOW_CHUNK_VERSION, &version)); + if ((version != 0x0011) && (version != GLOW_VERSION)) + { + ELog.DlgMsg(mtError, "CGlow: Unsupported version."); + return false; + } + + CCustomObject::LoadStream(F); + + if (F.find_chunk(GLOW_CHUNK_SHADER)) + { + F.r_stringZ(m_ShaderName); + } + + R_ASSERT(F.find_chunk(GLOW_CHUNK_TEXTURE)); + F.r_stringZ(m_TexName); + + R_ASSERT(F.find_chunk(GLOW_CHUNK_PARAMS)); + m_fRadius = F.r_float(); + if (version == 0x0011) + { + F.r_fvector3(FPosition); + UpdateTransform(); + } + + if (F.find_chunk(GLOW_CHUNK_FLAGS)) + m_Flags.assign(F.r_u16()); + + return true; +} + +void CGlow::SaveStream(IWriter &F) +{ + CCustomObject::SaveStream(F); + + F.open_chunk(GLOW_CHUNK_VERSION); + F.w_u16(GLOW_VERSION); + F.close_chunk(); + + F.open_chunk(GLOW_CHUNK_PARAMS); + F.w_float(m_fRadius); + F.close_chunk(); + + F.open_chunk(GLOW_CHUNK_SHADER); + F.w_stringZ(m_ShaderName); + F.close_chunk(); + + F.open_chunk(GLOW_CHUNK_TEXTURE); + F.w_stringZ(m_TexName); + F.close_chunk(); + + F.open_chunk(GLOW_CHUNK_FLAGS); + F.w_u16(m_Flags.get()); + F.close_chunk(); +} +//---------------------------------------------------- + +void CGlow::FillProp(LPCSTR pref, PropItemVec &items) +{ + inherited::FillProp(pref, items); + PropValue *V = 0; + V = PHelper().CreateChoose(items, PrepareKey(pref, "Texture"), &m_TexName, smTexture); + V->OnChangeEvent.bind(this, &CGlow::ShaderChange); + V = PHelper().CreateChoose(items, PrepareKey(pref, "Shader"), &m_ShaderName, smEShader); + V->OnChangeEvent.bind(this, &CGlow::ShaderChange); + PHelper().CreateFloat(items, PrepareKey(pref, "Radius"), &m_fRadius, 0.01f, 10000.f); + //. PHelper().CreateFlag(items,PHelper().PrepareKey(pref,"Fixed size"), &m_Flags, gfFixedSize); +} +//---------------------------------------------------- + +bool CGlow::GetSummaryInfo(SSceneSummary *inf) +{ + inherited::GetSummaryInfo(inf); + xr_string temp = ChangeFileExt(*m_TexName, ""); + xr_strlwr(temp); + if (m_TexName.size()) + inf->AppendTexture(temp.c_str(), SSceneSummary::sttGlow, 0, 0, "$GLOW$"); + inf->glow_cnt++; + return true; +} diff --git a/src/editors/LevelEditor/Entry/Glow/Glow.h b/src/editors/LevelEditor/Entry/Glow/Glow.h new file mode 100644 index 00000000000..6f07ba60cbd --- /dev/null +++ b/src/editors/LevelEditor/Entry/Glow/Glow.h @@ -0,0 +1,74 @@ +#pragma once + +class CFrustum; + +class CGlow : public CCustomObject +{ + typedef CCustomObject inherited; + CTLSprite m_RenderSprite; + +public: + enum EFlags + { + gfFixedSize = (1 << 0), + gfForce_u8 = u8(-1) + }; + ref_shader m_GShader; + shared_str m_ShaderName; + shared_str m_TexName; + float m_fRadius; + Flags8 m_Flags; + + bool m_bDefLoad; + void ShaderChange(PropValue *value); + +private: + mutable Fvector Ftemp; + +protected: + virtual const Fvector &GetScale() const + { + Ftemp.set(m_fRadius, m_fRadius, m_fRadius); + return Ftemp; + } + virtual void SetScale(const Fvector &sc) + { + float v = m_fRadius; + if (!fsimilar(FScale.x, sc.x)) + v = sc.x; + if (!fsimilar(FScale.y, sc.y)) + v = sc.y; + if (!fsimilar(FScale.z, sc.z)) + v = sc.z; + FScale.set(v, v, v); + m_fRadius = v; + UpdateTransform(); + } + +public: + CGlow(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + virtual ~CGlow(); + virtual bool CanAttach() { return true; } + + void Compile(); + + virtual void Render(int priority, bool strictB2F); + virtual bool RayPick(float &distance, const Fvector &start, const Fvector &direction, + SRayPickInfo *pinf = NULL); + virtual bool FrustumPick(const CFrustum &frustum); + + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual bool GetBox(Fbox &box); + virtual void FillProp(LPCSTR pref, PropItemVec &values); + + // device dependent routine + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + + virtual bool GetSummaryInfo(SSceneSummary *inf); +}; diff --git a/src/editors/LevelEditor/Entry/Group/GroupObject.cpp b/src/editors/LevelEditor/Entry/Group/GroupObject.cpp new file mode 100644 index 00000000000..b3bb8bc7a0e --- /dev/null +++ b/src/editors/LevelEditor/Entry/Group/GroupObject.cpp @@ -0,0 +1,530 @@ +#include "stdafx.h" + +#define GROUPOBJ_CURRENT_VERSION_SOC 0x0011 +#define GROUPOBJ_CURRENT_VERSION 0x0012 + +#define GROUPOBJ_CHUNK_VERSION 0x0000 +#define GROUPOBJ_CHUNK_OBJECT_LIST 0x0001 +#define GROUPOBJ_CHUNK_FLAGS 0x0003 +#define GROUPOBJ_CHUNK_REFERENCE 0x0004 +#define GROUPOBJ_CHUNK_OPEN_OBJECT_LIST 0x0005 + +CGroupObject::CGroupObject(LPVOID data, LPCSTR name) : CCustomObject(data, name) +{ + Construct(data); +} + +void CGroupObject::Construct(LPVOID data) +{ + FClassID = OBJCLASS_GROUP; +} + +CGroupObject::~CGroupObject() +{ +} + +u32 CGroupObject::GetObjects(ObjectList &lst) +{ + lst.clear(); + + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + lst.push_back(it->pObject); + + return lst.size(); +} + +void CGroupObject::Select(int flag) +{ + inherited::Select(flag); + if (EPrefs->object_flags.test(epoSelectInGroup)) + { + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + it->pObject->Select(flag); + } +} + +void CGroupObject::ClearInternal(ObjectsInGroup &v) +{ + for (ObjectsInGroup::iterator it = v.begin(); it != v.end(); ++it) + { + it->pObject->m_pOwnerObject = 0; + Scene->RemoveObject(it->pObject, false, true); + xr_delete(it->pObject); + } + v.clear(); +} + +void CGroupObject::OnFrame() +{ + inherited::OnFrame(); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + it->pObject->OnFrame(); +} + +bool CGroupObject::LL_AppendObject(CCustomObject *object) +{ + if (!object->CanAttach()) + { + ELog.Msg(mtError, "Can't attach object: '%s'", object->GetName()); + return false; + } + if (object->GetOwner()) + { + if (mrNo == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Object '%s' already in group '%s'. Change group?", object->GetName(), object->GetOwner()->GetName())) + return false; + + object->OnDetach(); + } + + object->OnAttach(this); + object->m_CO_Flags.set(flObjectInGroupUnique, FALSE); + m_ObjectsInGroup.resize(m_ObjectsInGroup.size() + 1); + m_ObjectsInGroup.back().pObject = object; + + return true; +} + +bool CGroupObject::AppendObjectLoadCB(CCustomObject *object) +{ + object->m_pOwnerObject = this; + object->m_CO_Flags.set(flObjectInGroup, TRUE); + m_ObjectsInGroup.resize(m_ObjectsInGroup.size() + 1); + m_ObjectsInGroup.back().pObject = object; + + string256 buf; + Scene->GenObjectName(object->FClassID, buf, object->GetName()); + LPCSTR N = object->GetName(); + if (xr_strcmp(N, buf) != 0) + { + Msg("Load_Append name changed from[%s] to[%s]", object->GetName(), buf); + object->SetName(buf); + } + + Scene->AppendObject(object, false); + + return true; +} + +void CGroupObject::SetRefName(LPCSTR nm) +{ + m_ReferenceName_ = nm; + if (nm && strstr(nm, "light_preset")) + save_id = 1; + else + save_id = 0; +} + +//------------------------------------------------------------------------------ +bool CGroupObject::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 version = ini.r_u32(sect_name, "version"); + if (version < 0x0011) + { + ELog.DlgMsg(mtError, "CGroupObject: unsupported file version. Object can't load."); + return false; + } + CCustomObject::LoadLTX(ini, sect_name); + + Flags32 tmp_flags; + tmp_flags.zero(); + if (version < 0x0012) + tmp_flags.assign(ini.r_u32(sect_name, "flags")); + + // objects + if (/*IsOpened()*/ tmp_flags.test((1 << 0))) + { // old opened group save format + ELog.DlgMsg(mtError, "old opened group save format"); + return false; + /* + u32 cnt = ini.r_u32 (sect_name, "objects_in_group_count"); + shared_str tmp; + string128 buff; + + for (u32 k=0; kReadObjectsLTX(ini, sect_name, "ingroup", EScene::TAppendObject(this, &CGroupObject::AppendObjectLoadCB), 0); + } + VERIFY(m_ObjectsInGroup.size()); + + SetRefName(ini.r_string(sect_name, "ref_name")); + if (!m_ReferenceName_.size()) + ELog.Msg(mtError, "ERROR: group '%s' - has empty reference. Corrupted file?", GetName()); + + if (version < 0x0012) + { + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + if (it->pObject) + { + it->pObject->m_CO_Flags.set(flObjectInGroup, TRUE); + it->pObject->m_CO_Flags.set(flObjectInGroupUnique, TRUE); + } + } + + return true; +} + +void CGroupObject::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + CCustomObject::SaveLTX(ini, sect_name); + + ini.w_u32(sect_name, "version", GROUPOBJ_CURRENT_VERSION); + + ObjectList grp_lst; + GetObjects(grp_lst); + ObjectList::iterator it; + for (it = grp_lst.begin(); it != grp_lst.end(); ++it) + (*it)->m_CO_Flags.set(CCustomObject::flObjectInGroup, FALSE); + + Scene->SaveObjectsLTX(grp_lst, sect_name, "ingroup", ini); + + for (it = grp_lst.begin(); it != grp_lst.end(); ++it) + (*it)->m_CO_Flags.set(CCustomObject::flObjectInGroup, TRUE); + + ini.w_string(sect_name, "ref_name", m_ReferenceName_.c_str()); +} + +bool CGroupObject::LoadStream(IReader &F) +{ + u16 version = 0; + + R_ASSERT(F.r_chunk(GROUPOBJ_CHUNK_VERSION, &version)); + if (version < 0x0011) + { + ELog.DlgMsg(mtError, "CGroupObject: unsupported file version. Object can't load."); + return false; + } + CCustomObject::LoadStream(F); + + Flags32 tmp_flags; + tmp_flags.zero(); + if (version < 0x0012) + F.r_chunk(GROUPOBJ_CHUNK_FLAGS, &tmp_flags); + + // objects + if (tmp_flags.test(1 << 0)) // opened flag, old group format + { + ELog.DlgMsg(mtError, "Warning! Group has old format. Objects from group will be loaded ungrouped."); + return false; + } + else + { + Scene->ReadObjectsStream(F, GROUPOBJ_CHUNK_OBJECT_LIST, EScene::TAppendObject(this, &CGroupObject::AppendObjectLoadCB), 0); + } + VERIFY(m_ObjectsInGroup.size()); + + if (F.find_chunk(GROUPOBJ_CHUNK_REFERENCE)) + { + shared_str rn; + F.r_stringZ(rn); + SetRefName(rn.c_str()); + } + + if (version < 0x0012) + { + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + if (it->pObject) + { + it->pObject->m_CO_Flags.set(flObjectInGroup, TRUE); + it->pObject->m_CO_Flags.set(flObjectInGroupUnique, TRUE); + } + } + + return true; +} + +void CGroupObject::SaveStream(IWriter &F) +{ + CCustomObject::SaveStream(F); + + F.open_chunk(GROUPOBJ_CHUNK_VERSION); + + if (Core.SocSdk) + { + F.w_u16(GROUPOBJ_CURRENT_VERSION_SOC); + F.close_chunk(); + + Flags32 flags; + flags.zero(); + F.w_chunk(GROUPOBJ_CHUNK_FLAGS, &flags, sizeof(flags)); + } + else + { + F.w_u16(GROUPOBJ_CURRENT_VERSION); + F.close_chunk(); + } + + { + ObjectList grp_lst; + GetObjects(grp_lst); + ObjectList::iterator it; + for (it = grp_lst.begin(); it != grp_lst.end(); ++it) + (*it)->m_CO_Flags.set(CCustomObject::flObjectInGroup, FALSE); + + Scene->SaveObjectsStream(grp_lst, GROUPOBJ_CHUNK_OBJECT_LIST, F); + + for (it = grp_lst.begin(); it != grp_lst.end(); ++it) + (*it)->m_CO_Flags.set(CCustomObject::flObjectInGroup, TRUE); + } + + F.open_chunk(GROUPOBJ_CHUNK_REFERENCE); + F.w_stringZ(m_ReferenceName_); + F.close_chunk(); +} +//---------------------------------------------------- + +bool CGroupObject::ExportGame(SExportStreams *data) +{ + return true; +} + +void CGroupObject::ReferenceChange(PropValue *sender) +{ + UpdateReference(true); +} +//---------------------------------------------------- + +bool CGroupObject::SetReference(LPCSTR ref_name) +{ + shared_str old_refs = m_ReferenceName_; + SetRefName(ref_name); + bool bres = UpdateReference(old_refs != ref_name); + if (false == bres) + SetRefName(old_refs.c_str()); + + return bres; +} + +bool CGroupObject::UpdateReference(bool bForceReload) +{ + if (!m_ReferenceName_.size()) + { + ELog.Msg(mtError, "ERROR: '%s' - has empty reference.", GetName()); + return false; + } + + xr_string fn = m_ReferenceName_.c_str(); + fn = EFS.ChangeFileExt(fn, ".group"); + IReader *R = FS.r_open(_groups_, fn.c_str()); + bool bres = false; + if (R) + { + ObjectsInGroup ObjectsInGroupBk = m_ObjectsInGroup; + + if (bForceReload) + ClearInternal(ObjectsInGroupBk); + + m_ObjectsInGroup.clear(); + + xr_string nm = GetName(); + shared_str old_refs = m_ReferenceName_; + UpdateTransform(true); + Fvector old_pos = GetPosition(); + Fvector old_rot = GetRotation(); + Fvector old_sc = GetScale(); + + if (LoadStream(*R)) + { + SetName(nm.c_str()); + bres = true; + UpdateTransform(true); + } + FS.r_close(R); + + SetRefName(old_refs.c_str()); + NumSetPosition(old_pos); + NumSetRotation(old_rot); + NumSetScale(old_sc); + UpdateTransform(true); + + if (m_ObjectsInGroup.size() == ObjectsInGroupBk.size()) + { + ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); + ObjectsInGroup::iterator itBk = ObjectsInGroupBk.begin(); + for (; it != m_ObjectsInGroup.end(); ++it, ++itBk) + { + it->pObject->m_CO_Flags.set(flObjectInGroupUnique, FALSE); + + if (itBk->pObject->m_CO_Flags.test(flObjectInGroupUnique)) + { + std::swap(*itBk, *it); + } + else + it->pObject->SetName(itBk->pObject->GetName()); + } + } + else + { + if (ObjectsInGroupBk.size()) + { + ELog.Msg(mtError, "Not all objects synchronised correctly", GetName()); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + it->pObject->m_CO_Flags.set(flObjectInGroupUnique, FALSE); + } + else + { // first setup + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + it->pObject->m_CO_Flags.set(flObjectInGroupUnique, FALSE); + } + } + + ClearInternal(ObjectsInGroupBk); + } + else + { + ELog.Msg(mtError, "ERROR: Can't open group file: '%s'.", fn.c_str()); + } + + return bres; +} +//---------------------------------------------------- + +void CGroupObject::FillProp(LPCSTR pref, PropItemVec &items) +{ + inherited::FillProp(pref, items); + PropValue *V = PHelper().CreateChoose(items, PrepareKey(pref, "Reference"), &m_ReferenceName_, smGroup); + V->OnChangeEvent.bind(this, &CGroupObject::ReferenceChange); + + ButtonValue *B; + B = PHelper().CreateButton(items, PrepareKey(pref, "FreezeObjects"), "Unique,Reference", 0); + B->OnBtnClickEvent.bind(this, &CGroupObject::OnFreezeAllClick); + + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + string_path pk; + sprintf(pk, "%s (%s)", PrepareKey(pref, it->pObject->GetName()).c_str(), it->pObject->FParentTools->ClassDesc()); + V = PHelper().CreateFlag32(items, pk, &it->pObject->m_CO_Flags, flObjectInGroupUnique); + V->OnChangeEvent.bind(this, &CCustomObject::OnChangeIngroupUnique); + } +} + +void CGroupObject::OnFreezeAllClick(ButtonValue *sender, bool &bModif, bool &bSafe) +{ + ButtonValue *V = dynamic_cast(sender); + BOOL bDoUnique = FALSE; + switch (V->btn_num) + { + case 0: + { + bDoUnique = TRUE; + } + break; + case 1: + { + bDoUnique = FALSE; + } + break; + } + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + it->pObject->m_CO_Flags.set(flObjectInGroupUnique, bDoUnique); + + bModif = true; +} + +//---------------------------------------------------- + +void CGroupObject::OnShowHint(AStringVec &dest) +{ + inherited::OnShowHint(dest); + dest.push_back(xr_string("Reference: ") + m_ReferenceName_.c_str()); + dest.push_back(xr_string("-------")); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + dest.push_back(it->pObject->GetName()); +} +//---------------------------------------------------- + +void CGroupObject::OnObjectRemove(const CCustomObject *object) +{ + ObjectsInGroup::iterator it = std::find(m_ObjectsInGroup.begin(), m_ObjectsInGroup.end(), object); + if (it == m_ObjectsInGroup.end()) + return; + + m_ObjectsInGroup.erase(it); +} + +void CGroupObject::OnSceneUpdate() +{ + inherited::OnSceneUpdate(); + + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + if (it->pObject == NULL) + { + R_ASSERT(0); + /* + R_ASSERT(it->ObjectName.size()); + CCustomObject* CO = Scene->FindObjectByName(it->ObjectName.c_str(), (CCustomObject*)0); + + R_ASSERT2 (!CO->m_CO_Flags.test(flObjectInGroup), it->ObjectName.c_str()); + it->pObject = CO; + + string256 buf; + Scene->GenObjectName(CO->ClassID, buf, CO->GetName()); + if (CO->GetName()!=buf) + { + Msg("OG name changed from[%s] to[%s]",CO->GetName(), buf); + CO->GetName() = buf; + it->ObjectName = buf; + } + + it->pObject->m_CO_Flags.set(flObjectInGroup, TRUE); + it->pObject->m_CO_Flags.set(flObjectInGroupUnique, TRUE); + if(it->pObject==NULL) + ELog.Msg (mtError,"Gr%s' has invalid roup 'eference to object '%s'.", GetName(), it->ObjectName.c_str()); + */ + } + } + if (m_ObjectsInGroup.empty()) + { + ELog.Msg(mtInformation, "Group '%s' has no objects and will be removed.", GetName()); + DeleteThis(); + } +} + +//---------------------------------------------------- +bool CGroupObject::CanUngroup(bool bMsg) +{ + bool res = true; + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + ESceneToolBase *tool = Scene->GetTool(it->pObject->FClassID); + if (!tool->IsEditable()) + { + if (bMsg) + Msg("!.Can't detach object '%s'. Target '%s' in readonly mode.", it->pObject->GetName(), tool->ClassDesc()); + res = false; + } + } + return res; +} + +void CGroupObject::GroupObjects(ObjectList &lst) +{ + R_ASSERT(lst.size()); + for (ObjectIt it = lst.begin(); it != lst.end(); ++it) + { + if ((*it)->m_CO_Flags.test(flObjectInGroup)) + { + ELog.DlgMsg(mtInformation, "object[%s] already in group", (*it)->GetName()); + continue; + } + LL_AppendObject(*it); + } + if (m_ObjectsInGroup.size()) + UpdatePivot(0, false); +} + +void CGroupObject::UngroupObjects() +{ + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + it->pObject->OnDetach(); + + m_ObjectsInGroup.clear(); +} diff --git a/src/editors/LevelEditor/Entry/Group/GroupObject.h b/src/editors/LevelEditor/Entry/Group/GroupObject.h new file mode 100644 index 00000000000..2605aa4f2ec --- /dev/null +++ b/src/editors/LevelEditor/Entry/Group/GroupObject.h @@ -0,0 +1,80 @@ +#pragma once + +class CGroupObject : public CCustomObject +{ + typedef CCustomObject inherited; + + struct SGroupObjectItem + { + CCustomObject *pObject; + SGroupObjectItem() : pObject(NULL) {} + + bool operator==(const CCustomObject *obj) { return obj == pObject; } + }; + typedef xr_list ObjectsInGroup; + ObjectsInGroup m_ObjectsInGroup; + + bool LL_AppendObject(CCustomObject *object); + bool AppendObjectLoadCB(CCustomObject *object); + shared_str m_ReferenceName_; + void ReferenceChange(PropValue *sender); + void OnFreezeAllClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void ClearInternal(ObjectsInGroup &v); + +public: + void Clear1() { ClearInternal(m_ObjectsInGroup); }; + bool UpdateReference(bool bForceReload); + +public: + CGroupObject(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + virtual ~CGroupObject(); + bool CanUngroup(bool bMsg); + void GroupObjects(ObjectList &lst); + void UngroupObjects(); + u32 GetObjects(ObjectList &lst); + IC int ObjectInGroupCount() { return m_ObjectsInGroup.size(); } + + bool SetReference(LPCSTR nm); + virtual LPCSTR RefName() { return m_ReferenceName_.size() ? m_ReferenceName_.c_str() : "group"; } + bool RefCompare(LPCSTR nm) { return m_ReferenceName_.equal(nm); } + void SetRefName(LPCSTR nm); + void UpdatePivot(LPCSTR nm, bool center); + virtual bool GetBox(Fbox &box); + virtual bool CanAttach() { return false; } + + virtual void NumSetPosition(const Fvector &pos); + virtual void NumSetRotation(const Fvector &rot); + virtual void NumSetScale(const Fvector &scale); + virtual void MoveTo(const Fvector &pos, const Fvector &up); + virtual void Move(Fvector &amount); + virtual void RotateParent(Fvector &axis, float angle); + virtual void RotateLocal(Fvector &axis, float angle); + virtual void Scale(Fvector &amount); + + virtual void Render(int priority, bool strictB2F); + + virtual bool RayPick(float &dist, const Fvector &start, const Fvector &dir, SRayPickInfo *pinf = NULL); + virtual bool FrustumPick(const CFrustum &frustum); + + virtual void OnUpdateTransform(); + virtual void OnFrame(); + virtual void Select(int flag); + + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual bool ExportGame(SExportStreams *data); + + // device dependent routine + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + + virtual void OnShowHint(AStringVec &dest); + virtual void OnObjectRemove(const CCustomObject *object); + virtual void OnSceneUpdate(); + + virtual void FillProp(LPCSTR pref, PropItemVec &items); +}; diff --git a/src/editors/LevelEditor/Entry/Group/GroupObjectUtils.cpp b/src/editors/LevelEditor/Entry/Group/GroupObjectUtils.cpp new file mode 100644 index 00000000000..a44bf010514 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Group/GroupObjectUtils.cpp @@ -0,0 +1,318 @@ +#include "stdafx.h" + +static const float EMPTY_GROUP_SIZE = 0.5f; + +bool CGroupObject::GetBox(Fbox &bb) +{ + bb.invalidate(); + // update box + for (ObjectsInGroup::const_iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + switch (it->pObject->FClassID) + { + case OBJCLASS_SPAWNPOINT: + case OBJCLASS_SCENEOBJECT: + case OBJCLASS_WAY: + { + Fbox box; + if (it->pObject->GetBox(box)) + bb.merge(box); + } + break; + default: + bb.modify(it->pObject->GetPosition()); + } + } + if (!bb.is_valid()) + { + bb.set(GetPosition(), GetPosition()); + bb.grow(EMPTY_GROUP_SIZE); + } + return bb.is_valid(); +} + +void CGroupObject::OnUpdateTransform() +{ + inherited::OnUpdateTransform(); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + it->pObject->OnUpdateTransform(); +} + +void CGroupObject::UpdatePivot(LPCSTR nm, bool center) +{ + // first init + VERIFY(m_ObjectsInGroup.size()); + ObjectsInGroup::iterator it; + if (false == center) + { + CCustomObject *object = 0; + if (nm && nm[0]) + { + for (it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + if (0 == strcmp(nm, it->pObject->GetName())) + { + object = it->pObject; + break; + } + } + } + else + { + bool bValidPivot = false; + for (it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + if (it->pObject->FClassID == OBJCLASS_SCENEOBJECT) + { + object = it->pObject; + bValidPivot = true; + break; + } + } + if (!bValidPivot) + object = m_ObjectsInGroup.front().pObject; + } + if (object) + { + SetPosition(object->GetPosition()); + SetRotation(object->GetRotation()); + UpdateTransform(true); + } + } + else + { + // center alignment + it = m_ObjectsInGroup.begin(); + Fvector C; + C.set(it->pObject->GetPosition()); + it++; + + for (; it != m_ObjectsInGroup.end(); ++it) + C.add(it->pObject->GetPosition()); + + FPosition.div(C, static_cast(m_ObjectsInGroup.size())); + FRotation.set(0, 0, 0); + UpdateTransform(true); + } +} + +void CGroupObject::MoveTo(const Fvector &pos, const Fvector &up) +{ + Fvector old_r = FRotation; + inherited::MoveTo(pos, up); + Fmatrix prev; + prev.invert(FTransform); + UpdateTransform(true); + + Fvector dr; + dr.sub(FRotation, old_r); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + Fvector r = it->pObject->GetRotation(); + r.add(dr); + it->pObject->SetRotation(r); + Fvector v = it->pObject->GetPosition(); + prev.transform_tiny(v); + FTransform.transform_tiny(v); + it->pObject->SetPosition(v); + } +} + +void CGroupObject::NumSetPosition(const Fvector &pos) +{ + inherited::NumSetPosition(pos); + Fmatrix prev; + prev.invert(FTransform); + UpdateTransform(true); + + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + Fvector v = it->pObject->GetPosition(); + prev.transform_tiny(v); + FTransform.transform_tiny(v); + it->pObject->SetPosition(v); + } +} +void CGroupObject::NumSetRotation(const Fvector &rot) +{ + Fvector old_r; + FTransformR.getXYZ(old_r); + inherited::NumSetRotation(rot); + Fmatrix prev; + prev.invert(FTransform); + UpdateTransform(true); + + Fvector dr; + dr.sub(FRotation, old_r); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + Fvector r = it->pObject->GetRotation(); + r.add(dr); + it->pObject->SetRotation(r); + Fvector v = it->pObject->GetPosition(); + prev.transform_tiny(v); + FTransform.transform_tiny(v); + it->pObject->SetPosition(v); + } +} +void CGroupObject::NumSetScale(const Fvector &scale) +{ + Fvector old_s = GetScale(); + inherited::NumSetScale(scale); + Fmatrix prev; + prev.invert(FTransform); + UpdateTransform(true); + + Fvector ds; + ds.sub(FScale, old_s); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + Fvector s = it->pObject->GetScale(); + s.add(ds); + it->pObject->SetScale(s); + Fvector v = it->pObject->GetPosition(); + prev.transform_tiny(v); + FTransform.transform_tiny(v); + it->pObject->SetPosition(v); + } +} + +void CGroupObject::Move(Fvector &amount) +{ + Fvector old_r = FRotation; + inherited::Move(amount); + Fmatrix prev; + prev.invert(FTransform); + UpdateTransform(true); + + Fvector dr; + dr.sub(FRotation, old_r); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + Fvector r = it->pObject->GetRotation(); + r.add(dr); + it->pObject->SetRotation(r); + Fvector v = it->pObject->GetPosition(); + prev.transform_tiny(v); + FTransform.transform_tiny(v); + it->pObject->SetPosition(v); + } +} +void CGroupObject::RotateParent(Fvector &axis, float angle) +{ + inherited::RotateParent(axis, angle); + Fmatrix Ginv; + Ginv.set(FITransformRP); + UpdateTransform(true); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + Fmatrix O, On; + O.mul(Ginv, it->pObject->FTransformRP); + On.mul(FTransform, O); + Fvector xyz; + On.getXYZ(xyz); + it->pObject->NumSetRotation(xyz); + it->pObject->NumSetPosition(On.c); + } +} + +void CGroupObject::RotateLocal(Fvector &axis, float angle) +{ + inherited::RotateLocal(axis, angle); + Fmatrix Ginv; + Ginv.set(FITransformRP); + UpdateTransform(true); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + Fmatrix O, On; + O.mul(Ginv, it->pObject->FTransformRP); + On.mul(FTransform, O); + Fvector xyz; + On.getXYZ(xyz); + it->pObject->NumSetRotation(xyz); + it->pObject->NumSetPosition(On.c); + } +} + +void CGroupObject::Scale(Fvector &amount) +{ + inherited::Scale(amount); + Fmatrix m_old; + m_old.invert(FTransform); + UpdateTransform(true); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + it->pObject->ScalePivot(m_old, FTransform, amount); +} + +void CGroupObject::Render(int priority, bool strictB2F) +{ + inherited::Render(priority, strictB2F); + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + { + if (it->pObject->IsRender()) + { + switch (it->pObject->FClassID) + { + case OBJCLASS_SCENEOBJECT: + it->pObject->Render(priority, strictB2F); + break; + default: + EDevice.SetShader(strictB2F ? EDevice.m_SelectionShader : EDevice.m_WireShader); + RCache.set_xform_world(Fidentity); + it->pObject->Render(priority, strictB2F); + } + } + } + if ((1 == priority) && (false == strictB2F)) + { + Fbox bb; + if (Selected() && GetBox(bb)) + { + EDevice.SetShader(EDevice.m_WireShader); + RCache.set_xform_world(Fidentity); + u32 clr = 0xFF7070FF; + DU_impl.DrawSelectionBoxB(bb, &clr); + } + } +} + +bool CGroupObject::FrustumPick(const CFrustum &frustum) +{ + if (m_ObjectsInGroup.empty()) + { + Fbox bb; + GetBox(bb); + u32 mask = u32(-1); + return (frustum.testAABB(bb.data(), mask)); + } + else + { + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + if (it->pObject->FrustumPick(frustum)) + return true; + } + return false; +} + +bool CGroupObject::RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf) +{ + bool bPick = false; + + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + if (it->pObject->RayPick(distance, start, direction, pinf)) + bPick = true; + + return bPick; +} + +void CGroupObject::OnDeviceCreate() +{ + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + it->pObject->OnDeviceCreate(); +} + +void CGroupObject::OnDeviceDestroy() +{ + for (ObjectsInGroup::iterator it = m_ObjectsInGroup.begin(); it != m_ObjectsInGroup.end(); ++it) + it->pObject->OnDeviceDestroy(); +} diff --git a/src/editors/LevelEditor/Entry/Light/ELight.cpp b/src/editors/LevelEditor/Entry/Light/ELight.cpp new file mode 100644 index 00000000000..5f128673254 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Light/ELight.cpp @@ -0,0 +1,255 @@ +#include "stdafx.h" + +static const u32 LIGHT_VERSION = 0x0011; + +enum +{ + LIGHT_CHUNK_VERSION = 0xB411, + LIGHT_CHUNK_FLAG = 0xB413, + LIGHT_CHUNK_BRIGHTNESS = 0xB425, + LIGHT_CHUNK_D3D_PARAMS = 0xB435, + LIGHT_CHUNK_USE_IN_D3D = 0xB436, + LIGHT_CHUNK_ROTATE = 0xB437, + LIGHT_CHUNK_ANIMREF = 0xB438, + LIGHT_CHUNK_SPOT_TEXTURE = 0xB439, + LIGHT_CHUNK_FUZZY_DATA = 0xB440, + LIGHT_CHUNK_LCONTROL = 0xB441, + LIGHT_CHUNK_PARAMS = 0xB442, +}; + +#define VIS_RADIUS 0.25f +#define SEL_COLOR 0x00FFFFFF +#define NORM_COLOR 0x00FFFF00 +#define NORM_DYN_COLOR 0x0000FF00 +#define LOCK_COLOR 0x00FF0000 + +CLight::CLight(LPVOID data, LPCSTR name) : CCustomObject(data, name) +{ + Construct(data); +} + +void CLight::Construct(LPVOID data) +{ + FClassID = OBJCLASS_LIGHT; + + m_UseInD3D = TRUE; + + m_FuzzyData = 0; + + m_Type = ELight::ltPoint; + m_Color.set(1.f, 1.f, 1.f, 0); + m_Brightness = 1.f; + m_Attenuation0 = 1.f; + m_Attenuation1 = 0.f; + m_Attenuation2 = 0.f; + m_Range = 8.f; + m_Cone = PI_DIV_8; + + m_VirtualSize = 0.f; + + m_pAnimRef = 0; + m_LControl = 0; + + m_Flags.assign(ELight::flAffectStatic); +} + +CLight::~CLight() +{ + xr_delete(m_FuzzyData); +} + +void CLight::OnUpdateTransform() +{ + FScale.set(1.f, 1.f, 1.f); + inherited::OnUpdateTransform(); +} + +void CLight::CopyFrom(CLight *src) +{ + THROW2("CLight:: Go to AlexMX"); +} + +void CLight::AffectD3D(BOOL flag) +{ + m_UseInD3D = flag; + UI->UpdateScene(); +} +//---------------------------------------------------- + +bool CLight::GetBox(Fbox &box) +{ + box.set(GetPosition(), GetPosition()); + box.vMin.sub(m_Range); + box.vMax.add(m_Range); + return true; +} + +void CLight::Render(int priority, bool strictB2F) +{ + inherited::Render(priority, strictB2F); + if ((1 == priority) && (false == strictB2F)) + { + EDevice.SetShader(EDevice.m_WireShader); + RCache.set_xform_world(Fidentity); + u32 clr = Selected() ? SEL_COLOR : (m_Flags.is(ELight::flAffectDynamic) ? NORM_DYN_COLOR : NORM_COLOR); + switch (m_Type) + { + case ELight::ltPoint: + if (Selected()) + DU_impl.DrawLineSphere(GetPosition(), m_Range, clr, true); + + DU_impl.DrawPointLight(GetPosition(), VIS_RADIUS, clr); + if (m_Flags.is(ELight::flPointFuzzy)) + { + VERIFY(m_FuzzyData); + for (FvectorIt it = m_FuzzyData->m_Positions.begin(); it != m_FuzzyData->m_Positions.end(); it++) + { + Fvector tmp; + _Transform().transform_tiny(tmp, *it); + DU_impl.DrawPointLight(tmp, VIS_RADIUS / 6, clr); + } + } + break; + case ELight::ltSpot: + { + // Fvector dir; + // dir.setHP (GetRotation().y,GetRotation().x); + // DU.DrawCone (Fidentity, GetPosition(), dir, Selected()?m_Range:VIS_RADIUS, radius2, clr, true, false); + if (Selected()) + DU_impl.DrawSpotLight(GetPosition(), FTransformR.k, m_Range, m_Cone, clr); + else + DU_impl.DrawSpotLight(GetPosition(), FTransformR.k, VIS_RADIUS, m_Cone, clr); + } + break; + default: + THROW; + } + ESceneLightTool *lt = dynamic_cast(FParentTools); + VERIFY(lt); + + if (lt->m_Flags.is(ESceneLightTool::flShowControlName)) + { + Fvector D; + D.sub(EDevice.vCameraPosition, GetPosition()); + float dist = D.normalize_magn(); + if (!Scene->RayPickObject(dist, GetPosition(), D, OBJCLASS_SCENEOBJECT, 0, 0)) + DU_impl.OutText(GetPosition(), make_string(" %s", GetLControlName()).c_str(), 0xffffffff, 0xff000000); + } + } + else if ((1 == priority) && (true == strictB2F)) + { + EDevice.SetShader(EDevice.m_SelectionShader); + RCache.set_xform_world(Fidentity); + switch (m_Type) + { + case ELight::ltPoint: + if (m_Flags.is(ELight::flPointFuzzy)) + { + u32 clr = Selected() ? SEL_COLOR : (m_Flags.is(ELight::flAffectDynamic) ? NORM_DYN_COLOR : NORM_COLOR); + clr = subst_alpha(clr, 0x40); + const Fvector zero = {0.f, 0.f, 0.f}; + VERIFY(m_FuzzyData); + switch (m_FuzzyData->m_ShapeType) + { + case CLight::SFuzzyData::fstSphere: + DU_impl.DrawSphere(_Transform(), zero, m_FuzzyData->m_SphereRadius, clr, clr, true, true); + break; + case CLight::SFuzzyData::fstBox: + DU_impl.DrawAABB(_Transform(), zero, m_FuzzyData->m_BoxDimension, clr, clr, true, true); + break; + } + } + break; + case ELight::ltSpot: + break; + default: + THROW; + } + } +} + +bool CLight::FrustumPick(const CFrustum &frustum) +{ + // return (frustum.testSphere(m_Position,m_Range))?true:false; + return (frustum.testSphere_dirty(GetPosition(), VIS_RADIUS)) ? true : false; +} + +bool CLight::RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf) +{ + Fvector ray2; + ray2.sub(GetPosition(), start); + + float d = ray2.dotproduct(direction); + if (d > 0) + { + float d2 = ray2.magnitude(); + if (((d2 * d2 - d * d) < (VIS_RADIUS * VIS_RADIUS)) && (d > VIS_RADIUS)) + { + if (d < distance) + { + distance = d; + return true; + } + } + } + return false; +} +//---------------------------------------------------- + +void CLight::OnFrame() +{ + inherited::OnFrame(); +} +//---------------------------------------------------- + +void CLight::Update() +{ + UpdateTransform(); +} +//---------------------------------------------------- + +LPCSTR CLight::GetLControlName() +{ + ESceneLightTool *lt = dynamic_cast(FParentTools); + VERIFY(lt); + xr_rtoken *lc = lt->FindLightControl(m_LControl); + return lc ? *lc->name : 0; +} +//---------------------------------------------------- + +void CLight::OnNeedUpdate(PropValue *value) +{ + Update(); +} +//---------------------------------------------------- + +bool CLight::GetSummaryInfo(SSceneSummary *inf) +{ + inherited::GetSummaryInfo(inf); + switch (m_Type) + { + case ELight::ltPoint: + inf->light_point_cnt++; + break; + case ELight::ltSpot: + inf->light_spot_cnt++; + break; + } + + switch (m_Type) + { + case ELight::ltPoint: + case ELight::ltSpot: + if (m_Flags.is(ELight::flAffectStatic)) + inf->light_static_cnt++; + if (m_Flags.is(ELight::flAffectDynamic)) + inf->light_dynamic_cnt++; + if (m_Flags.is(ELight::flProcedural)) + inf->light_procedural_cnt++; + if (m_Flags.is(ELight::flBreaking)) + inf->light_breakable_cnt++; + break; + } + return true; +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Entry/Light/ELight.h b/src/editors/LevelEditor/Entry/Light/ELight.h new file mode 100644 index 00000000000..951026b1acc --- /dev/null +++ b/src/editors/LevelEditor/Entry/Light/ELight.h @@ -0,0 +1,165 @@ +#pragma once + +namespace ELight +{ + enum EFlags + { + flAffectStatic = (1 << 0), + flAffectDynamic = (1 << 1), + flProcedural = (1 << 2), + flBreaking = (1 << 3), + flPointFuzzy = (1 << 4), + flCastShadow = (1 << 5), + }; + + enum EType + { + ltPoint = D3DLIGHT_POINT, + ltSpot = D3DLIGHT_SPOT, + ltDirect = D3DLIGHT_DIRECTIONAL, + ltMaxCount, + lt_max_type = u32(-1), + }; +}; + +#define LCONTROL_HEMI "$hemi" // hemisphere +#define LCONTROL_SUN "$sun" // sun +#define LCONTROL_STATIC "$static" // all other static lights + +// refs +class CLAItem; + +class CLight : public CCustomObject +{ +protected: + typedef CCustomObject inherited; + +public: + // flags + Flags32 m_Flags; + + // light + ELight::EType m_Type; /* Type of light source */ + Fcolor m_Color; /* Diffuse color of light */ + float m_Brightness; + float m_Range; /* Cutoff range */ + float m_Attenuation0; /* Constant attenuation */ + float m_Attenuation1; /* Linear attenuation */ + float m_Attenuation2; /* Quadratic attenuation */ + float m_Cone; /* Outer angle of spotlight cone */ + + float m_VirtualSize; + + CLAItem *m_pAnimRef; + + // spot light + shared_str m_FalloffTex; + + // controller + u32 m_LControl; + + // build options + BOOL m_UseInD3D; + + // fuzzy + struct SFuzzyData + { + enum EShapeType + { + fstSphere, + fstBox, + fstForceU8 = u8(-1) + }; + EShapeType m_ShapeType; + float m_SphereRadius; + Fvector m_BoxDimension; + s16 m_PointCount; + FvectorVec m_Positions; + SFuzzyData() + { + m_ShapeType = fstSphere; + m_SphereRadius = 0.1f; + m_BoxDimension.set(0.1f, 0.1f, 0.1f); + m_PointCount = 1; + m_Positions.resize(m_PointCount, Fvector().set(0, 0, 0)); + } + void Generate(Fvector &p) + { + switch (m_ShapeType) + { + case fstSphere: + p.random_point(m_SphereRadius); + break; + case fstBox: + p.random_point(m_BoxDimension); + break; + } + } + void SaveStream(IWriter &F); + void LoadStream(IReader &F); + void SaveLTX(CInifile &ini, LPCSTR sect_name); + void LoadLTX(CInifile &ini, LPCSTR sect_name); + }; + SFuzzyData *m_FuzzyData; + + virtual void OnUpdateTransform(); + void OnTypeChange(PropValue *value); + + void OnFuzzyFlagChange(PropValue *value); + void OnFuzzyDataChange(PropValue *value); + void OnFuzzyTypeChange(PropValue *value); + + void OnFuzzyGenerateClick(ButtonValue *value, bool &bModif, bool &bSafe); + void OnAutoClick(ButtonValue *value, bool &bModif, bool &bSafe); + void OnNeedUpdate(PropValue *value); + + void OnPointDataChange(PropValue *value); + void OnAttenuationDraw(CanvasValue *sender); + void OnPointDataTestEqual(CanvasValue *a, CanvasValue *b, bool &res); + +protected: + // virtual Fvector& GetPosition () { return m_D3D.position; } + // virtual void SetPosition (const Fvector& pos) { m_D3D.position.set(pos); UpdateTransform();} +public: + CLight(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + virtual ~CLight(); + void CopyFrom(CLight *src); + virtual bool CanAttach() { return true; } + + // pick functions + virtual bool RayPick(float &distance, const Fvector &start, const Fvector &direction, + SRayPickInfo *pinf = NULL); + virtual bool FrustumPick(const CFrustum &frustum); + + // change position/orientation methods + virtual void Scale(Fvector &amount) { ; } + + // placement functions + virtual bool GetBox(Fbox &box); + + // file system function + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual void FillProp(LPCSTR pref, PropItemVec &items); + void FillSunProp(LPCSTR pref, PropItemVec &items); + void FillPointProp(LPCSTR pref, PropItemVec &items); + void FillSpotProp(LPCSTR pref, PropItemVec &items); + void FillAttProp(LPCSTR pref, PropItemVec &items); + virtual bool GetSummaryInfo(SSceneSummary *inf); + + // render utility function + void AffectD3D(BOOL flag); + + virtual void Render(int priority, bool strictB2F); + virtual void OnFrame(); + void Update(); + + LPCSTR GetLControlName(); + + // events + virtual void OnShowHint(AStringVec &dest); +}; diff --git a/src/editors/LevelEditor/Entry/Light/ELight_IO.cpp b/src/editors/LevelEditor/Entry/Light/ELight_IO.cpp new file mode 100644 index 00000000000..c3623c0765d --- /dev/null +++ b/src/editors/LevelEditor/Entry/Light/ELight_IO.cpp @@ -0,0 +1,283 @@ +#include "stdafx.h" + +static const u32 LIGHT_VERSION = 0x0011; + +enum +{ + LIGHT_CHUNK_VERSION = 0xB411, + LIGHT_CHUNK_FLAG = 0xB413, + LIGHT_CHUNK_BRIGHTNESS = 0xB425, + LIGHT_CHUNK_D3D_PARAMS = 0xB435, + LIGHT_CHUNK_USE_IN_D3D = 0xB436, + LIGHT_CHUNK_ROTATE = 0xB437, + LIGHT_CHUNK_ANIMREF = 0xB438, + LIGHT_CHUNK_FALLOFF_TEXTURE = 0xB439, + LIGHT_CHUNK_FUZZY_DATA = 0xB440, + LIGHT_CHUNK_LCONTROL = 0xB441, + LIGHT_CHUNK_PARAMS = 0xB442, +}; + +void CLight::SFuzzyData::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + ini.w_u8(sect_name, "fuzzy_shape_type", m_ShapeType); + ini.w_float(sect_name, "fuzzy_sphere_radius", m_SphereRadius); + ini.w_fvector3(sect_name, "fuzzy_box_dim", m_BoxDimension); + ini.w_u32(sect_name, "fuzzy_point_count", m_PointCount); + + string128 buff; + for (u32 idx = 0; idx < m_PointCount; ++idx) + { + sprintf(buff, "fuzzy_point_%d", idx); + ini.w_fvector3(sect_name, buff, m_Positions[idx]); + } +} + +void CLight::SFuzzyData::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + m_ShapeType = static_cast(ini.r_u8(sect_name, "fuzzy_shape_type")); + m_SphereRadius = ini.r_float(sect_name, "fuzzy_sphere_radius"); + m_BoxDimension = ini.r_fvector3(sect_name, "fuzzy_box_dim"); + m_PointCount = ini.r_u32(sect_name, "fuzzy_point_count"); + + string128 buff; + m_Positions.clear(); + for (u32 idx = 0; idx < m_PointCount; ++idx) + { + sprintf(buff, "fuzzy_point_%d", idx); + Fvector p = ini.r_fvector3(sect_name, buff); + m_Positions.push_back(p); + } +} + +void CLight::SFuzzyData::SaveStream(IWriter &F) +{ + F.w_u8(m_ShapeType); + F.w_float(m_SphereRadius); + F.w_fvector3(m_BoxDimension); + F.w_s16(m_PointCount); + F.w(&*m_Positions.begin(), sizeof(Fvector) * m_PointCount); +} + +void CLight::SFuzzyData::LoadStream(IReader &F) +{ + m_ShapeType = (EShapeType)F.r_u8(); + m_SphereRadius = F.r_float(); + F.r_fvector3(m_BoxDimension); + m_PointCount = F.r_s16(); + m_Positions.resize(m_PointCount); + F.r(&*m_Positions.begin(), sizeof(Fvector) * m_PointCount); +} + +bool CLight::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 version = ini.r_u32(sect_name, "version"); + + if (version != LIGHT_VERSION) + { + ELog.DlgMsg(mtError, "CLight: Unsupported version."); + return false; + } + + CCustomObject::LoadLTX(ini, sect_name); + + m_Type = (ELight::EType)(ini.r_u32(sect_name, "type")); + m_Color = ini.r_fcolor(sect_name, "color"); + m_Brightness = ini.r_float(sect_name, "brightness"); + m_Range = ini.r_float(sect_name, "range"); + m_Attenuation0 = ini.r_float(sect_name, "attenuation0"); + m_Attenuation1 = ini.r_float(sect_name, "attenuation1"); + m_Attenuation2 = ini.r_float(sect_name, "attenuation2"); + m_Cone = ini.r_float(sect_name, "cone"); + m_VirtualSize = ini.r_float(sect_name, "virtual_size"); + + m_UseInD3D = ini.r_bool(sect_name, "use_in_d3d"); + m_Flags.assign(ini.r_u32(sect_name, "light_flags")); + m_LControl = ini.r_u32(sect_name, "light_control"); + + LPCSTR anm = ini.r_string(sect_name, "anim_ref_name"); + if (anm) + { + m_pAnimRef = LALib.FindItem(anm); + if (!m_pAnimRef) + ELog.Msg(mtError, "Can't find light animation: %s", anm); + } + + m_FalloffTex = ini.r_string(sect_name, "fallof_texture"); + + if (m_Flags.is(ELight::flPointFuzzy)) + { + m_FuzzyData = xr_new(); + m_FuzzyData->LoadLTX(ini, sect_name); + } + + UpdateTransform(); + return true; +} + +void CLight::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + CCustomObject::SaveLTX(ini, sect_name); + + ini.w_u16(sect_name, "version", LIGHT_VERSION); + + ini.w_u32(sect_name, "type", m_Type); + ini.w_fcolor(sect_name, "color", m_Color); + ini.w_float(sect_name, "brightness", m_Brightness); + ini.w_float(sect_name, "range", m_Range); + ini.w_float(sect_name, "attenuation0", m_Attenuation0); + ini.w_float(sect_name, "attenuation1", m_Attenuation1); + ini.w_float(sect_name, "attenuation2", m_Attenuation2); + ini.w_float(sect_name, "cone", m_Cone); + ini.w_float(sect_name, "virtual_size", m_VirtualSize); + + ini.w_bool(sect_name, "use_in_d3d", m_UseInD3D); + ini.w_u32(sect_name, "light_flags", m_Flags.get()); + ini.w_u32(sect_name, "light_control", m_LControl); + + ini.w_string(sect_name, "anim_ref_name", (m_pAnimRef) ? m_pAnimRef->cName.c_str() : ""); + + ini.w_string(sect_name, "fallof_texture", m_FalloffTex.c_str()); + + if (m_Flags.is(ELight::flPointFuzzy)) + { + VERIFY(m_FuzzyData); + m_FuzzyData->SaveLTX(ini, sect_name); + } +} + +bool CLight::LoadStream(IReader &F) +{ + u16 version = 0; + + string1024 buf; + R_ASSERT(F.r_chunk(LIGHT_CHUNK_VERSION, &version)); + if ((version != 0x0010) && (version != LIGHT_VERSION)) + { + ELog.DlgMsg(mtError, "CLight: Unsupported version."); + return false; + } + + CCustomObject::LoadStream(F); + + if (F.find_chunk(LIGHT_CHUNK_PARAMS)) + { + m_Type = (ELight::EType)F.r_u32(); + F.r_fcolor(m_Color); + m_Brightness = F.r_float(); + m_Range = F.r_float(); + m_Attenuation0 = F.r_float(); + m_Attenuation1 = F.r_float(); + m_Attenuation2 = F.r_float(); + m_Cone = F.r_float(); + m_VirtualSize = F.r_float(); + } + else + { + R_ASSERT(F.find_chunk(LIGHT_CHUNK_D3D_PARAMS)); + Flight d3d; + F.r(&d3d, sizeof(d3d)); + m_Type = (ELight::EType)d3d.type; + m_Color.set(d3d.diffuse); + SetPosition(d3d.position); + m_Range = d3d.range; + m_Attenuation0 = d3d.attenuation0; + m_Attenuation1 = d3d.attenuation1; + m_Attenuation2 = d3d.attenuation2; + m_Cone = d3d.phi; + R_ASSERT(F.r_chunk(LIGHT_CHUNK_BRIGHTNESS, &m_Brightness)); + } + + R_ASSERT(F.r_chunk(LIGHT_CHUNK_USE_IN_D3D, &m_UseInD3D)); + + if (F.find_chunk(LIGHT_CHUNK_FLAG)) + F.r(&m_Flags.flags, sizeof(m_Flags)); + + if (F.find_chunk(LIGHT_CHUNK_LCONTROL)) + F.r(&m_LControl, sizeof(m_LControl)); + + if (D3DLIGHT_DIRECTIONAL == m_Type) + { + ESceneLightTool *lt = dynamic_cast(FParentTools); + VERIFY(lt); + lt->m_SunShadowDir.set(FRotation.x, FRotation.y); + ELog.DlgMsg(mtError, "CLight: Can't load sun."); + return false; + } + + if (F.find_chunk(LIGHT_CHUNK_ANIMREF)) + { + F.r_stringZ(buf, sizeof(buf)); + m_pAnimRef = LALib.FindItem(buf); + if (!m_pAnimRef) + ELog.Msg(mtError, "Can't find light animation: %s", buf); + } + + if (F.find_chunk(LIGHT_CHUNK_FALLOFF_TEXTURE)) + { + F.r_stringZ(m_FalloffTex); + } + + if (F.find_chunk(LIGHT_CHUNK_FUZZY_DATA)) + { + m_FuzzyData = xr_new(); + m_FuzzyData->LoadStream(F); + m_Flags.set(ELight::flPointFuzzy, TRUE); + } + else + { + m_Flags.set(ELight::flPointFuzzy, FALSE); + } + + UpdateTransform(); + + return true; +} +//---------------------------------------------------- + +void CLight::SaveStream(IWriter &F) +{ + CCustomObject::SaveStream(F); + + F.open_chunk(LIGHT_CHUNK_VERSION); + F.w_u16(LIGHT_VERSION); + F.close_chunk(); + + F.open_chunk(LIGHT_CHUNK_PARAMS); + F.w_u32(m_Type); + F.w_fcolor(m_Color); + F.w_float(m_Brightness); + F.w_float(m_Range); + F.w_float(m_Attenuation0); + F.w_float(m_Attenuation1); + F.w_float(m_Attenuation2); + F.w_float(m_Cone); + F.w_float(m_VirtualSize); + F.close_chunk(); + + F.w_chunk(LIGHT_CHUNK_USE_IN_D3D, &m_UseInD3D, sizeof(m_UseInD3D)); + F.w_chunk(LIGHT_CHUNK_FLAG, &m_Flags, sizeof(m_Flags)); + F.w_chunk(LIGHT_CHUNK_LCONTROL, &m_LControl, sizeof(m_LControl)); + + if (m_pAnimRef) + { + F.open_chunk(LIGHT_CHUNK_ANIMREF); + F.w_stringZ(m_pAnimRef->cName); + F.close_chunk(); + } + + if (m_FalloffTex.size()) + { + F.open_chunk(LIGHT_CHUNK_FALLOFF_TEXTURE); + F.w_stringZ(m_FalloffTex); + F.close_chunk(); + } + + if (m_Flags.is(ELight::flPointFuzzy)) + { + VERIFY(m_FuzzyData); + F.open_chunk(LIGHT_CHUNK_FUZZY_DATA); + m_FuzzyData->SaveStream(F); + F.close_chunk(); + } +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Entry/Light/ELight_props.cpp b/src/editors/LevelEditor/Entry/Light/ELight_props.cpp new file mode 100644 index 00000000000..01d2fa6de75 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Light/ELight_props.cpp @@ -0,0 +1,309 @@ +#include "stdafx.h" + +void CLight::OnAutoClick(ButtonValue *value, bool &bModif, bool &bSafe) +{ + ButtonValue *B = dynamic_cast(value); + R_ASSERT(B); + switch (B->btn_num) + { + case 0: + { + float P = 0.1f; + m_Attenuation0 = 1.f; + m_Attenuation1 = (m_Brightness - P - P * m_Range * m_Range * m_Attenuation2) / (P * m_Range); + clamp(m_Attenuation1, 0.f, 1.f); + } + break; + case 1: + { + float P = 0.1f; + m_Attenuation0 = 1.f; + m_Attenuation2 = (m_Brightness - P - P * m_Range * m_Attenuation1) / (P * m_Range * m_Range); + clamp(m_Attenuation2, 0.f, 1.f); + } + } + bModif = true; + OnPointDataChange(value); +} + +void CLight::OnFuzzyGenerateClick(ButtonValue *value, bool &bModif, bool &bSafe) +{ + ButtonValue *B = dynamic_cast(value); + R_ASSERT(B); + switch (B->btn_num) + { + case 0: + { + OnFuzzyDataChange(value); + } + break; + } + bModif = true; +} + +void CLight::OnFuzzyFlagChange(PropValue *value) +{ + if (m_Flags.is(ELight::flPointFuzzy)) + { + m_FuzzyData = xr_new(); + OnFuzzyTypeChange(value); + } + else + { + xr_delete(m_FuzzyData); + OnTypeChange(value); + } +} + +void CLight::OnFuzzyTypeChange(PropValue *value) +{ + OnTypeChange(value); + OnFuzzyDataChange(value); +} + +void CLight::OnFuzzyDataChange(PropValue *value) +{ + VERIFY(m_FuzzyData); + m_FuzzyData->m_Positions.resize(m_FuzzyData->m_PointCount); + for (FvectorIt it = m_FuzzyData->m_Positions.begin(); it != m_FuzzyData->m_Positions.end(); it++) + m_FuzzyData->Generate(*it); +} + +#define X_GRID 14 +#define Y_GRID 6 + +void CLight::OnAttenuationDraw(CanvasValue *sender) +{ + /*TCanvas* canvas = (TCanvas*)_canvas; + const TRect& rect = *((TRect*)&_rect); +// canvas + int w = rect.Width(); + int h = rect.Height(); + int x0= rect.left; + int y0= rect.top; + + canvas->Brush->Color = clBlack; + canvas->FillRect(rect); + canvas->Pen->Color = TColor(0x00006600); + canvas->MoveTo(x0,y0); + for (int i=0; iLineTo(x0+i*w/X_GRID,y0+h); + canvas->MoveTo(x0+(i+1)*w/X_GRID,y0+0); + } + canvas->MoveTo(x0+0,y0+0); + for (int j=0; jLineTo(x0+w,y0+j*h/Y_GRID); + canvas->MoveTo(x0+0,y0+(j+1)*h/Y_GRID); + } + canvas->Pen->Color = clYellow; + canvas->MoveTo(x0+0,y0+h/2); + canvas->LineTo(x0+w,y0+h/2); + + float d_cost = m_Range/w; + xr_string temp; +// float v = m_D3D.range; +// temp.sprintf("Range = %.2f",v); lbRange->Caption = temp; + canvas->Pen->Color = clLime; + if (!(fis_zero(m_Attenuation0)&&fis_zero(m_Attenuation1)&&fis_zero(m_Attenuation2))){ + for (int d=1; dMoveTo(x0+d,y); +else canvas->LineTo(x0+d,y); +} +}*/ +#define WIETH 90 +#define HEIGHT 80.f + float d_cost = m_Range / WIETH; + static float values[WIETH] = {}; + + for (int i = 0; i < WIETH; i++) + { + values[i] = 0; + } + + if (!(fis_zero(m_Attenuation0) && fis_zero(m_Attenuation1) && fis_zero(m_Attenuation2))) + { + for (int d = 1; d < WIETH + 1; d++) + { + float R = d * d_cost; + float b = m_Brightness / (m_Attenuation0 + m_Attenuation1 * R + m_Attenuation2 * R * R); + b -= m_Brightness * R / (m_Range * (m_Attenuation0 + m_Attenuation1 * m_Range + m_Attenuation2 * m_Range * m_Range)); + float bb = (HEIGHT * b); + float y = floorf(bb); + clamp(y, 0.f, HEIGHT); + values[d - 1] = y; + } + } + ImGui::PlotLines("##LinesSound", values, IM_ARRAYSIZE(values), 0, 0, 0, HEIGHT, ImVec2(0, HEIGHT), 4); +} + +void CLight::OnPointDataChange(PropValue *value) +{ + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CLight::OnPointDataTestEqual(CanvasValue *a, CanvasValue *b, bool &res) +{ + CLight *A = (CLight *)(a->tag); + VERIFY(A); + CLight *B = (CLight *)(b->tag); + VERIFY(B); + res = (fsimilar(A->m_Range, B->m_Range) && + fsimilar(A->m_Attenuation0, B->m_Attenuation0) && + fsimilar(A->m_Attenuation1, B->m_Attenuation1) && + fsimilar(A->m_Attenuation2, B->m_Attenuation2) && + fsimilar(A->m_Brightness, B->m_Brightness)); +} + +void CLight::FillAttProp(LPCSTR pref, PropItemVec &items) +{ + PropValue *V; + V = PHelper().CreateFloat(items, PrepareKey(pref, "Range"), &m_Range, 0.1f, 1000.f); + V->OnChangeEvent.bind(this, &CLight::OnPointDataChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Attenuation\\Constant"), &m_Attenuation0, 0.f, 1.f, 0.0001f, 6); + V->OnChangeEvent.bind(this, &CLight::OnPointDataChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Attenuation\\Linear"), &m_Attenuation1, 0.f, 1.f, 0.0001f, 6); + V->OnChangeEvent.bind(this, &CLight::OnPointDataChange); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Attenuation\\Quadratic"), &m_Attenuation2, 0.f, 1.f, 0.0001f, 6); + V->OnChangeEvent.bind(this, &CLight::OnPointDataChange); + ButtonValue *B = 0; + B = PHelper().CreateButton(items, PrepareKey(pref, "Attenuation\\Auto"), "Linear,Quadratic", 0); + B->OnBtnClickEvent.bind(this, &CLight::OnAutoClick); + CanvasValue *C = 0; + C = PHelper().CreateCanvas(items, PrepareKey(pref, "Attenuation\\Graphic"), "", 64); + C->tag = (size_t)this; + C->OnDrawCanvasEvent.bind(this, &CLight::OnAttenuationDraw); + C->OnTestEqual.bind(this, &CLight::OnPointDataTestEqual); +} + +xr_token fuzzy_shape_types[] = { + {"Sphere", CLight::SFuzzyData::fstSphere}, + {"Box", CLight::SFuzzyData::fstBox}, + {0, 0}}; +void CLight::FillPointProp(LPCSTR pref, PropItemVec &items) +{ + // flags + PHelper().CreateFlag32(items, PrepareKey(pref, "Usage\\LightMap"), &m_Flags, ELight::flAffectStatic); + PHelper().CreateFlag32(items, PrepareKey(pref, "Usage\\Dynamic"), &m_Flags, ELight::flAffectDynamic); + PHelper().CreateFlag32(items, PrepareKey(pref, "Usage\\Animated"), &m_Flags, ELight::flProcedural); + // PHelper().CreateFlag32 (items, PrepareKey(pref,"Flags\\Breakable"),&m_Flags, CLight::flBreaking); + + FillAttProp(pref, items); + PropValue *P = 0; + ButtonValue *B = 0; + P = PHelper().CreateFlag32(items, PrepareKey(pref, "Fuzzy"), &m_Flags, ELight::flPointFuzzy); + P->OnChangeEvent.bind(this, &CLight::OnFuzzyFlagChange); + if (m_Flags.is(ELight::flPointFuzzy)) + { + VERIFY(m_FuzzyData); + P = PHelper().CreateS16(items, PrepareKey(pref, "Fuzzy\\Count"), &m_FuzzyData->m_PointCount, 1, 100); + P->OnChangeEvent.bind(this, &CLight::OnFuzzyDataChange); + B = PHelper().CreateButton(items, PrepareKey(pref, "Fuzzy\\Generate"), "Random", 0); + B->OnBtnClickEvent.bind(this, &CLight::OnFuzzyGenerateClick); + P = PHelper().CreateToken8(items, PrepareKey(pref, "Fuzzy\\Shape"), (u8 *)&m_FuzzyData->m_ShapeType, fuzzy_shape_types); + P->OnChangeEvent.bind(this, &CLight::OnFuzzyTypeChange); + switch (m_FuzzyData->m_ShapeType) + { + case CLight::SFuzzyData::fstSphere: + P = PHelper().CreateFloat(items, PrepareKey(pref, "Fuzzy\\Radius"), &m_FuzzyData->m_SphereRadius, 0.01f, 100.f, 0.01f, 2); + P->OnChangeEvent.bind(this, &CLight::OnFuzzyDataChange); + break; + case CLight::SFuzzyData::fstBox: + P = PHelper().CreateVector(items, PrepareKey(pref, "Fuzzy\\Half Dimension"), &m_FuzzyData->m_BoxDimension, 0.01f, 100.f, 0.01f, 2); + P->OnChangeEvent.bind(this, &CLight::OnFuzzyDataChange); + break; + } + } +} +//---------------------------------------------------- + +void CLight::FillSpotProp(LPCSTR pref, PropItemVec &items) +{ + // flags + PHelper().CreateFlag32(items, PrepareKey(pref, "Usage\\LightMap"), &m_Flags, ELight::flAffectStatic); + PHelper().CreateFlag32(items, PrepareKey(pref, "Usage\\Dynamic"), &m_Flags, ELight::flAffectDynamic); + PHelper().CreateFlag32(items, PrepareKey(pref, "Usage\\Animated"), &m_Flags, ELight::flProcedural); + // PHelper().CreateFlag32 (items, PHelper().PrepareKey(pref,"Flags\\Breakable"),&m_Flags, CLight::flBreaking); + + FillAttProp(pref, items); + PHelper().CreateAngle(items, PrepareKey(pref, "Spot R1\\Cone Angle"), &m_Cone, 0.1f, deg2rad(120.f), 0.01f, 2); + PHelper().CreateChoose(items, PrepareKey(pref, "Spot R1\\Texture"), &m_FalloffTex, smTexture); +} +//---------------------------------------------------- + +xr_token token_light_type[] = { + {"Point", ELight::ltPoint}, + //. andy { "Spot", ELight::ltSpot }, + {0, 0}}; + +void CLight::FillProp(LPCSTR pref, PropItemVec &items) +{ + inherited::FillProp(pref, items); + + PropValue *V = 0; + + V = PHelper().CreateToken32(items, PrepareKey(pref, "Type"), (u32 *)&m_Type, token_light_type); + V->OnChangeEvent.bind(this, &CLight::OnTypeChange); + V = PHelper().CreateFColor(items, PrepareKey(pref, "Color"), &m_Color); + V->OnChangeEvent.bind(this, &CLight::OnNeedUpdate); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Brightness"), &m_Brightness, -3.f, 3.f, 0.1f, 2); + V->OnChangeEvent.bind(this, &CLight::OnPointDataChange); + + ESceneLightTool *lt = dynamic_cast(FParentTools); + VERIFY(lt); + PHelper().CreateRToken32(items, PrepareKey(pref, "Light Control"), &m_LControl, &*lt->lcontrols.begin(), lt->lcontrols.size()); + + switch (m_Type) + { + case ELight::ltPoint: + FillPointProp(pref, items); + break; + case ELight::ltSpot: + FillSpotProp(pref, items); + break; + default: + THROW; + } + PHelper().CreateBOOL(items, PrepareKey(pref, "Use In D3D"), &m_UseInD3D); +} + +void CLight::OnTypeChange(PropValue *value) +{ + ExecCommand(COMMAND_UPDATE_PROPERTIES); + + Update(); +} +//---------------------------------------------------- + +void CLight::OnShowHint(AStringVec &dest) +{ + CCustomObject::OnShowHint(dest); + xr_string temp = make_string("Type: ").c_str(); + switch (m_Type) + { + case ELight::ltPoint: + temp += "point"; + break; + case ELight::ltSpot: + temp += "spot"; + break; + default: + temp += "undef"; + } + dest.push_back(temp); + temp = "Flags: "; + if (m_Flags.is(ELight::flAffectStatic)) + temp += "Stat "; + if (m_Flags.is(ELight::flAffectDynamic)) + temp += "Dyn "; + if (m_Flags.is(ELight::flProcedural)) + temp += "Proc "; + dest.push_back(temp); + temp = make_string("Pos: %3.2f, %3.2f, %3.2f", GetPosition().x, GetPosition().y, GetPosition().z).c_str(); + dest.push_back(temp); +} diff --git a/src/editors/LevelEditor/Entry/Particles/EParticlesObject.cpp b/src/editors/LevelEditor/Entry/Particles/EParticlesObject.cpp new file mode 100644 index 00000000000..00ba6f81db7 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Particles/EParticlesObject.cpp @@ -0,0 +1,346 @@ +#include "stdafx.h" + +#define CPSOBJECT_VERSION 0x0013 + +#define CPSOBJECT_CHUNK_VERSION 0x0001 +#define CPSOBJECT_CHUNK_REFERENCE 0x0002 +#define CPSOBJECT_CHUNK_PARAMS 0x0003 +#define CPSOBJECT_CHUNK_GAMETYPE 0x0004 + +#define PSOBJECT_SIZE 0.5f + +EParticlesObject::EParticlesObject(LPVOID data, LPCSTR name) : CCustomObject(data, name) +{ + Construct(data); +} + +void EParticlesObject::Construct(LPVOID data) +{ + FClassID = OBJCLASS_PS; + m_Particles = 0; + m_GameType.SetDefaults(); +} + +EParticlesObject::~EParticlesObject() +{ + auto model = dynamic_cast(m_Particles); + ::Render->model_Delete(model); + m_Particles = nullptr; +} + +bool EParticlesObject::GetBox(Fbox &box) +{ + box.set(GetPosition(), GetPosition()); + box.vMin.x -= PSOBJECT_SIZE; + box.vMin.y -= PSOBJECT_SIZE; + box.vMin.z -= PSOBJECT_SIZE; + box.vMax.x += PSOBJECT_SIZE; + box.vMax.y += PSOBJECT_SIZE; + box.vMax.z += PSOBJECT_SIZE; + return true; +} + +void EParticlesObject::OnUpdateTransform() +{ + inherited::OnUpdateTransform(); + Fvector v = {0.f, 0.f, 0.f}; + if (m_Particles) + m_Particles->UpdateParent(_Transform(), v, FALSE); +} +//---------------------------------------------------- + +void EParticlesObject::OnFrame() +{ + inherited::OnFrame(); + Fbox bb; + GetBox(bb); + if (::Render->occ_visible(bb)) + if (m_Particles) + m_Particles->OnFrame(EDevice.dwTimeDelta); +} +//---------------------------------------------------- + +void EParticlesObject::Render(int priority, bool strictB2F) +{ + inherited::Render(priority, strictB2F); + Fbox bb; + GetBox(bb); + if (::Render->occ_visible(bb)) + { + RCache.set_xform_world(Fidentity); + if (2 == priority) + { + if (false == strictB2F) + { + // draw emitter + EDevice.SetShader(EDevice.m_WireShader); + if (!Selected()) + DU_impl.DrawCross(GetPosition(), 0.30f, 0.1f, 0.3f, 0.3f, 0.3f, 0.3f, 0xFFFFEBAA, false); + + Fvector p = GetPosition(); + DU_impl.DrawRomboid(p, 0.1f, 0x0AFFEBAA); + if (Selected()) + { + Fbox bb; + GetBox(bb); + u32 clr = 0xFFFFFFFF; + DU_impl.DrawSelectionBoxB(bb, &clr); + } + } + } + if (m_Particles) + ::Render->model_Render(dynamic_cast(m_Particles), _Transform(), priority, strictB2F, 1.f); + } +} +//---------------------------------------------------- + +void EParticlesObject::RenderSingle() +{ + Render(1, false); + Render(1, true); +} +//---------------------------------------------------- + +bool EParticlesObject::FrustumPick(const CFrustum &frustum) +{ + return (frustum.testSphere_dirty(GetPosition(), PSOBJECT_SIZE)) ? true : false; +} +//---------------------------------------------------- + +bool EParticlesObject::RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf) +{ + Fvector pos, ray2; + pos.set(GetPosition()); + ray2.sub(pos, start); + + float d = ray2.dotproduct(direction); + if (d > 0) + { + float d2 = ray2.magnitude(); + if (((d2 * d2 - d * d) < (PSOBJECT_SIZE * PSOBJECT_SIZE)) && (d > PSOBJECT_SIZE)) + { + if (d < distance) + { + distance = d; + return true; + } + } + } + return false; +} +//---------------------------------------------------- + +void EParticlesObject::Play() +{ + if (m_Particles) + m_Particles->Play(); +} +//---------------------------------------------------- + +void EParticlesObject::Stop() +{ + if (m_Particles) + m_Particles->Stop(); +} +//---------------------------------------------------- +bool EParticlesObject::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 version = ini.r_u32(sect_name, "version"); + + inherited::LoadLTX(ini, sect_name); + + if (version >= 0x0012) + m_GameType.LoadLTX(ini, sect_name, false); + + m_RefName = ini.r_string(sect_name, "ref_name"); + if (!Compile(*m_RefName)) + { + ELog.DlgMsg(mtError, "EParticlesObject: '%s' not found in library", *m_RefName); + return false; + } + return true; +} + +void EParticlesObject::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + CCustomObject::SaveLTX(ini, sect_name); + + ini.w_u32(sect_name, "version", CPSOBJECT_VERSION); + + ini.w_string(sect_name, "ref_name", m_RefName.c_str()); + m_GameType.SaveLTX(ini, sect_name); +} + +bool EParticlesObject::LoadStream(IReader &F) +{ + u16 version = 0; + + R_ASSERT(F.r_chunk(CPSOBJECT_CHUNK_VERSION, &version)); + if (version < 0x0011) + { + ELog.DlgMsg(mtError, "PSObject: Unsupported version."); + return false; + } + + inherited::LoadStream(F); + + R_ASSERT(F.find_chunk(CPSOBJECT_CHUNK_REFERENCE)); + + F.r_stringZ(m_RefName); + + if (version >= 0x0013) + { + R_ASSERT(F.find_chunk(CPSOBJECT_CHUNK_GAMETYPE)); + m_GameType.LoadStream(F); + } + + if (!Compile(*m_RefName)) + { + ELog.DlgMsg(mtError, "EParticlesObject: '%s' not found in library", *m_RefName); + return false; + } + + return true; +} +//---------------------------------------------------- + +void EParticlesObject::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.open_chunk(CPSOBJECT_CHUNK_VERSION); + + if (Core.SocSdk) + F.w_u16(CPSOBJECT_VERSION - 2); + else + F.w_u16(CPSOBJECT_VERSION); + + F.close_chunk(); + + F.open_chunk(CPSOBJECT_CHUNK_REFERENCE); + F.w_stringZ(m_RefName); + F.close_chunk(); + + if (!Core.SocSdk) + { + F.open_chunk(CPSOBJECT_CHUNK_GAMETYPE); + m_GameType.SaveStream(F); + F.close_chunk(); + } +} + +void EParticlesObject::OnDeviceCreate() +{ +} + +void EParticlesObject::OnDeviceDestroy() +{ +} + +bool EParticlesObject::ExportGame(SExportStreams *F) +{ + SExportStreamItem &I = F->pe_static; + + if (!Core.SocSdk) + { + if (I.chunk == 0) + { + I.stream.open_chunk(I.chunk++); + I.stream.w_u32(1); // version + I.stream.close_chunk(); + } + + I.stream.open_chunk(I.chunk++); + I.stream.w_u16(m_GameType.m_GameType.get()); + I.stream.w_stringZ(m_RefName); + I.stream.w(&_Transform(), sizeof(Fmatrix)); + I.stream.close_chunk(); + } + else + { + I.stream.open_chunk(I.chunk++); + I.stream.w_stringZ(m_RefName); + I.stream.w(&_Transform(), sizeof(Fmatrix)); + I.stream.close_chunk(); + } + + return true; +} +//---------------------------------------------------- + +bool EParticlesObject::Compile(LPCSTR ref_name) +{ + auto model = dynamic_cast(m_Particles); + ::Render->model_Delete(model); + m_Particles = nullptr; + if (ref_name) + { + IRenderVisual *base = ::Render->model_CreateParticles(ref_name); + m_Particles = dynamic_cast(base); + if (m_Particles) + { + UpdateTransform(); + m_RefName = ref_name; + return true; + } + } + m_RefName = ""; + return false; +} + +void EParticlesObject::OnRefChange(PropValue *V) +{ + if (!Compile(*m_RefName)) + { + ELog.Msg(mtError, "Can't compile particle system '%s'", *m_RefName); + } + else + { + ExecCommand(COMMAND_REFRESH_PROPERTIES); + } +} + +void EParticlesObject::OnControlClick(ButtonValue *sender, bool &bModif, bool &bSafe) +{ + ButtonValue *V = dynamic_cast(sender); + R_ASSERT(V); + switch (V->btn_num) + { + case 0: + Play(); + break; + case 1: + Stop(); + break; + } + UI->RedrawScene(); + bModif = false; +} + +void EParticlesObject::FillProp(LPCSTR pref, PropItemVec &items) +{ + inherited::FillProp(pref, items); + PropValue *V; + V = PHelper().CreateChoose(items, PrepareKey(pref, "Reference"), &m_RefName, smParticles); + V->OnChangeEvent.bind(this, &EParticlesObject::OnRefChange); + ButtonValue *B; + B = PHelper().CreateButton(items, PrepareKey(pref, "Controls"), "Play,Stop", 0); + B->OnBtnClickEvent.bind(this, &EParticlesObject::OnControlClick); + + m_GameType.FillProp(pref, items); +} +//---------------------------------------------------- + +bool EParticlesObject::GetSummaryInfo(SSceneSummary *inf) +{ + inherited::GetSummaryInfo(inf); + /* + if (!m_RefName.IsEmpty()&&m_PE.GetDefinition()){ + inf->pe_static.insert(m_PE.GetDefinition()->m_Name); + if (m_PE.GetDefinition()->m_TextureName&&m_PE.GetDefinition()->m_TextureName[0]) inf->textures.insert(ChangeFileExt(m_PE.GetDefinition()->m_TextureName,"").LowerCase()); + } + inf->pe_static_cnt++; + */ + return true; +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Entry/Particles/EParticlesObject.h b/src/editors/LevelEditor/Entry/Particles/EParticlesObject.h new file mode 100644 index 00000000000..c8f43d163ea --- /dev/null +++ b/src/editors/LevelEditor/Entry/Particles/EParticlesObject.h @@ -0,0 +1,58 @@ +#pragma once + +class EParticlesObject : public CCustomObject +{ + typedef CCustomObject inherited; + Fbox m_BBox; + shared_str m_RefName; + + IParticleCustom *m_Particles; + GameTypeChooser m_GameType; + + void OnRefChange(PropValue *V); + void OnControlClick(ButtonValue *sender, bool &bModif, bool &bSafe); + +public: + EParticlesObject(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + virtual ~EParticlesObject(); + virtual bool CanAttach() { return true; } + + IParticleCustom *GetParticles() { return m_Particles; } + LPCSTR GetReferenceName() { return m_Particles ? *m_Particles->Name() : 0; } + + void RenderSingle(); + virtual void Render(int priority, bool strictB2F); + virtual bool RayPick(float &distance, const Fvector &start, const Fvector &direction, + SRayPickInfo *pinf = NULL); + virtual bool FrustumPick(const CFrustum &frustum); + + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual bool ExportGame(SExportStreams *data); + virtual bool GetBox(Fbox &box); + virtual void OnFrame(); + + void Play(); + void Stop(); + + virtual void OnUpdateTransform(); + + IC bool RefCompare(LPCSTR ref_name) + { + VERIFY(ref_name && ref_name[0]); + return (0 == stricmp(ref_name, GetReferenceName())); + } + + bool Compile(LPCSTR ref_name); + + // device dependent routine + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + + virtual void FillProp(LPCSTR pref, PropItemVec &items); + virtual bool GetSummaryInfo(SSceneSummary *inf); +}; diff --git a/src/editors/LevelEditor/Entry/Portal/Portal.cpp b/src/editors/LevelEditor/Entry/Portal/Portal.cpp new file mode 100644 index 00000000000..caed0176e9c --- /dev/null +++ b/src/editors/LevelEditor/Entry/Portal/Portal.cpp @@ -0,0 +1,596 @@ +#include "stdafx.h" + +#define PORTAL_VERSION 0x0010 + +#define PORTAL_CHUNK_VERSION 0xFA10 +#define PORTAL_CHUNK_COLOR 0xFA20 +#define PORTAL_CHUNK_SECTOR_FRONT 0xFA30 +#define PORTAL_CHUNK_SECTOR_BACK 0xFA40 +#define PORTAL_CHUNK_VERTICES 0xFA50 + +CPortal::CPortal(LPVOID data, LPCSTR name) : CCustomObject(data, name) +{ + Construct(data); +} + +void CPortal::Construct(LPVOID data) +{ + FClassID = OBJCLASS_PORTAL; + m_Center.set(0, 0, 0); + m_SectorFront = 0; + m_SectorBack = 0; +} + +CPortal::~CPortal() +{ +} + +bool CPortal::GetBox(Fbox &box) +{ + if (m_Vertices.empty()) + { + box.set(0, 0, 0, 0, 0, 0); + return false; + } + + box.set(m_Vertices[0], m_Vertices[0]); + for (FvectorVec::const_iterator pt = m_Vertices.begin() + 1; pt != m_Vertices.end(); pt++) + box.modify(*pt); + + return true; +} + +void CPortal::Render(int priority, bool strictB2F) +{ + if ((1 == priority) && (false == strictB2F)) + { + FvectorVec &src = m_SimplifyVertices; //(fraBottomBar->miDrawPortalSimpleModel->Checked)?m_SimplifyVertices:m_Vertices; + if (src.size() < 2) + return; + + EDevice.SetShader(EDevice.m_WireShader); + RCache.set_xform_world(Fidentity); + + u32 i; + FvectorVec V; + V.resize(src.size() + 2); + V[0].set(m_Center); + for (i = 0; i < src.size(); i++) + V[i + 1].set(src[i]); + V[V.size() - 1].set(src[0]); + // render portal tris + Fcolor col; + // front + if (m_SectorFront) + { + col.set(m_SectorFront->sector_color); + if (!Selected()) + col.mul_rgb(0.7f); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_CCW); + DU_impl.DrawPrimitiveL(D3DPT_TRIANGLEFAN, V.size() - 2, V.data(), V.size(), col.get(), true, false); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_CCW); + } + // back + if (m_SectorBack) + { + col.set(m_SectorBack->sector_color); + if (!Selected()) + col.mul_rgb(0.7f); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_CW); + DU_impl.DrawPrimitiveL(D3DPT_TRIANGLEFAN, V.size() - 2, V.data(), V.size(), col.get(), true, false); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_CCW); + } + col.set(1.f, 1.f, 1.f, 1.f); + EDevice.RenderNearer(0.0002); + if (!Selected()) + col.mul_rgb(0.5f); + // render portal edges + EScenePortalTool *lt = dynamic_cast(FParentTools); + VERIFY(lt); + FvectorVec &src_ln = (lt->m_Flags.is(EScenePortalTool::flDrawSimpleModel)) ? m_SimplifyVertices : m_Vertices; + DU_impl.DrawPrimitiveL(D3DPT_LINESTRIP, src_ln.size(), src_ln.data(), src_ln.size(), col.get(), true, true); + EDevice.ResetNearer(); + DU_impl.DrawFaceNormal(m_Center, m_Normal, 1, 0xFFFFFFFF); + DU_impl.DrawFaceNormal(m_Center, m_Normal, 1, 0x00000000); + } +} + +void CPortal::Move(Fvector &amount) +{ + // internal use only!!! + FvectorIt v_it; + for (v_it = m_Vertices.begin(); v_it != m_Vertices.end(); v_it++) + v_it->add(amount); + for (v_it = m_SimplifyVertices.begin(); v_it != m_SimplifyVertices.end(); v_it++) + v_it->add(amount); + m_Center.add(amount); +} + +bool CPortal::FrustumPick(const CFrustum &frustum) +{ + if (frustum.testPolyInside(m_Vertices.data(), m_Vertices.size())) + return true; + return false; +} + +bool CPortal::RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf) +{ + Fvector p[3]; + float range; + bool bPick = false; + p[0].set(m_Center); + EScenePortalTool *lt = dynamic_cast(FParentTools); + VERIFY(lt); + FvectorVec &src = (lt->m_Flags.is(EScenePortalTool::flDrawSimpleModel)) ? m_SimplifyVertices : m_Vertices; + + for (FvectorIt it = src.begin(); it != src.end(); it++) + { + p[1].set(*it); + p[2].set(((it + 1) == src.end()) ? src.front() : *(it + 1)); + range = UI->ZFar(); + + if (CDB::TestRayTri2(start, direction, p, range)) + { + if ((range >= 0) && (range < distance)) + { + distance = range; + bPick = true; + } + } + } + return bPick; +} + +bool CPortal::Update(bool bLoadMode) +{ + Fbox box; + GetBox(box); + box.getsphere(m_Center, m_Radius); + // check normal + //------------------------------------------------------------------------------ + m_Normal.set(0, 0, 0); + + R_ASSERT(!m_Vertices.empty()); + R_ASSERT(m_Vertices.size() >= 3); + + for (u32 i = 0; i < m_Vertices.size() - 1; i++) + { + Fvector temp; + temp.mknormal(m_Center, m_Vertices[i], m_Vertices[i + 1]); + m_Normal.add(temp); + } + float m = m_Normal.magnitude(); + if (fabsf(m) <= EPS_S) + { + Tools->m_DebugDraw.AppendWireFace(m_Vertices[0], m_Vertices[1], m_Vertices[2]); + ELog.Msg(mtError, "Portal: Degenerate portal found."); + SetValid(false); + return false; + } + m_Normal.div(m); + + // simplify portal + Simplify(); + + if (!bLoadMode) + { + xr_map A, B; + Fvector SF_dir, SB_dir; + Fvector InvNorm; + InvNorm.invert(m_Normal); + float dist; + for (int k = 0; k < 100; k++) + { + SF_dir.random_dir(m_Normal, PI_DIV_4); + SB_dir.random_dir(InvNorm, PI_DIV_4); + dist = 1000; + if (m_SectorFront->RayPick(dist, m_Center, SF_dir)) + A[m_SectorFront] += 1; + dist = 1000; + if (m_SectorBack->RayPick(dist, m_Center, SB_dir)) + A[m_SectorBack] += 1; + dist = 1000; + if (m_SectorFront->RayPick(dist, m_Center, SB_dir)) + B[m_SectorFront] += 1; + dist = 1000; + if (m_SectorBack->RayPick(dist, m_Center, SF_dir)) + B[m_SectorBack] += 1; + } + int a = A[m_SectorFront] + A[m_SectorBack]; + int b = B[m_SectorFront] + B[m_SectorBack]; + if (a > b) + ; + else if (a < b) + InvertOrientation(false); + else + ELog.Msg(mtError, "Check portal orientation: '%s'", GetName()); + } + + return true; +} + +void CPortal::InvertOrientation(bool bUndo) +{ + std::reverse(m_Vertices.begin(), m_Vertices.end()); + std::reverse(m_SimplifyVertices.begin(), m_SimplifyVertices.end()); + m_Normal.invert(); + UI->RedrawScene(); + + if (bUndo) + Scene->UndoSave(); +} + +double tri_area(Fvector2 P0, Fvector2 P1, Fvector2 P2) +{ + double e1 = P0.distance_to(P1); + double e2 = P1.distance_to(P2); + double e3 = P2.distance_to(P0); + + double p = (e1 + e2 + e3) / 2.0; + return sqrt(p * (p - e1) * (p - e2) * (p - e3)); +} + +bool Isect2DLvs2DL(Fvector2 &P1, Fvector2 &P2, Fvector2 &P3, Fvector2 &P4, Fvector2 &P) +{ + double a1, a2, b1, b2, c1, c2; /* Coefficients of line eqns. */ + double r1, r2, r3, r4; /* 'Sign' values */ + double denom, num; /* Intermediate values */ + + /* Compute a1, b1, c1, where line joining points 1 and 2 + * is "a1 x + b1 y + c1 = 0". */ + + a1 = P2.y - P1.y; + b1 = P1.x - P2.x; + c1 = P2.x * P1.y - P1.x * P2.y; + + /* Compute a2, b2, c2 */ + + a2 = P4.y - P3.y; + b2 = P3.x - P4.x; + c2 = P4.x * P3.y - P3.x * P4.y; + + /* Lines intersect: compute intersection point. + */ + + denom = a1 * b2 - a2 * b1; + if (fabs(denom) < EPS) + return false; + + num = b1 * c2 - b2 * c1; + P.x = float(num / denom); + + num = a2 * c1 - a1 * c2; + P.y = float(num / denom); + + return true; +} +//------------------------------------------------------------------------------ + +void SimplifyVertices(Fvector2Vec &vertices) +{ + // 1. Select smallest edge + double min_size = dbl_max; + int edge_id = -1; + Fvector2 P; + for (u32 I = 0; I < vertices.size(); I++) + { + // 2. Build two lines (1[L1a,L1b], 2[L2a,L2b]) and search point of intersection + int L1a = I - 1; + if (L1a < 0) + L1a = vertices.size() - 1; + int L1b = I; + int L2a = I + 1; + if (L2a >= int(vertices.size())) + L2a -= vertices.size(); + int L2b = I + 2; + if (L2b >= int(vertices.size())) + L2b -= vertices.size(); + + Fvector2 P_Test; + if (!Isect2DLvs2DL(vertices[L1a], vertices[L1b], vertices[L2b], vertices[L2a], P_Test)) + continue; + + double area = tri_area(vertices[L1b], P_Test, vertices[L2a]); //*(vertices[L1b].dist(vertices[L2a])); + + if (area < min_size) + { + edge_id = I; + min_size = area; + P = P_Test; + } + } + + // 3. Remove L1b & L2b - insert P + if (edge_id < 0) + return; + + int L1b = edge_id; + int L2a = edge_id + 1; + if (L2a >= int(vertices.size())) + L2a -= vertices.size(); + vertices[L1b] = P; + vertices.erase(vertices.begin() + L2a); +} +//------------------------------------------------------------------------------ + +void CPortal::Simplify() +{ + Fvector rkOffset; + Fvector rkNormal; + // compute plane + Fplane P; + Mgc::OrthogonalPlaneFit(m_Vertices.size(), (Mgc::Vector3 *)m_Vertices.data(), (Mgc::Vector3 &)rkOffset, (Mgc::Vector3 &)rkNormal); + P.build(rkOffset, rkNormal); + // project points + Fmatrix mView; + Fvector at, from, up, right, y; + from.set(rkOffset); + at.sub(from, rkNormal); + y.set(0, 1, 0); + if (fabsf(rkNormal.y) > 0.99f) + y.set(1, 0, 0); + right.crossproduct(y, rkNormal); + right.normalize(); + up.crossproduct(rkNormal, right); + up.normalize(); + mView.build_camera(from, at, up); + + Fvector2Vec points, vertices; + Fvector p; + points.resize(m_Vertices.size()); + for (u32 k = 0; k < m_Vertices.size(); k++) + { + mView.transform_tiny(p, m_Vertices[k]); + points[k].set(p.x, p.y); + } + // compute 2D Convex Hull + Mgc::ConvexHull2D Hull(points.size(), (const Mgc::Vector2 *)points.data()); + // Hull.ByDivideAndConquer(); + Hull.ByIncremental(); + Hull.RemoveCollinear(); + int Count = Hull.GetQuantity(); + if (Count <= 0) + return; + const int *indices = Hull.GetIndices(); + for (int ind_i = 0; ind_i < Count; ind_i++) + { + vertices.push_back(points[indices[ind_i]]); + } + // R_ASSERT2(0,"Go to ALEXMX and say: ''Test portal simplifier. Please!''"); + /* + int* indices = Hull.GetIndices(); + int CurVert = indices[0]; + vertices.push_back(points[CurVert]); + CurVert = indices[1]; + vertices.push_back(points[CurVert]); + + vector marks(Count,false); + marks[0]=true; + for (int A=0; A XR_MAX_PORTAL_VERTS) + { + int f_cnt = vertices.size(); + SimplifyVertices(vertices); + if (f_cnt == int(vertices.size())) + { + SetValid(false); + return; + } + } + + if (vertices.size() <= 2) + { + SetValid(false); + return; + } + else + SetValid(true); + + // convert to 3D & check portal normal + Fvector center, temp, norm; + center.set(0, 0, 0); + mView.invert(); + m_SimplifyVertices.resize(vertices.size()); + for (u32 k = 0; k < vertices.size(); k++) + { + p.set(vertices[k].x, vertices[k].y, 0.f); + mView.transform_tiny(m_SimplifyVertices[k], p); + center.add(m_SimplifyVertices[k]); + } + center.div(static_cast(vertices.size())); + + norm.set(0, 0, 0); + for (u32 k = 0; k < m_SimplifyVertices.size() - 1; k++) + { + temp.mknormal(center, m_SimplifyVertices[k], m_SimplifyVertices[k + 1]); + norm.add(temp); + } + norm.div(static_cast(m_SimplifyVertices.size())); + float m = norm.magnitude(); + VERIFY(fabsf(m) > EPS); + norm.div(m); + + if (norm.dotproduct(m_Normal) < 0) + { + std::reverse(m_SimplifyVertices.begin(), m_SimplifyVertices.end()); + m_Normal.invert(norm); + } + else + { + m_Normal.set(norm); + } +} +//------------------------------------------------------------------------------ + +bool CPortal::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 version = ini.r_u32(sect_name, "version"); + + if (version != PORTAL_VERSION) + { + ELog.Msg(mtError, "CPortal: Unsupported version."); + return false; + } + + CCustomObject::LoadLTX(ini, sect_name); + LPCSTR str; + str = ini.r_string(sect_name, "sector_front"); + m_SectorFront = (CSector *)Scene->FindObjectByName(str, OBJCLASS_SECTOR); + + str = ini.r_string(sect_name, "sector_back"); + m_SectorBack = (CSector *)Scene->FindObjectByName(str, OBJCLASS_SECTOR); + + if (!m_SectorBack || !m_SectorFront) + { + ELog.Msg(mtError, "Portal: Can't find required sectors.\nObject '%s' can't load.", GetName()); + return false; + } + + u32 cnt = ini.r_u32(sect_name, "vert_count"); + m_Vertices.resize(cnt); + string512 buff; + for (u32 i = 0; i < cnt; ++i) + { + sprintf(buff, "vertex_%.4d", i); + m_Vertices[i] = ini.r_fvector3(sect_name, buff); + } + if (cnt < 3) + { + ELog.Msg(mtError, "Portal: '%s' can't create.\nInvalid portal. (m_Vertices.size()<3)", GetName()); + return false; + } + + Update(true); + return true; +} + +void CPortal::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + CCustomObject::SaveLTX(ini, sect_name); + + ini.w_u32(sect_name, "version", PORTAL_VERSION); + + ini.w_string(sect_name, "sector_front", m_SectorFront ? m_SectorFront->GetName() : ""); + ini.w_string(sect_name, "sector_back", m_SectorBack ? m_SectorBack->GetName() : ""); + + ini.w_u32(sect_name, "vert_count", m_Vertices.size()); + string512 buff; + for (u32 i = 0; i < m_Vertices.size(); ++i) + { + sprintf(buff, "vertex_%.4d", i); + ini.w_fvector3(sect_name, buff, m_Vertices[i]); + } +} + +bool CPortal::LoadStream(IReader &F) +{ + u16 version = 0; + + string64 buf; + R_ASSERT(F.r_chunk(PORTAL_CHUNK_VERSION, &version)); + if (version != PORTAL_VERSION) + { + ELog.Msg(mtError, "CPortal: Unsupported version."); + return false; + } + + CCustomObject::LoadStream(F); + + if (F.find_chunk(PORTAL_CHUNK_SECTOR_FRONT)) + { + F.r_stringZ(buf, sizeof(buf)); + m_SectorFront = (CSector *)Scene->FindObjectByName(buf, OBJCLASS_SECTOR); + } + if (F.find_chunk(PORTAL_CHUNK_SECTOR_BACK)) + { + F.r_stringZ(buf, sizeof(buf)); + m_SectorBack = (CSector *)Scene->FindObjectByName(buf, OBJCLASS_SECTOR); + } + + if (!m_SectorBack || !m_SectorFront) + { + ELog.Msg(mtError, "Portal: Can't find required sectors.\nObject '%s' can't load.", GetName()); + return false; + } + + R_ASSERT(F.find_chunk(PORTAL_CHUNK_VERTICES)); + m_Vertices.resize(F.r_u16()); + F.r(m_Vertices.data(), m_Vertices.size() * sizeof(Fvector)); + + if (m_Vertices.size() < 3) + { + ELog.Msg(mtError, "Portal: '%s' can't create.\nInvalid portal. (m_Vertices.size()<3)", GetName()); + return false; + } + + Update(true); + return true; +} +//------------------------------------------------------------------------------ + +void CPortal::SaveStream(IWriter &F) +{ + CCustomObject::SaveStream(F); + + F.open_chunk(PORTAL_CHUNK_VERSION); + F.w_u16(PORTAL_VERSION); + F.close_chunk(); + + if (m_SectorFront) + { + F.open_chunk(PORTAL_CHUNK_SECTOR_FRONT); + F.w_stringZ(m_SectorFront->GetName()); + F.close_chunk(); + } + + if (m_SectorBack) + { + F.open_chunk(PORTAL_CHUNK_SECTOR_BACK); + F.w_stringZ(m_SectorBack->GetName()); + F.close_chunk(); + } + + F.open_chunk(PORTAL_CHUNK_VERTICES); + F.w_u16((u16)m_Vertices.size()); + F.w(m_Vertices.data(), m_Vertices.size() * sizeof(Fvector)); + F.close_chunk(); +} +//------------------------------------------------------------------------------ + +bool CPortal::GetSummaryInfo(SSceneSummary *inf) +{ + inherited::GetSummaryInfo(inf); + inf->portal_cnt++; + return true; +} diff --git a/src/editors/LevelEditor/Entry/Portal/Portal.h b/src/editors/LevelEditor/Entry/Portal/Portal.h new file mode 100644 index 00000000000..93a8b1daf40 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Portal/Portal.h @@ -0,0 +1,53 @@ +#pragma once + +// refs +class CSector; + +class CPortal : public CCustomObject +{ + friend class TfrmPropertiesPortal; + friend class CSector; + friend class TfraPortal; + friend class SceneBuilder; + friend class CPortalUtils; + friend struct co_plane_pred; + typedef CCustomObject inherited; + + FvectorVec m_Vertices; + FvectorVec m_SimplifyVertices; + Fvector m_Center; + float m_Radius; + Fvector m_Normal; + CSector *m_SectorFront; + CSector *m_SectorBack; + +public: + CPortal(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + virtual ~CPortal(); + virtual bool CanAttach() { return false; } + + virtual void Render(int priority, bool strictB2F); + virtual bool RayPick(float &distance, const Fvector &start, const Fvector &direction, + SRayPickInfo *pinf = NULL); + virtual bool FrustumPick(const CFrustum &frustum); + virtual void Move(Fvector &amount); // need for Shift Level + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual bool GetBox(Fbox &box); + void Simplify(); + bool Update(bool bLoadMode = false); + void InvertOrientation(bool bUndo); + + FvectorVec &Vertices() { return m_Vertices; } + void SetSectors(CSector *sf, CSector *sb) + { + m_SectorFront = sf; + m_SectorBack = sb; + } + + virtual bool GetSummaryInfo(SSceneSummary *inf); +}; diff --git a/src/editors/LevelEditor/Entry/Sector/Sector.cpp b/src/editors/LevelEditor/Entry/Sector/Sector.cpp new file mode 100644 index 00000000000..7cf69c77f5b --- /dev/null +++ b/src/editors/LevelEditor/Entry/Sector/Sector.cpp @@ -0,0 +1,711 @@ +#include "stdafx.h" +#include + +#define SECTOR_VERSION 0x0012 + +#define SECTOR_CHUNK_VERSION 0xF010 +#define SECTOR_CHUNK_COLOR 0xF020 +#define SECTOR_CHUNK_PRIVATE 0xF025 +#define SECTOR_CHUNK_ITEMS 0xF030 +#define SECTOR_CHUNK_ONE_ITEM 0xF031 +#define SECTOR_CHUNK_MAP_IDX 0xF032 + +CSectorItem::CSectorItem() +{ + object = NULL; + mesh = NULL; +} + +CSectorItem::CSectorItem(CSceneObject *o, CEditableMesh *m) +{ + object = o; + mesh = m; +} + +void CSectorItem::GetTransform(Fmatrix &parent) +{ + object->GetFullTransformToWorld(parent); +} + +bool CSectorItem::IsItem(const char *O, const char *M) +{ + return (0 == stricmp(O, object->GetName())) && (0 == stricmp(M, mesh->Name().c_str())); +} + +CSector::CSector(LPVOID data, LPCSTR name) : CCustomObject(data, name) +{ + Construct(data); +} + +void CSector::Construct(LPVOID data) +{ + FClassID = OBJCLASS_SECTOR; + sector_color.set(1, 1, 1, 0); + m_bDefault = false; + m_sector_num = -1; + m_bHasLoadError = false; + m_Flags.zero(); + m_map_idx = u8(-1); +} + +CSector::~CSector() +{ + OnDestroy(); +} + +void CSector::OnFrame() +{ + inherited::OnFrame(); + if (m_Flags.is(flNeedUpdateVolume)) + UpdateVolume(); +} + +bool CSector::FindSectorItem(const char *O, const char *M, SItemIt &it) +{ + for (it = sector_items.begin(); it != sector_items.end(); it++) + if ((*it).IsItem(O, M)) + return true; + return false; +} + +bool CSector::FindSectorItem(CSceneObject *o, CEditableMesh *m, SItemIt &it) +{ + for (it = sector_items.begin(); it != sector_items.end(); it++) + if ((*it).IsItem(o, m)) + return true; + return false; +} + +bool CSector::AddMesh(CSceneObject *O, CEditableMesh *M) +{ + VERIFY(O && M); + SItemIt it; + if (!(O->IsStatic() || O->IsMUStatic())) + return false; + if (!PortalUtils.FindSector(O, M)) + if (!FindSectorItem(O, M, it)) + { + sector_items.push_back(CSectorItem(O, M)); + m_Flags.set(flNeedUpdateVolume, TRUE); + return true; + } + return false; +} + +int CSector::DelMesh(CSceneObject *O, CEditableMesh *M) +{ + VERIFY(O && M); + int res = 0; + SItemIt it; + if (FindSectorItem(O, M, it)) + { + sector_items.erase(it); + m_Flags.set(flNeedUpdateVolume, TRUE); + res = 1; + } + if (sector_items.empty()) + { + res = 2; + ELog.Msg(mtInformation, "Last mesh deleted.\nSector has no meshes and will be removed."); + DeleteThis(); + } + return res; +} + +bool CSector::GetBox(Fbox &box) +{ + box.set(m_SectorBox); + return true; +} + +void CSector::Render(int priority, bool strictB2F) +{ + ESceneSectorTool *lt = dynamic_cast(FParentTools); + VERIFY(lt); + if (2 == priority) + { + if (true == strictB2F) + { + if (!lt->m_Flags.is(ESceneSectorTool::flDrawSolid)) + { + Fmatrix matrix; + Fcolor color; + float k = Selected() ? 0.4f : 0.2f; + color.set(sector_color.r, sector_color.g, sector_color.b, k); + EDevice.SetShader(EDevice.m_SelectionShader); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_NONE); + for (SItemIt it = sector_items.begin(); it != sector_items.end(); ++it) + { + it->object->GetFullTransformToWorld(matrix); + it->mesh->RenderSelection(matrix, 0, color.get()); + } + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_CCW); + } + } + else if (false == strictB2F) + { + Fmatrix matrix; + Fcolor color; + Fcolor color2; + float k = Selected() ? 0.8f : 0.5f; + float k2 = Selected() ? 0.5f : 0.2f; + color.set(sector_color.r * k, sector_color.g * k, sector_color.b * k, 1.f); + color2.set(sector_color.r * k2, sector_color.g * k2, sector_color.b * k2, 1.f); + if (lt->m_Flags.is(ESceneSectorTool::flDrawSolid)) + { + EDevice.SetShader(EDevice.m_WireShader); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_NONE); + for (SItemIt it = sector_items.begin(); it != sector_items.end(); ++it) + { + it->object->GetFullTransformToWorld(matrix); + it->mesh->RenderSelection(matrix, 0, color.get()); + it->mesh->RenderEdge(matrix, 0, color2.get()); + } + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_CCW); + } + if (Selected()) + { + RCache.set_xform_world(Fidentity); + DU_impl.DrawSelectionBoxB(m_SectorBox); + } + } + } +} + +void CSector::Move(Fvector &amount) +{ + // internal use only!!! + m_SectorCenter.add(amount); +} + +bool CSector::FrustumPick(const CFrustum &frustum) +{ + if (!frustum.testSphere_dirty(m_SectorCenter, m_SectorRadius)) + return false; + for (SItemIt s_it = sector_items.begin(); s_it != sector_items.end(); s_it++) + if (s_it->mesh->FrustumPick(frustum, s_it->object->_Transform())) + return true; + return false; +} + +bool CSector::RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf) +{ + bool bPick = false; + for (SItemIt s_it = sector_items.begin(); s_it != sector_items.end(); s_it++) + if (s_it->mesh->RayPick(distance, start, direction, s_it->object->_ITransform(), pinf)) + bPick = true; + return bPick; +} +//---------------------------------------------------- + +void CSector::UpdateVolume() +{ + Fbox bb; + Fvector pt; + m_SectorBox.invalidate(); + for (SItemIt s_it = sector_items.begin(); s_it != sector_items.end(); s_it++) + { + s_it->mesh->GetBox(bb); + bb.xform(s_it->object->_Transform()); + for (int i = 0; i < 8; i++) + { + bb.getpoint(i, pt); + m_SectorBox.modify(pt); + } + } + m_SectorBox.getsphere(m_SectorCenter, m_SectorRadius); + + UI->RedrawScene(); + + m_Flags.set(flNeedUpdateVolume, FALSE); +} +//---------------------------------------------------- +void CSector::OnDestroy() +{ + // remove existence sector portal + PortalUtils.RemoveSectorPortal(this); +} + +void CSector::OnSceneUpdate() +{ + /* + bool bUpdate=false; + for(SItemIt it = sector_items.begin();it!=sector_items.end();it++){ + if (!(Scene->ContainsObject(it->object,OBJCLASS_SCENEOBJECT)&&it->object->GetReference()->ContainsMesh(it->mesh))){ + sector_items.erase(it); it--; + bUpdate=true; + } + } + if (bUpdate) PortalUtils.RemoveSectorPortal(this); + */ + m_Flags.set(flNeedUpdateVolume, TRUE); +} +//---------------------------------------------------- + +EVisible CSector::Intersect(const Fvector ¢er, float radius) +{ + float dist = m_SectorCenter.distance_to(center); + + Fvector R; + m_SectorBox.getradius(R); + + bool bInSphere = ((dist + radius) < m_SectorRadius) && (radius > R.x) && (radius > R.y) && (radius > R.z); + if (m_SectorBox.contains(center)) + { + if (bInSphere) + return fvFully; + else + return fvPartialInside; + } + else + { + if (dist < (radius + m_SectorRadius)) + return fvPartialOutside; + } + return fvNone; +} +//---------------------------------------------------- + +EVisible CSector::Intersect(const Fbox &box) +{ + if (m_SectorBox.intersect(box)) + { + Fvector c; + float r; + box.getsphere(c, r); + return Intersect(c, r); + } + else + return fvNone; +} +//---------------------------------------------------- + +void CSector::CaptureInsideVolume() +{ + // test all mesh faces + // fill object list (test bounding sphere intersection) + ObjectList lst; + if (Scene->SpherePick(m_SectorCenter, m_SectorRadius, OBJCLASS_SCENEOBJECT, lst)) + { + // test all object meshes + Fmatrix matrix; + CSceneObject *obj = NULL; + // ignore dynamic objects + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + { + obj = (CSceneObject *)(*_F); + if (!(obj->IsStatic() || obj->IsMUStatic())) + continue; + EditMeshVec *M = obj->Meshes(); + R_ASSERT(M); + for (EditMeshIt m_def = M->begin(); m_def != M->end(); m_def++) + { + obj->GetFullTransformToWorld(matrix); + Fbox bb; + (*m_def)->GetBox(bb); + bb.xform(matrix); + EVisible vis = Intersect(bb); + if ((fvFully == vis) || (fvPartialInside == vis)) + AddMesh(obj, *m_def); + } + } + m_Flags.set(flNeedUpdateVolume, TRUE); + UI->RedrawScene(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } +} +//---------------------------------------------------- + +//. Fvector _dir[6]={{0,-1,0},{0,1,0},} + +void CSector::DistributeInsideObjects() +{ + /* + // test all mesh faces + // fill object list (test bounding sphere intersection) + ObjectList lst; + if (Scene->SpherePick(m_SectorCenter, m_SectorRadius, OBJCLASS_SCENEOBJECT, lst)){ + // test all object meshes + Fmatrix matrix; + CSceneObject *obj=NULL; + // ignore dynamic objects + for(ObjectIt _F = lst.begin();_F!=lst.end();_F++){ + obj = (CSceneObject*)(*_F); + if (!(obj->IsStatic()||obj->IsMUStatic())) continue; + EditMeshVec* M = obj->Meshes(); + R_ASSERT(M); + for(EditMeshIt m_def = M->begin();m_def!=M->end();m_def++){ + obj->GetFullTransformToWorld(matrix); + Fbox bb; + (*m_def)->GetBox(bb); + bb.xform (matrix); + EVisible vis=Intersect(bb); + if ((fvFully==vis)||(fvPartialInside==vis)){ + float dist = m_SectorRadius; + Fvector start,dir; + bb.getcenter (start); + _f o r () + Scene->RayPickObject(dist,start,dir,) + //.AddMesh(obj,*m_def); + } + } + } + m_Flags.set (flNeedUpdateVolume,TRUE); + UI->RedrawScene (); + ExecCommand (COMMAND_UPDATE_PROPERTIES); + } + */ +} +//---------------------------------------------------- + +void CSector::CaptureAllUnusedMeshes() +{ + U32Vec fl; + CSceneObject *obj = NULL; + ObjectList &lst = Scene->ListObj(OBJCLASS_SCENEOBJECT); + // ignore dynamic objects + SPBItem *pb = UI->ProgressStart(static_cast(lst.size()), "Capturing unused face..."); + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + { + pb->Inc(); + obj = (CSceneObject *)(*_F); + if (!(obj->IsStatic() || obj->IsMUStatic())) + continue; + EditMeshVec *M = obj->Meshes(); + R_ASSERT(M); + for (EditMeshIt m_def = M->begin(); m_def != M->end(); m_def++) + AddMesh(obj, *m_def); + } + UI->ProgressEnd(pb); + UI->RedrawScene(); +} + +//---------------------------------------------------- +bool CSector::SpherePick(const Fvector ¢er, float radius) +{ + float R = radius + m_SectorRadius; + float dist_sqr = center.distance_to_sqr(m_SectorCenter); + if (dist_sqr < R * R) + return true; + return false; +} +//---------------------------------------------------- + +bool CSector::IsEmpty() +{ + int count = 0; + for (SItemIt it = sector_items.begin(); it != sector_items.end(); it++) + count += it->mesh->GetFaceCount(true); + return !count; +} +//---------------------------------------------------- + +void CSector::GetCounts(int *objects, int *meshes, int *faces) +{ + if (faces) + { + *faces = 0; + for (SItemIt it = sector_items.begin(); it != sector_items.end(); it++) + *faces += it->mesh->GetFaceCount(true); + } + if (meshes) + *meshes = sector_items.size(); + if (objects) + { + xr_set objs; + for (SItemIt it = sector_items.begin(); it != sector_items.end(); it++) + objs.insert(it->object); + *objects = objs.size(); + } +} +//---------------------------------------------------- + +void CSector::LoadSectorDef(IReader *F) +{ + string256 o_name = ""; + string256 m_name = ""; + + CSectorItem sitem; + + // sector item + R_ASSERT(F->find_chunk(SECTOR_CHUNK_ONE_ITEM)); + F->r_stringZ(o_name, sizeof(o_name)); + sitem.object = (CSceneObject *)Scene->FindObjectByName(o_name, OBJCLASS_SCENEOBJECT); + if (sitem.object == NULL) + { + ELog.Msg(mtError, "Sector Item contains object '%s' - can't load.\nObject not found.", o_name); + m_bHasLoadError = true; + return; + } + + if (!(sitem.object->IsStatic() || sitem.object->IsMUStatic())) + { + ELog.Msg(mtError, "Sector Item contains object '%s' - can't load.\nObject is dynamic.", o_name); + m_bHasLoadError = true; + return; + } + + F->r_stringZ(m_name, sizeof(m_name)); + sitem.mesh = sitem.object->GetReference()->FindMeshByName(m_name); + if (sitem.mesh == 0) + { + ELog.Msg(mtError, "Sector Item contains object '%s' mesh '%s' - can't load.\nMesh not found.", o_name, m_name); + m_bHasLoadError = true; + return; + } + + sector_items.push_back(sitem); +} + +void CSector::LoadSectorDefLTX(CInifile &ini, LPCSTR sect_name, u32 item_idx) +{ + LPCSTR o_name = NULL; + LPCSTR m_name = NULL; + + CSectorItem sitem; + string512 buff; + + sprintf(buff, "item_object_name_%.4d", item_idx); + o_name = ini.r_string(sect_name, buff); + + // sector item + o_name = ini.r_string(sect_name, buff); + if (!o_name) + ELog.Msg(mtError, "Sector Item contains not nnamed object - can't load"); + + sitem.object = (CSceneObject *)Scene->FindObjectByName(o_name, OBJCLASS_SCENEOBJECT); + if (sitem.object == NULL) + { + ELog.Msg(mtError, "Sector Item contains object '%s' - can't load.\nObject not found.", o_name); + m_bHasLoadError = true; + return; + } + + if (!(sitem.object->IsStatic() || sitem.object->IsMUStatic())) + { + ELog.Msg(mtError, "Sector Item contains object '%s' - can't load.\nObject is dynamic.", o_name); + m_bHasLoadError = true; + return; + } + + sprintf(buff, "item_mesh_name_%.4d", item_idx); + m_name = ini.r_string(sect_name, buff); + + sitem.mesh = sitem.object->GetReference()->FindMeshByName(m_name); + if (sitem.mesh == 0) + { + ELog.Msg(mtError, "Sector Item contains object '%s' mesh '%s' - can't load.\nMesh not found.", o_name, m_name); + m_bHasLoadError = true; + return; + } + + sector_items.push_back(sitem); +} + +bool CSector::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 version = ini.r_u32(sect_name, "version"); + if (version < 0x0011) + { + ELog.Msg(mtError, "CSector: Unsupported version."); + return false; + } + + CCustomObject::LoadLTX(ini, sect_name); + + sector_color.set(ini.r_color(sect_name, "sector_color")); + + m_bDefault = ini.r_bool(sect_name, "default"); + + u32 obj_cnt = ini.r_u32(sect_name, "items_count"); + for (u32 i = 0; i < obj_cnt; ++i) + { + LoadSectorDefLTX(ini, sect_name, i); + } + + if (version >= 0x0012) + m_map_idx = ini.r_u8(sect_name, "change_map_to_idx"); + + if (sector_items.empty()) + return false; + + m_Flags.set(flNeedUpdateVolume, TRUE); + return true; +} + +void CSector::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + CCustomObject::SaveLTX(ini, sect_name); + + ini.w_u32(sect_name, "version", SECTOR_VERSION); + + ini.w_color(sect_name, "sector_color", sector_color.get()); + + ini.w_bool(sect_name, "default", m_bDefault); + + int count = 0; + ini.w_u32(sect_name, "items_count", sector_items.size()); + string512 buff; + for (SItemIt it = sector_items.begin(); it != sector_items.end(); ++it) + { + sprintf(buff, "item_object_name_%.4d", count); + ini.w_string(sect_name, buff, it->object->GetName()); + sprintf(buff, "item_mesh_name_%.4d", count); + ini.w_string(sect_name, buff, it->mesh->Name().c_str()); + ++count; + } + ini.w_u8(sect_name, "change_map_to_idx", m_map_idx); +} + +bool CSector::LoadStream(IReader &F) +{ + u16 version = 0; + + char buf[1024]; + R_ASSERT(F.r_chunk(SECTOR_CHUNK_VERSION, &version)); + if (version != SECTOR_VERSION) + { + ELog.Msg(mtError, "CSector: Unsupported version."); + return false; + } + + CCustomObject::LoadStream(F); + + R_ASSERT(F.r_chunk(SECTOR_CHUNK_COLOR, §or_color)); + + R_ASSERT(F.find_chunk(SECTOR_CHUNK_PRIVATE)); + m_bDefault = F.r_u8(); + + // Objects + IReader *OBJ = F.open_chunk(SECTOR_CHUNK_ITEMS); + if (OBJ) + { + IReader *O = OBJ->open_chunk(0); + for (int count = 1; O; count++) + { + LoadSectorDef(O); + O->close(); + O = OBJ->open_chunk(count); + } + OBJ->close(); + } + + if (F.find_chunk(SECTOR_CHUNK_MAP_IDX)) + m_map_idx = F.r_u8(); + + if (sector_items.empty()) + return false; + + m_Flags.set(flNeedUpdateVolume, TRUE); + return true; +} + +void CSector::SaveStream(IWriter &F) +{ + CCustomObject::SaveStream(F); + + F.open_chunk(SECTOR_CHUNK_VERSION); + F.w_u16(SECTOR_VERSION); + F.close_chunk(); + + F.w_chunk(SECTOR_CHUNK_COLOR, §or_color, sizeof(Fcolor)); + + F.open_chunk(SECTOR_CHUNK_PRIVATE); + F.w_u8(m_bDefault); + F.close_chunk(); + + F.open_chunk(SECTOR_CHUNK_ITEMS); + int count = 0; + for (SItemIt it = sector_items.begin(); it != sector_items.end(); it++) + { + F.open_chunk(count); + count++; + F.open_chunk(SECTOR_CHUNK_ONE_ITEM); + F.w_stringZ(it->object->GetName()); + F.w_stringZ(it->mesh->Name()); + F.close_chunk(); + F.close_chunk(); + } + F.close_chunk(); + + F.open_chunk(SECTOR_CHUNK_MAP_IDX); + F.w_u8(m_map_idx); + F.close_chunk(); +} + +//---------------------------------------------------- +xr_token level_sub_map[] = + { + {"default", u8(-1)}, + {"#0", 0}, + {"#1", 1}, + {"#2", 2}, + {"#3", 3}, + {NULL, 4}}; + +void CSector::FillProp(LPCSTR pref, PropItemVec &items) +{ + inherited::FillProp(pref, items); + PHelper().CreateFColor(items, PrepareKey(pref, "Color"), §or_color); + int faces, objects, meshes; + GetCounts(&objects, &meshes, &faces); + PHelper().CreateCaption(items, PrepareKey(pref, GetName(), "Contents\\Objects"), std::to_string(objects).c_str()); + PHelper().CreateCaption(items, PrepareKey(pref, GetName(), "Contents\\Meshes"), std::to_string(meshes).c_str()); + PHelper().CreateCaption(items, PrepareKey(pref, GetName(), "Contents\\Faces"), std::to_string(faces).c_str()); + PHelper().CreateToken8(items, PrepareKey(pref, GetName(), "Change LevelMap to"), &m_map_idx, level_sub_map); +} +//---------------------------------------------------- + +bool CSector::GetSummaryInfo(SSceneSummary *inf) +{ + inherited::GetSummaryInfo(inf); + inf->sector_cnt++; + return true; +} + +const int SectorMinFaceCount = 4; + +bool CSector::Validate(bool bMsg) +{ + bool bRes = true; + + // verify face count + int faceCount = 0; + GetCounts(0, 0, &faceCount); + + if (faceCount <= SectorMinFaceCount) + { + if (bMsg) + ELog.Msg(mtError, "*ERROR: Sector: '%s' - face count < %u!", GetName(), SectorMinFaceCount); + + bRes = false; + } + + // verify shader compatibility + bool bRenderableFound = false; + + for (SItemIt it = sector_items.begin(); it != sector_items.end(); it++) + { + for (SurfFacesPairIt sf_it = it->mesh->m_SurfFaces.begin(); sf_it != it->mesh->m_SurfFaces.end(); sf_it++) + { + CSurface *surf = sf_it->first; + LPCSTR compileShaderName = surf->_ShaderXRLCName(); + + if (Shader_xrLC *c_sh = EDevice.ShaderXRLC.Get(compileShaderName)) + { + if (c_sh->flags.bRendering) + bRenderableFound = true; + } + } + } + + if (!bRenderableFound) + { + if (bMsg) + ELog.Msg(mtError, "*ERROR: Sector: '%s' - can't find any renderable face!", GetName()); + + bRes = false; + } + + return bRes; +} diff --git a/src/editors/LevelEditor/Entry/Sector/Sector.h b/src/editors/LevelEditor/Entry/Sector/Sector.h new file mode 100644 index 00000000000..fca049c4f61 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Sector/Sector.h @@ -0,0 +1,116 @@ +#pragma once + +enum EVisible +{ + fvNone, + fvPartialInside, + fvPartialOutside, + fvFully +}; + +#define DEFAULT_SECTOR_NAME "Sector_DEFAULT" +// refs +class CEditableMesh; + +class CSectorItem +{ + friend class CSector; + friend class SceneBuilder; + friend class CPortalUtils; + CSceneObject *object; + CEditableMesh *mesh; + +public: + CSectorItem(); + CSectorItem(CSceneObject *o, CEditableMesh *m); + void GetTransform(Fmatrix &parent); + bool IsItem(const char *O, const char *M); + IC bool IsItem(CSceneObject *o, CEditableMesh *m) { return (o == object) && (m == mesh); } +}; + +DEFINE_VECTOR(CSectorItem, SItemVec, SItemIt); + +class CSector : public CCustomObject +{ + friend class TfrmPropertiesSector; + friend class SceneBuilder; + friend class CPortalUtils; + friend class CPortal; + typedef CCustomObject inherited; + + u8 m_bDefault; + bool m_bHasLoadError; + + Fbox m_SectorBox; + + Fvector m_SectorCenter; + float m_SectorRadius; + + Fcolor sector_color; + SItemVec sector_items; + bool FindSectorItem(CSceneObject *o, CEditableMesh *m, SItemIt &it); + bool FindSectorItem(const char *O, const char *M, SItemIt &it); + void LoadSectorDef(IReader *F); + void LoadSectorDefLTX(CInifile &ini, LPCSTR sect_name, u32 item_idx); + enum + { + flNeedUpdateVolume = (1 << 0) + }; + + Flags32 m_Flags; + + // only for build + int m_sector_num; + void OnDestroy(); + void UpdateVolume(); + +public: + u8 m_map_idx; + + CSector(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + virtual ~CSector(); + virtual bool CanAttach() { return false; } + + virtual void Render(int priority, bool strictB2F); + virtual bool RayPick(float &distance, const Fvector &start, const Fvector &direction, + SRayPickInfo *pinf = NULL); + virtual bool FrustumPick(const CFrustum &frustum); + virtual bool SpherePick(const Fvector ¢er, float radius); + virtual bool GetBox(Fbox &box); + virtual void Move(Fvector &amount); // need for Shift Level + virtual void OnSceneUpdate(); + + // file system function + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + virtual void FillProp(LPCSTR pref, PropItemVec &values); + virtual bool GetSummaryInfo(SSceneSummary *inf); + + bool AddMesh(CSceneObject *O, CEditableMesh *M); // + int DelMesh(CSceneObject *O, CEditableMesh *M); // 0- 1- 2- + + bool IsDefault() { return m_bDefault; } + bool Contains(CSceneObject *O, CEditableMesh *M) + { + SItemIt it; + return FindSectorItem(O, M, it); + } + + void SetColor(u32 clr) { sector_color.set(subst_alpha(clr, 0)); } + + void CaptureInsideVolume(); + void DistributeInsideObjects(); + void CaptureAllUnusedMeshes(); + void GetCounts(int *objects, int *meshes, int *faces); + bool IsEmpty(); + + virtual void OnFrame(); + + EVisible Intersect(const Fvector ¢er, float radius); + EVisible Intersect(const Fbox &box); + + virtual bool Validate(bool bMsg); +}; diff --git a/src/editors/LevelEditor/Entry/Shape/EShape.cpp b/src/editors/LevelEditor/Entry/Shape/EShape.cpp new file mode 100644 index 00000000000..892b9a13d40 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Shape/EShape.cpp @@ -0,0 +1,546 @@ +#include "stdafx.h" + +#define SHAPE_COLOR_TRANSP 0x3C808080 +#define SHAPE_COLOR_EDGE 0xFF202020 + +#define SHAPE_CURRENT_VERSION 0x0002 + +#define SHAPE_CHUNK_VERSION 0x0000 +#define SHAPE_CHUNK_SHAPES 0x0001 +#define SHAPE_CHUNK_DATA 0x0002 + +xr_token shape_type_tok[] = +{ + {"common", eShapeCommon}, + {"level bound", eShapeLevelBound}, + {0, 0} +}; + +CEditShape::CEditShape(LPVOID data, LPCSTR name) : CCustomObject(data, name) +{ + Construct(data); +} + +CEditShape::~CEditShape() +{ +} + +void CEditShape::Construct(LPVOID data) +{ + FClassID = OBJCLASS_SHAPE; + m_DrawTranspColor = SHAPE_COLOR_TRANSP; + m_DrawEdgeColor = SHAPE_COLOR_EDGE; + m_shape_type = eShapeCommon; + m_Box.invalidate(); +} + +void CEditShape::OnUpdateTransform() +{ + inherited::OnUpdateTransform(); +} + +void CEditShape::ComputeBounds() +{ + m_Box.invalidate(); + + for (auto it = shapes.begin(); it != shapes.end(); it++) + { + switch (it->type) + { + case cfSphere: + { + Fsphere &T = it->data.sphere; + Fvector P; + P.set(T.P); + P.sub(T.R); + m_Box.modify(P); + P.set(T.P); + P.add(T.R); + m_Box.modify(P); + } + break; + case cfBox: + { + Fvector P; + Fmatrix &T = it->data.box; + + // Build points + Fvector p; + for (int i = 0; i < DU_BOX_NUMVERTEX; i++) + { + T.transform_tiny(P, du_box_vertices[i]); + m_Box.modify(P); + } + } + break; + } + } + m_Box.getsphere(m_Sphere.P, m_Sphere.R); +} + +void CEditShape::SetScale(const Fvector &val) +{ + if (shapes.size() == 1) + { + switch (shapes[0].type) + { + case cfSphere: + { + FScale.set(val.x, val.x, val.x); + } + break; + case cfBox: + FScale.set(val.x, val.y, val.z); + break; + default: + THROW; + } + } + else + { + FScale.set(val.x, val.x, val.x); + } + ComputeBounds(); + UpdateTransform(); +} + +void CEditShape::ApplyScale() +{ + for (auto it = shapes.begin(); it != shapes.end(); it++) + { + switch (it->type) + { + case cfSphere: + { + Fsphere &T = it->data.sphere; + FTransformS.transform_tiny(T.P); + T.R *= FScale.x; + } + break; + case cfBox: + { + Fmatrix &B = it->data.box; + B.mulA_43(FTransformS); + } + break; + } + } + FScale.set(1.f, 1.f, 1.f); + UpdateTransform(true); + + ComputeBounds(); +} + +void CEditShape::add_sphere(const Fsphere &S) +{ + shapes.push_back(shape_def()); + shapes.back().type = cfSphere; + shapes.back().data.sphere.set(S); + + ComputeBounds(); +} + +void CEditShape::add_box(const Fmatrix &B) +{ + shapes.push_back(shape_def()); + shapes.back().type = cfBox; + shapes.back().data.box.set(B); + + ComputeBounds(); +} + +void CEditShape::Attach(CEditShape *from) +{ + ApplyScale(); + // transfer data + from->ApplyScale(); + Fmatrix M = from->_Transform(); + M.mulA_43(_ITransform()); + for (auto it = from->shapes.begin(); it != from->shapes.end(); it++) + { + switch (it->type) + { + case cfSphere: + { + Fsphere &T = it->data.sphere; + M.transform_tiny(T.P); + add_sphere(T); + } + break; + case cfBox: + { + Fmatrix B = it->data.box; + B.mulA_43(M); + add_box(B); + } + break; + default: + THROW; + } + } + // common + Scene->RemoveObject(from, true, true); + xr_delete(from); + + ComputeBounds(); +} + +void CEditShape::Detach() +{ + if (shapes.size() > 1) + { + Select(true); + ApplyScale(); + // create scene shapes + const Fmatrix &M = _Transform(); + auto it = shapes.begin(); + it++; + for (; it != shapes.end(); it++) + { + string256 namebuffer; + Scene->GenObjectName(OBJCLASS_SHAPE, namebuffer, GetName()); + CEditShape *shape = (CEditShape *)Scene->GetOTool(FClassID)->CreateObject(0, namebuffer); + switch (it->type) + { + case cfSphere: + { + Fsphere T = it->data.sphere; + M.transform_tiny(T.P); + shape->SetPosition(T.P); + T.P.set(0, 0, 0); + shape->add_sphere(T); + } + break; + case cfBox: + { + Fmatrix B = it->data.box; + B.mulA_43(M); + shape->SetPosition(B.c); + B.c.set(0, 0, 0); + shape->add_box(B); + } + break; + default: + THROW; + } + Scene->AppendObject(shape, false); + shape->Select(true); + } + // erase shapes in base object + it = shapes.begin(); + it++; + shapes.erase(it, shapes.end()); + + ComputeBounds(); + + Scene->UndoSave(); + } +} + +void CEditShape::OnDetach() +{ + inherited::OnDetach(); + + m_DrawTranspColor = SHAPE_COLOR_TRANSP; + m_DrawEdgeColor = SHAPE_COLOR_EDGE; +} + +bool CEditShape::RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf) +{ + float dist = distance; + + for (auto it = shapes.begin(); it != shapes.end(); it++) + { + switch (it->type) + { + case cfSphere: + { + Fvector S, D; + Fmatrix M; + M.invert(FTransformR); + M.transform_dir(D, direction); + FITransform.transform_tiny(S, start); + Fsphere &T = it->data.sphere; + float bk_r = T.R; + // T.R = FScale.x; + T.intersect(S, D, dist); + if (dist <= 0.f) + dist = distance; + + T.R = bk_r; + } + break; + case cfBox: + { + Fbox box; + box.identity(); + Fmatrix BI; + BI.invert(it->data.box); + Fvector S, D, S1, D1, P; + FITransform.transform_tiny(S, start); + FITransform.transform_dir(D, direction); + BI.transform_tiny(S1, S); + BI.transform_dir(D1, D); + Fbox::ERP_Result rp_res = box.Pick2(S1, D1, P); + if (rp_res == Fbox::rpOriginOutside) + { + it->data.box.transform_tiny(P); + FTransform.transform_tiny(P); + P.sub(start); + dist = P.magnitude(); + } + } + break; + } + } + if (dist < distance) + { + distance = dist; + return true; + } + return false; +} + +bool CEditShape::FrustumPick(const CFrustum &frustum) +{ + const Fmatrix &M = _Transform(); + for (auto it = shapes.begin(); it != shapes.end(); it++) + { + switch (it->type) + { + case cfSphere: + { + Fvector C; + Fsphere &T = it->data.sphere; + M.transform_tiny(C, T.P); + if (frustum.testSphere_dirty(C, T.R * FScale.x)) + return true; + } + break; + case cfBox: + { + Fbox box; + box.identity(); + Fmatrix B = it->data.box; + B.mulA_43(_Transform()); + box.xform(B); + u32 mask = 0xff; + if (frustum.testAABB(box.data(), mask)) + return true; + } + break; + } + } + return false; +} + +bool CEditShape::GetBox(Fbox &box) +{ + if (m_Box.is_valid()) + { + box.xform(m_Box, FTransform); + return true; + } + return false; +} + +bool CEditShape::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 vers = ini.r_u32(sect_name, "version"); + + inherited::LoadLTX(ini, sect_name); + + u32 count = ini.r_u32(sect_name, "shapes_count"); + if (vers > 0x0001) + m_shape_type = ini.r_u8(sect_name, "shape_type"); + + string128 buff; + shapes.resize(count); + for (u32 i = 0; i < count; ++i) + { + sprintf(buff, "shape_type_%d", i); + shapes[i].type = ini.r_u8(sect_name, buff); + if (shapes[i].type == CShapeData::cfSphere) + { + sprintf(buff, "shape_center_%d", i); + shapes[i].data.sphere.P = ini.r_fvector3(sect_name, buff); + + sprintf(buff, "shape_radius_%d", i); + shapes[i].data.sphere.R = ini.r_float(sect_name, buff); + } + else + { + R_ASSERT(shapes[i].type == CShapeData::cfBox); + sprintf(buff, "shape_matrix_i_%d", i); + shapes[i].data.box.i = ini.r_fvector3(sect_name, buff); + + sprintf(buff, "shape_matrix_j_%d", i); + shapes[i].data.box.j = ini.r_fvector3(sect_name, buff); + + sprintf(buff, "shape_matrix_k_%d", i); + shapes[i].data.box.k = ini.r_fvector3(sect_name, buff); + + sprintf(buff, "shape_matrix_c_%d", i); + shapes[i].data.box.c = ini.r_fvector3(sect_name, buff); + } + } + + ComputeBounds(); + return true; +} + +void CEditShape::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + inherited::SaveLTX(ini, sect_name); + + ini.w_u32(sect_name, "version", SHAPE_CURRENT_VERSION); + + ini.w_u32(sect_name, "shapes_count", shapes.size()); + ini.w_u8(sect_name, "shape_type", m_shape_type); + + string128 buff; + for (u32 i = 0; i < shapes.size(); ++i) + { + sprintf(buff, "shape_type_%d", i); + ini.w_u8(sect_name, buff, shapes[i].type); + if (shapes[i].type == CShapeData::cfSphere) + { + sprintf(buff, "shape_center_%d", i); + ini.w_fvector3(sect_name, buff, shapes[i].data.sphere.P); + + sprintf(buff, "shape_radius_%d", i); + ini.w_float(sect_name, buff, shapes[i].data.sphere.R); + } + else + { + R_ASSERT(shapes[i].type == CShapeData::cfBox); + sprintf(buff, "shape_matrix_i_%d", i); + ini.w_fvector3(sect_name, buff, shapes[i].data.box.i); + sprintf(buff, "shape_matrix_j_%d", i); + ini.w_fvector3(sect_name, buff, shapes[i].data.box.j); + sprintf(buff, "shape_matrix_k_%d", i); + ini.w_fvector3(sect_name, buff, shapes[i].data.box.k); + sprintf(buff, "shape_matrix_c_%d", i); + ini.w_fvector3(sect_name, buff, shapes[i].data.box.c); + } + } +} + +bool CEditShape::LoadStream(IReader &F) +{ + R_ASSERT(F.find_chunk(SHAPE_CHUNK_VERSION)); + u16 vers = F.r_u16(); + + inherited::LoadStream(F); + + R_ASSERT(F.find_chunk(SHAPE_CHUNK_SHAPES)); + shapes.resize(F.r_u32()); + F.r(shapes.data(), shapes.size() * sizeof(shape_def)); + + if (F.find_chunk(SHAPE_CHUNK_DATA)) + m_shape_type = F.r_u8(); + + ComputeBounds(); + return true; +} + +void CEditShape::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + F.open_chunk(SHAPE_CHUNK_VERSION); + + if (Core.SocSdk) + F.w_u16(SHAPE_CURRENT_VERSION - 1); + else + F.w_u16(SHAPE_CURRENT_VERSION); + + F.close_chunk(); + + F.open_chunk(SHAPE_CHUNK_SHAPES); + F.w_u32(shapes.size()); + F.w(shapes.data(), shapes.size() * sizeof(shape_def)); + F.close_chunk(); + + if (!Core.SocSdk) + { + F.open_chunk(SHAPE_CHUNK_DATA); + F.w_u8(m_shape_type); + F.close_chunk(); + } +} + +void CEditShape::FillProp(LPCSTR pref, PropItemVec &values) +{ + inherited::FillProp(pref, values); + PHelper().CreateCaption(values, PrepareKey(pref, "Shape usage"), m_shape_type == eShapeCommon ? "common" : "level bound"); +} + +void CEditShape::Render(int priority, bool strictB2F) +{ + inherited::Render(priority, strictB2F); + if (1 == priority) + { + if (strictB2F) + { + EDevice.SetShader(EDevice.m_WireShader); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_NONE); + u32 clr = Selected() ? subst_alpha(m_DrawTranspColor, color_get_A(m_DrawTranspColor) * 2) : m_DrawTranspColor; + + Fvector zero = {0.f, 0.f, 0.f}; + for (auto it = shapes.begin(); it != shapes.end(); ++it) + { + switch (it->type) + { + case cfSphere: + { + Fsphere &S = it->data.sphere; + Fmatrix B; + B.scale(S.R, S.R, S.R); + B.translate_over(S.P); + B.mulA_43(_Transform()); + RCache.set_xform_world(B); + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawCross(zero, 1.f, m_DrawEdgeColor, false); + DU_impl.DrawIdentSphere(true, true, clr, m_DrawEdgeColor); + } + break; + case cfBox: + { + Fmatrix B = it->data.box; + B.mulA_43(_Transform()); + RCache.set_xform_world(B); + DU_impl.DrawIdentBox(true, true, clr, m_DrawEdgeColor); + } + break; + } + } + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_CCW); + } + else + { + if (Selected() && m_Box.is_valid()) + { + EDevice.SetShader(EDevice.m_SelectionShader); + RCache.set_xform_world(_Transform()); + u32 clr = 0xFFFFFFFF; + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawSelectionBoxB(m_Box, &clr); + } + } + } +} + +void CEditShape::OnFrame() +{ + inherited::OnFrame(); + if (m_shape_type == eShapeLevelBound) + { + UIShapeTool *F = (UIShapeTool *)FParentTools->pForm; + BOOL bVis = F->EditLevelBound; + m_RT_Flags.set(flRT_Visible, bVis); + } +} + +void CEditShape::OnShowHint(AStringVec &dest) +{ +} diff --git a/src/editors/LevelEditor/Entry/Shape/EShape.h b/src/editors/LevelEditor/Entry/Shape/EShape.h new file mode 100644 index 00000000000..053c09191d8 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Shape/EShape.h @@ -0,0 +1,78 @@ +#pragma once + +enum eShapeUsage +{ + eShapeCommon = 0, + eShapeLevelBound +}; + +class CEditShape : public CCustomObject, protected CShapeData +{ + typedef CCustomObject inherited; + +private: + // bounds + Fbox m_Box; + Fsphere m_Sphere; + void ComputeBounds(); + +public: + u8 m_shape_type; + u32 m_DrawTranspColor; + u32 m_DrawEdgeColor; + + void SetDrawColor(u32 transp, u32 edge) + { + m_DrawTranspColor = transp; + m_DrawEdgeColor = edge; + } + void ApplyScale(); + void add_sphere(const Fsphere &S); + void add_box(const Fmatrix &B); + const shape_def &get_shape(int idx) + { + R_ASSERT(idx < (int)shapes.size()); + return shapes[idx]; + } + virtual void FillProp(LPCSTR pref, PropItemVec &values); + +protected: + virtual void SetScale(const Fvector &val); + virtual void OnUpdateTransform(); + +public: + CEditShape(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + virtual ~CEditShape(); + virtual bool CanAttach() { return true; } + + // pick functions + virtual bool RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf = NULL); + virtual bool FrustumPick(const CFrustum &frustum); + + // placement functions + virtual bool GetBox(Fbox &box); + + // change position/orientation methods + // virtual void Scale (Fvector& amount){;} + + // file system function + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + // render utility function + virtual void Render(int priority, bool strictB2F); + virtual void OnFrame(); + + // tools + void Attach(CEditShape *from); + void Detach(); + + ShapeVec &GetShapes() { return shapes; } + + virtual void OnDetach(); + // events + virtual void OnShowHint(AStringVec &dest); +}; diff --git a/src/editors/LevelEditor/Entry/Sound/ESound_Environment.cpp b/src/editors/LevelEditor/Entry/Sound/ESound_Environment.cpp new file mode 100644 index 00000000000..e0d7e422318 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Sound/ESound_Environment.cpp @@ -0,0 +1,132 @@ +#include "stdafx.h" + +#define SOUND_SEL0_COLOR 0x00A0A0A0 +#define SOUND_SEL1_COLOR 0x00FFFFFF +#define SOUND_NORM_COLOR 0x000000FF +#define SOUND_LOCK_COLOR 0x00FF0000 + +#define SOUND_ENV_VERSION 0x0012 + +#define SOUND_CHUNK_VERSION 0x1001 +#define SOUND_CHUNK_ENV_SHAPE 0x1002 +#define SOUND_CHUNK_ENV_REFS 0x1003 + +ESoundEnvironment::ESoundEnvironment(LPVOID data, LPCSTR name) : CEditShape(data, name) +{ + Construct(data); +} + +void ESoundEnvironment::Construct(LPVOID data) +{ + FClassID = OBJCLASS_SOUND_ENV; + + add_box(Fidentity); + SetDrawColor(0x205050FF, 0xFF202020); + m_EnvInner = ""; + m_EnvOuter = ""; +} + +ESoundEnvironment::~ESoundEnvironment() +{ +} +//---------------------------------------------------- + +void ESoundEnvironment::OnUpdateTransform() +{ + inherited::OnUpdateTransform(); + ExecCommand(COMMAND_REFRESH_SOUND_ENV_GEOMETRY); +} +//---------------------------------------------------- +bool ESoundEnvironment::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 version = ini.r_u32(sect_name, "version"); + + if (version != SOUND_ENV_VERSION) + { + ELog.DlgMsg(mtError, "ESoundSource: Unsupported version."); + return false; + } + inherited::LoadLTX(ini, sect_name); + + return true; +} + +void ESoundEnvironment::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + inherited::SaveLTX(ini, sect_name); + + ini.w_u32(sect_name, "version", SOUND_ENV_VERSION); + + ini.w_string(sect_name, "env_inner", m_EnvInner.c_str()); + ini.w_string(sect_name, "env_outer", m_EnvOuter.c_str()); +} + +bool ESoundEnvironment::LoadStream(IReader &F) +{ + u16 version = 0; + + R_ASSERT(F.r_chunk(SOUND_CHUNK_VERSION, &version)); + if (version != SOUND_ENV_VERSION) + { + ELog.DlgMsg(mtError, "ESoundSource: Unsupported version."); + return false; + } + inherited::LoadStream(F); + + R_ASSERT(F.find_chunk(SOUND_CHUNK_ENV_REFS)); + F.r_stringZ(m_EnvInner); + F.r_stringZ(m_EnvOuter); + + return true; +} + +void ESoundEnvironment::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.open_chunk(SOUND_CHUNK_VERSION); + F.w_u16(SOUND_ENV_VERSION); + F.close_chunk(); + + F.open_chunk(SOUND_CHUNK_ENV_REFS); + F.w_stringZ(m_EnvInner); + F.w_stringZ(m_EnvOuter); + F.close_chunk(); +} +//---------------------------------------------------- + +void ESoundEnvironment::OnChangeEnvs(PropValue *prop) +{ + ExecCommand(COMMAND_REFRESH_SOUND_ENV_GEOMETRY); +} +//---------------------------------------------------- + +void ESoundEnvironment::FillProp(LPCSTR pref, PropItemVec &values) +{ + inherited::FillProp(pref, values); + PropValue *P; + P = PHelper().CreateChoose(values, PrepareKey(pref, "Environment Inner"), &m_EnvInner, smSoundEnv); + P->OnChangeEvent.bind(this, &ESoundEnvironment::OnChangeEnvs); + P = PHelper().CreateChoose(values, PrepareKey(pref, "Environment Outer"), &m_EnvOuter, smSoundEnv); + P->OnChangeEvent.bind(this, &ESoundEnvironment::OnChangeEnvs); +} +//---------------------------------------------------- + +bool ESoundEnvironment::GetSummaryInfo(SSceneSummary *inf) +{ + inherited::GetSummaryInfo(inf); + return true; +} + +void ESoundEnvironment::get_box(Fmatrix &m) +{ + CShapeData::shape_def shape = get_shape(0); + R_ASSERT(shape.type == static_cast(CShapeData::cfBox)); + m.mul(_Transform(), shape.data.box); +} + +void ESoundEnvironment::OnSceneUpdate() +{ + inherited::OnSceneUpdate(); + ExecCommand(COMMAND_REFRESH_SOUND_ENV_GEOMETRY); +} diff --git a/src/editors/LevelEditor/Entry/Sound/ESound_Environment.h b/src/editors/LevelEditor/Entry/Sound/ESound_Environment.h new file mode 100644 index 00000000000..66fe4d58b02 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Sound/ESound_Environment.h @@ -0,0 +1,32 @@ +#pragma once + +class ESoundEnvironment : public CEditShape +{ + typedef CCustomObject inherited; + + friend class CLevelSoundManager; + // Env + shared_str m_EnvInner; + shared_str m_EnvOuter; + + void OnChangeEnvs(PropValue *prop); + +public: + void get_box(Fmatrix &m); + +public: + ESoundEnvironment(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + ~ESoundEnvironment(); + virtual bool CanAttach() { return true; } + virtual void OnUpdateTransform(); + + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual void FillProp(LPCSTR pref, PropItemVec &values); + virtual bool GetSummaryInfo(SSceneSummary *inf); + virtual void OnSceneUpdate(); +}; diff --git a/src/editors/LevelEditor/Entry/Sound/ESound_Source.cpp b/src/editors/LevelEditor/Entry/Sound/ESound_Source.cpp new file mode 100644 index 00000000000..6f632a777b8 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Sound/ESound_Source.cpp @@ -0,0 +1,481 @@ +#include "stdafx.h" +#include "../../xrSound/stdafx.h" +#include "../../xrSound/SoundRender_Source.h" + +#define VIS_RADIUS 0.25f +#define SOUND_SEL0_COLOR 0x00A0A0F0 +#define SOUND_SEL1_COLOR 0x00FFFFFF +#define SOUND_NORM_COLOR 0x000000FF +#define SOUND_LOCK_COLOR 0x00FF0000 + +#define SOUND_SOURCE_VERSION 0x0014 + +#define SOUND_CHUNK_VERSION 0x1001 +#define SOUND_CHUNK_TYPE 0x1002 +#define SOUND_CHUNK_SOURCE_NAME 0x1003 +#define SOUND_CHUNK_SOURCE_PARAMS 0x1004 +#define SOUND_CHUNK_SOURCE_FLAGS 0x1005 +#define SOUND_CHUNK_SOURCE_PARAMS2 0x1006 +#define SOUND_CHUNK_SOURCE_PARAMS3 0x1007 +#define SOUND_CHUNK_GAME_PARAMS 0x1008 + +ESoundSource::ESoundSource(LPVOID data, LPCSTR name) + : CCustomObject(data, name) +{ + Construct(data); +} + +void ESoundSource::Construct(LPVOID data) +{ + FClassID = OBJCLASS_SOUND_SRC; + + m_Type = stStaticSource; + + m_WAVName = ""; + m_Params.volume = 1.f; + m_Params.freq = 1.f; + m_Params.min_distance = 1.f; + m_Params.max_distance = 300.f; + m_Params.max_ai_distance = 300.f; + m_Params.position.set(0, 0, 0); + + m_Flags.set(flLooped, TRUE); + m_Command = stNothing; + m_RandomPause.set(0.f, 0.f); + m_ActiveTime.set(0.f, 0.f); + m_PlayTime.set(0.f, 0.f); + m_NextTime = 0; + m_StopTime = 0; +} + +ESoundSource::~ESoundSource() +{ + m_Source.destroy(); +} + +//---------------------------------------------------- + +bool ESoundSource::GetBox(Fbox &box) +{ + box.set(m_Params.position, m_Params.position); + box.vMin.sub(m_Params.max_distance); + box.vMax.add(m_Params.max_distance); + return true; +} + +void ESoundSource::Render(int priority, bool strictB2F) +{ + if ((1 == priority) && (false == strictB2F)) + { + RCache.set_xform_world(Fidentity); + EDevice.SetShader(EDevice.m_WireShader); + u32 clr0 = Selected() ? SOUND_SEL0_COLOR : SOUND_NORM_COLOR; + u32 clr1 = Selected() ? SOUND_SEL1_COLOR : SOUND_NORM_COLOR; + if (Selected()) + { + DU_impl.DrawLineSphere(m_Params.position, m_Params.max_distance, clr1, true); + DU_impl.DrawLineSphere(m_Params.position, m_Params.min_distance, clr0, false); + } + else + { + DU_impl.DrawSound(m_Params.position, VIS_RADIUS, clr1); + } + } +} + +bool ESoundSource::FrustumPick(const CFrustum &frustum) +{ + return (frustum.testSphere_dirty(m_Params.position, VIS_RADIUS)) ? true : false; +} + +bool ESoundSource::RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf) +{ + Fvector ray2; + ray2.sub(m_Params.position, start); + + float d = ray2.dotproduct(direction); + if (d > 0) + { + float d2 = ray2.magnitude(); + if (((d2 * d2 - d * d) < (VIS_RADIUS * VIS_RADIUS)) && (d > VIS_RADIUS)) + { + if (d < distance) + { + distance = d; + return true; + } + } + } + + return false; +} +//---------------------------------------------------- +bool ESoundSource::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 version = ini.r_u32(sect_name, "version"); + + if (version != SOUND_SOURCE_VERSION) + { + ELog.Msg(mtError, "ESoundSource: Unsupported version."); + return false; + } + + inherited::LoadLTX(ini, sect_name); + + m_Type = ESoundType(ini.r_u32(sect_name, "snd_type")); + + m_WAVName = ini.r_string(sect_name, "snd_name"); + + m_Flags.assign(ini.r_u32(sect_name, "flags")); + + m_Params.position = ini.r_fvector3(sect_name, "snd_position"); + m_Params.volume = ini.r_float(sect_name, "volume"); + m_Params.freq = ini.r_float(sect_name, "freq"); + m_Params.min_distance = ini.r_float(sect_name, "min_dist"); + m_Params.max_distance = ini.r_float(sect_name, "max_dist"); + m_Params.max_ai_distance = ini.r_float(sect_name, "max_ai_dist"); + + m_RandomPause = ini.r_fvector2(sect_name, "random_pause"); + m_ActiveTime = ini.r_fvector2(sect_name, "active_time"); + m_PlayTime = ini.r_fvector2(sect_name, "play_time"); + + ResetSource(); + + switch (m_Type) + { + case stStaticSource: + if (m_Flags.is(flPlaying)) + Play(); + //. if (m_Flags.is(flSimulating)) Simulate(); + break; + default: + THROW; + } + return true; +} + +void ESoundSource::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + inherited::SaveLTX(ini, sect_name); + + ini.w_u32(sect_name, "version", SOUND_SOURCE_VERSION); + + ini.w_u32(sect_name, "snd_type", m_Type); + + ini.w_string(sect_name, "snd_name", m_WAVName.c_str()); + + ini.w_u32(sect_name, "flags", m_Flags.get()); + + ini.w_fvector3(sect_name, "snd_position", m_Params.position); + ini.w_float(sect_name, "volume", m_Params.volume); + ini.w_float(sect_name, "freq", m_Params.freq); + ini.w_float(sect_name, "min_dist", m_Params.min_distance); + ini.w_float(sect_name, "max_dist", m_Params.max_distance); + ini.w_float(sect_name, "max_ai_dist", m_Params.max_ai_distance); + + ini.w_fvector2(sect_name, "random_pause", m_RandomPause); + ini.w_fvector2(sect_name, "active_time", m_ActiveTime); + ini.w_fvector2(sect_name, "play_time", m_PlayTime); +} + +bool ESoundSource::LoadStream(IReader &F) +{ + u16 version = 0; + + if (F.r_chunk(SOUND_CHUNK_VERSION, &version)) + { + if (version != SOUND_SOURCE_VERSION) + { + ELog.Msg(mtError, "ESoundSource: Unsupported version."); + return false; + } + } + else + return false; + + inherited::LoadStream(F); + + R_ASSERT(F.find_chunk(SOUND_CHUNK_TYPE)); + m_Type = ESoundType(F.r_u32()); + + if (m_Type != stStaticSource) + { + Msg("! WARNING unknown type of sound: %u", (u32)m_Type); + m_Type = stStaticSource; + } + + R_ASSERT(F.find_chunk(SOUND_CHUNK_SOURCE_NAME)); + F.r_stringZ(m_WAVName); + + if (F.find_chunk(SOUND_CHUNK_SOURCE_PARAMS3)) + { + m_Params.base_volume = 1.f; + F.r_fvector3(m_Params.position); + m_Params.volume = F.r_float(); + m_Params.freq = F.r_float(); + m_Params.min_distance = F.r_float(); + m_Params.max_distance = F.r_float(); + m_Params.max_ai_distance = F.r_float(); + } + else if (F.find_chunk(SOUND_CHUNK_SOURCE_PARAMS2)) + { + m_Params.base_volume = 1.f; + F.r_fvector3(m_Params.position); + m_Params.volume = F.r_float(); + m_Params.freq = F.r_float(); + m_Params.min_distance = F.r_float(); + m_Params.max_distance = F.r_float(); + m_Params.max_ai_distance = F.r_float(); + } + else + { + if (!F.find_chunk(SOUND_CHUNK_SOURCE_PARAMS)) + { + ELog.DlgMsg(mtError, "ESoundSource: Can't load Sound Source '%s'. Unsupported version.", *m_WAVName); + return false; + } + m_Params.base_volume = 1.f; + F.r_fvector3(m_Params.position); + m_Params.volume = F.r_float(); + m_Params.freq = F.r_float(); + m_Params.min_distance = F.r_float(); + m_Params.max_distance = F.r_float(); + m_Params.max_ai_distance = m_Params.max_distance; + } + + if (F.find_chunk(SOUND_CHUNK_SOURCE_FLAGS)) + F.r(&m_Flags, sizeof(m_Flags)); + + if (F.find_chunk(SOUND_CHUNK_GAME_PARAMS)) + { + F.r_fvector2(m_RandomPause); + F.r_fvector2(m_ActiveTime); + F.r_fvector2(m_PlayTime); + } + + ResetSource(); + + switch (m_Type) + { + case stStaticSource: + if (m_Flags.is(flPlaying)) + Play(); + //. if (m_Flags.is(flSimulating)) Simulate(); + break; + default: + THROW; + } + return true; +} + +void ESoundSource::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.open_chunk(SOUND_CHUNK_VERSION); + F.w_u16(SOUND_SOURCE_VERSION); + F.close_chunk(); + + F.w_chunk(SOUND_CHUNK_TYPE, &m_Type, sizeof(m_Type)); + + F.open_chunk(SOUND_CHUNK_SOURCE_NAME); + F.w_stringZ(m_WAVName); + F.close_chunk(); + + F.w_chunk(SOUND_CHUNK_SOURCE_FLAGS, &m_Flags, sizeof(m_Flags)); + + F.open_chunk(SOUND_CHUNK_SOURCE_PARAMS3); + F.w_fvector3(m_Params.position); + F.w_float(m_Params.volume); + F.w_float(m_Params.freq); + F.w_float(m_Params.min_distance); + F.w_float(m_Params.max_distance); + F.w_float(m_Params.max_ai_distance); + F.close_chunk(); + + F.open_chunk(SOUND_CHUNK_GAME_PARAMS); + F.w_fvector2(m_RandomPause); + F.w_fvector2(m_ActiveTime); + F.w_fvector2(m_PlayTime); + F.close_chunk(); +} + +//---------------------------------------------------- + +void ESoundSource::OnChangeWAV(PropValue *prop) +{ + BOOL bPlay = !!m_Source._feedback(); + ResetSource(); + if (bPlay) + Play(); +} + +void ESoundSource::OnChangeSource(PropValue *prop) +{ + m_Source.set_params(&m_Params); +} + +void ESoundSource::OnControlClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + switch (V->btn_num) + { + case 0: + Play(); + break; + case 1: + Stop(); + break; + //. case 2: Simulate(); break; + } + UI->RedrawScene(); + bModif = false; +} + +void ESoundSource::FillProp(LPCSTR pref, PropItemVec &values) +{ + inherited::FillProp(pref, values); + ButtonValue *B; + B = PHelper().CreateButton(values, PrepareKey(pref, "Custom\\Controls"), "Play,Stop,Simulate", 0); + B->OnBtnClickEvent.bind(this, &ESoundSource::OnControlClick); + PropValue *V; + V = PHelper().CreateChoose(values, PrepareKey(pref, "Source\\WAVE name"), &m_WAVName, smSoundSource); + V->OnChangeEvent.bind(this, &ESoundSource::OnChangeWAV); + V = PHelper().CreateFloat(values, PrepareKey(pref, "Source\\Frequency"), &m_Params.freq, 0.0f, 2.f); + V->OnChangeEvent.bind(this, &ESoundSource::OnChangeSource); + V = PHelper().CreateFloat(values, PrepareKey(pref, "Source\\Volume"), &m_Params.volume, 0.0f, 1.f); + V->OnChangeEvent.bind(this, &ESoundSource::OnChangeSource); + V = PHelper().CreateFloat(values, PrepareKey(pref, "Source\\Min dist"), &m_Params.min_distance, 0.1f, 1000.f, 0.1f, 1); + V->Owner()->Enable(FALSE); + V = PHelper().CreateFloat(values, PrepareKey(pref, "Source\\Max dist"), &m_Params.max_distance, 0.1f, 1000.f, 0.1f, 1); + V->Owner()->Enable(FALSE); + V = PHelper().CreateFloat(values, PrepareKey(pref, "Source\\Max ai dist"), &m_Params.max_ai_distance, 0.1f, 1000.f, 0.1f, 1); + V->Owner()->Enable(FALSE); + PHelper().CreateCaption(values, PrepareKey(pref, "Game\\Active time\\Hint"), "Zero - play sound looped round the clock."); + PHelper().CreateTime(values, PrepareKey(pref, "Game\\Active time\\From"), &m_ActiveTime.x); + PHelper().CreateTime(values, PrepareKey(pref, "Game\\Active time\\To"), &m_ActiveTime.y); + PHelper().CreateCaption(values, PrepareKey(pref, "Game\\Play time\\Hint"), "Zero - play sound once."); + PHelper().CreateTime(values, PrepareKey(pref, "Game\\Play time\\From"), &m_PlayTime.x); + PHelper().CreateTime(values, PrepareKey(pref, "Game\\Play time\\To"), &m_PlayTime.y); + PHelper().CreateCaption(values, PrepareKey(pref, "Game\\Pause delta\\Hint"), "Zero - play sound looped."); + PHelper().CreateTime(values, PrepareKey(pref, "Game\\Pause delta\\From"), &m_RandomPause.x); + PHelper().CreateTime(values, PrepareKey(pref, "Game\\Pause delta\\To"), &m_RandomPause.y); + // V=PHelper().CreateFlag32 (values,PHelper().PrepareKey(pref,"Looped"), &m_Flags, flLooped); + // V->OnChangeEvent = OnChangeSource; +} +//---------------------------------------------------- + +bool ESoundSource::GetSummaryInfo(SSceneSummary *inf) +{ + inherited::GetSummaryInfo(inf); + if (m_WAVName.size()) + inf->waves.insert(*m_WAVName); + inf->sound_source_cnt++; + return true; +} + +void ESoundSource::OnFrame() +{ + inherited::OnFrame(); + switch (m_Command) + { + case stPlay: + m_Source.play(0, m_Flags.is(flLooped)); + m_Source.set_params(&m_Params); + m_Command = stNothing; + m_Flags.set(flPlaying, TRUE); + break; + case stStop: + m_Source.stop(); + m_Command = stNothing; + m_Flags.set(flPlaying, FALSE); + m_Flags.set(flSimulating, FALSE); + break; + case stSimulate: + { + /* + m_Flags.set (flSimulating,TRUE); + if ((fis_zero(m_ActiveTime.x)&&fis_zero(m_ActiveTime.y))|| + ((g_pGamePersistent->Environment().GetGameTime()>m_ActiveTime.x)&&(g_pGamePersistent->Environment().GetGameTime()=m_NextTime) + { + bool bFullPlay = fis_zero(m_PlayTime.x)&&fis_zero(m_PlayTime.y); + m_Source.play (0,bFullPlay?0:sm_Looped); + m_Source.set_params (&m_Params); + if (bFullPlay) + { + m_StopTime = 0xFFFFFFFF; + m_NextTime = EDevice.dwTimeGlobal+iFloor(m_Source.get_length_sec()/1000.0f)+Random.randF(m_RandomPause.x,m_RandomPause.y)*1000; + }else{ + m_StopTime = bFullPlay?0:EDevice.dwTimeGlobal+Random.randF(m_PlayTime.x,m_PlayTime.y)*1000; + m_NextTime = m_StopTime+Random.randF(m_RandomPause.x,m_RandomPause.y)*1000; + } + } + } + }else{ + if (EDevice.dwTimeGlobal>=m_StopTime) + m_Source.stop_deffered(); + } + + }else{ + if (0!=m_Source._feedback()) + m_Source.stop_deffered(); + } + */ + } + break; + case stNothing: + break; + default: + THROW; + } +} + +void ESoundSource::ResetSource() +{ + m_Source.destroy(); + if (m_WAVName.size()) + { + m_Source.create(*m_WAVName, st_Effect, sg_Undefined); + CSoundRender_Source *src = (CSoundRender_Source *)m_Source._handle(); + m_Params.min_distance = src->m_fMinDist; + m_Params.max_distance = src->m_fMaxDist; + m_Params.max_ai_distance = src->m_fMaxAIDist; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + m_Source.set_params(&m_Params); +} + +void ESoundSource::SetSourceWAV(LPCSTR fname) +{ + m_WAVName = fname; + ResetSource(); +} + +bool ESoundSource::ExportGame(SExportStreams *F) +{ + SExportStreamItem &I = F->sound_static; + I.stream.open_chunk(I.chunk++); + I.stream.open_chunk(0); + I.stream.w_stringZ(m_WAVName); + I.stream.w_fvector3(m_Params.position); + I.stream.w_float(m_Params.volume); + I.stream.w_float(m_Params.freq); + I.stream.w_u32(static_cast(m_ActiveTime.x * 1000)); + I.stream.w_u32(static_cast(m_ActiveTime.y * 1000)); + I.stream.w_u32(static_cast(m_PlayTime.x * 1000)); + I.stream.w_u32(static_cast(m_PlayTime.y * 1000)); + I.stream.w_u32(static_cast(m_RandomPause.x * 1000)); + I.stream.w_u32(static_cast(m_RandomPause.y * 1000)); + I.stream.close_chunk(); + I.stream.close_chunk(); + return true; +} diff --git a/src/editors/LevelEditor/Entry/Sound/ESound_Source.h b/src/editors/LevelEditor/Entry/Sound/ESound_Source.h new file mode 100644 index 00000000000..de29ee65ddd --- /dev/null +++ b/src/editors/LevelEditor/Entry/Sound/ESound_Source.h @@ -0,0 +1,78 @@ +#pragma once + +class ESoundSource : public CCustomObject +{ + typedef CCustomObject inherited; + // static sound + ref_sound m_Source; + shared_str m_WAVName; + CSound_params m_Params; + Fvector2 m_PlayTime; + Fvector2 m_RandomPause; + Fvector2 m_ActiveTime; + u32 m_NextTime; + u32 m_StopTime; + // edit events + void OnChangeWAV(PropValue *prop); + void OnChangeSource(PropValue *prop); + void OnControlClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void ResetSource(); + enum + { + flLooped = (1 << 0), + flPlaying = (1 << 1), + flSimulating = (1 << 2) + }; + Flags32 m_Flags; + enum ECommand + { + stNothing, + stPlay, + stStop, + stPause, + stSimulate, + }; + ECommand m_Command; + +public: + enum ESoundType + { + stStaticSource = 0, + }; + ESoundType m_Type; + +public: + virtual const Fvector &GetPosition() const { return m_Params.position; } + virtual void SetPosition(const Fvector &pos) + { + m_Params.position.set(pos); + if (m_Source._feedback()) + m_Source.set_position(m_Params.position); + } + +public: + ESoundSource(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + ~ESoundSource(); + virtual bool CanAttach() { return true; } + + LPCSTR GetSourceWAV() { return *m_WAVName; } + void SetSourceWAV(LPCSTR fname); + void Play() { m_Command = stPlay; } + void Stop() { m_Command = stStop; } + void Simulate() { m_Command = stSimulate; } + + virtual void Render(int priority, bool strictB2F); + virtual bool RayPick(float &dist, const Fvector &S, const Fvector &D, SRayPickInfo *pinf = NULL); + virtual bool FrustumPick(const CFrustum &frustum); + virtual void OnFrame(); + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + virtual bool GetBox(Fbox &box); + virtual void Scale(Fvector &amount) { ; } + virtual void FillProp(LPCSTR pref, PropItemVec &values); + virtual bool GetSummaryInfo(SSceneSummary *inf); + virtual bool ExportGame(SExportStreams *data); +}; diff --git a/src/editors/LevelEditor/Entry/Spawn/SpawnPoint.cpp b/src/editors/LevelEditor/Entry/Spawn/SpawnPoint.cpp new file mode 100644 index 00000000000..4588eba7917 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Spawn/SpawnPoint.cpp @@ -0,0 +1,1629 @@ +#include "stdafx.h" + +#define SPAWNPOINT_CHUNK_VERSION 0xE411 +#define SPAWNPOINT_CHUNK_POSITION 0xE412 +#define SPAWNPOINT_CHUNK_RPOINT 0xE413 +#define SPAWNPOINT_CHUNK_DIRECTION 0xE414 +#define SPAWNPOINT_CHUNK_SQUADID 0xE415 +#define SPAWNPOINT_CHUNK_GROUPID 0xE416 +#define SPAWNPOINT_CHUNK_TYPE 0xE417 + +#define SPAWNPOINT_CHUNK_ENTITYREF 0xE419 +#define SPAWNPOINT_CHUNK_SPAWNDATA 0xE420 + +#define SPAWNPOINT_CHUNK_ATTACHED_OBJ 0xE421 + +#define SPAWNPOINT_CHUNK_ENVMOD 0xE422 +#define SPAWNPOINT_CHUNK_ENVMOD2 0xE423 +#define SPAWNPOINT_CHUNK_ENVMOD3 0xE424 + +// ?? +//#define SPAWNPOINT_CHUNK_FLAGS 0xE418 +#define SPAWNPOINT_CHUNK_FLAGS 0xE425 + +const float RPOINT_SIZE = 0.5f; +const float ENVMOD_SIZE = 0.25f; +const int MAX_TEAM = 32; + +const u32 RP_COLORS[MAX_TEAM] = +{ + 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0x00ffff, 0xff00ff, 0xCD5C5C, 0xF08080, + 0xDC143C, 0xB22222, 0x8B0000, 0xFFC0CB, 0xFF69B4, 0xC71585, 0xFF7F50, 0xFF8C00, + 0xFFD700, 0xFFFFE0, 0xFFE4B5, 0xF0E68C, 0xBDB76B, 0xE6E6FA, 0xDDA0DD, 0xEE82EE, + 0xFF00FF, 0xBA55D3, 0x9400D3, 0x4B0082, 0xB8860B, 0x800000, 0x808080, 0x000000 +}; + +void CSE_Visual::set_visual(LPCSTR name, bool load) +{ + string_path tmp; + strcpy(tmp, name); + if (strext(tmp)) + *strext(tmp) = 0; + xr_strlwr(tmp); + visual_name = tmp; +} + +//------------------------------------------------------------------------------ +// CLE_Visual +//------------------------------------------------------------------------------ +CLE_Visual::CLE_Visual(CSE_Visual *src) +{ + source = src; + visual = 0; +} + +bool CLE_Visual::g_tmp_lock = false; + +CLE_Visual::~CLE_Visual() +{ + ::Render->model_Delete(visual, TRUE); +} + +void CLE_Visual::OnDrawUI() +{ + bool ok; + shared_str name; + if (UIChooseForm::GetResult(ok, name)) + { + if (ok) + { + source->visual_name = name; + visual = ::Render->model_Create(source->visual_name.c_str()); + } + EDevice.seqDrawUI.Remove(this); + } + UIChooseForm::Update(); +} + +void CLE_Visual::OnChangeVisual() +{ + ::Render->model_Delete(visual, TRUE); + if (source->visual_name.size()) + { + visual = ::Render->model_Create(source->visual_name.c_str()); + + if (NULL == visual && !g_tmp_lock) + { + xr_string _msg = "Model [" + xr_string(source->visual_name.c_str()) + "] not found. Do you want to select it from library?"; + int mr = ELog.DlgMsg(mtConfirmation, mbYes | mbNo, _msg.c_str()); + LPCSTR _new_val = 0; + g_tmp_lock = true; + if (mr == mrYes) + { + UIChooseForm::SelectItem(smVisual, 1); + EDevice.seqDrawUI.Add(this); + } + + g_tmp_lock = false; + } + PlayAnimationFirstFrame(); + } + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CLE_Visual::PlayAnimation() +{ + if (g_tmp_lock) + return; + // play motion if skeleton + StopAllAnimations(); + + CKinematicsAnimated *KA = PKinematicsAnimated(visual); + IKinematics *K = PKinematics(visual); + if (KA) + { + MotionID M = KA->ID_Cycle_Safe(source->startup_animation.c_str()); + if (M.valid()) + KA->PlayCycle(M); + } + if (K) + K->CalculateBones(); +} + +void CLE_Visual::StopAllAnimations() +{ + if (g_tmp_lock) + return; + // play motion if skeleton + CKinematicsAnimated *KA = PKinematicsAnimated(visual); + if (KA) + { + for (u16 i = 0; i < MAX_PARTS; ++i) + KA->LL_CloseCycle(i, u8(-1)); + } +} + +void CLE_Visual::PlayAnimationFirstFrame() +{ + if (g_tmp_lock) + return; + // play motion if skeleton + + StopAllAnimations(); + + CKinematicsAnimated *KA = PKinematicsAnimated(visual); + IKinematics *K = PKinematics(visual); + if (KA) + { + MotionID M = KA->ID_Cycle_Safe(source->startup_animation.c_str()); + if (M.valid()) + { + KA->PlayCycle(M); + PauseAnimation(); + } + else + Msg("! visual [%s] has no animation [%s]", source->visual_name.c_str(), source->startup_animation.c_str()); + } + if (K) + K->CalculateBones(); +} +struct SetBlendLastFrameCB : public IterateBlendsCallback +{ + virtual void operator()(CBlend &B) + { + B.timeCurrent = B.timeTotal - 0.4444f; + B.blendAmount = 1.0f; + B.playing = !B.playing; + } +} g_Set_blend_last_frame_CB; + +void CLE_Visual::PlayAnimationLastFrame() +{ + if (g_tmp_lock) + return; + // play motion if skeleton + + StopAllAnimations(); + + CKinematicsAnimated *KA = PKinematicsAnimated(visual); + IKinematics *K = PKinematics(visual); + if (KA) + { + MotionID M = KA->ID_Cycle_Safe(source->startup_animation.c_str()); + if (M.valid()) + { + KA->PlayCycle(M); + KA->LL_IterateBlends(g_Set_blend_last_frame_CB); + } + } + if (K) + K->CalculateBones(); +} + +struct TogglelendCB : public IterateBlendsCallback +{ + virtual void operator()(CBlend &B) + { + B.playing = !B.playing; + } +} g_toggle_pause_blendCB; + +void CLE_Visual::PauseAnimation() +{ + if (g_tmp_lock) + return; + + CKinematicsAnimated *KA = PKinematicsAnimated(visual); + IKinematics *K = PKinematics(visual); + + if (KA) + KA->LL_IterateBlends(g_toggle_pause_blendCB); + + if (K) + K->CalculateBones(); +} + +//------------------------------------------------------------------------------ +// CLE_Motion +//------------------------------------------------------------------------------ +CSpawnPoint::CLE_Motion::CLE_Motion(CSE_Motion *src) +{ + source = src; + animator = 0; +} +CSpawnPoint::CLE_Motion::~CLE_Motion() +{ +} +void CSpawnPoint::CLE_Motion::OnChangeMotion() +{ + xr_delete(animator); + if (source->motion_name.size()) + { + animator = xr_new(); + animator->Load(*source->motion_name); + PlayMotion(); + } + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} +void CSpawnPoint::CLE_Motion::PlayMotion() +{ + // play motion if skeleton + if (animator) + animator->Play(true); +} +//------------------------------------------------------------------------------ +// SpawnData +//------------------------------------------------------------------------------ +void CSpawnPoint::SSpawnData::Create(LPCSTR _entity_ref) +{ + m_Data = xrSE_Factory::create_entity(_entity_ref); + if (m_Data) + { + m_Data->set_name(_entity_ref); + if (m_Data->visual()) + { + m_Visual = xr_new(m_Data->visual()); + m_Data->set_editor_flag(IServerEntity::flVisualChange | IServerEntity::flVisualAnimationChange); + } + if (m_Data->motion()) + { + m_Motion = xr_new(m_Data->motion()); + m_Data->set_editor_flag(IServerEntity::flMotionChange); + } + if (pSettings->line_exist(m_Data->name(), "$player")) + { + if (pSettings->r_bool(m_Data->name(), "$player")) + { + m_Data->flags().set(M_SPAWN_OBJECT_ASPLAYER, TRUE); + } + } + m_ClassID = pSettings->r_clsid(m_Data->name(), "class"); + } + else + { + Log("!Can't create entity: ", _entity_ref); + } + + if (pSettings->line_exist(_entity_ref, "$render_if_selected")) + { + m_owner->SetRenderIfSelected(TRUE); + } + else + m_owner->SetRenderIfSelected(FALSE); +} + +void CSpawnPoint::SSpawnData::Destroy() +{ + xrSE_Factory::destroy_entity(m_Data); + xr_delete(m_Visual); + xr_delete(m_Motion); +} + +void CSpawnPoint::SSpawnData::get_bone_xform(LPCSTR name, Fmatrix &xform) +{ + xform.identity(); + if (name && name[0] && m_Visual && m_Visual->visual) + { + IKinematics *P = PKinematics(m_Visual->visual); + if (P) + { + u16 id = P->LL_BoneID(name); + if (id != BI_NONE) + xform = P->LL_GetTransform(id); + } + } +} + +bool CSpawnPoint::SSpawnData::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + xr_string temp = ini.r_string(sect_name, "name"); + Create(temp.c_str()); + + if (ini.line_exist(sect_name, "fl")) + m_flags.assign(ini.r_u8(sect_name, "fl")); + + NET_Packet Packet; + SIniFileStream ini_stream; + ini_stream.ini = &ini; + ini_stream.sect = sect_name; + ini_stream.move_begin(); + Packet.inistream = &ini_stream; + + if (Valid()) + if (!m_Data->Spawn_Read(Packet)) + Destroy(); + + return Valid(); +} + +void CSpawnPoint::SSpawnData::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + ini.w_string(sect_name, "name", m_Data->name()); + ini.w_u8(sect_name, "fl", m_flags.get()); + + NET_Packet Packet; + SIniFileStream ini_stream; + ini_stream.ini = &ini; + ini_stream.sect = sect_name; + ini_stream.move_begin(); + Packet.inistream = &ini_stream; + + m_Data->Spawn_Write(Packet, TRUE); +} + +void CSpawnPoint::SSpawnData::SaveStream(IWriter &F) +{ + F.open_chunk(SPAWNPOINT_CHUNK_ENTITYREF); + F.w_stringZ(m_Data->name()); + F.close_chunk(); + + if (!Core.SocSdk) + { + F.open_chunk(SPAWNPOINT_CHUNK_FLAGS); + F.w_u8(m_flags.get()); + F.close_chunk(); + } + + F.open_chunk(SPAWNPOINT_CHUNK_SPAWNDATA); + NET_Packet Packet; + m_Data->Spawn_Write(Packet, TRUE); + F.w_u32(Packet.B.count); + F.w(Packet.B.data, Packet.B.count); + F.close_chunk(); +} + +bool CSpawnPoint::SSpawnData::LoadStream(IReader &F) +{ + string64 temp; + R_ASSERT(F.find_chunk(SPAWNPOINT_CHUNK_ENTITYREF)); + F.r_stringZ(temp, sizeof(temp)); + + if (F.find_chunk(SPAWNPOINT_CHUNK_FLAGS)) + m_flags.assign(F.r_u8()); + + NET_Packet Packet; + R_ASSERT(F.find_chunk(SPAWNPOINT_CHUNK_SPAWNDATA)); + Packet.B.count = F.r_u32(); + F.r(Packet.B.data, Packet.B.count); + Create(temp); + + if (Valid() && !m_Data->Spawn_Read(Packet)) + Destroy(); + + return Valid(); +} + +bool CSpawnPoint::SSpawnData::ExportGame(SExportStreams *F, CSpawnPoint *owner) +{ + // set params + m_Data->set_name_replace(owner->GetName()); + m_Data->position().set(owner->GetPosition()); + m_Data->angle().set(owner->GetRotation()); + + // export cform (if needed) + IServerEntityShape* cform = m_Data->shape(); + + // SHAPE + if (cform && !(owner->m_AttachedObject && (owner->m_AttachedObject->FClassID == OBJCLASS_SHAPE))) + { + ELog.DlgMsg(mtError, "Spawn Point: '%s' must contain attached shape.", owner->GetName()); + return false; + } + + if (cform) + { + CEditShape *shape = dynamic_cast(owner->m_AttachedObject); + R_ASSERT(shape); + shape->ApplyScale(); + owner->SetScale(shape->GetScale()); + cform->assign_shapes(&*shape->GetShapes().begin(), shape->GetShapes().size()); + } + // end + + NET_Packet Packet; + m_Data->Spawn_Write(Packet, TRUE); + + SExportStreamItem &tgt = (m_flags.test(eSDTypeRespawn)) ? F->spawn_rs : F->spawn; + tgt.stream.open_chunk(tgt.chunk++); + tgt.stream.w(Packet.B.data, Packet.B.count); + tgt.stream.close_chunk(); + + return true; +} + +void CSpawnPoint::SSpawnData::OnAnimControlClick(ButtonValue *value, bool &bModif, bool &bSafe) +{ + ButtonValue *B = dynamic_cast(value); + R_ASSERT(B); + switch (B->btn_num) + { + // "First,Play,Pause,Stop,Last", + case 0: // first + { + m_Visual->PlayAnimationFirstFrame(); + } + break; + case 1: // play + { + m_Visual->PlayAnimation(); + } + break; + case 2: // pause + { + m_Visual->PauseAnimation(); + } + break; + case 3: // stop + { + m_Visual->StopAllAnimations(); + } + break; + case 4: // last + { + m_Visual->PlayAnimationLastFrame(); + } + break; + } +} + +void CSpawnPoint::SSpawnData::FillProp(LPCSTR pref, PropItemVec &items) +{ + m_Data->FillProp(pref, items); + + if (Scene->m_LevelOp.m_mapUsage.MatchType(eGameIDDeathmatch | eGameIDTeamDeathmatch | eGameIDArtefactHunt | eGameIDCaptureTheArtefact)) + PHelper().CreateFlag8(items, PrepareKey(pref, "MP respawn"), &m_flags, eSDTypeRespawn); + + if (m_Visual) + { + ButtonValue *BV = PHelper().CreateButton(items, + PrepareKey(pref, m_Data->name(), "Model\\AnimationControl"), + "|<<,Play,Pause,Stop,>>|", + 0); + BV->OnBtnClickEvent.bind(this, &CSpawnPoint::SSpawnData::OnAnimControlClick); + } +} + +void CSpawnPoint::SSpawnData::Render(bool bSelected, const Fmatrix &parent, int priority, bool strictB2F) +{ + if (m_Visual && m_Visual->visual) + ::Render->model_Render(m_Visual->visual, parent, priority, strictB2F, 1.f); + + if (m_Motion && m_Motion->animator && bSelected && (1 == priority) && (false == strictB2F)) + m_Motion->animator->DrawPath(); + + RCache.set_xform_world(Fidentity); + EDevice.SetShader(EDevice.m_WireShader); + m_Data->on_render(&DU_impl, this, bSelected, parent, priority, strictB2F); + + if (bSelected) + { + xr_vector::iterator it = m_VisualHelpers.begin(); + xr_vector::iterator it_e = m_VisualHelpers.end(); + Fmatrix M; + u32 idx = 0; + for (; it != it_e; ++it, ++idx) + { + visual_data *vc = m_Data->visual_collection() + idx; + M.mul(parent, vc->matrix); + CLE_Visual *v = *it; + ::Render->model_Render(v->visual, M, priority, strictB2F, 1.f); + } + } +} + +void CSpawnPoint::SSpawnData::OnFrame() +{ + if (m_Data->m_editor_flags.is(IServerEntity::flUpdateProperties)) + ExecCommand(COMMAND_UPDATE_PROPERTIES); + // visual part + if (m_Visual) + { + if (m_Data->m_editor_flags.is(IServerEntity::flVisualChange)) + m_Visual->OnChangeVisual(); + + if (m_Data->m_editor_flags.is(IServerEntity::flVisualAnimationChange)) + { + m_Visual->PlayAnimationFirstFrame(); + m_Data->m_editor_flags.set(IServerEntity::flVisualAnimationChange, FALSE); + } + + if (m_Visual->visual && PKinematics(m_Visual->visual)) + PKinematics(m_Visual->visual)->CalculateBones(TRUE); + } + // motion part + if (m_Motion) + { + if (m_Data->m_editor_flags.is(IServerEntity::flMotionChange)) + m_Motion->OnChangeMotion(); + if (m_Motion->animator) + m_Motion->animator->Update(EDevice.fTimeDelta); + } + + if (m_Data->m_editor_flags.is(IServerEntity::flVisualChange)) + { + xr_vector::iterator it = m_VisualHelpers.begin(); + xr_vector::iterator it_e = m_VisualHelpers.end(); + for (; it != it_e; ++it) + { + CLE_Visual *v = *it; + xr_delete(v); + } + m_VisualHelpers.clear(); + + u32 cnt = m_Data->visual_collection_size(); + visual_data *vc = m_Data->visual_collection(); + + for (u32 i = 0; i < cnt; ++i, ++vc) + { + CLE_Visual *V = xr_new(vc->visual); + V->OnChangeVisual(); + m_VisualHelpers.push_back(V); + V->PlayAnimation(); + } + } + + xr_vector::iterator it = m_VisualHelpers.begin(); + xr_vector::iterator it_e = m_VisualHelpers.end(); + for (; it != it_e; ++it) + { + CLE_Visual *v = *it; + if (PKinematics(v->visual)) + PKinematics(v->visual)->CalculateBones(TRUE); + } + + // reset editor flags + m_Data->m_editor_flags.zero(); +} +//------------------------------------------------------------------------------ +CSpawnPoint::CSpawnPoint(LPVOID data, LPCSTR name) : CCustomObject(data, name), m_SpawnData(this) +{ + m_rpProfile = ""; + m_EM_Flags.one(); + Construct(data); +} + +void CSpawnPoint::Construct(LPVOID data) +{ + FClassID = OBJCLASS_SPAWNPOINT; + m_AttachedObject = nullptr; + + if (!data) + { + SetValid(false); + return; + } + + if (!strcmp(LPSTR(data), RPOINT_CHOOSE_NAME)) + { + m_Type = ptRPoint; + m_RP_Type = rptActorSpawn; + + if (Core.SocSdk) + { + m_GameType.m_GameType.assign(static_cast(0) /*ERPGameType::rpgtGameAny*/); + m_RP_TeamID = 0; + } + else + { + m_GameType.SetDefaults(); + m_RP_TeamID = 1; + } + } + else if (!strcmp(LPSTR(data), ENVMOD_CHOOSE_NAME)) + { + m_Type = ptEnvMod; + m_EM_Radius = 10.f; + m_EM_Power = 1.f; + m_EM_ViewDist = 300.f; + m_EM_FogColor = 0x00808080; + m_EM_FogDensity = 1.f; + m_EM_AmbientColor = 0x00000000; + m_EM_SkyColor = 0x00FFFFFF; + m_EM_HemiColor = 0x00FFFFFF; + } + else + { + CreateSpawnData(LPCSTR(data)); + + if (!m_SpawnData.Valid()) + SetValid(false); + else + m_Type = ptSpawnPoint; + } +} + +void CSpawnPoint::OnSceneRemove() +{ + DeletePhysicsShell(); + inherited::OnSceneRemove(); +} +CSpawnPoint::~CSpawnPoint() +{ + xr_delete(m_AttachedObject); + OnDeviceDestroy(); +} + +void CSpawnPoint::Select(int flag) +{ + inherited::Select(flag); + if (m_AttachedObject) + m_AttachedObject->Select(flag); +} + +void CSpawnPoint::Move(Fvector &amount) +{ + inherited::Move(amount); + const float f_drag_factor = 200.f; + if (m_physics_shell) + ApplyDragForce(Fvector().mul(amount, f_drag_factor)); +} + +void CSpawnPoint::SetPosition(const Fvector &pos) +{ + if (m_physics_shell) + return; + inherited::SetPosition(pos); + if (m_AttachedObject) + m_AttachedObject->SetPosition(pos); +} +void CSpawnPoint::SetRotation(const Fvector &rot) +{ + if (m_physics_shell) + return; + inherited::SetRotation(rot); + if (m_AttachedObject) + m_AttachedObject->SetRotation(rot); +} +void CSpawnPoint::SetScale(const Fvector &scale) +{ + if (m_physics_shell) + return; + inherited::SetScale(scale); + if (m_AttachedObject) + m_AttachedObject->SetScale(scale); +} + +bool CSpawnPoint::AttachObject(CCustomObject *obj) +{ + bool bAllowed = false; + // + if (m_SpawnData.Valid()) + { + switch (obj->FClassID) + { + case OBJCLASS_SHAPE: + bAllowed = !!m_SpawnData.m_Data->shape(); + break; + // case OBJCLASS_SCENEOBJECT: + // bAllowed = !!dynamic_cast(m_SpawnData.m_Data); + // break; + } + } + // + if (bAllowed) + { + DetachObject(); + OnAppendObject(obj); + m_AttachedObject->OnAttach(this); + SetPosition(m_AttachedObject->GetPosition()); + FRotation = m_AttachedObject->GetRotation(); + SetScale(m_AttachedObject->GetScale()); + } + return bAllowed; +} + +void CSpawnPoint::DetachObject() +{ + if (m_AttachedObject) + { + m_AttachedObject->OnDetach(); + Scene->AppendObject(m_AttachedObject, false); + m_AttachedObject = 0; + } +} + +bool CSpawnPoint::RefCompare(LPCSTR ref) +{ + return ref && ref[0] && m_SpawnData.Valid() ? (strcmp(ref, m_SpawnData.m_Data->name()) == 0) : false; +} + +LPCSTR CSpawnPoint::RefName() +{ + return m_SpawnData.Valid() ? m_SpawnData.m_Data->name() : 0; +} + +bool CSpawnPoint::CreateSpawnData(LPCSTR entity_ref) +{ + R_ASSERT(entity_ref && entity_ref[0]); + m_SpawnData.Destroy(); + m_SpawnData.Create(entity_ref); + if (m_SpawnData.Valid()) + m_Type = ptSpawnPoint; + return m_SpawnData.Valid(); +} +//---------------------------------------------------- + +bool CSpawnPoint::GetBox(Fbox &box) +{ + switch (m_Type) + { + case ptRPoint: + box.set(GetPosition(), GetPosition()); + box.vMin.x -= RPOINT_SIZE; + box.vMin.y -= 0; + box.vMin.z -= RPOINT_SIZE; + box.vMax.x += RPOINT_SIZE; + box.vMax.y += RPOINT_SIZE * 2.f; + box.vMax.z += RPOINT_SIZE; + break; + case ptEnvMod: + box.set(GetPosition(), GetPosition()); + box.grow(Selected() ? m_EM_Radius : ENVMOD_SIZE); + break; + case ptSpawnPoint: + if (m_SpawnData.Valid()) + { + if (m_SpawnData.m_Visual && m_SpawnData.m_Visual->visual) + { + box.set(m_SpawnData.m_Visual->visual->getVisData().box); + Fmatrix transform = FTransformRP; + if (m_physics_shell) + UpdateObjectXform(transform); + + box.xform(transform); + } + else + { + CEditShape *shape = dynamic_cast(m_AttachedObject); + if (shape && !shape->GetShapes().empty()) + { + CShapeData::ShapeVec &SV = shape->GetShapes(); + box.invalidate(); + Fvector p; + for (auto it = SV.begin(); it != SV.end(); it++) + { + switch (it->type) + { + case CShapeData::cfSphere: + p.add(it->data.sphere.P, it->data.sphere.R); + shape->_Transform().transform_tiny(p); + box.modify(p); + p.sub(it->data.sphere.P, it->data.sphere.R); + shape->_Transform().transform_tiny(p); + box.modify(p); + break; + case CShapeData::cfBox: + p.set(0.5f, 0.5f, 0.5f); + it->data.box.transform_tiny(p); + shape->_Transform().transform_tiny(p); + box.modify(p); + p.set(-0.5f, -0.5f, -0.5f); + it->data.box.transform_tiny(p); + shape->_Transform().transform_tiny(p); + box.modify(p); + break; + } + } + } + else + { + box.set(GetPosition(), GetPosition()); + box.vMin.x -= RPOINT_SIZE; + box.vMin.y -= 0; + box.vMin.z -= RPOINT_SIZE; + box.vMax.x += RPOINT_SIZE; + box.vMax.y += RPOINT_SIZE * 2.f; + box.vMax.z += RPOINT_SIZE; + } + } + } + else + { + box.set(GetPosition(), GetPosition()); + box.vMin.x -= RPOINT_SIZE; + box.vMin.y -= 0; + box.vMin.z -= RPOINT_SIZE; + box.vMax.x += RPOINT_SIZE; + box.vMax.y += RPOINT_SIZE * 2.f; + box.vMax.z += RPOINT_SIZE; + } + break; + default: + NODEFAULT; + } + if (m_AttachedObject) + { + Fbox bb; + m_AttachedObject->GetBox(bb); + box.merge(bb); + } + return true; +} + +void CSpawnPoint::OnFrame() +{ + inherited::OnFrame(); + if (m_AttachedObject) + m_AttachedObject->OnFrame(); + if (m_SpawnData.Valid()) + { + if (m_physics_shell && m_SpawnData.m_Data->m_editor_flags.is(IServerEntity::flVisualAnimationChange)) + { + DeletePhysicsShell(); + m_SpawnData.OnFrame(); + CreatePhysicsShell(&FTransform); + } + else + m_SpawnData.OnFrame(); + } +} +void CSpawnPoint::RenderSimBox() +{ + Fbox box; + GetBox(box); + + Fvector c, s; + + box.get_CD(c, s); + Fmatrix m; + m.scale(Fvector().mul(s, 2)); + m.c.set(c); + + // B.mulA_43 (_Transform()); + RCache.set_xform_world(m); + u32 clr = 0x06005000; + DU_impl.DrawIdentBox(true, false, clr, clr); +} +void CSpawnPoint::Render(int priority, bool strictB2F) +{ + + Fmatrix SaveTransform = FTransformRP; + + if (m_physics_shell) + { + UpdateObjectXform(FTransformRP); + RenderSimBox(); + } + inherited::Render(priority, strictB2F); + Scene->SelectLightsForObject(this); + + // render attached object + if (m_AttachedObject) + m_AttachedObject->Render(priority, strictB2F); + if (m_SpawnData.Valid()) + m_SpawnData.Render(Selected(), FTransformRP, priority, strictB2F); + // render spawn point + if (1 == priority) + { + if (strictB2F) + { + RCache.set_xform_world(FTransformRP); + if (m_SpawnData.Valid()) + { + // render icon + ESceneSpawnTool *st = dynamic_cast(FParentTools); + VERIFY(st); + ref_shader s = st->GetIcon(m_SpawnData.m_Data->name()); + DU_impl.DrawEntity(0xffffffff, s); + } + else + { + switch (m_Type) + { + case ptRPoint: + { + ESceneSpawnTool *st = dynamic_cast(FParentTools); + VERIFY(st); + + if (!st->get_draw_visual(m_RP_TeamID, m_RP_Type, m_GameType)) + { + Fcolor c; + c.set(RP_COLORS[m_RP_TeamID]); + DU_impl.DrawEntity(c.get(), EDevice.m_WireShader); + } + } + break; + case ptEnvMod: + { + Fvector pos = {0, 0, 0}; + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawCross(pos, 0.25f, 0x20FFAE00, true); + if (Selected()) + DU_impl.DrawSphere(Fidentity, GetPosition(), m_EM_Radius, 0x30FFAE00, 0x00FFAE00, true, true); + } + break; + + default: + THROW2("CSpawnPoint:: Unknown Type"); + } + } + } + else + { + ESceneSpawnTool *st = dynamic_cast(FParentTools); + VERIFY(st); + if (st->m_Flags.is(ESceneSpawnTool::flShowSpawnType)) + { + xr_string s_name; + if (m_SpawnData.Valid()) + { + s_name = m_SpawnData.m_Data->name(); + } + else + { + switch (m_Type) + { + case ptRPoint: + s_name = make_string("RPoint T:%d", m_RP_TeamID).c_str(); + break; + case ptEnvMod: + s_name = make_string("EnvMod V:%3.2f, F:%3.2f", m_EM_ViewDist, m_EM_FogDensity).c_str(); + break; + default: + THROW2("CSpawnPoint:: Unknown Type"); + } + } + + Fvector D; + D.sub(EDevice.vCameraPosition, GetPosition()); + float dist = D.normalize_magn(); + if (!st->m_Flags.is(ESceneSpawnTool::flPickSpawnType) || + !Scene->RayPickObject(dist, GetPosition(), D, OBJCLASS_SCENEOBJECT, 0, 0)) + DU_impl.OutText(GetPosition(), s_name.c_str(), 0xffffffff, 0xff000000); + } + if (Selected()) + { + RCache.set_xform_world(Fidentity); + Fbox bb; + GetBox(bb); + u32 clr = 0xFFFFFFFF; + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawSelectionBoxB(bb, &clr); + } + } + } + + if (m_Type == ptRPoint) + { + ESceneSpawnTool *st = dynamic_cast(FParentTools); + VERIFY(st); + CEditableObject *v = st->get_draw_visual(m_RP_TeamID, m_RP_Type, m_GameType); + if (v) + v->Render(FTransformRP, priority, strictB2F); + } + FTransformRP = SaveTransform; +} + +bool CSpawnPoint::FrustumPick(const CFrustum &frustum) +{ + if (m_AttachedObject && m_AttachedObject->FrustumPick(frustum)) + return true; + Fbox bb; + GetBox(bb); + u32 mask = 0xff; + return (frustum.testAABB(bb.data(), mask)); +} + +bool CSpawnPoint::RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf) +{ + bool bPick = false; + if (m_AttachedObject) + { + bPick = m_AttachedObject->RayPick(distance, start, direction, pinf); + return bPick; + } + + Fbox bb; + Fvector pos; + float radius; + GetBox(bb); + bb.getsphere(pos, radius); + + Fvector ray2; + ray2.sub(pos, start); + + float d = ray2.dotproduct(direction); + if (d > 0) + { + float d2 = ray2.magnitude(); + if (((d2 * d2 - d * d) < (radius * radius)) && (d > radius)) + { + Fvector pt; + if (Fbox::rpOriginOutside == bb.Pick2(start, direction, pt)) + { + d = start.distance_to(pt); + if (d < distance) + { + distance = d; + bPick = true; + if (pinf && m_SpawnData.m_Visual && m_SpawnData.m_Visual->visual) + { + + IKinematics *K = m_SpawnData.m_Visual->visual->dcast_PKinematics(); + u16 b_id = u16(-1); + Fvector norm; + if (K) + { + bPick = ETOOLS::intersect(FTransformRP, *K, start, direction, b_id, distance, norm); + if (bPick) + { + pinf->visual_inf.K = K; + pinf->visual_inf.normal = norm; + pt.mad(start, direction, distance); + } + } + + pinf->s_obj = this; + pinf->e_obj = 0; + pinf->e_mesh = 0; + pinf->pt = pt; + pinf->inf.range = distance; + } + } + } + } + } + + return bPick; +} + +bool CSpawnPoint::OnAppendObject(CCustomObject *object) +{ + R_ASSERT(!m_AttachedObject); + if (object->FClassID != OBJCLASS_SHAPE) + return false; + // all right + m_AttachedObject = object; + object->m_pOwnerObject = this; + Scene->RemoveObject(object, false, false); + + CEditShape *sh = dynamic_cast(m_AttachedObject); + if (m_SpawnData.Valid()) + { + if (pSettings->line_exist(m_SpawnData.m_Data->name(), "shape_transp_color")) + { + sh->m_DrawTranspColor = pSettings->r_color(m_SpawnData.m_Data->name(), "shape_transp_color"); + sh->m_DrawEdgeColor = pSettings->r_color(m_SpawnData.m_Data->name(), "shape_edge_color"); + } + } + + return true; +} + +bool CSpawnPoint::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 version = ini.r_u32(sect_name, "version"); + + if (version < 0x0014) + { + ELog.Msg(mtError, "SPAWNPOINT: Unsupported version."); + return false; + } + + CCustomObject::LoadLTX(ini, sect_name); + m_Type = (EPointType)ini.r_u32(sect_name, "type"); + + if (m_Type >= ptMaxType) + { + ELog.Msg(mtError, "SPAWNPOINT: Unsupported spawn version."); + return false; + } + + switch (m_Type) + { + case ptSpawnPoint: + { + string128 buff; + strconcat(sizeof(buff), buff, sect_name, "_spawndata"); + if (!m_SpawnData.LoadLTX(ini, buff)) + { + ELog.Msg(mtError, "SPAWNPOINT: Can't load Spawn Data."); + return false; + } + SetValid(true); + } + break; + + case ptRPoint: + { + if (version >= 0x0017) + m_rpProfile = ini.r_string(sect_name, "rp_profile"); + + m_RP_TeamID = ini.r_u8(sect_name, "team_id"); + m_RP_Type = ini.r_u8(sect_name, "rp_type"); + m_GameType.LoadLTX(ini, sect_name, (version == 0x0014)); + } + break; + + case ptEnvMod: + { + m_EM_Radius = ini.r_float(sect_name, "em_radius"); + m_EM_Power = ini.r_float(sect_name, "em_power"); + m_EM_ViewDist = ini.r_float(sect_name, "view_dist"); + m_EM_FogColor = ini.r_u32(sect_name, "fog_color"); + m_EM_FogDensity = ini.r_float(sect_name, "fog_density"); + m_EM_AmbientColor = ini.r_u32(sect_name, "ambient_color"); + m_EM_SkyColor = ini.r_u32(sect_name, "sky_color"); + m_EM_HemiColor = ini.r_u32(sect_name, "hemi_color"); + if (version >= 0x0016) + m_EM_Flags.assign(ini.r_u16(sect_name, "em_flags")); + } + break; + default: + THROW; + } + + // objects + if (ini.line_exist(sect_name, "attached_count")) + Scene->ReadObjectsLTX(ini, sect_name, "attached", EScene::TAppendObject(this, &CSpawnPoint::OnAppendObject), 0); + + UpdateTransform(); + + // BUG fix + CEditShape *shape = dynamic_cast(m_AttachedObject); + if (shape) + SetScale(shape->GetScale()); + + return true; +} + +void CSpawnPoint::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + CCustomObject::SaveLTX(ini, sect_name); + ini.w_u32(sect_name, "version", SPAWNPOINT_VERSION); + + // save attachment + if (m_AttachedObject) + { + ObjectList lst; + lst.push_back(m_AttachedObject); + Scene->SaveObjectsLTX(lst, sect_name, "attached", ini); + } + + ini.w_u32(sect_name, "type", m_Type); + + switch (m_Type) + { + case ptSpawnPoint: + { + string128 buff; + m_SpawnData.SaveLTX(ini, strconcat(sizeof(buff), buff, sect_name, "_spawndata")); + } + break; + + case ptRPoint: + { + ini.w_u8(sect_name, "team_id", m_RP_TeamID); + ini.w_string(sect_name, "rp_profile", m_rpProfile.c_str()); + ini.w_u8(sect_name, "rp_type", m_RP_Type); + m_GameType.SaveLTX(ini, sect_name); + } + break; + + case ptEnvMod: + { + ini.w_float(sect_name, "em_radius", m_EM_Radius); + ini.w_float(sect_name, "em_power", m_EM_Power); + ini.w_float(sect_name, "view_dist", m_EM_ViewDist); + ini.w_u32(sect_name, "fog_color", m_EM_FogColor); + ini.w_float(sect_name, "fog_density", m_EM_FogDensity); + ini.w_u32(sect_name, "ambient_color", m_EM_AmbientColor); + ini.w_u32(sect_name, "sky_color", m_EM_SkyColor); + ini.w_u32(sect_name, "hemi_color", m_EM_HemiColor); + ini.w_u16(sect_name, "em_flags", m_EM_Flags.get()); + } + break; + + default: + THROW; + } +} + +bool CSpawnPoint::LoadStream(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(SPAWNPOINT_CHUNK_VERSION, &version)); + + if (version < 0x0014) + { + ELog.Msg(mtError, "SPAWNPOINT: Unsupported version."); + return false; + } + + CCustomObject::LoadStream(F); + + // new generation + if (F.find_chunk(SPAWNPOINT_CHUNK_ENTITYREF)) + { + if (!m_SpawnData.LoadStream(F)) + { + ELog.Msg(mtError, "SPAWNPOINT: Can't load Spawn Data."); + return false; + } + SetValid(true); + m_Type = ptSpawnPoint; + } + else + { + if (F.find_chunk(SPAWNPOINT_CHUNK_TYPE)) + m_Type = (EPointType)F.r_u32(); + if (m_Type >= ptMaxType) + { + ELog.Msg(mtError, "SPAWNPOINT: Unsupported spawn version."); + return false; + } + switch (m_Type) + { + case ptRPoint: + if (F.find_chunk(SPAWNPOINT_CHUNK_RPOINT)) + { + + m_RP_TeamID = F.r_u8(); + m_RP_Type = F.r_u8(); + m_GameType.LoadStream(F); + if (version >= 0x0017) + F.r_stringZ(m_rpProfile); + } + break; + case ptEnvMod: + if (F.find_chunk(SPAWNPOINT_CHUNK_ENVMOD)) + { + m_EM_Radius = F.r_float(); + m_EM_Power = F.r_float(); + m_EM_ViewDist = F.r_float(); + m_EM_FogColor = F.r_u32(); + m_EM_FogDensity = F.r_float(); + m_EM_AmbientColor = F.r_u32(); + m_EM_SkyColor = F.r_u32(); + if (F.find_chunk(SPAWNPOINT_CHUNK_ENVMOD2)) + m_EM_HemiColor = F.r_u32(); + if (F.find_chunk(SPAWNPOINT_CHUNK_ENVMOD3)) + m_EM_Flags.assign(F.r_u16()); + } + break; + default: + THROW; + } + } + + // objects + Scene->ReadObjectsStream(F, SPAWNPOINT_CHUNK_ATTACHED_OBJ, EScene::TAppendObject(this, &CSpawnPoint::OnAppendObject), 0); + + UpdateTransform(); + + // BUG fix + CEditShape *shape = dynamic_cast(m_AttachedObject); + if (shape) + SetScale(shape->GetScale()); + + return true; +} + +void CSpawnPoint::SaveStream(IWriter &F) +{ + CCustomObject::SaveStream(F); + F.open_chunk(SPAWNPOINT_CHUNK_VERSION); + + if (!Core.SocSdk) + F.w_u16(SPAWNPOINT_VERSION); + else + F.w_u16(SPAWNPOINT_VERSION - 3); + + F.close_chunk(); + + // save attachment + if (m_AttachedObject) + { + ObjectList lst; + lst.push_back(m_AttachedObject); + Scene->SaveObjectsStream(lst, SPAWNPOINT_CHUNK_ATTACHED_OBJ, F); + } + + if (m_SpawnData.Valid()) + { + m_SpawnData.SaveStream(F); + return; + } + + F.w_chunk(SPAWNPOINT_CHUNK_TYPE, &m_Type, sizeof(u32)); + + switch (m_Type) + { + case ptRPoint: + F.open_chunk(SPAWNPOINT_CHUNK_RPOINT); + F.w_u8(m_RP_TeamID); + F.w_u8(m_RP_Type); + + if (Core.SocSdk) + { + F.w_u8(m_GameType.m_GameType.get()); + F.w_u8(0); + } + else + { + m_GameType.SaveStream(F); + F.w_stringZ(m_rpProfile); + } + + F.close_chunk(); + break; + + case ptEnvMod: + F.open_chunk(SPAWNPOINT_CHUNK_ENVMOD); + F.w_float(m_EM_Radius); + F.w_float(m_EM_Power); + F.w_float(m_EM_ViewDist); + F.w_u32(m_EM_FogColor); + F.w_float(m_EM_FogDensity); + F.w_u32(m_EM_AmbientColor); + F.w_u32(m_EM_SkyColor); + F.close_chunk(); + + F.open_chunk(SPAWNPOINT_CHUNK_ENVMOD2); + F.w_u32(m_EM_HemiColor); + F.close_chunk(); + + if (!Core.SocSdk) + { + F.open_chunk(SPAWNPOINT_CHUNK_ENVMOD3); + F.w_u16(m_EM_Flags.get()); + F.close_chunk(); + } + break; + default: + THROW; + } +} + +Fvector3 u32_3f(u32 clr) +{ + Fvector tmp; + float f = 1.f / 255.f; + tmp.x = f * float((clr >> 16) & 0xff); + tmp.y = f * float((clr >> 8) & 0xff); + tmp.z = f * float((clr >> 0) & 0xff); + return tmp; +} + +bool CSpawnPoint::ExportGame(SExportStreams *F) +{ + // spawn + if (m_SpawnData.Valid()) + { + if (m_SpawnData.m_Data->validate()) + m_SpawnData.ExportGame(F, this); + else + { + Log("!Invalid spawn data:", GetName()); + return false; + } + } + else + { + // game + switch (m_Type) + { + case ptRPoint: + F->rpoint.stream.open_chunk(F->rpoint.chunk++); + F->rpoint.stream.w_fvector3(GetPosition()); + F->rpoint.stream.w_fvector3(GetRotation()); + F->rpoint.stream.w_u8(m_RP_TeamID); + F->rpoint.stream.w_u8(m_RP_Type); + + if (Core.SocSdk) + { + F->rpoint.stream.w_u8(static_cast(m_GameType.m_GameType.get())); + F->rpoint.stream.w_u8(0); + } + else + F->rpoint.stream.w_u16(m_GameType.m_GameType.get()); + + F->rpoint.stream.w_stringZ(m_rpProfile); + F->rpoint.stream.close_chunk(); + break; + + case ptEnvMod: + Fcolor tmp; + F->envmodif.stream.open_chunk(F->envmodif.chunk++); + F->envmodif.stream.w_fvector3(GetPosition()); + F->envmodif.stream.w_float(m_EM_Radius); + F->envmodif.stream.w_float(m_EM_Power); + F->envmodif.stream.w_float(m_EM_ViewDist); + F->envmodif.stream.w_fvector3(u32_3f(m_EM_FogColor)); + F->envmodif.stream.w_float(m_EM_FogDensity); + F->envmodif.stream.w_fvector3(u32_3f(m_EM_AmbientColor)); + F->envmodif.stream.w_fvector3(u32_3f(m_EM_SkyColor)); + F->envmodif.stream.w_fvector3(u32_3f(m_EM_HemiColor)); + F->envmodif.stream.w_u16(m_EM_Flags.get()); + F->envmodif.stream.close_chunk(); + break; + default: + THROW; + } + } + return true; +} + +void CSpawnPoint::OnFillRespawnItemProfile(ChooseValue *val) +{ + val->m_Items->clear(); + string_path fn; + FS.update_path(fn, "$game_config$", "mp\\respawn_items.ltx"); + CInifile ini(fn); + auto it = ini.sections().begin(); + auto it_e = ini.sections().end(); + + for (; it != it_e; ++it) + { + shared_str name = (*it)->Name; + shared_str hint; + if (ini.line_exist(name, "description")) + hint = ini.r_string(name, "description"); + else + hint = ""; + + val->m_Items->push_back(SChooseItem(name.c_str(), hint.c_str())); + } +} + +void CSpawnPoint::OnFillChooseItems(ChooseValue *val) +{ + ESceneSpawnTool *st = dynamic_cast(FParentTools); + VERIFY(st); + CLASS_ID cls_id = m_SpawnData.m_ClassID; + ESceneSpawnTool::ClassSpawnMapIt cls_it = st->m_Classes.find(cls_id); + VERIFY(cls_it != st->m_Classes.end()); + *val->m_Items = cls_it->second; +} + +shared_str CSpawnPoint::SectionToEditor(shared_str nm) +{ + ESceneSpawnTool *st = dynamic_cast(FParentTools); + VERIFY(st); + ESceneSpawnTool::ClassSpawnMapIt cls_it = st->m_Classes.find(m_SpawnData.m_ClassID); + VERIFY(cls_it != st->m_Classes.end()); + for (ESceneSpawnTool::SSVecIt ss_it = cls_it->second.begin(); ss_it != cls_it->second.end(); ++ss_it) + if (nm.equal(ss_it->hint)) + return ss_it->name; + return 0; +} + +shared_str CSpawnPoint::EditorToSection(shared_str nm) +{ + ESceneSpawnTool *st = dynamic_cast(FParentTools); + VERIFY(st); + ESceneSpawnTool::ClassSpawnMapIt cls_it = st->m_Classes.find(m_SpawnData.m_ClassID); + VERIFY(cls_it != st->m_Classes.end()); + for (ESceneSpawnTool::SSVecIt ss_it = cls_it->second.begin(); ss_it != cls_it->second.end(); ++ss_it) + if (nm.equal(ss_it->name)) + return ss_it->hint; + return 0; +} + +void CSpawnPoint::OnRPointTypeChange(PropValue *prop) +{ + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CSpawnPoint::OnProfileChange(PropValue *prop) +{ + if (m_SpawnData.m_Profile.size() != 0) + { + shared_str s_name = EditorToSection(m_SpawnData.m_Profile); + VERIFY(s_name.size()); + if (0 != strcmp(m_SpawnData.m_Data->name(), *s_name)) + { + IServerEntity* tmp = xrSE_Factory::create_entity(*s_name); + VERIFY(tmp); + NET_Packet Packet; + tmp->Spawn_Write(Packet, TRUE); + R_ASSERT(m_SpawnData.m_Data->Spawn_Read(Packet)); + m_SpawnData.m_Data->set_editor_flag(IServerEntity::flVisualChange | IServerEntity::flVisualAnimationChange); + xrSE_Factory::destroy_entity(tmp); + } + } + else + { + m_SpawnData.m_Profile = SectionToEditor(m_SpawnData.m_Data->name()); + } +} + +void CSpawnPoint::FillProp(LPCSTR pref, PropItemVec &items) +{ + inherited::FillProp(pref, items); + + if (m_SpawnData.Valid()) + { + shared_str pref1 = PrepareKey(pref, m_SpawnData.m_Data->name()); + m_SpawnData.m_Profile = SectionToEditor(m_SpawnData.m_Data->name()); + ChooseValue *C = PHelper().CreateChoose(items, PrepareKey(pref1.c_str(), "Profile (spawn section)"), &m_SpawnData.m_Profile, smCustom, 0, 0, 1, cfFullExpand); + C->OnChooseFillEvent.bind(this, &CSpawnPoint::OnFillChooseItems); + C->OnChangeEvent.bind(this, &CSpawnPoint::OnProfileChange); + m_SpawnData.FillProp(pref, items); + } + else + { + switch (m_Type) + { + case ptRPoint: + { + if (m_RP_Type == rptItemSpawn && !Core.SocSdk) + { + ChooseValue *C = PHelper().CreateChoose(items, PrepareKey(pref, "Respawn Point\\Profile"), &m_rpProfile, smCustom, 0, 0, 10, cfMultiSelect); + C->OnChooseFillEvent.bind(this, &CSpawnPoint::OnFillRespawnItemProfile); + } + else + PHelper().CreateU8(items, PrepareKey(pref, "Respawn Point\\Team"), &m_RP_TeamID, 0, MAX_TEAM - 1); + + Token8Value *TV; + + if (Core.SocSdk) + TV = PHelper().CreateToken8(items, PrepareKey(pref, "Respawn Point\\Spawn Type"), &m_RP_Type, rpoint_type_soc); + else + TV = PHelper().CreateToken8(items, PrepareKey(pref, "Respawn Point\\Spawn Type"), &m_RP_Type, rpoint_type); + + TV->OnChangeEvent.bind(this, &CSpawnPoint::OnRPointTypeChange); + + m_GameType.FillProp(pref, items); + } + break; + case ptEnvMod: + { + PHelper().CreateFloat(items, PrepareKey(pref, "Environment Modificator\\Radius"), &m_EM_Radius, EPS_L, 10000.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Environment Modificator\\Power"), &m_EM_Power, EPS, 1000.f); + + Flag16Value *FV = NULL; + + FV = PHelper().CreateFlag16(items, PrepareKey(pref, "Environment Modificator\\View Distance"), &m_EM_Flags, eViewDist); + FV->OnChangeEvent.bind(this, &CSpawnPoint::OnEnvModFlagChange); + if (m_EM_Flags.test(eViewDist)) + PHelper().CreateFloat(items, PrepareKey(pref, "Environment Modificator\\View Distance\\ "), &m_EM_ViewDist, EPS_L, 10000.f); + + FV = PHelper().CreateFlag16(items, PrepareKey(pref, "Environment Modificator\\Fog Color"), &m_EM_Flags, eFogColor); + FV->OnChangeEvent.bind(this, &CSpawnPoint::OnEnvModFlagChange); + if (m_EM_Flags.test(eFogColor)) + PHelper().CreateColor(items, PrepareKey(pref, "Environment Modificator\\Fog Color\\ "), &m_EM_FogColor); + + FV = PHelper().CreateFlag16(items, PrepareKey(pref, "Environment Modificator\\Fog Density"), &m_EM_Flags, eFogDensity); + FV->OnChangeEvent.bind(this, &CSpawnPoint::OnEnvModFlagChange); + if (m_EM_Flags.test(eFogDensity)) + PHelper().CreateFloat(items, PrepareKey(pref, "Environment Modificator\\Fog Density\\ "), &m_EM_FogDensity, 0.f, 10000.f); + + FV = PHelper().CreateFlag16(items, PrepareKey(pref, "Environment Modificator\\Ambient Color"), &m_EM_Flags, eAmbientColor); + FV->OnChangeEvent.bind(this, &CSpawnPoint::OnEnvModFlagChange); + if (m_EM_Flags.test(eAmbientColor)) + PHelper().CreateColor(items, PrepareKey(pref, "Environment Modificator\\Ambient Color\\ "), &m_EM_AmbientColor); + + FV = PHelper().CreateFlag16(items, PrepareKey(pref, "Environment Modificator\\Sky Color"), &m_EM_Flags, eSkyColor); + FV->OnChangeEvent.bind(this, &CSpawnPoint::OnEnvModFlagChange); + if (m_EM_Flags.test(eSkyColor)) + PHelper().CreateColor(items, PrepareKey(pref, "Environment Modificator\\Sky Color\\ "), &m_EM_SkyColor); + + FV = PHelper().CreateFlag16(items, PrepareKey(pref, "Environment Modificator\\Hemi Color"), &m_EM_Flags, eHemiColor); + FV->OnChangeEvent.bind(this, &CSpawnPoint::OnEnvModFlagChange); + if (m_EM_Flags.test(eHemiColor)) + PHelper().CreateColor(items, PrepareKey(pref, "Environment Modificator\\Hemi Color\\ "), &m_EM_HemiColor); + } + break; + default: + THROW; + } + } +} + +void CSpawnPoint::OnEnvModFlagChange(PropValue *prop) +{ + LTools->UpdateProperties(FALSE); +} + +bool CSpawnPoint::OnChooseQuery(LPCSTR specific) +{ + return (m_SpawnData.Valid() && (0 == strcmp(m_SpawnData.m_Data->name(), specific))); +} + +void CSpawnPoint::UseSimulatePose() +{ + if (m_physics_shell) + { + Fmatrix m; + UpdateObjectXform(m); + FPosition.set(m.c); + m.getXYZ(FRotation); + UpdateTransform(); + } +} + +void CSpawnPoint::OnUpdateTransform() +{ + inherited::OnUpdateTransform(); +} diff --git a/src/editors/LevelEditor/Entry/Spawn/SpawnPoint.h b/src/editors/LevelEditor/Entry/Spawn/SpawnPoint.h new file mode 100644 index 00000000000..2b271732fb1 --- /dev/null +++ b/src/editors/LevelEditor/Entry/Spawn/SpawnPoint.h @@ -0,0 +1,199 @@ +#pragma once + +#define SPAWNPOINT_VERSION 0x0017 + +// refs +class CSE_Visual; +class CSE_Motion; +class CObjectAnimator; +class IServerEntity; + + + +class CLE_Visual : private pureDrawUI +{ + virtual void OnDrawUI(); + +public: + static bool g_tmp_lock; + CSE_Visual *source; + IRenderVisual *visual; + void OnChangeVisual(); + void StopAllAnimations(); + void PlayAnimation(); + void PlayAnimationFirstFrame(); + void PlayAnimationLastFrame(); + void PauseAnimation(); + +public: + CLE_Visual(CSE_Visual *src); + virtual ~CLE_Visual(); +}; +class CSpawnPoint : public CCustomObject, + public CPhysicsShellHolderEditorBase +{ + typedef CCustomObject inherited; + + friend class SceneBuilder; + +public: + class CLE_Motion + { + public: + CSE_Motion *source; + CObjectAnimator *animator; + void OnChangeMotion(); + void PlayMotion(); + + public: + CLE_Motion(CSE_Motion *src); + virtual ~CLE_Motion(); + }; + struct SSpawnData : public IServerEntityLEOwner + { + CLASS_ID m_ClassID; + shared_str m_Profile; + IServerEntity *m_Data; + CLE_Visual *m_Visual; + Flags8 m_flags; + xr_vector m_VisualHelpers; + + CLE_Motion *m_Motion; + CSpawnPoint *m_owner; + enum + { + eSDTypeRespawn = (1 << 0), + }; + SSpawnData(CSpawnPoint *o) + { + m_ClassID = 0; + m_Data = 0; + m_Visual = 0; + m_Motion = 0; + m_owner = o; + m_flags.zero(); + } + ~SSpawnData() + { + Destroy(); + } + void Create(LPCSTR entity_ref); + void Destroy(); + bool Valid() const { return m_Data; } + + bool LoadStream(IReader &); + void SaveStream(IWriter &); + bool LoadLTX(CInifile &ini, LPCSTR sect_name); + void SaveLTX(CInifile &ini, LPCSTR sect_name); + + bool ExportGame(SExportStreams *F, CSpawnPoint *owner); + + void FillProp(LPCSTR pref, PropItemVec &values); + + void Render(bool bSelected, const Fmatrix &parent, int priority, bool strictB2F); + void OnFrame(); + void OnAnimControlClick(ButtonValue *value, bool &bModif, bool &bSafe); + + virtual void get_bone_xform(LPCSTR name, Fmatrix &xform); + }; + + SSpawnData m_SpawnData; + CCustomObject *m_AttachedObject; + + EPointType m_Type; + shared_str m_rpProfile; + union + { + struct + { + u8 m_RP_TeamID; + u8 m_RP_Type; + GameTypeChooser m_GameType; + }; + struct + { + float m_EM_Radius; + float m_EM_Power; + float m_EM_ViewDist; + u32 m_EM_FogColor; + float m_EM_FogDensity; + u32 m_EM_AmbientColor; + u32 m_EM_SkyColor; + u32 m_EM_HemiColor; + Flags16 m_EM_Flags; + }; + }; + + shared_str SectionToEditor(shared_str); + shared_str EditorToSection(shared_str); + void OnProfileChange(PropValue *prop); + void OnRPointTypeChange(PropValue *prop); + + void OnEnvModFlagChange(PropValue *prop); + void OnFillChooseItems(ChooseValue *); + void OnFillRespawnItemProfile(ChooseValue *); + bool OnAppendObject(CCustomObject *object); + +protected: + virtual void SetPosition(const Fvector &pos); + virtual void SetRotation(const Fvector &rot); + virtual void SetScale(const Fvector &scale); + +protected: + virtual void Move(Fvector &amount); + +public: + CSpawnPoint(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + virtual ~CSpawnPoint(); + virtual bool CanAttach() { return true; } + + bool RefCompare(LPCSTR ref); + virtual LPCSTR RefName(); + + bool CreateSpawnData(LPCSTR entity_ref); + virtual void Render(int priority, bool strictB2F); + + virtual bool RayPick(float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf = NULL); + virtual bool FrustumPick(const CFrustum &frustum); + virtual bool GetBox(Fbox &box); + + virtual void OnFrame(); + + virtual void Select(int flag); + + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual bool ExportGame(SExportStreams *data); + + virtual void FillProp(LPCSTR pref, PropItemVec &values); + + bool AttachObject(CCustomObject *obj); + void DetachObject(); + + virtual bool OnChooseQuery(LPCSTR specific); + virtual void OnSceneRemove(); + void UseSimulatePose(); + + // --#SM+#-- shit + IGameObject* IObject() override { R_ASSERT(false); return nullptr; } + bool IsCollideWithBullets() override { R_ASSERT(false); return false; } + bool IsCollideWithActorCamera() override { R_ASSERT(false); return false; } + +public: + virtual IKinematics *ObjectKinematics() + { + if (!m_SpawnData.m_Visual || !m_SpawnData.m_Visual->visual) + return 0; + return m_SpawnData.m_Visual->visual->dcast_PKinematics(); + } + +private: + virtual void OnUpdateTransform(); + +private: + void RenderSimBox(); +}; diff --git a/src/editors/LevelEditor/Entry/StaticObject/SceneObject.cpp b/src/editors/LevelEditor/Entry/StaticObject/SceneObject.cpp new file mode 100644 index 00000000000..9320a483433 --- /dev/null +++ b/src/editors/LevelEditor/Entry/StaticObject/SceneObject.cpp @@ -0,0 +1,474 @@ +#include "stdafx.h" + +const float BLINK_TIME = 300.f; + +CSceneObject::CSceneObject(LPVOID data, LPCSTR name) : CCustomObject(data, name) +{ + Construct(data); +} + +void CSceneObject::Construct(LPVOID data) +{ + FClassID = OBJCLASS_SCENEOBJECT; + + m_ReferenceName = ""; + m_pReference = 0; + + m_TBBox.invalidate(); + m_iBlinkTime = 0; + m_BlinkSurf = 0; + + m_Flags.zero(); +} + +CSceneObject::~CSceneObject() +{ + for (CSurface *&i : m_Surfaces) + { + i->OnDeviceDestroy(); + xr_delete(i); + } + Lib.RemoveEditObject(m_pReference); +} + +void CSceneObject::EvictObject() +{ + if (m_pReference) + m_pReference->EvictObject(); +} + +void CSceneObject::Select(BOOL flag) +{ + inherited::Select(flag); + if (flag) + Blink(); +} + +int CSceneObject::GetFaceCount() +{ + return m_pReference ? m_pReference->GetFaceCount() : 0; +} + +int CSceneObject::GetSurfFaceCount(const char *surf_name) +{ + return m_pReference ? m_pReference->GetSurfFaceCount(surf_name) : 0; +} + +int CSceneObject::GetVertexCount() +{ + return m_pReference ? m_pReference->GetVertexCount() : 0; +} + +void CSceneObject::OnUpdateTransform() +{ + inherited::OnUpdateTransform(); + // update bounding volume + if (m_pReference) + { + m_TBBox.set(m_pReference->GetBox()); + m_TBBox.xform(_Transform()); + } +} + +bool CSceneObject::GetBox(Fbox &box) +{ + if (!m_pReference) + return false; + box.set(m_TBBox); + return true; +} + +bool CSceneObject::GetUTBox(Fbox &box) +{ + if (!m_pReference) + return false; + box.set(m_pReference->GetBox()); + return true; +} + +bool CSceneObject::IsRender() +{ + if (!m_pReference) + return false; + return inherited::IsRender(); +} + +void CSceneObject::Render(int priority, bool strictB2F) +{ + inherited::Render(priority, strictB2F); + if (!m_pReference) + return; +#ifdef _LEVEL_EDITOR + Scene->SelectLightsForObject(this); +#endif + m_pReference->Render(_Transform(), priority, strictB2F, &m_Surfaces); + if (Selected()) + { + if (1 == priority) + { + if (false == strictB2F) + { + EDevice.SetShader(EDevice.m_WireShader); + RCache.set_xform_world(_Transform()); + u32 clr = 0xFFFFFFFF; + DU_impl.DrawSelectionBoxB(m_pReference->GetBox(), &clr); + } + else + { + RenderBlink(); + } + } + } +} + +void CSceneObject::RenderBlink() +{ + if (m_iBlinkTime > 0) + { + if (m_iBlinkTime > (int)EDevice.dwTimeGlobal) + { + int alpha = iFloor(sqrtf(float(m_iBlinkTime - EDevice.dwTimeGlobal) / BLINK_TIME) * 64); + m_pReference->RenderSelection(_Transform(), 0, m_BlinkSurf, D3DCOLOR_ARGB(alpha, 255, 255, 255)); + UI->RedrawScene(); + } + else + { + m_iBlinkTime = 0; + m_BlinkSurf = 0; + } + } +} + +void CSceneObject::RenderSingle() +{ + if (!m_pReference) + return; + m_pReference->RenderSingle(_Transform()); + RenderBlink(); +} + +void CSceneObject::RenderBones() +{ + if (!m_pReference) + return; + m_pReference->RenderBones(_Transform()); +} + +void CSceneObject::RenderEdge(CEditableMesh *mesh, u32 color) +{ + if (!m_pReference) + return; + if (::Render->occ_visible(m_TBBox)) + m_pReference->RenderEdge(_Transform(), mesh, 0, color); +} + +void CSceneObject::RenderSelection(u32 color) +{ + if (!m_pReference) + return; + m_pReference->RenderSelection(_Transform(), 0, 0, color); +} + +bool CSceneObject::FrustumPick(const CFrustum &frustum) +{ + if (!m_pReference) + return false; + if (::Render->occ_visible(m_TBBox)) + return m_pReference->FrustumPick(frustum, _Transform()); + return false; +} + +bool CSceneObject::SpherePick(const Fvector ¢er, float radius) +{ + if (!m_pReference) + return false; + float fR; + Fvector vC; + m_TBBox.getsphere(vC, fR); + float R = radius + fR; + float dist_sqr = center.distance_to_sqr(vC); + if (dist_sqr < R * R) + return true; + return false; +} + +bool CSceneObject::RayPick(float &dist, const Fvector &S, const Fvector &D, SRayPickInfo *pinf) +{ + if (!m_pReference) + return false; + if (::Render->occ_visible(m_TBBox)) + if (m_pReference->RayPick(dist, S, D, _ITransform(), pinf)) + { + if (pinf) + pinf->s_obj = this; + return true; + } + return false; +} + +void CSceneObject::RayQuery(SPickQuery &pinf) +{ + if (!m_pReference) + return; + m_pReference->RayQuery(_Transform(), _ITransform(), pinf); +} + +void CSceneObject::BoxQuery(SPickQuery &pinf) +{ + if (!m_pReference) + return; + m_pReference->BoxQuery(_Transform(), _ITransform(), pinf); +} + +bool CSceneObject::BoxPick(const Fbox &box, SBoxPickInfoVec &pinf) +{ + if (!m_pReference) + return false; + return m_pReference->BoxPick(this, box, _ITransform(), pinf); +} + +void CSceneObject::GetFullTransformToWorld(Fmatrix &m) +{ + m.set(_Transform()); +} + +void CSceneObject::GetFullTransformToLocal(Fmatrix &m) +{ + m.set(_ITransform()); +} + +CEditableObject *CSceneObject::UpdateReference() +{ + for (CSurface *i : m_Surfaces) + { + i->OnDeviceDestroy(); + xr_delete(i); + } + m_Surfaces.clear(); + Lib.RemoveEditObject(m_pReference); + m_pReference = (m_ReferenceName.size()) ? Lib.CreateEditObject(*m_ReferenceName) : 0; + UpdateTransform(); + if (m_pReference) + { + for (size_t i = 0; i < m_pReference->SurfaceCount(); i++) + { + CSurface *surf = xr_new(); + surf->CopyFrom(m_pReference->Surfaces()[i]); + m_Surfaces.push_back(surf); + if (surf->IsVoid()) + surf->OnDeviceCreate(); + } + } + return m_pReference; +} + +CEditableObject *CSceneObject::SetReference(LPCSTR ref_name) +{ + m_ReferenceName = ref_name; + return UpdateReference(); +} + +void CSceneObject::OnFrame() +{ + inherited::OnFrame(); + if (!m_pReference) + return; + if (m_pReference) + m_pReference->OnFrame(); + if (psDeviceFlags.is(rsStatistic)) + { + if (IsStatic() || IsMUStatic() || Selected()) + { + EDevice.Statistic->dwLevelSelFaceCount += GetFaceCount(); + EDevice.Statistic->dwLevelSelVertexCount += GetVertexCount(); + } + } +} + +void CSceneObject::ReferenceChange(PropValue *sender) +{ + Scene->BeforeObjectChange(this); + UpdateReference(); +} +void CSceneObject::OnChangeShader(PropValue *sender) +{ + OnChangeSurface(sender); + for (CSurface *i : m_Surfaces) + { + i->OnDeviceDestroy(); + } +} +void CSceneObject::OnChangeSurface(PropValue *sender) +{ + m_Flags.set(flUseSurface, 1); +} +bool CSceneObject::AfterEditGameMtl(PropValue *sender, shared_str &str) +{ + return str != "materials\\occ"; +} +void CSceneObject::OnClickClearSurface(ButtonValue *, bool &, bool &) +{ + Scene->UndoSave(); + ClearSurface(); +} +void CSceneObject::FillProp(LPCSTR pref, PropItemVec &items) +{ + static shared_str occ_name = "materials\\occ"; + inherited::FillProp(pref, items); + PropValue *V = PHelper().CreateChoose(items, PrepareKey(pref, "Reference"), &m_ReferenceName, smObject); + V->OnChangeEvent.bind(this, &CSceneObject::ReferenceChange); + if (IsDynamic()) + inherited::AnimationFillProp(pref, items); + SurfaceVec &s_lst = m_Surfaces; + { + shared_str Pref1 = PrepareKey(pref, "Surfaces").c_str(); + for (SurfaceIt s_it = s_lst.begin(); s_it != s_lst.end(); s_it++) + { + shared_str Pref2 = PrepareKey(Pref1.c_str(), (*s_it)->_Name()).c_str(); + { + if ((*s_it)->m_GameMtlName != occ_name) + { + PropValue *V; + V = PHelper().CreateChoose(items, PrepareKey(Pref2.c_str(), "Texture"), &(*s_it)->m_Texture, smTexture); + V->OnChangeEvent.bind(this, &CSceneObject::OnChangeShader); + V = PHelper().CreateChoose(items, PrepareKey(Pref2.c_str(), "Shader"), &(*s_it)->m_ShaderName, smEShader); + V->OnChangeEvent.bind(this, &CSceneObject::OnChangeShader); + V = PHelper().CreateChoose(items, PrepareKey(Pref2.c_str(), "Compile"), &(*s_it)->m_ShaderXRLCName, smCShader); + V->OnChangeEvent.bind(this, &CSceneObject::OnChangeSurface); + auto VA = PHelper().CreateChoose(items, PrepareKey(Pref2.c_str(), "Game Mtl"), &(*s_it)->m_GameMtlName, smGameMaterial); + VA->OnChangeEvent.bind(this, &CSceneObject::OnChangeSurface); + VA->OnAfterEditEvent.bind(this, &CSceneObject::AfterEditGameMtl); + } + } + } + PHelper().CreateButton(items, PrepareKey(Pref1.c_str(), "Action"), "Clear", ButtonValue::flFirstOnly)->OnBtnClickEvent.bind(this, &CSceneObject::OnClickClearSurface); + } +} + +bool CSceneObject::GetSummaryInfo(SSceneSummary *inf) +{ + inherited::GetSummaryInfo(inf); + CEditableObject *E = GetReference(); + R_ASSERT(E); + if (IsStatic() || IsMUStatic()) + { + for (SurfaceIt s_it = E->m_Surfaces.begin(); s_it != E->m_Surfaces.end(); s_it++) + { + float area = 0.f; + float pixel_area = 0.f; + for (EditMeshIt m = E->Meshes().begin(); m != E->Meshes().end(); m++) + { + area += (*m)->CalculateSurfaceArea(*s_it, true); + pixel_area += (*m)->CalculateSurfacePixelArea(*s_it, true); + } + xr_string temp = ChangeFileExt(xr_string(*(*s_it)->m_Texture), ""); + xr_strlwr(temp); + inf->AppendTexture(temp.c_str(), SSceneSummary::sttBase, area, pixel_area, E->m_LibName.c_str()); + } + if (m_Flags.is(CEditableObject::eoUsingLOD)) + { + inf->AppendTexture(E->GetLODTextureName().c_str(), SSceneSummary::sttLOD, 0, 0, "$LOD$"); + inf->lod_objects.insert(E->m_LibName.c_str()); + inf->object_lod_ref_cnt++; + } + if (m_Flags.is(CEditableObject::eoMultipleUsage)) + { + inf->mu_objects.insert(E->m_LibName.c_str()); + inf->object_mu_ref_cnt++; + } + + inf->face_cnt += E->GetFaceCount(); + inf->vert_cnt += E->GetVertexCount(); + } + if (m_Flags.is(CEditableObject::eoHOM)) + { + inf->hom_face_cnt += E->GetFaceCount(); + inf->hom_vert_cnt += E->GetVertexCount(); + } + if (m_Flags.is(CEditableObject::eoSoundOccluder)) + { + inf->snd_occ_face_cnt += E->GetFaceCount(); + inf->snd_occ_vert_cnt += E->GetVertexCount(); + } + inf->AppendObject(E->GetName()); + return true; +} + +extern xr_token ECORE_API eo_type_token[]; + +void CSceneObject::OnShowHint(AStringVec &dest) +{ + inherited::OnShowHint(dest); + dest.push_back(xr_string("Reference: ") + *m_ReferenceName); + dest.push_back(xr_string("-------")); + float dist = UI->ZFar(); + SRayPickInfo pinf; + if (m_pReference->RayPick(dist, UI->m_CurrentRStart, UI->m_CurrentRDir, _ITransform(), &pinf)) + { + dest.push_back(xr_string("Object Type: ") + get_token_name(eo_type_token, pinf.e_obj->m_objectFlags.flags)); + R_ASSERT(pinf.e_mesh); + CSurface *surf = pinf.e_mesh->GetSurfaceByFaceID(pinf.inf.id); + dest.push_back(xr_string("Surface: ") + xr_string(surf->_Name())); + dest.push_back(xr_string("2 Sided: ") + xr_string(surf->m_Flags.is(CSurface::sf2Sided) ? "on" : "off")); + if (pinf.e_obj->m_objectFlags.is(CEditableObject::eoSoundOccluder)) + { + dest.push_back(xr_string("Game Mtl: ") + xr_string(surf->_GameMtlName())); + int gm_id = surf->_GameMtl(); + if (gm_id != GAMEMTL_NONE_ID) + { + SGameMtl *mtl = GMLib.GetMaterialByID(gm_id); + if (mtl) + dest.push_back(make_string("Occlusion Factor: %3.2f", mtl->fSndOcclusionFactor).c_str()); + } + } + else if (pinf.e_obj->m_objectFlags.is(CEditableObject::eoHOM)) + { + } + else + { + dest.push_back(xr_string("Texture: ") + xr_string(surf->_Texture())); + dest.push_back(xr_string("Shader: ") + xr_string(surf->_ShaderName())); + dest.push_back(xr_string("LC Shader: ") + xr_string(surf->_ShaderXRLCName())); + dest.push_back(xr_string("Game Mtl: ") + xr_string(surf->_GameMtlName())); + } + } +} +//---------------------------------------------------- + +void CSceneObject::Blink(CSurface *surf) +{ + m_BlinkSurf = surf; + m_iBlinkTime = static_cast(EDevice.dwTimeGlobal + BLINK_TIME + EDevice.dwTimeDelta); +} +//---------------------------------------------------- + +bool CSceneObject::Validate(bool bMsg) +{ + CEditableObject *E = GetReference(); + R_ASSERT(E); + return E->Validate(); +} +//---------------------------------------------------- + +void CSceneObject::ClearSurface() +{ + for (CSurface *i : m_Surfaces) + { + i->OnDeviceDestroy(); + xr_delete(i); + } + m_Surfaces.clear(); + if (m_pReference) + { + for (size_t i = 0; i < m_pReference->SurfaceCount(); i++) + { + CSurface *surf = xr_new(); + surf->CopyFrom(m_pReference->Surfaces()[i]); + m_Surfaces.push_back(surf); + if (surf->IsVoid()) + surf->OnDeviceCreate(); + } + } + m_Flags.set(flUseSurface, 0); + Tools->UpdateProperties(); +} diff --git a/src/editors/LevelEditor/Entry/StaticObject/SceneObject.h b/src/editors/LevelEditor/Entry/StaticObject/SceneObject.h new file mode 100644 index 00000000000..7aec2ffdd20 --- /dev/null +++ b/src/editors/LevelEditor/Entry/StaticObject/SceneObject.h @@ -0,0 +1,119 @@ +#pragma once + +class CSceneObject : public CCustomObject +{ + shared_str m_ReferenceName; + CEditableObject *m_pReference; + void ReferenceChange(PropValue *sender); + void OnChangeShader(PropValue *sender); + void OnChangeSurface(PropValue *sender); + bool AfterEditGameMtl(PropValue *sender, shared_str &str); + void OnClickClearSurface(ButtonValue *, bool &, bool &); + +public: + SurfaceVec m_Surfaces; + enum + { + // flDynamic = (1<<0), + flUseSurface = (1 << 0), + flFORCE32 = u32(-1) + }; + +private: + Fbox m_TBBox; + // options + Flags32 m_Flags; + +public: + virtual void SetScale(const Fvector &scale) + { + if (m_pReference && m_pReference->IsDynamic()) + { + ELog.Msg(mtError, "Dynamic object %s - can't scale.", GetName()); + } + else + { + FScale.set(scale); + UpdateTransform(); + } + } + +protected: + typedef CCustomObject inherited; + int m_iBlinkTime; + CSurface *m_BlinkSurf; + void RenderBlink(); + +public: + // constructor/destructor methods + CSceneObject(LPVOID data, LPCSTR name); + virtual ~CSceneObject(); + + virtual void Select(BOOL flag); + void Construct(LPVOID data); + + // get object properties methods + IC bool RefCompare(CEditableObject *to) { return m_pReference ? !!(m_pReference == to) : false; } + IC bool RefCompare(LPCSTR ref) { return ref && m_pReference ? (strcmp(ref, m_pReference->GetName()) == 0) : false; } + IC CEditableObject *GetReference() { return m_pReference; } + CEditableObject *SetReference(LPCSTR ref_name); + CEditableObject *UpdateReference(); + IC EditMeshVec *Meshes() { return m_pReference ? &m_pReference->Meshes() : 0; } + virtual LPCSTR RefName() { return m_pReference ? m_pReference->GetName() : 0; } + virtual bool CanAttach() { return true; } + + // statistics methods + IC bool IsDynamic() { return (m_pReference ? m_pReference->IsDynamic() : false); } + IC bool IsStatic() { return (m_pReference ? m_pReference->IsStatic() : false); } + IC bool IsMUStatic() { return (m_pReference ? m_pReference->IsMUStatic() : false); } + int GetFaceCount(); + int GetVertexCount(); + int GetSurfFaceCount(const char *surf_name); + + // render methods + virtual bool IsRender(); + virtual void Render(int priority, bool strictB2F); + void RenderSelection(u32 color = 0x80E64646); + void RenderEdge(CEditableMesh *m = 0, u32 color = 0xFFC0C0C0); + void RenderBones(); + void RenderSingle(); + + // update methods + virtual void OnFrame(); + virtual void OnUpdateTransform(); + + // misc + void EvictObject(); + + // pick methods + bool BoxPick(const Fbox &box, SBoxPickInfoVec &pinf); + virtual bool RayPick(float &dist, const Fvector &S, const Fvector &D, SRayPickInfo *pinf = 0); + virtual void RayQuery(SPickQuery &pinf); + virtual void BoxQuery(SPickQuery &pinf); + virtual bool FrustumPick(const CFrustum &frustum); + virtual bool SpherePick(const Fvector ¢er, float radius); + + // get orintation/bounding volume methods + virtual bool GetBox(Fbox &box); + virtual bool GetUTBox(Fbox &box); + void GetFullTransformToWorld(Fmatrix &m); + void GetFullTransformToLocal(Fmatrix &m); + + // editor integration + virtual void FillProp(LPCSTR pref, PropItemVec &values); + virtual bool GetSummaryInfo(SSceneSummary *inf); + + // load/save methods + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual void OnShowHint(AStringVec &dest); + + void Blink(CSurface *surf = 0); + + virtual bool Validate(bool bMsg); + + void ClearSurface(); +}; diff --git a/src/editors/LevelEditor/Entry/StaticObject/SceneObjectIO.cpp b/src/editors/LevelEditor/Entry/StaticObject/SceneObjectIO.cpp new file mode 100644 index 00000000000..602ae121362 --- /dev/null +++ b/src/editors/LevelEditor/Entry/StaticObject/SceneObjectIO.cpp @@ -0,0 +1,300 @@ +#include "stdafx.h" + +#define SCENEOBJ_CURRENT_VERSION 0x0012 + +#define SCENEOBJ_CHUNK_VERSION 0x0900 +#define SCENEOBJ_CHUNK_REFERENCE 0x0902 +#define SCENEOBJ_CHUNK_PLACEMENT 0x0904 +#define SCENEOBJ_CHUNK_FLAGS 0x0905 +#define SCENEOBJ_CHUNK_SURFACE 0x0906 + +bool CSceneObject::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + bool bRes = true; + + do + { + u32 version = ini.r_u32(sect_name, "version"); + + CCustomObject::LoadLTX(ini, sect_name); + + xr_string ref_name = ini.r_string(sect_name, "reference_name"); + + if (!SetReference(ref_name.c_str())) + { + ELog.Msg(mtError, "CSceneObject: '%s' not found in library", ref_name.c_str()); + bRes = false; + int mr = mrNone; + + xr_string _new_name; + bool b_found = Scene->GetSubstObjectName(ref_name.c_str(), _new_name); + if (b_found) + { + xr_string _message; + _message = "Object [" + ref_name + "] not found. Relace it with [" + _new_name + "] or select other from library?"; + mr = ELog.DlgMsg(mtConfirmation, mbYes | mbNo, _message.c_str()); + if (mrYes == mr) + { + bRes = SetReference(_new_name.c_str()); + } + } + if (!bRes) + { + + /* if ( (mr==mrNone||mr==mrYes) && TfrmChoseItem::SelectItem(smObject,new_val,1)) + { + bRes = SetReference(new_val); + if(bRes) + Scene->RegisterSubstObjectName(ref_name.c_str(), new_val); + }*/ + } + + Scene->Modified(); + } + // if(!CheckVersion()) + // ELog.Msg( mtError, "CSceneObject: '%s' different file version!", ref_name.c_str() ); + + m_Flags.assign(ini.r_u32(sect_name, "flags")); + if (m_Flags.test(flUseSurface)) + { + SIniFileStream ini_stream; + ini_stream.ini = &ini; + ini_stream.sect = sect_name; + ini_stream.move_begin(); + if (ini.line_exist(sect_name, ini_stream.gen_name())) + { + ini_stream.move_begin(); + u32 Size; + ini_stream.r_u32(Size); + for (u32 i = 0; i < Size; i++) + { + xr_string Name; + ini_stream.r_string(Name); + CSurface *Surf = nullptr; + for (SurfaceIt sf_it = m_Surfaces.begin(); sf_it != m_Surfaces.end(); ++sf_it) + { + if ((*sf_it)->m_Name == Name.c_str()) + { + Surf = *sf_it; + break; + } + } + + if (Surf) + { + if (!Surf->IsVoid()) + Surf->OnDeviceDestroy(); + } + { + ini_stream.r_string(Name); + if (Surf) + Surf->SetShader(Name.c_str()); + ini_stream.r_string(Name); + if (Surf) + Surf->SetShaderXRLC(Name.c_str()); + ini_stream.r_string(Name); + if (Surf) + Surf->SetGameMtl(Name.c_str()); + ini_stream.r_string(Name); + if (Surf) + Surf->SetTexture(Name.c_str()); + ini_stream.r_string(Name); + if (Surf) + Surf->SetVMap(Name.c_str()); + } + + if (Surf) + Surf->OnDeviceCreate(); + } + } + } + + if (!bRes) + break; + } while (0); + + return bRes; +} + +void CSceneObject::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + CCustomObject::SaveLTX(ini, sect_name); + + ini.w_u32(sect_name, "version", SCENEOBJ_CURRENT_VERSION); + + // reference object version + R_ASSERT(m_pReference); + ini.w_string(sect_name, "reference_name", m_ReferenceName.c_str()); + + ini.w_u32(sect_name, "flags", m_Flags.get()); + if (m_Flags.test(flUseSurface)) + { + SIniFileStream ini_stream; + ini_stream.ini = &ini; + ini_stream.sect = sect_name; + ini_stream.move_begin(); + ini_stream.w_u32(m_Surfaces.size()); + for (SurfaceIt sf_it = m_Surfaces.begin(); sf_it != m_Surfaces.end(); ++sf_it) + { + ini_stream.w_stringZ((*sf_it)->_Name()); + ini_stream.w_stringZ((*sf_it)->_ShaderName()); + ini_stream.w_stringZ((*sf_it)->_ShaderXRLCName()); + ini_stream.w_stringZ((*sf_it)->_GameMtlName()); + ini_stream.w_stringZ((*sf_it)->_Texture()); + ini_stream.w_stringZ((*sf_it)->_VMap()); + } + } +} + +bool CSceneObject::LoadStream(IReader &F) +{ + bool bRes = true; + + do + { + u16 version = 0; + string1024 buf; + R_ASSERT(F.r_chunk(SCENEOBJ_CHUNK_VERSION, &version)); + + if (version == 0x0010) + { + R_ASSERT(F.find_chunk(SCENEOBJ_CHUNK_PLACEMENT)); + F.r_fvector3(FPosition); + F.r_fvector3(FRotation); + F.r_fvector3(FScale); + } + + CCustomObject::LoadStream(F); + + R_ASSERT(F.find_chunk(SCENEOBJ_CHUNK_REFERENCE)); + if (version <= 0x0011) + { + F.r_u32(); + F.r_u32(); + } + F.r_stringZ(buf, sizeof(buf)); + + if (!SetReference(buf)) + { + ELog.Msg(mtError, "CSceneObject: '%s' not found in library", buf); + bRes = false; + int mr = mrNone; + + xr_string _new_name; + bool b_found = Scene->GetSubstObjectName(buf, _new_name); + if (b_found) + { + xr_string _message; + _message = "Object [" + xr_string(buf) + "] not found. Relace it with [" + _new_name + "] or select other from library?"; + mr = ELog.DlgMsg(mtConfirmation, mbYes | mbNo, _message.c_str()); + if (mrYes == mr) + { + bRes = SetReference(_new_name.c_str()); + } + } + + Scene->Modified(); + } + + // flags + if (F.find_chunk(SCENEOBJ_CHUNK_FLAGS)) + { + m_Flags.assign(F.r_u32()); + } + if (m_Flags.test(flUseSurface)) + { + if (F.find_chunk(SCENEOBJ_CHUNK_SURFACE)) + { + + u32 Size = F.r_u32(); + for (u32 i = 0; i < Size; i++) + { + xr_string Name; + F.r_stringZ(Name); + CSurface *Surf = nullptr; + for (SurfaceIt sf_it = m_Surfaces.begin(); sf_it != m_Surfaces.end(); ++sf_it) + { + if ((*sf_it)->m_Name == Name.c_str()) + { + Surf = *sf_it; + break; + } + } + if (Surf) + Surf->OnDeviceDestroy(); + { + F.r_stringZ(Name); + if (Surf) + Surf->SetShader(Name.c_str()); + F.r_stringZ(Name); + if (Surf) + Surf->SetShaderXRLC(Name.c_str()); + F.r_stringZ(Name); + if (Surf) + Surf->SetGameMtl(Name.c_str()); + F.r_stringZ(Name); + if (Surf) + Surf->SetTexture(Name.c_str()); + F.r_stringZ(Name); + if (Surf) + Surf->SetVMap(Name.c_str()); + } + if (Surf) + Surf->OnDeviceCreate(); + } + } + } + if (!bRes) + break; + } while (0); + + return bRes; +} + +void CSceneObject::SaveStream(IWriter &F) +{ + CCustomObject::SaveStream(F); + F.open_chunk(SCENEOBJ_CHUNK_VERSION); + + if (Core.SocSdk) + F.w_u16(SCENEOBJ_CURRENT_VERSION - 1); + else + F.w_u16(SCENEOBJ_CURRENT_VERSION); + + F.close_chunk(); + + // reference object version + F.open_chunk(SCENEOBJ_CHUNK_REFERENCE); + R_ASSERT2(m_pReference, "Empty SceneObject REFS"); + + if (Core.SocSdk) + { + F.w_s32(m_pReference->Version()); + F.w_s32(0); // reserved + } + + F.w_stringZ(m_ReferenceName); + F.close_chunk(); + + F.open_chunk(SCENEOBJ_CHUNK_FLAGS); + F.w_u32(m_Flags.flags); + F.close_chunk(); + + if (m_Flags.test(flUseSurface) && !Core.SocSdk) + { + F.open_chunk(SCENEOBJ_CHUNK_FLAGS); + F.w_u32(m_Surfaces.size()); + + for (SurfaceIt sf_it = m_Surfaces.begin(); sf_it != m_Surfaces.end(); ++sf_it) + { + F.w_stringZ((*sf_it)->_Name()); + F.w_stringZ((*sf_it)->_ShaderName()); + F.w_stringZ((*sf_it)->_ShaderXRLCName()); + F.w_stringZ((*sf_it)->_GameMtlName()); + F.w_stringZ((*sf_it)->_Texture()); + F.w_stringZ((*sf_it)->_VMap()); + } + + F.close_chunk(); + } +} diff --git a/src/editors/LevelEditor/Entry/WayPoint/WayPoint.cpp b/src/editors/LevelEditor/Entry/WayPoint/WayPoint.cpp new file mode 100644 index 00000000000..8f839c9d6e7 --- /dev/null +++ b/src/editors/LevelEditor/Entry/WayPoint/WayPoint.cpp @@ -0,0 +1,957 @@ +#include "stdafx.h" +#include + +#define WAYPOINT_SIZE 1.5f +#define WAYPOINT_RADIUS WAYPOINT_SIZE * .5f + +bool IsPointMode() +{ + return LTools->GetSubTarget() == estWayModePoint; +} + +//------------------------------------------------------------------------------ +// Way Point +//------------------------------------------------------------------------------ +CWayPoint::CWayPoint(LPCSTR name) +{ + m_Name = name; + m_vPosition.set(0, 0, 0); + m_Flags.zero(); + m_bSelected = false; +} + +CWayPoint::~CWayPoint() +{ + for (WPLIt it = m_Links.begin(); it != m_Links.end(); it++) + xr_delete(*it); + m_Links.clear(); +} + +void CWayPoint::GetBox(Fbox &bb) +{ + bb.set(m_vPosition, m_vPosition); + bb.vMax.y += WAYPOINT_SIZE; + bb.vMax.x += WAYPOINT_RADIUS; + bb.vMax.z += WAYPOINT_RADIUS; + bb.vMin.x -= WAYPOINT_RADIUS; + bb.vMin.z -= WAYPOINT_RADIUS; +} +void CWayPoint::Render(LPCSTR parent_name, bool bParentSelect) +{ + Fvector pos; + pos.set(m_vPosition.x, m_vPosition.y + WAYPOINT_SIZE * 0.85f, m_vPosition.z); + DU_impl.DrawCross(pos, WAYPOINT_RADIUS, WAYPOINT_SIZE * 0.85f, WAYPOINT_RADIUS, WAYPOINT_RADIUS, WAYPOINT_SIZE * 0.15f, WAYPOINT_RADIUS, 0x0000ff00); + // draw links + Fvector p1; + p1.set(m_vPosition.x, m_vPosition.y + WAYPOINT_SIZE * 0.85f, m_vPosition.z); + + if (bParentSelect) + { + u32 c = (m_bSelected) ? 0xFFFFFFFF : 0xFFA0A0A0; + u32 s = 0xFF000000; + + xr_string hint = xr_string(" ") + parent_name; + hint += " ["; + hint += *m_Name; + hint += "]"; + Fvector p2; + for (WPLIt it = m_Links.begin(); it != m_Links.end(); it++) + { + SWPLink *O = (SWPLink *)(*it); + p2.set(O->way_point->m_vPosition.x, O->way_point->m_vPosition.y + WAYPOINT_SIZE * 0.85f, O->way_point->m_vPosition.z); + Fvector xx; + xx.sub(p2, p1); + xx.mul(0.95f); + xx.add(p1); + DU_impl.OutText(xx, make_string("P: %1.2f", O->probability).c_str(), c, s); + } + DU_impl.OutText(m_vPosition, hint.c_str(), c, s); + } + + Fvector p2; + u32 l = 0xff606000; + if (bParentSelect) + l = m_bSelected ? 0xffffff00 : 0xff909000; + for (WPLIt it = m_Links.begin(); it != m_Links.end(); it++) + { + SWPLink *O = (SWPLink *)(*it); + p2.set(O->way_point->m_vPosition.x, O->way_point->m_vPosition.y + WAYPOINT_SIZE * 0.85f, O->way_point->m_vPosition.z); + DU_impl.DrawLink(p1, p2, 0.25f, l); + } + if (bParentSelect && m_bSelected) + { + Fbox bb; + GetBox(bb); + u32 clr = 0xffffffff; + DU_impl.DrawSelectionBoxB(bb, &clr); + } +} +bool CWayPoint::RayPick(float &distance, const Fvector &S, const Fvector &D) +{ + Fvector ray2; + ray2.sub(m_vPosition, S); + ray2.y += WAYPOINT_RADIUS; + + float d = ray2.dotproduct(D); + if (d > 0) + { + float d2 = ray2.magnitude(); + if (((d2 * d2 - d * d) < (WAYPOINT_RADIUS * WAYPOINT_RADIUS)) && (d > WAYPOINT_RADIUS)) + { + if (d < distance) + { + distance = d; + return true; + } + } + } + return false; +} +bool CWayPoint::FrustumPick(const CFrustum &frustum) +{ + Fvector P = m_vPosition; + P.y += WAYPOINT_RADIUS; + return (frustum.testSphere_dirty(P, WAYPOINT_RADIUS)) ? true : false; +} +bool CWayPoint::FrustumSelect(int flag, const CFrustum &frustum) +{ + if (FrustumPick(frustum)) + { + Select(flag); + return true; + } + return false; +} +void CWayPoint::Select(int flag) +{ + m_bSelected = (flag == -1) ? (m_bSelected ? false : true) : flag; + UI->RedrawScene(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} +WPLIt CWayPoint::FindLink(CWayPoint *P) +{ + for (WPLIt it = m_Links.begin(); it != m_Links.end(); it++) + if ((*it)->way_point == P) + return it; + return m_Links.end(); +} +void CWayPoint::InvertLink(CWayPoint *P) +{ + WPLIt A = FindLink(P); + WPLIt B = P->FindLink(this); + bool a = (A != m_Links.end()), b = (B != P->m_Links.end()); + float p_a; + float p_b; + if (a) + { + p_a = (*A)->probability; + xr_delete(*A); + m_Links.erase(A); + } + if (b) + { + p_b = (*B)->probability; + xr_delete(*B); + P->m_Links.erase(B); + } + if (a) + { + P->CreateLink(this, p_a); + } + if (b) + { + CreateLink(P, p_b); + } +} +void CWayPoint::Convert1Link(CWayPoint *P) +{ + WPLIt A = FindLink(P); + WPLIt B = P->FindLink(this); + bool a = (A != m_Links.end()), b = (B != P->m_Links.end()); + float p_a = 1.f; + float p_b = 1.f; + if ((a && !b) || (!a && b) || (!a && !b)) + return; + if (a) + { + p_a = (*A)->probability; + xr_delete(*A); + m_Links.erase(A); + } + + if (b) + { + // p_b = (*B)->probability; + xr_delete(*B); + P->m_Links.erase(B); + } + + CreateLink(P, p_a); +} +void CWayPoint::Convert2Link(CWayPoint *P) +{ + WPLIt A = FindLink(P); + WPLIt B = P->FindLink(this); + bool a = (A != m_Links.end()), b = (B != P->m_Links.end()); + float p_a = 1.f; + float p_b = 1.f; + if ((a && b) || (!a && !b)) + return; + if (a) + { + p_a = (*A)->probability; + xr_delete(*A); + m_Links.erase(A); + } + if (b) + { + p_b = (*B)->probability; + xr_delete(*B); + P->m_Links.erase(B); + } + P->CreateLink(this, p_b); + CreateLink(P, p_a); +} +void CWayPoint::CreateLink(CWayPoint *P, float pb) +{ + if (P != this) + m_Links.push_back(xr_new(P, pb)); +} +bool CWayPoint::AppendLink(CWayPoint *P, float pb) +{ + if (FindLink(P) == m_Links.end()) + { + CreateLink(P, pb); + return true; + } + return false; +} +bool CWayPoint::DeleteLink(CWayPoint *P) +{ + WPLIt it = FindLink(P); + if (it != m_Links.end()) + { + xr_delete(*it); + m_Links.erase(it); + UI->RedrawScene(); + return true; + } + return false; +} +bool CWayPoint::AddSingleLink(CWayPoint *P) +{ + UI->RedrawScene(); + return AppendLink(P, 1.f); +} +bool CWayPoint::AddDoubleLink(CWayPoint *P) +{ + UI->RedrawScene(); + bool bRes = AppendLink(P, 1.f); + bRes |= P->AppendLink(this, 1.f); + return bRes; +} +bool CWayPoint::RemoveLink(CWayPoint *P) +{ + if (DeleteLink(P)) + { + P->DeleteLink(this); + return true; + } + return false; +} +//------------------------------------------------------------------------------ +// Way Object +//------------------------------------------------------------------------------ +CWayObject::CWayObject(LPVOID data, LPCSTR name) : CCustomObject(data, name) +{ + Construct(data); +} + +void CWayObject::Construct(LPVOID data) +{ + FClassID = OBJCLASS_WAY; + m_Type = wtPatrolPath; + AppendWayPoint(); +} + +CWayObject::~CWayObject() +{ + Clear(); +} + +void CWayObject::Clear() +{ + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + xr_delete(*it); +} + +void CWayObject::InvertLink() +{ + WPVec objects; + if (GetSelectedPoints(objects)) + { + WPIt _A0 = objects.begin(); + WPIt _A1 = objects.end(); + _A1--; + WPIt _B1 = objects.end(); + for (WPIt _A = _A0; _A != _A1; _A++) + { + CWayPoint *A = (CWayPoint *)(*_A); + WPIt _B = _A; + _B++; + for (; _B != _B1; _B++) + { + CWayPoint *B = (CWayPoint *)(*_B); + A->InvertLink(B); + } + } + } +} + +void CWayObject::Convert1Link() +{ + WPVec objects; + if (GetSelectedPoints(objects)) + { + WPIt _A0 = objects.begin(); + WPIt _A1 = objects.end(); + _A1--; + WPIt _B1 = objects.end(); + for (WPIt _A = _A0; _A != _A1; _A++) + { + CWayPoint *A = (CWayPoint *)(*_A); + WPIt _B = _A; + _B++; + for (; _B != _B1; _B++) + { + CWayPoint *B = (CWayPoint *)(*_B); + A->Convert1Link(B); + } + } + } +} + +void CWayObject::Convert2Link() +{ + WPVec objects; + if (GetSelectedPoints(objects)) + { + WPIt _A0 = objects.begin(); + WPIt _A1 = objects.end(); + _A1--; + WPIt _B1 = objects.end(); + for (WPIt _A = _A0; _A != _A1; _A++) + { + CWayPoint *A = (CWayPoint *)(*_A); + WPIt _B = _A; + _B++; + for (; _B != _B1; _B++) + { + CWayPoint *B = (CWayPoint *)(*_B); + A->Convert2Link(B); + } + } + } +} + +bool CWayObject::Add1Link() +{ + bool bRes = false; + // RemoveLink(); + WPVec objects; + if (GetSelectedPoints(objects)) + { + WPIt _A0 = objects.begin(); + WPIt _A1 = objects.end(); + _A1--; + WPIt _B1 = objects.end(); + for (WPIt _A = _A0; _A != _A1; _A++) + { + CWayPoint *A = (CWayPoint *)(*_A); + WPIt _B = _A; + _B++; + for (; _B != _B1; _B++) + { + CWayPoint *B = (CWayPoint *)(*_B); + bRes |= A->AddSingleLink(B); + A->InvertLink(B); + } + } + } + return bRes; +} + +bool CWayObject::Add2Link() +{ + bool bRes = false; + // RemoveLink(); + WPVec objects; + if (GetSelectedPoints(objects)) + { + WPIt _A0 = objects.begin(); + WPIt _A1 = objects.end(); + _A1--; + WPIt _B1 = objects.end(); + for (WPIt _A = _A0; _A != _A1; _A++) + { + CWayPoint *A = (CWayPoint *)(*_A); + WPIt _B = _A; + _B++; + for (; _B != _B1; _B++) + { + CWayPoint *B = (CWayPoint *)(*_B); + bRes |= A->AddDoubleLink(B); + } + } + } + return bRes; +} + +void CWayObject::RemoveLink() +{ + WPVec objects; + if (GetSelectedPoints(objects)) + { + WPIt _A0 = objects.begin(); + WPIt _A1 = objects.end(); + WPIt _B1 = objects.end(); + for (WPIt _A = _A0; _A != _A1; _A++) + { + CWayPoint *A = (CWayPoint *)(*_A); + WPIt _B = _A0; + for (; _B != _B1; _B++) + { + CWayPoint *B = (CWayPoint *)(*_B); + A->RemoveLink(B); + } + } + } +} + +void CWayObject::RemoveSelectedPoints() +{ + for (WPIt f_it = m_WayPoints.begin(); f_it != m_WayPoints.end(); f_it++) + { + if ((*f_it)->m_bSelected) + { + for (WPIt l_it = m_WayPoints.begin(); l_it != m_WayPoints.end(); l_it++) + { + if (l_it == f_it) + continue; + (*l_it)->DeleteLink(*f_it); + } + } + } + for (int i = 0; i < (int)m_WayPoints.size(); i++) + if (m_WayPoints[i]->m_bSelected) + { + WPIt it = m_WayPoints.begin() + i; + xr_delete(*it); + m_WayPoints.erase(it); + i--; + } +} + +int CWayObject::GetSelectedPoints(WPVec &lst) +{ + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + if ((*it)->m_bSelected) + lst.push_back(*it); + return lst.size(); +} + +CWayPoint *CWayObject::GetFirstSelected() +{ + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + if ((*it)->m_bSelected) + return *it; + return 0; +} + +CWayPoint *CWayObject::AppendWayPoint() +{ + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + (*it)->Select(0); + string_path buffer; + { + const char *pref = "wp"; + for (int i = 0; true; i++) + { + bool result; + xr_string temp; + if (i == 0) + { + temp = pref; + } + else + { + temp = make_string("%s_%02d", pref, i - 1).c_str(); + } + FindWPByName(temp.c_str(), result); + if (!result) + { + xr_strcpy(buffer, 256, temp.c_str()); + break; + } + } + } + m_WayPoints.push_back(xr_new(buffer)); + m_WayPoints.back()->m_bSelected = true; + return m_WayPoints.back(); +} + +void CWayObject::Select(int flag) +{ + if (IsPointMode()) + { + if (Selected()) + { + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + (*it)->Select(flag); + } + } + else + { + inherited::Select(flag); + } +} + +bool CWayObject::RaySelect(int flag, const Fvector &start, const Fvector &dir, bool bRayTest) +{ + if (IsPointMode()) + { + float dist = UI->ZFar(); + CWayPoint *nearest = 0; + dist = UI->ZFar(); + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + if ((*it)->RayPick(dist, start, dir)) + nearest = *it; + if (nearest != 0) + { + nearest->Select(flag); + return true; + } + } + else + return inherited::RaySelect(flag, start, dir, bRayTest); + return false; +} + +bool CWayObject::FrustumSelect(int flag, const CFrustum &frustum) +{ + if (IsPointMode()) + { + if (Selected()) + { + bool bRes = false; + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + bRes |= (*it)->FrustumSelect(flag, frustum); + return true; + } + return false; + } + else + return inherited::FrustumSelect(flag, frustum); +} + +bool CWayObject::GetBox(Fbox &box) +{ + box.invalidate(); + for (WPVec::const_iterator it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + box.modify((*it)->m_vPosition); + + box.vMax.x += WAYPOINT_RADIUS; + box.vMax.z += WAYPOINT_RADIUS; + box.vMax.y += WAYPOINT_SIZE; + box.vMin.x -= WAYPOINT_RADIUS; + box.vMin.z -= WAYPOINT_RADIUS; + return true; +} + +void CWayObject::MoveTo(const Fvector &pos, const Fvector &up) +{ + if (IsPointMode()) + { + CWayPoint *sel_point = 0; + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + if ((*it)->m_bSelected) + { + if (sel_point) + { + Msg("!Only one selected way point supported."); + return; + } + sel_point = *it; + } + if (sel_point) + sel_point->m_vPosition.set(pos); + } + else + { + if (!m_WayPoints.empty()) + { + Fvector diff; + diff.sub(pos, m_WayPoints.front()->m_vPosition); + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + (*it)->m_vPosition.add(diff); + } + } +} + +void CWayObject::Move(Fvector &amount) +{ + if (IsPointMode()) + { + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + if ((*it)->m_bSelected) + (*it)->m_vPosition.add(amount); + } + else + { + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + (*it)->m_vPosition.add(amount); + } +} + +void CWayObject::Render(int priority, bool strictB2F) +{ + // inherited::Render(priority, strictB2F); + if ((1 == priority) && (false == strictB2F)) + { + RCache.set_xform_world(Fidentity); + EDevice.SetShader(EDevice.m_WireShader); + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + (*it)->Render(GetName(), Selected()); + if (Selected()) + { + u32 clr = 0xFFFFFFFF; + Fbox bb; + GetBox(bb); + DU_impl.DrawSelectionBoxB(bb, &clr); + } + } +} + +bool CWayObject::RayPick(float &distance, const Fvector &S, const Fvector &D, SRayPickInfo *pinf) +{ + bool bPick = false; + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + if ((*it)->RayPick(distance, S, D)) + bPick = true; + return bPick; +} + +bool CWayObject::FrustumPick(const CFrustum &frustum) +{ + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + if ((*it)->FrustumPick(frustum)) + return true; + return false; +} + +bool CWayObject::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + Clear(); + + u32 version = ini.r_u32(sect_name, "version"); + + if (version != WAYOBJECT_VERSION) + { + ELog.DlgMsg(mtError, "CWayPoint: Unsupported version."); + return false; + } + + CCustomObject::LoadLTX(ini, sect_name); + + if (!GetName()) + { + ELog.DlgMsg(mtError, "Corrupted scene file.[%s] sect[%s] has empty name", ini.fname(), sect_name); + return false; + } + + u32 cnt = ini.r_u32(sect_name, "wp_count"); + m_WayPoints.resize(cnt); + + string128 buff; + u32 wp_idx = 0; + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); ++it, ++wp_idx) + { + CWayPoint *W = xr_new(""); + *it = W; + + sprintf(buff, "wp_%d_pos", wp_idx); + W->m_vPosition = ini.r_fvector3(sect_name, buff); + + sprintf(buff, "wp_%d_flags", wp_idx); + W->m_Flags.assign(ini.r_u32(sect_name, buff)); + + sprintf(buff, "wp_%d_selected", wp_idx); + W->m_bSelected = ini.r_bool(sect_name, buff); + + sprintf(buff, "wp_%d_name", wp_idx); + W->m_Name = ini.r_string(sect_name, buff); + } + + CInifile::Sect &S = ini.r_section(sect_name); + auto cit = S.Data.begin(); + auto cit_e = S.Data.end(); + for (; cit != cit_e; ++cit) + { + if (cit->first.c_str() == strstr(cit->first.c_str(), "link_wp_")) + { + u32 wp_idx = u32(-1); + u32 wp_link_idx = u32(-1); + + int res = sscanf(cit->first.c_str(), "link_wp_%4d_%4d", &wp_idx, &wp_link_idx); + R_ASSERT4(res == 2, "bad waypoint link record format", sect_name, cit->first.c_str()); + + Fvector2 val = ini.r_fvector2(sect_name, cit->first.c_str()); + u32 wp_to_idx = iFloor(val.x); + m_WayPoints[wp_idx]->CreateLink(m_WayPoints[wp_to_idx], val.y); + } + } + + m_Type = EWayType(ini.r_u32(sect_name, "type")); + + return true; +} + +void CWayObject::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + CCustomObject::SaveLTX(ini, sect_name); + ini.w_u32(sect_name, "version", WAYOBJECT_VERSION); + + ini.w_u32(sect_name, "wp_count", m_WayPoints.size()); + + u32 wp_idx = 0; + string128 buff; + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); ++it, ++wp_idx) + { + CWayPoint *W = *it; + sprintf(buff, "wp_%d_pos", wp_idx); + ini.w_fvector3(sect_name, buff, W->m_vPosition); + sprintf(buff, "wp_%d_flags", wp_idx); + ini.w_u32(sect_name, buff, W->m_Flags.get()); + + sprintf(buff, "wp_%d_selected", wp_idx); + ini.w_bool(sect_name, buff, W->m_bSelected); + + sprintf(buff, "wp_%d_name", wp_idx); + ini.w_string(sect_name, buff, *W->m_Name ? *W->m_Name : ""); + } + wp_idx = 0; + for (auto it = m_WayPoints.begin(); it != m_WayPoints.end(); ++it, ++wp_idx) + { + CWayPoint *W = *it; + u32 link_idx = 0; + for (WPLIt l_it = W->m_Links.begin(); l_it != W->m_Links.end(); ++l_it, ++link_idx) + { + sprintf(buff, "link_wp_%4d_%4d", wp_idx, link_idx); + + WPIt to = std::find(m_WayPoints.begin(), m_WayPoints.end(), (*l_it)->way_point); + + R_ASSERT(to != m_WayPoints.end()); + Fvector2 tmp; + tmp.set(float((to - m_WayPoints.begin())), (*l_it)->probability); + ini.w_fvector2(sect_name, buff, tmp); + } + } + ini.w_u32(sect_name, "type", m_Type); +} + +bool CWayObject::LoadStream(IReader &F) +{ + Clear(); + + u16 version = 0; + shared_str buf; + + if (!F.find_chunk(WAYOBJECT_CHUNK_VERSION)) + return false; + R_ASSERT(F.r_chunk(WAYOBJECT_CHUNK_VERSION, &version)); + if (version != WAYOBJECT_VERSION) + { + ELog.DlgMsg(mtError, "CWayPoint: Unsupported version."); + return false; + } + + CCustomObject::LoadStream(F); + + R_ASSERT(F.find_chunk(WAYOBJECT_CHUNK_POINTS)); + m_WayPoints.resize(F.r_u16()); + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + { + CWayPoint *W = xr_new(""); + *it = W; + F.r_fvector3(W->m_vPosition); + W->m_Flags.assign(F.r_u32()); + W->m_bSelected = F.r_u16(); + F.r_stringZ(buf); + W->m_Name = buf.c_str(); + } + + R_ASSERT(F.find_chunk(WAYOBJECT_CHUNK_LINKS)); + int l_cnt = F.r_u16(); + for (int k = 0; k < l_cnt; k++) + { + int idx0 = F.r_u16(); + int idx1 = F.r_u16(); + float pb = F.r_float(); + m_WayPoints[idx0]->CreateLink(m_WayPoints[idx1], pb); + } + + R_ASSERT(F.find_chunk(WAYOBJECT_CHUNK_TYPE)); + m_Type = EWayType(F.r_u32()); + + return true; +} +//---------------------------------------------------- + +void CWayObject::SaveStream(IWriter &F) +{ + CCustomObject::SaveStream(F); + + F.open_chunk(WAYOBJECT_CHUNK_VERSION); + F.w_u16(WAYOBJECT_VERSION); + F.close_chunk(); + + int l_cnt = 0; + F.open_chunk(WAYOBJECT_CHUNK_POINTS); + F.w_u16((u16)m_WayPoints.size()); + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + { + CWayPoint *W = *it; + F.w_fvector3(W->m_vPosition); + F.w_u32(W->m_Flags.get()); + F.w_u16((u16)W->m_bSelected); + F.w_stringZ(*W->m_Name ? *W->m_Name : ""); + l_cnt += W->m_Links.size(); + } + F.close_chunk(); + + F.open_chunk(WAYOBJECT_CHUNK_LINKS); + F.w_u16((u16)l_cnt); + for (auto it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + { + CWayPoint *W = *it; + int from = it - m_WayPoints.begin(); + for (WPLIt l_it = W->m_Links.begin(); l_it != W->m_Links.end(); l_it++) + { + WPIt to = std::find(m_WayPoints.begin(), m_WayPoints.end(), (*l_it)->way_point); + R_ASSERT(to != m_WayPoints.end()); + F.w_u16((u16)from); + F.w_u16((u16)(to - m_WayPoints.begin())); + F.w_float((*l_it)->probability); + } + } + F.close_chunk(); + + F.open_chunk(WAYOBJECT_CHUNK_TYPE); + F.w_u32(m_Type); + F.close_chunk(); +} + +bool CWayObject::ExportGame(SExportStreams *F) +{ + F->patrolpath.stream.open_chunk(F->patrolpath.chunk++); + { + F->patrolpath.stream.open_chunk(WAYOBJECT_CHUNK_VERSION); + F->patrolpath.stream.w_u16(WAYOBJECT_VERSION); + F->patrolpath.stream.close_chunk(); + + F->patrolpath.stream.open_chunk(WAYOBJECT_CHUNK_NAME); + F->patrolpath.stream.w_stringZ(GetName()); + F->patrolpath.stream.close_chunk(); + + int l_cnt = 0; + F->patrolpath.stream.open_chunk(WAYOBJECT_CHUNK_POINTS); + F->patrolpath.stream.w_u16((u16)m_WayPoints.size()); + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + { + CWayPoint *W = *it; + F->patrolpath.stream.w_fvector3(W->m_vPosition); + F->patrolpath.stream.w_u32(W->m_Flags.get()); + F->patrolpath.stream.w_stringZ(*W->m_Name ? *W->m_Name : ""); + l_cnt += W->m_Links.size(); + } + F->patrolpath.stream.close_chunk(); + + F->patrolpath.stream.open_chunk(WAYOBJECT_CHUNK_LINKS); + F->patrolpath.stream.w_u16((u16)l_cnt); + for (auto it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + { + CWayPoint *W = *it; + int from = it - m_WayPoints.begin(); + for (WPLIt l_it = W->m_Links.begin(); l_it != W->m_Links.end(); l_it++) + { + WPIt to = std::find(m_WayPoints.begin(), m_WayPoints.end(), (*l_it)->way_point); + R_ASSERT(to != m_WayPoints.end()); + F->patrolpath.stream.w_u16((u16)from); + F->patrolpath.stream.w_u16((u16)(to - m_WayPoints.begin())); + F->patrolpath.stream.w_float((*l_it)->probability); + } + } + F->patrolpath.stream.close_chunk(); + } + F->patrolpath.stream.close_chunk(); + return true; +} +//---------------------------------------------------- + +CWayPoint *CWayObject::FindWayPoint(const shared_str &nm) +{ + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); it++) + if ((*it)->m_Name.equal(nm)) + return *it; + return 0; +} + +bool CWayObject::OnWayPointNameAfterEdit(PropValue *sender, shared_str &edit_val) +{ + xr_string name = edit_val.c_str(); + xr_strlwr(name); + edit_val = name.c_str(); + return !FindWayPoint(edit_val); +} + +void CWayObject::FillProp(LPCSTR pref, PropItemVec &items) +{ + //. inherited::FillProp (pref,items); + + PropValue *V; + EName = GetName(); + V = PHelper().CreateNameCB(items, PrepareKey(pref, "Way Name"), &EName, NULL, NULL, RTextValue::TOnAfterEditEvent(this, &CCustomObject::OnObjectNameAfterEdit)); + V->OnChangeEvent.bind(this, &CCustomObject::OnNameChange); + + if (IsPointMode()) + { + for (WPIt it = m_WayPoints.begin(); it != m_WayPoints.end(); ++it) + { + CWayPoint *W = *it; + if ((*it)->m_bSelected) + { + PHelper().CreateNameCB(items, PrepareKey(pref, "Way Point\\Name"), &W->m_Name, 0, 0, RTextValue::TOnAfterEditEvent(this, &CWayObject::OnWayPointNameAfterEdit)); + PHelper().CreateVector(items, PrepareKey(pref, "Way Point\\Transform\\Position"), &W->m_vPosition, -10000, 10000, 0.01, 2); + + for (WPLIt l_it = W->m_Links.begin(); l_it != W->m_Links.end(); l_it++) + PHelper().CreateFloat(items, PrepareKey(pref, "Way Point\\Links", *(*l_it)->way_point->m_Name), &(*l_it)->probability); + + for (int k = 0; k < 32; k++) + PHelper().CreateFlag32(items, PrepareKey(pref, "Way Point\\Flags", std::to_string(k).c_str()), &W->m_Flags, 1 << k); + } + } + } +} +//---------------------------------------------------- + +bool CWayObject::OnSelectionRemove() +{ + if (IsPointMode()) + { + RemoveSelectedPoints(); + return m_WayPoints.empty(); + } + else + return true; +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Entry/WayPoint/WayPoint.h b/src/editors/LevelEditor/Entry/WayPoint/WayPoint.h new file mode 100644 index 00000000000..19e6aeeffe1 --- /dev/null +++ b/src/editors/LevelEditor/Entry/WayPoint/WayPoint.h @@ -0,0 +1,114 @@ +#pragma once + +class CFrustum; +class CWayPoint; + +struct SWPLink +{ + CWayPoint *way_point; + float probability; + // SWPLink():way_point(0),probability(0){} + SWPLink(CWayPoint *wp, float pb) : way_point(wp), probability(pb) {} +}; +DEFINE_VECTOR(SWPLink *, WPLVec, WPLIt); + +class CWayPoint +{ + friend class CWayObject; + friend class TfrmPropertiesWayPoint; + shared_str m_Name; + Fvector m_vPosition; + Flags32 m_Flags; + BOOL m_bSelected; + WPLVec m_Links; + void CreateLink(CWayPoint *P, float pb); + bool AppendLink(CWayPoint *P, float pb); + bool DeleteLink(CWayPoint *P); + +public: + CWayPoint(LPCSTR name); + ~CWayPoint(); + void Render(LPCSTR parent_name, bool bParentSelect); + bool RayPick(float &distance, const Fvector &S, const Fvector &D); + bool FrustumPick(const CFrustum &frustum); + bool FrustumSelect(int flag, const CFrustum &frustum); + void Select(int flag); + void MoveTo(const Fvector &pos) { m_vPosition.set(pos); } + bool AddSingleLink(CWayPoint *P); + bool AddDoubleLink(CWayPoint *P); + bool RemoveLink(CWayPoint *P); + void InvertLink(CWayPoint *P); + void Convert1Link(CWayPoint *P); + void Convert2Link(CWayPoint *P); + WPLIt FindLink(CWayPoint *P); + void GetBox(Fbox &bb); +}; + +DEFINE_VECTOR(CWayPoint *, WPVec, WPIt); + +class CWayObject : public CCustomObject +{ +protected: + friend class TfrmPropertiesWayPoint; + EWayType m_Type; + WPVec m_WayPoints; + typedef CCustomObject inherited; + CWayPoint *FindWayPoint(const shared_str &nm); + void FindWPByName(LPCSTR new_name, bool &res) { res = !!FindWayPoint(new_name); } + bool OnWayPointNameAfterEdit(PropValue *sender, shared_str &edit_val); + +public: + CWayObject(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + virtual ~CWayObject(); + void Clear(); + virtual bool CanAttach() { return true; } + + EWayType GetType() { return m_Type; } + + virtual void Select(int flag); + virtual bool RaySelect(int flag, const Fvector &start, const Fvector &dir, bool bRayTest = false); // flag 1,0,-1 (-1 invert) + virtual bool FrustumSelect(int flag, const CFrustum &frustum); + + CWayPoint *AppendWayPoint(); + CWayPoint *GetFirstSelected(); + int GetSelectedPoints(WPVec &lst); + void RemoveSelectedPoints(); + void RemoveLink(); + void InvertLink(); + void Convert1Link(); + void Convert2Link(); + bool Add1Link(); + bool Add2Link(); + // change position/orientation methods + virtual void MoveTo(const Fvector &pos, const Fvector &up); + virtual void Move(Fvector &amount); + virtual void RotateParent(Fvector &axis, float angle) { ; } + virtual void RotateLocal(Fvector &axis, float angle) { ; } + virtual void RotatePivot(const Fmatrix &prev_inv, const Fmatrix ¤t) { ; } + virtual void Scale(Fvector &amount) { ; } + virtual void ScalePivot(const Fmatrix &prev_inv, const Fmatrix ¤t, Fvector &amount) { ; } + + virtual bool GetBox(Fbox &box); + virtual void Render(int priority, bool strictB2F); + virtual bool RayPick(float &distance, const Fvector &S, const Fvector &D, SRayPickInfo *pinf = NULL); + virtual bool FrustumPick(const CFrustum &frustum); + + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual bool ExportGame(SExportStreams *data); + + virtual void FillProp(LPCSTR pref, PropItemVec &items); + + virtual bool OnSelectionRemove(); + + virtual const Fvector &GetPosition() const { return m_WayPoints.front()->m_vPosition; } + virtual void SetPosition(const Fvector &pos) + { + MoveTo(pos, Fvector().set(0, 1, 0)); + UpdateTransform(); + } +}; diff --git a/src/editors/LevelEditor/Kernel/LevelEditor.cpp b/src/editors/LevelEditor/Kernel/LevelEditor.cpp new file mode 100644 index 00000000000..a8fd4eaecc2 --- /dev/null +++ b/src/editors/LevelEditor/Kernel/LevelEditor.cpp @@ -0,0 +1,32 @@ +#include "stdafx.h" + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow) +{ + if (!IsDebuggerPresent()) + xrDebug::Initialize(pCmdLine); + + Core.Initialize("level", pCmdLine, LogCallback(ELogCallback, nullptr), true, "fs.ltx", false, true); + xrSE_Factory::initialize(); + + LTools = xr_new(); + Tools = LTools; + + LUI = xr_new(); + UI = LUI; + UI->RegisterCommands(); + + Scene = xr_new(); + UIMainForm *MainForm = xr_new(); + + ::MainForm = MainForm; + UI->Push(MainForm, false); + + while (MainForm->Frame()) + { + } + + xr_delete(MainForm); + xrSE_Factory::destroy(); + Core._destroy(); + return 0; +} diff --git a/src/editors/LevelEditor/Kernel/UI_LevelMain.cpp b/src/editors/LevelEditor/Kernel/UI_LevelMain.cpp new file mode 100644 index 00000000000..a0cf1800ce2 --- /dev/null +++ b/src/editors/LevelEditor/Kernel/UI_LevelMain.cpp @@ -0,0 +1,1411 @@ +#include "stdafx.h" + +#ifdef _LEVEL_EDITOR +//. if (m_Cursor->GetVisible()) RedrawScene(); +#endif + +CLevelMain *LUI = (CLevelMain *)UI; + +CLevelMain::CLevelMain() +{ + m_Cursor = xr_new(); + EPrefs = xr_new(); +} + +CLevelMain::~CLevelMain() +{ + xr_delete(EPrefs); + xr_delete(m_Cursor); + // TClipMaker::DestroyForm(g_clip_maker); +} + +//------------------------------------------------------------------------------ +// Tools commands +//------------------------------------------------------------------------------ +CCommandVar CLevelTool::CommandChangeTarget(CCommandVar p1, CCommandVar p2) +{ + if (Scene->GetTool(p1)->IsEnabled()) + { + SetTarget(p1, p2); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + return TRUE; + } + else + { + return FALSE; + } +} +CCommandVar CLevelTool::CommandShowObjectList(CCommandVar p1, CCommandVar p2) +{ + if (LUI->GetEState() == esEditScene) + ShowObjectList(); + return TRUE; +} + +//------------------------------------------------------------------------------ +// Main commands +//------------------------------------------------------------------------------ +CCommandVar CommandLibraryEditor(CCommandVar p1, CCommandVar p2) +{ + if (Scene->ObjCount() || (LUI->GetEState() != esEditScene)) + { + if (LUI->GetEState() == esEditLibrary) + UIEditLibrary::Show(); + else + ELog.DlgMsg(mtError, "Scene must be empty before editing library!"); + } + else + UIEditLibrary::Show(); + + return TRUE; +} + +CCommandVar CommandLAnimEditor(CCommandVar p1, CCommandVar p2) +{ + // TfrmEditLightAnim::ShowEditor(); + return TRUE; +} +CCommandVar CommandFileMenu(CCommandVar p1, CCommandVar p2) +{ + // FHelper.ShowPPMenu(fraLeftBar->pmSceneFile,0); + return TRUE; +} +CCommandVar CLevelTool::CommandEnableTarget(CCommandVar p1, CCommandVar p2) +{ + ESceneToolBase *M = Scene->GetTool(p1); + VERIFY(M); + BOOL res = FALSE; + if (p2) + { + res = ExecCommand(COMMAND_LOAD_LEVEL_PART, M->FClassID, TRUE); + if (res) + M->m_EditFlags.set(ESceneToolBase::flEnable, TRUE); + } + else + { + if (!Scene->IfModified()) + { + M->m_EditFlags.set(ESceneToolBase::flEnable, TRUE); + res = FALSE; + } + else + { + res = ExecCommand(COMMAND_UNLOAD_LEVEL_PART, M->FClassID, TRUE); + if (res) + M->m_EditFlags.set(ESceneToolBase::flEnable, FALSE); + } + if (res) + ExecCommand(COMMAND_CHANGE_TARGET, OBJCLASS_SCENEOBJECT); + } + ExecCommand(COMMAND_REFRESH_UI_BAR); + return res; +} + +CCommandVar CLevelTool::CommandShowTarget(CCommandVar p1, CCommandVar p2) +{ + ESceneToolBase *M = Scene->GetTool(p1); + if (p2) + M->m_EditFlags.set(ESceneToolBase::flVisible, TRUE); + else + M->m_EditFlags.set(ESceneToolBase::flVisible, FALSE); + + return TRUE; +} + +CCommandVar CLevelTool::CommandReadonlyTarget(CCommandVar p1, CCommandVar p2) +{ + ESceneToolBase *M = Scene->GetTool(p1); + VERIFY(M); + BOOL res = TRUE; + if (p2) + { + if (!Scene->IfModified()) + { + M->m_EditFlags.set(ESceneToolBase::flForceReadonly, FALSE); + res = FALSE; + } + else + { + //. xr_string pn = Scene->LevelPartName(LTools->m_LastFileName.c_str(),M->ClassID); + } + } + else + { + //. xr_string pn = Scene->LevelPartName(LTools->m_LastFileName.c_str(), M->ClassID); + } + if (res) + { + Reset(); + ExecCommand(COMMAND_REFRESH_UI_BAR); + } + return res; +} + +CCommandVar CLevelTool::CommandMultiRenameObjects(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (mrYes == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to rename selected objects?")) + { + int cnt = Scene->MultiRenameObjects(); + if (cnt) + { + ExecCommand(COMMAND_UPDATE_PROPERTIES); + Scene->UndoSave(); + } + ELog.DlgMsg(mtInformation, "%d - objects are renamed.", cnt); + } + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} +CCommandVar CommandLoadLevelPart(CCommandVar p1, CCommandVar p2) +{ + xr_string temp_fn = LTools->m_LastFileName.c_str(); + if (!temp_fn.empty()) + return Scene->LoadLevelPart(temp_fn.c_str(), p1); + return TRUE; +} +CCommandVar CommandUnloadLevelPart(CCommandVar p1, CCommandVar p2) +{ + xr_string temp_fn = LTools->m_LastFileName.c_str(); + if (!temp_fn.empty()) + return Scene->UnloadLevelPart(temp_fn.c_str(), p1); + return TRUE; +} +CCommandVar CommandLoad(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (!p1.IsString()) + { + xr_string temp_fn = LTools->m_LastFileName.c_str(); + if (EFS.GetOpenName(EDevice.m_hWnd, _maps_, temp_fn)) + return ExecCommand(COMMAND_LOAD, temp_fn); + } + else + { + xr_string temp_fn = p1; + xr_strlwr(temp_fn); + + if (!Scene->IfModified()) + return FALSE; + + UI->SetStatus("Level loading..."); + ExecCommand(COMMAND_CLEAR); + + IReader *R = FS.r_open(temp_fn.c_str()); + if (!R) + return false; + char ch; + R->r(&ch, sizeof(ch)); + bool is_ltx = (ch == '['); + FS.r_close(R); + bool res; + LTools->m_LastFileName = temp_fn.c_str(); + + if (is_ltx) + res = Scene->LoadLTX(temp_fn.c_str(), false); + else + res = Scene->Load(temp_fn.c_str(), false); + + if (res) + { + UI->ResetStatus(); + Scene->UndoClear(); + + BOOL bk1 = Scene->m_RTFlags.test(EScene::flRT_Unsaved); + BOOL bk2 = Scene->m_RTFlags.test(EScene::flRT_Modified); + + Scene->UndoSave(); + + Scene->m_RTFlags.set(EScene::flRT_Unsaved, bk1); + Scene->m_RTFlags.set(EScene::flRT_Modified, bk2); + + ExecCommand(COMMAND_CLEAN_LIBRARY); + ExecCommand(COMMAND_UPDATE_CAPTION); + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + EPrefs->AppendRecentFile(temp_fn.c_str()); + } + else + { + ELog.DlgMsg(mtError, "Can't load map '%s'", temp_fn.c_str()); + LTools->m_LastFileName = ""; + } + // update props + ExecCommand(COMMAND_UPDATE_PROPERTIES); + UI->RedrawScene(); + } + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } + return TRUE; +} +CCommandVar CommandSaveBackup(CCommandVar p1, CCommandVar p2) +{ + string_path fn; + strconcat(sizeof(fn), fn, Core.CompName, "_", Core.UserName, "_backup.level"); + FS.update_path(fn, _maps_, fn); + return ExecCommand(COMMAND_SAVE, xr_string(fn)); +} + +CCommandVar CommandSave(CCommandVar p1, CCommandVar p2) +{ + if (Scene->locked()) + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } + + if (p2 == 1) + { + xr_string temp_fn = LTools->m_LastFileName.c_str(); + + if (EFS.GetSaveName(_maps_, temp_fn)) + return ExecCommand(COMMAND_SAVE, temp_fn, 66); + else + return FALSE; + } + + if (p1.IsInteger()) + return ExecCommand(COMMAND_SAVE, xr_string(LTools->m_LastFileName.c_str()), 0); + + xr_string temp_fn = xr_string(p1); + + if (temp_fn.empty()) + return ExecCommand(COMMAND_SAVE, temp_fn, 1); + + xr_strlwr(temp_fn); + UI->SetStatus("Level saving..."); + + if (Core.SocSdk) + Scene->Save(temp_fn.c_str(), false, true); + else + Scene->SaveLTX(temp_fn.c_str(), false, (p2 == 66)); + + UI->ResetStatus(); + // set new name + if (xr_strcmp(Tools->m_LastFileName.c_str(), temp_fn.c_str())) + Tools->m_LastFileName = temp_fn.c_str(); + + ExecCommand(COMMAND_UPDATE_CAPTION); + EPrefs->AppendRecentFile(temp_fn.c_str()); + return TRUE; +} + +CCommandVar CommandClear(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (!Scene->IfModified()) + return TRUE; + EDevice.m_Camera.Reset(); + Scene->Reset(); + Scene->m_LevelOp.Reset(); + Tools->m_LastFileName = ""; + LTools->m_LastSelectionName = ""; + Scene->UndoClear(); + ExecCommand(COMMAND_UPDATE_CAPTION); + ExecCommand(COMMAND_CHANGE_TARGET, OBJCLASS_SCENEOBJECT); + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect, estDefault); + ExecCommand(COMMAND_UPDATE_PROPERTIES, 1); + Scene->UndoSave(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandLoadFirstRecent(CCommandVar p1, CCommandVar p2) +{ + if (EPrefs->FirstRecentFile()) + return ExecCommand(COMMAND_LOAD, xr_string(EPrefs->FirstRecentFile())); + return FALSE; +} + +CCommandVar CommandClearDebugDraw(CCommandVar p1, CCommandVar p2) +{ + Tools->ClearDebugDraw(); + UI->RedrawScene(); + return TRUE; +} + +CCommandVar CommandShowClipEditor(CCommandVar p1, CCommandVar p2) +{ + /* if(g_clip_maker==NULL) + g_clip_maker = TClipMaker::CreateForm(); + + if(!g_clip_maker->Visible) + { + ESceneCustomOTool* st = Scene->GetOTool(OBJCLASS_SPAWNPOINT); + + ObjectList& ol = st->GetObjects(); + ObjectList::iterator it = ol.begin(); + ObjectList::iterator it_e = ol.end(); + + CCustomObject* CO = NULL; + for(;it!=it_e;++it) + { + if((*it)->Selected()==true) + { + CO=*it; + break; + } + } + if(!CO) + return TRUE; + + CSpawnPoint* sp = dynamic_cast(CO); + + + CKinematicsAnimated* KA = PKinematicsAnimated(sp->m_SpawnData.m_Visual->visual); + R_ASSERT (KA); + g_clip_maker->ShowEditor (KA); + }*/ + return TRUE; +} + +CCommandVar CommandImportCompilerError(CCommandVar p1, CCommandVar p2) +{ + xr_string fn; + if (EFS.GetOpenName(EDevice.m_hWnd, "$logs$", fn, false, NULL, 0)) + { + Scene->LoadCompilerError(fn.c_str()); + } + UI->RedrawScene(); + return TRUE; +} +CCommandVar CommandExportCompilerError(CCommandVar p1, CCommandVar p2) +{ + xr_string fn; + if (EFS.GetSaveName("$logs$", fn, NULL, 0)) + { + Scene->SaveCompilerError(fn.c_str()); + } + return TRUE; +} +CCommandVar CommandValidateScene(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->Validate(true, true, true, true, true, true); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandCleanLibrary(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Lib.CleanLibrary(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene must be empty before refreshing library!"); + return FALSE; + } +} + +CCommandVar CommandReloadObjects(CCommandVar p1, CCommandVar p2) +{ + Lib.ReloadObjects(); + return TRUE; +} + +CCommandVar CommandCut(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->CutSelection(LTools->CurrentClassID()); + /* fraLeftBar->miPaste->Enabled = true; + fraLeftBar->miPaste2->Enabled = true;*/ + Scene->UndoSave(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } + return FALSE; +} +CCommandVar CommandCopy(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->CopySelection(LTools->CurrentClassID()); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } + return FALSE; +} + +CCommandVar CommandPaste(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->PasteSelection(); + Scene->UndoSave(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } + return FALSE; +} + +CCommandVar CommandLoadSelection(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + xr_string fn = LTools->m_LastSelectionName; + if (EFS.GetOpenName(EDevice.m_hWnd, _maps_, fn)) + { + LPCSTR maps_path = FS.get_path(_maps_)->m_Path; + if (fn.c_str() == strstr(fn.c_str(), maps_path)) + LTools->m_LastSelectionName = fn.c_str() + xr_strlen(maps_path); + UI->SetStatus("Fragment loading..."); + + Scene->LoadSelection(fn.c_str()); + + UI->ResetStatus(); + Scene->UndoSave(); + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + UI->RedrawScene(); + return TRUE; + } + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} +CCommandVar CommandSaveSelection(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + xr_string fn = LTools->m_LastSelectionName; + if (EFS.GetSaveName(_maps_, fn)) + { + LPCSTR maps_path = FS.get_path(_maps_)->m_Path; + if (fn.c_str() == strstr(fn.c_str(), maps_path)) + LTools->m_LastSelectionName = fn.c_str() + xr_strlen(maps_path); + UI->SetStatus("Fragment saving..."); + Scene->SaveSelection(LTools->CurrentClassID(), fn.c_str()); + UI->ResetStatus(); + return TRUE; + } + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} + +CCommandVar CommandUndo(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (!Scene->Undo()) + ELog.DlgMsg(mtInformation, "Undo buffer empty"); + else + { + LTools->Reset(); + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + return TRUE; + } + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} + +CCommandVar CommandRedo(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (!Scene->Redo()) + ELog.DlgMsg(mtInformation, "Redo buffer empty"); + else + { + LTools->Reset(); + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + return TRUE; + } + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} + +CCommandVar CommandClearSceneSummary(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->ClearSummaryInfo(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandCollectSceneSummary(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->CollectSummaryInfo(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandShowSceneSummary(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->ShowSummaryInfo(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandExportSceneSummary(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->ExportSummaryInfo(xr_string(p1).c_str()); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} + +CCommandVar CommandSceneHighlightTexture(CCommandVar p1, CCommandVar p2) +{ + /*if( !Scene->locked() ){ + LPCSTR new_val = 0; + if (TfrmChoseItem::SelectItem(smTexture,new_val,1)){ + Scene->HighlightTexture(new_val,false,0,0,false); + return TRUE; + } + } else { + ELog.DlgMsg( mtError, "Scene sharing violation" ); + } + return FALSE;*/ + return FALSE; +} + +CCommandVar CommandOptions(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + ExecCommand(COMMAND_SHOW_PROPERTIES, p1, p2); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} + +CCommandVar CommandBuild(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (mrYes == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to build level?")) + return Builder.Compile(false); + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} +CCommandVar CommandMakeAIMap(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (mrYes == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to export ai-map?")) + return Builder.MakeAIMap(); + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} +CCommandVar CommandMakeGame(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (mrYes == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to export game?")) + return Builder.MakeGame(); + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} +CCommandVar CommandMakeDetails(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (mrYes == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to export details?")) + return Builder.MakeDetails(); + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} +CCommandVar CommandMakeHOM(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (mrYes == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to export HOM?")) + return Builder.MakeHOM(); + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} +CCommandVar CommandMakeSOM(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + if (mrYes == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to export Sound Occlusion Model?")) + return Builder.MakeSOM(); + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} +CCommandVar CommandInvertSelectionAll(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->InvertSelection(LTools->CurrentClassID()); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} + +CCommandVar CommandSelectAll(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->SelectObjects(true, LTools->CurrentClassID()); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + } + return FALSE; +} + +CCommandVar CommandDeselectAll(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->SelectObjects(false, LTools->CurrentClassID()); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} + +CCommandVar CommandDeleteSelection(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->RemoveSelection(LTools->CurrentClassID()); + Scene->UndoSave(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} + +CCommandVar CommandHideUnsel(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->ShowObjects(false, LTools->CurrentClassID(), true, false); + Scene->UndoSave(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandHideSel(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->ShowObjects(bool(p1), LTools->CurrentClassID(), true, true); + Scene->UndoSave(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandHideAll(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->ShowObjects(bool(p1), LTools->CurrentClassID(), false); + Scene->UndoSave(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandSetSnapObjects(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->SetSnapList(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandAddSelSnapObjects(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->AddSelToSnapList(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandDelSelSnapObjects(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->DelSelFromSnapList(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandClearSnapObjects(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->ClearSnapList(true); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandSelectSnapObjects(CCommandVar p1, CCommandVar p2) +{ + if (!Scene->locked()) + { + Scene->SelectSnapList(); + return TRUE; + } + else + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return FALSE; + } +} +CCommandVar CommandRefreshSnapObjects(CCommandVar p1, CCommandVar p2) +{ + // fraLeftBar->UpdateSnapList(); + return TRUE; +} +/* +CCommandVar CommandRefreshSoundEnvs(CCommandVar p1, CCommandVar p2) +{ + ::Sound->refresh_env_library(); + return TRUE; +// ::Sound->_restart(); +} +*/ + +CCommandVar CommandRefreshSoundEnvGeometry(CCommandVar p1, CCommandVar p2) +{ + LSndLib->RefreshEnvGeometry(); + return TRUE; +} +CCommandVar CommandShowContextMenu(CCommandVar p1, CCommandVar p2) +{ + LUI->ShowContextMenu(p1); + return TRUE; +} +//------ +CCommandVar CommandRefreshUIBar(CCommandVar p1, CCommandVar p2) +{ + if (MainForm) + if (MainForm->GetTopBarForm()) + MainForm->GetTopBarForm()->RefreshBar(); + /*fraTopBar->RefreshBar (); + fraLeftBar->RefreshBar (); + fraBottomBar->RefreshBar ();*/ + return TRUE; +} +CCommandVar CommandRestoreUIBar(CCommandVar p1, CCommandVar p2) +{ + /*fraTopBar->fsStorage->RestoreFormPlacement(); + fraLeftBar->fsStorage->RestoreFormPlacement(); + fraBottomBar->fsStorage->RestoreFormPlacement();*/ + return TRUE; +} +CCommandVar CommandSaveUIBar(CCommandVar p1, CCommandVar p2) +{ + /* fraTopBar->fsStorage->SaveFormPlacement(); + fraLeftBar->fsStorage->SaveFormPlacement(); + fraBottomBar->fsStorage->SaveFormPlacement();*/ + return TRUE; +} +CCommandVar CommandUpdateToolBar(CCommandVar p1, CCommandVar p2) +{ + /* fraLeftBar->UpdateBar ();*/ + return TRUE; +} +CCommandVar CommandUpdateCaption(CCommandVar p1, CCommandVar p2) +{ + /* frmMain->UpdateCaption ();*/ + return TRUE; +} +//------ +CCommandVar CommandCreateSoundLib(CCommandVar p1, CCommandVar p2) +{ + SndLib = xr_new(); + LSndLib = (CLevelSoundManager *)SndLib; + return TRUE; +} + +extern BOOL ai_map_shown; +CCommandVar CommandToggleAiMapVisibility(CCommandVar p1, CCommandVar p2) +{ + ai_map_shown = !ai_map_shown; + return TRUE; +} + +void CLevelMain::RegisterCommands() +{ + inherited::RegisterCommands(); + // tools + REGISTER_SUB_CMD_CE(COMMAND_CHANGE_TARGET, "Change Target", LTools, CLevelTool::CommandChangeTarget, true); + APPEND_SUB_CMD("Object", OBJCLASS_SCENEOBJECT, 0); + APPEND_SUB_CMD("Light", OBJCLASS_LIGHT, 0); + APPEND_SUB_CMD("Sound Source", OBJCLASS_SOUND_SRC, 0); + APPEND_SUB_CMD("Sound Env", OBJCLASS_SOUND_ENV, 0); + APPEND_SUB_CMD("Glow", OBJCLASS_GLOW, 0); + APPEND_SUB_CMD("Shape", OBJCLASS_SHAPE, 0); + APPEND_SUB_CMD("Spawn Point", OBJCLASS_SPAWNPOINT, 0); + APPEND_SUB_CMD("Way", OBJCLASS_WAY, 0); + APPEND_SUB_CMD("Way Point", OBJCLASS_WAY, 1); + APPEND_SUB_CMD("Toggle Way Mode", OBJCLASS_WAY, 2); + APPEND_SUB_CMD("Sector", OBJCLASS_SECTOR, 0); + APPEND_SUB_CMD("Portal", OBJCLASS_PORTAL, 0); + APPEND_SUB_CMD("Group", OBJCLASS_GROUP, 0); + APPEND_SUB_CMD("Particle System", OBJCLASS_PS, 0); + APPEND_SUB_CMD("Detail Objects", OBJCLASS_DO, 0); + APPEND_SUB_CMD("AI Map", OBJCLASS_AIMAP, 0); + APPEND_SUB_CMD("Static Wallmark", OBJCLASS_WM, 0); + REGISTER_SUB_CMD_END; + REGISTER_CMD_C(COMMAND_ENABLE_TARGET, LTools, CLevelTool::CommandEnableTarget); + REGISTER_CMD_C(COMMAND_SHOW_TARGET, LTools, CLevelTool::CommandShowTarget); + REGISTER_CMD_C(COMMAND_READONLY_TARGET, LTools, CLevelTool::CommandReadonlyTarget); + REGISTER_CMD_C(COMMAND_MULTI_RENAME_OBJECTS, LTools, CLevelTool::CommandMultiRenameObjects); + + REGISTER_CMD_CE(COMMAND_SHOW_OBJECTLIST, "Scene\\Show Object List", LTools, CLevelTool::CommandShowObjectList, false); + // common + REGISTER_CMD_S(COMMAND_LIBRARY_EDITOR, CommandLibraryEditor); + REGISTER_CMD_S(COMMAND_LANIM_EDITOR, CommandLAnimEditor); + REGISTER_CMD_SE(COMMAND_FILE_MENU, "File\\Menu", CommandFileMenu, true); + REGISTER_CMD_S(COMMAND_LOAD_LEVEL_PART, CommandLoadLevelPart); + REGISTER_CMD_S(COMMAND_UNLOAD_LEVEL_PART, CommandUnloadLevelPart); + REGISTER_CMD_SE(COMMAND_LOAD, "File\\Load Level", CommandLoad, true); + REGISTER_SUB_CMD_SE(COMMAND_SAVE, "File", CommandSave, true); + APPEND_SUB_CMD("Save", 0, 0); + APPEND_SUB_CMD("Save As", 0, 1); + REGISTER_SUB_CMD_END; + REGISTER_CMD_S(COMMAND_SAVE_BACKUP, CommandSaveBackup); + REGISTER_CMD_SE(COMMAND_CLEAR, "File\\Clear Scene", CommandClear, true); + REGISTER_CMD_SE(COMMAND_LOAD_FIRSTRECENT, "File\\Load First Recent", CommandLoadFirstRecent, true); + REGISTER_CMD_S(COMMAND_CLEAR_DEBUG_DRAW, CommandClearDebugDraw); + REGISTER_CMD_S(COMMAND_IMPORT_COMPILER_ERROR, CommandImportCompilerError); + REGISTER_CMD_S(COMMAND_EXPORT_COMPILER_ERROR, CommandExportCompilerError); + REGISTER_CMD_S(COMMAND_VALIDATE_SCENE, CommandValidateScene); + REGISTER_CMD_S(COMMAND_CLEAN_LIBRARY, CommandCleanLibrary); + REGISTER_CMD_S(COMMAND_RELOAD_OBJECTS, CommandReloadObjects); + REGISTER_CMD_SE(COMMAND_CUT, "Edit\\Cut", CommandCut, false); + REGISTER_CMD_SE(COMMAND_COPY, "Edit\\Copy", CommandCopy, false); + REGISTER_CMD_SE(COMMAND_PASTE, "Edit\\Paste", CommandPaste, false); + REGISTER_CMD_S(COMMAND_LOAD_SELECTION, CommandLoadSelection); + REGISTER_CMD_S(COMMAND_SAVE_SELECTION, CommandSaveSelection); + REGISTER_CMD_SE(COMMAND_UNDO, "Edit\\Undo", CommandUndo, false); + REGISTER_CMD_SE(COMMAND_REDO, "Edit\\Redo", CommandRedo, false); + REGISTER_CMD_S(COMMAND_CLEAR_SCENE_SUMMARY, CommandClearSceneSummary); + REGISTER_CMD_S(COMMAND_COLLECT_SCENE_SUMMARY, CommandCollectSceneSummary); + REGISTER_CMD_S(COMMAND_SHOW_SCENE_SUMMARY, CommandShowSceneSummary); + REGISTER_CMD_S(COMMAND_EXPORT_SCENE_SUMMARY, CommandExportSceneSummary); + REGISTER_CMD_S(COMMAND_SCENE_HIGHLIGHT_TEXTURE, CommandSceneHighlightTexture); + REGISTER_CMD_SE(COMMAND_OPTIONS, "Scene\\Options", CommandOptions, false); + REGISTER_CMD_SE(COMMAND_BUILD, "Compile\\Build", CommandBuild, false); + REGISTER_CMD_SE(COMMAND_MAKE_GAME, "Compile\\Make Game", CommandMakeGame, false); + REGISTER_CMD_SE(COMMAND_MAKE_AIMAP, "Compile\\Make AI Map", CommandMakeAIMap, false); + REGISTER_CMD_SE(COMMAND_MAKE_DETAILS, "Compile\\Make Details", CommandMakeDetails, false); + REGISTER_CMD_SE(COMMAND_MAKE_HOM, "Compile\\Make HOM", CommandMakeHOM, false); + REGISTER_CMD_SE(COMMAND_MAKE_SOM, "Compile\\Make SOM", CommandMakeSOM, false); + REGISTER_CMD_SE(COMMAND_INVERT_SELECTION_ALL, "Selection\\Invert", CommandInvertSelectionAll, false); + REGISTER_CMD_SE(COMMAND_SELECT_ALL, "Selection\\Select All", CommandSelectAll, false); + REGISTER_CMD_SE(COMMAND_DESELECT_ALL, "Selection\\Unselect All", CommandDeselectAll, false); + REGISTER_CMD_SE(COMMAND_DELETE_SELECTION, "Edit\\Delete", CommandDeleteSelection, false); + REGISTER_CMD_SE(COMMAND_HIDE_UNSEL, "Visibility\\Hide Unselected", CommandHideUnsel, false); + REGISTER_CMD_SE(COMMAND_HIDE_SEL, "Visibility\\Hide Selected", CommandHideSel, false); + REGISTER_CMD_SE(COMMAND_HIDE_ALL, "Visibility\\Hide All", CommandHideAll, false); + REGISTER_CMD_S(COMMAND_SET_SNAP_OBJECTS, CommandSetSnapObjects); + REGISTER_CMD_S(COMMAND_ADD_SEL_SNAP_OBJECTS, CommandAddSelSnapObjects); + REGISTER_CMD_S(COMMAND_DEL_SEL_SNAP_OBJECTS, CommandDelSelSnapObjects); + REGISTER_CMD_S(COMMAND_CLEAR_SNAP_OBJECTS, CommandClearSnapObjects); + REGISTER_CMD_S(COMMAND_SELECT_SNAP_OBJECTS, CommandSelectSnapObjects); + REGISTER_CMD_S(COMMAND_REFRESH_SNAP_OBJECTS, CommandRefreshSnapObjects); + // REGISTER_CMD_S (COMMAND_REFRESH_SOUND_ENVS, CommandRefreshSoundEnvs); + REGISTER_CMD_S(COMMAND_REFRESH_SOUND_ENV_GEOMETRY, CommandRefreshSoundEnvGeometry); + REGISTER_CMD_S(COMMAND_SHOWCONTEXTMENU, CommandShowContextMenu); + REGISTER_CMD_S(COMMAND_REFRESH_UI_BAR, CommandRefreshUIBar); + REGISTER_CMD_S(COMMAND_RESTORE_UI_BAR, CommandRestoreUIBar); + REGISTER_CMD_S(COMMAND_SAVE_UI_BAR, CommandSaveUIBar); + REGISTER_CMD_S(COMMAND_UPDATE_TOOLBAR, CommandUpdateToolBar); + REGISTER_CMD_S(COMMAND_UPDATE_CAPTION, CommandUpdateCaption); + REGISTER_CMD_S(COMMAND_CREATE_SOUND_LIB, CommandCreateSoundLib); + REGISTER_CMD_SE(COMMAND_TOGGLE_AIMAP_VISIBILITY, "Visibility\\Toggle AIMap", CommandToggleAiMapVisibility, true); + REGISTER_CMD_S(COMMAND_SHOW_CLIP_EDITOR, CommandShowClipEditor); +} + +const char *CLevelMain::GetCaption() +{ + return Tools->m_LastFileName.empty() ? "noname" : Tools->m_LastFileName.c_str(); +} + +bool CLevelMain::ApplyShortCut(DWORD Key, TShiftState Shift) +{ + return inherited::ApplyShortCut(Key, Shift); +} +//--------------------------------------------------------------------------- + +bool CLevelMain::ApplyGlobalShortCut(DWORD Key, TShiftState Shift) +{ + return inherited::ApplyGlobalShortCut(Key, Shift); +} +//--------------------------------------------------------------------------- +void RetrieveSceneObjPointAndNormal(Fvector &hitpoint, Fvector *hitnormal, const SRayPickInfo &pinf, int bSnap) +{ + if (pinf.e_mesh == 0) + { + hitpoint = pinf.pt; + if (hitnormal && pinf.visual_inf.K) + *hitnormal = pinf.visual_inf.normal; + return; + } + if (Tools->GetSettings(etfVSnap) && bSnap) + { + Fvector pn; + float u = pinf.inf.u; + float v = pinf.inf.v; + float w = 1 - (u + v); + Fvector verts[3]; + pinf.e_obj->GetFaceWorld(pinf.s_obj->_Transform(), pinf.e_mesh, pinf.inf.id, verts); + + if ((w > u) && (w > v)) + pn.set(verts[0]); + else if ((u > w) && (u > v)) + pn.set(verts[1]); + else + pn.set(verts[2]); + + if (pn.distance_to(pinf.pt) < LTools->m_MoveSnap) + hitpoint.set(pn); + else + hitpoint.set(pinf.pt); + } + else + { + hitpoint.set(pinf.pt); + } + + if (hitnormal) + { + Fvector verts[3]; + pinf.e_obj->GetFaceWorld(pinf.s_obj->_Transform(), pinf.e_mesh, pinf.inf.id, verts); + hitnormal->mknormal(verts[0], verts[1], verts[2]); + } +} + +bool EditLibPickObjectGeometry(Fvector &hitpoint, const Fvector &start, const Fvector &direction, int bSnap, Fvector *hitnormal) +{ + SRayPickInfo pinf; + /*if( TfrmEditLibrary::RayPick( start, direction, &pinf ) ) + { + RetrieveSceneObjPointAndNormal( hitpoint, hitnormal, pinf, bSnap ); + return true; + }*/ + return false; +} + +bool ScenePickObjectGeometry(Fvector &hitpoint, const Fvector &start, const Fvector &direction, int bSnap, Fvector *hitnormal) +{ + + SRayPickInfo pinf; + + SRayPickInfo l_pinf; + bool bResult = false; + + { + SRayPickInfo l_pinf; + bool l_bres = Scene->RayPickObject(l_pinf.inf.range, start, direction, OBJCLASS_SPAWNPOINT, &l_pinf, Scene->GetSnapList(false)); + + if (l_bres) + { + pinf = l_pinf; + bResult = true; + } + } + { + + SRayPickInfo l_pinf; + bool l_bres = Scene->RayPickObject(l_pinf.inf.range, start, direction, OBJCLASS_SCENEOBJECT, &l_pinf, Scene->GetSnapList(false)); + + if (!bResult || (l_bres && l_pinf.inf.range < pinf.inf.range)) + pinf = l_pinf; + if (l_bres) + bResult = true; + } + + if (bResult) + RetrieveSceneObjPointAndNormal(hitpoint, hitnormal, pinf, bSnap); + + return bResult; +} + +bool PickObjectGeometry(EEditorState est, Fvector &hitpoint, const Fvector &start, const Fvector &direction, int bSnap, Fvector *hitnormal) +{ + + switch (est) + { + case esEditLibrary: + return EditLibPickObjectGeometry(hitpoint, start, direction, bSnap, hitnormal); + case esEditScene: + return ScenePickObjectGeometry(hitpoint, start, direction, bSnap, hitnormal); + default: + NODEFAULT; + } + return false; +} + +bool PickGrid(Fvector &hitpoint, const Fvector &start, const Fvector &direction, int bSnap, Fvector *hitnormal) +{ + + // pick grid + Fvector normal; + normal.set(0, 1, 0); + float clcheck = direction.dotproduct(normal); + + if (fis_zero(clcheck)) + return false; + + float alpha = -start.dotproduct(normal) / clcheck; + + if (alpha <= 0) + return false; + + hitpoint.x = start.x + direction.x * alpha; + hitpoint.y = start.y + direction.y * alpha; + hitpoint.z = start.z + direction.z * alpha; + + if (Tools->GetSettings(etfGSnap) && bSnap) + { + hitpoint.x = snapto(hitpoint.x, LTools->m_MoveSnap); + hitpoint.z = snapto(hitpoint.z, LTools->m_MoveSnap); + hitpoint.y = 0.f; + } + + if (hitnormal) + hitnormal->set(0, 1, 0); + return true; +} + +bool CLevelMain::PickGround(Fvector &hitpoint, const Fvector &start, const Fvector &direction, int bSnap, Fvector *hitnormal) +{ + VERIFY(m_bReady); + + EEditorState est = GetEState(); + if (est != esEditLibrary && est != esEditScene) + return false; + + // pick object geometry + if ((bSnap == -1) || (Tools->GetSettings(etfOSnap) && (bSnap == 1))) + { + bool b = PickObjectGeometry(est, hitpoint, start, direction, bSnap, hitnormal); + if (b) + return true; + } + + return PickGrid(hitpoint, start, direction, bSnap, hitnormal); +} +//---------------------------------------------------- + +bool CLevelMain::SelectionFrustum(CFrustum &frustum) +{ + VERIFY(m_bReady); + Fvector st, d, p[4]; + Ivector2 pt[4]; + + float depth = 0; + + int x1 = m_StartCp.x, x2 = m_CurrentCp.x; + int y1 = m_StartCp.y, y2 = m_CurrentCp.y; + + if (!(x1 != x2 && y1 != y2)) + return false; + + pt[0].set(_min(x1, x2), _min(y1, y2)); + pt[1].set(_max(x1, x2), _min(y1, y2)); + pt[2].set(_max(x1, x2), _max(y1, y2)); + pt[3].set(_min(x1, x2), _max(y1, y2)); + + SRayPickInfo pinf; + for (int i = 0; i < 4; i++) + { + EDevice.m_Camera.MouseRayFromPoint(st, d, pt[i]); + if (EPrefs->bp_lim_depth) + { + pinf.inf.range = EDevice.m_Camera._Zfar(); // max pick range + if (Scene->RayPickObject(pinf.inf.range, st, d, OBJCLASS_SCENEOBJECT, &pinf, 0)) + if (pinf.inf.range > depth) + depth = pinf.inf.range; + } + } + if (depth < EDevice.m_Camera._Znear()) + depth = EDevice.m_Camera._Zfar(); + else + depth += EPrefs->bp_depth_tolerance; + + for (int i = 0; i < 4; i++) + { + EDevice.m_Camera.MouseRayFromPoint(st, d, pt[i]); + p[i].mad(st, d, depth); + } + + Fvector pos = EDevice.m_Camera.GetPosition(); + frustum.CreateFromPoints(p, 4, pos); + + Fplane P; + P.build(p[0], p[1], p[2]); + if (P.classify(st) > 0) + P.build(p[2], p[1], p[0]); + frustum._add(P); + + return true; +} +//---------------------------------------------------- +void CLevelMain::RealUpdateScene() +{ + inherited::RealUpdateScene(); + if (GetEState() == esEditScene) + { + Scene->OnObjectsUpdate(); + LTools->OnObjectsUpdate(); // �������� ��� ��� ���-�� ������� � ��������� + RedrawScene(); + } +} +//--------------------------------------------------------------------------- + +void CLevelMain::ShowContextMenu(int cls) +{ + VERIFY(m_bReady); + /* POINT pt; + GetCursorPos(&pt); + fraLeftBar->miProperties->Enabled = false; + if (Scene->SelectionCount( true, cls )) fraLeftBar->miProperties->Enabled = true; + RedrawScene(true); + fraLeftBar->pmObjectContext->TrackButton = tbRightButton; + fraLeftBar->pmObjectContext->Popup(pt.x,pt.y);*/ +} +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// Common +//--------------------------------------------------------------------------- +void CLevelMain::ResetStatus() +{ + VERIFY(m_bReady); + /* if (fraBottomBar->paStatus->Caption!=""){ + fraBottomBar->paStatus->Caption=""; fraBottomBar->paStatus->Repaint(); + }*/ +} +void CLevelMain::SetStatus(LPCSTR s, bool bOutLog) +{ + VERIFY(m_bReady); + /* if (fraBottomBar->paStatus->Caption!=s){ + fraBottomBar->paStatus->Caption=s; fraBottomBar->paStatus->Repaint(); + if (bOutLog&&s&&s[0]) ELog.Msg(mtInformation,s); + }*/ +} +void CLevelMain::ProgressDraw() +{ + inherited::ProgressDraw(); + // fraBottomBar->RedrawBar(); +} +//--------------------------------------------------------------------------- +void CLevelMain::OutCameraPos() +{ + if (m_bReady) + { + xr_string s; + const Fvector &c = EDevice.m_Camera.GetPosition(); + // s.sprintf("C: %3.1f, %3.1f, %3.1f", c.x, c.y, c.z); + // const Fvector& hpb = EDevice.m_Camera.GetHPB(); + // s.sprintf(" Cam: %3.1f�, %3.1f�, %3.1f�",rad2deg(hpb.y),rad2deg(hpb.x),rad2deg(hpb.z)); + // fraBottomBar->paCamera->Caption=s; fraBottomBar->paCamera->Repaint(); + } +} +//--------------------------------------------------------------------------- +void CLevelMain::OutUICursorPos() +{ + /*VERIFY(fraBottomBar); + xr_string s; POINT pt; + GetCursorPos(&pt); + s.sprintf("Cur: %d, %d",pt.x,pt.y); + fraBottomBar->paUICursor->Caption=s; fraBottomBar->paUICursor->Repaint();*/ +} +//--------------------------------------------------------------------------- +void CLevelMain::OutGridSize() +{ + /*VERIFY(fraBottomBar); + xr_string s; + s.sprintf("Grid: %1.1f",EPrefs->grid_cell_size); + fraBottomBar->paGridSquareSize->Caption=s; fraBottomBar->paGridSquareSize->Repaint();*/ +} +//--------------------------------------------------------------------------- +void CLevelMain::OutInfo() +{ + // fraBottomBar->paSel->Caption = Tools->GetInfo(); +} +//--------------------------------------------------------------------------- +void CLevelMain::RealQuit() +{ + // frmMain->Close(); +} +//--------------------------------------------------------------------------- + +void CLevelMain::SaveSettings(CInifile *I) +{ + inherited::SaveSettings(I); + SSceneSummary::Save(I); +} +void CLevelMain::LoadSettings(CInifile *I) +{ + inherited::LoadSettings(I); + SSceneSummary::Load(I); +} + +Ivector2 CLevelMain::GetRenderMousePosition() const +{ + return MainForm->GetRenderForm()->GetMousePos(); +} + +void CLevelMain::OnDrawUI() +{ + inherited::OnDrawUI(); + UIObjectList::Update(); + UIEditLibrary::Update(); + + if (LTools->GetToolForm()) + { + LTools->GetToolForm()->OnDrawUI(); + } +} + +#include "..\Resources\resource.h" + +HICON CLevelMain::EditorIcon() +{ + return LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(MAINICON)); +} diff --git a/src/editors/LevelEditor/Kernel/UI_LevelMain.h b/src/editors/LevelEditor/Kernel/UI_LevelMain.h new file mode 100644 index 00000000000..daeb06f5cb8 --- /dev/null +++ b/src/editors/LevelEditor/Kernel/UI_LevelMain.h @@ -0,0 +1,116 @@ +#pragma once + +enum +{ + COMMAND_EXTFIRST_EXT = COMMAND_MAIN_LAST - 1, + + COMMAND_CHANGE_TARGET, + COMMAND_ENABLE_TARGET, + COMMAND_READONLY_TARGET, + COMMAND_SHOW_TARGET, + + COMMAND_SHOW_OBJECTLIST, + COMMAND_MULTI_RENAME_OBJECTS, + + COMMAND_REFRESH_SOUND_ENVS, + COMMAND_REFRESH_SOUND_ENV_GEOMETRY, + + COMMAND_CLEAN_LIBRARY, + COMMAND_LIBRARY_EDITOR, + COMMAND_LANIM_EDITOR, + COMMAND_FILE_MENU, + COMMAND_CLEAR_DEBUG_DRAW, + COMMAND_IMPORT_COMPILER_ERROR, + COMMAND_EXPORT_COMPILER_ERROR, + COMMAND_VALIDATE_SCENE, + COMMAND_RELOAD_OBJECTS, + + COMMAND_CUT, + COMMAND_COPY, + COMMAND_PASTE, + COMMAND_LOAD_SELECTION, + COMMAND_SAVE_SELECTION, + COMMAND_LOAD_LEVEL_PART, + COMMAND_UNLOAD_LEVEL_PART, + + COMMAND_CLEAR_SCENE_SUMMARY, + COMMAND_COLLECT_SCENE_SUMMARY, + COMMAND_SHOW_SCENE_SUMMARY, + COMMAND_EXPORT_SCENE_SUMMARY, + COMMAND_SCENE_HIGHLIGHT_TEXTURE, + + COMMAND_OPTIONS, + COMMAND_BUILD, + + COMMAND_MAKE_GAME, + COMMAND_MAKE_DETAILS, + COMMAND_MAKE_HOM, + COMMAND_MAKE_SOM, + COMMAND_MAKE_AIMAP, + + COMMAND_INVERT_SELECTION_ALL, + COMMAND_SELECT_ALL, + COMMAND_DESELECT_ALL, + COMMAND_DELETE_SELECTION, + COMMAND_HIDE_UNSEL, + COMMAND_HIDE_SEL, + COMMAND_HIDE_ALL, + + COMMAND_SET_SNAP_OBJECTS, + COMMAND_ADD_SEL_SNAP_OBJECTS, + COMMAND_DEL_SEL_SNAP_OBJECTS, + COMMAND_CLEAR_SNAP_OBJECTS, + COMMAND_SELECT_SNAP_OBJECTS, + COMMAND_REFRESH_SNAP_OBJECTS, + + COMMAND_LOAD_FIRSTRECENT, + + COMMAND_SHOWCONTEXTMENU, + COMMAND_SHOW_CLIP_EDITOR, +}; +//------------------------------------------------------------------------------ + +class CLevelMain : public TUI +{ + typedef TUI inherited; + + virtual void RealUpdateScene(); + virtual void RealQuit(); + +public: + C3DCursor *m_Cursor; + +public: + CLevelMain(); + virtual ~CLevelMain(); + + virtual const char* GetCaption(); + + virtual void ResetStatus(); + virtual void SetStatus(LPCSTR s, bool bOutLog = true); + virtual void ProgressDraw(); + virtual void OutCameraPos(); + virtual void OutUICursorPos(); + virtual void OutGridSize(); + virtual void OutInfo(); + + virtual LPCSTR EditorName() { return "level"; } + virtual LPCSTR EditorDesc() { return "Level Editor"; } + virtual HICON EditorIcon() override; + + void ShowContextMenu(int cls); + bool PickGround(Fvector &hitpoint, const Fvector &start, const Fvector &direction, int bSnap = 1, Fvector *hitnormal = 0); + bool SelectionFrustum(CFrustum &frustum); + + virtual bool ApplyShortCut(DWORD Key, TShiftState Shift); + virtual bool ApplyGlobalShortCut(DWORD Key, TShiftState Shift); + + // commands + virtual void RegisterCommands(); + + virtual void SaveSettings(CInifile *); + virtual void LoadSettings(CInifile *); + virtual Ivector2 GetRenderMousePosition() const; + virtual void OnDrawUI(); +}; +extern CLevelMain *LUI; diff --git a/src/editors/LevelEditor/Kernel/UI_LevelTools.cpp b/src/editors/LevelEditor/Kernel/UI_LevelTools.cpp new file mode 100644 index 00000000000..bc777b193e9 --- /dev/null +++ b/src/editors/LevelEditor/Kernel/UI_LevelTools.cpp @@ -0,0 +1,489 @@ +#include "stdafx.h" + +#define DETACH_FRAME(a) \ + if (a) \ + { \ + a = 0; \ + } +#define ATTACH_FRAME(a, b) \ + if (a) \ + { \ + b = a; \ + } + +CLevelTool *LTools = (CLevelTool *)Tools; + +TShiftState ssRBOnly; + +CLevelTool::CLevelTool() +{ + fFogness = 0.9f; + dwFogColor = 0xffffffff; + m_Flags.zero(); + m_ToolForm = 0; +} + +CLevelTool::~CLevelTool() +{ +} + +bool CLevelTool::OnCreate() +{ + inherited::OnCreate(); + target = OBJCLASS_DUMMY; + sub_target = -1; + pCurTool = 0; + ssRBOnly = ssRight; + m_Flags.set(flChangeAction, FALSE); + m_Flags.set(flChangeTarget, FALSE); + Scene->OnCreate(); + ExecCommand(COMMAND_CHANGE_TARGET, OBJCLASS_SCENEOBJECT); + m_Props = xr_new(); + m_Props->SetModifiedEvent(TOnCloseEvent(this, &CLevelTool::OnPropsModified)); + + return true; +} + +void CLevelTool::OnDestroy() +{ + inherited::OnDestroy(); + xr_delete(m_Props); + /*TfrmObjectList::DestroyForm(pObjectListForm); + TProperties::DestroyForm(m_Props);*/ + // scene destroing + if (pCurTool) + pCurTool->OnDeactivate(); + Scene->OnDestroy(); +} + +void CLevelTool::Reset() +{ + RealSetTarget(GetTarget(), estDefault, true); +} + +bool CLevelTool::MouseStart(TShiftState Shift) +{ + inherited::MouseStart(Shift); + if (pCurTool && pCurTool->pCurControl) + { + if ((pCurTool->pCurControl->Action() != etaSelect) && + (!pCurTool->IsEditable() || !pCurTool->AllowMouseStart() || (pCurTool->FClassID == OBJCLASS_DUMMY))) + return false; + + return pCurTool->pCurControl->Start(Shift); + } + return false; +} + +void CLevelTool::MouseMove(TShiftState Shift) +{ + inherited::MouseMove(Shift); + if (pCurTool && pCurTool->pCurControl) + { + if (HiddenMode()) + ExecCommand(COMMAND_UPDATE_PROPERTIES); + + pCurTool->pCurControl->Move(Shift); + } +} + +bool CLevelTool::MouseEnd(TShiftState Shift) +{ + inherited::MouseEnd(Shift); + if (pCurTool && pCurTool->pCurControl) + { + if (HiddenMode()) + ExecCommand(COMMAND_UPDATE_PROPERTIES); + + return pCurTool->pCurControl->End(Shift); + } + return false; +} + +void CLevelTool::OnObjectsUpdate() +{ + UpdateProperties(false); + if (pCurTool && pCurTool->pCurControl) + return pCurTool->OnObjectsUpdate(); +} + +bool CLevelTool::HiddenMode() +{ + if (pCurTool && pCurTool->pCurControl) + return pCurTool->pCurControl->HiddenMode(); + return false; +} + +bool CLevelTool::KeyDown(WORD Key, TShiftState Shift) +{ + if (pCurTool && pCurTool->pCurControl) + return pCurTool->pCurControl->KeyDown(Key, Shift); + + return false; +} + +bool CLevelTool::KeyUp(WORD Key, TShiftState Shift) +{ + if (pCurTool && pCurTool->pCurControl) + return pCurTool->pCurControl->KeyUp(Key, Shift); + + return false; +} + +bool CLevelTool::KeyPress(WORD Key, TShiftState Shift) +{ + if (pCurTool && pCurTool->pCurControl) + return pCurTool->pCurControl->KeyPress(Key, Shift); + + return false; +} + +void CLevelTool::RealSetAction(ETAction act) +{ + inherited::SetAction(act); + if (pCurTool) + pCurTool->SetAction(act); + + ExecCommand(COMMAND_UPDATE_TOOLBAR); + m_Flags.set(flChangeAction, FALSE); +} + +void CLevelTool::SetAction(ETAction act) +{ + // если мышь захвачена - изменим action после того как она освободится + if (UI->IsMouseCaptured() || UI->IsMouseInUse() || !false) + { + m_Flags.set(flChangeAction, TRUE); + iNeedAction = act; + } + else + RealSetAction(act); +} + +void CLevelTool::RealSetTarget(ObjClassID tgt, int sub_tgt, bool bForced) +{ + if (bForced || (target != tgt) || (sub_target != sub_tgt)) + { + target = tgt; + sub_target = sub_tgt; + if (pCurTool) + { + DETACH_FRAME(m_ToolForm); + pCurTool->OnDeactivate(); + } + pCurTool = Scene->GetTool(tgt); + VERIFY(pCurTool); + pCurTool->SetSubTarget(sub_target); + + pCurTool->OnActivate(); + + pCurTool->SetAction(GetAction()); + + if (pCurTool->IsEditable()) + ATTACH_FRAME(pCurTool->pForm, m_ToolForm); + } + + UI->RedrawScene(); + ExecCommand(COMMAND_UPDATE_TOOLBAR); + m_Flags.set(flChangeTarget, FALSE); +} + +void CLevelTool::ResetSubTarget() +{ + VERIFY(pCurTool); + pCurTool->ResetSubTarget(); +} + +void CLevelTool::SetTarget(ObjClassID tgt, int sub_tgt) +{ + // если мышь захвачена - изменим target после того как она освободится + if (UI->IsMouseCaptured() || UI->IsMouseInUse() || !false) + { + m_Flags.set(flChangeTarget, TRUE); + if (tgt == OBJCLASS_WAY && sub_tgt == 2 && target == tgt) + { + iNeedTarget = tgt; + iNeedSubTarget = (sub_target) ? 0 : 1; + } + else + { + iNeedTarget = tgt; + iNeedSubTarget = sub_tgt; + } + } + else + RealSetTarget(tgt, sub_tgt, false); +} + +ObjClassID CLevelTool::CurrentClassID() +{ + return GetTarget(); +} + +void CLevelTool::OnShowHint(AStringVec &ss) +{ + Scene->OnShowHint(ss); +} + +bool CLevelTool::Pick(TShiftState Shift) +{ + if (Scene->locked() && (esEditLibrary == UI->GetEState())) + { + UI->m_CurrentCp = MainForm->GetRenderForm()->GetMousePos(); + UI->m_StartCp = UI->m_CurrentCp; + EDevice.m_Camera.MouseRayFromPoint(UI->m_CurrentRStart, UI->m_CurrentRDir, UI->m_CurrentCp); + SRayPickInfo pinf; + return true; + } + return false; +} + +void CLevelTool::RefreshProperties() +{ +} + +void CLevelTool::ShowProperties(LPCSTR focus_to_item) +{ + RealUpdateProperties(); + + if (MainForm) + MainForm->GetPropertiesFrom()->Open(); + + UI->RedrawScene(); +} + +void CLevelTool::RealUpdateProperties() +{ + m_Props->ClearProperties(); + if (/*m_Props->Visible*/ 1) + { + if (m_Props->IsModified()) + Scene->UndoSave(); + + ObjectList lst; + PropItemVec items; + + // scene common props + Scene->FillProp("", items, CurrentClassID()); + + m_Props->AssignItems(items); + } + m_Flags.set(flUpdateProperties, FALSE); +} + +void CLevelTool::OnPropsClose() +{ +} + +void CLevelTool::OnPropsModified() +{ + Scene->Modified(); + UI->RedrawScene(); +} + +bool CLevelTool::IfModified() +{ + return false; +} + +void CLevelTool::ZoomObject(BOOL bSelectedOnly) +{ + if (!Scene->locked()) + { + Scene->ZoomExtents(CurrentClassID(), bSelectedOnly); + } + else + { + if (UI->GetEState() == esEditLibrary) + { + // TfrmEditLibrary::ZoomObject(); + } + } +} + +void CLevelTool::GetCurrentFog(u32 &fog_color, float &s_fog, float &e_fog) +{ + s_fog = psDeviceFlags.is(rsFog) ? (1.0f - fFogness) * 0.85f * UI->ZFar() : 0.99f * UI->ZFar(); + e_fog = psDeviceFlags.is(rsFog) ? 0.91f * UI->ZFar() : UI->ZFar(); + fog_color = dwFogColor; +} + +LPCSTR CLevelTool::GetInfo() +{ + int cnt = Scene->SelectionCount(true, CurrentClassID()); + return make_string(" Sel: %d", cnt).c_str(); +} + +void CLevelTool::OnFrame() +{ + Scene->OnFrame(EDevice.fTimeDelta); + EEditorState est = UI->GetEState(); + if ((est == esEditScene) || (est == esEditLibrary) || (est == esEditLightAnim)) + { + if (true /*!UI->IsMouseCaptured()*/) + { + // если нужно изменить target выполняем после того как мышь освободится + if (m_Flags.is(flChangeTarget)) + RealSetTarget(iNeedTarget, iNeedSubTarget, false); + // если нужно изменить action выполняем после того как мышь освободится + if (m_Flags.is(flChangeAction)) + RealSetAction(ETAction(iNeedAction)); + } + if (m_Flags.is(flUpdateProperties)) + RealUpdateProperties(); + if (m_Flags.is(flUpdateObjectList)) + RealUpdateObjectList(); + } +} + +void CLevelTool::RenderEnvironment() +{ + // draw sky + EEditorState est = UI->GetEState(); + switch (est) + { + case esEditLightAnim: + case esEditScene: + if (psDeviceFlags.is(rsEnvironment)) + { + } + } +} + +void CLevelTool::Render() +{ + // Render update + ::Render->Calculate(); + ::Render->Render(); + + EEditorState est = UI->GetEState(); + // draw scene + switch (est) + { + case esEditLibrary: + UIEditLibrary::OnRender(); + break; + case esEditLightAnim: + case esEditScene: + Scene->Render(EDevice.m_Camera.GetTransform()); + //. if (psDeviceFlags.is(rsEnvironment)) g_pGamePersistent->Environment().RenderLast (); + break; + case esBuildLevel: + Builder.OnRender(); + break; + } + // draw cursor + LUI->m_Cursor->Render(); + + inherited::Render(); +} + +void CLevelTool::ShowObjectList() +{ +} + +void CLevelTool::RealUpdateObjectList() +{ + m_Flags.set(flUpdateObjectList, FALSE); +} + +bool CLevelTool::IsModified() +{ + return Scene->IsUnsaved(); +} + +bool CLevelTool::RayPick(const Fvector &start, const Fvector &dir, float &dist, Fvector *pt, Fvector *n) +{ + if (Scene->ObjCount() && (UI->GetEState() == esEditScene)) + { + SRayPickInfo pinf; + pinf.inf.range = dist; + if (Scene->RayPickObject(dist, start, dir, OBJCLASS_SCENEOBJECT, &pinf, 0)) + { + dist = pinf.inf.range; + if (pt) + pt->set(pinf.pt); + if (n) + { + const Fvector *PT[3]; + pinf.e_mesh->GetFacePT(pinf.inf.id, PT); + n->mknormal(*PT[0], *PT[1], *PT[2]); + } + return true; + } + } + Fvector N = {0.f, -1.f, 0.f}; + Fvector P = {0.f, 0.f, 0.f}; + Fplane PL; + PL.build(P, N); + float d; + if (PL.intersectRayDist(start, dir, d) && (d <= dist)) + { + dist = d; + if (pt) + pt->mad(start, dir, dist); + if (n) + n->set(N); + return true; + } + else + return false; +} + +bool CLevelTool::GetSelectionPosition(Fmatrix &result) +{ + if (pCurTool) + { + Fvector center; + Fbox BB; + BB.invalidate(); + // pCurTool->GetBBox (BB, true); + + const CCustomObject *object = pCurTool->LastSelected(); + if (!object) + return false; + + const_cast(object)->GetBox(BB); + + BB.getcenter(center); + center.y = BB.vMax.y; + + Fvector2 pt_ss; + pt_ss.set(10000, -10000); + Fvector pt_ss_3d; + BB.setb(center, Fvector().set(1.0f, 1.0f, 1.0f)); + for (int k = 0; k < 8; ++k) + { + Fvector pt; + BB.getpoint(k, pt); + EDevice.mFullTransform.transform(pt_ss_3d, pt); + + pt_ss.x = _min(pt_ss.x, pt_ss_3d.y); + pt_ss.y = _max(pt_ss.y, pt_ss_3d.y); + } + + float r_bb_ss = pt_ss.y - pt_ss.x; + clamp(r_bb_ss, 0.0f, 0.10f); + float des_radius = 0.2f; + float csale = des_radius / r_bb_ss; + + result.scale(csale, csale, csale); + result.c = center; + return true; + } + else + return false; +} +void CLevelTool::Simulate() +{ + if (!g_scene_physics.Simulating()) + g_scene_physics.CreateShellsSelected(); + else + g_scene_physics.DestroyAll(); + UI->RedrawScene(); + ExecCommand(COMMAND_REFRESH_UI_BAR); +} +void CLevelTool::UseSimulatePositions() +{ + g_scene_physics.UseSimulatePoses(); +} diff --git a/src/editors/LevelEditor/Kernel/UI_LevelTools.h b/src/editors/LevelEditor/Kernel/UI_LevelTools.h new file mode 100644 index 00000000000..513f9a38636 --- /dev/null +++ b/src/editors/LevelEditor/Kernel/UI_LevelTools.h @@ -0,0 +1,157 @@ +#pragma once + +// refs +class ESceneToolBase; +class TfrmObjectList; + +#define estDefault 0 +#define CHECK_SNAP(R, A, C) \ + { \ + R += A; \ + if (fabsf(R) >= C) \ + { \ + A = snapto(R, C); \ + R = 0; \ + } \ + else \ + { \ + A = 0; \ + } \ + } + +class CLevelTool : public CToolCustom +{ + typedef CToolCustom inherited; + UIToolCustom *m_ToolForm; + int sub_target; + ObjClassID target; + + Flags32 m_Flags; + + enum + { + flChangeAction = (1 << 0), + flChangeTarget = (1 << 1), + flUpdateProperties = (1 << 2), + flUpdateObjectList = (1 << 3) + // flSimulating = (1<<4) + }; + + int iNeedAction; + ObjClassID iNeedTarget; + int iNeedSubTarget; + + ESceneToolBase *pCurTool; + + TfrmObjectList *pObjectListForm; + + void SetTargetAction(); + + void RealSetAction(ETAction act); + void RealSetTarget(ObjClassID tgt, int sub_tgt, bool bForced); //=false); + + UIPropertiesForm *m_Props; + void OnPropsModified(); + void OnPropsClose(); + + void RealUpdateProperties(); + void RealUpdateObjectList(); + +public: + float fFogness; + u32 dwFogColor; + xr_string m_LastSelectionName; + +public: + CLevelTool(); + virtual ~CLevelTool(); + + IC UIToolCustom *GetToolForm() const { return m_ToolForm; } + IC UIPropertiesForm *GetProperties() const { return m_Props; } + IC ObjClassID GetTarget() { return target; } + IC int GetSubTarget() { return sub_target; } + virtual void SetAction(ETAction act); + void SetTarget(ObjClassID tgt, int sub_tgt); + + virtual void SetFog(u32 fog_color, float fogness) + { + dwFogColor = fog_color; + fFogness = fogness; + } + virtual void GetCurrentFog(u32 &fog_color, float &s_fog, float &e_fog); + + virtual void Render(); + virtual void RenderEnvironment(); + virtual void OnFrame(); + + virtual bool OnCreate(); + virtual void OnDestroy(); + + virtual bool IfModified(); + virtual bool IsModified(); + virtual void Modified() { ; } + + virtual LPCSTR GetInfo(); + + virtual void ZoomObject(BOOL bSelOnly); + + virtual bool Load(LPCSTR name) { return true; } + virtual bool Save(LPCSTR name, bool bInternal = false) { return true; } + virtual void Reload() { ; } + + virtual void OnDeviceCreate() { ; } + virtual void OnDeviceDestroy() { ; } + + virtual void Clear() { inherited::Clear(); } + + virtual void OnShowHint(AStringVec &SS); + + virtual bool MouseStart(TShiftState Shift); + virtual bool MouseEnd(TShiftState Shift); + virtual void MouseMove(TShiftState Shift); + virtual bool HiddenMode(); + virtual bool KeyDown(WORD Key, TShiftState Shift); + virtual bool KeyUp(WORD Key, TShiftState Shift); + virtual bool KeyPress(WORD Key, TShiftState Shift); + + virtual bool Pick(TShiftState Shift); + virtual bool RayPick(const Fvector &start, const Fvector &dir, float &dist, Fvector *pt, Fvector *n); + + virtual void ShowProperties(LPCSTR focused_item); + virtual void UpdateProperties(BOOL bForced) + { + m_Flags.set(flUpdateProperties | flUpdateObjectList, TRUE); + if (bForced) + OnFrame(); + } + virtual void RefreshProperties(); + +private: + virtual void Simulate(); + virtual void UseSimulatePositions(); + +public: + // specified functions + void Reset(); + + void ResetSubTarget(); + + void OnObjectsUpdate(); + + ObjClassID CurrentClassID(); + + void ShowObjectList(); + virtual bool GetSelectionPosition(Fmatrix &result); + + // commands + CCommandVar CommandChangeTarget(CCommandVar p1, CCommandVar p2); + CCommandVar CommandShowObjectList(CCommandVar p1, CCommandVar p2); + CCommandVar CommandEnableTarget(CCommandVar p1, CCommandVar p2); + CCommandVar CommandShowTarget(CCommandVar p1, CCommandVar p2); + CCommandVar CommandReadonlyTarget(CCommandVar p1, CCommandVar p2); + CCommandVar CommandMultiRenameObjects(CCommandVar p1, CCommandVar p2); +}; +extern CLevelTool *LTools; + +extern ECORE_API void ResetActionToSelect(); +extern TShiftState ssRBOnly; diff --git a/src/editors/LevelEditor/Kernel/stdafx.cpp b/src/editors/LevelEditor/Kernel/stdafx.cpp new file mode 100644 index 00000000000..13076240827 --- /dev/null +++ b/src/editors/LevelEditor/Kernel/stdafx.cpp @@ -0,0 +1,15 @@ +#include "stdafx.h" + +u32 dm_size = 24; +u32 dm_cache1_line = 12; // dm_size*2/dm_cache1_count +u32 dm_cache_line = 49; // dm_size+1+dm_size +u32 dm_cache_size = 2401; // dm_cache_line*dm_cache_line +float dm_fade = 47.5; // float(2*dm_size)-.5f; +u32 dm_current_size = 24; +u32 dm_current_cache1_line = 12; // dm_current_size*2/dm_cache1_count +u32 dm_current_cache_line = 49; // dm_current_size+1+dm_current_size +u32 dm_current_cache_size = 2401; // dm_current_cache_line*dm_current_cache_line +float dm_current_fade = 47.5; // float(2*dm_current_size)-.5f; + +float ps_current_detail_density = 0.6f; +float ps_current_detail_height = 1.f; diff --git a/src/editors/LevelEditor/Kernel/stdafx.h b/src/editors/LevelEditor/Kernel/stdafx.h new file mode 100644 index 00000000000..a48567ed96f --- /dev/null +++ b/src/editors/LevelEditor/Kernel/stdafx.h @@ -0,0 +1,157 @@ +#pragma once +#include "../xrECore/stdafx.h" +#include "../xrECore/Editor/device.h" +#include "../xrECore/Editor/UI_MainCommand.h" +#include "../xrECore/Editor/UI_ToolsCustom.h" +#include "../xrECore/Editor/ui_main.h" +#include "../xrECore/Editor/GeometryCollector.h" +#include "../xrECore/Editor/EditorPreferences.h" +#include "../xrECore/Editor/render.h" +#include "../xrECore/Editor/UIRenderForm.h" +#include "../xrECore/Editor/ELog.h" +#include "../xrECore/Editor/tlsprite.h" +#include "../xrECore/Editor/EditObject.h" +#include "../xrECore/Editor/EditMesh.h" +#include "../xrECore/Editor/D3DUtils.h" +#include "../xrEcore/Editor/PhysicsShellHolderEditorBase.h" +#include "utils/ETools/ETools.h" +#include "../xrECore/Engine/Texture.h" +#include "../xrECore/Editor/Library.h" +#include "../xrECore/Editor/ImageManager.h" +#include "../xrECore/Editor/pick_defs.h" +#include "../xrECore/Editor/SoundManager.h" +#include "../xrECore/Editor/EDetailModel.h" +#include "../xrECore/Engine/Image.h" +#include "../xrECore/Engine/guid_generator.h" +#include "../xrECore/Editor/ExportSkeleton.h" +#include "../FreeMagic/MgcAppr3DPlaneFit.h" +#include "../FreeMagic/MgcEigen.h" +#include "../FreeMagic/MgcLinearSystem.h" +#include "../FreeMagic/MgcConvexHull2D.h" + +#include "xrCore/Containers/FixedMap.h" +#include "xrCommon/xr_map.h" + +#include "xrEngine/LightAnimLibrary.h" +#include "xrCore/Animation/motion.hpp" +#include "xrCore/Animation/envelope.hpp" +#include "Common/LevelStructure.hpp" +#include "Engine/communicate.h" +#include "xrEngine/xrHemisphere.h" +#include "Common/LevelGameDef.h" +#include "Layers/xrRender/SkeletonAnimated.h" +#include "xrEngine/ObjectAnimator.h" +#include "xrEngine/xr_efflensflare.h" +#include "Layers/xrRender/du_box.h" + +#include "xrCommon/xr_list.h" +#include "xrCDB/xrCDB.h" +#include "xrCDB/ISpatial.h" +#include "Common/RDevice.h" +#include "include/xrRender/ParticleCustom.h" +#include "Layers/xrRender/DetailManager.h" +#include "Layers/xrRender/ParticleEffect.h" +#include "Layers/xrRender/ParticleEffectDef.h" +#include "Layers/xrRender/ParticleGroup.h" + +#include "xrCDB/intersect.hpp" +#include "xrServerEntities/xrMessages.h" +#include "xrServerEntities/ShapeData.h" +#include "xrServerEntities/xrServer_Objects_Abstract.h" +#include "utils/xrSE_Factory/xrSE_Factory_import_export.h" + +#ifndef _DEBUG +#define USE_ARENA_ALLOCATOR +#endif + +#include "UI/UITopBarForm.h" +#include "UI/UIMainMenuForm.h" +#include "UI/UILeftBarForm.h" +#include "UI/UILPropertiesFrom.h" +#include "UI/UIMainForm.h" +#include "UI/Tools/UIToolCustom.h" +#include "UI/UIPropertiesModal.h" +#include "UI/Tools/UIShapeTool.h" +#include "UI/UIEditLibrary.h" + +#include "Tools/ESceneClassList.h" + +#include "UI_LevelMain.h" +#include "UI_LevelTools.h" + +#include "Utils/Cursor3D.h" +#include "Utils/portalutils.h" +#include "Utils/iniStreamImpl.h" +#include "Utils/SoundManager_LE.h" +#include "Utils/LevelPreferences.h" +#include "Utils/Custom2DProjector.h" +#include "Utils/GeometryPartExtractor.h" + +#include "Entry/CustomObject.h" +#include "Entry/Glow/glow.h" +#include "Entry/Group/GroupObject.h" +#include "Entry/Light/ELight.h" +#include "Entry/Particles/EParticlesObject.h" +#include "Entry/Portal/portal.h" +#include "Entry/Sector/sector.h" +#include "Entry/Shape/EShape.h" +#include "Entry/Sound/ESound_Environment.h" +#include "Entry/Sound/ESound_Source.h" +#include "Entry/Spawn/SpawnPoint.h" +#include "Entry/StaticObject/SceneObject.h" +#include "Entry/WayPoint/WayPoint.h" + +#include "Tools/Base/ESceneControlsCustom.h" +#include "Tools/Base/ESceneCustomMTools.h" +#include "Tools/Base/ESceneCustomOTools.h" +#include "Tools/Base/ESceneDummyTools.h" + +#include "Tools/AIMap/ESceneAIMapTools_Export.h" +#include "Tools/AIMap/ESceneAIMapTools.h" +#include "Tools/AIMap/ESceneAIMapControls.h" +#include "Tools/Details/ESceneDOTools.h" +#include "Tools/FogVolume/ESceneFogVolumeTools.h" +#include "Tools/Group/ESceneGroupTools.h" +#include "Tools/Group/ESceneGroupControls.h" +#include "Tools/Light/ESceneLightTools.h" +#include "Tools/Particles/EScenePSTools.h" +#include "Tools/Particles/EScenePSControls.h" +#include "Tools/Sector/ESceneSectorTools.h" +#include "Tools/Sector/ESceneSectorControls.h" +#include "Tools/Portal/EScenePortalTools.h" +#include "Tools/Portal/EScenePortalControls.h" +#include "Tools/Shape/ESceneShapeTools.h" +#include "Tools/Shape/ESceneShapeControls.h" +#include "Tools/Sound/ESceneSoundSrcTools.h" +#include "Tools/Sound/ESceneSoundEnvTools.h" +#include "Tools/Spawn/ESceneSpawnTools.h" +#include "Tools/Spawn/ESceneSpawnControls.h" +#include "Tools/StaticObject/ESceneObjectTools.h" +#include "Tools/StaticObject/ESceneObjectControls.h" +#include "Tools/Wallmark/ESceneWallmarkTools.h" +#include "Tools/Wallmark/ESceneWallmarkControls.h" +#include "Tools/WayPoint/ESceneWayTools.h" +#include "Tools/WayPoint/ESceneWayControls.h" +#include "Tools/Glow/ESceneGlowTools.h" + +#include "Scene/scene.h" +#include "Scene/LEPhysics.h" +#include "Scene/SceneGraph.h" +#include "Scene/SceneSummaryInfo.h" +#include "Builder/Builder.h" + +#include "UI/UIDOOneColor.h" +#include "UI/UIDOShuffle.h" +#include "UI/UIObjectList.h" + +#include "UI/Tools/UIAIMapTool.h" +#include "UI/Tools/UIDOTool.h" +#include "UI/Tools/UIFogVolTool.h" +#include "UI/Tools/UIGroupTool.h" +#include "UI/Tools/UILightTool.h" +#include "UI/Tools/UIObjectTool.h" +#include "UI/Tools/UIParticlesTool.h" +#include "UI/Tools/UIPortalTool.h" +#include "UI/Tools/UISectorTool.h" +#include "UI/Tools/UISpawnTool.h" +#include "UI/Tools/UIWayTool.h" diff --git a/src/editors/LevelEditor/LevelEditor.vcxproj b/src/editors/LevelEditor/LevelEditor.vcxproj new file mode 100644 index 00000000000..79c2799203f --- /dev/null +++ b/src/editors/LevelEditor/LevelEditor.vcxproj @@ -0,0 +1,315 @@ + + + + + + + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B} + LevelEditor + + + + + + + Application + + + + + + + + + + + + stdafx.h + $(xrExternals)libvorbis\include;$(xrExternals)libogg\include;%(AdditionalIncludeDirectories) + _EDITOR;_WINDOWS;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Create + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {1daec516-e52c-4a3c-a4da-ae3553e6e0f8} + + + {65cbb9d0-fbc6-41a4-8316-f5e9b5d7fb33} + + + {7885cf3c-ee04-4c67-9467-1fbf9a36b037} + + + {3ad26fd3-4f52-4e22-a4cf-ad4c49e74c61} + + + {a19b1df2-82ec-4364-8bdf-85d13a1c89b5} + + + {a0f7d1fb-59a7-4717-a7e4-96f37e91998e} + + + {98d24a3d-7666-4c11-9d6e-b10393ce8cba} + + + {ccca7859-eb86-493e-9b53-c4235f45b3c5} + + + {dcc5b76d-be13-4d1f-be14-75d0fa678340} + + + {9187be98-531a-4276-b78e-dba3c8ab8447} + + + {6d47afc7-0557-4bbf-8902-b248f3621419} + + + {7e28883c-db86-4ee8-813a-991ba20c68c9} + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/editors/LevelEditor/LevelEditor.vcxproj.filters b/src/editors/LevelEditor/LevelEditor.vcxproj.filters new file mode 100644 index 00000000000..734bfe7f7b0 --- /dev/null +++ b/src/editors/LevelEditor/LevelEditor.vcxproj.filters @@ -0,0 +1,805 @@ + + + + + {8de59519-90ea-45b4-aa15-357dbcb5c246} + + + {820cd9c6-8985-464f-82cf-f053ef14ef09} + + + {04a1bd6e-c754-494c-9fa6-1fbe7ef47912} + + + {3e179e6c-ce08-4955-a1ad-7b268a674b30} + + + {d77891c4-006b-41e0-98a2-975029f38952} + + + {3ae2edbd-3917-49a7-b0ec-3e0002dfbbb0} + + + {a0eb3571-4d90-4a1a-b2dd-23dc2d864e79} + + + {6b368f40-1040-4abb-9db4-946b5a937e8c} + + + {179ab143-6290-443a-bd97-f0576e8bf3ef} + + + {c4a0505e-3bde-4064-9732-9d61e3003104} + + + {aa6c8d9b-0eca-4bf0-a5a6-6c1412d24678} + + + {726316a5-fd58-4b2b-8d47-72f5e002e373} + + + {bc25a0f1-39cd-43bb-9e44-4e19065279bb} + + + {811c2ddc-88b1-436f-88fa-5be83b7cb2b2} + + + {90586b40-8993-4e6b-a1dc-bfcde9487ce2} + + + {5441db24-0d16-4748-ab11-0c3ac153fb67} + + + {0893dd87-17b5-4f40-98ee-4b678d505203} + + + {c25d7765-53f6-4855-834e-f9fbe02abb93} + + + {42163d90-a985-4187-9e5a-acea962ccfd9} + + + {6a74b957-227e-4bf4-92bf-7a9e28930a1e} + + + {16c87ce6-30ce-4cf1-8312-a2613886324b} + + + {6f64b3e1-9eb4-4a7d-90e5-e9e5f26eaf0f} + + + {ad0e582f-7ecf-49f2-9f7c-84ec52daa67e} + + + {2f853909-07fd-4a6a-b1d9-228867e00d2a} + + + {3448225e-5b50-4fdf-8207-0fd03756fed0} + + + {3094e49d-1ca9-42e1-9b60-e771e443ae09} + + + {19c9c444-a4a5-4161-b118-24993d238f1e} + + + {523a8a0c-6bb3-4ce1-b55d-1e914a9abd69} + + + {e1f6b1e0-5dea-44ff-a7e6-cd7a32795b25} + + + {0b7b0716-10c3-4a75-a22d-f55ad1bc8d96} + + + {a8f068bf-f3ab-46d9-85f2-8a63b975bc13} + + + {1a32b836-ff5c-40db-9bd7-44ec715eae26} + + + {080758fa-1e11-4129-bf32-be15d4bafcc4} + + + {36e55bf5-7628-4887-8704-920034464f99} + + + {ed99d204-7e34-4c20-b8ed-8fcc3bafb44b} + + + {b0fa3245-b937-4131-a909-30df1bd5cd56} + + + {d2191ea4-5b63-46db-a2a6-d5a468e9f521} + + + {57fd408d-c43a-41f0-b942-32593fc55853} + + + + + UI + + + UI + + + UI + + + UI + + + ServerEntities + + + UI\Tools + + + UI + + + UI\Tools + + + UI + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI + + + UI + + + UI + + + UI + + + Kernel + + + Kernel + + + Kernel + + + Kernel + + + Utils + + + Utils + + + Utils + + + Utils + + + Utils + + + Utils + + + Utils + + + Builder + + + Builder + + + Builder + + + Builder + + + Builder + + + Builder + + + Builder + + + Scene + + + Scene + + + Scene + + + Scene + + + Scene + + + Scene + + + Scene + + + Scene + + + Scene + + + Scene + + + Scene + + + Entry + + + Entry + + + Entry + + + Entry\Glow + + + Entry\Group + + + Entry\Group + + + Entry\Light + + + Entry\Light + + + Entry\Light + + + Entry\Particles + + + Entry\Portal + + + Entry\Sector + + + Entry\Shape + + + Entry\Sound + + + Entry\Sound + + + Entry\Spawn + + + Entry\StaticObject + + + Entry\StaticObject + + + Entry\WayPoint + + + Tools\AIMap + + + Tools\AIMap + + + Tools\AIMap + + + Tools\AIMap + + + Tools\AIMap + + + Tools\AIMap + + + Tools\AIMap + + + Tools\AIMap + + + Tools\Base + + + Tools\Base + + + Tools\Base + + + Tools\Base + + + Tools\Base + + + Tools\Base + + + Tools\Details + + + Tools\Details + + + Tools\Details + + + Tools\Details + + + Tools\FogVolume + + + Tools\Glow + + + Tools\Glow + + + Tools\Group + + + Tools\Group + + + Tools\Group + + + Tools\Light + + + Tools\Light + + + Tools\Particles + + + Tools\Particles + + + Tools\Particles + + + Tools\Portal + + + Tools\Portal + + + Tools\Portal + + + Tools\Sector + + + Tools\Sector + + + Tools\Sector + + + Tools\Shape + + + Tools\Shape + + + Tools\Shape + + + Tools\Sound + + + Tools\Sound + + + Tools\Sound + + + Tools\Sound + + + Tools\Spawn + + + Tools\Spawn + + + Tools\Spawn + + + Tools\StaticObject + + + Tools\StaticObject + + + Tools\StaticObject + + + Tools\StaticObject + + + Tools\Wallmark + + + Tools\Wallmark + + + Tools\WayPoint + + + Tools\WayPoint + + + Tools\WayPoint + + + Render + + + Render + + + Render + + + Render + + + Render + + + ServerEntities + + + Render + + + Render + + + Render + + + + + UI + + + UI + + + UI + + + UI + + + UI + + + UI\Tools + + + UI + + + UI\Tools + + + UI\Tools + + + UI + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI\Tools + + + UI + + + UI + + + UI + + + UI + + + Resources + + + Kernel + + + Kernel + + + Kernel + + + Utils + + + Utils + + + Utils + + + Utils + + + Utils + + + Utils + + + Utils + + + Builder + + + Scene + + + Scene + + + Scene + + + Scene + + + Scene + + + Entry + + + Entry\Glow + + + Entry\Group + + + Entry\Light + + + Entry\Particles + + + Entry\Portal + + + Entry\Sector + + + Entry\Shape + + + Entry\Sound + + + Entry\Sound + + + Entry\Spawn + + + Entry\StaticObject + + + Entry\WayPoint + + + Tools + + + Tools\AIMap + + + Tools\AIMap + + + Tools\AIMap + + + Tools\Base + + + Tools\Base + + + Tools\Base + + + Tools\Base + + + Tools\Details + + + Tools\FogVolume + + + Tools\Glow + + + Tools\Group + + + Tools\Group + + + Tools\Light + + + Tools\Particles + + + Tools\Particles + + + Tools\Portal + + + Tools\Portal + + + Tools\Sector + + + Tools\Sector + + + Tools\Shape + + + Tools\Shape + + + Tools\Sound + + + Tools\Sound + + + Tools\Spawn + + + Tools\Spawn + + + Tools\StaticObject + + + Tools\StaticObject + + + Tools\Wallmark + + + Tools\Wallmark + + + Tools\WayPoint + + + Tools\WayPoint + + + Render + + + Render + + + ServerEntities + + + + + Resources + + + + + Resources + + + + + + \ No newline at end of file diff --git a/src/editors/LevelEditor/Resources/IconLE.ico b/src/editors/LevelEditor/Resources/IconLE.ico new file mode 100644 index 00000000000..4189de2c14a Binary files /dev/null and b/src/editors/LevelEditor/Resources/IconLE.ico differ diff --git a/src/editors/LevelEditor/Resources/LevelEditor.rc b/src/editors/LevelEditor/Resources/LevelEditor.rc new file mode 100644 index 00000000000..df54d1a0567 --- /dev/null +++ b/src/editors/LevelEditor/Resources/LevelEditor.rc @@ -0,0 +1,71 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// () resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_RUS) +LANGUAGE LANG_RUSSIAN, SUBLANG_DEFAULT +#pragma code_page(1251) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +MAINICON ICON "IconLE.ico" + +#endif // () resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/editors/LevelEditor/Resources/resource.h b/src/editors/LevelEditor/Resources/resource.h new file mode 100644 index 00000000000..5f898022da6 --- /dev/null +++ b/src/editors/LevelEditor/Resources/resource.h @@ -0,0 +1,17 @@ +//{{NO_DEPENDENCIES}} +// ���������� ����, ��������� � Microsoft Visual C++. +// ������������ LevelEditor.rc +// +#define IDI_ICON2 102 +#define MAINICON 102 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 103 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/editors/LevelEditor/Scene/LEPhysics.cpp b/src/editors/LevelEditor/Scene/LEPhysics.cpp new file mode 100644 index 00000000000..bcaba0130a0 --- /dev/null +++ b/src/editors/LevelEditor/Scene/LEPhysics.cpp @@ -0,0 +1,251 @@ +#include "stdafx.h" +#include "mesh_data.h" +#include "../../xrphysics/iphworld.h" + +CScenePhyscs g_scene_physics; + +bool CScenePhyscs ::Simulating() +{ + return !!physics_world(); +} + +BOOL GetStaticCformData(const Fmatrix &parent, CEditableMesh *mesh, CEditableObject *object, Fvector *verts, int &vert_cnt, int &vert_it, CDB::TRI *faces, int &face_cnt, int &face_it); +BOOL GetStaticCformData(CSceneObject *obj, mesh_build_data &data, bool b_selected_only) +{ + Fmatrix T = obj->_Transform(); + CEditableObject *O = obj->GetReference(); + + for (EditMeshIt M = O->FirstMesh(); M != O->LastMesh(); M++) + { + // CSector* S = PortalUtils.FindSector(obj,*M); + // int sect_num = S?S->m_sector_num:m_iDefaultSectorNum; + // if (!BuildMesh(T,O,*M,sect_num,l_verts,l_vert_cnt,l_vert_it,l_faces,l_face_cnt,l_face_it,l_smgroups,obj->_Transform())) + + if (!::GetStaticCformData(T, *M, O, data.l_verts, data.l_vert_cnt, data.l_vert_it, data.l_faces, data.l_face_cnt, data.l_face_it)) + return FALSE; + } + + return FALSE; +} +// BOOL GetMuStaticCformData( CSceneObject* obj,mesh_build_data &data, bool b_selected_only ); +BOOL GetStaticCformData(ObjectList &lst, mesh_build_data &data, bool b_selected_only) +{ + + BOOL bResult = TRUE; + + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + { + // pb->Inc((*_F)->Name); + // if (UI->NeedAbort()) break; + if (b_selected_only && !(*_F)->Selected()) + continue; + + switch ((*_F)->FClassID) + { + // case OBJCLASS_LIGHT: + // bResult = BuildLight((CLight*)(*_F)); + // break; + // case OBJCLASS_GLOW: + // bResult = BuildGlow((CGlow*)(*_F)); + // break; + /// case OBJCLASS_PORTAL: + // l_portals.push_back(b_portal()); + // BuildPortal(&l_portals.back(),(CPortal*)(*_F)); + // break; + case OBJCLASS_SCENEOBJECT: + { + CSceneObject *obj = (CSceneObject *)(*_F); + if (obj->IsStatic()) + bResult = GetStaticCformData(obj, data, b_selected_only); + else if (obj->IsMUStatic()) + bResult = GetStaticCformData(obj, data, b_selected_only); + } + break; + /* case OBJCLASS_GROUP:{ + CGroupObject* group = (CGroupObject*)(*_F); + + ObjectList grp_lst; + group->GetObjects (grp_lst); + + bResult = ParseStaticObjects(grp_lst, group->Name, b_selected_only); + }break; */ + } // end switch + } + // UI->ProgressEnd(pb); + return bResult; +} + +void GetBox(Fbox &box, const Fvector *verts, u32 cnt) +{ + box.invalidate(); + for (u32 i = 0; i < cnt; ++i) + box.modify(verts[i]); +} + +void CScenePhyscs::OnSceneModified() +{ + ObjClassID cls = LTools->CurrentClassID(); + if (cls == OBJCLASS_SCENEOBJECT || cls == OBJCLASS_GROUP) + UpdateLevelCollision(); +} +bool CScenePhyscs::CreateObjectSpace(bool b_selected_only) +{ + + ObjClassID cls = LTools->CurrentClassID(); + if (cls == OBJCLASS_DUMMY) + return FALSE; + ESceneToolBase *pCurrentTool = Scene->GetOTool(cls); + + bool bResult = true; + + mesh_build_data build_data; + + if (b_selected_only) + { + if (pCurrentTool) + pCurrentTool->GetStaticDesc(build_data.l_vert_cnt, build_data.l_face_cnt, b_selected_only, true); + } + else + { + SceneToolsMapPairIt t_it = Scene->FirstTool(); + SceneToolsMapPairIt t_end = Scene->LastTool(); + for (; t_it != t_end; ++t_it) + { + ESceneToolBase *mt = t_it->second; + if (mt) + mt->GetStaticDesc(build_data.l_vert_cnt, build_data.l_face_cnt, b_selected_only, true); + + // if (!mt->ExportStatic(this,b_selected_only)) + // {bResult = FALSE; break;} + } + } + if (!bResult) + return false; + + build_data.l_faces = xr_alloc(build_data.l_face_cnt); + build_data.l_verts = xr_alloc(build_data.l_vert_cnt); + if (b_selected_only) + { + if (pCurrentTool) + if (!pCurrentTool->GetStaticCformData(build_data, b_selected_only)) + { + bResult = false; + } + } + else + { + SceneToolsMapPairIt t_it = Scene->FirstTool(); + SceneToolsMapPairIt t_end = Scene->LastTool(); + for (; t_it != t_end; ++t_it) + { + ESceneToolBase *mt = t_it->second; + if (mt) + if (!mt->GetStaticCformData(build_data, b_selected_only)) + { + bResult = false; + break; + } + } + } + VERIFY(!m_object_space); + hdrCFORM H; + H.vertcount = build_data.l_vert_cnt; + H.facecount = build_data.l_face_cnt; + H.version = CFORM_CURRENT_VERSION; + GetBox(H.aabb, build_data.l_verts, build_data.l_vert_cnt); + VERIFY(!m_object_space); + m_object_space = mesh_create_object_space(build_data.l_verts, build_data.l_faces, H, 0); + + xr_free(build_data.l_faces); + xr_free(build_data.l_verts); + + b_update_level_collision = false; + + return bResult; +} + +CScenePhyscs::~CScenePhyscs() +{ + // DestroyAll () ; + DestroyObjectSpace(); + R_ASSERT(!m_object_space); +} + +void CScenePhyscs::DestroyObjectSpace() +{ + destroy_object_space(m_object_space); +} +void CScenePhyscs::DestroyWorld() +{ + if (physics_world()) + destroy_physics_world(); +} + +void CScenePhyscs::CreateWorld() +{ + + VERIFY(!physics_world()); + //set_mtl_lib(&GMLib); + + VERIFY(m_object_space); + create_physics_world(false, m_object_space, 0); +} + +void CreatePhysicsShellsSelected() +{ + ObjectList lst; + if (Scene->GetQueryObjects(lst, OBJCLASS_SPAWNPOINT, 1, 1, 0)) + { + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + CSpawnPoint *O = dynamic_cast(*it); + R_ASSERT(O); + if (O->Selected() && O->ObjectKinematics()) + O->CreatePhysicsShell(&O->FTransform); + } + } +} +void CScenePhyscs::UseSimulatePoses() +{ + ObjectList lst; + if (Scene->GetQueryObjects(lst, OBJCLASS_SPAWNPOINT, 1, 1, 0)) + { + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + CSpawnPoint *O = dynamic_cast(*it); + R_ASSERT(O); + if (O->Selected()) + O->UseSimulatePose(); + } + } +} + +void DestroyPhysicsShells() +{ + ObjectList lst; + if (Scene->GetQueryObjects(lst, OBJCLASS_SPAWNPOINT, -1, -1, 0)) + { + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + CSpawnPoint *O = dynamic_cast(*it); + R_ASSERT(O); + O->DeletePhysicsShell(); + } + } +} + +void CScenePhyscs::CreateShellsSelected() +{ + if (b_update_level_collision) + DestroyObjectSpace(); + if (!m_object_space) + CreateObjectSpace(false); + + CreateWorld(); + CreatePhysicsShellsSelected(); +} +void CScenePhyscs::DestroyAll() +{ + DestroyPhysicsShells(); + DestroyWorld(); +} diff --git a/src/editors/LevelEditor/Scene/LEPhysics.h b/src/editors/LevelEditor/Scene/LEPhysics.h new file mode 100644 index 00000000000..7ee41a6e5ab --- /dev/null +++ b/src/editors/LevelEditor/Scene/LEPhysics.h @@ -0,0 +1,28 @@ +#pragma once + +class CObjectSpace; +class CScenePhyscs +{ + CObjectSpace *m_object_space; + bool b_update_level_collision; + +public: + CScenePhyscs() : m_object_space(0), b_update_level_collision(false) {} + ~CScenePhyscs(); + +public: + void CreateWorld(); + void DestroyWorld(); + void CreateShellsSelected(); + void DestroyAll(); + void UseSimulatePoses(); + void UpdateLevelCollision() { b_update_level_collision = true; } + void OnSceneModified(); + bool Simulating(); + +private: + bool CreateObjectSpace(bool b_selected_only); + void DestroyObjectSpace(); +}; + +extern CScenePhyscs g_scene_physics; diff --git a/src/editors/LevelEditor/Scene/OldFixedMap.h b/src/editors/LevelEditor/Scene/OldFixedMap.h new file mode 100644 index 00000000000..8aaa1cda1e2 --- /dev/null +++ b/src/editors/LevelEditor/Scene/OldFixedMap.h @@ -0,0 +1,332 @@ +#ifndef _FIXEDMAP_H +#define _FIXEDMAP_H +#pragma once + +template +class FixedMAP +{ + enum + { + SG_REALLOC_ADVANCE = 64 + }; + +public: + struct TNode + { + K key; + T val; + TNode *left, *right; + }; + typedef void callback(TNode *); + typedef bool callback_cmp(TNode &N1, TNode &N2); + +private: + TNode *nodes; + u32 pool; + u32 limit; + + IC u32 Size(u32 Count) + { + return Count * sizeof(TNode); + } + + void Realloc() + { + u32 newLimit = limit + SG_REALLOC_ADVANCE; + VERIFY(newLimit % SG_REALLOC_ADVANCE == 0); + TNode *newNodes = (TNode *)allocator::alloc(sizeof(TNode) * newLimit); + VERIFY(newNodes); + + ZeroMemory(newNodes, Size(newLimit)); + if (limit) + CopyMemory(newNodes, nodes, Size(limit)); + + for (u32 I = 0; I < pool; I++) + { + VERIFY(nodes); + TNode *Nold = nodes + I; + TNode *Nnew = newNodes + I; + + if (Nold->left) + { + size_t Lid = Nold->left - nodes; + Nnew->left = newNodes + Lid; + } + if (Nold->right) + { + size_t Rid = Nold->right - nodes; + Nnew->right = newNodes + Rid; + } + } + if (nodes) + allocator::dealloc(nodes); + + nodes = newNodes; + limit = newLimit; + } + + IC TNode *Alloc(const K &key) + { + if (pool == limit) + Realloc(); + TNode *node = nodes + pool; + node->key = key; + node->right = node->left = 0; + pool++; + return node; + } + IC TNode *CreateChild(TNode *&parent, const K &key) + { + size_t PID = size_t(parent - nodes); + TNode *N = Alloc(key); + parent = nodes + PID; + return N; + } + + IC void recurseLR(TNode *N, callback CB) + { + if (N->left) + recurseLR(N->left, CB); + CB(N); + if (N->right) + recurseLR(N->right, CB); + } + IC void recurseRL(TNode *N, callback CB) + { + if (N->right) + recurseRL(N->right, CB); + CB(N); + if (N->left) + recurseRL(N->left, CB); + } + IC void getLR(TNode *N, xr_vector::result> &D) + { + if (N->left) + getLR(N->left, D); + D.push_back(N->val); + if (N->right) + getLR(N->right, D); + } + IC void getRL(TNode *N, xr_vector::result> &D) + { + if (N->right) + getRL(N->right, D); + D.push_back(N->val); + if (N->left) + getRL(N->left, D); + } + IC void getLR_P(TNode *N, xr_vector::result> &D) + { + if (N->left) + getLR_P(N->left, D); + D.push_back(N); + if (N->right) + getLR_P(N->right, D); + } + IC void getRL_P(TNode *N, xr_vector::result> &D) + { + if (N->right) + getRL_P(N->right, D); + D.push_back(N); + if (N->left) + getRL_P(N->left, D); + } + +public: + FixedMAP() + { + pool = 0; + limit = 0; + nodes = 0; + } + ~FixedMAP() + { + destroy(); + } + void destroy() + { + if (nodes) + { + for (TNode *cur = begin(); cur != last(); cur++) + cur->~TNode(); + allocator::dealloc(nodes); + } + } + IC TNode *insert(const K &k) + { + if (pool) + { + TNode *node = nodes; + + once_more: + if (k < node->key) + { + if (node->left) + { + node = node->left; + goto once_more; + } + else + { + TNode *N = CreateChild(node, k); + node->left = N; + return N; + } + } + else if (k > node->key) + { + if (node->right) + { + node = node->right; + goto once_more; + } + else + { + TNode *N = CreateChild(node, k); + node->right = N; + return N; + } + } + else + return node; + } + else + { + return Alloc(k); + } + } + IC TNode *insertInAnyWay(const K &k) + { + if (pool) + { + TNode *node = nodes; + + once_more: + if (k <= node->key) + { + if (node->left) + { + node = node->left; + goto once_more; + } + else + { + TNode *N = CreateChild(node, k); + node->left = N; + return N; + } + } + else + { + if (node->right) + { + node = node->right; + goto once_more; + } + else + { + TNode *N = CreateChild(node, k); + node->right = N; + return N; + } + } + } + else + { + return Alloc(k); + } + } + IC TNode *insert(const K &k, const T &v) + { + TNode *N = insert(k); + N->val = v; + return N; + } + IC TNode *insertInAnyWay(const K &k, const T &v) + { + TNode *N = insertInAnyWay(k); + N->val = v; + return N; + } + IC void discard() + { + if (nodes) + allocator::dealloc(nodes); + nodes = 0; + pool = 0; + limit = 0; + } + IC u32 allocated() { return this->limit; } + IC void clear() { pool = 0; } + IC TNode *begin() { return nodes; } + IC TNode *end() { return nodes + pool; } + IC TNode *last() { return nodes + limit; } // for setup only + IC u32 size() { return pool; } + IC TNode &operator[](int v) { return nodes[v]; } + + IC void traverseLR(callback CB) + { + if (pool) + recurseLR(nodes, CB); + } + IC void traverseRL(callback CB) + { + if (pool) + recurseRL(nodes, CB); + } + IC void traverseANY(callback CB) + { + TNode *_end = end(); + for (TNode *cur = begin(); cur != _end; cur++) + CB(cur); + } + + IC void getLR(xr_vector::result> &D) + { + if (pool) + getLR(nodes, D); + } + IC void getLR_P(xr_vector::result> &D) + { + if (pool) + getLR_P(nodes, D); + } + IC void getRL(xr_vector::result> &D) + { + if (pool) + getRL(nodes, D); + } + IC void getRL_P(xr_vector::result> &D) + { + if (pool) + getRL_P(nodes, D); + } + IC void getANY(xr_vector::result> &D) + { + TNode *_end = end(); + for (TNode *cur = begin(); cur != _end; cur++) + D.push_back(cur->val); + } + IC void getANY_P(xr_vector::result> &D) + { + D.resize(size()); + TNode **_it = &*D.begin(); + TNode *_end = end(); + for (TNode *cur = begin(); cur != _end; cur++, _it++) + *_it = cur; + } + IC void getANY_P(xr_vector::result> &D) + { + D.resize(size()); + void **_it = &*D.begin(); + TNode *_end = end(); + for (TNode *cur = begin(); cur != _end; cur++, _it++) + *_it = cur; + } + IC void setup(callback CB) + { + for (int i = 0; i < limit; i++) + CB(nodes + i); + } +}; +#endif diff --git a/src/editors/LevelEditor/Scene/SceneGraph.h b/src/editors/LevelEditor/Scene/SceneGraph.h new file mode 100644 index 00000000000..c5ce575352a --- /dev/null +++ b/src/editors/LevelEditor/Scene/SceneGraph.h @@ -0,0 +1,274 @@ +#pragma once +#if 0 +template +class FixedMAP +{ +public: + struct TNode + { + K key; + T val; + TNode *left, *right; + + TNode() { right = left = 0; } + }; + typedef void callback(TNode *); + +private: + TNode *nodes; + DWORD pool; + DWORD limit; + + IC TNode *Alloc(const K &key, const T &val) + { + VERIFY(nodes); + TNode *node = nodes + pool; + node->key = key; + node->val = val; + node->right = node->left = 0; + pool++; + VERIFY(pool < limit); + return node; + } + IC TNode *Alloc(const K &key) + { + VERIFY(nodes); + TNode *node = nodes + pool; + node->key = key; + node->right = node->left = 0; + pool++; + VERIFY(pool < limit); + return node; + } + IC void recurseLR(TNode *N, callback CB) + { + if (N->left) + recurseLR(N->left, CB); + CB(N); + if (N->right) + recurseLR(N->right, CB); + } + IC void recurseRL(TNode *N, callback CB) + { + if (N->right) + recurseRL(N->right, CB); + CB(N); + if (N->left) + recurseRL(N->left, CB); + } + +public: + FixedMAP() + { + nodes = 0; + pool = 0; + limit = 0; + } + ~FixedMAP() + { + delete[] nodes; + } + IC void init(int maxnodes) + { + limit = maxnodes; + nodes = new TNode[limit]; + } + IC TNode *insert(const K &k, const T &v) + { + if (pool) + { + TNode *node = nodes; + + once_more: + if (k < node->key) + { + if (node->left) + { + node = node->left; + goto once_more; + } + else + { + TNode *N = Alloc(k, v); + node->left = N; + return N; + } + } + else if (k > node->key) + { + if (node->right) + { + node = node->right; + goto once_more; + } + else + { + TNode *N = Alloc(k, v); + node->right = N; + return N; + } + } + else + return node; + } + else + { + return Alloc(k, v); + } + } + IC TNode *insertInAnyWay(const K &k, const T &v) + { + if (pool) + { + TNode *node = nodes; + + once_more: + if (k <= node->key) + { + VERIFY(node->val != v); + if (node->left) + { + node = node->left; + goto once_more; + } + else + { + TNode *N = Alloc(k, v); + node->left = N; + return N; + } + } + else + { + if (node->right) + { + node = node->right; + goto once_more; + } + else + { + TNode *N = Alloc(k, v); + node->right = N; + return N; + } + } + } + else + { + return Alloc(k, v); + } + } + IC TNode *insert(const K &k) + { + if (pool) + { + TNode *node = nodes; + + once_more: + if (k < node->key) + { + if (node->left) + { + node = node->left; + goto once_more; + } + else + { + TNode *N = Alloc(k); + node->left = N; + return N; + } + } + else if (k > node->key) + { + if (node->right) + { + node = node->right; + goto once_more; + } + else + { + TNode *N = Alloc(k); + node->right = N; + return N; + } + } + else + return node; + } + else + { + return Alloc(k); + } + } + IC TNode *insertInAnyWay(const K &k) + { + if (pool) + { + TNode *node = nodes; + + once_more: + if (k <= node->key) + { + if (node->left) + { + node = node->left; + goto once_more; + } + else + { + TNode *N = Alloc(k); + node->left = N; + return N; + } + } + else + { + if (node->right) + { + node = node->right; + goto once_more; + } + else + { + TNode *N = Alloc(k); + node->right = N; + return N; + } + } + } + else + { + return Alloc(k); + } + } + IC void clear() { pool = 0; } + IC TNode *begin() { return nodes; } + IC TNode *end() { return nodes + pool; } + IC TNode *last() { return nodes + limit; } // for setup only + IC TNode *size() { return pool; } + IC TNode &operator[](int v) { return nodes[v]; } + + IC void traverseLR(callback CB) + { + if (pool) + recurseLR(nodes, CB); + } + IC void traverseRL(callback CB) + { + if (pool) + recurseRL(nodes, CB); + } + IC void traverseANY(callback CB) + { + TNode *_end = end(); + for (TNode *cur = begin(); cur != _end; cur++) + CB(cur); + } + IC void setup(callback CB) + { + for (int i = 0; i < limit; i++) + CB(nodes + i); + } +}; +#endif \ No newline at end of file diff --git a/src/editors/LevelEditor/Scene/SceneIO.cpp b/src/editors/LevelEditor/Scene/SceneIO.cpp new file mode 100644 index 00000000000..b11299299ef --- /dev/null +++ b/src/editors/LevelEditor/Scene/SceneIO.cpp @@ -0,0 +1,1425 @@ +#include "stdafx.h" + +#define CURRENT_FILE_VERSION 0x00000005 +#define CURRENT_LEVELOP_VERSION 0x0000000C + +#define CURRENT_LEVELOP_BP_VERSION 0x00000009 +#define CURRENT_ENV_VERSION 0x00000007 + +#define CHUNK_VERSION 0x9df3 +#define CHUNK_OBJECT_CLASS 0x7703 +#define CHUNK_OBJECT_LIST 0x7708 +#define CHUNK_CAMERA 0x7709 +#define CHUNK_SNAPOBJECTS 0x7710 +#define CHUNK_LEVELOP 0x7711 +#define CHUNK_OBJECT_COUNT 0x7712 +#define CHUNK_LEVEL_TAG 0x7777 + +#define CHUNK_TOOLS_GUID 0x7000 +#define CHUNK_TOOLS_DATA 0x8000 + +// level options +#define CHUNK_LO_VERSION 0x7801 +#define CHUNK_LO_NAMES 0x7802 +#define CHUNK_LO_BOP 0x7803 +#define CHUNK_LO_PREFIX 0x7804 +#define CHUNK_LO_BP_VERSION 0x7849 +#define CHUNK_BUILD_PARAMS 0x7850 +#define CHUNK_LIGHT_QUALITY 0x7851 +#define CHUNK_MAP_USAGE 0x7852 +#define CHUNK_LO_MAP_VER 0x7853 +//------------------------------------------------------------------------------------------------ +// Level Options +//------------------------------------------------------------------------------------------------ +void st_LevelOptions::SaveLTX(CInifile &ini) +{ + LPCSTR section = "level_options"; + ini.w_u32(section, "version", CURRENT_LEVELOP_VERSION); + + ini.w_string(section, "level_path", m_FNLevelPath.c_str()); + ini.w_string(section, "level_prefix", m_LevelPrefix.c_str()); + xr_string s = "\""; + s += m_BOPText.c_str(); + s += "\""; + ini.w_string(section, "bop", s.c_str()); + ini.w_string(section, "map_version", m_map_version.c_str()); + + ini.w_u32(section, "version_bp", CURRENT_LEVELOP_BP_VERSION); + + m_BuildParams.SaveLTX(ini); + + ini.w_u8(section, "light_hemi_quality", m_LightHemiQuality); + ini.w_u8(section, "light_sun_quality", m_LightSunQuality); + + m_mapUsage.SaveLTX(ini, section); +} + +void st_LevelOptions::Save(IWriter &F) +{ + F.open_chunk(CHUNK_LO_VERSION); + + if (!Core.SocSdk) + F.w_u32(CURRENT_LEVELOP_VERSION); + else + F.w_u32(0x00000008); + + F.close_chunk(); + + F.open_chunk(CHUNK_LO_NAMES); + F.w_stringZ(m_FNLevelPath.size() ? m_FNLevelPath.c_str() : ""); + F.close_chunk(); + + F.open_chunk(CHUNK_LO_PREFIX); + F.w_stringZ(m_LevelPrefix.size() ? m_LevelPrefix.c_str() : ""); + F.close_chunk(); + + F.open_chunk(CHUNK_LO_BOP); + F.w_stringZ(m_BOPText.size() ? m_BOPText.c_str() : ""); + F.close_chunk(); + + if (!Core.SocSdk) + { + F.open_chunk(CHUNK_LO_MAP_VER); + F.w_stringZ(m_map_version.size() ? m_map_version.c_str() : "1.0"); + F.close_chunk(); + } + + F.open_chunk(CHUNK_LO_BP_VERSION); + F.w_u32(CURRENT_LEVELOP_BP_VERSION); + F.close_chunk(); + + F.open_chunk(CHUNK_BUILD_PARAMS); + F.w(&m_BuildParams, sizeof(m_BuildParams)); + F.close_chunk(); + + F.open_chunk(CHUNK_LIGHT_QUALITY); + F.w_u8(m_LightHemiQuality); + F.w_u8(m_LightSunQuality); + F.close_chunk(); + + F.open_chunk(CHUNK_MAP_USAGE); + + if (Core.SocSdk) + { + F.w_s32(m_mapUsage.m_GameType.is(eGameIDDeathmatch)); + F.w_s32(m_mapUsage.m_GameType.is(eGameIDTeamDeathmatch)); + F.w_s32(m_mapUsage.m_GameType.is(eGameIDArtefactHunt)); + } + else + F.w_u16(m_mapUsage.m_GameType.get()); + + F.close_chunk(); +} + +void st_LevelOptions::ReadLTX(CInifile &ini) +{ + LPCSTR section = "level_options"; + + u32 vers_op = ini.r_u32(section, "version"); + if (vers_op < 0x00000008) + { + ELog.DlgMsg(mtError, "Skipping bad version of level options."); + return; + } + + m_FNLevelPath = ini.r_string(section, "level_path"); + m_LevelPrefix = ini.r_string(section, "level_prefix"); + m_BOPText = ini.r_string_wb(section, "bop"); + + if (vers_op > 0x0000000B) + m_map_version = ini.r_string(section, "map_version"); + + m_BuildParams.LoadLTX(ini); + + m_LightHemiQuality = ini.r_u8(section, "light_hemi_quality"); + m_LightSunQuality = ini.r_u8(section, "light_sun_quality"); + + m_mapUsage.SetDefaults(); + + if (vers_op > 0x0000000A) + m_mapUsage.LoadLTX(ini, section, false); + else + { + m_mapUsage.m_GameType.set(eGameIDDeathmatch, ini.r_s32(section, "usage_deathmatch")); + m_mapUsage.m_GameType.set(eGameIDTeamDeathmatch, ini.r_s32(section, "usage_teamdeathmatch")); + m_mapUsage.m_GameType.set(eGameIDArtefactHunt, ini.r_s32(section, "usage_artefacthunt")); + + if (vers_op > 0x00000008) + { + m_mapUsage.m_GameType.set(eGameIDCaptureTheArtefact, ini.r_s32(section, "usage_captretheartefact")); + m_mapUsage.m_GameType.set(eGameIDTeamDominationZone, ini.r_s32(section, "usage_team_domination_zone")); + + if (vers_op == 0x00000009) + m_mapUsage.m_GameType.set(eGameIDDominationZone, ini.r_s32(section, "domination_zone")); + else + m_mapUsage.m_GameType.set(eGameIDDominationZone, ini.r_s32(section, "usage_domination_zone")); + } + } +} + +void st_LevelOptions::Read(IReader &F) +{ + R_ASSERT(F.find_chunk(CHUNK_LO_VERSION)); + DWORD vers = F.r_u32(); + if (vers < 0x00000008) + { + ELog.DlgMsg(mtError, "Skipping bad version of level options."); + return; + } + + R_ASSERT(F.find_chunk(CHUNK_LO_NAMES)); + F.r_stringZ(m_FNLevelPath); + + if (F.find_chunk(CHUNK_LO_PREFIX)) + F.r_stringZ(m_LevelPrefix); + + R_ASSERT(F.find_chunk(CHUNK_LO_BOP)); + F.r_stringZ(m_BOPText); + + if (F.find_chunk(CHUNK_LO_MAP_VER)) + F.r_stringZ(m_map_version); + + vers = 0; + if (F.find_chunk(CHUNK_LO_BP_VERSION)) + vers = F.r_u32(); + + if (CURRENT_LEVELOP_BP_VERSION == vers) + { + if (F.find_chunk(CHUNK_BUILD_PARAMS)) + F.r(&m_BuildParams, sizeof(m_BuildParams)); + } + else + { + ELog.DlgMsg(mtError, "Skipping bad version of build params."); + m_BuildParams.Init(); + } + + if (F.find_chunk(CHUNK_LIGHT_QUALITY)) + { + m_LightHemiQuality = F.r_u8(); + m_LightSunQuality = F.r_u8(); + } + + if (F.find_chunk(CHUNK_MAP_USAGE)) + { + if (vers > 0x00000008) + m_mapUsage.m_GameType.assign(F.r_u16()); + else + { + m_mapUsage.m_GameType.zero(); + m_mapUsage.m_GameType.set(eGameIDDeathmatch, F.r_s32()); + m_mapUsage.m_GameType.set(eGameIDTeamDeathmatch, F.r_s32()); + m_mapUsage.m_GameType.set(eGameIDArtefactHunt, F.r_s32()); + } + } +} + +//------------------------------------------------------------------------------------------------ +// Scene +//------------------------------------------------------------------------------------------------ +BOOL EScene::LoadLevelPartLTX(ESceneToolBase *M, LPCSTR mn) +{ + string_path map_name; + strcpy(map_name, mn); + + if (!M->can_use_inifile()) + return LoadLevelPart(M, map_name); + + int fnidx = 0; + while (FS.exist(map_name)) + { + IReader *R = FS.r_open(map_name); + VERIFY(R); + char ch; + R->r(&ch, sizeof(ch)); + bool b_is_inifile = (ch == '['); + FS.r_close(R); + + if (!b_is_inifile) + return LoadLevelPart(M, map_name); + + M->m_EditFlags.set(ESceneToolBase::flReadonly, FALSE); + + CInifile ini(map_name); + + // check level part GUID + xrGUID guid; + guid.LoadLTX(ini, "guid", "guid"); + + if (guid != m_GUID) + { + ELog.DlgMsg(mtError, "Skipping invalid version of level part: '%s\\%s.part'", EFS.ExtractFileName(map_name).c_str(), M->ClassName()); + return FALSE; + } + // read data + M->LoadLTX(ini); + + ++fnidx; + sprintf(map_name, "%s%d", mn, fnidx); + } + + return TRUE; +} + +BOOL EScene::LoadLevelPart(ESceneToolBase *M, LPCSTR map_name) +{ + if (!Core.SocSdk) + { + if (M->can_use_inifile()) + return LoadLevelPartLTX(M, map_name); + } + + if (FS.exist(map_name)) + { + // check locking + M->m_EditFlags.set(ESceneToolBase::flReadonly, FALSE); + + IReader *R = FS.r_open(map_name); + VERIFY(R); + // check level part GUID + R_ASSERT(R->find_chunk(CHUNK_TOOLS_GUID)); + xrGUID guid; + R->r(&guid, sizeof(guid)); + + if (guid != m_GUID) + { + ELog.DlgMsg(mtError, "Skipping invalid version of level part: '%s\\%s.part'", EFS.ExtractFileName(map_name).c_str(), M->ClassName()); + FS.r_close(R); + return FALSE; + } + // read data + IReader *chunk = R->open_chunk(CHUNK_TOOLS_DATA + M->FClassID); + if (chunk != NULL) + { + M->LoadStream(*chunk); + chunk->close(); + } + else + { + ELog.DlgMsg(mtError, "Skipping corrupted version of level part: '%s\\%s.part'", EFS.ExtractFileName(map_name).c_str(), M->ClassName()); + FS.r_close(R); + return FALSE; + } + // success + FS.r_close(R); + return TRUE; + } + return TRUE; +} + +BOOL EScene::LoadLevelPart(LPCSTR map_name, ObjClassID cls) +{ + xr_string pn = LevelPartName(map_name, cls); + if (LoadLevelPart(GetTool(cls), pn.c_str())) + return TRUE; + else + return FALSE; +} + +BOOL EScene::UnloadLevelPart(ESceneToolBase *M) +{ + M->Clear(); + return TRUE; +} + +BOOL EScene::UnloadLevelPart(LPCSTR map_name, ObjClassID cls) +{ + xr_string pn = LevelPartName(map_name, cls); + if (UnloadLevelPart(GetTool(cls))) + return TRUE; + else + return FALSE; +} + +xr_string EScene::LevelPartPath(LPCSTR full_name) +{ + return EFS.ExtractFilePath(full_name) + EFS.ExtractFileName(full_name) + "\\"; +} + +xr_string EScene::LevelPartName(LPCSTR map_name, ObjClassID cls) +{ + return LevelPartPath(map_name) + GetTool(cls)->ClassName() + ".part"; +} + +void EScene::SaveLTX(LPCSTR map_name, bool bForUndo, bool bForceSaveAll) +{ + VERIFY(map_name); + R_ASSERT(!bForUndo); + + CTimer T; + T.Start(); + xr_string full_name; + full_name = map_name; + + xr_string part_prefix; + + bool bSaveMain = true; + + if (!bForUndo) + { + if (bSaveMain) + { + EFS.MarkFile(full_name.c_str(), true); + } + part_prefix = LevelPartPath(full_name.c_str()); + } + + CInifile ini(full_name.c_str(), FALSE, FALSE, TRUE); + + if (bSaveMain) + { + ini.w_u32("version", "value", CURRENT_FILE_VERSION); + + m_LevelOp.SaveLTX(ini); + + m_GUID.SaveLTX(ini, "guid", "guid"); + + ini.w_string("level_tag", "owner", m_OwnerName.c_str()); + ini.w_u32("level_tag", "create_time", m_CreateTime); + + ini.w_fvector3("camera", "hpb", EDevice.m_Camera.GetHPB()); + ini.w_fvector3("camera", "pos", EDevice.m_Camera.GetPosition()); + + for (ObjectIt SO = m_ESO_SnapObjects.begin(); SO != m_ESO_SnapObjects.end(); ++SO) + { + ini.w_string("snap_objects", (*SO)->GetName(), NULL); + } + } + + m_SaveCache.clear(); + + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + + for (; _I != _E; ++_I) + { + if ((_I->first != OBJCLASS_DUMMY) && + _I->second && + _I->second->IsEnabled() && + _I->second->IsEditable()) + { + if (bForUndo) + { + if (_I->second->IsNeedSave()) + _I->second->SaveStream(m_SaveCache); + } + else + { + // !ForUndo + xr_string part_name = part_prefix + _I->second->ClassName() + ".part"; + if (_I->second->can_use_inifile()) + { + EFS.MarkFile(part_name.c_str(), true); + SaveToolLTX(_I->second->FClassID, part_name.c_str()); + } // can_use_ini_file + else + { + _I->second->SaveStream(m_SaveCache); + + EFS.MarkFile(part_name.c_str(), true); + + IWriter *FF = FS.w_open(part_name.c_str()); + R_ASSERT(FF); + FF->open_chunk(CHUNK_TOOLS_GUID); + FF->w(&m_GUID, sizeof(m_GUID)); + FF->close_chunk(); + + FF->open_chunk(CHUNK_TOOLS_DATA + _I->first); + FF->w(m_SaveCache.pointer(), m_SaveCache.size()); + FF->close_chunk(); + + FS.w_close(FF); + + } // ! can_use_ini_file + } + m_SaveCache.clear(); + } + } + + if (!bForUndo) + { + m_RTFlags.set(flRT_Unsaved, FALSE); + Msg("Saving time: %3.2f sec", T.GetElapsed_sec()); + } +} +//-------------------------------------------------------------------------------------------------- +void EScene::SaveToolLTX(ObjClassID clsid, LPCSTR fn) +{ + ESceneToolBase *tool = GetTool(clsid); + int fc = tool->SaveFileCount(); + if (fc == 1) + { + CInifile ini_part(fn, FALSE, FALSE, FALSE); + tool->SaveLTX(ini_part, 0); + m_GUID.SaveLTX(ini_part, "guid", "guid"); + ini_part.save_as(); + } + else + { + for (int i = 0; i < fc; ++i) + { + + string_path filename; + if (i) + sprintf(filename, "%s%d", fn, i); + else + strcpy(filename, fn); + + CInifile ini_part(filename, FALSE, FALSE, FALSE); + tool->SaveLTX(ini_part, i); + m_GUID.SaveLTX(ini_part, "guid", "guid"); + ini_part.save_as(); + } + } +} + +bool EScene::LoadToolLTX(ObjClassID clsid, LPCSTR fn) +{ + ESceneToolBase *tool = GetTool(clsid); + tool->Clear(true); + bool res = LoadLevelPartLTX(tool, fn); + return res; +} + +void EScene::Save(LPCSTR map_name, bool bUndo, bool bForceSaveAll) +{ + if (!Core.SocSdk) + R_ASSERT(bUndo); + + VERIFY(map_name); + + CTimer T; + T.Start(); + xr_string full_name; + full_name = map_name; + + xr_string part_prefix; + + bool bSaveMain = true; + + IWriter *F = 0; + + if (bSaveMain) + { + F = FS.w_open(full_name.c_str()); + R_ASSERT(F); + + F->open_chunk(CHUNK_VERSION); + F->w_u32(CURRENT_FILE_VERSION); + F->close_chunk(); + + F->open_chunk(CHUNK_LEVELOP); + m_LevelOp.Save(*F); + F->close_chunk(); + + F->open_chunk(CHUNK_TOOLS_GUID); + F->w(&m_GUID, sizeof(m_GUID)); + F->close_chunk(); + + F->open_chunk(CHUNK_LEVEL_TAG); + F->w_stringZ(m_OwnerName); + F->w(&m_CreateTime, sizeof(m_CreateTime)); + F->close_chunk(); + + F->open_chunk(CHUNK_CAMERA); + F->w_fvector3(EDevice.m_Camera.GetHPB()); + F->w_fvector3(EDevice.m_Camera.GetPosition()); + F->close_chunk(); + + F->open_chunk(CHUNK_SNAPOBJECTS); + F->w_u32(m_ESO_SnapObjects.size()); + + for (ObjectIt _F = m_ESO_SnapObjects.begin(); _F != m_ESO_SnapObjects.end(); ++_F) + F->w_stringZ((*_F)->GetName()); + + F->close_chunk(); + } + + m_SaveCache.clear(); + + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + + for (; _I != _E; ++_I) + { + if ((_I->first != OBJCLASS_DUMMY) && + _I->second && + _I->second->IsEnabled() && + _I->second->IsEditable() && + (_I->second->IsChanged() || bForceSaveAll)) + { + + if (_I->second->IsEnabled() && _I->second->IsEditable()) + { + if (_I->second->IsNeedSave()) + { + _I->second->SaveStream(m_SaveCache); + F->open_chunk(CHUNK_TOOLS_DATA + _I->first); + F->w(m_SaveCache.pointer(), m_SaveCache.size()); + F->close_chunk(); + } + } + m_SaveCache.clear(); + } + } + + // save data + if (bSaveMain) + FS.w_close(F); + + if (!bUndo) + { + m_RTFlags.set(flRT_Unsaved, FALSE); + Msg("Saving time: %3.2f sec", T.GetElapsed_sec()); + } +} + +void EScene::SaveObjectLTX(CCustomObject *O, LPCSTR sect_name, CInifile &ini) +{ + ini.w_u32(sect_name, "clsid", O->FClassID); + O->SaveLTX(ini, sect_name); +} + +void EScene::SaveObjectStream(CCustomObject *O, IWriter &F) +{ + F.open_chunk(CHUNK_OBJECT_CLASS); + F.w_u32(O->FClassID); + F.close_chunk(); + F.open_chunk(CHUNK_OBJECT_BODY); + O->SaveStream(F); + F.close_chunk(); +} +//-------------------------------------------------------------------------------------------------- + +void EScene::SaveObjectsLTX(ObjectList &lst, LPCSTR sect_name_parent, LPCSTR sect_name_prefix, CInifile &ini) +{ + u32 i = 0; + string256 buff; + for (ObjectIt _F = lst.begin(); _F != lst.end(); ++_F, ++i) + { + sprintf(buff, "%s_%s_%d", sect_name_parent, sect_name_prefix, i); + SaveObjectLTX(*_F, buff, ini); + } + sprintf(buff, "%s_count", sect_name_prefix); + ini.w_u32(sect_name_parent, buff, lst.size()); +} + +void EScene::SaveObjectsStream(ObjectList &lst, u32 chunk_id, IWriter &F) +{ + F.open_chunk(chunk_id); + int count = 0; + for (ObjectIt _F = lst.begin(); _F != lst.end(); ++_F) + { + F.open_chunk(count); + ++count; + SaveObjectStream(*_F, F); + F.close_chunk(); + } + F.close_chunk(); +} +//-------------------------------------------------------------------------------------------------- + +bool EScene::ReadObjectStream(IReader &F, CCustomObject *&O) +{ + ObjClassID clsid = OBJCLASS_DUMMY; + R_ASSERT(F.find_chunk(CHUNK_OBJECT_CLASS)); + clsid = ObjClassID(F.r_u32()); + O = GetOTool(clsid)->CreateObject(0, 0); + + IReader *S = F.open_chunk(CHUNK_OBJECT_BODY); + R_ASSERT(S); + bool bRes = O->LoadStream(*S); + S->close(); + + if (!bRes) + xr_delete(O); + + return bRes; +} +//---------------------------------------------------- +bool EScene::ReadObjectLTX(CInifile &ini, LPCSTR sect_name, CCustomObject *&O) +{ + ObjClassID clsid = OBJCLASS_DUMMY; + clsid = ObjClassID(ini.r_u32(sect_name, "clsid")); + O = GetOTool(clsid)->CreateObject(0, 0); + + bool bRes = O->LoadLTX(ini, sect_name); + + if (!bRes) + xr_delete(O); + + return bRes; +} + +bool EScene::ReadObjectsLTX(CInifile &ini, LPCSTR sect_name_parent, LPCSTR sect_name_prefix, TAppendObject on_append, SPBItem *pb) +{ + string128 buff; + R_ASSERT(on_append); + sprintf(buff, "%s_count", sect_name_prefix); + u32 count = ini.r_u32(sect_name_parent, buff); + bool bRes = true; + + for (u32 i = 0; i < count; ++i) + { + sprintf(buff, "%s_%s_%d", sect_name_parent, sect_name_prefix, i); + CCustomObject *obj = NULL; + + if (ReadObjectLTX(ini, buff, obj)) + { + LPCSTR obj_name = obj->GetName(); + CCustomObject *existing = FindObjectByName(obj_name, obj->FClassID); + if (existing) + { + + /*if(g_frmConflictLoadObject->m_result!=2 && g_frmConflictLoadObject->m_result!=4 && g_frmConflictLoadObject->m_result!=6) + { + g_frmConflictLoadObject->m_existing_object = existing; + g_frmConflictLoadObject->m_new_object = obj; + g_frmConflictLoadObject->Prepare (); + g_frmConflictLoadObject->ShowModal (); + }*/ + /* switch(g_frmConflictLoadObject->m_result) + { + case 1: //Overwrite + case 2: //Overwrite All + { + bool res = RemoveObject (existing, true, true); + if(!res) + Msg("! RemoveObject [%s] failed", existing->GetName()); + else + xr_delete(existing); + }break; + case 3: //Insert new + case 4: //Insert new All + { + string256 buf; + GenObjectName (obj->FClassID, buf, obj->GetName()); + obj->SetName(buf); + }break; + case 0: //Cancel + case 5: //Skip + case 6: //Skip All + { + xr_delete(obj); + }break; + } //switch + } //if exist*/ + string256 buf; + GenObjectName(obj->FClassID, buf, obj->GetName()); + obj->SetName(buf); + } + if (obj && !on_append(obj)) + xr_delete(obj); + } + + else + bRes = false; + + if (pb) + pb->Inc(); + } + return bRes; +} + +bool EScene::ReadObjectsStream(IReader &F, u32 chunk_id, TAppendObject on_append, SPBItem *pb) +{ + R_ASSERT(on_append); + bool bRes = true; + IReader *OBJ = F.open_chunk(chunk_id); + if (OBJ) + { + IReader *O = OBJ->open_chunk(0); + for (int count = 1; O; ++count) + { + CCustomObject *obj = NULL; + if (ReadObjectStream(*O, obj)) + { + LPCSTR obj_name = obj->GetName(); + CCustomObject *existing = FindObjectByName(obj_name, obj->FClassID); + if (existing) + { + /*if(g_frmConflictLoadObject->m_result!=2 && g_frmConflictLoadObject->m_result!=4 && g_frmConflictLoadObject->m_result!=6) + { + g_frmConflictLoadObject->m_existing_object = existing; + g_frmConflictLoadObject->m_new_object = obj; + g_frmConflictLoadObject->Prepare (); + g_frmConflictLoadObject->ShowModal (); + } + switch(g_frmConflictLoadObject->m_result) + { + case 1: //Overwrite + case 2: //Overwrite All + { + bool res = RemoveObject (existing, true, true); + if(!res) + Msg("! RemoveObject [%s] failed", existing->Name); + else + xr_delete(existing); + }break; + case 3: //Insert new + case 4: //Insert new All*/ + + string256 buf; + GenObjectName(obj->FClassID, buf, obj->GetName()); + obj->SetName(buf); + /*}break; + case 0: //Cancel + case 5: //Skip + case 6: //Skip All + { + xr_delete(obj); + }break; + }*/ + } + if (obj && !on_append(obj)) + xr_delete(obj); + } + else + bRes = false; + + O->close(); + O = OBJ->open_chunk(count); + + if (pb) + pb->Inc(); + } + OBJ->close(); + } + return bRes; +} + +bool EScene::OnLoadAppendObject(CCustomObject *O) +{ + AppendObject(O, false); + return true; +} + +//---------------------------------------------------- +bool EScene::LoadLTX(LPCSTR map_name, bool bUndo) +{ + DWORD version = 0; + if (!map_name || (0 == map_name[0])) + return false; + + xr_string full_name; + full_name = map_name; + + ELog.Msg(mtInformation, "EScene: loading '%s'", map_name); + if (FS.exist(full_name.c_str())) + { + CTimer T; + T.Start(); + + // lock main level + CInifile ini(full_name.c_str()); + version = ini.r_u32("version", "value"); + + if (version != CURRENT_FILE_VERSION) + { + ELog.DlgMsg(mtError, "EScene: unsupported file version. Can't load Level."); + UI->UpdateScene(); + return false; + } + + m_LevelOp.ReadLTX(ini); + + Fvector hpb, pos; + pos = ini.r_fvector3("camera", "pos"); + hpb = ini.r_fvector3("camera", "hpb"); + EDevice.m_Camera.Set(hpb, pos); + EDevice.m_Camera.SetStyle(EDevice.m_Camera.GetStyle()); + EDevice.m_Camera.SetStyle(EDevice.m_Camera.GetStyle()); + + m_GUID.LoadLTX(ini, "guid", "guid"); + + m_OwnerName = ini.r_string("level_tag", "owner"); + m_CreateTime = ini.r_u32("level_tag", "create_time"); + + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; ++_I) + { + if (_I->second) + { + { + if (!bUndo && _I->second->IsEnabled() && (_I->first != OBJCLASS_DUMMY)) + { + xr_string fn = LevelPartName(map_name, _I->first).c_str(); + LoadLevelPartLTX(_I->second, fn.c_str()); + } + } + } + } + + if (ini.section_exist("snap_objects")) + { + CInifile::Sect &S = ini.r_section("snap_objects"); + auto Si = S.Data.begin(); + auto Se = S.Data.end(); + for (; Si != Se; ++Si) + { + CCustomObject *O = FindObjectByName(Si->first.c_str(), OBJCLASS_SCENEOBJECT); + if (!O) + ELog.Msg(mtError, "EScene: Can't find snap object '%s'.", Si->second.c_str()); + else + m_ESO_SnapObjects.push_back(O); + } + UpdateSnapList(); + } + + Msg("EScene: %d objects loaded, %3.2f sec", ObjCount(), T.GetElapsed_sec()); + + UI->UpdateScene(true); + + SynchronizeObjects(); + + if (!bUndo) + m_RTFlags.set(flRT_Unsaved | flRT_Modified, FALSE); + + return true; + } + else + { + ELog.Msg(mtError, "Can't find file: '%s'", map_name); + } + return false; +} + +bool EScene::Load(LPCSTR map_name, bool bUndo) +{ + u32 version = 0; + + if (!map_name || (0 == map_name[0])) + return false; + + xr_string full_name; + full_name = map_name; + + ELog.Msg(mtInformation, "EScene: loading '%s'", map_name); + if (FS.exist(full_name.c_str())) + { + CTimer T; + T.Start(); + + // read main level + IReader *F = FS.r_open(full_name.c_str()); + VERIFY(F); + // Version + R_ASSERT(F->r_chunk(CHUNK_VERSION, &version)); + if (version != CURRENT_FILE_VERSION) + { + ELog.DlgMsg(mtError, "EScene: unsupported file version. Can't load Level."); + UI->UpdateScene(); + FS.r_close(F); + return false; + } + + // Lev. ops. + IReader *LOP = F->open_chunk(CHUNK_LEVELOP); + if (LOP) + { + m_LevelOp.Read(*LOP); + LOP->close(); + } + else + { + ELog.DlgMsg(mtError, "Skipping old version of level options.\nCheck level options after loading."); + } + + // + if (F->find_chunk(CHUNK_CAMERA)) + { + Fvector hpb, pos; + F->r_fvector3(hpb); + F->r_fvector3(pos); + EDevice.m_Camera.Set(hpb, pos); + EDevice.m_Camera.SetStyle(EDevice.m_Camera.GetStyle()); + } + + if (F->find_chunk(CHUNK_TOOLS_GUID)) + { + F->r(&m_GUID, sizeof(m_GUID)); + } + + if (F->find_chunk(CHUNK_LEVEL_TAG)) + { + F->r_stringZ(m_OwnerName); + F->r(&m_CreateTime, sizeof(m_CreateTime)); + } + else + { + m_OwnerName = ""; + m_CreateTime = 0; + } + + DWORD obj_cnt = 0; + + if (F->find_chunk(CHUNK_OBJECT_COUNT)) + obj_cnt = F->r_u32(); + + SPBItem *pb = UI->ProgressStart(static_cast(obj_cnt), "Loading objects..."); + ReadObjectsStream(*F, CHUNK_OBJECT_LIST, TAppendObject(this, &EScene::OnLoadAppendObject), pb); + UI->ProgressEnd(pb); + + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; ++_I) + { + if (_I->second) + { + IReader *chunk = F->open_chunk(CHUNK_TOOLS_DATA + _I->first); + if (chunk) + { + _I->second->LoadStream(*chunk); + chunk->close(); + } + else + { + if (!bUndo && _I->second->IsEnabled() && (_I->first != OBJCLASS_DUMMY)) + { + LoadLevelPart(_I->second, LevelPartName(map_name, _I->first).c_str()); + } + } + } + } + + // snap list + if (F->find_chunk(CHUNK_SNAPOBJECTS)) + { + shared_str buf; + int cnt = F->r_u32(); + if (cnt) + { + for (int i = 0; i < cnt; ++i) + { + F->r_stringZ(buf); + CCustomObject *O = FindObjectByName(buf.c_str(), OBJCLASS_SCENEOBJECT); + if (!O) + ELog.Msg(mtError, "EScene: Can't find snap object '%s'.", buf.c_str()); + + else + m_ESO_SnapObjects.push_back(O); + } + } + UpdateSnapList(); + } + + Msg("EScene: %d objects loaded, %3.2f sec", ObjCount(), T.GetElapsed_sec()); + + UI->UpdateScene(true); + + FS.r_close(F); + + SynchronizeObjects(); + + if (!bUndo) + m_RTFlags.set(flRT_Unsaved | flRT_Modified, FALSE); + + return true; + } + else + { + ELog.Msg(mtError, "Can't find file: '%s'", map_name); + } + return false; +} + +//--------------------------------------------------------------------------------------- +// copy/paste utils +//--------------------------------------------------------------------------------------- +void EScene::SaveSelection(ObjClassID classfilter, LPCSTR fname) +{ + VERIFY(fname); + + xr_string full_name; + full_name = fname; + + IWriter *F = FS.w_open(full_name.c_str()); + R_ASSERT(F); + + F->open_chunk(CHUNK_VERSION); + F->w_u32(CURRENT_FILE_VERSION); + F->close_chunk(); + + m_SaveCache.clear(); + if (OBJCLASS_DUMMY == classfilter) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; ++_I) + if (_I->second && _I->second->IsNeedSave()) + { + F->open_chunk(CHUNK_TOOLS_DATA + _I->first); + _I->second->SaveSelection(m_SaveCache); + F->w(m_SaveCache.pointer(), m_SaveCache.size()); + m_SaveCache.clear(); + F->close_chunk(); + } + } + else + { + ESceneToolBase *mt = GetTool(classfilter); + VERIFY(mt); + F->open_chunk(CHUNK_TOOLS_DATA + classfilter); + mt->SaveSelection(m_SaveCache); + F->w(m_SaveCache.pointer(), m_SaveCache.size()); + m_SaveCache.clear(); + F->close_chunk(); + } + + FS.w_close(F); +} + +//---------------------------------------------------- +bool EScene::OnLoadSelectionAppendObject(CCustomObject *obj) +{ + string256 buf; + GenObjectName(obj->FClassID, buf, obj->GetName()); + obj->SetName(buf); + AppendObject(obj, false); + obj->Select(true); + return true; +} +//---------------------------------------------------- + +bool EScene::LoadSelection(LPCSTR fname) +{ + u32 version = 0; + + VERIFY(fname); + + xr_string full_name; + full_name = fname; + + ELog.Msg(mtInformation, "EScene: loading part %s...", fname); + + bool res = true; + + if (FS.exist(full_name.c_str())) + { + SelectObjects(false); + + IReader *F = FS.r_open(full_name.c_str()); + + // Version + R_ASSERT(F->r_chunk(CHUNK_VERSION, &version)); + if (version != CURRENT_FILE_VERSION) + { + ELog.DlgMsg(mtError, "EScene: unsupported file version. Can't load Level."); + UI->UpdateScene(); + FS.r_close(F); + return false; + } + + // Objects + if (!ReadObjectsStream(*F, CHUNK_OBJECT_LIST, TAppendObject(this, &EScene::OnLoadSelectionAppendObject), 0)) + { + ELog.DlgMsg(mtError, "EScene. Failed to load selection."); + res = false; + } + + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + if (_I->second && _I->second->IsEnabled() && _I->second->IsEditable()) + { + IReader *chunk = F->open_chunk(CHUNK_TOOLS_DATA + _I->first); + if (chunk) + { + _I->second->LoadSelection(*chunk); + chunk->close(); + } + } + // Synchronize + SynchronizeObjects(); + FS.r_close(F); + } + return res; +} +//---------------------------------------------------- + +#pragma pack(push, 1) +struct SceneClipData +{ + int m_ClassFilter; + char m_FileName[MAX_PATH]; +}; +#pragma pack(pop) + +void EScene::CopySelection(ObjClassID classfilter) +{ + HGLOBAL hmem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, sizeof(SceneClipData)); + SceneClipData *sceneclipdata = (SceneClipData *)GlobalLock(hmem); + + sceneclipdata->m_ClassFilter = classfilter; + GetTempFileName(FS.get_path(_temp_)->m_Path, "clip", 0, sceneclipdata->m_FileName); + SaveSelection(classfilter, sceneclipdata->m_FileName); + + GlobalUnlock(hmem); + + int clipformat = RegisterClipboardFormat("CF_XRAY_CLASS_LIST"); + if (OpenClipboard(0)) + { + SetClipboardData(clipformat, hmem); + CloseClipboard(); + } + else + { + ELog.DlgMsg(mtError, "Failed to open clipboard"); + GlobalFree(hmem); + } +} + +void EScene::PasteSelection() +{ + int clipformat = RegisterClipboardFormat("CF_XRAY_CLASS_LIST"); + if (OpenClipboard(0)) + { + + HGLOBAL hmem = GetClipboardData(clipformat); + if (hmem) + { + SceneClipData *sceneclipdata = (SceneClipData *)GlobalLock(hmem); + LoadSelection(sceneclipdata->m_FileName); + GlobalUnlock(hmem); + } + else + { + ELog.DlgMsg(mtError, "No data in clipboard"); + } + + CloseClipboard(); + } + else + { + ELog.DlgMsg(mtError, "Failed to open clipboard"); + } +} + +void EScene::CutSelection(ObjClassID classfilter) +{ + CopySelection(classfilter); + RemoveSelection(classfilter); +} +//---------------------------------------------------- + +void EScene::LoadCompilerError(LPCSTR fn) +{ + Tools->ClearDebugDraw(); + /* + CInifile ini(fn); + string256 buff; + LPCSTR sect; + u32 sz, i; + + sect = "t-junction"; + sz = ini.r_u32(sect,"count"); + Tools->m_DebugDraw.m_Points.resize(sz); + for(i=0; im_DebugDraw.m_Points[i]; + sprintf (buff,"%d_p",i); + pt.p[0] = ini.r_fvector3(sect,buff); + + sprintf (buff,"%d_c",i); + pt.c = ini.r_u32 (sect,buff); + + sprintf (buff,"%d_i",i); + pt.i = ini.r_bool(sect,buff); + + sprintf (buff,"%d_m",i); + pt.m = ini.r_bool(sect,buff); + } + + sect = "m-edje"; + sz = ini.r_u32(sect,"count"); + Tools->m_DebugDraw.m_Lines.resize(sz); + for(i=0; im_DebugDraw.m_Lines[i]; + sprintf (buff,"%d_p0",i); + pt.p[0] = ini.r_fvector3(sect,buff); + + sprintf (buff,"%d_p1",i); + pt.p[1] = ini.r_fvector3(sect,buff); + + sprintf (buff,"%d_c",i); + pt.c = ini.r_u32 (sect,buff); + + sprintf (buff,"%d_i",i); + pt.i = ini.r_bool(sect,buff); + + sprintf (buff,"%d_m",i); + pt.m = ini.r_bool(sect,buff); + } + sect = "invalid_face"; + sz = ini.r_u32(sect,"count"); + Tools->m_DebugDraw.m_WireFaces.resize(sz); + for(i=0; im_DebugDraw.m_WireFaces[i]; + sprintf (buff,"%d_p0",i); + pt.p[0] = ini.r_fvector3(sect,buff); + + sprintf (buff,"%d_p1",i); + pt.p[1] = ini.r_fvector3(sect,buff); + + sprintf (buff,"%d_p2",i); + pt.p[2] = ini.r_fvector3(sect,buff); + + sprintf (buff,"%d_c",i); + pt.c = ini.r_u32 (sect,buff); + + sprintf (buff,"%d_i",i); + pt.i = ini.r_bool(sect,buff); + + sprintf (buff,"%d_m",i); + pt.m = ini.r_bool(sect,buff); + } + */ + + IReader *F = FS.r_open(fn); + Tools->ClearDebugDraw(); + Fvector pt[3]; + if (F->find_chunk(10)) + { // lc error (TJ) + Tools->m_DebugDraw.m_Points.resize(F->r_u32()); + F->r(Tools->m_DebugDraw.m_Points.data(), sizeof(CLevelTool::SDebugDraw::Point) * Tools->m_DebugDraw.m_Points.size()); + } + else if (F->find_chunk(0)) + { // lc error (TJ) + u32 cnt = F->r_u32(); + for (u32 k = 0; k < cnt; k++) + { + F->r(pt, sizeof(Fvector)); + Tools->m_DebugDraw.AppendPoint(pt[0], 0xff00ff00, true, true, "TJ"); + } + } + /* + if (F->find_chunk(11)){ // lc error (multiple edges) + Tools->m_DebugDraw.m_Lines.resize(F->r_u32()); + F->r(Tools->m_DebugDraw.m_Lines.begin(),sizeof(CLevelTool::SDebugDraw::Line)*Tools->m_DebugDraw.m_Lines.size()); + }else if (F->find_chunk(1)){ // lc error (multiple edges) + u32 cnt = F->r_u32(); + for (u32 k=0;kr(pt,sizeof(Fvector)*2); Tools->m_DebugDraw.AppendLine(pt[0],pt[1],0xff0000ff,false,false); } + } + */ + if (F->find_chunk(12)) + { // lc error (invalid faces) + Tools->m_DebugDraw.m_WireFaces.resize(F->r_u32()); + F->r(Tools->m_DebugDraw.m_WireFaces.data(), sizeof(CLevelTool::SDebugDraw::Face) * Tools->m_DebugDraw.m_WireFaces.size()); + } + else if (F->find_chunk(2)) + { // lc error (invalid faces) + u32 cnt = F->r_u32(); + for (u32 k = 0; k < cnt; k++) + { + F->r(pt, sizeof(Fvector) * 3); + Tools->m_DebugDraw.AppendWireFace(pt[0], pt[1], pt[2]); + } + } + FS.r_close(F); +} + +void EScene::SaveCompilerError(LPCSTR fn) +{ + /* + CInifile ini(fn,FALSE,FALSE,TRUE); + string256 buff; + LPCSTR sect; + u32 sz, i; + + sz = Tools->m_DebugDraw.m_Points.size(); + sect = "t-junction"; + ini.w_u32 (sect,"count",sz); + for(i=0; im_DebugDraw.m_Points[i].p[0]); + + sprintf (buff,"%d_c",i); + ini.w_u32 (sect,buff,Tools->m_DebugDraw.m_Points[i].c); + + sprintf (buff,"%d_i",i); + ini.w_bool (sect,buff,Tools->m_DebugDraw.m_Points[i].i); + + sprintf (buff,"%d_m",i); + ini.w_bool (sect,buff,Tools->m_DebugDraw.m_Points[i].m); + } + + sz = Tools->m_DebugDraw.m_Lines.size(); + sect = "m-edje"; + ini.w_u32 ("sect","count",sz); + for(i=0; im_DebugDraw.m_Lines[i].p[0]); + + sprintf (buff,"%d_p1",i); + ini.w_fvector3(sect,buff,Tools->m_DebugDraw.m_Lines[i].p[1]); + + sprintf (buff,"%d_c",i); + ini.w_u32 (sect,buff,Tools->m_DebugDraw.m_Lines[i].c); + + sprintf (buff,"%d_i",i); + ini.w_bool (sect,buff,Tools->m_DebugDraw.m_Lines[i].i); + + sprintf (buff,"%d_m",i); + ini.w_bool (sect,buff,Tools->m_DebugDraw.m_Lines[i].m); + } + + sz = Tools->m_DebugDraw.m_WireFaces.size(); + sect = "invalid_face"; + ini.w_u32 (sect,"count",sz); + for(i=0; im_DebugDraw.m_WireFaces[i].p[0]); + + sprintf (buff,"%d_p1",i); + ini.w_fvector3(sect,buff,Tools->m_DebugDraw.m_WireFaces[i].p[1]); + + sprintf (buff,"%d_p2",i); + ini.w_fvector3(sect,buff,Tools->m_DebugDraw.m_WireFaces[i].p[2]); + + sprintf (buff,"%d_c",i); + ini.w_u32 (sect,buff,Tools->m_DebugDraw.m_WireFaces[i].c); + + sprintf (buff,"%d_i",i); + ini.w_bool (sect,buff,Tools->m_DebugDraw.m_WireFaces[i].i); + + sprintf (buff,"%d_m",i); + ini.w_bool (sect,buff,Tools->m_DebugDraw.m_WireFaces[i].m); + } + */ + IWriter *fs = FS.w_open(fn); + R_ASSERT(fs); + IWriter &err = *fs; + + // t-junction + err.open_chunk(10); + err.w_u32(Tools->m_DebugDraw.m_Points.size()); + err.w(Tools->m_DebugDraw.m_Points.data(), Tools->m_DebugDraw.m_Points.size() * sizeof(CLevelTool::SDebugDraw::Point)); + err.close_chunk(); + + // m-edje + err.open_chunk(11); + err.w_u32(Tools->m_DebugDraw.m_Lines.size()); + err.w(Tools->m_DebugDraw.m_Lines.data(), Tools->m_DebugDraw.m_Lines.size() * sizeof(CLevelTool::SDebugDraw::Line)); + err.close_chunk(); + + // invalid + err.open_chunk(12); + err.w_u32(Tools->m_DebugDraw.m_WireFaces.size()); + err.w(Tools->m_DebugDraw.m_WireFaces.data(), Tools->m_DebugDraw.m_WireFaces.size() * sizeof(CLevelTool::SDebugDraw::Face)); + err.close_chunk(); + + FS.w_close(fs); +} + +void EScene::ExportObj(bool b_selected_only) +{ + Builder.m_save_as_object = true; + Builder.Compile(b_selected_only); + Builder.m_save_as_object = false; +} diff --git a/src/editors/LevelEditor/Scene/ScenePick.cpp b/src/editors/LevelEditor/Scene/ScenePick.cpp new file mode 100644 index 00000000000..52d0f2e1be5 --- /dev/null +++ b/src/editors/LevelEditor/Scene/ScenePick.cpp @@ -0,0 +1,215 @@ +#include "stdafx.h" + +int EScene::FrustumPick(const CFrustum &frustum, ObjClassID classfilter, ObjectList &ol) +{ + int count = 0; + + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + { + ESceneCustomOTool *mt = dynamic_cast(_I->second); + if (mt) + count += mt->FrustumPick(ol, frustum); + } + } + else + { + ESceneCustomOTool *mt = GetOTool(classfilter); + if (mt) + count += mt->FrustumPick(ol, frustum); + } + + return count; +} +//------------------------------------------------------------------------------ + +int EScene::SpherePick(const Fvector ¢er, float radius, ObjClassID classfilter, ObjectList &ol) +{ + int count = 0; + + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + { + ESceneCustomOTool *mt = dynamic_cast(_I->second); + if (mt) + count += mt->SpherePick(ol, center, radius); + } + } + else + { + ESceneCustomOTool *mt = GetOTool(classfilter); + if (mt) + count += mt->SpherePick(ol, center, radius); + } + + return count; +} +//------------------------------------------------------------------------------ + +int EScene::RayQuery(SPickQuery &PQ, const Fvector &start, const Fvector &dir, float dist, u32 flags, ObjectList *snap_list) +{ + VERIFY(snap_list); + PQ.prepare_rq(start, dir, dist, flags); + ETOOLS::ray_options(flags); + for (ObjectIt _F = snap_list->begin(); _F != snap_list->end(); _F++) + ((CSceneObject *)(*_F))->RayQuery(PQ); + return PQ.r_count(); +} +//------------------------------------------------------------------------------ + +int EScene::BoxQuery(SPickQuery &PQ, const Fbox &bb, u32 flags, ObjectList *snap_list) +{ + VERIFY(snap_list); + PQ.prepare_bq(bb, flags); + ETOOLS::box_options(flags); + for (ObjectIt _F = snap_list->begin(); _F != snap_list->end(); _F++) + ((CSceneObject *)(*_F))->BoxQuery(PQ); + return PQ.r_count(); +} +//------------------------------------------------------------------------------ + +int EScene::RayQuery(SPickQuery &PQ, const Fvector &start, const Fvector &dir, float dist, u32 flags, CDB::MODEL *model) +{ + PQ.prepare_rq(start, dir, dist, flags); + ETOOLS::ray_options(flags); + ETOOLS::ray_query(model, start, dir, dist); + for (int r = 0; r < ETOOLS::r_count(); r++) + PQ.append(ETOOLS::r_begin() + r, 0, 0); + return PQ.r_count(); +} +//------------------------------------------------------------------------------ + +int EScene::BoxQuery(SPickQuery &PQ, const Fbox &bb, u32 flags, CDB::MODEL *model) +{ + PQ.prepare_bq(bb, flags); + ETOOLS::box_options(flags); + Fvector c, d; + bb.getcenter(c); + bb.getradius(d); + ETOOLS::box_query(model, c, d); + for (int r = 0; r < ETOOLS::r_count(); r++) + PQ.append(ETOOLS::r_begin() + r, 0, 0); + return PQ.r_count(); +} +//------------------------------------------------------------------------------ + +CCustomObject *EScene::RayPickObject(float nearest_dist, const Fvector &start, const Fvector &direction, ObjClassID classfilter, SRayPickInfo *pinf, ObjectList *from_list) +{ + if (!valid()) + return 0; + + CCustomObject *nearest_object = 0; + if (from_list) + { + for (ObjectIt _F = from_list->begin(); _F != from_list->end(); _F++) + if ((*_F)->Visible() && (*_F)->RayPick(nearest_dist, start, direction, pinf)) + nearest_object = (*_F); + } + else + { + if (classfilter == OBJCLASS_DUMMY) + { + CCustomObject *obj = 0; + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + { + ESceneCustomOTool *mt = dynamic_cast(_I->second); + if (mt && mt->RayPick(obj, nearest_dist, start, direction, pinf)) + nearest_object = obj; + } + } + else + { + ESceneCustomOTool *mt = GetOTool(classfilter); + if (mt) + mt->RayPick(nearest_object, nearest_dist, start, direction, pinf); + } + } + return nearest_object; +} +//------------------------------------------------------------------------------ + +int EScene::GetQueryObjects(ObjectList &lst, ObjClassID classfilter, int iSel, int iVis, int iLock) +{ + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; ++_I) + { + ESceneCustomOTool *mt = dynamic_cast(_I->second); + if (mt) + mt->GetQueryObjects(lst, iSel, iVis, iLock); + } + } + else + { + ESceneCustomOTool *mt = GetOTool(classfilter); + if (mt) + mt->GetQueryObjects(lst, iSel, iVis, iLock); + } + return lst.size(); +} +//------------------------------------------------------------------------------ + +int EScene::RaySelect(int flag, ObjClassID classfilter) +{ + if (!valid()) + return 0; + + float dist = UI->ZFar(); + ESceneToolBase *mt = 0; + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + { + float range = UI->ZFar(); + _I->second->RaySelect(flag, range, UI->m_CurrentRStart, UI->m_CurrentRDir, TRUE); + if (range < dist) + { + dist = range; + mt = _I->second; + } + } + } + else + { + mt = GetTool(classfilter); + } + int count = 0; + dist = UI->ZFar(); + if (mt) + count = mt->RaySelect(flag, dist, UI->m_CurrentRStart, UI->m_CurrentRDir, FALSE); + return count; + /* + CCustomObject *nearest_object = RayPickObject(flt_max,UI->m_CurrentRStart,UI->m_CurrentRNorm,classfilter,0,0); + if (nearest_object) nearest_object->Select(flag); + UI->RedrawScene(); + return nearest_object?1:0; + */ +} +//------------------------------------------------------------------------------ + +int EScene::BoxPickObjects(const Fbox &box, SBoxPickInfoVec &pinf, ObjectList *lst) +{ + if (lst) + { + for (ObjectIt _F = lst->begin(); _F != lst->end(); _F++) + { + CSceneObject *_S = dynamic_cast(*_F); + if (_S) + _S->BoxPick(box, pinf); + } + } + return pinf.size(); +} +//------------------------------------------------------------------------------ diff --git a/src/editors/LevelEditor/Scene/SceneRender.cpp b/src/editors/LevelEditor/Scene/SceneRender.cpp new file mode 100644 index 00000000000..269e60f1194 --- /dev/null +++ b/src/editors/LevelEditor/Scene/SceneRender.cpp @@ -0,0 +1,169 @@ +#include "stdafx.h" + +#define RENDER_OBJECT(P, B) \ + { \ + try \ + { \ + (N->val)->RenderRoot(P, B); \ + } \ + catch (...) \ + { \ + ELog.DlgMsg(mtError, "Please notify AlexMX!!! Critical error has occured in render routine!!! [Type B] - Tools: '%s' Object: '%s'", (N->val)->FParentTools->ClassName(), (N->val)->GetName()); \ + } \ + } + +void object_Normal_0(EScene::mapObject_Node *N) +{ + RENDER_OBJECT(0, false); +} +void object_Normal_1(EScene::mapObject_Node *N) { RENDER_OBJECT(1, false); } +void object_Normal_2(EScene::mapObject_Node *N) { RENDER_OBJECT(2, false); } +void object_Normal_3(EScene::mapObject_Node *N) { RENDER_OBJECT(3, false); } +//------------------------------------------------------------------------------ +void object_StrictB2F_0(EScene::mapObject_Node *N) { RENDER_OBJECT(0, true); } +void object_StrictB2F_1(EScene::mapObject_Node *N) { RENDER_OBJECT(1, true); } +void object_StrictB2F_2(EScene::mapObject_Node *N) { RENDER_OBJECT(2, true); } +void object_StrictB2F_3(EScene::mapObject_Node *N) { RENDER_OBJECT(3, true); } +//------------------------------------------------------------------------------ + +#define RENDER_SCENE_TOOLS(P, B) \ + { \ + SceneMToolsIt s_it = scene_tools.begin(); \ + SceneMToolsIt s_end = scene_tools.end(); \ + for (; s_it != s_end; s_it++) \ + { \ + EDevice.SetShader(B ? EDevice.m_SelectionShader : EDevice.m_WireShader); \ + RCache.set_xform_world(Fidentity); \ + try \ + { \ + (*s_it)->OnRenderRoot(P, B); \ + } \ + catch (...) \ + { \ + ELog.DlgMsg(mtError, "Please notify AlexMX!!! Critical error has occured in render routine!!! [Type B] - Tools: '%s'", (*s_it)->ClassName()); \ + } \ + } \ + } + +void EScene::RenderSky(const Fmatrix &camera) +{ + if (!valid()) + return; + + // draw sky + /* + //. + if (m_SkyDome&&fraBottomBar->miDrawSky->Checked){ + st_Environment& E = m_LevelOp.m_Envs[m_LevelOp.m_CurEnv]; + m_SkyDome->GetPosition() = camera.c; + m_SkyDome->UpdateTransform(true); + EDevice.SetRS(D3DRS_TEXTUREFACTOR, E.m_SkyColor.get()); + m_SkyDome->RenderSingle(); + EDevice.SetRS(D3DRS_TEXTUREFACTOR, 0xffffffff); + } + */ +} + +struct tools_rp_pred +{ + IC bool operator()(ESceneToolBase *x, ESceneToolBase *y) const + { + return x->RenderPriority() < y->RenderPriority(); + } +}; + +#define DEFINE_MSET_PRED(T, N, I, P) \ + typedef xr_multiset N; \ + typedef N::iterator I; + +DEFINE_MSET_PRED(ESceneToolBase *, SceneMToolsSet, SceneMToolsIt, tools_rp_pred); +DEFINE_MSET_PRED(ESceneCustomOTool *, SceneOToolsSet, SceneOToolsIt, tools_rp_pred); + +void EScene::Render(const Fmatrix &camera) +{ + if (!valid()) + return; + + // if( locked() ) return; + + // extract and sort object tools + SceneOToolsSet object_tools; + SceneMToolsSet scene_tools; + { + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + for (; t_it != t_end; t_it++) + if (t_it->second) + { + // before render + t_it->second->BeforeRender(); + // sort tools + ESceneCustomOTool *mt = dynamic_cast(t_it->second); + if (mt) + object_tools.insert(mt); + scene_tools.insert(t_it->second); + } + } + + // insert objects + { + SceneOToolsIt t_it = object_tools.begin(); + SceneOToolsIt t_end = object_tools.end(); + for (; t_it != t_end; t_it++) + { + ObjectList &lst = (*t_it)->GetObjects(); + ObjectIt o_it = lst.begin(); + ObjectIt o_end = lst.end(); + for (; o_it != o_end; o_it++) + { + if ((*o_it)->Visible() && (*o_it)->IsRender()) + { + float distSQ = EDevice.vCameraPosition.distance_to_sqr((*o_it)->FPosition); + mapRenderObjects.insertInAnyWay(distSQ, *o_it); + } + } + } + } + + // priority #0 + // normal + mapRenderObjects.traverseLR(object_Normal_0); + RENDER_SCENE_TOOLS(0, false); + // alpha + mapRenderObjects.traverseRL(object_StrictB2F_0); + RENDER_SCENE_TOOLS(0, true); + + // priority #1 + // normal + mapRenderObjects.traverseLR(object_Normal_1); + RENDER_SCENE_TOOLS(1, false); + // alpha + mapRenderObjects.traverseRL(object_StrictB2F_1); + RENDER_SCENE_TOOLS(1, true); + // priority #2 + // normal + mapRenderObjects.traverseLR(object_Normal_2); + RENDER_SCENE_TOOLS(2, false); + // alpha + mapRenderObjects.traverseRL(object_StrictB2F_2); + RENDER_SCENE_TOOLS(2, true); + // priority #3 + // normal + mapRenderObjects.traverseLR(object_Normal_3); + RENDER_SCENE_TOOLS(3, false); + // alpha + mapRenderObjects.traverseRL(object_StrictB2F_3); + RENDER_SCENE_TOOLS(3, true); + + // render snap + RenderSnapList(); + + // clear + mapRenderObjects.clear(); + + SceneMToolsIt s_it = scene_tools.begin(); + SceneMToolsIt s_end = scene_tools.end(); + for (; s_it != s_end; s_it++) + (*s_it)->AfterRender(); +} +//------------------------------------------------------------------------------ diff --git a/src/editors/LevelEditor/Scene/SceneSelection.cpp b/src/editors/LevelEditor/Scene/SceneSelection.cpp new file mode 100644 index 00000000000..0d9ed872d47 --- /dev/null +++ b/src/editors/LevelEditor/Scene/SceneSelection.cpp @@ -0,0 +1,200 @@ +#include "stdafx.h" + +void EScene::SelectObjects(bool flag, ObjClassID classfilter) +{ + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + if (_I->second) + _I->second->SelectObjects(flag); + } + else + { + ESceneToolBase *mt = GetTool(classfilter); + if (mt) + mt->SelectObjects(flag); + } + + UI->RedrawScene(); +} +//------------------------------------------------------------------------------ + +int EScene::FrustumSelect(int flag, ObjClassID classfilter) +{ + CFrustum frustum; + int count = 0; + if (!LUI->SelectionFrustum(frustum)) + return 0; + + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; ++_I) + if (_I->second) + count += _I->second->FrustumSelect(flag, frustum); + } + else + { + ESceneToolBase *mt = GetTool(classfilter); + if (mt) + count += mt->FrustumSelect(flag, frustum); + } + + UI->RedrawScene(); + return count; +} +//------------------------------------------------------------------------------ + +void EScene::InvertSelection(ObjClassID classfilter) +{ + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; ++_I) + if (_I->second) + _I->second->InvertSelection(); + } + else + { + ESceneToolBase *mt = GetTool(classfilter); + if (mt) + mt->InvertSelection(); + } + UI->RedrawScene(); +} +//------------------------------------------------------------------------------ + +void EScene::RemoveSelection(ObjClassID classfilter) +{ + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + if (_I->second && _I->second->IsEditable()) + _I->second->RemoveSelection(); + } + else + { + ESceneToolBase *mt = GetTool(classfilter); + if (mt && mt->IsEditable()) + mt->RemoveSelection(); + } + UI->UpdateScene(true); +} +//------------------------------------------------------------------------------ + +int EScene::SelectionCount(bool testflag, ObjClassID classfilter) +{ + int count = 0; + + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + if (_I->second) + count += _I->second->SelectionCount(testflag); + } + else + { + ESceneToolBase *mt = GetTool(classfilter); + if (mt) + count += mt->SelectionCount(testflag); + } + + return count; +} +//------------------------------------------------------------------------------ + +bool EScene::ContainsObject(CCustomObject *object, ObjClassID classfilter) +{ + VERIFY(object); + VERIFY(m_Valid); + ObjectList &lst = ListObj(classfilter); + ObjectIt it = std::find(lst.begin(), lst.end(), object); + if (it != lst.end()) + return true; + return false; +} +//------------------------------------------------------------------------------ + +int EScene::ObjCount() +{ + int cnt = 0; + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + { + ESceneCustomOTool *mt = dynamic_cast(_I->second); + if (mt) + cnt += mt->ObjCount(); + } + return cnt; +} +//------------------------------------------------------------------------------ + +void EScene::ShowObjects(bool flag, ObjClassID classfilter, bool bAllowSelectionFlag, bool bSelFlag) +{ + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + if (_I->second) + _I->second->ShowObjects(flag, bAllowSelectionFlag, bSelFlag); + } + else + { + ESceneToolBase *mt = GetTool(classfilter); + if (mt) + mt->ShowObjects(flag, bAllowSelectionFlag, bSelFlag); + } + UI->RedrawScene(); +} +//------------------------------------------------------------------------------ + +void EScene::SynchronizeObjects() +{ + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + if (_I->second) + _I->second->OnSynchronize(); +} +//------------------------------------------------------------------------------ + +void EScene::ZoomExtents(ObjClassID cls, BOOL bSel) +{ + Fbox BB; + BB.invalidate(); + if (cls == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + if (_I->second) + { + Fbox bb; + bb.invalidate(); + _I->second->GetBBox(bb, bSel); + if (bb.is_valid()) + BB.merge(bb); + } + } + else + { + ESceneToolBase *mt = GetTool(cls); + if (mt) + mt->GetBBox(BB, bSel); + } + if (BB.is_valid()) + EDevice.m_Camera.ZoomExtents(BB); + else + ELog.Msg(mtError, "Can't calculate bounding box. Nothing selected or some object unsupported this function."); +} +//------------------------------------------------------------------------------ diff --git a/src/editors/LevelEditor/Scene/SceneSnap.cpp b/src/editors/LevelEditor/Scene/SceneSnap.cpp new file mode 100644 index 00000000000..1d6bf5cdcbb --- /dev/null +++ b/src/editors/LevelEditor/Scene/SceneSnap.cpp @@ -0,0 +1,213 @@ +#include "stdafx.h" + +ObjectList *EScene::GetSnapList(bool bIgnoreUse) +{ + ObjClassID cls = LTools->CurrentClassID(); + ESceneToolBase *mt = m_SceneTools[cls]; + if (0 == mt) + return 0; + ObjectList *snap_list = mt->GetSnapList() ? mt->GetSnapList() : &m_ESO_SnapObjects; + + return bIgnoreUse ? snap_list : (MainForm->GetLeftBarForm()->IsUseSnapList() ? snap_list : NULL); +} +//-------------------------------------------------------------------------------------------------- + +bool EScene::FindObjectInSnapList(CCustomObject *O) +{ + ObjectList *snap_objects = GetSnapList(true); + return snap_objects ? std::find(snap_objects->begin(), snap_objects->end(), O) != snap_objects->end() : false; +} + +void EScene::RenderSnapList() +{ + ObjectList *lst = GetSnapList(false); + if (lst) + { + for (ObjectIt _F = lst->begin(); _F != lst->end(); _F++) + if ((*_F)->Visible()) + ((CSceneObject *)(*_F))->RenderSelection(); + } +} +//------------------------------------------------------------------------------ + +bool EScene::AddToSnapList(CCustomObject *O, bool bUpdateScene) +{ + if (!O) + return false; + ObjectList *snap_objects = GetSnapList(true); + if (snap_objects) + { + if (std::find(snap_objects->begin(), snap_objects->end(), O) == snap_objects->end()) + { + snap_objects->push_back(O); + if (bUpdateScene) + { + UI->RedrawScene(); + UpdateSnapList(); + UndoSave(); + } + return true; + } + } + return false; +} +//------------------------------------------------------------------------------ + +bool EScene::DelFromSnapList(CCustomObject *O, bool bUpdateScene) +{ + ObjectList *snap_objects = GetSnapList(true); + if (snap_objects) + { + ObjectIt it = std::find(snap_objects->begin(), snap_objects->end(), O); + if (it != snap_objects->end()) + { + snap_objects->erase(it); + if (bUpdateScene) + { + UI->RedrawScene(); + UpdateSnapList(); + UndoSave(); + } + return true; + } + } + return false; +} +//------------------------------------------------------------------------------ + +int EScene::AddSelToSnapList() +{ + int count = 0; + if (GetSnapList(true)) + { + ObjectList lst; + int count = GetQueryObjects(lst, OBJCLASS_SCENEOBJECT, 1, 1, 0); + if (count) + { + count = 0; + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + if (AddToSnapList(*_F, false)) + count++; + if (count) + { + UI->RedrawScene(); + UpdateSnapList(); + UndoSave(); + } + } + } + return count; +} +//------------------------------------------------------------------------------ + +int EScene::DelSelFromSnapList() +{ + int count = 0; + if (GetSnapList(true)) + { + ObjectList lst; + int count = GetQueryObjects(lst, OBJCLASS_SCENEOBJECT, 1, 1, 0); + if (count) + { + count = 0; + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + if (DelFromSnapList(*_F, false)) + count++; + if (count) + { + UI->RedrawScene(); + UpdateSnapList(); + UndoSave(); + } + } + } + return count; +} +//------------------------------------------------------------------------------ + +int EScene::SetSnapList() +{ + ClearSnapList(true); + ObjectList *snap_objects = GetSnapList(true); + int count = 0; + if (snap_objects) + { + ObjectList &lst = ListObj(OBJCLASS_SCENEOBJECT); + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + if ((*_F)->Visible() && (*_F)->Selected()) + { + snap_objects->push_back(*_F); + count++; + } + UI->RedrawScene(); + UpdateSnapList(); + UndoSave(); + } + return count; +} +//------------------------------------------------------------------------------ + +void EScene::ClearSnapList(bool bCurrentOnly) +{ + if (bCurrentOnly) + { + ObjectList *snap_objects = GetSnapList(true); + if (snap_objects) + { + snap_objects->clear(); + UpdateSnapList(); + UndoSave(); + } + } + else + { + m_ESO_SnapObjects.clear(); + for (int i = 0; i < OBJCLASS_COUNT; i++) + { + ESceneToolBase *mt = m_SceneTools[ObjClassID(i)]; + if (mt && mt->GetSnapList()) + mt->GetSnapList()->clear(); + } + UpdateSnapList(); + } +} +//------------------------------------------------------------------------------ + +void EScene::SelectSnapList() +{ + ObjectList *snap_objects = GetSnapList(true); + if (snap_objects) + { + SelectObjects(FALSE, OBJCLASS_SCENEOBJECT); + for (ObjectIt _F = snap_objects->begin(); _F != snap_objects->end(); _F++) + (*_F)->Select(TRUE); + UI->RedrawScene(); + } +} +//------------------------------------------------------------------------------ + +void EScene::UpdateSnapList() +{ + m_RTFlags.set(flUpdateSnapList, TRUE); +} + +void EScene::UpdateSnapListReal() +{ + if (NULL == LTools) + return; + ObjClassID cls = LTools->CurrentClassID(); + switch (cls) + { + case OBJCLASS_DUMMY: + break; + default: + ESceneToolBase *mt = m_SceneTools[cls]; + if (mt) + mt->UpdateSnapList(); + } + // visual update + // if (fraLeftBar) fraLeftBar->UpdateSnapList(); + + m_RTFlags.set(flUpdateSnapList, FALSE); +} +//------------------------------------------------------------------------------ diff --git a/src/editors/LevelEditor/Scene/SceneSummaryInfo.cpp b/src/editors/LevelEditor/Scene/SceneSummaryInfo.cpp new file mode 100644 index 00000000000..8b96db2771c --- /dev/null +++ b/src/editors/LevelEditor/Scene/SceneSummaryInfo.cpp @@ -0,0 +1,529 @@ +#include "stdafx.h" + +static SSceneSummary s_summary; + +xr_token summary_texture_type_tokens[] = +{ + {"Base", SSceneSummary::sttBase}, + {"Implicit", SSceneSummary::sttImplicit}, + {"DO", SSceneSummary::sttDO}, + {"Glow", SSceneSummary::sttGlow}, + {"LOD", SSceneSummary::sttLOD}, + {0, 0} +}; + +void SSceneSummary::Prepare() +{ + for (TISetIt t_it = textures.begin(); t_it != textures.end(); t_it++) + { + STextureInfo *info = (STextureInfo *)(&(*t_it)); + if (!info->bReady) + info->Prepare(); + } + for (OISetIt o_it = objects.begin(); o_it != objects.end(); o_it++) + { + SObjectInfo *info = (SObjectInfo *)(&(*o_it)); + if (!info->bReady) + info->Prepare(); + } +} + +xr_string _itoa(int val) +{ + string64 tmp; + return itoa(val, tmp, 10); +} +void SSceneSummary::SObjectInfo::Prepare() +{ + bReady = true; + if (object_name.size()) + { + CEditableObject *O = Lib.CreateEditObject(object_name.c_str()); + xr_string pref = object_name.c_str(); + if (O) + { + SPairInfo tmp; + tmp.first = pref + "\\References"; + tmp.second = _itoa(ref_count); + info.push_back(tmp); + tmp.first = pref + "\\Geometry\\Faces"; + tmp.second = _itoa(O->GetFaceCount()); + info.push_back(tmp); + tmp.first = pref + "\\Geometry\\Vertices"; + tmp.second = _itoa(O->GetVertexCount()); + info.push_back(tmp); + SurfaceVec &surfaces = O->Surfaces(); + for (SurfaceIt it = surfaces.begin(); it != surfaces.end(); it++) + { + xr_string pr = pref + xr_string("\\Materials\\") + (*it)->_Name(); + tmp.first = pr + "\\Texture"; + tmp.second = (*it)->_Texture(); + info.push_back(tmp); + tmp.first = pr + "\\Faces"; + tmp.second = _itoa(O->GetSurfFaceCount((*it)->_Name())); + info.push_back(tmp); + } + Lib.RemoveEditObject(O); + } + } + else + { + Msg("!Empty object name found."); + } +} +void SSceneSummary::SObjectInfo::FillProp(PropItemVec &items, LPCSTR main_pref) +{ + if (object_name.size()) + { + for (PIVecIt it = info.begin(); it != info.end(); it++) + PHelper().CreateCaption(items, PrepareKey(main_pref, it->first.c_str()), it->second.c_str()); + } +} +void SSceneSummary::SObjectInfo::Export(IWriter *F) +{ + string1024 tmp; + for (PIVecIt it = info.begin(); it != info.end(); it++) + { + sprintf(tmp, "%s=%s", it->first.c_str(), it->second.c_str()); + F->w_string(tmp); + } +} + +void SSceneSummary::STextureInfo::Prepare() +{ + bReady = true; + if (file_name.size()) + { + ETextureThumbnail *T = (ETextureThumbnail *)ImageLib.CreateThumbnail(file_name.c_str(), ECustomThumbnail::ETTexture, true); + if (!T->Valid()) + { + Msg("!Can't get info from texture: '%s'", file_name.c_str()); + } + else + { + info = T->_Format(); + if (info.flags.is(STextureParams::flImplicitLighted)) + type = sttImplicit; + } + xr_delete(T); + } + else + { + Msg("!Empty texture name found."); + } +} + +void SSceneSummary::STextureInfo::OnHighlightClick(ButtonValue *sender, bool &bDataModified, bool &bSafe) +{ + ButtonValue *V = dynamic_cast(sender); + R_ASSERT(V); + switch (V->btn_num) + { + case 0: + Scene->HighlightTexture((LPCSTR)sender->tag, false, info.width, info.height, false); + break; + case 1: + Scene->HighlightTexture((LPCSTR)sender->tag, true, info.width, info.height, false); + break; + case 2: + Scene->HighlightTexture((LPCSTR)sender->tag, true, info.width, info.height, true); + break; + case 3: + ExecCommand(COMMAND_CLEAR_DEBUG_DRAW); + break; + } + + bDataModified = false; + bSafe = false; +} + +void SSceneSummary::STextureInfo::FillProp(PropItemVec &items, LPCSTR main_pref, u32 &mem_use) +{ + if (file_name.size()) + { + int tex_mem = info.MemoryUsage(*file_name); + mem_use += tex_mem; + xr_string pref = PrepareKey(xr_string(main_pref).c_str(), *file_name).c_str(); + PropValue *V = 0; + V = PHelper().CreateChoose(items, PrepareKey(pref.c_str(), "Texture"), &file_name, smTexture); + V->Owner()->Enable(FALSE); + PHelper().CreateCaption(items, PrepareKey(pref.c_str(), "Format"), info.FormatString()); + PHelper().CreateCaption(items, PrepareKey(pref.c_str(), "Size"), shared_str().printf("%d x %d x %s", info.width, info.height, info.HasAlpha() ? "32b" : "24b")); + PHelper().CreateCaption(items, PrepareKey(pref.c_str(), "Memory Usage"), shared_str().printf("%d Kb", iFloor(tex_mem / 1024.f))); + PHelper().CreateCaption(items, PrepareKey(pref.c_str(), "Effective Area"), shared_str().printf("%3.2f m^2", effective_area)); + PHelper().CreateCaption(items, PrepareKey(pref.c_str(), "Pixel Density"), shared_str().printf("%3.2f p/m", _sqrt((pixel_area * info.width * info.height) / effective_area))); + /* + //. убрал из-за кол-ва > 4096 + xr_string tmp = "on demand"; + for (objinf_map_it o_it=objects.begin(); o_it!=objects.end(); o_it++){ + tmp += make_string("%s%s[%d*%3.2f]",tmp.Length()?"; ":"",o_it->first.c_str(),o_it->second.ref_count,o_it->second.area); + } + PHelper().CreateCaption(items,PrepareKey(pref.c_str(),"Objects"), tmp.c_str()); + */ + if (info.flags.is_any(STextureParams::flDiffuseDetail | STextureParams::flBumpDetail)) + { + if (0 != info.detail_name.size()) + { + V = PHelper().CreateChoose(items, PrepareKey(pref.c_str(), "Detail Texture"), &info.detail_name, smTexture); + V->Owner()->Enable(FALSE); + PHelper().CreateCaption(items, PrepareKey(pref.c_str(), "Detail Scale"), shared_str().printf("%3.2f", info.detail_scale)); + } + else + { + PHelper().CreateCaption(items, PrepareKey(pref.c_str(), "Detail Texture"), "INVALID"); + ELog.Msg(mtError, "Empty details on texture: '%s'", *file_name); + } + } + if (info.bump_mode == STextureParams::tbmUse) + { + if (0 != info.bump_name.size()) + { + V = PHelper().CreateChoose(items, PrepareKey(pref.c_str(), "Bump Texture"), &info.bump_name, smTexture); + V->Owner()->Enable(FALSE); + } + else + { + PHelper().CreateCaption(items, PrepareKey(pref.c_str(), "Bump Texture"), "INVALID"); + ELog.Msg(mtError, "Empty bump on texture: '%s'", *file_name); + } + } + ButtonValue *B = PHelper().CreateButton(items, PrepareKey(pref.c_str(), "Highlight Texture"), "Select,Density =,Density +,Clear", 0); + B->OnBtnClickEvent.bind(this, &SSceneSummary::STextureInfo::OnHighlightClick); + B->tag = (size_t)(*file_name); + } +} +void SSceneSummary::STextureInfo::Export(IWriter *F, u32 &mem_use) +{ + string128 mask; + strcpy(mask, "%s=%s,%d,%d,%s,%d,%3.2f,%3.2f,%s"); + if (info.flags.is_any(STextureParams::flDiffuseDetail | STextureParams::flBumpDetail)) + { + if (0 != info.detail_name.size()) + { + strcat(mask, ",%s,%3.2f"); + } + } + if (info.bump_mode == STextureParams::tbmUse) + { + if (0 != info.bump_name.size()) + { + strcat(mask, ",%s"); + } + } + xr_string tmp2; + for (objinf_map_it o_it = objects.begin(); o_it != objects.end(); o_it++) + { + tmp2 += make_string("%s%s[%d*%3.2f]", tmp2.size() ? "; " : "", o_it->first.c_str(), o_it->second.ref_count, o_it->second.area); + } + int tex_mem = info.MemoryUsage(*file_name); + mem_use += tex_mem; + auto tmp = make_string(mask, *file_name, info.FormatString(), + info.width, info.height, info.HasAlpha() ? "present" : "absent", + iFloor(tex_mem / 1024.f), + effective_area, _sqrt((pixel_area * info.width * info.height) / effective_area), tmp2.c_str(), + *info.detail_name, info.detail_scale, *info.bump_name); + F->w_string(tmp.c_str()); +} + +void SSceneSummary::OnFileClick(ButtonValue *sender, bool &bModif, bool &bSafe) +{ + ButtonValue *V = dynamic_cast(sender); + R_ASSERT(V); + switch (V->btn_num) + { + case 0: + { + xr_string fn = Scene->m_LevelOp.m_FNLevelPath.c_str(); + if (EFS.GetSaveName(_import_, fn, 0, 2)) + if (ExportSummaryInfo(fn.c_str())) + ELog.DlgMsg(mtInformation, "Export completed."); + else + ELog.DlgMsg(mtInformation, "Export failed."); + } + break; + } + bModif = false; +} +void SSceneSummary::OnHighlightClick(ButtonValue *V, bool &bDataModified, bool &bSafe) +{ + switch (V->btn_num) + { + case 0: + { + ExecCommand(COMMAND_CLEAR_DEBUG_DRAW); + for (TISetIt it = textures.begin(); it != textures.end(); it++) + { + STextureInfo *info = (STextureInfo *)(&(*it)); + if (info->type == sttBase) + Scene->HighlightTexture(info->file_name.c_str(), true, info->info.width, info->info.height, true); + } + } + break; + case 1: + ExecCommand(COMMAND_CLEAR_DEBUG_DRAW); + break; + } + + bDataModified = false; + bSafe = false; +} + +bool SSceneSummary::ExportSummaryInfo(LPCSTR fn) +{ + IWriter *F = FS.w_open(fn); + if (F) + { + string256 tmp; + // textures + u32 total_mem_usage = 0; + F->w_string("[TEXTURES]"); + F->w_string("texture name=format,width,height,alpha,mem usage (Kb),area,pixel density,objects (name[count*area]),detail name,detail scale,bump name"); + for (u32 stt = sttFirst; stt < sttLast; stt++) + { + u32 cur_mem_usage = 0; + float cur_area = 0; + xr_string pref = "["; + pref += get_token_name(summary_texture_type_tokens, stt); + pref += "]"; + F->w_string(pref.c_str()); + for (TISetIt it = textures.begin(); it != textures.end(); it++) + { + STextureInfo *info = (STextureInfo *)(&(*it)); + if (info->type == stt) + { + cur_area += info->effective_area; + info->Export(F, cur_mem_usage); + } + } + total_mem_usage += cur_mem_usage; + sprintf(tmp, "%s mem usage - %d Kb", pref.c_str(), cur_mem_usage); + F->w_string(tmp); + sprintf(tmp, "%s effective area - %3.2f m^2", pref.c_str(), cur_area); + F->w_string(tmp); + } + sprintf(tmp, "Total mem usage - %d Kb", total_mem_usage); + F->w_string(tmp); + // objects + F->w_string(""); + sprintf(tmp, "[OBJECTS]"); + F->w_string(tmp); + for (OISetIt o_it = objects.begin(); o_it != objects.end(); o_it++) + { + SObjectInfo *info = (SObjectInfo *)(&(*o_it)); + info->Export(F); + } + FS.w_close(F); + return true; + } + else + { + return false; + } +} +bool SSceneSummary::OnWeightAfterEditClick(PropValue *sender, float &edit_val) +{ + if (sender->tag == 0) + { + return edit_val < pm_colors[sender->tag + 1].pm; + } + else if (sender->tag == pm_colors.size() - 1) + { + return edit_val > pm_colors[sender->tag - 1].pm; + } + else + { + return edit_val > pm_colors[sender->tag - 1].pm && edit_val < pm_colors[sender->tag + 1].pm; + } +} +void SSceneSummary::FillProp(PropItemVec &items) +{ + // fill items + ButtonValue *B = PHelper().CreateButton(items, "Common\\File", "Export...", 0); + B->OnBtnClickEvent.bind(this, &SSceneSummary::OnFileClick); + // fill items + PHelper().CreateCaption(items, "Common\\Level Name", Scene->m_LevelOp.m_FNLevelPath.c_str()); + PHelper().CreateCaption(items, "Geometry\\Bounding\\Min", shared_str().printf("{%3.2f, %3.2f, %3.2f}", VPUSH(bbox.vMin))); + PHelper().CreateCaption(items, "Geometry\\Bounding\\Max", shared_str().printf("{%3.2f, %3.2f, %3.2f}", VPUSH(bbox.vMax))); + PHelper().CreateCaption(items, "Geometry\\Mesh\\Total Faces", shared_str().printf("%d", face_cnt)); + PHelper().CreateCaption(items, "Geometry\\Mesh\\Total Vertices", shared_str().printf("%d", vert_cnt)); + PHelper().CreateCaption(items, "Geometry\\MU\\Objects", shared_str().printf("%d", mu_objects.size())); + PHelper().CreateCaption(items, "Geometry\\MU\\References", shared_str().printf("%d", object_mu_ref_cnt)); + PHelper().CreateCaption(items, "Geometry\\LOD\\Objects", shared_str().printf("%d", lod_objects.size())); + PHelper().CreateCaption(items, "Geometry\\LOD\\References", shared_str().printf("%d", object_lod_ref_cnt)); + PHelper().CreateCaption(items, "Visibility\\HOM\\Faces", shared_str().printf("%d", hom_face_cnt)); + PHelper().CreateCaption(items, "Visibility\\HOM\\Vertices", shared_str().printf("%d", hom_vert_cnt)); + PHelper().CreateCaption(items, "Visibility\\Sectors", shared_str().printf("%d", sector_cnt)); + PHelper().CreateCaption(items, "Visibility\\Portals", shared_str().printf("%d", portal_cnt)); + PHelper().CreateCaption(items, "Lights\\Count", shared_str().printf("%d", light_point_cnt + light_spot_cnt)); + PHelper().CreateCaption(items, "Lights\\By Type\\Point", shared_str().printf("%d", light_point_cnt)); + PHelper().CreateCaption(items, "Lights\\By Type\\Spot", shared_str().printf("%d", light_spot_cnt)); + PHelper().CreateCaption(items, "Lights\\By Usage\\Dynamic", shared_str().printf("%d", light_dynamic_cnt)); + PHelper().CreateCaption(items, "Lights\\By Usage\\Static", shared_str().printf("%d", light_static_cnt)); + PHelper().CreateCaption(items, "Lights\\By Usage\\Breakable", shared_str().printf("%d", light_breakable_cnt)); + PHelper().CreateCaption(items, "Lights\\By Usage\\Procedural", shared_str().printf("%d", light_procedural_cnt)); + PHelper().CreateCaption(items, "Glows\\Count", shared_str().printf("%d", glow_cnt)); + // objects + for (OISetIt o_it = objects.begin(); o_it != objects.end(); o_it++) + { + SObjectInfo *info = (SObjectInfo *)(&(*o_it)); + info->FillProp(items, "Objects"); + } + // textures + CaptionValue *total_count = PHelper().CreateCaption(items, "Textures\\Count", ""); + CaptionValue *total_mem = PHelper().CreateCaption(items, "Textures\\Memory Usage", ""); + u32 total_mem_usage = 0; + ButtonValue *BB = PHelper().CreateButton(items, "Textures\\Highlight Textures\\Command", "Pixel Density,Clear", ButtonValue::flFirstOnly); + BB->OnBtnClickEvent.bind(this, &SSceneSummary::OnHighlightClick); + for (PDVecIt pd_it = pm_colors.begin(); pd_it != pm_colors.end(); pd_it++) + { + string128 tmp; + sprintf(tmp, "Textures\\Highlight Textures\\Color Legend\\Item #%d", static_cast(pd_it - pm_colors.begin())); + PHelper().CreateColor(items, PrepareKey(tmp, "Color").c_str(), &pd_it->color); + FloatValue *V = PHelper().CreateFloat(items, PrepareKey(tmp, "Weight (p/m)").c_str(), &pd_it->pm, 0, 1000000, 1, 0); + V->OnAfterEditEvent.bind(this, &SSceneSummary::OnWeightAfterEditClick); + V->tag = pd_it - pm_colors.begin(); + } + for (u32 stt = sttFirst; stt < sttLast; stt++) + { + LPCSTR nm = get_token_name(summary_texture_type_tokens, stt); + if (nm && nm[0]) + { + u32 cur_mem_usage = 0; + float cur_area = 0; + shared_str pref = PrepareKey("Textures", nm); + CaptionValue *mem = PHelper().CreateCaption(items, PrepareKey(pref.c_str(), "Memory Usage").c_str(), ""); + CaptionValue *area = PHelper().CreateCaption(items, PrepareKey(pref.c_str(), "Effective Area").c_str(), ""); + for (TISetIt it = textures.begin(); it != textures.end(); it++) + { + STextureInfo *info = (STextureInfo *)(&(*it)); + if (info->type == stt) + { + cur_area += info->effective_area; + info->FillProp(items, pref.c_str(), cur_mem_usage); + } + } + mem->ApplyValue(shared_str().printf("%d Kb", iFloor(cur_mem_usage / 1024.f))); + area->ApplyValue(shared_str().printf("%3.2f m^2", cur_area)); + total_mem_usage += cur_mem_usage; + } + } + total_count->ApplyValue(shared_str().printf("%d", textures.size())); + total_mem->ApplyValue(shared_str().printf("%d Kb", iFloor(total_mem_usage / 1024.f))); + // sound + PHelper().CreateCaption(items, "Sounds\\Occluder\\Faces", shared_str().printf("%d", snd_occ_face_cnt)); + PHelper().CreateCaption(items, "Sounds\\Occluder\\Vertices", shared_str().printf("%d", snd_occ_vert_cnt)); + PHelper().CreateCaption(items, "Sounds\\Sources", shared_str().printf("%d", sound_source_cnt)); + PHelper().CreateCaption(items, "Sounds\\Waves\\Count", shared_str().printf("%d", waves.size())); + for (RStringSetIt w_it = waves.begin(); w_it != waves.end(); w_it++) + PHelper().CreateCaption(items, PrepareKey("Sounds\\Waves", w_it->c_str()), "-"); + // particles + PHelper().CreateCaption(items, "Particle System\\Sources", shared_str().printf("%d", pe_static_cnt)); + PHelper().CreateCaption(items, "Particle System\\Refs\\Count", shared_str().printf("%d", pe_static.size())); + for (RStringSetIt pe_it = pe_static.begin(); pe_it != pe_static.end(); pe_it++) + PHelper().CreateCaption(items, PrepareKey("Particle System\\Refs", pe_it->c_str()), "-"); +} + +SSceneSummary::SSceneSummary() +{ + Clear(); + pm_colors.push_back(SPixelDensityPair(0, 0x80FF0000)); + pm_colors.push_back(SPixelDensityPair(100, 0x80FFFF00)); + pm_colors.push_back(SPixelDensityPair(200, 0x8000FF00)); + pm_colors.push_back(SPixelDensityPair(500, 0x8000FFFF)); + pm_colors.push_back(SPixelDensityPair(1000, 0x800000FF)); +} + +void SSceneSummary::Save(CInifile *I) +{ + I->w_u32("summary_info", "pm_count", s_summary.pm_colors.size()); + for (u32 idx = 0; idx < s_summary.pm_colors.size(); ++idx) + { + string128 tmp; + sprintf(tmp, "pm_item_%d_color", idx); + I->w_u32("summary_info", tmp, s_summary.pm_colors[idx].color); + sprintf(tmp, "pm_item_%d_weight", idx); + I->w_float("summary_info", tmp, s_summary.pm_colors[idx].pm); + } +} + +void SSceneSummary::Load(CInifile *I) +{ + if (I->section_exist("summary_info") && I->line_exist("summary_info", "pm_count") && (5 == I->r_u32("summary_info", "pm_count"))) + { + for (u32 idx = 0; idx < s_summary.pm_colors.size(); ++idx) + { + string128 tmp; + sprintf(tmp, "pm_item_%d_color", idx); + s_summary.pm_colors[idx].color = R_U32_SAFE("summary_info", tmp, s_summary.pm_colors[idx].color); + sprintf(tmp, "pm_item_%d_weight", idx); + s_summary.pm_colors[idx].pm = R_FLOAT_SAFE("summary_info", tmp, s_summary.pm_colors[idx].pm); + } + } + std::sort(s_summary.pm_colors.begin(), s_summary.pm_colors.end()); +} + +u32 SSceneSummary::SelectPMColor(float pm) +{ + VERIFY(!s_summary.pm_colors.empty()); + u32 from; + u32 to; + float w = 0.f; + if (pm < s_summary.pm_colors[0].pm) + { + from = s_summary.pm_colors[0].color; + to = s_summary.pm_colors[0].color; + } + else if (pm >= s_summary.pm_colors[s_summary.pm_colors.size() - 1].pm) + { + from = s_summary.pm_colors.back().color; + to = s_summary.pm_colors.back().color; + } + else + { + u32 idx_clr = 0; + for (; idx_clr < s_summary.pm_colors.size() - 1; ++idx_clr) + if (pm >= s_summary.pm_colors[idx_clr].pm && pm < s_summary.pm_colors[idx_clr + 1].pm) + break; + w = (pm - s_summary.pm_colors[idx_clr].pm) / float(s_summary.pm_colors[idx_clr + 1].pm); + from = s_summary.pm_colors[idx_clr + 0].color; + to = s_summary.pm_colors[idx_clr + 1].color; + } + + const float inv_w = 1.f - w; + const u32 r = static_cast(color_get_R(from) * inv_w + color_get_R(to) * w); + const u32 g = static_cast(color_get_G(from) * inv_w + color_get_G(to) * w); + const u32 b = static_cast(color_get_B(from) * inv_w + color_get_B(to) * w); + const u32 a = static_cast(color_get_A(from) * inv_w + color_get_A(to) * w); + return color_rgba(r, g, b, a); +} + +void EScene::ClearSummaryInfo() +{ + s_summary.Clear(); +} + +void EScene::CollectSummaryInfo() +{ + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + if (_I->second) + _I->second->GetSummaryInfo(&s_summary); + s_summary.Prepare(); +} + +void EScene::ShowSummaryInfo() +{ + PropItemVec items; + // fill items + s_summary.FillProp(items); + + /* m_SummaryInfo->ShowProperties (); + m_SummaryInfo->AssignItems (items);*/ +} + +void EScene::ExportSummaryInfo(LPCSTR f_name) +{ + s_summary.ExportSummaryInfo(f_name); +} +//-------------------------------------------------------------------------------------------------- diff --git a/src/editors/LevelEditor/Scene/SceneSummaryInfo.h b/src/editors/LevelEditor/Scene/SceneSummaryInfo.h new file mode 100644 index 00000000000..b485d811d16 --- /dev/null +++ b/src/editors/LevelEditor/Scene/SceneSummaryInfo.h @@ -0,0 +1,198 @@ +#pragma once +#include "Layers/xrRender/ETextureParams.h" + +class SSceneSummary +{ +public: + enum ESummaryTextureType + { + sttFirst = 0, + sttBase = 0, + sttImplicit, + sttDetail, + sttBump, + sttDO, + sttGlow, + sttLOD, + sttLast + }; // не забывать токен менять +private: + struct STextureInfo + { + shared_str file_name; + STextureParams info; + ESummaryTextureType type; + bool bReady; + struct SObjInfo + { + int ref_count; + float area; + SObjInfo(float a) : ref_count(0), area(a) {} + }; + DEFINE_MAP(shared_str, SObjInfo, objinf_map, objinf_map_it); + objinf_map objects; + float effective_area; + float pixel_area; + void OnHighlightClick(ButtonValue *sender, bool &bDataModified, bool &bSafe); + + public: + STextureInfo(const shared_str &fn, ESummaryTextureType t) + { + file_name = fn; + ZeroMemory(&info, sizeof(info)); + type = t; + effective_area = 0; + pixel_area = 0; + bReady = false; + } + void Prepare(); + void FillProp(PropItemVec &items, LPCSTR pref, u32 &mem_use); + void Export(IWriter *F, u32 &mem_use); + bool operator<(const STextureInfo &other) const { return xr_strcmp(file_name, other.file_name) < 0; }; + bool operator<(const shared_str &fn) const { return xr_strcmp(file_name, fn) < 0; }; + bool operator==(const shared_str &fn) const { return file_name.equal(fn); }; + }; + DEFINE_SET(STextureInfo, TISet, TISetIt); + TISet textures; + struct SPairInfo + { + xr_string first; + xr_string second; + }; + DEFINE_VECTOR(SPairInfo, PIVec, PIVecIt); + struct SObjectInfo + { + shared_str object_name; + PIVec info; + u32 ref_count; + bool bReady; + + public: + SObjectInfo(const shared_str &name) + { + object_name = name; + ref_count = 0; + bReady = false; + } + void Prepare(); + void FillProp(PropItemVec &items, LPCSTR prvectoref); + void Export(IWriter *F); + bool operator<(const SObjectInfo &other) const { return xr_strcmp(object_name, other.object_name) < 0; }; + bool operator<(const shared_str &fn) const { return xr_strcmp(object_name, fn) < 0; }; + bool operator==(const shared_str &fn) const { return object_name.equal(fn); }; + }; + DEFINE_SET(SObjectInfo, OISet, OISetIt); + OISet objects; + +public: + RStringSet lod_objects; + RStringSet mu_objects; + RStringSet waves; + RStringSet pe_static; + int face_cnt; + int vert_cnt; + int hom_face_cnt, hom_vert_cnt; + int snd_occ_face_cnt, snd_occ_vert_cnt; + int object_mu_ref_cnt; + int object_lod_ref_cnt; + int light_point_cnt; + int light_spot_cnt; + int light_dynamic_cnt; + int light_static_cnt; + int light_breakable_cnt; + int light_procedural_cnt; + int glow_cnt; + int sector_cnt; + int portal_cnt; + int sound_source_cnt; + int pe_static_cnt; + Fbox bbox; + +private: + void OnFileClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnHighlightClick(ButtonValue *sender, bool &bDataModified, bool &bSafe); + +public: + void Prepare(); + +protected: + struct SPixelDensityPair + { + float pm; + u32 color; + SPixelDensityPair(float _pm, u32 _c) : pm(_pm), color(_c) {} + bool operator<(const SPixelDensityPair &other) const { return pm < other.pm; }; + }; + DEFINE_VECTOR(SPixelDensityPair, PDVec, PDVecIt); + PDVec pm_colors; + bool OnWeightAfterEditClick(PropValue *sender, float &edit_val); + +public: + static u32 SelectPMColor(float pm); + +public: + SSceneSummary(); + void AppendTexture(shared_str name, ESummaryTextureType type, float area, float pixel_area, shared_str obj_name) + { + TISetIt it = std::find(textures.begin(), textures.end(), name); + if (it == textures.end()) + { + std::pair res = textures.insert(STextureInfo(name, type)); + it = res.first; + } + STextureInfo *info = (STextureInfo *)(&(*it)); + + STextureInfo::objinf_map_it o_it = info->objects.find(obj_name); + if (o_it == info->objects.end()) + { + std::pair res = info->objects.insert(std::make_pair(obj_name, STextureInfo::SObjInfo(area))); + o_it = res.first; + } + o_it->second.ref_count++; + info->effective_area += area; + info->pixel_area += pixel_area; + } + void AppendObject(shared_str name) + { + OISetIt it = std::find(objects.begin(), objects.end(), name); + if (it == objects.end()) + { + std::pair res = objects.insert(SObjectInfo(name)); + it = res.first; + } + SObjectInfo *info = (SObjectInfo *)(&(*it)); + info->ref_count++; + } + bool ExportSummaryInfo(LPCSTR fn); + void FillProp(PropItemVec &items); + void Clear() + { + bbox.invalidate(); + textures.clear(); + lod_objects.clear(); + mu_objects.clear(); + waves.clear(); + pe_static; + face_cnt = 0; + vert_cnt = 0; + hom_face_cnt = 0; + hom_vert_cnt = 0; + snd_occ_face_cnt = 0; + snd_occ_vert_cnt = 0; + object_mu_ref_cnt = 0; + object_lod_ref_cnt = 0; + light_point_cnt = 0; + light_spot_cnt = 0; + light_dynamic_cnt = 0; + light_static_cnt = 0; + light_breakable_cnt = 0; + light_procedural_cnt = 0; + glow_cnt = 0; + sector_cnt = 0; + portal_cnt = 0; + sound_source_cnt = 0; + pe_static_cnt = 0; + } + static void Load(CInifile *I); + static void Save(CInifile *I); +}; diff --git a/src/editors/LevelEditor/Scene/SceneUndo.cpp b/src/editors/LevelEditor/Scene/SceneUndo.cpp new file mode 100644 index 00000000000..7da0030b00b --- /dev/null +++ b/src/editors/LevelEditor/Scene/SceneUndo.cpp @@ -0,0 +1,98 @@ +#include "stdafx.h" + +void EScene::UndoClear() +{ + while (!m_RedoStack.empty()) + { + unlink(m_RedoStack.back().m_FileName); + m_RedoStack.pop_back(); + } + while (!m_UndoStack.empty()) + { + unlink(m_UndoStack.back().m_FileName); + m_UndoStack.pop_back(); + } +} + +void EScene::UndoSave() +{ + if (UI->GetEState() != esEditScene) + return; + Modified(); + UI->RedrawScene(); + + if (0 == EPrefs->scene_undo_level) + return; + + UndoItem item; + GetTempFileName(FS.get_path(_temp_)->m_Path, "undo", 0, item.m_FileName); + + Save(item.m_FileName, true, true); + m_UndoStack.push_back(item); + + while (!m_RedoStack.empty()) + { + unlink(m_RedoStack.back().m_FileName); + m_RedoStack.pop_back(); + } + + if (m_UndoStack.size() > EPrefs->scene_undo_level) + { + unlink(m_UndoStack.front().m_FileName); + m_UndoStack.pop_front(); + } +} + +bool EScene::Undo() +{ + // if( !m_UndoStack.empty() ){ + if (m_UndoStack.size() > 1) + { + m_RedoStack.push_back(m_UndoStack.back()); + m_UndoStack.pop_back(); + + if (m_RedoStack.size() > EPrefs->scene_undo_level) + { + unlink(m_RedoStack.front().m_FileName); + m_RedoStack.pop_front(); + } + + if (!m_UndoStack.empty()) + { + Unload(TRUE); + Load(m_UndoStack.back().m_FileName, true); + } + + UI->UpdateScene(); + Modified(); + + return true; + } + return false; +} + +bool EScene::Redo() +{ + if (!m_RedoStack.empty()) + { + Unload(TRUE); + Load(m_RedoStack.back().m_FileName, true); + + m_UndoStack.push_back(m_RedoStack.back()); + m_RedoStack.pop_back(); + + if (m_UndoStack.size() > EPrefs->scene_undo_level) + { + unlink(m_UndoStack.front().m_FileName); + m_UndoStack.pop_front(); + } + + UI->UpdateScene(); + Modified(); + + return true; + } + return false; +} + +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Scene/SceneUtil.cpp b/src/editors/LevelEditor/Scene/SceneUtil.cpp new file mode 100644 index 00000000000..301abf8f7ac --- /dev/null +++ b/src/editors/LevelEditor/Scene/SceneUtil.cpp @@ -0,0 +1,100 @@ +#include "stdafx.h" + +CCustomObject *EScene::FindObjectByName(LPCSTR name, ObjClassID classfilter) +{ + if (!name) + return NULL; + + CCustomObject *object = 0; + if (classfilter == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; ++_I) + { + ESceneCustomOTool *mt = dynamic_cast(_I->second); + + if (mt && (0 != (object = mt->FindObjectByName(name)))) + return object; + } + } + else + { + ESceneCustomOTool *mt = GetOTool(classfilter); + VERIFY(mt); + if (mt && (0 != (object = mt->FindObjectByName(name)))) + return object; + } + return object; +} + +CCustomObject *EScene::FindObjectByName(LPCSTR name, CCustomObject *pass_object) +{ + CCustomObject *object = 0; + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + { + ESceneCustomOTool *mt = dynamic_cast(_I->second); + if (mt && (0 != (object = mt->FindObjectByName(name, pass_object)))) + return object; + } + return 0; +} + +bool EScene::FindDuplicateName() +{ + // find duplicate name + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + { + ESceneCustomOTool *mt = dynamic_cast(_I->second); + if (mt) + { + ObjectList &lst = mt->GetObjects(); + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + if (FindObjectByName((*_F)->GetName(), *_F)) + { + ELog.DlgMsg(mtError, "Duplicate object name already exists: '%s'", (*_F)->GetName()); + return true; + } + } + } + return false; +} + +void EScene::GenObjectName(ObjClassID cls_id, char *buffer, const char *pref) +{ + for (int i = 0; true; i++) + { + bool result; + std::string temp; + if (pref) + { + if (i == 0) + { + if (*pref == '\0') + { + ESceneCustomOTool* ot = GetOTool(cls_id); + VERIFY(ot); + pref = ot->ClassName(); + } + + temp = pref; + } + else + temp = make_string("%s_%02d", pref, i - 1); + } + else + temp = make_string("%02d", i); + + FindObjectByNameCB(temp.c_str(), result); + + if (!result) + { + xr_strcpy(buffer, 256, temp.c_str()); + return; + } + } +} diff --git a/src/editors/LevelEditor/Scene/Scene_Tools.cpp b/src/editors/LevelEditor/Scene/Scene_Tools.cpp new file mode 100644 index 00000000000..cbe7669556a --- /dev/null +++ b/src/editors/LevelEditor/Scene/Scene_Tools.cpp @@ -0,0 +1,43 @@ +#include "stdafx.h" + +void EScene::RegisterSceneTools(ESceneToolBase *mt) +{ + m_SceneTools[mt->FClassID] = mt; + mt->OnCreate(); +} + +void EScene::CreateSceneTools() +{ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ + RegisterSceneTools(xr_new()); //+ +} + +void EScene::DestroySceneTools() +{ + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + { + if (_I->second) + _I->second->OnDestroy(); + + xr_delete(_I->second); + } + m_SceneTools.clear(); +} diff --git a/src/editors/LevelEditor/Scene/mesh_data.h b/src/editors/LevelEditor/Scene/mesh_data.h new file mode 100644 index 00000000000..7ed99c3d430 --- /dev/null +++ b/src/editors/LevelEditor/Scene/mesh_data.h @@ -0,0 +1,22 @@ +#ifndef _MESH_DATA_H_ +#define _MESH_DATA_H_ +namespace CDB +{ + class TRI; +} +struct mesh_build_data +{ + int l_vert_cnt, l_vert_it; + int l_face_cnt, l_face_it; + Fvector *l_verts; + CDB::TRI *l_faces; + + mesh_build_data() : l_verts(0), l_faces(0), l_vert_cnt(0), l_vert_it(0), l_face_cnt(0), l_face_it(0) {} + ~mesh_build_data() + { + R_ASSERT(!l_verts); + R_ASSERT(!l_faces); + } +}; + +#endif diff --git a/src/editors/LevelEditor/Scene/scene.cpp b/src/editors/LevelEditor/Scene/scene.cpp new file mode 100644 index 00000000000..182586f27a5 --- /dev/null +++ b/src/editors/LevelEditor/Scene/scene.cpp @@ -0,0 +1,677 @@ +#include "stdafx.h" + +EScene *Scene; + +st_LevelOptions::st_LevelOptions() +{ + Reset(); +} + +void st_LevelOptions::Reset() +{ + m_FNLevelPath = "level"; + m_LevelPrefix = "level_prefix"; + m_LightHemiQuality = 3; + m_LightSunQuality = 3; + m_BOPText = ""; + m_map_version = "1.0"; + m_BuildParams.Init(); + m_BuildParams.setHighQuality(); + m_mapUsage.SetDefaults(); +} + +void st_LevelOptions::SetCustomQuality() +{ + m_BuildParams.m_quality = ebqCustom; +} + +void st_LevelOptions::SetDraftQuality() +{ + m_BuildParams.setDraftQuality(); + m_LightHemiQuality = 0; + m_LightSunQuality = 0; +} + +void st_LevelOptions::SetHighQuality() +{ + m_BuildParams.setHighQuality(); + m_LightHemiQuality = 3; + m_LightSunQuality = 3; +} +//------------------------------------------------------------------------------ + +#define MAX_VISUALS 16384 +#ifdef USE_ARENA_ALLOCATOR +char* s_fake_array = nullptr; +#endif +EScene::EScene() +{ +#ifdef USE_ARENA_ALLOCATOR + s_fake_array = xr_new(64 * 1024 * 1024); +#endif + m_Valid = false; + m_Locked = 0; + + for (int i = 0; i < OBJCLASS_COUNT; i++) + m_SceneTools.insert(std::make_pair((ObjClassID)i, (ESceneToolBase *)NULL)); + + // first init scene graph for objects + // mapRenderObjects.init(MAX_VISUALS); + // Build options + m_SummaryInfo = 0; + // ClearSnapList (false); + // g_frmConflictLoadObject = xr_new((TComponent*)NULL); +} + +EScene::~EScene() +{ + // xr_delete(g_frmConflictLoadObject); + VERIFY(m_Valid == false); + m_ESO_SnapObjects.clear(); + +#ifdef USE_ARENA_ALLOCATOR + xr_free(s_fake_array); +#endif +} + +void EScene::OnCreate() +{ + CreateSceneTools(); + + m_LastAvailObject = 0; + m_LevelOp.Reset(); + ELog.Msg(mtInformation, "Scene: initialized"); + m_Valid = true; + m_RTFlags.zero(); + ExecCommand(COMMAND_UPDATE_CAPTION); + // m_SummaryInfo = TProperties::CreateForm("Level Summary Info", 0, alNone, 0,0,0, TProperties::plFolderStore|TProperties::plItemFolders); +} + +void EScene::OnDestroy() +{ + g_scene_physics.DestroyAll(); + + // TProperties::DestroyForm(m_SummaryInfo); + Unload(FALSE); + UndoClear(); + ELog.Msg(mtInformation, "Scene: cleared"); + m_LastAvailObject = 0; + m_Valid = false; + DestroySceneTools(); +} + +void EScene::AppendObject(CCustomObject *object, bool bUndo) +{ + VERIFY(object); + VERIFY(m_Valid); + + ESceneCustomOTool *mt = GetOTool(object->FClassID); + VERIFY3(mt, "Can't find Object Tools:", GetTool(object->FClassID)->ClassDesc()); + mt->_AppendObject(object); + UI->UpdateScene(); + if (bUndo) + { + object->Select(true); + UndoSave(); + } +} + +bool EScene::RemoveObject(CCustomObject *object, bool bUndo, bool bDeleting) +{ + VERIFY(object); + VERIFY(m_Valid); + + ESceneCustomOTool *mt = GetOTool(object->FClassID); + if (mt && mt->IsEditable()) + { + mt->_RemoveObject(object); + // signal everyone "I'm deleting" + // if (object->ClassID==OBJCLASS_SCENEOBJECT) + { + m_ESO_SnapObjects.remove(object); + + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + { + ESceneToolBase *mt = _I->second; + if (mt) + mt->OnObjectRemove(object, bDeleting); + } + UpdateSnapList(); + } + UI->UpdateScene(); + } + if (bUndo) + UndoSave(); + return true; +} + +void EScene::BeforeObjectChange(CCustomObject *object) +{ + VERIFY(object); + VERIFY(m_Valid); + + ESceneCustomOTool *mt = GetOTool(object->FClassID); + if (mt && mt->IsEditable()) + { + SceneToolsMapPairIt _I = m_SceneTools.begin(); + SceneToolsMapPairIt _E = m_SceneTools.end(); + for (; _I != _E; _I++) + { + ESceneToolBase *mt = _I->second; + if (mt) + mt->OnBeforeObjectChange(object); + } + UI->UpdateScene(); + } +} + +int EScene::MultiRenameObjects() +{ + int cnt = 0; + + if (LTools->GetTarget() == OBJCLASS_DUMMY) + { + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + for (; t_it != t_end; t_it++) + { + ESceneCustomOTool *ot = dynamic_cast(t_it->second); + if (ot && (t_it->first != OBJCLASS_DUMMY)) + cnt += ot->MultiRenameObjects(); + } + } + else + { + ESceneCustomOTool *ot = GetOTool(LTools->GetTarget()); + if (ot) + cnt += ot->MultiRenameObjects(); + } + return cnt; +} + +void EScene::OnFrame(float dT) +{ + if (!valid()) + return; + if (locked()) + return; + + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + for (; t_it != t_end; t_it++) + if (t_it->second && t_it->second->IsEnabled() && t_it->second->IsVisible()) + t_it->second->OnFrame(); + + if (m_RTFlags.test(flUpdateSnapList)) + UpdateSnapListReal(); +} + +void EScene::Reset() +{ + // unload scene + Unload(FALSE); + // reset tools + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + for (; t_it != t_end; t_it++) + if (t_it->second && t_it->first != OBJCLASS_DUMMY) + t_it->second->Reset(); + g_scene_physics.UpdateLevelCollision(); +} + +void EScene::Unload(BOOL bEditableOnly) +{ + m_LastAvailObject = 0; + Clear(bEditableOnly); + // if (m_SummaryInfo) m_SummaryInfo->HideProperties(); +} + +void EScene::Clear(BOOL bEditableToolsOnly) +{ + // clear snap + ClearSnapList(false); + // clear scene tools + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + for (; t_it != t_end; t_it++) + if (t_it->second && t_it->first != OBJCLASS_DUMMY) + { + if (!bEditableToolsOnly || (bEditableToolsOnly && t_it->second->IsEditable())) + { + t_it->second->Clear(); + } + } + + Tools->ClearDebugDraw(); + + m_RTFlags.set(flRT_Unsaved | flRT_Modified, FALSE); + + m_GUID = generate_guid(); + m_OwnerName = make_string("\\\\%s\\%s", Core.CompName, Core.UserName).c_str(); + m_CreateTime = time(NULL); + + m_SaveCache.free(); +} +//---------------------------------------------------- + +bool EScene::GetBox(Fbox &box, ObjClassID classfilter) +{ + return GetBox(box, ListObj(classfilter)); +} +//---------------------------------------------------- + +bool EScene::GetBox(Fbox &box, ObjectList &lst) +{ + box.invalidate(); + bool bRes = false; + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + Fbox bb; + + if ((*it)->GetBox(bb)) + { + box.modify(bb.vMin); + box.modify(bb.vMax); + bRes = true; + } + } + return bRes; +} +//---------------------------------------------------- + +void EScene::Modified() +{ + m_RTFlags.set(flRT_Modified | flRT_Unsaved, TRUE); + g_scene_physics.OnSceneModified(); + ExecCommand(COMMAND_UPDATE_CAPTION); +} + +bool EScene::IsUnsaved() +{ + return (m_RTFlags.is(flRT_Unsaved) && (ObjCount() || !Tools->GetEditFileName().empty())); +} +bool EScene::IsModified() +{ + return (m_RTFlags.is(flRT_Modified)); +} + +bool EScene::IfModified() +{ + if (locked()) + { + ELog.DlgMsg(mtError, "Scene sharing violation"); + return false; + } + if (m_RTFlags.is(flRT_Unsaved) && (ObjCount() || !Tools->GetEditFileName().empty())) + { + int mr = ELog.DlgMsg(mtConfirmation, "The scene has been modified. Do you want to save your changes?"); + switch (mr) + { + case mrYes: + if (!ExecCommand(COMMAND_SAVE)) + return false; + break; + case mrNo: + { + m_RTFlags.set(flRT_Unsaved, FALSE); + ExecCommand(COMMAND_UPDATE_CAPTION); + } + break; + case mrCancel: + return false; + } + } + return true; +} + +void EScene::OnObjectsUpdate() +{ + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + for (; t_it != t_end; t_it++) + if (t_it->second) + t_it->second->OnSceneUpdate(); +} + +void EScene::OnDeviceCreate() +{ + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + for (; t_it != t_end; t_it++) + if (t_it->second) + t_it->second->OnDeviceCreate(); +} + +void EScene::OnDeviceDestroy() +{ + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + for (; t_it != t_end; t_it++) + if (t_it->second) + t_it->second->OnDeviceDestroy(); +} +//------------------------------------------------------------------------------ + +void EScene::OnShowHint(AStringVec &dest) +{ + CCustomObject *obj = RayPickObject(flt_max, UI->m_CurrentRStart, UI->m_CurrentRDir, LTools->CurrentClassID(), 0, 0); + if (obj) + obj->OnShowHint(dest); +} +//------------------------------------------------------------------------------ + +bool EScene::ExportGame(SExportStreams *F) +{ + bool bres = true; + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + for (; t_it != t_end; t_it++) + if (t_it->second) + if (!t_it->second->ExportGame(F)) + bres = false; + return bres; +} +//------------------------------------------------------------------------------ + +bool EScene::Validate(bool bNeedOkMsg, bool bTestPortal, bool bTestHOM, bool bTestGlow, bool bTestShaderCompatible, bool bFullTest) +{ + bool bRes = true; + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + for (; t_it != t_end; t_it++) + { + if (t_it->second) + { + if (!t_it->second->Validate(bFullTest)) + { + ELog.Msg(mtError, "ERROR: Validate '%s' failed!", t_it->second->ClassDesc()); + bRes = false; + } + } + } + + if (bTestPortal) + { + if (Scene->ObjCount(OBJCLASS_SECTOR) || Scene->ObjCount(OBJCLASS_PORTAL)) + if (!PortalUtils.Validate(true)) + bRes = false; + } + if (bTestHOM) + { + bool bHasHOM = false; + ObjectList &lst = ListObj(OBJCLASS_SCENEOBJECT); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + CEditableObject *O = ((CSceneObject *)(*it))->GetReference(); + R_ASSERT(O); + if (O->m_objectFlags.is(CEditableObject::eoHOM)) + { + bHasHOM = true; + break; + } + } + if (!bHasHOM) + Msg("!Level doesn't contain HOM objects!"); + //. if (mrNo==ELog.DlgMsg(mtConfirmation,mbYes |mbNo,"Level doesn't contain HOM.\nContinue anyway?")) + //. return false; + } + if (ObjCount(OBJCLASS_SPAWNPOINT) == 0) + { + ELog.Msg(mtError, "*ERROR: Can't find any Spawn Object."); + bRes = false; + } + if (ObjCount(OBJCLASS_LIGHT) == 0) + { + ELog.Msg(mtError, "*ERROR: Can't find any Light Object."); + bRes = false; + } + if (ObjCount(OBJCLASS_SCENEOBJECT) == 0) + { + ELog.Msg(mtError, "*ERROR: Can't find any Scene Object."); + bRes = false; + } + if (bTestGlow) + { + if (ObjCount(OBJCLASS_GLOW) == 0) + { + ELog.Msg(mtError, "*ERROR: Can't find any Glow Object."); + bRes = false; + } + } + if (FindDuplicateName()) + { + ELog.Msg(mtError, "*ERROR: Found duplicate object name."); + bRes = false; + } + + if (bTestShaderCompatible) + { + bool res = true; + ObjectList &lst = ListObj(OBJCLASS_SCENEOBJECT); + DEFINE_SET(CEditableObject *, EOSet, EOSetIt); + EOSet objects; + int static_obj = 0; + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + CSceneObject *S = (CSceneObject *)(*it); + if (S->IsStatic() || S->IsMUStatic()) + { + static_obj++; + CEditableObject *O = ((CSceneObject *)(*it))->GetReference(); + R_ASSERT(O); + if (objects.find(O) == objects.end()) + { + if (!O->CheckShaderCompatible()) + res = false; + objects.insert(O); + } + } + } + if (!res) + { + ELog.Msg(mtError, "*ERROR: Scene has non compatible shaders. See log."); + bRes = false; + } + if (0 == static_obj) + { + ELog.Msg(mtError, "*ERROR: Can't find static geometry."); + bRes = false; + } + } + + if (!SndLib->Validate()) + bRes = false; + + { + ObjectList &lst = ListObj(OBJCLASS_PS); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + EParticlesObject *S = (EParticlesObject *)(*it); + if (!S->GetParticles()) + { + ELog.Msg(mtError, "*ERROR: Particle System hasn't reference."); + bRes = false; + } + } + } + + if (bRes) + { + if (bNeedOkMsg) + ELog.DlgMsg(mtInformation, "Validation OK!"); + } + else + { + ELog.DlgMsg(mtInformation, "Validation FAILED!"); + } + return bRes; +} + +xr_string EScene::LevelPath() +{ + string_path path; + if (m_LevelOp.m_FNLevelPath.size()) + { + FS.update_path(path, "$level$", m_LevelOp.m_FNLevelPath.c_str()); + strcat(path, "\\"); + } + return xr_string(path); +} + +void EScene::SelectLightsForObject(CCustomObject *obj) +{ + ESceneCustomOTool *t = Scene->GetOTool(OBJCLASS_LIGHT); + if (!t) + return; + + ESceneLightTool *lt = dynamic_cast(t); + VERIFY(lt); + lt->SelectLightsForObject(obj); +} + +void EScene::HighlightTexture(LPCSTR t_name, bool allow_ratio, u32 t_width, u32 t_height, bool leave_previous) +{ + if (!leave_previous) + Tools->ClearDebugDraw(); + + SceneToolsMapPairIt t_it = m_SceneTools.begin(); + SceneToolsMapPairIt t_end = m_SceneTools.end(); + + for (; t_it != t_end; ++t_it) + if (t_it->second) + t_it->second->HighlightTexture(t_name, allow_ratio, t_width, t_height, !leave_previous); + + UI->RedrawScene(); +} + +xr_token js_token[] = { + {"1 - Low", 1}, + {"4 - Medium", 4}, + {"9 - High", 9}, + {0, 0}}; + +void EScene::OnBuildControlClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + switch (V->btn_num) + { + case 0: + m_LevelOp.SetDraftQuality(); + break; + case 1: + m_LevelOp.SetHighQuality(); + break; + case 2: + m_LevelOp.SetCustomQuality(); + break; + } + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void EScene::OnRTFlagsChange(PropValue *sender) +{ + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void EScene::FillProp(LPCSTR pref, PropItemVec &items, ObjClassID cls_id) +{ + PHelper().CreateCaption(items, PrepareKey(pref, "Scene\\Name"), LTools->m_LastFileName.c_str()); + PHelper().CreateRText(items, PrepareKey(pref, "Scene\\Name prefix"), &m_LevelOp.m_LevelPrefix); + + PropValue *V; + PHelper().CreateRText(items, PrepareKey(pref, "Scene\\Build options\\Level path"), &m_LevelOp.m_FNLevelPath); + PHelper().CreateRText(items, PrepareKey(pref, "Scene\\Build options\\Custom data"), &m_LevelOp.m_BOPText); + PHelper().CreateRText(items, PrepareKey(pref, "Scene\\Map version"), &m_LevelOp.m_map_version); + + m_LevelOp.m_mapUsage.FillProp("Scene\\Usage", items); + + // common + ButtonValue *B; + B = PHelper().CreateButton(items, PrepareKey(pref, "Scene\\Build options\\Quality"), "Draft,High,Custom", 0); + B->OnBtnClickEvent.bind(this, &EScene::OnBuildControlClick); + + BOOL enabled = (m_LevelOp.m_BuildParams.m_quality == ebqCustom); + V = PHelper().CreateU8(items, PrepareKey(pref, "Scene\\Build options\\Lighting\\Hemisphere quality [0-3]"), &m_LevelOp.m_LightHemiQuality, 0, 3); + V->Owner()->Enable(enabled); + V = PHelper().CreateU8(items, PrepareKey(pref, "Scene\\Build options\\Lighting\\Sun shadow quality [0-3]"), &m_LevelOp.m_LightSunQuality, 0, 3); + V->Owner()->Enable(enabled); + + // Build Options + // Normals & optimization + V = PHelper().CreateFloat(items, PrepareKey(pref, "Scene\\Build options\\Optimizing\\Normal smooth angle"), &m_LevelOp.m_BuildParams.m_sm_angle, 0.f, 180.f); + V->Owner()->Enable(enabled); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Scene\\Build options\\Optimizing\\Weld distance (m)"), &m_LevelOp.m_BuildParams.m_weld_distance, 0.f, 1.f, 0.001f, 4); + V->Owner()->Enable(enabled); + + // Light maps + V = PHelper().CreateFloat(items, PrepareKey(pref, "Scene\\Build options\\Lighting\\Pixel per meter"), &m_LevelOp.m_BuildParams.m_lm_pixels_per_meter, 0.f, 20.f); + V->Owner()->Enable(enabled); + V = PHelper().CreateU32(items, PrepareKey(pref, "Scene\\Build options\\Lighting\\Error (LM collapsing)"), &m_LevelOp.m_BuildParams.m_lm_rms, 0, 255); + V->Owner()->Enable(enabled); + V = PHelper().CreateU32(items, PrepareKey(pref, "Scene\\Build options\\Lighting\\Error (LM zero)"), &m_LevelOp.m_BuildParams.m_lm_rms_zero, 0, 255); + V->Owner()->Enable(enabled); + V = PHelper().CreateToken32(items, PrepareKey(pref, "Scene\\Build options\\Lighting\\Jitter samples"), &m_LevelOp.m_BuildParams.m_lm_jitter_samples, js_token); + V->Owner()->Enable(enabled); + + // tools options + if (OBJCLASS_DUMMY == cls_id) + { + SceneToolsMapPairIt _I = FirstTool(); + SceneToolsMapPairIt _E = LastTool(); + for (; _I != _E; _I++) + { + ESceneToolBase *mt = _I->second; + if ((_I->first != OBJCLASS_DUMMY) && mt) + { + mt->FillProp(mt->ClassDesc(), items); + } + } + } + else + { + ESceneToolBase *mt = GetTool(cls_id); + if (mt) + { + mt->FillProp(mt->ClassDesc(), items); + } + } +} + +void EScene::RegisterSubstObjectName(const xr_string &_from, const xr_string &_to) +{ + xr_string _tmp; + bool b = GetSubstObjectName(_from, _tmp); + if (b) + Msg("! subst for '%s' already exist -'%s'", _from.c_str(), _tmp.c_str()); + + TSubstPairs_it It = m_subst_pairs.begin(); + TSubstPairs_it It_e = m_subst_pairs.end(); + for (; It != It_e; ++It) + { + if (It->first == _from) + { + It->second = _to; + break; + } + } + + if (It == It_e) + m_subst_pairs.push_back(TSubstPair(_from, _to)); +} + +bool EScene::GetSubstObjectName(const xr_string &_from, xr_string &_to) const +{ + TSubstPairs_cit It = m_subst_pairs.begin(); + TSubstPairs_cit It_e = m_subst_pairs.end(); + for (; It != It_e; ++It) + { + if (It->first == _from) + { + _to = It->second; + break; + } + } + + return (It != It_e); +} diff --git a/src/editors/LevelEditor/Scene/scene.h b/src/editors/LevelEditor/Scene/scene.h new file mode 100644 index 00000000000..56906fd16cd --- /dev/null +++ b/src/editors/LevelEditor/Scene/scene.h @@ -0,0 +1,362 @@ +#pragma once +#include "OldFixedMap.h" // todo: replace with FixedMap from xrCore +#include "xrCommon/xr_deque.h" + +#if 1 +template +class alloc +{ +public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef T *pointer; + typedef const T *const_pointer; + typedef T &reference; + typedef const T &const_reference; + typedef T value_type; + +public: + template + struct rebind + { + typedef alloc<_Other> other; + }; + +public: + pointer address(reference _Val) const { return (&_Val); } + const_pointer address(const_reference _Val) const { return (&_Val); } + alloc() {} + alloc(const alloc &) {} + template + alloc(const alloc<_Other> &) {} + template + alloc &operator=(const alloc<_Other> &) { return (*this); } + pointer allocate(size_type n, const void* p = 0) const + { + return (T*)Memory.mem_alloc(sizeof(T) * (u32)n); + } + void deallocate(pointer p, size_type n) const { Memory.mem_free((void*&)p); } + void deallocate(void* p, size_type n) const { Memory.mem_free(p); } + char *__charalloc(size_type n) { return (char *)allocate(n); } + void construct(pointer p, const T &_Val) { new (p) T(_Val); } + + void destroy(pointer p) { p->~T(); } + size_type max_size() const + { + size_type _Count = (size_type)(-1) / sizeof(T); + return (0 < _Count ? _Count : 1); + } +}; + +template +inline bool operator==(const alloc<_Ty> &, const alloc<_Other> &) { return (true); } +template +inline bool operator!=(const alloc<_Ty> &, const alloc<_Other> &) { return (false); } + +struct allocator_wrapper +{ + template + struct helper + { + typedef alloc result; + }; + + static void* alloc(const u32& n) { return Memory.mem_alloc((u32)n); } + template + static void dealloc(T *&p) { Memory.mem_free((void *&)p); } +}; + +#define render_alloc alloc +typedef allocator_wrapper render_allocator; +#endif + +struct FSChunkDef; +class PropValue; +struct SPBItem; + +#pragma pack(push, 1) +struct UndoItem +{ + char m_FileName[MAX_PATH]; +}; +#pragma pack(pop) + +class TProperties; + +struct st_LevelOptions +{ + shared_str m_FNLevelPath; + shared_str m_LevelPrefix; + shared_str m_BOPText; + shared_str m_map_version; + + u8 m_LightHemiQuality; + u8 m_LightSunQuality; + + b_params m_BuildParams; + + GameTypeChooser m_mapUsage; + st_LevelOptions(); + + void SetCustomQuality(); + void SetDraftQuality(); + void SetHighQuality(); + + void Save(IWriter &); + void SaveLTX(CInifile &); + + void Read(IReader &); + void ReadLTX(CInifile &); + void Reset(); +}; + +class EScene +{ + CMemoryWriter m_SaveCache; + +public: + typedef FixedMAP mapObject_D; + typedef mapObject_D::TNode mapObject_Node; + mapObject_D mapRenderObjects; + +public: + st_LevelOptions m_LevelOp; + +protected: + bool m_Valid; + int m_Locked; + // version control + xrGUID m_GUID; + shared_str m_OwnerName; + time_t m_CreateTime; + + // + int m_LastAvailObject; + + SceneToolsMap m_SceneTools; + + xr_deque m_UndoStack; + xr_deque m_RedoStack; + + TProperties *m_SummaryInfo; + + ObjectList m_ESO_SnapObjects; // временно здесь а вообще нужно перенести в ESceneTools +protected: + bool OnLoadAppendObject(CCustomObject *O); + bool OnLoadSelectionAppendObject(CCustomObject *O); + +protected: + void RegisterSceneTools(ESceneToolBase *mt); + void CreateSceneTools(); + void DestroySceneTools(); + + void FindObjectByNameCB(LPCSTR new_name, bool &res) { res = !!FindObjectByName(new_name, (CCustomObject *)0); } + + void OnBuildControlClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnRTFlagsChange(PropValue *sender); + +public: + enum + { + flRT_Unsaved = (1 << 0), + flRT_Modified = (1 << 1), + flUpdateSnapList = (1 << 2), + }; + Flags32 m_RTFlags; + +public: + typedef fastdelegate::FastDelegate1 TAppendObject; + + bool ReadObjectStream(IReader &F, CCustomObject *&O); + bool ReadObjectLTX(CInifile &ini, LPCSTR sect_name, CCustomObject *&O); + bool ReadObjectsStream(IReader &F, u32 chunk_id, TAppendObject on_append, SPBItem *pb); + bool ReadObjectsLTX(CInifile &ini, LPCSTR sect_name_parent, LPCSTR sect_name_prefix, TAppendObject on_append, SPBItem *pb); + + void SaveObjectStream(CCustomObject *O, IWriter &F); + void SaveObjectLTX(CCustomObject *O, LPCSTR sect_name, CInifile &ini); + void SaveObjectsStream(ObjectList &lst, u32 chunk_id, IWriter &F); + void SaveObjectsLTX(ObjectList &lst, LPCSTR sect_name_parent, LPCSTR sect_name_prefix, CInifile &ini); + + xr_string LevelPartPath(LPCSTR map_name); + xr_string LevelPartName(LPCSTR map_name, ObjClassID cls); + + BOOL LoadLevelPart(ESceneToolBase *M, LPCSTR map_name); + BOOL LoadLevelPartLTX(ESceneToolBase *M, LPCSTR map_name); + + BOOL LoadLevelPart(LPCSTR map_name, ObjClassID cls); + BOOL UnloadLevelPart(ESceneToolBase *M); + BOOL UnloadLevelPart(LPCSTR map_name, ObjClassID cls); + +public: + bool ExportGame(SExportStreams *F); + + bool Load(LPCSTR map_name, bool bUndo); + bool LoadLTX(LPCSTR map_name, bool bUndo); + + void Save(LPCSTR map_name, bool bUndo, bool bForceSaveAll); + void SaveLTX(LPCSTR map_name, bool bUndo, bool bForceSaveAll); + + bool LoadSelection(LPCSTR fname); + void SaveSelection(ObjClassID classfilter, LPCSTR fname); + + void SaveToolLTX(ObjClassID clsid, LPCSTR fn); + bool LoadToolLTX(ObjClassID clsid, LPCSTR fn); + + void Unload(BOOL bEditableToolsOnly); + void Clear(BOOL bEditableToolsOnly); + void Reset(); + void LoadCompilerError(LPCSTR fn); + void SaveCompilerError(LPCSTR fn); + void HighlightTexture(LPCSTR t_name, bool allow_ratio, u32 t_width, u32 t_height, bool leave_previous); + + int MultiRenameObjects(); + + IC bool valid() { return m_Valid; } + + IC bool locked() { return m_Locked != 0; } + IC void lock() { m_Locked++; } + IC void unlock() { m_Locked--; } + IC void waitlock() + { + while (locked()) + Sleep(0); + } + + IC ESceneToolBase *GetTool(ObjClassID cat) { return m_SceneTools[cat]; } + IC u32 ToolCount() { return m_SceneTools.size(); } + + IC ESceneCustomOTool *GetOTool(ObjClassID cat) { return dynamic_cast(GetTool(cat)); } + + IC SceneToolsMapPairIt FirstTool() { return m_SceneTools.begin(); } + IC SceneToolsMapPairIt LastTool() { return m_SceneTools.end(); } + + IC ObjectList &ListObj(ObjClassID cat) + { + VERIFY(GetOTool(cat)); + return GetOTool(cat)->GetObjects(); + } + IC ObjectIt FirstObj(ObjClassID cat) + { + VERIFY(GetOTool(cat)); + return ListObj(cat).begin(); + } + IC ObjectIt LastObj(ObjClassID cat) + { + VERIFY(GetOTool(cat)); + return ListObj(cat).end(); + } + IC int ObjCount(ObjClassID cat) { return ListObj(cat).size(); } + int ObjCount(); + + void RenderSky(const Fmatrix &camera); + void Render(const Fmatrix &camera); + void OnFrame(float dT); + + virtual void AppendObject(CCustomObject *object, bool bExecUnd = true); + virtual bool RemoveObject(CCustomObject *object, bool bExecUndo, bool bDeleting); + void BeforeObjectChange(CCustomObject *object); + bool ContainsObject(CCustomObject *object, ObjClassID classfilter); + + // Snap List Part + bool FindObjectInSnapList(CCustomObject *O); + bool AddToSnapList(CCustomObject *O, bool bUpdateScene = true); + bool DelFromSnapList(CCustomObject *O, bool bUpdateScene = true); + int AddSelToSnapList(); + int DelSelFromSnapList(); + int SetSnapList(); + void RenderSnapList(); + void ClearSnapList(bool bCurrentOnly); + void SelectSnapList(); + void UpdateSnapList(); + void UpdateSnapListReal(); + virtual ObjectList *GetSnapList(bool bIgnoreUse); + + virtual CCustomObject *RayPickObject(float dist, const Fvector &start, const Fvector &dir, ObjClassID classfilter, SRayPickInfo *pinf, ObjectList *from_list); + int BoxPickObjects(const Fbox &box, SBoxPickInfoVec &pinf, ObjectList *from_list); + int RayQuery(SPickQuery &RQ, const Fvector &start, const Fvector &dir, float dist, u32 flags, ObjectList *snap_list); + int BoxQuery(SPickQuery &RQ, const Fbox &bb, u32 flags, ObjectList *snap_list); + int RayQuery(SPickQuery &RQ, const Fvector &start, const Fvector &dir, float dist, u32 flags, CDB::MODEL *model); + int BoxQuery(SPickQuery &RQ, const Fbox &bb, u32 flags, CDB::MODEL *model); + + int RaySelect(int flag, ObjClassID classfilter = OBJCLASS_DUMMY); // flag=0,1,-1 (-1 invert) + int FrustumSelect(int flag, ObjClassID classfilter = OBJCLASS_DUMMY); + void SelectObjects(bool flag, ObjClassID classfilter = OBJCLASS_DUMMY); + void ShowObjects(bool flag, ObjClassID classfilter = OBJCLASS_DUMMY, bool bAllowSelectionFlag = false, bool bSelFlag = true); + void InvertSelection(ObjClassID classfilter); + int SelectionCount(bool testflag, ObjClassID classfilter); + void RemoveSelection(ObjClassID classfilter); + void CutSelection(ObjClassID classfilter); + void CopySelection(ObjClassID classfilter); + void PasteSelection(); + + void SelectLightsForObject(CCustomObject *obj); + + void ZoomExtents(ObjClassID cls, BOOL bSelectedOnly); + + int FrustumPick(const CFrustum &frustum, ObjClassID classfilter, ObjectList &ol); + int SpherePick(const Fvector ¢er, float radius, ObjClassID classfilter, ObjectList &ol); + + virtual void GenObjectName(ObjClassID cls_id, char *buffer, const char *prefix = NULL); + virtual CCustomObject *FindObjectByName(LPCSTR name, ObjClassID classfilter); + virtual CCustomObject *FindObjectByName(LPCSTR name, CCustomObject *pass_object); + bool FindDuplicateName(); + + void UndoClear(); + void UndoSave(); + bool Undo(); + bool Redo(); + + bool GetBox(Fbox &box, ObjClassID classfilter); + bool GetBox(Fbox &box, ObjectList &lst); + +public: + int GetQueryObjects(ObjectList &objset, ObjClassID classfilter, int iSel = 1, int iVis = 1, int iLock = 0); + +public: + void OnCreate(); + void OnDestroy(); + void Modified(); + bool IfModified(); + bool IsUnsaved(); + bool IsModified(); + + int GetUndoCount() { return m_UndoStack.size(); } + int GetRedoCount() { return m_RedoStack.size(); } + + bool Validate(bool bNeedOkMsg, bool bTestPortal, bool bTestHOM, bool bTestGlow, bool bTestShaderCompatible, bool bFullTest); + void OnObjectsUpdate(); + + EScene(); + virtual ~EScene(); + + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + + void OnShowHint(AStringVec &dest); + + void SynchronizeObjects(); + + void ClearSummaryInfo(); + void CollectSummaryInfo(); + void ExportObj(bool b_selected_only); + void ShowSummaryInfo(); + void ExportSummaryInfo(LPCSTR f_name); + + xr_string LevelPath(); + shared_str LevelPrefix() { return m_LevelOp.m_LevelPrefix; } + + void FillProp(LPCSTR pref, PropItemVec &items, ObjClassID cls_id); + +protected: + typedef std::pair TSubstPair; + typedef xr_vector TSubstPairs; + typedef TSubstPairs::iterator TSubstPairs_it; + typedef TSubstPairs::const_iterator TSubstPairs_cit; + TSubstPairs m_subst_pairs; + +public: + void RegisterSubstObjectName(const xr_string &from, const xr_string &to); + bool GetSubstObjectName(const xr_string &from, xr_string &to) const; +}; + +extern EScene *Scene; diff --git a/src/editors/LevelEditor/ServerEntities/LevelGameDef.cpp b/src/editors/LevelEditor/ServerEntities/LevelGameDef.cpp new file mode 100644 index 00000000000..60965617437 --- /dev/null +++ b/src/editors/LevelEditor/ServerEntities/LevelGameDef.cpp @@ -0,0 +1,16 @@ +#include "stdafx.h" +#include "Common/LevelGameDef.h" + +xr_token rpoint_type[] = + { + {"Actor Spawn", rptActorSpawn}, + {"Artefact Spawn", rptArtefactSpawn}, + {"Item Spawn", rptItemSpawn}, + {0, 0}}; + +xr_token rpoint_type_soc[] = + { + {"Actor Spawn", rptActorSpawn}, + {"Artefact Spawn", rptArtefactSpawn}, + {"TeamBase Particle", rptTeamBaseParticle}, + {0, 0}}; diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapControls.cpp b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapControls.cpp new file mode 100644 index 00000000000..b1efd58966b --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapControls.cpp @@ -0,0 +1,145 @@ +#include "stdafx.h" + +// Node Add +TUI_ControlAIMapNodeAdd::TUI_ControlAIMapNodeAdd(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} + +bool TUI_ControlAIMapNodeAdd::Start(TShiftState Shift) +{ + append_nodes = 0; + Fvector p; + ESceneAIMapTool *S = (ESceneAIMapTool *)parent_tool; + if (S->PickObjects(p, UI->m_CurrentRStart, UI->m_CurrentRDir, UI->ZFar())) + { + S->SelectObjects(false); + append_nodes = S->AddNode(p, ((UIAIMapTool *)S->pForm)->IsIgnoreConstraints(), ((UIAIMapTool *)S->pForm)->IsAutoLink(), S->m_BrushSize); + if (Shift & ssAlt) + { + if (append_nodes) + Scene->UndoSave(); + ResetActionToSelect(); + return false; + } + else + return true; + } + return false; +} +void TUI_ControlAIMapNodeAdd::Move(TShiftState _Shift) +{ + Fvector p; + ESceneAIMapTool *S = (ESceneAIMapTool *)parent_tool; + if (S->PickObjects(p, UI->m_CurrentRStart, UI->m_CurrentRDir, UI->ZFar())) + { + append_nodes += S->AddNode(p, ((UIAIMapTool *)S->pForm)->IsIgnoreConstraints(), ((UIAIMapTool *)S->pForm)->IsAutoLink(), S->m_BrushSize); + } +} +bool TUI_ControlAIMapNodeAdd::End(TShiftState _Shift) +{ + if (!(_Shift & ssAlt)) + ResetActionToSelect(); + if (append_nodes) + Scene->UndoSave(); + return true; +} + +//------------------------------------------------------------------------------------ +// Node Move +//------------------------------------------------------------------------------------ +TUI_ControlAIMapNodeMove::TUI_ControlAIMapNodeMove(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} +bool TUI_ControlAIMapNodeMove::Start(TShiftState Shift) +{ + if (parent_tool->SelectionCount(true) == 0) + return false; + + if (etAxisY == Tools->GetAxis()) + { + m_MovingXVector.set(0, 0, 0); + m_MovingYVector.set(0, 1, 0); + } + else + { + m_MovingXVector.set(0, 0, 0); + m_MovingYVector.set(0, 0, 0); + } + m_MovingReminder.set(0, 0, 0); + return true; +} + +void TUI_ControlAIMapNodeMove::Move(TShiftState _Shift) +{ + Fvector amount; + if (DefaultMovingProcess(_Shift, amount)) + { + AINodeVec &lst = ((ESceneAIMapTool *)parent_tool)->Nodes(); + for (AINodeIt _F = lst.begin(); _F != lst.end(); _F++) + if ((*_F)->flags.is(SAINode::flSelected)) + { + (*_F)->Pos.add(amount); + (*_F)->Plane.build((*_F)->Pos, (*_F)->Plane.n); + } + } +} + +bool TUI_ControlAIMapNodeMove::End(TShiftState _Shift) +{ + return MovingEnd(_Shift); +} + +//------------------------------------------------------------------------------------ +// Rotate Node +//------------------------------------------------------------------------------------ +TUI_ControlAIMapNodeRotate::TUI_ControlAIMapNodeRotate(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} +bool TUI_ControlAIMapNodeRotate::Start(TShiftState Shift) +{ + if (parent_tool->SelectionCount(true) == 0) + return false; + + m_RotateVector.set(0, 0, 0); + if (etAxisX == Tools->GetAxis()) + m_RotateVector.set(1, 0, 0); + else if (etAxisY == Tools->GetAxis()) + m_RotateVector.set(0, 0, 0); + else if (etAxisZ == Tools->GetAxis()) + m_RotateVector.set(0, 0, 1); + m_fRotateSnapAngle = 0; + return true; +} + +void TUI_ControlAIMapNodeRotate::Move(TShiftState _Shift) +{ + if (_Shift & ssLeft) + { + float amount = -UI->m_DeltaCpH.x * UI->m_MouseSR; + + if (Tools->GetSettings(etfASnap)) + CHECK_SNAP(m_fRotateSnapAngle, amount, Tools->m_RotateSnapAngle); + + Fmatrix R; + if (fis_zero(m_RotateVector.x)) + R.rotateZ(amount); + else + R.rotateX(amount); + + AINodeVec &lst = ((ESceneAIMapTool *)parent_tool)->Nodes(); + for (AINodeIt _F = lst.begin(); _F != lst.end(); _F++) + if ((*_F)->flags.is(SAINode::flSelected)) + { + Fvector new_n; + R.transform_dir(new_n, (*_F)->Plane.n); + if (Fvector().set(0, 1, 0).dotproduct(new_n) > 0.02f) + { + (*_F)->Plane.build((*_F)->Pos, new_n); + } + } + } +} +bool TUI_ControlAIMapNodeRotate::End(TShiftState _Shift) +{ + return RotateEnd(_Shift); +} diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapControls.h b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapControls.h new file mode 100644 index 00000000000..27ccf6324ed --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapControls.h @@ -0,0 +1,35 @@ +#pragma once + +// refs +class ESceneAIMapTool; + +#define estAIMapNode 0 + +class TUI_ControlAIMapNodeAdd : public TUI_CustomControl +{ + int append_nodes; + +public: + TUI_ControlAIMapNodeAdd(int st, int act, ESceneToolBase *parent); + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); +}; + +class TUI_ControlAIMapNodeMove : public TUI_CustomControl +{ +public: + TUI_ControlAIMapNodeMove(int st, int act, ESceneToolBase *parent); + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); +}; +//--------------------------------------------------------------------------- +class TUI_ControlAIMapNodeRotate : public TUI_CustomControl +{ +public: + TUI_ControlAIMapNodeRotate(int st, int act, ESceneToolBase *parent); + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); +}; diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools.cpp b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools.cpp new file mode 100644 index 00000000000..02a42813008 --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools.cpp @@ -0,0 +1,635 @@ +#include "stdafx.h" + +// chunks +#define AIMAP_VERSION 0x0002 + +#define AIMAP_CHUNK_VERSION 0x0001 +#define AIMAP_CHUNK_FLAGS 0x0002 +#define AIMAP_CHUNK_BOX 0x0003 +#define AIMAP_CHUNK_PARAMS 0x0004 +#define AIMAP_CHUNK_NODES 0x0006 +#define AIMAP_CHUNK_SNAP_OBJECTS 0x0007 +#define AIMAP_CHUNK_INTERNAL_DATA 0x0008 +#define AIMAP_CHUNK_INTERNAL_DATA2 0x0009 + +/* ?? +poolSS g_ainode_pool; + +void *SAINode::operator new(std::size_t size) +{ + return g_ainode_pool.create(); +} + +void *SAINode::operator new(std::size_t size, SAINode *src) +{ + return src; +} + +void SAINode::operator delete(void *ptr) +{ + auto node = (SAINode *)ptr; + g_ainode_pool.destroy(node); +} +*/ + +void SAINode::PointLF(Fvector &D, float patch_size) +{ + Fvector d; + d.set(0, -1, 0); + Fvector v = Pos; + float s = patch_size / 2; + v.x -= s; + v.z += s; + Plane.intersectRayPoint(v, d, D); +} + +void SAINode::PointFR(Fvector &D, float patch_size) +{ + Fvector d; + d.set(0, -1, 0); + Fvector v = Pos; + float s = patch_size / 2; + v.x += s; + v.z += s; + Plane.intersectRayPoint(v, d, D); +} + +void SAINode::PointRB(Fvector &D, float patch_size) +{ + Fvector d; + d.set(0, -1, 0); + Fvector v = Pos; + float s = patch_size / 2; + v.x += s; + v.z -= s; + Plane.intersectRayPoint(v, d, D); +} + +void SAINode::PointBL(Fvector &D, float patch_size) +{ + Fvector d; + d.set(0, -1, 0); + Fvector v = Pos; + float s = patch_size / 2; + v.x -= s; + v.z -= s; + Plane.intersectRayPoint(v, d, D); +} + +void SAINode::LoadLTX(CInifile &ini, LPCSTR sect_name, ESceneAIMapTool *tools) +{ + R_ASSERT(0); +} + +void SAINode::SaveLTX(CInifile &ini, LPCSTR sect_name, ESceneAIMapTool *tools) +{ + R_ASSERT2(0, "dont use it !!!"); + u32 id; + u16 pl; + NodePosition np; + + id = n1 ? (u32)n1->idx : InvalidNode; + ini.w_u32(sect_name, "n1", id); + + id = n2 ? (u32)n2->idx : InvalidNode; + ini.w_u32(sect_name, "n2", id); + + id = n3 ? (u32)n3->idx : InvalidNode; + ini.w_u32(sect_name, "n3", id); + + id = n4 ? (u32)n4->idx : InvalidNode; + ini.w_u32(sect_name, "n4", id); + + pl = pvCompress(Plane.n); + ini.w_u16(sect_name, "plane", pl); + + tools->PackPosition(np, Pos, tools->m_AIBBox, tools->m_Params); + string256 buff; + + s16 x; + u16 y; + s16 z; + + sprintf(buff, "%i,%u,%i", np.x, np.y, np.z); + ini.w_string(sect_name, "np", buff); + ini.w_u8(sect_name, "flag", flags.get()); +} + +void SAINode::LoadStream(IReader &F, ESceneAIMapTool *tools) +{ + u32 id; + u16 pl; + NodePosition np; + +#pragma TODO("TSMP: seems wrong to cast 32 bit value to 64 bit pointer (on x64)") + + F.r(&id, 3); + n1 = (SAINode*)(size_t)tools->UnpackLink(id); + F.r(&id, 3); + n2 = (SAINode*)(size_t)tools->UnpackLink(id); + F.r(&id, 3); + n3 = (SAINode*)(size_t)tools->UnpackLink(id); + F.r(&id, 3); + n4 = (SAINode*)(size_t)tools->UnpackLink(id); + pl = F.r_u16(); + pvDecompress(Plane.n, pl); + F.r(&np, sizeof(np)); + tools->UnpackPosition(Pos, np, tools->m_AIBBox, tools->m_Params); + Plane.build(Pos, Plane.n); + flags.assign(F.r_u8()); +} + +void SAINode::SaveStream(IWriter &F, ESceneAIMapTool *tools) +{ + u32 id; + u16 pl; + NodePosition np; + + id = n1 ? (u32)n1->idx : InvalidNode; + F.w(&id, 3); + id = n2 ? (u32)n2->idx : InvalidNode; + F.w(&id, 3); + id = n3 ? (u32)n3->idx : InvalidNode; + F.w(&id, 3); + id = n4 ? (u32)n4->idx : InvalidNode; + F.w(&id, 3); + pl = pvCompress(Plane.n); + F.w_u16(pl); + tools->PackPosition(np, Pos, tools->m_AIBBox, tools->m_Params); + F.w(&np, sizeof(np)); + F.w_u8(flags.get()); +} + +ESceneAIMapTool::ESceneAIMapTool() : ESceneToolBase(OBJCLASS_AIMAP) +{ + m_Shader = 0; + m_Flags.zero(); + + m_AIBBox.invalidate(); + // m_Header.size_y = m_Header.aabb.max.y-m_Header.aabb.min.y+EPS_L; + hash_Initialize(); + m_VisRadius = 30.f; + m_SmoothHeight = 0.5f; + m_BrushSize = 1; + m_CFModel = 0; +} +//---------------------------------------------------- + +ESceneAIMapTool::~ESceneAIMapTool() +{ +} +//---------------------------------------------------- + +void ESceneAIMapTool::Clear(bool bOnlyNodes) +{ + inherited::Clear(); + hash_Clear(); + for (SAINode *node : m_Nodes) + xr_delete(node); + m_Nodes.clear(); + if (!bOnlyNodes) + { + // m_SnapObjects.clear (); + m_AIBBox.invalidate(); + ExecCommand(COMMAND_REFRESH_SNAP_OBJECTS); + //g_ainode_pool.clear(); + RealUpdateSnapList(); + } +} +//---------------------------------------------------- + +void ESceneAIMapTool::CalculateNodesBBox(Fbox &bb) +{ + bb.invalidate(); + for (AINodeIt b_it = m_Nodes.begin(); b_it != m_Nodes.end(); ++b_it) + { + VERIFY(_valid((*b_it)->Pos)); + bb.modify((*b_it)->Pos); + } +} +//---------------------------------------------------- +extern BOOL ai_map_shown; +void ESceneAIMapTool::OnActivate() +{ + inherited::OnActivate(); + ai_map_shown = TRUE; +} + +void ESceneAIMapTool::OnFrame() +{ + if (m_Flags.is(flUpdateHL)) + { + m_Flags.set(flUpdateHL, FALSE); + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + (*it)->flags.set(SAINode::flHLSelected, FALSE); + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + { + SAINode &N = **it; + if (N.flags.is(SAINode::flSelected)) + for (int k = 0; k < 4; k++) + if (N.n[k]) + N.n[k]->flags.set(SAINode::flHLSelected, TRUE); + } + } + if (m_Flags.is(flUpdateSnapList)) + RealUpdateSnapList(); +} +//---------------------------------------------------- + +void ESceneAIMapTool::EnumerateNodes() +{ + u32 idx = 0; + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++, idx++) + (*it)->idx = idx; +} + +void ESceneAIMapTool::DenumerateNodes() +{ +#pragma TODO("TSMP: seems wrong to cast 64 bit pointer to 32 bit value (on x64)") + + u32 cnt = m_Nodes.size(); + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + { + if (!((((u32)(size_t)(*it)->n1 < cnt) || ((u32)(size_t)(*it)->n1 == InvalidNode)) && + (((u32)(size_t)(*it)->n2 < cnt) || ((u32)(size_t)(*it)->n2 == InvalidNode)) && + (((u32)(size_t)(*it)->n3 < cnt) || ((u32)(size_t)(*it)->n3 == InvalidNode)) && + (((u32)(size_t)(*it)->n4 < cnt) || ((u32)(size_t)(*it)->n4 == InvalidNode)))) + { + ELog.Msg(mtError, "Node: has wrong link [%3.2f, %3.2f, %3.2f], {%d,%d,%d,%d}", VPUSH((*it)->Pos), (*it)->n1, (*it)->n2, (*it)->n3, (*it)->n4); + (*it)->n1 = 0; + (*it)->n2 = 0; + (*it)->n3 = 0; + (*it)->n4 = 0; + continue; + } + // ,"AINode: Wrong link found."); + (*it)->n1 = ((u32)(size_t)(*it)->n1 == InvalidNode) ? 0 : m_Nodes[(u32)(size_t)(*it)->n1]; + (*it)->n2 = ((u32)(size_t)(*it)->n2 == InvalidNode) ? 0 : m_Nodes[(u32)(size_t)(*it)->n2]; + (*it)->n3 = ((u32)(size_t)(*it)->n3 == InvalidNode) ? 0 : m_Nodes[(u32)(size_t)(*it)->n3]; + (*it)->n4 = ((u32)(size_t)(*it)->n4 == InvalidNode) ? 0 : m_Nodes[(u32)(size_t)(*it)->n4]; + /* + if (((u32)(*it)->n1n1==InvalidNode)) (*it)->n1 = ((u32)(*it)->n1==InvalidNode)?0:m_Nodes[(u32)(*it)->n1]; + else (*it)->n1=0; + if (((u32)(*it)->n2n2==InvalidNode)) (*it)->n2 = ((u32)(*it)->n2==InvalidNode)?0:m_Nodes[(u32)(*it)->n2]; + else (*it)->n2=0; + if (((u32)(*it)->n3n3==InvalidNode)) (*it)->n3 = ((u32)(*it)->n3==InvalidNode)?0:m_Nodes[(u32)(*it)->n3]; + else (*it)->n3=0; + if (((u32)(*it)->n4n4==InvalidNode)) (*it)->n4 = ((u32)(*it)->n4==InvalidNode)?0:m_Nodes[(u32)(*it)->n4]; + else (*it)->n4=0; + */ + } +} +bool ESceneAIMapTool::LoadLTX(CInifile &ini) +{ + R_ASSERT(0); + return true; +} + +void ESceneAIMapTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + + ini.w_u32("main", "version", AIMAP_VERSION); + ini.w_u32("main", "flags", m_Flags.get()); + + ini.w_fvector3("main", "bbox_min", m_AIBBox.vMin); + ini.w_fvector3("main", "bbox_max", m_AIBBox.vMax); + + ini.w_float("params", "patch_size", m_Params.fPatchSize); + ini.w_float("params", "test_height", m_Params.fTestHeight); + ini.w_float("params", "can_up", m_Params.fCanUP); + ini.w_float("params", "can_down", m_Params.fCanDOWN); + + EnumerateNodes(); + ini.w_u32("main", "nodes_count", m_Nodes.size()); + + u32 i = 0; + string128 buff; + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); ++it, ++i) + { + sprintf(buff, "n_%d", i); + (*it)->SaveLTX(ini, buff, this); + } + + ini.w_float("main", "vis_radius", m_VisRadius); + ini.w_u32("main", "brush_size", m_BrushSize); + + ini.w_float("main", "smooth_height", m_SmoothHeight); + + for (ObjectIt o_it = m_SnapObjects.begin(); o_it != m_SnapObjects.end(); ++o_it) + ini.w_string("snap_objects", (*o_it)->GetName(), NULL); +} + +bool ESceneAIMapTool::LoadStream(IReader &F) +{ + inherited::LoadStream(F); + + u16 version = 0; + + R_ASSERT(F.r_chunk(AIMAP_CHUNK_VERSION, &version)); + if (version != AIMAP_VERSION) + { + ELog.DlgMsg(mtError, "AIMap: Unsupported version."); + return false; + } + + R_ASSERT(F.find_chunk(AIMAP_CHUNK_FLAGS)); + F.r(&m_Flags, sizeof(m_Flags)); + + R_ASSERT(F.find_chunk(AIMAP_CHUNK_BOX)); + F.r(&m_AIBBox, sizeof(m_AIBBox)); + + R_ASSERT(F.find_chunk(AIMAP_CHUNK_PARAMS)); + F.r(&m_Params, sizeof(m_Params)); + + R_ASSERT(F.find_chunk(AIMAP_CHUNK_NODES)); + m_Nodes.resize(F.r_u32()); + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + { + *it = xr_new(); + (*it)->LoadStream(F, this); + } + DenumerateNodes(); + + if (F.find_chunk(AIMAP_CHUNK_INTERNAL_DATA)) + { + m_VisRadius = F.r_float(); + m_BrushSize = F.r_u32(); + } + if (F.find_chunk(AIMAP_CHUNK_INTERNAL_DATA2)) + { + m_SmoothHeight = F.r_float(); + } + + // snap objects + if (F.find_chunk(AIMAP_CHUNK_SNAP_OBJECTS)) + { + shared_str buf; + int cnt = F.r_u32(); + if (cnt) + { + for (int i = 0; i < cnt; i++) + { + F.r_stringZ(buf); + CCustomObject *O = Scene->FindObjectByName(buf.c_str(), OBJCLASS_SCENEOBJECT); + if (!O) + ELog.Msg(mtError, "AIMap: Can't find snap object '%s'.", buf.c_str()); + else + m_SnapObjects.push_back(O); + } + } + } + + hash_FillFromNodes(); + + return true; +} +//---------------------------------------------------- + +bool ESceneAIMapTool::LoadSelection(IReader &F) +{ + Clear(); + return LoadStream(F); +} + +void ESceneAIMapTool::OnSynchronize() +{ + RealUpdateSnapList(); +} +//---------------------------------------------------- + +void ESceneAIMapTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.open_chunk(AIMAP_CHUNK_VERSION); + F.w_u16(AIMAP_VERSION); + F.close_chunk(); + + F.open_chunk(AIMAP_CHUNK_FLAGS); + F.w(&m_Flags, sizeof(m_Flags)); + F.close_chunk(); + + F.open_chunk(AIMAP_CHUNK_BOX); + F.w(&m_AIBBox, sizeof(m_AIBBox)); + F.close_chunk(); + + F.open_chunk(AIMAP_CHUNK_PARAMS); + F.w(&m_Params, sizeof(m_Params)); + F.close_chunk(); + + EnumerateNodes(); + F.open_chunk(AIMAP_CHUNK_NODES); + F.w_u32(m_Nodes.size()); + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + (*it)->SaveStream(F, this); + F.close_chunk(); + + F.open_chunk(AIMAP_CHUNK_INTERNAL_DATA); + F.w_float(m_VisRadius); + F.w_u32(m_BrushSize); + F.close_chunk(); + + F.open_chunk(AIMAP_CHUNK_INTERNAL_DATA2); + F.w_float(m_SmoothHeight); + F.close_chunk(); + + F.open_chunk(AIMAP_CHUNK_SNAP_OBJECTS); + F.w_u32(m_SnapObjects.size()); + for (ObjectIt o_it = m_SnapObjects.begin(); o_it != m_SnapObjects.end(); o_it++) + F.w_stringZ((*o_it)->GetName()); + F.close_chunk(); +} +//---------------------------------------------------- + +void ESceneAIMapTool::SaveSelection(IWriter &F) +{ + SaveStream(F); +} + +bool ESceneAIMapTool::Valid() +{ + return !m_Nodes.empty(); +} + +bool ESceneAIMapTool::IsNeedSave() +{ + return (!m_Nodes.empty() || !m_SnapObjects.empty()); +} + +void ESceneAIMapTool::OnObjectRemove(CCustomObject *O, bool bDeleting) +{ + if (OBJCLASS_SCENEOBJECT == O->FClassID) + { + if (find(m_SnapObjects.begin(), m_SnapObjects.end(), O) != m_SnapObjects.end()) + { + m_SnapObjects.remove(O); + RealUpdateSnapList(); + } + } +} + +int ESceneAIMapTool::AddNode(const Fvector &pos, bool bIgnoreConstraints, bool bAutoLink, int sz) +{ + Fvector Pos = pos; + if (1 == sz) + { + SAINode *N = BuildNode(Pos, Pos, bIgnoreConstraints, true); + if (N) + { + N->flags.set(SAINode::flSelected, TRUE); + if (bAutoLink) + UpdateLinks(N, bIgnoreConstraints); + return 1; + } + else + { + ELog.Msg(mtError, "Can't create node."); + return 0; + } + } + else + { + return BuildNodes(Pos, sz, bIgnoreConstraints); + } +} + +void ESceneAIMapTool::SelectNodesByLink(int link) +{ + SelectObjects(false); + // remove link to sel nodes + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + if ((*it)->Links() == link) + // if (!(*it)->flags.is(SAINode::flHide)) + (*it)->flags.set(SAINode::flSelected, TRUE); + UI->RedrawScene(); +} + +void ESceneAIMapTool::SelectObjects(bool flag) +{ + switch (LTools->GetSubTarget()) + { + case estAIMapNode: + { + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + // if (!(*it)->flags.is(SAINode::flHide)) + (*it)->flags.set(SAINode::flSelected, flag); + } + break; + } + UpdateHLSelected(); + UI->RedrawScene(); +} +struct delete_sel_node_pred +{ + bool operator()(SAINode *&x) + { + // breaking links + for (int k = 0; k < 4; k++) + if (x->n[k] && x->n[k]->flags.is(SAINode::flSelected)) + x->n[k] = 0; + // free memory + bool res = x->flags.is(SAINode::flSelected); + if (res) + xr_delete(x); + return res; + } +}; +void ESceneAIMapTool::RemoveSelection() +{ + switch (LTools->GetSubTarget()) + { + case estAIMapNode: + { + if (m_Nodes.size() == (u32)SelectionCount(true)) + { + Clear(true); + } + else + { + SPBItem *pb = UI->ProgressStart(3, "Removing nodes..."); + // remove link to sel nodes + pb->Inc("erasing nodes"); + // remove sel nodes + AINodeIt result = std::remove_if(m_Nodes.begin(), m_Nodes.end(), delete_sel_node_pred()); + m_Nodes.erase(result, m_Nodes.end()); + pb->Inc("updating hash"); + hash_Clear(); + hash_FillFromNodes(); + pb->Inc("end"); + UI->ProgressEnd(pb); + } + } + break; + } + UpdateHLSelected(); + UI->RedrawScene(); +} + +void ESceneAIMapTool::InvertSelection() +{ + switch (LTools->GetSubTarget()) + { + case estAIMapNode: + { + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + // if (!(*it)->flags.is(SAINode::flHide)) + (*it)->flags.invert(SAINode::flSelected); + } + break; + } + UpdateHLSelected(); + UI->RedrawScene(); +} + +int ESceneAIMapTool::SelectionCount(bool testflag) +{ + int count = 0; + switch (LTools->GetSubTarget()) + { + case estAIMapNode: + { + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + if ((*it)->flags.is(SAINode::flSelected) == testflag) + count++; + } + break; + } + return count; +} + +void ESceneAIMapTool::FillProp(LPCSTR pref, PropItemVec &items) +{ + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Draw Nodes"), &m_Flags, flHideNodes, 0, 0, FlagValueCustom::flInvertedDraw); + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Slow Calculate Mode"), &m_Flags, flSlowCalculate); + PHelper().CreateFloat(items, PrepareKey(pref, "Common\\Visible Radius"), &m_VisRadius, 10.f, 250.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Common\\Smooth Height"), &m_SmoothHeight, 0.1f, 100.f); + + PHelper().CreateU32(items, PrepareKey(pref, "Params\\Brush Size"), &m_BrushSize, 1, 100); + PHelper().CreateFloat(items, PrepareKey(pref, "Params\\Can Up"), &m_Params.fCanUP, 0.f, 10.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Params\\Can Down"), &m_Params.fCanDOWN, 0.f, 10.f); +} + +void ESceneAIMapTool::GetBBox(Fbox &bb, bool bSelOnly) +{ + switch (LTools->GetSubTarget()) + { + case estAIMapNode: + { + if (bSelOnly) + { + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + if ((*it)->flags.is(SAINode::flSelected)) + { + bb.modify(Fvector().add((*it)->Pos, -m_Params.fPatchSize * 0.5f)); + bb.modify(Fvector().add((*it)->Pos, m_Params.fPatchSize * 0.5f)); + } + } + else + { + bb.merge(m_AIBBox); + } + } + break; + } +} diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools.h b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools.h new file mode 100644 index 00000000000..8a85a5324ce --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools.h @@ -0,0 +1,234 @@ +#pragma once + +// refs +class ESceneAIMapTool; +struct SAINode; + +const DWORD InvalidNode = (1 << 24) - 1; + +#pragma pack(push, 1) +struct SAINode // definition of "patch" or "node" +{ + union + { + struct + { + SAINode *n1; // Left + SAINode *n2; // Forward + SAINode *n3; // Right + SAINode *n4; // Backward + }; + SAINode *n[4]; + }; + Fplane Plane; // plane of patch + Fvector Pos; // position of patch center + + enum + { + flSelected = (1 << 0), + flHLSelected = (1 << 1), + // flHide = (1<<2), // obsolette + + flN1 = (1 << 4), + flN2 = (1 << 5), + flN3 = (1 << 6), + flN4 = (1 << 7), + }; + Flags8 flags; + u32 idx; + + SAINode() + { + n1 = n2 = n3 = n4 = 0; + idx = 0; + flags.zero(); + } + SAINode *nLeft() { return n1; } + SAINode *nForward() { return n2; } + SAINode *nRight() { return n3; } + SAINode *nBack() { return n4; } + + int Links() const + { + int cnt = 0; + for (int k = 0; k < 4; k++) + if (n[k]) + cnt++; + return cnt; + } + void PointLF(Fvector &D, float patch_size); + void PointFR(Fvector &D, float patch_size); + void PointRB(Fvector &D, float patch_size); + void PointBL(Fvector &D, float patch_size); + + void LoadStream(IReader &, ESceneAIMapTool *); + void SaveStream(IWriter &, ESceneAIMapTool *); + void LoadLTX(CInifile &ini, LPCSTR sect_name, ESceneAIMapTool *); + void SaveLTX(CInifile &ini, LPCSTR sect_name, ESceneAIMapTool *); + + /* + void *operator new(std::size_t size); + void *operator new(std::size_t size, SAINode *); + void operator delete(void *); + */ +}; +#pragma pack(pop) + +DEFINE_VECTOR(SAINode *, AINodeVec, AINodeIt); + +const int HDIM_X = 128; +const int HDIM_Z = 128; + +class ESceneAIMapTool : public ESceneToolBase +{ + friend struct SAINode; + typedef ESceneToolBase inherited; + ObjectList m_SnapObjects; + // hash + AINodeVec m_HASH[HDIM_X + 1][HDIM_Z + 1]; + AINodeVec m_Nodes; + + SAIParams m_Params; + Fbox m_AIBBox; + + ref_geom m_RGeom; + ref_shader m_Shader; + CDB::MODEL *m_CFModel; + +protected: + void hash_FillFromNodes(); + void hash_Initialize(); + void hash_Clear(); + void HashRect(const Fvector &v, float radius, Irect &result); + AINodeVec *HashMap(int ix, int iz); + AINodeVec *HashMap(Fvector &V); + SAINode *FindNode(Fvector &vAt, float eps = 0.05f); + SAINode *FindNeighbor(SAINode *N, int side, bool bIgnoreConstraints); + void MotionSimulate(Fvector &result, Fvector &start, Fvector &end, float _radius, float _height); + + SAINode *BuildNode(Fvector &vFrom, Fvector &vAt, bool bIgnoreConstraints, bool bSuperIgnoreConstraints = false); + int BuildNodes(const Fvector &pos, int sz, bool bIgnoreConstraints); + void BuildNodes(bool bFromSelectedOnly); + BOOL CreateNode(Fvector &vAt, SAINode &N, bool bIgnoreConstraints); + BOOL CanTravel(Fvector _from, Fvector _at); + + SAINode *GetNode(Fvector vAt, bool bIgnoreConstraints); + void UpdateLinks(SAINode *N, bool bIgnoreConstraints); + + void UnpackPosition(Fvector &Pdest, const NodePosition &Psrc, Fbox &bb, SAIParams ¶ms); + u32 UnpackLink(u32 &L); + void PackPosition(NodePosition &Dest, Fvector &Src, Fbox &bb, SAIParams ¶ms); + + void EnumerateNodes(); + void DenumerateNodes(); + + bool RealUpdateSnapList(); + int RemoveOutOfBoundsNodes(); + + void CalculateNodesBBox(Fbox &bb); + + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + enum EMode + { + mdAppend, + mdRemove, + mdInvert, + }; + enum + { + flUpdateSnapList = (1 << 0), + flHideNodes = (1 << 1), + flSlowCalculate = (1 << 2), + flUpdateHL = (1 << 15), + }; + Flags32 m_Flags; + + float m_VisRadius; + float m_SmoothHeight; + u32 m_BrushSize; + xr_vector m_ignored_materials; + + bool PickObjects(Fvector &dest, const Fvector &start, const Fvector &dir, float dist); + +public: + ESceneAIMapTool(); + virtual ~ESceneAIMapTool(); + + virtual bool AllowEnabling() { return true; } + virtual BOOL AllowMouseStart() { return true; } + + virtual void OnObjectRemove(CCustomObject *O, bool bDeleting); + virtual void UpdateSnapList() { m_Flags.set(flUpdateSnapList, TRUE); } + virtual ObjectList *GetSnapList() { return &m_SnapObjects; } + + // selection manipulate + SAINode *PickNode(const Fvector &start, const Fvector &dir, float &dist); + virtual int RaySelect(int flag, float &distance, const Fvector &start, const Fvector &direction, BOOL bDistanceOnly); + virtual int FrustumSelect(int flag, const CFrustum &frustum); + virtual void SelectObjects(bool flag); + virtual void InvertSelection(); + virtual void RemoveSelection(); + virtual int SelectionCount(bool testflag); + virtual void ShowObjects(bool flag, bool bAllowSelectionFlag = false, bool bSelFlag = true) {} + + virtual void Clear(bool bOnlyNodes = false); + + // definition + IC LPCSTR ClassName() { return "ai_map"; } + IC LPCSTR ClassDesc() { return "AI Map"; } + IC int RenderPriority() { return 10; } + + // validation + virtual bool Valid(); + virtual bool Validate(bool) { return true; } + virtual bool IsNeedSave(); + + // events + virtual void OnFrame(); + virtual void OnRender(int priority, bool strictB2F); + virtual void OnActivate(); + + // IO + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool can_use_inifile() { return false; } + + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + virtual bool Export(LPCSTR path); + + // device dependent funcs + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + + virtual void OnSynchronize(); + + // utils + bool GenerateMap(bool bFromSelectedOnly); + virtual bool GetSummaryInfo(SSceneSummary *inf) { return false; } + virtual void GetBBox(Fbox &bb, bool bSelOnly); + + // properties + virtual void FillProp(LPCSTR pref, PropItemVec &items); + + // other + int AddNode(const Fvector &pos, bool bIgnoreConstraints, bool bAutoLink, int cnt); + + AINodeVec &Nodes() { return m_Nodes; } + + void MakeLinks(u8 side_flag, EMode mode, bool bIgnoreConstraints); + void RemoveLinks(); + void InvertLinks(); + + void UpdateHLSelected() { m_Flags.set(flUpdateHL, TRUE); } + + void SmoothNodes(); + void ResetNodes(); + void SelectNodesByLink(int link); +}; diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Controls.cpp b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Controls.cpp new file mode 100644 index 00000000000..ce4794876d8 --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Controls.cpp @@ -0,0 +1,19 @@ +#include "stdafx.h" + +void ESceneAIMapTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); + // node tools + // AddControl(xr_new (estAIMapNode, etaSelect, this)); + AddControl(xr_new(estAIMapNode, etaAdd, this)); + AddControl(xr_new(estAIMapNode, etaMove, this)); + AddControl(xr_new(estAIMapNode, etaRotate, this)); + // frame + pForm = xr_new(); + ((UIAIMapTool *)pForm)->tool = this; +} + +void ESceneAIMapTool::RemoveControls() +{ + inherited::RemoveControls(); +} diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Export.cpp b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Export.cpp new file mode 100644 index 00000000000..fa1b0f53a7b --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Export.cpp @@ -0,0 +1,115 @@ +#include "stdafx.h" + +const u32 MAX_NODE_BIT_COUNT = 23; // original, todo: replace + +void ESceneAIMapTool::UnpackPosition(Fvector &Pdest, const NodePosition &Psrc, Fbox &bb, SAIParams ¶ms) +{ + Pdest.x = float(Psrc.x) * params.fPatchSize; + Pdest.y = (float(Psrc.y) / 65535) * (bb.vMax.y - bb.vMin.y) + bb.vMin.y; + Pdest.z = float(Psrc.z) * params.fPatchSize; +} + +u32 ESceneAIMapTool::UnpackLink(u32 &L) +{ + return L & 0x00ffffff; +} + +void ESceneAIMapTool::PackPosition(NodePosition &Dest, Fvector &Src, Fbox &bb, SAIParams ¶ms) +{ + float sp = 1 / params.fPatchSize; + int px, py, pz; + px = iFloor(Src.x * sp + EPS_L); + py = iFloor(65535.f * (Src.y - bb.vMin.y) / (bb.vMax.y - bb.vMin.y) + EPS_L); + pz = iFloor(Src.z * sp + EPS_L); + + clamp(px, -32767, 32767); + Dest.x = s16(px); + clamp(py, 0, 65535); + Dest.y = u16(py); + clamp(pz, -32767, 32767); + Dest.z = s16(pz); +} + +bool ESceneAIMapTool::Export(LPCSTR path) +{ + //.? if (!RealUpdateSnapList()) return false; + if (!Valid()) + return false; + + // calculate bbox + Fbox bb; + CalculateNodesBBox(bb); + + xr_string fn = xr_string(path) + "build.aimap"; + + // export + IWriter *F = FS.w_open(fn.c_str()); + + if (F) + { + F->open_chunk(E_AIMAP_CHUNK_VERSION); + F->w_u16(E_AIMAP_VERSION); + F->close_chunk(); + + F->open_chunk(E_AIMAP_CHUNK_BOX); + F->w(&bb, sizeof(bb)); + F->close_chunk(); + + F->open_chunk(E_AIMAP_CHUNK_PARAMS); + F->w(&m_Params, sizeof(m_Params)); + F->close_chunk(); + + EnumerateNodes(); + F->open_chunk(E_AIMAP_CHUNK_NODES); + + u32 nodesCount = m_Nodes.size(); + u32 defaultMaxNodesCount = (u32(1) << u32(MAX_NODE_BIT_COUNT)) - 2; + + if (nodesCount > defaultMaxNodesCount) + { + ELog.DlgMsg(mtInformation, "Warning. AI-Map contains %u nodes. Original compiler/game can handle only %u nodes. Extra: %u nodes", + nodesCount, + defaultMaxNodesCount, + nodesCount - defaultMaxNodesCount); + } + + F->w_u32(nodesCount); + + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + { + u32 id; + u16 pl; + NodePosition np; + + id = (*it)->n1 ? (u32)(*it)->n1->idx : InvalidNode; + F->w(&id, 3); + id = (*it)->n2 ? (u32)(*it)->n2->idx : InvalidNode; + F->w(&id, 3); + id = (*it)->n3 ? (u32)(*it)->n3->idx : InvalidNode; + F->w(&id, 3); + id = (*it)->n4 ? (u32)(*it)->n4->idx : InvalidNode; + F->w(&id, 3); + pl = pvCompress((*it)->Plane.n); + F->w_u16(pl); + PackPosition(np, (*it)->Pos, bb, m_Params); + F->w(&np, sizeof(np)); + } + F->close_chunk(); + + FS.w_close(F); + return true; + } + return false; +} +/* + u32 id; + u16 pl; + NodePosition np; + F.r (&id,3); n1 = (SAINode*)tools->UnpackLink(id); + F.r (&id,3); n2 = (SAINode*)tools->UnpackLink(id); + F.r (&id,3); n3 = (SAINode*)tools->UnpackLink(id); + F.r (&id,3); n4 = (SAINode*)tools->UnpackLink(id); + pl = F.r_u16(); pvDecompress(Plane.n,pl); + F.r (&np,sizeof(np)); tools->UnpackPosition(Pos,np,tools->m_BBox,tools->m_Params); + Plane.build (Pos,Plane.n); +*/ diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Export.h b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Export.h new file mode 100644 index 00000000000..f16baaab9ab --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Export.h @@ -0,0 +1,29 @@ +#ifndef ESceneAIMapTools_ExportH +#define ESceneAIMapTools_ExportH + +//---------------------------------------------------- +struct SAIParams +{ + float fPatchSize; // patch size + float fTestHeight; // test height (center of the "tester") + float fCanUP; // can reach point in up (dist) + float fCanDOWN; // can reach point down (dist) + + SAIParams() + { + fPatchSize = 0.7f; + fTestHeight = 1.0f; + fCanUP = 1.5f; + fCanDOWN = 4.0f; + } +}; + +// chunks +#define E_AIMAP_VERSION 0x0001 +//---------------------------------------------------- +#define E_AIMAP_CHUNK_VERSION 0x0001 +#define E_AIMAP_CHUNK_BOX 0x0002 +#define E_AIMAP_CHUNK_PARAMS 0x0003 +#define E_AIMAP_CHUNK_NODES 0x0004 +//---------------------------------------------------- +#endif diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Generate.cpp b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Generate.cpp new file mode 100644 index 00000000000..08e3c75cfd5 --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Generate.cpp @@ -0,0 +1,1284 @@ +#include "stdafx.h" + +static SPickQuery PQ; + +IC void SnapXZ(Fvector &V, float ps) +{ + V.x = snapto(V.x, ps); + V.z = snapto(V.z, ps); +} + +struct tri +{ + Fvector *v[3]; + Fvector N; +}; + +const int RCAST_MaxTris = (2 * 1024); +const int RCAST_Count = 4; +const int RCAST_Total = (2 * RCAST_Count + 1) * (2 * RCAST_Count + 1); +const float RCAST_Depth = 1.f; +const float RCAST_VALID = 0.55f; + +BOOL ESceneAIMapTool::CreateNode(Fvector &vAt, SAINode &N, bool bIC) +{ + // *** Query and cache polygons for ray-casting + Fvector PointUp; + PointUp.set(vAt); + PointUp.y += RCAST_Depth; + SnapXZ(PointUp, m_Params.fPatchSize); + Fvector PointDown; + PointDown.set(vAt); + PointDown.y -= RCAST_Depth; + SnapXZ(PointDown, m_Params.fPatchSize); + + Fbox BB; + BB.set(PointUp, PointUp); + BB.grow(m_Params.fPatchSize / 2); // box 1 + Fbox B2; + B2.set(PointDown, PointDown); + B2.grow(m_Params.fPatchSize / 2); // box 2 + BB.merge(B2); + + if (m_CFModel) + { + /* + for(u32 i=0; iget_tris_count(); ++i) + { + CDB::TRI* tri = (m_CFModel->get_tris()+i); + if(tri->material!=0) + Msg("non-default material"); + } + */ + Scene->BoxQuery(PQ, BB, CDB::OPT_FULL_TEST, m_CFModel); + } + else + Scene->BoxQuery(PQ, BB, CDB::OPT_FULL_TEST, GetSnapList()); + + DWORD dwCount = PQ.r_count(); + if (dwCount == 0) + { + // Log("chasm1"); + return FALSE; // chasm? + } + + // *** Transfer triangles and compute sector + // R_ASSERT(dwCount tris; + tris.reserve(RCAST_MaxTris); + tris.clear(); + for (DWORD i = 0; i < dwCount; i++) + { + SPickQuery::SResult *R = PQ.r_begin() + i; + + if (R->e_obj && R->e_mesh) + { + CSurface *surf = R->e_mesh->GetSurfaceByFaceID(R->tag); + //. SGameMtl* mtl = GMLib.GetMaterialByID(surf->_GameMtl()); + //. if (mtl->Flags.is(SGameMtl::flPassable))continue; + + Shader_xrLC *c_sh = EDevice.ShaderXRLC.Get(surf->_ShaderXRLCName()); + if (!c_sh->flags.bCollision) + continue; + } + /* + if(m_CFModel) + { + u16 mtl_id = R->material; + + if(std::find(m_ignored_materials.begin(), m_ignored_materials.end(), mtl_id) != m_ignored_materials.end() ) + { + //. Msg("--ignore"); + continue; + } + } + */ + tris.push_back(tri()); + tri &D = tris.back(); + Fvector *V = R->verts; + + D.v[0] = &V[0]; + D.v[1] = &V[1]; + D.v[2] = &V[2]; + D.N.mknormal(*D.v[0], *D.v[1], *D.v[2]); + if (D.N.y <= 0) + tris.pop_back(); + } + if (tris.size() == 0) + { + // Log("chasm2"); + return FALSE; // chasm? + } + + static xr_vector points; + points.reserve(RCAST_Total); + points.clear(); + static xr_vector normals; + normals.reserve(RCAST_Total); + normals.clear(); + Fvector P, D; + D.set(0, -1, 0); + + float coeff = 0.5f * m_Params.fPatchSize / float(RCAST_Count); + + for (int x = -RCAST_Count; x <= RCAST_Count; x++) + { + P.x = vAt.x + coeff * float(x); + for (int z = -RCAST_Count; z <= RCAST_Count; z++) + { + P.z = vAt.z + coeff * float(z); + P.y = vAt.y + 10.f; + + float tri_min_range = flt_max; + int tri_selected = -1; + float range, u, v; + for (DWORD i = 0; i < DWORD(tris.size()); i++) + { + if (ETOOLS::TestRayTriA(P, D, tris[i].v, u, v, range, false)) + { + if (range < tri_min_range) + { + tri_min_range = range; + tri_selected = i; + } + } + } + if (tri_selected >= 0) + { + P.y -= tri_min_range; + points.push_back(P); + normals.push_back(tris[tri_selected].N); + } + } + } + if (points.size() < 3) + { + // Msg ("Failed to create node at [%f,%f,%f].",vAt.x,vAt.y,vAt.z); + return FALSE; + } + //. + float rc_lim = bIC ? 0.015f : 0.7f; + if (float(points.size()) / float(RCAST_Total) < rc_lim) + { + // Msg ("Partial chasm at [%f,%f,%f].",vAt.x,vAt.y,vAt.z); + return FALSE; + } + + // *** Calc normal + Fvector vNorm; + vNorm.set(0, 0, 0); + for (DWORD n = 0; n < normals.size(); n++) + vNorm.add(normals[n]); + vNorm.div(float(normals.size())); + vNorm.normalize(); + /* + { + // second algorithm (Magic) + Fvector N,O; + N.set(vNorm); + O.set(points[0]); + Mgc::OrthogonalPlaneFit( + points.size(),(Mgc::Vector3*)points.begin(), + *((Mgc::Vector3*)&O), + *((Mgc::Vector3*)&N) + ); + if (N.y<0) N.invert(); + N.normalize(); + vNorm.lerp(vNorm,N,.3f); + vNorm.normalize(); + } + */ + + // *** Align plane + Fvector vOffs; + vOffs.set(0, -1000, 0); + Fplane PL; + PL.build(vOffs, vNorm); + for (DWORD p = 0; p < points.size(); p++) + { + float dist = PL.classify(points[p]); + if (dist > 0) + { + vOffs = points[p]; + PL.build(vOffs, vNorm); + } + } + + // *** Create node and register it + N.Plane.build(vOffs, vNorm); // build plane + D.set(0, 1, 0); + N.Plane.intersectRayPoint(PointDown, D, N.Pos); // "project" position + + // *** Validate results + vNorm.set(0, 1, 0); + if (vNorm.dotproduct(N.Plane.n) < _cos(deg2rad(60.f))) + return FALSE; + + float y_old = vAt.y; + float y_new = N.Pos.y; + if (y_old > y_new) + { + // down + if (y_old - y_new > m_Params.fCanDOWN) + return FALSE; + } + else + { + // up + if (y_new - y_old > m_Params.fCanUP) + return FALSE; + } + + // *** Validate plane + { + Fvector PLP; + D.set(0, -1, 0); + int num_successed_rays = 0; + for (int x = -RCAST_Count; x <= RCAST_Count; x++) + { + P.x = N.Pos.x + coeff * float(x); + for (int z = -RCAST_Count; z <= RCAST_Count; z++) + { + P.z = N.Pos.z + coeff * float(z); + P.y = N.Pos.y; + N.Plane.intersectRayPoint(P, D, PLP); // "project" position + P.y = PLP.y + RCAST_VALID * 0.01f; + + float tri_min_range = flt_max; + int tri_selected = -1; + float range, u, v; + for (size_t i = 0; i < tris.size(); i++) + { + if (ETOOLS::TestRayTriA(P, D, tris[i].v, u, v, range, false)) + { + if (range < tri_min_range) + { + tri_min_range = range; + tri_selected = i; + } + } + } + if (tri_selected >= 0) + { + if (tri_min_range < RCAST_VALID) + num_successed_rays++; + } + } + } + float perc = float(num_successed_rays) / float(RCAST_Total); + //. if (!bIC&&(perc < 0.5f)){ + float perc_lim = bIC ? 0.015f : 0.5f; + if (perc < perc_lim) + { + // Msg ("Floating node."); + return FALSE; + } + } + + // *** Mask check + // ??? + + return TRUE; +} + +void ESceneAIMapTool::hash_Initialize() +{ + for (int i = 0; i <= HDIM_X; i++) + for (int j = 0; j <= HDIM_Z; j++) + { + // m_HASH[i][j] = xr_new(); + m_HASH[i][j].clear(); + m_HASH[i][j].reserve(64); + } +} + +void ESceneAIMapTool::hash_FillFromNodes() +{ + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + { + AINodeVec *V = HashMap((*it)->Pos); + R_ASSERT2(V, "AINode position out of bounds."); + V->push_back(*it); + } +} + +void ESceneAIMapTool::hash_Clear() +{ + for (int i = 0; i <= HDIM_X; i++) + for (int j = 0; j <= HDIM_Z; j++) + // xr_delete (m_HASH[i][j]); + m_HASH[i][j].clear(); +} + +void ESceneAIMapTool::HashRect(const Fvector &v, float radius, Irect &result) +{ + Fvector VMmin, VMscale, VMeps, scale; + + Fbox &bb = m_AIBBox; + VMscale.set(bb.vMax.x - bb.vMin.x, bb.vMax.y - bb.vMin.y, bb.vMax.z - bb.vMin.z); + VMmin.set(bb.vMin); + VMeps.set(float(VMscale.x / HDIM_X / 2.f), float(0), float(VMscale.z / HDIM_Z / 2.f)); + VMeps.x = (VMeps.x < EPS_L) ? VMeps.x : EPS_L; + VMeps.y = (VMeps.y < EPS_L) ? VMeps.y : EPS_L; + VMeps.z = (VMeps.z < EPS_L) ? VMeps.z : EPS_L; + scale.set(float(HDIM_X), float(0), float(HDIM_Z)); + scale.div(VMscale); + + // Hash + result.x1 = iFloor((v.x - VMmin.x - radius) * scale.x); + clamp(result.x1, 0, HDIM_X); + result.y1 = iFloor((v.z - VMmin.z - radius) * scale.z); + clamp(result.y1, 0, HDIM_Z); + result.x2 = iFloor((v.x - VMmin.x + radius) * scale.x); + clamp(result.x2, 0, HDIM_X); + result.y2 = iFloor((v.z - VMmin.z + radius) * scale.z); + clamp(result.y2, 0, HDIM_Z); +} + +AINodeVec *ESceneAIMapTool::HashMap(int ix, int iz) +{ + return (ix <= HDIM_X && iz <= HDIM_Z) ? &m_HASH[ix][iz] : 0; +} + +AINodeVec *ESceneAIMapTool::HashMap(Fvector &V) +{ + // Calculate offset,scale,epsilon + Fvector VMmin, VMscale, VMeps, scale; + + Fbox &bb = m_AIBBox; + VMscale.set(bb.vMax.x - bb.vMin.x, bb.vMax.y - bb.vMin.y, bb.vMax.z - bb.vMin.z); + VMmin.set(bb.vMin); + VMeps.set(float(VMscale.x / HDIM_X / 2.f), float(0), float(VMscale.z / HDIM_Z / 2.f)); + VMeps.x = (VMeps.x < EPS_L) ? VMeps.x : EPS_L; + VMeps.y = (VMeps.y < EPS_L) ? VMeps.y : EPS_L; + VMeps.z = (VMeps.z < EPS_L) ? VMeps.z : EPS_L; + scale.set(float(HDIM_X), float(0), float(HDIM_Z)); + scale.div(VMscale); + + // Hash + DWORD ix, iz; + ix = iFloor((V.x - VMmin.x) * scale.x); + iz = iFloor((V.z - VMmin.z) * scale.z); + return (ix <= HDIM_X && iz <= HDIM_Z) ? &m_HASH[ix][iz] : 0; +} + +SAINode *ESceneAIMapTool::FindNode(Fvector &vAt, float eps) +{ + AINodeVec *V = HashMap(vAt); + if (!V) + return 0; + + for (AINodeIt I = V->begin(); I != V->end(); I++) + { + SAINode *N = *I; + if (vAt.similar(N->Pos, eps)) + return N; + } + return 0; +} + +BOOL ESceneAIMapTool::CanTravel(Fvector _from, Fvector _at) +{ + _at.y = _from.y; + + float eps = 0.1f; + float eps_y = m_Params.fPatchSize * 1.5f; // * tan(56) = 1.5 + Fvector Result; + float radius = m_Params.fPatchSize / _sqrt(2.f); + + // 1 + MotionSimulate(Result, _from, _at, radius, 0.7f); + BOOL b1 = fsimilar(Result.x, _at.x, eps) && fsimilar(Result.z, _at.z, eps) && fsimilar(Result.y, _at.y, eps_y); + if (b1) + return TRUE; + + // 2 + MotionSimulate(Result, _from, _at, radius, 2.f); + BOOL b2 = fsimilar(Result.x, _at.x, eps) && fsimilar(Result.z, _at.z, eps) && fsimilar(Result.y, _at.y, eps_y); + if (b2) + return TRUE; + + return FALSE; +} + +SAINode *ESceneAIMapTool::BuildNode(Fvector &vFrom, Fvector &vAt, bool bIC, bool bSuperIC) // return node's index +{ + // *** Test if we can travel this path + SnapXZ(vAt, m_Params.fPatchSize); + + if (!(bIC || CanTravel(vFrom, vAt))) + return 0; + + // *** set up node + SAINode N; + + BOOL bRes = CreateNode(vAt, N, bIC); + if (!bRes && bIC && bSuperIC) + { + Fvector D = {0, 1, 0}; + N.Plane.build(vAt, D); // build plane + N.Plane.intersectRayPoint(vAt, D, N.Pos); // "project" position + bRes = TRUE; + } + if (bRes) + { + //*** check if similar node exists + SAINode *old = FindNode(N.Pos); + if (!old) + { + // register xr_new(N)); + V->push_back(m_Nodes.back()); + return m_Nodes.back(); + } + else + return 0; + } + else + { + // where already was node - return it + return old; + } + } + else + { + return 0; + } +} + +int ESceneAIMapTool::BuildNodes(const Fvector &pos, int sz, bool bIC) +{ + // Align emitter + Fvector Pos = pos; + SnapXZ(Pos, m_Params.fPatchSize); + Pos.y += 1; + Fvector Dir; + Dir.set(0, -1, 0); + + int cnt = 0; + if (m_CFModel) + cnt = Scene->RayQuery(PQ, Pos, Dir, 3, CDB::OPT_ONLYNEAREST | CDB::OPT_CULL, m_CFModel); + else + cnt = Scene->RayQuery(PQ, Pos, Dir, 3, CDB::OPT_ONLYNEAREST | CDB::OPT_CULL, GetSnapList()); + + if (0 == cnt) + { + ELog.Msg(mtInformation, "Can't align position."); + return 0; + } + else + { + Pos.y = Pos.y - PQ.r_begin()->range; + } + + // Build first node + int oldcount = m_Nodes.size(); + SAINode *start = BuildNode(Pos, Pos, bIC); + if (!start) + return 0; + + // Estimate nodes + float estimated_nodes = static_cast((2 * sz - 1) * (2 * sz - 1)); + + SPBItem *pb = 0; + if (estimated_nodes > 1024) + pb = UI->ProgressStart(1, "Building nodes..."); + float radius = sz * m_Params.fPatchSize - EPS_L; + // General cycle + for (int k = 0; k < (int)m_Nodes.size(); k++) + { + SAINode *N = m_Nodes[k]; + // left + if (0 == N->n1) + { + Pos.set(N->Pos); + Pos.x -= m_Params.fPatchSize; + if (Pos.distance_to(start->Pos) <= radius) + N->n1 = BuildNode(N->Pos, Pos, bIC); + } + // fwd + if (0 == N->n2) + { + Pos.set(N->Pos); + Pos.z += m_Params.fPatchSize; + if (Pos.distance_to(start->Pos) <= radius) + N->n2 = BuildNode(N->Pos, Pos, bIC); + } + // right + if (0 == N->n3) + { + Pos.set(N->Pos); + Pos.x += m_Params.fPatchSize; + if (Pos.distance_to(start->Pos) <= radius) + N->n3 = BuildNode(N->Pos, Pos, bIC); + } + // back + if (0 == N->n4) + { + Pos.set(N->Pos); + Pos.z -= m_Params.fPatchSize; + if (Pos.distance_to(start->Pos) <= radius) + N->n4 = BuildNode(N->Pos, Pos, bIC); + } + if (estimated_nodes > 1024) + { + if (k % 128 == 0) + { + float p1 = float(k) / float(m_Nodes.size()); + float p2 = float(m_Nodes.size()) / estimated_nodes; + float p = 0.1f * p1 + 0.9f * p2; + + clamp(p, 0.f, 1.f); + pb->Update(p); + // check need abort && redraw + if (UI->NeedAbort()) + break; + } + } + } + if (estimated_nodes > 1024) + UI->ProgressEnd(pb); + return oldcount - m_Nodes.size(); +} + +void ESceneAIMapTool::BuildNodes(bool bFromSelectedOnly) +{ + // begin + m_Nodes.reserve(1024 * 1024); + + // Initialize hash + // hash_Initialize (); + + R_ASSERT(!m_Nodes.empty()); + // Estimate nodes + Fvector Pos, LevelSize; + m_AIBBox.getsize(LevelSize); + float estimated_nodes = (LevelSize.x / m_Params.fPatchSize) * (LevelSize.z / m_Params.fPatchSize); + + SPBItem *pb = UI->ProgressStart(1, "Building nodes..."); + // General cycle + for (int k = 0; k < (int)m_Nodes.size(); k++) + { + SAINode *N = m_Nodes[k]; + if (bFromSelectedOnly && !N->flags.is(SAINode::flSelected)) + continue; + // left + if (0 == N->n1) + { + Pos.set(N->Pos); + Pos.x -= m_Params.fPatchSize; + N->n1 = BuildNode(N->Pos, Pos, false); + } + // fwd + if (0 == N->n2) + { + Pos.set(N->Pos); + Pos.z += m_Params.fPatchSize; + N->n2 = BuildNode(N->Pos, Pos, false); + } + // right + if (0 == N->n3) + { + Pos.set(N->Pos); + Pos.x += m_Params.fPatchSize; + N->n3 = BuildNode(N->Pos, Pos, false); + } + // back + if (0 == N->n4) + { + Pos.set(N->Pos); + Pos.z -= m_Params.fPatchSize; + N->n4 = BuildNode(N->Pos, Pos, false); + } + if (bFromSelectedOnly) + { + // select neighbour nodes + if (N->n1) + N->n1->flags.set(SAINode::flSelected, TRUE); + if (N->n2) + N->n2->flags.set(SAINode::flSelected, TRUE); + if (N->n3) + N->n3->flags.set(SAINode::flSelected, TRUE); + if (N->n4) + N->n4->flags.set(SAINode::flSelected, TRUE); + } + + if (k % 512 == 0) + { + float p1 = float(k) / float(m_Nodes.size()); + float p2 = float(m_Nodes.size()) / estimated_nodes; + float p = 0.1f * p1 + 0.9f * p2; + + clamp(p, 0.f, 1.f); + pb->Update(p); + // check need abort && redraw + if (k % 32768 == 0) + UI->RedrawScene(false); + if (UI->NeedAbort()) + break; + } + } + UI->ProgressEnd(pb); +} + +SAINode *ESceneAIMapTool::GetNode(Fvector vAt, bool bIC) // return node's index +{ + // *** Test if we can travel this path + SnapXZ(vAt, m_Params.fPatchSize); + + // *** set up xr_new(); + SAINode *R = 0; + if (CreateNode(vAt, *N, bIC)) + { + R = FindNode(N->Pos); + xr_delete(N); + } + xr_delete(N); + return R; +} + +void ESceneAIMapTool::UpdateLinks(SAINode *N, bool bIC) +{ + Fvector Pos; + SAINode *D; + // left + { + Pos.set(N->Pos); + Pos.x -= m_Params.fPatchSize; + D = GetNode(Pos, bIC); + if (bIC || CanTravel(N->Pos, Pos)) + N->n1 = D; + if (D && (bIC || CanTravel(D->Pos, N->Pos))) + D->n3 = N; + } + // fwd + { + Pos.set(N->Pos); + Pos.z += m_Params.fPatchSize; + D = GetNode(Pos, bIC); + if (bIC || CanTravel(N->Pos, Pos)) + N->n2 = D; + if (D && (bIC || CanTravel(D->Pos, N->Pos))) + D->n4 = N; + } + // right + { + Pos.set(N->Pos); + Pos.x += m_Params.fPatchSize; + D = GetNode(Pos, bIC); + if (bIC || CanTravel(N->Pos, Pos)) + N->n3 = D; + if (D && (bIC || CanTravel(D->Pos, N->Pos))) + D->n1 = N; + } + // back + { + Pos.set(N->Pos); + Pos.z -= m_Params.fPatchSize; + D = GetNode(Pos, bIC); + if (bIC || CanTravel(N->Pos, Pos)) + N->n4 = D; + if (D && (bIC || CanTravel(D->Pos, N->Pos))) + D->n2 = N; + } +} + +bool ESceneAIMapTool::GenerateMap(bool bFromSelectedOnly) +{ + std::sort(m_ignored_materials.begin(), m_ignored_materials.end()); + bool bRes = false; + if (!GetSnapList()->empty()) + { + if (!RealUpdateSnapList()) + return false; + if (m_Nodes.empty()) + { + ELog.DlgMsg(mtError, "Append at least one node."); + return false; + } + + if (!m_Flags.is(flSlowCalculate)) + { + // evict resources + ExecCommand(COMMAND_EVICT_OBJECTS); + ExecCommand(COMMAND_EVICT_TEXTURES); + + // prepare collision model + u32 avg_face_cnt = 0; + u32 avg_vert_cnt = 0; + u32 mesh_cnt = 0; + Fbox snap_bb; + { + snap_bb.invalidate(); + for (ObjectIt o_it = m_SnapObjects.begin(); o_it != m_SnapObjects.end(); o_it++) + { + CSceneObject *S = dynamic_cast(*o_it); + VERIFY(S); + avg_face_cnt += S->GetFaceCount(); + avg_vert_cnt += S->GetVertexCount(); + mesh_cnt += S->Meshes()->size(); + Fbox bb; + S->GetBox(bb); + snap_bb.merge(bb); + } + } + + SPBItem *pb = UI->ProgressStart(static_cast(mesh_cnt), "Prepare collision model..."); + + CDB::Collector *CL = ETOOLS::create_collector(); + Fvector verts[3]; + for (ObjectIt o_it = m_SnapObjects.begin(); o_it != m_SnapObjects.end(); o_it++) + { + CSceneObject *S = dynamic_cast(*o_it); + VERIFY(S); + CEditableObject *E = S->GetReference(); + VERIFY(E); + EditMeshVec &_meshes = E->Meshes(); + for (EditMeshIt m_it = _meshes.begin(); m_it != _meshes.end(); m_it++) + { + pb->Inc(make_string("%s [%s]", S->GetName(), (*m_it)->Name().c_str()).c_str()); + const SurfFaces &_sfaces = (*m_it)->GetSurfFaces(); + for (SurfFaces::const_iterator sp_it = _sfaces.begin(); sp_it != _sfaces.end(); sp_it++) + { + CSurface *surf = sp_it->first; + // test passable + //. SGameMtl* mtl = GMLib.GetMaterialByID(surf->_GameMtl()); + //. if (mtl->Flags.is(SGameMtl::flPassable))continue; + + Shader_xrLC *c_sh = EDevice.ShaderXRLC.Get(surf->_ShaderXRLCName()); + if (!c_sh->flags.bCollision) + continue; + // collect tris + const IntVec &face_lst = sp_it->second; + for (IntVec::const_iterator it = face_lst.begin(); it != face_lst.end(); it++) + { + E->GetFaceWorld(S->_Transform(), *m_it, *it, verts); + + ETOOLS::collector_add_face_d(CL, verts[0], verts[1], verts[2], surf->_GameMtl() /* *it */); + if (surf->m_Flags.is(CSurface::sf2Sided)) + ETOOLS::collector_add_face_d(CL, verts[2], verts[1], verts[0], surf->_GameMtl() /* *it */); + } + } + } + } + + UI->ProgressEnd(pb); + + UI->SetStatus("Building collision model..."); + // create CFModel + m_CFModel = ETOOLS::create_model_cl(CL); + ETOOLS::destroy_collector(CL); + } + + // building + Scene->lock(); + CTimer tm; + tm.Start(); + BuildNodes(bFromSelectedOnly); + tm.GetElapsed_sec(); + Scene->unlock(); + //. Log("-test time: ", g_tm.GetElapsed_sec()); + Log("-building time: ", tm.GetElapsed_sec()); + //. Msg("-Rate: %3.2f Count: %d",(g_tm.GetElapsed_sec()/tm.GetElapsed_sec())*100.f,g_tm.count); + + // unload CFModel + ETOOLS::destroy_model(m_CFModel); + + Scene->UndoSave(); + bRes = true; + + UI->SetStatus(""); + } + else + { + ELog.DlgMsg(mtError, "Fill snap list before generating slots!"); + } + return bRes; +} + +int ESceneAIMapTool::RemoveOutOfBoundsNodes() +{ + int count = 0; + for (int k = 0; k < (int)m_Nodes.size(); k++) + { + SAINode *N = m_Nodes[k]; + AINodeVec *V = HashMap(N->Pos); + if (!V) + { + m_Nodes.erase(m_Nodes.begin() + k); + k--; + count++; + } + } + return count; +} + +bool ESceneAIMapTool::RealUpdateSnapList() +{ + m_Flags.set(flUpdateSnapList, FALSE); + Fbox nodes_bb; + CalculateNodesBBox(nodes_bb); + if (!GetSnapList()->empty()) + { + Fbox bb, snap_bb; + Scene->GetBox(snap_bb, *GetSnapList()); + if (nodes_bb.is_valid()) + bb.merge(snap_bb, nodes_bb); + else + bb.set(snap_bb); + if (!m_AIBBox.similar(bb)) + { + m_AIBBox.set(bb); + hash_Clear(); + hash_FillFromNodes(); + } + return true; + } + else + { + m_AIBBox.set(nodes_bb); + hash_Clear(); + hash_FillFromNodes(); + return false; + } +} + +void ESceneAIMapTool::RemoveLinks() +{ + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + if ((*it)->flags.is(SAINode::flSelected)) + { + for (int k = 0; k < 4; k++) + if ((*it)->n[k] && (*it)->n[k]->flags.is(SAINode::flSelected)) + (*it)->n[k] = 0; + } + UpdateHLSelected(); +} + +static const int opposite[4] = {2, 3, 0, 1}; +static const u8 fl[4] = {SAINode::flN1, SAINode::flN2, SAINode::flN3, SAINode::flN4}; +void ESceneAIMapTool::InvertLinks() +{ + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + if ((*it)->flags.is(SAINode::flSelected)) + for (int k = 0; k < 4; k++) + if ((*it)->n[k] && (*it)->n[k]->flags.is(SAINode::flSelected) && !(*it)->flags.is(fl[k])) + { + if (0 == (*it)->n[k]->n[opposite[k]]) + { + (*it)->n[k]->n[opposite[k]] = (*it); + (*it)->n[k]->flags.set(fl[opposite[k]], TRUE); + (*it)->n[k] = 0; + } + } + // reset processing flag + for (AINodeIt a_it = m_Nodes.begin(); a_it != m_Nodes.end(); a_it++) + (*a_it)->flags.set(SAINode::flN1 | SAINode::flN2 | SAINode::flN3 | SAINode::flN4, FALSE); + UpdateHLSelected(); +} + +SAINode *ESceneAIMapTool::FindNeighbor(SAINode *N, int side, bool bIgnoreConstraints) +{ + Fvector Pos; + Pos.set(N->Pos); + SnapXZ(Pos, m_Params.fPatchSize); + switch (side) + { + case 0: + Pos.x -= m_Params.fPatchSize; + break; + case 1: + Pos.z += m_Params.fPatchSize; + break; + case 2: + Pos.x += m_Params.fPatchSize; + break; + case 3: + Pos.z -= m_Params.fPatchSize; + break; + } + AINodeVec *nodes = HashMap(Pos); + SAINode *R = 0; + if (nodes) + if (bIgnoreConstraints) + { + float dy = flt_max; + for (AINodeIt I = nodes->begin(); I != nodes->end(); I++) + if (fsimilar((*I)->Pos.x, Pos.x, EPS_L) && fsimilar((*I)->Pos.z, Pos.z, EPS_L)) + { + float _dy = _abs((*I)->Pos.y - Pos.y); + if (_dy < dy) + { + dy = _dy; + R = *I; + } + } + } + else + { + SAINode *R_up = 0; + SAINode *R_down = 0; + float dy_up = flt_max; + float dy_down = flt_max; + for (AINodeIt I = nodes->begin(); I != nodes->end(); I++) + { + if (fsimilar((*I)->Pos.x, Pos.x, EPS_L) && fsimilar((*I)->Pos.z, Pos.z, EPS_L)) + { + float _dy = (*I)->Pos.y - Pos.y; + float _ady = _abs(_dy); + if (_dy >= 0.f) + { + if ((_ady < m_Params.fCanUP) && (_ady < dy_up)) + { + dy_up = _ady; + R_up = *I; + } + } + else + { + if ((_ady < m_Params.fCanDOWN) && (_ady < dy_down)) + { + dy_down = _ady; + R_down = *I; + } + } + } + } + if (dy_down <= dy_up) + R = R_down; + else + R = R_up; + } + return R; +} + +void ESceneAIMapTool::MakeLinks(u8 side_flag, EMode mode, bool bIgnoreConstraints) +{ + if (!side_flag) + return; + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + { + SAINode *T = *it; + if ((*it)->flags.is(SAINode::flSelected)) + { + for (int k = 0; k < 4; k++) + { + if (!(side_flag & fl[k])) + continue; + switch (mode) + { + case mdAppend: + { + SAINode *S = FindNeighbor(T, k, bIgnoreConstraints); + if (S && S->flags.is(SAINode::flSelected)) + T->n[k] = S; + } + break; + case mdRemove: + { + SAINode *S = FindNeighbor(T, k, bIgnoreConstraints); + if (S && S->flags.is(SAINode::flSelected)) + T->n[k] = 0; + } + break; + case mdInvert: + { + SAINode *S = FindNeighbor(T, k, bIgnoreConstraints); + if (S) + { + if (!T->flags.is(fl[k])) + { + if (T->n[k] && S->n[opposite[k]]) + continue; + SAINode *a = T->n[k]; + T->n[k] = S->n[opposite[k]]; + S->n[opposite[k]] = a; + } + S->flags.set(fl[opposite[k]], TRUE); + } + } + break; + } + } + } + } + // reset processing flag + for (AINodeIt a_it = m_Nodes.begin(); a_it != m_Nodes.end(); a_it++) + (*a_it)->flags.set(SAINode::flN1 | SAINode::flN2 | SAINode::flN3 | SAINode::flN4, FALSE); + UpdateHLSelected(); +} + +void ESceneAIMapTool::ResetNodes() +{ + SPBItem *pb = UI->ProgressStart(static_cast(m_Nodes.size()), "Smoothing nodes..."); + + int n_cnt = 0; + + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + { + SAINode &N = **it; + if (N.flags.is(SAINode::flSelected)) + { + n_cnt++; + N.Plane.build(N.Pos, Fvector().set(0, 1, 0)); + } + } + UI->ProgressEnd(pb); + if (n_cnt) + Scene->UndoSave(); +} + +#define merge(pt) \ + if (fsimilar(P.y, REF.y, m_SmoothHeight)) \ + { \ + c++; \ + pt.add(P); \ + } +void ESceneAIMapTool::SmoothNodes() +{ + SPBItem *pb = UI->ProgressStart(static_cast(m_Nodes.size()), "Smoothing nodes..."); + + AINodeVec smoothed; + smoothed.reserve(m_Nodes.size()); + U8Vec mark; + mark.assign(m_Nodes.size(), 0); + + int sm_nodes = 0; + + EnumerateNodes(); + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + { + SAINode &N = **it; + Fvector P1, P2, P3, P4, P, REF; + int c; + + if (N.flags.is(SAINode::flSelected)) + { + sm_nodes++; + + // smooth point LF + { + bool bCorner = false; + + c = 1; + N.PointLF(REF, m_Params.fPatchSize); + P1.set(REF); + if (N.nLeft()) + { + SAINode &L = *N.nLeft(); + + L.PointFR(P, m_Params.fPatchSize); + merge(P1); + if (L.nForward()) + { + bCorner = true; + SAINode &C = *L.nForward(); + + C.PointRB(P, m_Params.fPatchSize); + merge(P1); + } + } + if (N.nForward()) + { + SAINode &F = *N.nForward(); + + F.PointBL(P, m_Params.fPatchSize); + merge(P1); + if ((!bCorner) && F.nLeft()) + { + bCorner = true; + + SAINode &C = *F.nLeft(); + C.PointRB(P, m_Params.fPatchSize); + merge(P1); + } + } + R_ASSERT(c <= 4); + P1.div(float(c)); + } + + // smooth point FR + { + bool bCorner = false; + + c = 1; + N.PointFR(REF, m_Params.fPatchSize); + P2.set(REF); + if (N.nForward()) + { + SAINode &F = *N.nForward(); + + F.PointRB(P, m_Params.fPatchSize); + merge(P2); + if (F.nRight()) + { + bCorner = true; + SAINode &C = *F.nRight(); + + C.PointBL(P, m_Params.fPatchSize); + merge(P2); + } + } + if (N.nRight()) + { + SAINode &R = *N.nRight(); + + R.PointLF(P, m_Params.fPatchSize); + merge(P2); + if ((!bCorner) && R.nForward()) + { + bCorner = true; + + SAINode &C = *R.nForward(); + C.PointBL(P, m_Params.fPatchSize); + merge(P2); + } + } + R_ASSERT(c <= 4); + P2.div(float(c)); + } + + // smooth point RB + { + bool bCorner = false; + + c = 1; + N.PointRB(REF, m_Params.fPatchSize); + P3.set(REF); + if (N.nRight()) + { + SAINode &R = *N.nRight(); + + R.PointBL(P, m_Params.fPatchSize); + merge(P3); + if (R.nBack()) + { + bCorner = true; + SAINode &C = *R.nBack(); + + C.PointLF(P, m_Params.fPatchSize); + merge(P3); + } + } + if (N.nBack()) + { + SAINode &B = *N.nBack(); + + B.PointFR(P, m_Params.fPatchSize); + merge(P3); + if ((!bCorner) && B.nRight()) + { + bCorner = true; + + SAINode &C = *B.nRight(); + C.PointLF(P, m_Params.fPatchSize); + merge(P3); + } + } + R_ASSERT(c <= 4); + P3.div(float(c)); + } + + // smooth point BL + { + bool bCorner = false; + + c = 1; + N.PointBL(REF, m_Params.fPatchSize); + P4.set(REF); + if (N.nBack()) + { + SAINode &B = *N.nBack(); + + B.PointLF(P, m_Params.fPatchSize); + merge(P4); + if (B.nLeft()) + { + bCorner = true; + SAINode &C = *B.nLeft(); + + C.PointFR(P, m_Params.fPatchSize); + merge(P4); + } + } + if (N.nLeft()) + { + SAINode &L = *N.nLeft(); + + L.PointRB(P, m_Params.fPatchSize); + merge(P4); + if ((!bCorner) && L.nBack()) + { + bCorner = true; + + SAINode &C = *L.nBack(); + C.PointFR(P, m_Params.fPatchSize); + merge(P4); + } + } + R_ASSERT(c <= 4); + P4.div(float(c)); + } + + // align plane + Fvector data[4]; + data[0] = P1; + data[1] = P2; + data[2] = P3; + data[3] = P4; + Fvector vOffs, vNorm, D; + vNorm.set(N.Plane.n); + vOffs.set(N.Pos); + Mgc::OrthogonalPlaneFit( + 4, (Mgc::Vector3 *)data, + *((Mgc::Vector3 *)&vOffs), + *((Mgc::Vector3 *)&vNorm)); + if (vNorm.y < 0) + vNorm.invert(); + // create _new node + SAINode *NEW = xr_new(N); +#pragma TODO("TSMP: seems wrong to cast 32 bit value to 64 bit pointer (on x64)") + NEW->n1 = (SAINode*)(size_t)(N.n1 ? N.n1->idx : InvalidNode); + NEW->n2 = (SAINode*)(size_t)(N.n2 ? N.n2->idx : InvalidNode); + NEW->n3 = (SAINode*)(size_t)(N.n3 ? N.n3->idx : InvalidNode); + NEW->n4 = (SAINode*)(size_t)(N.n4 ? N.n4->idx : InvalidNode); + NEW->Plane.build(vOffs, vNorm); + D.set(0, 1, 0); + N.Plane.intersectRayPoint(N.Pos, D, NEW->Pos); // "project" position + smoothed.push_back(NEW); + } + else + { + // create _new node + SAINode *NEW = xr_new(N); +#pragma TODO("TSMP: seems wrong to cast 32 bit value to 64 bit pointer (on x64)") + NEW->n1 = (SAINode*)(size_t)(N.n1 ? N.n1->idx : InvalidNode); + NEW->n2 = (SAINode*)(size_t)(N.n2 ? N.n2->idx : InvalidNode); + NEW->n3 = (SAINode*)(size_t)(N.n3 ? N.n3->idx : InvalidNode); + NEW->n4 = (SAINode*)(size_t)(N.n4 ? N.n4->idx : InvalidNode); + smoothed.push_back(NEW); + } + + int k = it - m_Nodes.begin(); + if (k % 128 == 0) + { + pb->Update(static_cast(k)); + if (UI->NeedAbort()) + break; + } + } + UI->ProgressEnd(pb); + Clear(true); + m_Nodes = smoothed; + DenumerateNodes(); + hash_FillFromNodes(); + + UpdateHLSelected(); + + if (sm_nodes) + Scene->UndoSave(); +} diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_MotionSimulator.cpp b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_MotionSimulator.cpp new file mode 100644 index 00000000000..a46e086caa6 --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_MotionSimulator.cpp @@ -0,0 +1,617 @@ +#include "stdafx.h" + +struct cl_tri +{ + Fvector e10; + float e10s; + Fvector e21; + float e21s; + Fvector e02; + float e02s; + Fvector p[3]; + Fvector N; + float d; +}; +struct SCollisionData +{ + // data about player movement + Fvector vVelocity; + Fvector vSourcePoint; + + // for error handling + Fvector vLastSafePosition; + BOOL bStuck; + + // data for collision response + bool bFoundCollision; + float fNearestDistance; // nearest distance to hit + Fvector vNearestIntersectionPoint; // on sphere + Fvector vNearestPolygonIntersectionPoint; // on polygon + + Fvector vRadius; +}; +DEF_VECTOR(vecTris, cl_tri); + +static int psCollideActDepth = 8; +static int psCollideActStuckDepth = 16; +static float cl_epsilon = EPS_L; +static vecTris clContactedT; + +// ---------------------------------------------------------------------- +// Name : classifyPoint() +// Input : point - point we wish to classify +// pO - Origin of plane +// pN - Normal to plane +// Notes : +// Return: One of 3 classification codes +// ----------------------------------------------------------------------- +IC float classifyPoint(const Fvector &point, const Fvector &planeO, const Fvector &planeN) +{ + Fvector dir; + dir.sub(point, planeO); + return dir.dotproduct(planeN); +} +// ---------------------------------------------------------------------- +// Name : intersectRayPlane() +// Input : rOrigin - origin of ray in world space +// rVector - vector describing direction of ray in world space +// pOrigin - Origin of plane +// pNormal - Normal to plane +// Notes : Normalized directional vectors expected +// Return: distance to plane in world units, -1 if no intersection. +// ----------------------------------------------------------------------- +IC float intersectRayPlane(const Fvector &rayOrigin, const Fvector &rayDirection, + const Fvector &planeOrigin, const Fvector &planeNormal) +{ + float numer = classifyPoint(rayOrigin, planeOrigin, planeNormal); + float denom = planeNormal.dotproduct(rayDirection); + + if (denom == 0) // normal is orthogonal to vector, cant intersect + return (-1.0f); + + return -(numer / denom); +} +// ---------------------------------------------------------------------- +// Name : closestPointOnLine() +// Input : a - first end of line segment +// b - second end of line segment +// p - point we wish to find closest point on line from +// Notes : Helper function for closestPointOnTriangle() +// Return: closest point on line segment +// ----------------------------------------------------------------------- + +IC void closestPointOnLine(Fvector &res, const Fvector &a, const Fvector &b, const Fvector &p) +{ + + // Determine t (the length of the vector from a to p) + Fvector c; + c.sub(p, a); + Fvector V; + V.sub(b, a); + + float d = V.magnitude(); + + V.div(d); + float t = V.dotproduct(c); + + // Check to see if t is beyond the extents of the line segment + if (t <= 0.0f) + { + res.set(a); + return; + } + if (t >= d) + { + res.set(b); + return; + } + + // Return the point between a and b + // set length of V to t. V is normalized so this is easy + res.mad(a, V, t); +} +IC void closestPointOnEdge(Fvector &res, // result + const Fvector &a, const Fvector &b, // points + const Fvector &ED, float elen, // edge direction (b-a) and length + const Fvector &P) // query point +{ + // Determine t (the length of the vector from a to p) + Fvector c; + c.sub(P, a); + float t = ED.dotproduct(c); + + // Check to see if t is beyond the extents of the line segment + if (t <= 0.0f) + { + res.set(a); + return; + } + if (t >= elen) + { + res.set(b); + return; + } + + // Return the point between a and b + res.mad(a, ED, t); +} + +// ---------------------------------------------------------------------- +// Name : closestPointOnTriangle() +// p - point we wish to find closest point on triangle from +// Return: closest point on line triangle edge +// ----------------------------------------------------------------------- + +IC void closestPointOnTriangle(Fvector &result, const Fvector *V, const Fvector &p) +{ + Fvector Rab; + closestPointOnLine(Rab, V[0], V[1], p); + float dAB = p.distance_to_sqr(Rab); + Fvector Rbc; + closestPointOnLine(Rbc, V[1], V[2], p); + float dBC = p.distance_to_sqr(Rbc); + Fvector Rca; + closestPointOnLine(Rca, V[2], V[0], p); + float dCA = p.distance_to_sqr(Rca); + + float min = dAB; + result.set(Rab); + if (dBC < min) + { + min = dBC; + result.set(Rbc); + } + if (dCA < min) + result.set(Rca); +} +IC void closestPointOnTriangle(Fvector &result, const cl_tri &T, const Fvector &P) +{ + Fvector Rab; + closestPointOnEdge(Rab, T.p[0], T.p[1], T.e10, T.e10s, P); + float dAB = P.distance_to_sqr(Rab); + Fvector Rbc; + closestPointOnEdge(Rbc, T.p[1], T.p[2], T.e21, T.e21s, P); + float dBC = P.distance_to_sqr(Rbc); + Fvector Rca; + closestPointOnEdge(Rca, T.p[2], T.p[0], T.e02, T.e02s, P); + float dCA = P.distance_to_sqr(Rca); + + float min; + if (dBC < dAB) + { + min = dBC; + result.set(Rbc); + } + else + { + min = dAB; + result.set(Rab); + } + if (dCA < min) + result.set(Rca); +} + +// ---------------------------------------------------------------------- +// Name : intersectRaySphere() +// Input : rO - origin of ray in world space +// rV - vector describing direction of ray in world space +// sO - Origin of sphere +// sR - radius of sphere +// Notes : Normalized directional vectors expected +// Return: distance to sphere in world units, -1 if no intersection. +// ----------------------------------------------------------------------- + +IC float intersectRaySphere(const Fvector &rO, const Fvector &rV, const Fvector &sO, float sR) +{ + Fvector Q; + Q.sub(sO, rO); + + float c = Q.magnitude(); + float v = Q.dotproduct(rV); + float d = sR * sR - (c * c - v * v); + + // If there was no intersection, return -1 + if (d < 0.0) + return (-1.0f); + + // Return the distance to the [first] intersecting point + return (v - _sqrt(d)); +} +IC float intersectRayIdentitySphere(const Fvector &rO, const Fvector &rV) +{ + Fvector Q; + Q.invert(rO); + + float c = Q.magnitude(); + float v = Q.dotproduct(rV); + float d = 1 - (c * c - v * v); + + // If there was no intersection, return -1 + if (d < 0.0) + return (-1.0f); + + // Return the distance to the [first] intersecting point + return (v - _sqrt(d)); +} +// ---------------------------------------------------------------------- +// Name : CheckPointInSphere() +// Input : point - point we wish to check for inclusion +// sO - Origin of sphere +// sR - radius of sphere +// Notes : +// Return: TRUE if point is in sphere, FALSE if not. +// ----------------------------------------------------------------------- +IC bool CheckPointInSphere(const Fvector &point, const Fvector &sO, float sR) +{ + return (sO.distance_to_sqr(point) < sR * sR); +} +IC bool CheckPointInIdentitySphere(const Fvector &point) +{ + return (point.square_magnitude() <= 1); +} +// ----------------------------------------------------------------------- +extern CStatTimer g_tm; + +void msimulator_CheckCollision(SCollisionData &cl) +{ + // from package + Fvector source; + Fvector velocity; + source.set(cl.vSourcePoint); + velocity.set(cl.vVelocity); + + // keep a copy of this as it's needed a few times + Fvector normalizedVelocity; + normalizedVelocity.normalize_safe(cl.vVelocity); + + // intersection data + Fvector sIPoint; // sphere intersection point + Fvector pIPoint; // plane intersection point + Fvector polyIPoint; // polygon intersection point + + // how long is our velocity + float distanceToTravel = velocity.magnitude(); + + float distToPlaneIntersection; + float distToEllipsoidIntersection; + + for (DWORD i_t = 0; i_t != clContactedT.size(); i_t++) + { + cl_tri &T = clContactedT[i_t]; + + // ignore backfaces. What we cannot see we cannot collide with ;) + if (T.N.dotproduct(normalizedVelocity) < 0.0f) + { + // calculate sphere intersection point (in future :) + // OLES: 'cause our radius has unit length, this point lies exactly on sphere + sIPoint.sub(source, T.N); + + // find the plane intersection point + // classify point to determine if ellipsoid span the plane + BOOL bInsideTri; + if ((sIPoint.dotproduct(T.N) + T.d) < -EPS_S) + { + // plane is embedded in ellipsoid / sphere + // find plane intersection point by shooting a ray from the + // sphere intersection point along the planes normal. + bInsideTri = ETOOLS::TestRayTri2(sIPoint, T.N, T.p, distToPlaneIntersection); + + // calculate plane intersection point + pIPoint.mad(sIPoint, T.N, distToPlaneIntersection); + } + else + { + // shoot ray along the velocity vector + bInsideTri = ETOOLS::TestRayTri2(sIPoint, normalizedVelocity, T.p, distToPlaneIntersection); + + // calculate plane intersection point + pIPoint.mad(sIPoint, normalizedVelocity, distToPlaneIntersection); + } + + // find polygon intersection point. By default we assume its equal to the + // plane intersection point + + polyIPoint.set(pIPoint); + distToEllipsoidIntersection = distToPlaneIntersection; + + if (!bInsideTri) + { + // if not in triangle + closestPointOnTriangle(polyIPoint, T, pIPoint); + + Fvector _normalizedVelocity; + _normalizedVelocity.invert(normalizedVelocity); + distToEllipsoidIntersection = intersectRaySphere(polyIPoint, _normalizedVelocity, source, 1.0f); + + if (distToEllipsoidIntersection >= 0) + { + // calculate true sphere intersection point + sIPoint.mad(polyIPoint, normalizedVelocity, -distToEllipsoidIntersection); + } + } + + // Here we do the error checking to see if we got ourself stuck last frame + if (CheckPointInSphere(polyIPoint, source, 1.0f)) + { + cl.bStuck = TRUE; + } + + // Ok, now we might update the collision data if we hit something + if ((distToEllipsoidIntersection >= 0) && (distToEllipsoidIntersection <= distanceToTravel)) + { + if ((cl.bFoundCollision == FALSE) || (distToEllipsoidIntersection < cl.fNearestDistance)) + { + // if we are hit we have a closest hit so far. We save the information + cl.fNearestDistance = distToEllipsoidIntersection; + cl.vNearestIntersectionPoint.set(sIPoint); + cl.vNearestPolygonIntersectionPoint.set(polyIPoint); + cl.bFoundCollision = TRUE; + } + } + } // if not backface + } // for all faces +} +//----------------------------------------------------------------------------- +void msimulator_ResolveStuck(SCollisionData &cl, Fvector &position) +{ + // intersection data + Fvector polyIPoint; // polygon intersection point + Fvector stuckDir; + int stuckCount; + + float dist; + float safe_R = 1.f + EPS_L * 2; // psSqueezeVelocity*EDevice.fTimeDelta; + + for (int passes = 0; passes < psCollideActStuckDepth; passes++) + { + // initialize + stuckDir.set(0, 0, 0); + stuckCount = 0; + + // for all faces + for (DWORD i_t = 0; i_t != clContactedT.size(); i_t++) + { + cl_tri &T = clContactedT[i_t]; + Fvector N_inv; + N_inv.invert(T.N); + + // find plane intersection point by shooting a ray from the + // sphere intersection point along the planes normal. + if (CDB::TestRayTri2(position, N_inv, T.p, dist)) + { + // calculate plane intersection point + polyIPoint.mad(position, N_inv, dist); + } + else + { + // calculate plane intersection point + Fvector tmp; + tmp.mad(position, N_inv, dist); + closestPointOnTriangle(polyIPoint, T, tmp); + } + if (CheckPointInSphere(polyIPoint, position, safe_R)) + { + Fvector dir; + dir.sub(position, polyIPoint); + float len = dir.magnitude(); + dir.mul((safe_R - len) / len); + stuckDir.add(dir); + stuckCount++; + } + } + + if (stuckCount) + { + stuckDir.div(float(stuckCount)); + position.add(stuckDir); + if (stuckDir.magnitude() < EPS) + break; + } + else + break; + } +} + +//----------------------------------------------------------------------------- +// Name: collideWithWorld() +// Desc: Recursive part of the collision response. This function is the +// one who actually calls the collision check on the meshes +//----------------------------------------------------------------------------- +Fvector msimulator_CollideWithWorld(SCollisionData &cl, Fvector position, Fvector velocity, WORD cnt) +{ + // + msimulator_ResolveStuck(cl, position); + + // do we need to worry ? + // if (fsimilar(position.x,target.x,EPS_L)&&fsimilar(position.z,target.z,EPS_L)) + if (velocity.magnitude() < EPS_L) + { + cl.vVelocity.set(0, 0, 0); + return position; + } + if (cnt > psCollideActDepth) + return cl.vLastSafePosition; + + Fvector ret_pos; + Fvector destinationPoint; + destinationPoint.add(position, velocity); + + // reset the collision package we send to the mesh + cl.vVelocity.set(velocity); + cl.vSourcePoint.set(position); + cl.bFoundCollision = FALSE; + cl.bStuck = FALSE; + cl.fNearestDistance = -1; + + // Check collision + msimulator_CheckCollision(cl); + + // check return value here, and possibly call recursively + if (cl.bFoundCollision == FALSE && !cl.bStuck) + { + // if no collision move very close to the desired destination. + float l = velocity.magnitude(); + Fvector V; + V.mul(velocity, (l - cl_epsilon) / l); + + // return the final position + ret_pos.add(position, V); + + // update the last safe position for future error recovery + cl.vLastSafePosition.set(ret_pos); + return ret_pos; + } + else + { + // There was a collision + // OK, first task is to move close to where we hit something : + Fvector newSourcePoint; + + // If we are stuck, we just back up to last safe position + if (cl.bStuck) + { + return cl.vLastSafePosition; + } + + // only update if we are not already very close + if (cl.fNearestDistance >= cl_epsilon) + { + Fvector V; + V.set(velocity); + V.set_length(cl.fNearestDistance - cl_epsilon); + newSourcePoint.add(cl.vSourcePoint, V); + } + else + { + newSourcePoint.set(cl.vSourcePoint); + } + + // Now we must calculate the sliding plane + Fvector slidePlaneOrigin; + slidePlaneOrigin.set(cl.vNearestPolygonIntersectionPoint); + Fvector slidePlaneNormal; + slidePlaneNormal.sub(newSourcePoint, cl.vNearestPolygonIntersectionPoint); + + // We now project the destination point onto the sliding plane + float l = intersectRayPlane(destinationPoint, slidePlaneNormal, slidePlaneOrigin, slidePlaneNormal); + + // We can now calculate a _new destination point on the sliding plane + Fvector newDestinationPoint; + newDestinationPoint.mad(destinationPoint, slidePlaneNormal, l); + + // Generate the slide vector, which will become our _new velocity vector + // for the next iteration + Fvector newVelocityVector; + newVelocityVector.sub(newDestinationPoint, cl.vNearestPolygonIntersectionPoint); + + // now we recursively call the function with the _new position and velocity + cl.vLastSafePosition.set(position); + return msimulator_CollideWithWorld(cl, newSourcePoint, newVelocityVector, u16(cnt + 1)); + } +} + +IC void create_bb(Fbox &B, Fvector &P, float r, float h) +{ + B.set(P.x - r, P.y, P.z - r, P.x + r, P.y + h, P.z + r); +} +void ESceneAIMapTool::MotionSimulate(Fvector &result, Fvector &start, Fvector &end, float _radius, float _height) +{ + SCollisionData cl_data; + float half_height = _height / 2; + + // Calc BB + Fbox b1, b2, bb; + create_bb(b1, start, _radius, _height); + create_bb(b2, end, _radius, _height); + bb.merge(b1, b2); + bb.grow(0.05f); + + // Collision query + Fvector bbC, bbD; + bb.get_CD(bbC, bbD); + static SPickQuery PQ; + if (m_CFModel) + Scene->BoxQuery(PQ, bb, CDB::OPT_FULL_TEST, m_CFModel); + else + Scene->BoxQuery(PQ, bb, CDB::OPT_FULL_TEST, GetSnapList()); + + // XForm everything to ellipsoid space + Fvector xf; + xf.set(1 / _radius, 1 / half_height, 1 / _radius); + + Fvector Lposition; + Lposition.set(start); + Lposition.y += half_height; + Lposition.mul(xf); + + Fvector target; + target.set(end); + target.y += half_height; + target.mul(xf); + + Fvector Lvelocity; + Lvelocity.sub(end, start); + Lvelocity.mul(xf); + + cl_data.vLastSafePosition.set(Lposition); + + // Get the data for the triangles in question and scale to ellipsoid space + int tri_count = PQ.r_count(); + clContactedT.clear(); + //. clContactedT.resize (tri_count); + + if (tri_count) + { + Fvector vel_dir; + vel_dir.normalize_safe(Lvelocity); + for (int i_t = 0; i_t < tri_count; i_t++) + { + SPickQuery::SResult *R = PQ.r_begin() + i_t; + if (R->e_obj && R->e_mesh) + { + CSurface *surf = R->e_mesh->GetSurfaceByFaceID(R->tag); + //. SGameMtl* mtl = GMLib.GetMaterialByID(surf->_GameMtl()); + //. if (mtl->Flags.is(SGameMtl::flPassable))continue; + Shader_xrLC *c_sh = EDevice.ShaderXRLC.Get(surf->_ShaderXRLCName()); + if (!c_sh->flags.bCollision) + continue; + } + clContactedT.push_back(cl_tri()); + cl_tri &T = clContactedT.back(); + Fvector *V = R->verts; + + T.p[0].mul(V[0], xf); + T.p[1].mul(V[1], xf); + T.p[2].mul(V[2], xf); + T.N.mknormal(T.p[0], T.p[1], T.p[2]); + + T.d = -T.N.dotproduct(T.p[0]); + T.e10.sub(T.p[1], T.p[0]); + T.e10s = T.e10.magnitude(); + T.e10.div(T.e10s); + T.e21.sub(T.p[2], T.p[1]); + T.e21s = T.e21.magnitude(); + T.e21.div(T.e21s); + T.e02.sub(T.p[0], T.p[2]); + T.e02s = T.e02.magnitude(); + T.e02.div(T.e02s); + } + } + + // call the recursive collision response function + Fvector POS; + + for (int i = 0; i < 3; i++) + { + POS.set(msimulator_CollideWithWorld(cl_data, Lposition, Lvelocity, 0)); + if (fsimilar(POS.x, target.x) && fsimilar(POS.z, target.z)) + break; + + Lposition.set(POS); + Lvelocity.sub(target, POS); + Lvelocity.y = 0; + } + + result.div(POS, xf); + result.y -= half_height; +} diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Pick.cpp b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Pick.cpp new file mode 100644 index 00000000000..4cf1c083947 --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Pick.cpp @@ -0,0 +1,117 @@ +#include "stdafx.h" + +SAINode *ESceneAIMapTool::PickNode(const Fvector &start, const Fvector &dir, float &dist) +{ + SAINode *R = 0; + CFrustum frustum; + LUI->m_CurrentCp.add(1); // fake add min vaalue for calculate frustum + float psz = (m_Params.fPatchSize / 2) * (m_Params.fPatchSize / 2); + if (LUI->SelectionFrustum(frustum)) + { + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + { + SAINode &N = **it; + u32 mask = 0xffff; + Fbox bb; + bb.set(N.Pos, N.Pos); + bb.vMin.sub(m_Params.fPatchSize * 0.35f); + bb.vMax.add(m_Params.fPatchSize * 0.35f); + if (frustum.testSAABB(N.Pos, m_Params.fPatchSize, bb.data(), mask)) + { + Fvector dest; + if (N.Plane.intersectRayPoint(start, dir, dest)) + { + if (N.Pos.distance_to_sqr(dest) < psz) + { + float d = start.distance_to(dest); + if (d < dist) + { + R = &N; + dist = d; + } + } + } + } + } + } + return R; +} +bool ESceneAIMapTool::PickObjects(Fvector &dest, const Fvector &start, const Fvector &dir, float dist) +{ + SPickQuery PQ; + if (!GetSnapList()->empty()) + { + if (Scene->RayQuery(PQ, start, dir, dist, CDB::OPT_ONLYNEAREST | CDB::OPT_CULL, GetSnapList())) + { + dest.mad(start, dir, PQ.r_begin()->range); + return true; + } + } + else + { + ELog.DlgMsg(mtInformation, "Fill object list and try again."); + } + return false; +} + +int ESceneAIMapTool::RaySelect(int flag, float &distance, const Fvector &start, const Fvector &direction, BOOL bDistanceOnly) +{ + int count = 0; + if (!m_Flags.is(flHideNodes)) + { + switch (LTools->GetSubTarget()) + { + case estAIMapNode: + { + SAINode *N = PickNode(start, direction, distance); + if (N && !bDistanceOnly) + { + if (flag == -1) + N->flags.invert(SAINode::flSelected); + N->flags.set(SAINode::flSelected, flag); + count++; + } + } + break; + } + UpdateHLSelected(); + UI->RedrawScene(); + } + return count; +} + +int ESceneAIMapTool::FrustumSelect(int flag, const CFrustum &frustum) +{ + int count = 0; + if (!m_Flags.is(flHideNodes)) + { + switch (LTools->GetSubTarget()) + { + case estAIMapNode: + { + for (AINodeIt it = m_Nodes.begin(); it != m_Nodes.end(); it++) + { + SAINode &N = **it; + u32 mask = 0xffff; + Fbox bb; + bb.set(N.Pos, N.Pos); + bb.vMin.sub(m_Params.fPatchSize * 0.35f); + bb.vMax.add(m_Params.fPatchSize * 0.35f); + if (frustum.testSAABB(N.Pos, m_Params.fPatchSize, bb.data(), mask)) + { + if (-1 == flag) + (*it)->flags.invert(SAINode::flSelected); + else + (*it)->flags.set(SAINode::flSelected, flag); + count++; + } + } + } + break; + } + + UpdateHLSelected(); + UI->RedrawScene(); + } + return count; +} diff --git a/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Render.cpp b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Render.cpp new file mode 100644 index 00000000000..4fb817b5b0f --- /dev/null +++ b/src/editors/LevelEditor/Tools/AIMap/ESceneAIMapTools_Render.cpp @@ -0,0 +1,172 @@ +#include "stdafx.h" + +typedef Fvector2 t_node_tc[4]; +static const float dtc = 0.25f; + +static t_node_tc node_tc[16] = + { + {{0.f + 0 * dtc, 0.25f + 0 * dtc}, {0.25f + 0 * dtc, 0.25f + 0 * dtc}, {0.25f + 0 * dtc, 0.f + 0 * dtc}, {0.f + 0 * dtc, 0.f + 0 * dtc}}, + {{0.f + 1 * dtc, 0.25f + 0 * dtc}, {0.25f + 1 * dtc, 0.25f + 0 * dtc}, {0.25f + 1 * dtc, 0.f + 0 * dtc}, {0.f + 1 * dtc, 0.f + 0 * dtc}}, + {{0.f + 2 * dtc, 0.25f + 0 * dtc}, {0.25f + 2 * dtc, 0.25f + 0 * dtc}, {0.25f + 2 * dtc, 0.f + 0 * dtc}, {0.f + 2 * dtc, 0.f + 0 * dtc}}, + {{0.f + 3 * dtc, 0.25f + 0 * dtc}, {0.25f + 3 * dtc, 0.25f + 0 * dtc}, {0.25f + 3 * dtc, 0.f + 0 * dtc}, {0.f + 3 * dtc, 0.f + 0 * dtc}}, + + {{0.f + 0 * dtc, 0.25f + 1 * dtc}, {0.25f + 0 * dtc, 0.25f + 1 * dtc}, {0.25f + 0 * dtc, 0.f + 1 * dtc}, {0.f + 0 * dtc, 0.f + 1 * dtc}}, + {{0.f + 1 * dtc, 0.25f + 1 * dtc}, {0.25f + 1 * dtc, 0.25f + 1 * dtc}, {0.25f + 1 * dtc, 0.f + 1 * dtc}, {0.f + 1 * dtc, 0.f + 1 * dtc}}, + {{0.f + 2 * dtc, 0.25f + 1 * dtc}, {0.25f + 2 * dtc, 0.25f + 1 * dtc}, {0.25f + 2 * dtc, 0.f + 1 * dtc}, {0.f + 2 * dtc, 0.f + 1 * dtc}}, + {{0.f + 3 * dtc, 0.25f + 1 * dtc}, {0.25f + 3 * dtc, 0.25f + 1 * dtc}, {0.25f + 3 * dtc, 0.f + 1 * dtc}, {0.f + 3 * dtc, 0.f + 1 * dtc}}, + + {{0.f + 0 * dtc, 0.25f + 2 * dtc}, {0.25f + 0 * dtc, 0.25f + 2 * dtc}, {0.25f + 0 * dtc, 0.f + 2 * dtc}, {0.f + 0 * dtc, 0.f + 2 * dtc}}, + {{0.f + 1 * dtc, 0.25f + 2 * dtc}, {0.25f + 1 * dtc, 0.25f + 2 * dtc}, {0.25f + 1 * dtc, 0.f + 2 * dtc}, {0.f + 1 * dtc, 0.f + 2 * dtc}}, + {{0.f + 2 * dtc, 0.25f + 2 * dtc}, {0.25f + 2 * dtc, 0.25f + 2 * dtc}, {0.25f + 2 * dtc, 0.f + 2 * dtc}, {0.f + 2 * dtc, 0.f + 2 * dtc}}, + {{0.f + 3 * dtc, 0.25f + 2 * dtc}, {0.25f + 3 * dtc, 0.25f + 2 * dtc}, {0.25f + 3 * dtc, 0.f + 2 * dtc}, {0.f + 3 * dtc, 0.f + 2 * dtc}}, + + {{0.f + 0 * dtc, 0.25f + 3 * dtc}, {0.25f + 0 * dtc, 0.25f + 3 * dtc}, {0.25f + 0 * dtc, 0.f + 3 * dtc}, {0.f + 0 * dtc, 0.f + 3 * dtc}}, + {{0.f + 1 * dtc, 0.25f + 3 * dtc}, {0.25f + 1 * dtc, 0.25f + 3 * dtc}, {0.25f + 1 * dtc, 0.f + 3 * dtc}, {0.f + 1 * dtc, 0.f + 3 * dtc}}, + {{0.f + 2 * dtc, 0.25f + 3 * dtc}, {0.25f + 2 * dtc, 0.25f + 3 * dtc}, {0.25f + 2 * dtc, 0.f + 3 * dtc}, {0.f + 2 * dtc, 0.f + 3 * dtc}}, + {{0.f + 3 * dtc, 0.25f + 3 * dtc}, {0.25f + 3 * dtc, 0.25f + 3 * dtc}, {0.25f + 3 * dtc, 0.f + 3 * dtc}, {0.f + 3 * dtc, 0.f + 3 * dtc}}, +}; + +void ESceneAIMapTool::OnDeviceCreate() +{ + m_Shader.create("editor\\ai_node", "ed\\ed_ai_arrows_01"); + m_RGeom.create(FVF::F_LIT, RImplementation.Vertex.Buffer(), RImplementation.Index.Buffer()); +} + +void ESceneAIMapTool::OnDeviceDestroy() +{ + m_Shader.destroy(); + m_RGeom.destroy(); +} + +BOOL ai_map_shown = TRUE; +static const u32 block_size = 0x2000; + +void ESceneAIMapTool::OnRender(int priority, bool strictB2F) +{ + if (m_Flags.is(flHideNodes) || !ai_map_shown) + return; + if (1 == priority) + { + if (false == strictB2F) + { + RCache.set_xform_world(Fidentity); + if (OBJCLASS_AIMAP == LTools->CurrentClassID()) + { + u32 clr = 0xffffc000; + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawSelectionBoxB(m_AIBBox, &clr); + } + if (Valid()) + { + // render nodes + EDevice.SetShader(m_Shader); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_NONE); + Irect rect; + HashRect(EDevice.m_Camera.GetPosition(), m_VisRadius, rect); + + u32 vBase; + _VertexStream* Stream = &RImplementation.Vertex; + FVF::LIT *pv = (FVF::LIT *)Stream->Lock(block_size, m_RGeom->vb_stride, vBase); + u32 cnt = 0; + // EDevice.Statistic.TEST0.Begin(); + // EDevice.Statistic.TEST2.Begin(); + for (int x = rect.x1; x <= rect.x2; x++) + { + for (int z = rect.y1; z <= rect.y2; z++) + { + AINodeVec *nodes = HashMap(x, z); + if (nodes) + { + const Fvector DUP = {0, 1, 0}; + const float st = (m_Params.fPatchSize * 0.9f) * 0.5f; + for (AINodeIt it = nodes->begin(); it != nodes->end(); it++) + { + SAINode &N = **it; + + Fvector v; + v.set(N.Pos.x - st, N.Pos.y, N.Pos.z - st); + float p_denom = N.Plane.n.dotproduct(DUP); + float b = (_abs(p_denom) < EPS_S) ? m_Params.fPatchSize : _abs(N.Plane.classify(v) / p_denom); + + if (Render->ViewBase.testSphere_dirty(N.Pos, _max(b, st))) + { + u32 clr; + if (N.flags.is(SAINode::flSelected)) + clr = 0xffffffff; + else + clr = N.flags.is(SAINode::flHLSelected) ? 0xff909090 : 0xff606060; + int k = 0; + if (N.n1) + k |= 1 << 0; + if (N.n2) + k |= 1 << 1; + if (N.n3) + k |= 1 << 2; + if (N.n4) + k |= 1 << 3; + Fvector v; + FVF::LIT v1, v2, v3, v4; + float tt = 0.01f; + v.set(N.Pos.x - st, N.Pos.y, N.Pos.z - st); + N.Plane.intersectRayPoint(v, DUP, v1.p); + v1.p.mad(v1.p, N.Plane.n, tt); + v1.t.set(node_tc[k][0]); + v1.color = clr; // minX,minZ + v.set(N.Pos.x + st, N.Pos.y, N.Pos.z - st); + N.Plane.intersectRayPoint(v, DUP, v2.p); + v2.p.mad(v2.p, N.Plane.n, tt); + v2.t.set(node_tc[k][1]); + v2.color = clr; // maxX,minZ + v.set(N.Pos.x + st, N.Pos.y, N.Pos.z + st); + N.Plane.intersectRayPoint(v, DUP, v3.p); + v3.p.mad(v3.p, N.Plane.n, tt); + v3.t.set(node_tc[k][2]); + v3.color = clr; // maxX,maxZ + v.set(N.Pos.x - st, N.Pos.y, N.Pos.z + st); + N.Plane.intersectRayPoint(v, DUP, v4.p); + v4.p.mad(v4.p, N.Plane.n, tt); + v4.t.set(node_tc[k][3]); + v4.color = clr; // minX,maxZ + pv->set(v3); + pv++; + pv->set(v2); + pv++; + pv->set(v1); + pv++; + pv->set(v1); + pv++; + pv->set(v4); + pv++; + pv->set(v3); + pv++; + cnt += 6; + if (cnt >= block_size - 6) + { + Stream->Unlock(cnt, m_RGeom->vb_stride); + EDevice.DP(D3DPT_TRIANGLELIST, m_RGeom, vBase, cnt / 3); + pv = (FVF::LIT *)Stream->Lock(block_size, m_RGeom->vb_stride, vBase); + cnt = 0; + } + } + } + } + } + } + // EDevice.Statistic.TEST2.End(); + // EDevice.Statistic.TEST0.End(); + Stream->Unlock(cnt, m_RGeom->vb_stride); + if (cnt) + EDevice.DP(D3DPT_TRIANGLELIST, m_RGeom, vBase, cnt / 3); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_CCW); + } + } + else + { +/* // render snap + if (m_Flags.is(flDrawSnapObjects)) + for(ObjectIt _F=m_SnapObjects.begin();_F!=m_SnapObjects.end();_F++) + if((*_F)->Visible()) ((CSceneObject*)(*_F))->RenderSelection(0x4046B646); +*/ } + } +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Tools/Base/ESceneControlsCustom.cpp b/src/editors/LevelEditor/Tools/Base/ESceneControlsCustom.cpp new file mode 100644 index 00000000000..9c435ed85e7 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Base/ESceneControlsCustom.cpp @@ -0,0 +1,453 @@ +#include "stdafx.h" + +void IR_GetMousePosScreen(Ivector2& p) +{ + GetCursorPos((LPPOINT)&p); +} + +void IR_GetMousePosReal(HWND hwnd, Ivector2& p) +{ + IR_GetMousePosScreen(p); + if (hwnd) + ScreenToClient(hwnd, (LPPOINT)&p); +} + +TUI_CustomControl::TUI_CustomControl(int st, int act, ESceneToolBase *parent) +{ + parent_tool = parent; + VERIFY(parent); + sub_target = st; + action = act; + bBoxSelection = false; +} + +bool TUI_CustomControl::Start(TShiftState _Shift) +{ + switch (action) + { + case etaSelect: + return SelectStart(_Shift); + case etaAdd: + return AddStart(_Shift); + case etaMove: + return MovingStart(_Shift); + case etaRotate: + return RotateStart(_Shift); + case etaScale: + return ScaleStart(_Shift); + } + return false; +} +bool TUI_CustomControl::End(TShiftState _Shift) +{ + switch (action) + { + case etaSelect: + return SelectEnd(_Shift); + case etaAdd: + return AddEnd(_Shift); + case etaMove: + return MovingEnd(_Shift); + case etaRotate: + return RotateEnd(_Shift); + case etaScale: + return ScaleEnd(_Shift); + } + return false; +} +void TUI_CustomControl::Move(TShiftState _Shift) +{ + switch (action) + { + case etaSelect: + SelectProcess(_Shift); + break; + case etaAdd: + AddProcess(_Shift); + break; + case etaMove: + MovingProcess(_Shift); + break; + case etaRotate: + RotateProcess(_Shift); + break; + case etaScale: + ScaleProcess(_Shift); + break; + } +} +bool TUI_CustomControl::HiddenMode() +{ + switch (action) + { + case etaSelect: + return false; + case etaAdd: + return false; + case etaMove: + return true; + case etaRotate: + return true; + case etaScale: + return true; + } + return false; +} + +//------------------------------------------------------------------------------ +// add +//------------------------------------------------------------------------------ +CCustomObject *TUI_CustomControl::DefaultAddObject(TShiftState Shift, TBeforeAppendCallback before, TAfterAppendCallback after) +{ + if (Shift == ssRBOnly) + { + ExecCommand(COMMAND_SHOWCONTEXTMENU, parent_tool->FClassID); + return 0; + } + Fvector p, n; + CCustomObject *obj = 0; + if (LUI->PickGround(p, UI->m_CurrentRStart, UI->m_CurrentRDir, 1, &n)) + { + // before callback + SBeforeAppendCallbackParams P; + if (before && !before(&P)) + return 0; + + string256 namebuffer; + Scene->GenObjectName(parent_tool->FClassID, namebuffer, P.name_prefix.c_str()); + obj = Scene->GetOTool(parent_tool->FClassID)->CreateObject(P.data, namebuffer); + if (!obj->Valid()) + { + xr_delete(obj); + return 0; + } + // after callback + if (after && !after(Shift, obj)) + { + xr_delete(obj); + return 0; + } + obj->MoveTo(p, n); + Scene->SelectObjects(false, parent_tool->FClassID); + Scene->AppendObject(obj); + if (Shift & ssCtrl) + ExecCommand(COMMAND_SHOW_PROPERTIES); + if (!(Shift & ssAlt)) + ResetActionToSelect(); + } + return obj; +} + +bool TUI_CustomControl::AddStart(TShiftState Shift) +{ + DefaultAddObject(Shift, 0); + return false; +} +void TUI_CustomControl::AddProcess(TShiftState _Shift) +{ +} +bool TUI_CustomControl::AddEnd(TShiftState _Shift) +{ + return true; +} + +bool TUI_CustomControl::CheckSnapList(TShiftState Shift) +{ + if (MainForm->GetLeftBarForm()->IsSnapListMode()) + { + CCustomObject *O = Scene->RayPickObject(UI->ZFar(), UI->m_CurrentRStart, UI->m_CurrentRDir, OBJCLASS_SCENEOBJECT, 0, 0); + if (O) + { + if (Scene->FindObjectInSnapList(O)) + { + if (Shift & ssAlt) + { + Scene->DelFromSnapList(O); + } + else if (Shift & ssCtrl) + { + Scene->DelFromSnapList(O); + } + } + else + { + if (!(Shift & (ssCtrl | ssAlt))) + { + Scene->AddToSnapList(O); + } + else if (Shift & ssCtrl) + { + Scene->AddToSnapList(O); + } + } + return true; + } + else + { + return false; + } + } + return false; +} + +//------------------------------------------------------------------------------ +// total select +//------------------------------------------------------------------------------ +bool TUI_CustomControl::SelectStart(TShiftState Shift) +{ + ObjClassID cls = LTools->CurrentClassID(); + + if (CheckSnapList(Shift)) + return false; + if (Shift == ssRBOnly) + { + ExecCommand(COMMAND_SHOWCONTEXTMENU, parent_tool->FClassID); + return false; + } + if (!((Shift & ssCtrl) || (Shift & ssAlt))) + Scene->SelectObjects(false, cls); + + int cnt = Scene->RaySelect((Shift & ssCtrl) ? -1 : (Shift & ssAlt) ? 0 + : 1, + parent_tool->FClassID); + bBoxSelection = ((0 != cnt) && ((Shift & ssCtrl) || (Shift & ssAlt))) || (0 == cnt); + if (bBoxSelection) + { + UI->EnableSelectionRect(true); + UI->UpdateSelectionRect(UI->m_StartCp, UI->m_CurrentCp); + return true; + } + return false; +} + +void TUI_CustomControl::SelectProcess(TShiftState _Shift) +{ + if (bBoxSelection) + UI->UpdateSelectionRect(UI->m_StartCp, UI->m_CurrentCp); +} + +bool TUI_CustomControl::SelectEnd(TShiftState _Shift) +{ + if (bBoxSelection) + { + UI->EnableSelectionRect(false); + bBoxSelection = false; + Scene->FrustumSelect(_Shift & ssAlt ? 0 : 1, LTools->CurrentClassID()); + } + return true; +} + +//------------------------------------------------------------------------------------ +// moving +//------------------------------------------------------------------------------------ +bool TUI_CustomControl::MovingStart(TShiftState Shift) +{ + ObjClassID cls = LTools->CurrentClassID(); + + if (Shift == ssRBOnly) + { + ExecCommand(COMMAND_SHOWCONTEXTMENU, parent_tool->FClassID); + return false; + } + if (Scene->SelectionCount(true, cls) == 0) + return false; + + if (Shift & ssCtrl) + { + ObjectList lst; + if (Scene->GetQueryObjects(lst, LTools->CurrentClassID(), 1, 1, 0)) + { + if (lst.size() == 1) + { + Fvector p, n; + IR_GetMousePosReal(EDevice.m_hWnd, UI->m_CurrentCp); + EDevice.m_Camera.MouseRayFromPoint(UI->m_CurrentRStart, UI->m_CurrentRDir, UI->m_CurrentCp); + if (LUI->PickGround(p, UI->m_CurrentRStart, UI->m_CurrentRDir, 1, &n)) + { + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + (*_F)->MoveTo(p, n); + Scene->UndoSave(); + } + } + else + { + Fvector p, n; + Fvector D = {0, -1, 0}; + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + { + if (LUI->PickGround(p, (*_F)->GetPosition(), D, 1, &n)) + { + (*_F)->MoveTo(p, n); + } + } + } + } + return false; + } + else + { + if (etAxisY == Tools->GetAxis()) + { + m_MovingXVector.set(0, 0, 0); + m_MovingYVector.set(0, 1, 0); + } + else + { + m_MovingXVector.set(EDevice.m_Camera.GetRight()); + m_MovingXVector.y = 0; + m_MovingYVector.set(EDevice.m_Camera.GetDirection()); + m_MovingYVector.y = 0; + m_MovingXVector.normalize_safe(); + m_MovingYVector.normalize_safe(); + } + m_MovingReminder.set(0, 0, 0); + } + return true; +} + +bool TUI_CustomControl::DefaultMovingProcess(TShiftState Shift, Fvector &amount) +{ + if ((Shift & ssLeft) || (Shift & ssRight)) + { + amount.mul(m_MovingXVector, UI->m_MouseSM * UI->m_DeltaCpH.x); + amount.mad(amount, m_MovingYVector, -UI->m_MouseSM * UI->m_DeltaCpH.y); + + if (Tools->GetSettings(etfMSnap)) + { + CHECK_SNAP(m_MovingReminder.x, amount.x, Tools->m_MoveSnap); + CHECK_SNAP(m_MovingReminder.y, amount.y, Tools->m_MoveSnap); + CHECK_SNAP(m_MovingReminder.z, amount.z, Tools->m_MoveSnap); + } + + if (!(etAxisX == Tools->GetAxis()) && !(etAxisZX == Tools->GetAxis())) + amount.x = 0.f; + if (!(etAxisZ == Tools->GetAxis()) && !(etAxisZX == Tools->GetAxis())) + amount.z = 0.f; + if (!(etAxisY == Tools->GetAxis())) + amount.y = 0.f; + + return (amount.square_magnitude() > EPS_S); + } + return false; +} + +void TUI_CustomControl::MovingProcess(TShiftState _Shift) +{ + Fvector amount; + if (DefaultMovingProcess(_Shift, amount)) + { + ObjectList lst; + if (Scene->GetQueryObjects(lst, LTools->CurrentClassID(), 1, 1, 0)) + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + (*_F)->Move(amount); + } +} + +bool TUI_CustomControl::MovingEnd(TShiftState _Shift) +{ + Scene->UndoSave(); + return true; +} + +//------------------------------------------------------------------------------------ +// rotate +//------------------------------------------------------------------------------------ +bool TUI_CustomControl::RotateStart(TShiftState Shift) +{ + ObjClassID cls = LTools->CurrentClassID(); + + if (Shift == ssRBOnly) + { + ExecCommand(COMMAND_SHOWCONTEXTMENU, parent_tool->FClassID); + return false; + } + if (Scene->SelectionCount(true, cls) == 0) + return false; + + m_RotateVector.set(0, 0, 0); + if (etAxisX == Tools->GetAxis()) + m_RotateVector.set(1, 0, 0); + else if (etAxisY == Tools->GetAxis()) + m_RotateVector.set(0, 1, 0); + else if (etAxisZ == Tools->GetAxis()) + m_RotateVector.set(0, 0, 1); + m_fRotateSnapAngle = 0; + return true; +} + +void TUI_CustomControl::RotateProcess(TShiftState _Shift) +{ + if (_Shift & ssLeft) + { + float amount = -UI->m_DeltaCpH.x * UI->m_MouseSR; + + if (Tools->GetSettings(etfASnap)) + CHECK_SNAP(m_fRotateSnapAngle, amount, Tools->m_RotateSnapAngle); + + ObjectList lst; + if (Scene->GetQueryObjects(lst, LTools->CurrentClassID(), 1, 1, 0)) + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + if (Tools->GetSettings(etfCSParent)) + { + (*_F)->RotateParent(m_RotateVector, amount); + } + else + { + (*_F)->RotateLocal(m_RotateVector, amount); + } + } +} +bool TUI_CustomControl::RotateEnd(TShiftState _Shift) +{ + Scene->UndoSave(); + return true; +} + +//------------------------------------------------------------------------------ +// scale +//------------------------------------------------------------------------------ +bool TUI_CustomControl::ScaleStart(TShiftState Shift) +{ + ObjClassID cls = LTools->CurrentClassID(); + if (Shift == ssRBOnly) + { + ExecCommand(COMMAND_SHOWCONTEXTMENU, parent_tool->FClassID); + return false; + } + if (Scene->SelectionCount(true, cls) == 0) + return false; + return true; +} + +void TUI_CustomControl::ScaleProcess(TShiftState _Shift) +{ + float dy = UI->m_DeltaCpH.x * UI->m_MouseSS; + if (dy > 1.f) + dy = 1.f; + else if (dy < -1.f) + dy = -1.f; + + Fvector amount; + amount.set(dy, dy, dy); + + if (Tools->GetSettings(etfNUScale)) + { + if (!(etAxisX == Tools->GetAxis()) && !(etAxisZX == Tools->GetAxis())) + amount.x = 0.f; + if (!(etAxisZ == Tools->GetAxis()) && !(etAxisZX == Tools->GetAxis())) + amount.z = 0.f; + if (!(etAxisY == Tools->GetAxis())) + amount.y = 0.f; + } + + ObjectList lst; + if (Scene->GetQueryObjects(lst, LTools->CurrentClassID(), 1, 1, 0)) + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + (*_F)->Scale(amount); +} +bool TUI_CustomControl::ScaleEnd(TShiftState _Shift) +{ + Scene->UndoSave(); + return true; +} +//------------------------------------------------------------------------------ diff --git a/src/editors/LevelEditor/Tools/Base/ESceneControlsCustom.h b/src/editors/LevelEditor/Tools/Base/ESceneControlsCustom.h new file mode 100644 index 00000000000..3550b97d1b9 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Base/ESceneControlsCustom.h @@ -0,0 +1,76 @@ +#pragma once + +// refs +class ESceneToolBase; + +struct SBeforeAppendCallbackParams +{ + LPVOID data; + xr_string name_prefix; + SBeforeAppendCallbackParams() + { + data = 0; + name_prefix = ""; + } +}; +typedef fastdelegate::FastDelegate1 TBeforeAppendCallback; +typedef fastdelegate::FastDelegate2 TAfterAppendCallback; + +class TUI_CustomControl +{ +protected: + friend class ESceneToolBase; + int sub_target; + int action; + // select + bool bBoxSelection; + bool SelectStart(TShiftState _Shift); + void SelectProcess(TShiftState _Shift); + bool SelectEnd(TShiftState _Shift); + // add + bool AddStart(TShiftState _Shift); + void AddProcess(TShiftState _Shift); + bool AddEnd(TShiftState _Shift); + // move + Fvector m_MovingXVector; + Fvector m_MovingYVector; + Fvector m_MovingReminder; + bool MovingStart(TShiftState _Shift); + void MovingProcess(TShiftState _Shift); + bool MovingEnd(TShiftState _Shift); + // scale + bool ScaleStart(TShiftState _Shift); + void ScaleProcess(TShiftState _Shift); + bool ScaleEnd(TShiftState _Shift); + // rotate + Fvector m_RotateVector; + float m_fRotateSnapAngle; + + bool RotateStart(TShiftState _Shift); + void RotateProcess(TShiftState _Shift); + bool RotateEnd(TShiftState _Shift); + +protected: + bool CheckSnapList(TShiftState Shift); + + CCustomObject *DefaultAddObject(TShiftState Shift, TBeforeAppendCallback before = 0, TAfterAppendCallback after = 0); + bool DefaultMovingProcess(TShiftState Shift, Fvector &amount); + +public: + ESceneToolBase *parent_tool; + +public: + TUI_CustomControl(int st, int act, ESceneToolBase *parent); + virtual ~TUI_CustomControl() { ; } + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); + virtual bool HiddenMode(); + virtual bool KeyDown(WORD Key, TShiftState Shift) { return false; } + virtual bool KeyUp(WORD Key, TShiftState Shift) { return false; } + virtual bool KeyPress(WORD Key, TShiftState Shift) { return false; } + virtual void OnEnter() { ; } + virtual void OnExit() { ; } + + int Action() { return action; } +}; diff --git a/src/editors/LevelEditor/Tools/Base/ESceneCustomMTools.cpp b/src/editors/LevelEditor/Tools/Base/ESceneCustomMTools.cpp new file mode 100644 index 00000000000..4b8240cc90c --- /dev/null +++ b/src/editors/LevelEditor/Tools/Base/ESceneCustomMTools.cpp @@ -0,0 +1,84 @@ +#include "stdafx.h" + +#define CHUNK_TOOLS_TAG 0x7777 + +ESceneToolBase::ESceneToolBase(ObjClassID cls) +{ + FClassID = cls; + // controls + sub_target = 0; + pCurControl = 0; + action = -1; + m_EditFlags.assign(flEnable | flVisible); + m_ModifName = ""; + m_ModifTime = 0; + pForm = 0; +} + +ESceneToolBase::~ESceneToolBase() +{ +} + +void ESceneToolBase::Clear(bool bSpecific) +{ + m_ModifName = ""; + m_ModifTime = 0; +} + +void ESceneToolBase::Reset() +{ + Clear(); + m_EditFlags.set(flReadonly, FALSE); +} + +void ESceneToolBase::OnCreate() +{ + OnDeviceCreate(); + CreateControls(); +} +void ESceneToolBase::OnDestroy() +{ + OnDeviceDestroy(); + RemoveControls(); +} + +bool ESceneToolBase::LoadLTX(CInifile &ini) +{ + m_ModifName = ini.r_string("modif", "name"); + m_ModifTime = ini.r_u32("modif", "time"); + return true; +} + +void ESceneToolBase::SaveLTX(CInifile &ini, int id) +{ + ini.w_string("modif", "name", m_ModifName.c_str()); + ini.w_u32("modif", "time", m_ModifTime); +} + +bool ESceneToolBase::LoadStream(IReader &F) +{ + if (F.find_chunk(CHUNK_TOOLS_TAG)) + { + F.r_stringZ(m_ModifName); + F.r(&m_ModifTime, sizeof(m_ModifTime)); + } + else + { + m_ModifName = ""; + m_ModifTime = 0; + } + return true; +} + +void ESceneToolBase::SaveStream(IWriter &F) +{ + /* + xr_string mn = make_string("\\\\%s\\%s",Core.CompName,Core.UserName).c_str(); + time_t mt = time(NULL); + + F.open_chunk (CHUNK_TOOLS_TAG); + F.w_stringZ (mn); + F.w (&mt,sizeof(mt)); + F.close_chunk (); + */ +} diff --git a/src/editors/LevelEditor/Tools/Base/ESceneCustomMTools.h b/src/editors/LevelEditor/Tools/Base/ESceneCustomMTools.h new file mode 100644 index 00000000000..209c79bdcab --- /dev/null +++ b/src/editors/LevelEditor/Tools/Base/ESceneCustomMTools.h @@ -0,0 +1,162 @@ +#pragma once + +// refs +class SSceneSummary; +class TUI_CustomControl; +class ESceneCustomMTools; +class SceneBuilder; +struct SExportStreams; +struct mesh_build_data; +DEFINE_VECTOR(TUI_CustomControl *, ControlsVec, ControlsIt); + +class ESceneToolBase +{ +protected: + // controls + ControlsVec m_Controls; + int action; + int sub_target; + +public: + ObjClassID FClassID; + enum + { + flEnable = (1 << 0), + flReadonly = (1 << 1), + flForceReadonly = (1 << 2), + flChanged = (1 << 3), + flVisible = (1 << 4), + }; + Flags32 m_EditFlags; + BOOL IsEnabled() { return m_EditFlags.is(flEnable); } + BOOL IsEditable() { return !m_EditFlags.is_any(flReadonly | flForceReadonly); } + BOOL IsReadonly() { return m_EditFlags.is(flReadonly); } + BOOL IsForceReadonly() { return m_EditFlags.is(flForceReadonly); } + BOOL IsChanged() { return m_EditFlags.is(flChanged); } + void SetChanged(BOOL b) { m_EditFlags.set(flChanged, b); } + BOOL IsVisible() { return m_EditFlags.is(flVisible); } + virtual BOOL AllowMouseStart() = 0; + +public: + // modifiers + shared_str m_ModifName; + time_t m_ModifTime; + // frame & Controls + TUI_CustomControl *pCurControl; + UIToolCustom *pForm; + +protected: + void AddControl(TUI_CustomControl *c); + TUI_CustomControl *FindControl(int subtarget, int action); + void UpdateControl(); + +public: + void SetAction(int action); + void SetSubTarget(int target); + void ResetSubTarget(); + +protected: + void CreateDefaultControls(u32 sub_target_id); + virtual void CreateControls() = 0; + virtual void RemoveControls(); + +public: + virtual void OnActivate(); + virtual void OnDeactivate(); + virtual void OnObjectsUpdate() { ; } + +public: + // definition + virtual LPCSTR ClassName() = 0; + virtual LPCSTR ClassDesc() = 0; + virtual int RenderPriority() = 0; + +public: + ESceneToolBase(ObjClassID cls); + virtual ~ESceneToolBase(); + + virtual void OnCreate(); + virtual void OnDestroy(); + + virtual bool AllowEnabling() = 0; + // snap + virtual ObjectList *GetSnapList() = 0; + virtual void UpdateSnapList() = 0; + + // selection manipulate + // flags: [0 - FALSE, 1 - TRUE, -1 - INVERT] + virtual int RaySelect(int flag, float &distance, const Fvector &start, const Fvector &direction, BOOL bDistanceOnly) = 0; + virtual int FrustumSelect(int flag, const CFrustum &frustum) = 0; + virtual void SelectObjects(bool flag) = 0; + virtual void InvertSelection() = 0; + virtual void RemoveSelection() = 0; + virtual int SelectionCount(bool testflag) = 0; + virtual void ShowObjects(bool flag, bool bAllowSelectionFlag = false, bool bSelFlag = true) = 0; + + virtual void Clear(bool bSpecific = false) = 0; + virtual void Reset(); + + // validation + virtual bool Valid() = 0; + virtual bool Validate(bool) = 0; + + // events + virtual void OnDeviceCreate() = 0; + virtual void OnDeviceDestroy() = 0; + virtual void OnSynchronize() = 0; + virtual void OnSceneUpdate() { ; } + virtual void OnObjectRemove(CCustomObject *O, bool bDeleting) = 0; + virtual void OnBeforeObjectChange(CCustomObject *O){}; + virtual void OnFrame() = 0; + + // render + virtual void BeforeRender() { ; } + virtual void OnRender(int priority, bool strictB2F) = 0; + void OnRenderRoot(int priority, bool strictB2F) + { + if (IsVisible()) + OnRender(priority, strictB2F); + }; + virtual void AfterRender() { ; } + + // IO + virtual int SaveFileCount() const { return 1; } + virtual bool IsNeedSave() = 0; + + virtual bool LoadStream(IReader &) = 0; + virtual bool LoadLTX(CInifile &) = 0; + virtual void SaveStream(IWriter &) = 0; + virtual void SaveLTX(CInifile &, int id) = 0; + virtual bool can_use_inifile() { return true; } + + virtual bool LoadSelection(IReader &) = 0; + virtual void SaveSelection(IWriter &) = 0; + + virtual bool Export(LPCSTR path) { return true; } + virtual bool ExportGame(SExportStreams *F) { return true; } + + virtual bool ExportStatic(SceneBuilder *B, bool b_selected_only) { return true; } + virtual void GetStaticDesc(int &v_cnt, int &f_cnt, bool b_selected_only, bool b_cform) {} + virtual bool GetStaticCformData(mesh_build_data &data, bool b_selected_only) + { +#ifdef DEBUG + int cnt_v = 0, cnt_f = 0; + GetStaticDesc(cnt_v, cnt_f, b_selected_only, true); + VERIFY(cnt_v == 0 && cnt_f == 0); +#endif + return true; + } + virtual void CompileStaticStart(){}; + virtual void CompileStaticEnd(){}; + + // properties + virtual void FillProp(LPCSTR pref, PropItemVec &items) = 0; + + // utils + virtual bool GetSummaryInfo(SSceneSummary *inf) = 0; + virtual void HighlightTexture(LPCSTR tex_name, bool allow_ratio, u32 t_width, u32 t_height, BOOL mark) {} + virtual void GetBBox(Fbox &bb, bool bSelOnly) = 0; + virtual const CCustomObject *LastSelected() const { return NULL; } +}; + +DEFINE_MAP(ObjClassID, ESceneToolBase *, SceneToolsMap, SceneToolsMapPairIt); diff --git a/src/editors/LevelEditor/Tools/Base/ESceneCustomMToolsControls.cpp b/src/editors/LevelEditor/Tools/Base/ESceneCustomMToolsControls.cpp new file mode 100644 index 00000000000..a2427c24c9a --- /dev/null +++ b/src/editors/LevelEditor/Tools/Base/ESceneCustomMToolsControls.cpp @@ -0,0 +1,82 @@ +#include "stdafx.h" + +void ESceneToolBase::CreateDefaultControls(u32 sub_target_id) +{ + for (int a = 0; a < etaMaxActions; a++) + AddControl(xr_new(sub_target_id, a, this)); +} + +void ESceneToolBase::RemoveControls() +{ + // controls + for (ControlsIt it = m_Controls.begin(); it != m_Controls.end(); it++) + xr_delete(*it); + m_Controls.clear(); + xr_delete(pForm); +} + +void ESceneToolBase::AddControl(TUI_CustomControl *c) +{ + R_ASSERT(c); + for (ControlsIt it = m_Controls.begin(); it != m_Controls.end(); it++) + { + if (((*it)->sub_target == c->sub_target) && ((*it)->action == c->action)) + { + xr_delete(*it); + m_Controls.erase(it); + break; + } + } + m_Controls.push_back(c); +} + +TUI_CustomControl *ESceneToolBase::FindControl(int subtarget, int action) +{ + if (action == -1) + return 0; + for (ControlsIt it = m_Controls.begin(); it != m_Controls.end(); it++) + if (((*it)->sub_target == subtarget) && ((*it)->action == action)) + return *it; + return 0; +} + +void ESceneToolBase::UpdateControl() +{ + if (pCurControl) + pCurControl->OnExit(); + pCurControl = FindControl(sub_target, action); + if (pCurControl) + pCurControl->OnEnter(); +} + +void ESceneToolBase::OnActivate() +{ + if (pCurControl) + pCurControl->OnEnter(); + + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect, estDefault); + SetChanged(TRUE); +} + +void ESceneToolBase::OnDeactivate() +{ + if (pCurControl) + pCurControl->OnExit(); +} + +void ESceneToolBase::SetAction(int act) +{ + action = act; + UpdateControl(); +} + +void ESceneToolBase::SetSubTarget(int tgt) +{ + sub_target = tgt; + UpdateControl(); +} + +void ESceneToolBase::ResetSubTarget() +{ + SetSubTarget(estDefault); +} diff --git a/src/editors/LevelEditor/Tools/Base/ESceneCustomOTools.cpp b/src/editors/LevelEditor/Tools/Base/ESceneCustomOTools.cpp new file mode 100644 index 00000000000..de0bbba417e --- /dev/null +++ b/src/editors/LevelEditor/Tools/Base/ESceneCustomOTools.cpp @@ -0,0 +1,402 @@ +#include "stdafx.h" + +ESceneCustomOTool::ESceneCustomOTool(ObjClassID cls) : ESceneToolBase(cls) +{ +} + +ESceneCustomOTool::~ESceneCustomOTool() +{ +} + +void ESceneCustomOTool::UpdateSnapList() +{ +} + +ObjectList *ESceneCustomOTool::GetSnapList() +{ + return 0; +} + +BOOL ESceneCustomOTool::_AppendObject(CCustomObject *object) +{ + m_Objects.push_back(object); + object->FParentTools = this; + return TRUE; +} +//---------------------------------------------------- + +BOOL ESceneCustomOTool::_RemoveObject(CCustomObject *object) +{ + object->OnSceneRemove(); + m_Objects.remove(object); + return FALSE; +} +//---------------------------------------------------- + +void ESceneCustomOTool::Clear(bool bInternal) +{ + inherited::Clear(); + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + { + (*it)->OnSceneRemove(); + xr_delete(*it); + } + m_Objects.clear(); +} + +BOOL ESceneCustomOTool::AllowMouseStart() +{ + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); ++it) + { + CCustomObject *CO = *it; + if (CO->Selected() && !CO->Editable()) + return FALSE; + } + + return TRUE; +} + +void ESceneCustomOTool::OnFrame() +{ + ObjectList remove_objects; + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + { + R_ASSERT(*it); + (*it)->OnFrame(); + if ((*it)->IsDeleted()) + remove_objects.push_back(*it); + } + bool need_undo = remove_objects.size(); + while (!remove_objects.empty()) + { + CCustomObject *O = remove_objects.back(); + Scene->RemoveObject(O, false, true); + xr_delete(O); + remove_objects.pop_back(); + } + if (need_undo) + Scene->UndoSave(); +} +//---------------------------------------------------- + +void ESceneCustomOTool::OnRender(int priority, bool strictB2F) +{ + // for (ObjectIt it=m_Objects.begin(); it!=m_Objects.end(); it++) + // (*it)->Render(priority,strictB2F); +} +//---------------------------------------------------- + +void ESceneCustomOTool::OnSynchronize() +{ + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + (*it)->OnSynchronize(); +} +//---------------------------------------------------- + +void ESceneCustomOTool::OnSceneUpdate() +{ + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + (*it)->OnSceneUpdate(); +} +//---------------------------------------------------- + +void ESceneCustomOTool::OnDeviceCreate() +{ + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + (*it)->OnDeviceCreate(); +} +//---------------------------------------------------- + +void ESceneCustomOTool::OnDeviceDestroy() +{ + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + (*it)->OnDeviceDestroy(); +} +//---------------------------------------------------- + +bool ESceneCustomOTool::Validate(bool) +{ + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + if (!(*it)->Validate(true)) + return false; + return true; +} + +bool ESceneCustomOTool::Valid() +{ + return true; +} + +bool ESceneCustomOTool::IsNeedSave() +{ + return !m_Objects.empty(); +} + +void ESceneCustomOTool::OnObjectRemove(CCustomObject *O, bool bDeleting) +{ + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + (*_F)->OnObjectRemove(O); +} + +void ESceneCustomOTool::SelectObjects(bool flag) +{ + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + if ((*_F)->Visible()) + { + (*_F)->Select(flag); + } + UI->RedrawScene(); +} + +void ESceneCustomOTool::RemoveSelection() +{ + ObjectIt _F = m_Objects.begin(); + while (_F != m_Objects.end()) + { + if ((*_F)->Selected() && !(*_F)->m_CO_Flags.test(CCustomObject::flObjectInGroup)) + { + if ((*_F)->OnSelectionRemove()) + { + ObjectIt _D = _F; + _F++; + CCustomObject *obj = *_D; + Scene->RemoveObject(obj, false, true); + xr_delete(obj); + } + else + { + _F++; + } + } + else + { + _F++; + } + } + UI->RedrawScene(); +} + +void ESceneCustomOTool::InvertSelection() +{ + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + if ((*_F)->Visible()) + { + (*_F)->Select(-1); + } + + UI->RedrawScene(); +} + +int ESceneCustomOTool::SelectionCount(bool testflag) +{ + int count = 0; + + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + if ((*_F)->Visible() && (!!(*_F)->Selected() == testflag)) + count++; + + return count; +} + +void ESceneCustomOTool::ShowObjects(bool flag, bool bAllowSelectionFlag, bool bSelFlag) +{ + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + { + if (bAllowSelectionFlag) + { + if (!!(*_F)->Selected() == bSelFlag) + { + (*_F)->Show(flag); + } + } + else + { + (*_F)->Show(flag); + } + } + UI->RedrawScene(); +} + +BOOL ESceneCustomOTool::RayPick(CCustomObject *&object, float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf) +{ + object = 0; + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + if ((*_F)->Visible() && (*_F)->RayPick(distance, start, direction, pinf)) + object = *_F; + return !!object; +} + +BOOL ESceneCustomOTool::FrustumPick(ObjectList &lst, const CFrustum &frustum) +{ + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + if ((*_F)->Visible() && (*_F)->FrustumPick(frustum)) + lst.push_back(*_F); + return !lst.empty(); +} + +BOOL ESceneCustomOTool::SpherePick(ObjectList &lst, const Fvector ¢er, float radius) +{ + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + if ((*_F)->Visible() && (*_F)->SpherePick(center, radius)) + lst.push_back(*_F); + return !lst.empty(); +} + +int ESceneCustomOTool::RaySelect(int flag, float &distance, const Fvector &start, const Fvector &direction, BOOL bDistanceOnly) +{ + CCustomObject *nearest_object = 0; + if (RayPick(nearest_object, distance, start, direction, 0) && !bDistanceOnly) + nearest_object->RaySelect(flag, start, direction, false); + // nearest_object->Select(flag); + UI->RedrawScene(); + return !!nearest_object; +} + +int ESceneCustomOTool::FrustumSelect(int flag, const CFrustum &frustum) +{ + ObjectList lst; + + FrustumPick(lst, frustum); + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + (*_F)->Select(flag); + + return 0; +} + +int ESceneCustomOTool::GetQueryObjects(ObjectList &lst, int iSel, int iVis, int iLock) +{ + int count = 0; + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + { + if (((iSel == -1) || ((*_F)->Selected() == iSel)) && + ((iVis == -1) || ((*_F)->Visible() == iVis))) + { + lst.push_back(*_F); + count++; + } + } + return count; +} + +CCustomObject *ESceneCustomOTool::FindObjectByName(LPCSTR name, CCustomObject *pass) +{ + ObjectIt _I = m_Objects.begin(); + ObjectIt _E = m_Objects.end(); + for (; _I != _E; _I++) + { + CCustomObject *CO = (*_I); + LPCSTR _name = CO->GetName(); + R_ASSERT(_name); + if ((pass != *_I) && (0 == strcmp(_name, name))) + return (*_I); + } + return 0; +} + +void setEditable(PropItemVec &items, u32 start_idx, bool bEditableTool, bool bObjectInGroup, bool bObjectInGroupUnique) +{ + PropItemIt it = items.begin() + start_idx; + PropItemIt it_e = items.end(); + u32 idx = 0; + + bool bEditableObject = bEditableTool && (!bObjectInGroup || (bObjectInGroup && bObjectInGroupUnique)); + + for (; it != it_e; ++it, ++idx) + { + bool bEnabledItem = bEditableObject; + if (!bEnabledItem && idx == 4 && bObjectInGroup) + bEnabledItem = true; + + (*it)->Enable(bEnabledItem); + } +} + +void ESceneCustomOTool::FillProp(LPCSTR pref, PropItemVec &items) +{ + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + { + if ((*it)->Selected()) + { + + u32 cnt = items.size(); + (*it)->FillProp(PrepareKey(pref, "Items").c_str(), items); + + setEditable(items, + cnt, + IsEditable(), + (*it)->m_CO_Flags.test(CCustomObject::flObjectInGroup), + (*it)->m_CO_Flags.test(CCustomObject::flObjectInGroupUnique)); + } + } +} + +/* +void ESceneCustomOTool::FillProp(LPCSTR pref, PropItemVec& items) +{ + for (ObjectIt it=m_Objects.begin(); it!=m_Objects.end(); ++it) + { + if ((*it)->Selected()) + (*it)->FillProp (PrepareKey(pref,"Items").c_str(), items); + } +} +*/ + +bool ESceneCustomOTool::GetSummaryInfo(SSceneSummary *inf) +{ + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + (*it)->GetSummaryInfo(inf); + return true; +} + +void ESceneCustomOTool::GetBBox(Fbox &BB, bool bSelOnly) +{ + Fbox bb; + ObjectList lst; + if (GetQueryObjects(lst, bSelOnly, true, -1)) + { + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + if ((*_F)->GetBox(bb)) + BB.merge(bb); + } +} + +int ESceneCustomOTool::MultiRenameObjects() +{ + int cnt = 0; + for (ObjectIt o_it = m_Objects.begin(); o_it != m_Objects.end(); o_it++) + { + CCustomObject *obj = *o_it; + if (obj->Selected()) + { + string256 buf; + Scene->GenObjectName(obj->FClassID, buf, obj->RefName()); + if (stricmp(obj->GetName(), buf) != 0) + { + obj->SetName(buf); + cnt++; + } + } + } + return cnt; +} + +void ESceneCustomOTool::OnSelected(CCustomObject *object) +{ + for (ObjectIt o_it = m_Objects.begin(); o_it != m_Objects.end(); ++o_it) + { + CCustomObject *obj = *o_it; + obj->m_RT_Flags.set(CCustomObject::flRT_SelectedLast, FALSE); + } + object->m_RT_Flags.set(CCustomObject::flRT_SelectedLast, TRUE); +} + +const CCustomObject *ESceneCustomOTool::LastSelected() const +{ + for (ObjectList::const_iterator o_it = m_Objects.begin(); o_it != m_Objects.end(); ++o_it) + { + const CCustomObject *obj = *o_it; + if (obj->m_RT_Flags.test(CCustomObject::flRT_SelectedLast)) + return obj; + } + return NULL; +} diff --git a/src/editors/LevelEditor/Tools/Base/ESceneCustomOTools.h b/src/editors/LevelEditor/Tools/Base/ESceneCustomOTools.h new file mode 100644 index 00000000000..5281a681be4 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Base/ESceneCustomOTools.h @@ -0,0 +1,100 @@ +#ifndef ESceneCustomOToolsH +#define ESceneCustomOToolsH + +#include "ESceneCustomMTools.h" + +struct SRayPickInfo; +struct mesh_build_data; +class ESceneCustomOTool : public ESceneToolBase +{ + typedef ESceneToolBase inherited; + +protected: + ObjectList m_Objects; + + bool OnLoadSelectionAppendObject(CCustomObject *obj); + bool OnLoadAppendObject(CCustomObject *obj); + +public: + ESceneCustomOTool(ObjClassID cls); + virtual ~ESceneCustomOTool(); + + virtual bool AllowEnabling() { return true; } + virtual BOOL AllowMouseStart(); + + // snap + virtual ObjectList *GetSnapList(); + virtual void UpdateSnapList(); + + // selection manipulate + virtual int RaySelect(int flag, float &distance, const Fvector &start, const Fvector &direction, BOOL bDistanceOnly); + virtual int FrustumSelect(int flag, const CFrustum &frustum); + virtual void SelectObjects(bool flag); + virtual void InvertSelection(); + virtual void RemoveSelection(); + virtual int SelectionCount(bool testflag); + virtual void ShowObjects(bool flag, bool bAllowSelectionFlag = false, bool bSelFlag = true); + + virtual void Clear(bool bSpecific = false) = 0; + + // validation + virtual bool Valid(); + virtual bool Validate(bool); + + // events + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + virtual void OnSynchronize(); + virtual void OnSceneUpdate(); + virtual void OnObjectRemove(CCustomObject *O, bool bDeleting); + + virtual void OnBeforeObjectChange(CCustomObject *O) { inherited::OnBeforeObjectChange(O); } + virtual void OnFrame(); + virtual void OnRender(int priority, bool strictB2F); + + // IO + virtual bool IsNeedSave() = 0; + + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + virtual bool Export(LPCSTR path); + virtual bool ExportGame(SExportStreams *F); + virtual bool ExportStatic(SceneBuilder *B, bool b_selected_only); + virtual bool GetStaticCformData(mesh_build_data &data, bool b_selected_only); + // properties + virtual void FillProp(LPCSTR pref, PropItemVec &items); + + // utils + virtual bool GetSummaryInfo(SSceneSummary *inf); + virtual void GetBBox(Fbox &bb, bool bSelOnly); + + //-------------------------------------------------------------------------- + // object part + //-------------------------------------------------------------------------- + IC ObjectList &GetObjects() { return m_Objects; } + IC int ObjCount() { return m_Objects.size(); } + + virtual BOOL _AppendObject(CCustomObject *object); + virtual BOOL _RemoveObject(CCustomObject *object); + + // pick function + virtual BOOL RayPick(CCustomObject *&object, float &distance, const Fvector &start, const Fvector &direction, SRayPickInfo *pinf); + virtual BOOL FrustumPick(ObjectList &lst, const CFrustum &frustum); + virtual BOOL SpherePick(ObjectList &lst, const Fvector ¢er, float radius); + virtual int GetQueryObjects(ObjectList &lst, int iSel, int iVis, int iLock); + + virtual CCustomObject *FindObjectByName(LPCSTR name, CCustomObject *pass = 0); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name) = 0; + + virtual int MultiRenameObjects(); + void OnSelected(CCustomObject *object); + virtual const CCustomObject *LastSelected() const; +}; +#endif // ESceneCustomOToolsH diff --git a/src/editors/LevelEditor/Tools/Base/ESceneCustomOToolsIO.cpp b/src/editors/LevelEditor/Tools/Base/ESceneCustomOToolsIO.cpp new file mode 100644 index 00000000000..d1d0bf4e74b --- /dev/null +++ b/src/editors/LevelEditor/Tools/Base/ESceneCustomOToolsIO.cpp @@ -0,0 +1,166 @@ +#include "stdafx.h" + +// chunks +static const u32 CHUNK_VERSION = 0x0001; +static const u32 CHUNK_OBJECT_COUNT = 0x0002; +static const u32 CHUNK_OBJECTS = 0x0003; +static const u32 CHUNK_FLAGS = 0x0004; + +bool ESceneCustomOTool::OnLoadSelectionAppendObject(CCustomObject *obj) +{ + string256 buf; + Scene->GenObjectName(obj->FClassID, buf, obj->GetName()); + obj->SetName(buf); + Scene->AppendObject(obj, false); + return true; +} + +bool ESceneCustomOTool::OnLoadAppendObject(CCustomObject *O) +{ + Scene->AppendObject(O, false); + return true; +} + +bool ESceneCustomOTool::LoadSelection(IReader &F) +{ + int count = 0; + F.r_chunk(CHUNK_OBJECT_COUNT, &count); + + SPBItem *pb = UI->ProgressStart(static_cast(count), make_string("Loading %s(stream)...", ClassDesc()).c_str()); + Scene->ReadObjectsStream(F, CHUNK_OBJECTS, EScene::TAppendObject(this, &ESceneCustomOTool::OnLoadSelectionAppendObject), pb); + UI->ProgressEnd(pb); + + return true; +} + +void ESceneCustomOTool::SaveSelection(IWriter &F) +{ + F.open_chunk(CHUNK_OBJECTS); + int count = 0; + + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); ++it) + { + if ((*it)->Selected() && !(*it)->IsDeleted()) + { + F.open_chunk(count++); + Scene->SaveObjectStream(*it, F); + F.close_chunk(); + } + } + + F.close_chunk(); + F.w_chunk(CHUNK_OBJECT_COUNT, &count, sizeof(count)); +} + +bool ESceneCustomOTool::LoadLTX(CInifile &ini) +{ + inherited::LoadLTX(ini); + + u32 count = ini.r_u32("main", "objects_count"); + SPBItem *pb = UI->ProgressStart(static_cast(count), make_string("Loading %s(ltx)...", ClassDesc()).c_str()); + + u32 i = 0; + string128 buff; + + for (i = 0; i < count; ++i) + { + + CCustomObject *obj = NULL; + sprintf(buff, "object_%d", i); + if (Scene->ReadObjectLTX(ini, buff, obj)) + { + if (!OnLoadAppendObject(obj)) + xr_delete(obj); + } + pb->Inc(); + } + + UI->ProgressEnd(pb); + + return true; +} + +bool ESceneCustomOTool::LoadStream(IReader &F) +{ + inherited::LoadStream(F); + + int count = 0; + F.r_chunk(CHUNK_OBJECT_COUNT, &count); + + SPBItem *pb = UI->ProgressStart(static_cast(count), make_string("Loading %s...", ClassDesc()).c_str()); + Scene->ReadObjectsStream(F, CHUNK_OBJECTS, EScene::TAppendObject(this, &ESceneCustomOTool::OnLoadAppendObject), pb); + UI->ProgressEnd(pb); + + return true; +} +//---------------------------------------------------- + +void ESceneCustomOTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + + u32 count = 0; + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); ++it) + { + CCustomObject *O = (*it); + if (O->save_id != id) + continue; + + if (O->IsDeleted() || O->m_CO_Flags.test(CCustomObject::flObjectInGroup)) + continue; + + string128 buff; + sprintf(buff, "object_%d", count); + Scene->SaveObjectLTX(*it, buff, ini); + count++; + } + + ini.w_u32("main", "objects_count", count); +} + +void ESceneCustomOTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + F.open_chunk(CHUNK_OBJECTS); + int objectsCount = 0; + + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); ++it) + { + if ((*it)->IsDeleted() || (*it)->m_CO_Flags.test(CCustomObject::flObjectInGroup)) + continue; + + F.open_chunk(objectsCount++); + Scene->SaveObjectStream(*it, F); + F.close_chunk(); + } + + F.close_chunk(); + F.w_chunk(CHUNK_OBJECT_COUNT, &objectsCount, sizeof(objectsCount)); +} + +bool ESceneCustomOTool::Export(LPCSTR path) +{ + return true; +} +//---------------------------------------------------- + +bool ESceneCustomOTool::ExportGame(SExportStreams *F) +{ + bool bres = true; + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + if (!(*it)->ExportGame(F)) + bres = false; + return bres; +} +//---------------------------------------------------- + +bool ESceneCustomOTool::ExportStatic(SceneBuilder *B, bool b_selected_only) +{ + return B->ParseStaticObjects(m_Objects, NULL, b_selected_only); +} +BOOL GetStaticCformData(ObjectList &lst, mesh_build_data &data, bool b_selected_only); +bool ESceneCustomOTool::GetStaticCformData(mesh_build_data &data, bool b_selected_only) // b_vertex* verts, int& vert_cnt, int& vert_it,b_face* faces, int& face_cnt, int& face_it, +{ + return ::GetStaticCformData(m_Objects, data, b_selected_only); +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Tools/Base/ESceneDummyTools.cpp b/src/editors/LevelEditor/Tools/Base/ESceneDummyTools.cpp new file mode 100644 index 00000000000..9a441d9704a --- /dev/null +++ b/src/editors/LevelEditor/Tools/Base/ESceneDummyTools.cpp @@ -0,0 +1,11 @@ +#include "stdafx.h" + +void ESceneDummyTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); +} + +void ESceneDummyTool::RemoveControls() +{ + inherited::RemoveControls(); +} diff --git a/src/editors/LevelEditor/Tools/Base/ESceneDummyTools.h b/src/editors/LevelEditor/Tools/Base/ESceneDummyTools.h new file mode 100644 index 00000000000..9edd19034cd --- /dev/null +++ b/src/editors/LevelEditor/Tools/Base/ESceneDummyTools.h @@ -0,0 +1,38 @@ +//--------------------------------------------------------------------------- +#ifndef ESceneDummyToolsH +#define ESceneDummyToolsH + +#include "ESceneCustomOTools.h" + +class ESceneDummyTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + ESceneDummyTool() : ESceneCustomOTool(OBJCLASS_DUMMY) { ; } + + virtual void Clear(bool bSpecific = false) { inherited::Clear(bSpecific); } + // definition + IC LPCSTR ClassName() + { + THROW; + return 0; + } + IC LPCSTR ClassDesc() + { + THROW; + return 0; + } + IC int RenderPriority() { return -1; } + + virtual bool IsNeedSave() { return false; } + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name) { return 0; }; +}; +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/LevelEditor/Tools/Details/ESceneDOTools.cpp b/src/editors/LevelEditor/Tools/Details/ESceneDOTools.cpp new file mode 100644 index 00000000000..39d74ff0f11 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Details/ESceneDOTools.cpp @@ -0,0 +1,634 @@ +#include "stdafx.h" +#include "Layers/xrRender/DetailFormat.h" + +static const u32 DETMGR_VERSION = 0x0003ul; + +enum +{ + DETMGR_CHUNK_VERSION = 0x1000ul, + DETMGR_CHUNK_HEADER = 0x0000ul, + DETMGR_CHUNK_OBJECTS = 0x0001ul, + DETMGR_CHUNK_SLOTS = 0x0002ul, + DETMGR_CHUNK_BBOX = 0x1001ul, + DETMGR_CHUNK_BASE_TEXTURE = 0x1002ul, + DETMGR_CHUNK_COLOR_INDEX = 0x1003ul, + DETMGR_CHUNK_SNAP_OBJECTS = 0x1004ul, + DETMGR_CHUNK_DENSITY = 0x1005ul, + DETMGR_CHUNK_FLAGS = 0x1006ul, +}; + +EDetailManager::EDetailManager() : ESceneToolBase(OBJCLASS_DO) +{ + dtSlots = 0; + ZeroMemory(&dtH, sizeof(dtH)); + m_Selected.clear(); + InitRender(); + + m_Flags.assign(flObjectsDraw); +} + +EDetailManager::~EDetailManager() +{ + Clear(); + Unload(); +} + +void EDetailManager::ClearColorIndices() +{ + inherited::Clear(); + RemoveDOs(); + m_ColorIndices.clear(); +} + +void EDetailManager::ClearSlots() +{ + ZeroMemory(&dtH, sizeof(DetailHeader)); + xr_free(dtSlots); + m_Selected.clear(); + InvalidateCache(); +} + +void EDetailManager::ClearBase() +{ + m_Base.Clear(); + m_SnapObjects.clear(); + ExecCommand(COMMAND_REFRESH_SNAP_OBJECTS); +} + +void EDetailManager::Clear(bool bSpecific) +{ + ClearBase(); + ClearColorIndices(); + ClearSlots(); + m_Flags.zero(); + m_RTFlags.zero(); +} + +void EDetailManager::InvalidateCache() +{ + // resize visible + m_visibles[0].resize(objects.size()); // dump(visible[0]); + m_visibles[1].resize(objects.size()); // dump(visible[1]); + m_visibles[2].resize(objects.size()); // dump(visible[2]); + // Initialize 'vis' and 'cache' + cache_Initialize(); +} + +extern void bwdithermap(int levels, int magic[16][16]); + +void EDetailManager::InitRender() +{ + // inavlidate cache + InvalidateCache(); + // Make dither matrix + bwdithermap(2, dither); + + soft_Load(); +} + +void EDetailManager::OnRender(int priority, bool strictB2F) +{ + if (dtSlots) + { + if (1 == priority) + { + if (false == strictB2F) + { + if (m_Flags.is(flSlotBoxesDraw)) + { + RCache.set_xform_world(Fidentity); + EDevice.SetShader(EDevice.m_WireShader); + + Fvector c; + Fbox bbox; + u32 inactive = 0xff808080; + u32 selected = 0xffffffff; + float dist_lim = 75.f * 75.f; + for (u32 z = 0; z < dtH.z_size(); z++) + { + c.z = fromSlotZ(z); + for (u32 x = 0; x < dtH.x_size(); x++) + { + bool bSel = m_Selected[z * dtH.x_size() + x]; + DetailSlot* slot = dtSlots + z * dtH.x_size() + x; + c.x = fromSlotX(x); + c.y = slot->r_ybase() + slot->r_yheight() * 0.5f; //(slot->y_max+slot->y_min)*0.5f; + float dist = EDevice.m_Camera.GetPosition().distance_to_sqr(c); + if ((dist < dist_lim) && ::Render->ViewBase.testSphere_dirty(c, DETAIL_SLOT_SIZE_2)) + { + bbox.vMin.set(c.x - DETAIL_SLOT_SIZE_2, slot->r_ybase(), c.z - DETAIL_SLOT_SIZE_2); + bbox.vMax.set(c.x + DETAIL_SLOT_SIZE_2, slot->r_ybase() + slot->r_yheight(), c.z + DETAIL_SLOT_SIZE_2); + bbox.shrink(0.05f); + DU_impl.DrawSelectionBoxB(bbox, bSel ? &selected : &inactive); + } + } + } + } + } + else + { + RCache.set_xform_world(Fidentity); + if (m_Flags.is(flBaseTextureDraw)) + m_Base.Render(m_Flags.is(flBaseTextureBlended)); + if (m_Flags.is(flObjectsDraw)) + CDetailManager::Render(RCache); + } + } + } +} + +void EDetailManager::OnDeviceCreate() +{ + // base texture + m_Base.CreateShader(); + // detail objects + for (DetailIt it = objects.begin(); it != objects.end(); it++) + ((EDetail *)(*it))->OnDeviceCreate(); + soft_Load(); +} + +void EDetailManager::OnDeviceDestroy() +{ + // base texture + m_Base.DestroyShader(); + // detail objects + for (DetailIt it = objects.begin(); it != objects.end(); it++) + ((EDetail *)(*it))->OnDeviceDestroy(); + soft_Unload(); +} + +void EDetailManager::OnObjectRemove(CCustomObject *O, bool bDeleting) +{ + ObjectIt it = std::find(m_SnapObjects.begin(), m_SnapObjects.end(), O); + if (it != m_SnapObjects.end()) + { + m_RTFlags.set(flRTGenerateBaseMesh, TRUE); + m_SnapObjects.remove(O); + } +} +void EDetailManager::OnSynchronize() +{ +} +void EDetailManager::OnSceneUpdate() +{ +} + +void EDetailManager::OnFrame() +{ + if (m_RTFlags.is(flRTGenerateBaseMesh) && m_Base.Valid()) + { + m_RTFlags.set(flRTGenerateBaseMesh, FALSE); + m_Base.CreateRMFromObjects(m_BBox, m_SnapObjects); + } +} + +void EDetailManager::ExportColorIndices(LPCSTR fname) +{ + IWriter *F = FS.w_open(fname); + if (F) + { + SaveColorIndices(*F); + FS.w_close(F); + } +} + +bool EDetailManager::ImportColorIndices(LPCSTR fname) +{ + IReader *F = FS.r_open(fname); + if (F) + { + ClearColorIndices(); + LoadColorIndices(*F); + FS.r_close(F); + return true; + } + else + { + ELog.DlgMsg(mtError, "Can't open file '%s'.", fname); + return false; + } +} + +void EDetailManager::SaveColorIndices(IWriter &F) +{ + // objects + F.open_chunk(DETMGR_CHUNK_OBJECTS); + for (DetailIt it = objects.begin(); it != objects.end(); it++) + { + F.open_chunk(it - objects.begin()); + ((EDetail *)(*it))->Save(F); + F.close_chunk(); + } + F.close_chunk(); + // color index map + F.open_chunk(DETMGR_CHUNK_COLOR_INDEX); + F.w_u8((u8)m_ColorIndices.size()); + ColorIndexPairIt S = m_ColorIndices.begin(); + ColorIndexPairIt E = m_ColorIndices.end(); + ColorIndexPairIt i_it = S; + for (; i_it != E; i_it++) + { + F.w_u32(i_it->first); + F.w_u8((u8)i_it->second.size()); + for (DOIt d_it = i_it->second.begin(); d_it != i_it->second.end(); d_it++) + F.w_stringZ((*d_it)->GetName()); + } + F.close_chunk(); +} + +bool EDetailManager::LoadColorIndices(IReader &F) +{ + VERIFY(objects.empty()); + VERIFY(m_ColorIndices.empty()); + + bool bRes = true; + // objects + IReader *OBJ = F.open_chunk(DETMGR_CHUNK_OBJECTS); + if (OBJ) + { + IReader *O = OBJ->open_chunk(0); + for (int count = 1; O; count++) + { + EDetail *DO = xr_new(); + if (DO->Load(*O)) + objects.push_back(DO); + else + bRes = false; + O->close(); + O = OBJ->open_chunk(count); + } + OBJ->close(); + } + // color index map + R_ASSERT(F.find_chunk(DETMGR_CHUNK_COLOR_INDEX)); + int cnt = F.r_u8(); + string256 buf; + u32 index; + int ref_cnt; + for (int k = 0; k < cnt; k++) + { + index = F.r_u32(); + ref_cnt = F.r_u8(); + for (int j = 0; j < ref_cnt; j++) + { + F.r_stringZ(buf, sizeof(buf)); + EDetail *DO = FindDOByName(buf); + if (DO) + m_ColorIndices[index].push_back(DO); + else + bRes = false; + } + } + InvalidateCache(); + + return bRes; +} +bool EDetailManager::LoadLTX(CInifile &ini) +{ + R_ASSERT2(0, "not_implemented"); + return true; +} + +void EDetailManager::SaveLTX(CInifile &ini, int id) +{ + R_ASSERT2(0, "not_implemented"); + /* + inherited::SaveLTX (ini); + + ini.w_u32 ("main", "version", DETMGR_VERSION); + + ini.w_u32 ("main", "flags", m_Flags.get()); + + // header + + ini.w_u32 ("detail_header", "version", dtH.version); + ini.w_u32 ("detail_header", "object_count", dtH.object_count); + ini.w_ivector2 ("detail_header", "offset", Ivector2().set(dtH.offs_x, dtH.offs_z) ); + ini.w_ivector2 ("detail_header", "size", Ivector2().set(dtH.size_x, dtH.size_z) ); + + // objects + SaveColorIndicesLTX (F); + + // slots + F.open_chunk (DETMGR_CHUNK_SLOTS); + F.w_u32 (dtH.size_x*dtH.size_z); + F.w (dtSlots,dtH.size_x*dtH.size_z*sizeof(DetailSlot)); + F.close_chunk (); + + // internal + // bbox + ini.w_fvector3 ("main", "bbox_min", m_BBox.min); + ini.w_fvector3 ("main", "bbox_max", m_BBox.max); + + // base texture + if (m_Base.Valid()) + { + ini.w_string ("main", "base_texture", m_Base.GetName()); + } + ini.w_float ("main", "detail_density", ps_r__Detail_density); + + // snap objects + for (ObjectIt o_it=m_SnapObjects.begin(); o_it!=m_SnapObjects.end(); ++o_it) + ini.w_string ("snap_objects", (*o_it)->Name, NULL); + */ +} + +bool EDetailManager::LoadStream(IReader &F) +{ + inherited::LoadStream(F); + + string256 buf; + R_ASSERT(F.find_chunk(DETMGR_CHUNK_VERSION)); + u32 version = F.r_u32(); + + if (version != DETMGR_VERSION) + { + ELog.Msg(mtError, "EDetailManager: unsupported version."); + return false; + } + + if (F.find_chunk(DETMGR_CHUNK_FLAGS)) + m_Flags.assign(F.r_u32()); + + // header + R_ASSERT(F.r_chunk(DETMGR_CHUNK_HEADER, &dtH)); + + // slots + R_ASSERT(F.find_chunk(DETMGR_CHUNK_SLOTS)); + int slot_cnt = F.r_u32(); + if (slot_cnt) + dtSlots = xr_alloc(slot_cnt); + m_Selected.resize(slot_cnt); + F.r(dtSlots, slot_cnt * sizeof(DetailSlot)); + + // objects + if (!LoadColorIndices(F)) + { + ELog.DlgMsg(mtError, "EDetailManager: Some objects removed. Reinitialize objects.", buf); + InvalidateSlots(); + } + + // internal + // bbox + R_ASSERT(F.r_chunk(DETMGR_CHUNK_BBOX, &m_BBox)); + + // snap objects + if (F.find_chunk(DETMGR_CHUNK_SNAP_OBJECTS)) + { + int snap_cnt = F.r_u32(); + if (snap_cnt) + { + for (int i = 0; i < snap_cnt; i++) + { + F.r_stringZ(buf, sizeof(buf)); + CCustomObject *O = Scene->FindObjectByName(buf, OBJCLASS_SCENEOBJECT); + if (!O) + ELog.Msg(mtError, "EDetailManager: Can't find snap object '%s'.", buf); + else + m_SnapObjects.push_back(O); + } + } + } + + if (F.find_chunk(DETMGR_CHUNK_DENSITY)) + ps_r__Detail_density = F.r_float(); + + // base texture + if (F.find_chunk(DETMGR_CHUNK_BASE_TEXTURE)) + { + F.r_stringZ(buf, sizeof(buf)); + if (m_Base.LoadImage(buf)) + { + m_Base.CreateShader(); + m_RTFlags.set(flRTGenerateBaseMesh, TRUE); + } + else + { + ELog.Msg(mtError, "EDetailManager: Can't find base texture '%s'.", buf); + ClearSlots(); + ClearBase(); + } + } + + InvalidateCache(); + + return true; +} + +bool EDetailManager::LoadSelection(IReader &F) +{ + Clear(); + return LoadStream(F); +} + +void EDetailManager::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + // version + F.open_chunk(DETMGR_CHUNK_VERSION); + F.w_u32(DETMGR_VERSION); + F.close_chunk(); + + F.open_chunk(DETMGR_CHUNK_FLAGS); + F.w_u32(m_Flags.get()); + F.close_chunk(); + + // header + F.w_chunk(DETMGR_CHUNK_HEADER, &dtH, sizeof(DetailHeader)); + + // objects + SaveColorIndices(F); + + // slots + F.open_chunk(DETMGR_CHUNK_SLOTS); + F.w_u32(dtH.x_size() * dtH.z_size()); + F.w(dtSlots, dtH.x_size() * dtH.z_size() * sizeof(DetailSlot)); + F.close_chunk(); + // internal + // bbox + F.w_chunk(DETMGR_CHUNK_BBOX, &m_BBox, sizeof(Fbox)); + // base texture + if (m_Base.Valid()) + { + F.open_chunk(DETMGR_CHUNK_BASE_TEXTURE); + F.w_stringZ(m_Base.GetName()); + F.close_chunk(); + } + F.open_chunk(DETMGR_CHUNK_DENSITY); + F.w_float(ps_r__Detail_density); + F.close_chunk(); + // snap objects + F.open_chunk(DETMGR_CHUNK_SNAP_OBJECTS); + F.w_u32(m_SnapObjects.size()); + for (ObjectIt o_it = m_SnapObjects.begin(); o_it != m_SnapObjects.end(); o_it++) + F.w_stringZ((*o_it)->GetName()); + F.close_chunk(); +} + +void EDetailManager::SaveSelection(IWriter &F) +{ + SaveStream(F); +} + +bool EDetailManager::Export(LPCSTR path) +{ + xr_string fn = xr_string(path) + "build.details"; + bool bRes = true; + + SPBItem *pb = UI->ProgressStart(5, "Making details..."); + CMemoryWriter F; + + pb->Inc("merge textures"); + Fvector2Vec offsets; + Fvector2Vec scales; + boolVec rotated; + RStringSet textures_set; + RStringVec textures; + U32Vec remap; + U8Vec remap_object(objects.size(), u8(-1)); + + int slot_cnt = dtH.x_size() * dtH.z_size(); + for (int slot_idx = 0; slot_idx < slot_cnt; slot_idx++) + { + DetailSlot *it = &dtSlots[slot_idx]; + for (int part = 0; part < 4; part++) + { + u8 id = it->r_id(part); + if (id != DetailSlot::ID_Empty) + { + textures_set.insert(((EDetail *)(objects[id]))->GetTextureName()); + remap_object[id] = 1; + } + } + } + textures.assign(textures_set.begin(), textures_set.end()); + + U8It remap_object_it = remap_object.begin(); + + u32 new_idx = 0; + for (DetailIt d_it = objects.begin(); d_it != objects.end(); d_it++, remap_object_it++) + if ((*remap_object_it == 1) && (textures_set.find(((EDetail *)(*d_it))->GetTextureName()) != textures_set.end())) + *remap_object_it = (u8)new_idx++; + + xr_string do_tex_name = ChangeFileExt(fn, "_details"); + int res = ImageLib.CreateMergedTexture(textures, do_tex_name.c_str(), STextureParams::tfDXT5, 256, 1024, 256, 1024, offsets, scales, rotated, remap); + if (1 != res) + bRes = FALSE; + + pb->Inc("export geometry"); + // objects + int object_idx = 0; + if (bRes) + { + do_tex_name = EFS.ExtractFileName(do_tex_name.c_str()); + F.open_chunk(DETMGR_CHUNK_OBJECTS); + for (DetailIt it = objects.begin(); it != objects.end(); it++) + { + if (remap_object[it - objects.begin()] != u8(-1)) + { + F.open_chunk(object_idx++); + if (!((EDetail *)(*it))->m_pRefs) + { + ELog.DlgMsg(mtError, "Bad object or object not found '%s'.", ((EDetail *)(*it))->m_sRefs.c_str()); + bRes = false; + } + else + { + LPCSTR tex_name = ((EDetail *)(*it))->GetTextureName(); + u32 t_idx = 0; + for (; t_idx < textures.size(); t_idx++) + if (textures[t_idx] == tex_name) + break; + VERIFY(t_idx < textures.size()); + t_idx = remap[t_idx]; + ((EDetail *)(*it))->Export(F, do_tex_name.c_str(), offsets[t_idx], scales[t_idx], rotated[t_idx]); + } + F.close_chunk(); + if (!bRes) + break; + } + } + F.close_chunk(); + } + + pb->Inc("export slots"); + // slots + if (bRes) + { + xr_vector dt_slots(slot_cnt); + dt_slots.assign(dtSlots, dtSlots + slot_cnt); + for (int slot_idx = 0; slot_idx < slot_cnt; slot_idx++) + { + DetailSlot &it = dt_slots[slot_idx]; + // zero colors need lighting + it.c_dir = 0; + it.c_hemi = 0; + it.c_r = 0; + it.c_g = 0; + it.c_b = 0; + for (int part = 0; part < 4; part++) + { + u8 id = it.r_id(part); + if (id != DetailSlot::ID_Empty) + it.w_id(part, remap_object[id]); + } + } + F.open_chunk(DETMGR_CHUNK_SLOTS); + F.w(dt_slots.data(), dtH.x_size() * dtH.z_size() * sizeof(DetailSlot)); + F.close_chunk(); + pb->Inc(); + + // write header + dtH._version = DETAIL_VERSION; + dtH.obj_count = object_idx; + + F.w_chunk(DETMGR_CHUNK_HEADER, &dtH, sizeof(DetailHeader)); + + bRes = F.save_to(fn.c_str()); + } + + pb->Inc(); + UI->ProgressEnd(pb); + return bRes; +} + +void EDetailManager::OnDensityChange(PropValue *prop) +{ + InvalidateCache(); +} + +void EDetailManager::OnBaseTextureChange(PropValue *prop) +{ + m_Base.OnImageChange(prop); + InvalidateSlots(); + ELog.DlgMsg(mtInformation, "Texture changed. Reinitialize objects."); +} + +void EDetailManager::FillProp(LPCSTR pref, PropItemVec &items) +{ + PropValue *P; + P = PHelper().CreateFloat(items, PrepareKey(pref, "Objects per square"), &ps_r__Detail_density); + P->OnChangeEvent.bind(this, &EDetailManager::OnDensityChange); + P = PHelper().CreateChoose(items, PrepareKey(pref, "Base Texture"), &m_Base.name, smTexture); + P->OnChangeEvent.bind(this, &EDetailManager::OnBaseTextureChange); + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Draw objects"), &m_Flags, flObjectsDraw); + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Draw base texture"), &m_Flags, flBaseTextureDraw); + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Base texture blended"), &m_Flags, flBaseTextureBlended); + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Draw slot boxes"), &m_Flags, flSlotBoxesDraw); +} + +bool EDetailManager::GetSummaryInfo(SSceneSummary *inf) +{ + for (DetailIt it = objects.begin(); it != objects.end(); it++) + { + ((EDetail *)(*it))->OnDeviceCreate(); + CEditableObject *E = ((EDetail *)(*it))->m_pRefs; + if (!E) + continue; + CSurface *surf = *E->FirstSurface(); + VERIFY(surf); + inf->AppendTexture(surf->_Texture(), SSceneSummary::sttDO, 0, 0, "$DETAILS$"); + } + return true; +} diff --git a/src/editors/LevelEditor/Tools/Details/ESceneDOTools.h b/src/editors/LevelEditor/Tools/Details/ESceneDOTools.h new file mode 100644 index 00000000000..c81791bbe60 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Details/ESceneDOTools.h @@ -0,0 +1,173 @@ +#pragma once + +class CFrustum; +class CEditableObject; +struct Shader; + +struct SIndexDist +{ + u32 index; + float dist; + float dens[4]; + float cnt[4]; + SIndexDist() { ZeroMemory(this, sizeof(SIndexDist)); } +}; + +using SIndexDistVec = svector; + + +DEFINE_MAP(u32, DOVec, ColorIndexMap, ColorIndexPairIt); + +#define DETAIL_SLOT_SIZE_2 DETAIL_SLOT_SIZE * 0.5f +#define DETAIL_SLOT_RADIUS DETAIL_SLOT_SIZE * 0.7071f + +class EDetailManager : public CDetailManager, + public ESceneToolBase +// ,public pureDeviceCreate, +// public pureDeviceDestroy +{ + friend class TfrmDOShuffle; + typedef ESceneToolBase inherited; + + enum + { + flBaseTextureDraw = (1 << 31), + flBaseTextureBlended = (1 << 30), + flSlotBoxesDraw = (1 << 29), + flObjectsDraw = (1 << 28), + }; + Flags32 m_Flags; + + enum + { + flRTGenerateBaseMesh = (1 << 0) + }; + Flags32 m_RTFlags; + + ObjectList m_SnapObjects; + + Fbox m_BBox; + + IC u32 toSlotX(float x) { return static_cast(x / DETAIL_SLOT_SIZE + 0.5f) + dtH.x_offs(); } + IC u32 toSlotZ(float z) { return static_cast(z / DETAIL_SLOT_SIZE + 0.5f) + dtH.z_offs(); } + IC float fromSlotX(int x) { return (x - dtH.x_offs()) * DETAIL_SLOT_SIZE + DETAIL_SLOT_SIZE_2; } + IC float fromSlotZ(int z) { return (z - dtH.z_offs()) * DETAIL_SLOT_SIZE + DETAIL_SLOT_SIZE_2; } + + void UpdateSlotBBox(int x, int z, DetailSlot &slot); + + void GetSlotRect(Frect &rect, int sx, int sz); + void GetSlotTCRect(Irect &rect, int sx, int sz); + u8 GetRandomObject(u32 color_index); + u8 GetObject(ColorIndexPairIt &CI, u8 id); + + void CalcClosestCount(int part, const Fcolor &C, SIndexDistVec &best); + void FindClosestIndex(const Fcolor &C, SIndexDistVec &best); + + DetailSlot &GetSlot(u32 sx, u32 sz); + + void OnDensityChange(PropValue *prop); + void OnBaseTextureChange(PropValue *prop); + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + // render part ----------------------------------------------------------------- + void InitRender(); + void RenderTexture(float alpha); + void InvalidateCache(); + // render part ----------------------------------------------------------------- +public: + ColorIndexMap m_ColorIndices; + U8Vec m_Selected; + CCustom2DProjector m_Base; + + void SaveColorIndices(IWriter &); + bool LoadColorIndices(IReader &); + +public: + EDetailManager(); + virtual ~EDetailManager(); + + virtual bool AllowEnabling() { return true; } + virtual BOOL AllowMouseStart() { return true; } + + // snap + virtual ObjectList *GetSnapList() { return &m_SnapObjects; } + virtual void UpdateSnapList(){}; + + // selection manipulate + virtual int RaySelect(int flag, float &distance, const Fvector &start, const Fvector &direction, BOOL bDistanceOnly); + virtual int FrustumSelect(int flag, const CFrustum &frustum); + virtual void SelectObjects(bool flag); + virtual void InvertSelection(); + virtual void RemoveSelection() {} + virtual int SelectionCount(bool testflag); + virtual void ShowObjects(bool flag, bool bAllowSelectionFlag = false, bool bSelFlag = true) {} + + virtual void Clear(bool bSpecific = false); + + // definition + IC LPCSTR ClassName() { return "detail_object"; } + IC LPCSTR ClassDesc() { return "Detail Objects"; } + IC int RenderPriority() { return 10; } + + // validation + virtual bool Valid() { return dtSlots || objects.size() || m_Base.Valid() || m_SnapObjects.size(); } + virtual bool Validate(bool) { return true; } + + // events + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + virtual void OnSynchronize(); + virtual void OnObjectRemove(CCustomObject *O, bool bDeleting); + virtual void OnSceneUpdate(); + virtual void OnFrame(); + virtual void OnRender(int priority, bool strictB2F); + + // IO + virtual bool IsNeedSave() { return Valid(); } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool can_use_inifile() { return false; } + + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + virtual bool Export(LPCSTR fn); + + // properties + virtual void FillProp(LPCSTR pref, PropItemVec &items); + + // utils + virtual bool GetSummaryInfo(SSceneSummary *inf); + virtual void GetBBox(Fbox &bb, bool bSelOnly) {} + + // other + bool UpdateHeader(); + bool UpdateSlots(); + bool UpdateSlotObjects(int x, int z); + bool UpdateObjects(bool bUpdateTex, bool bUpdateSelectedOnly); + bool Initialize(); + bool Reinitialize(); + void InvalidateSlots(); + + EDetail *AppendDO(LPCSTR name, bool bTestUnique = true); + bool RemoveDO(LPCSTR name); + int RemoveDOs(); + DetailIt FindDOByNameIt(LPCSTR name); + EDetail *FindDOByName(LPCSTR name); + + void RemoveColorIndices(); + void AppendIndexObject(u32 color, LPCSTR name, bool bTestUnique = true); + EDetail *FindObjectInColorIndices(u32 index, LPCSTR name); + void ExportColorIndices(LPCSTR fname); + bool ImportColorIndices(LPCSTR fname); + + void ClearColorIndices(); + void ClearSlots(); + void ClearBase(); +}; diff --git a/src/editors/LevelEditor/Tools/Details/ESceneDOTools_Controls.cpp b/src/editors/LevelEditor/Tools/Details/ESceneDOTools_Controls.cpp new file mode 100644 index 00000000000..7f948e268cb --- /dev/null +++ b/src/editors/LevelEditor/Tools/Details/ESceneDOTools_Controls.cpp @@ -0,0 +1,15 @@ +#include "stdafx.h" + +void EDetailManager::CreateControls() +{ + AddControl(xr_new(estDefault, etaSelect, this)); + // frame + pForm = xr_new(); + ((UIDOTool *)pForm)->DM = this; +} +//---------------------------------------------------- + +void EDetailManager::RemoveControls() +{ + inherited::RemoveControls(); +} diff --git a/src/editors/LevelEditor/Tools/Details/ESceneDOTools_Generate.cpp b/src/editors/LevelEditor/Tools/Details/ESceneDOTools_Generate.cpp new file mode 100644 index 00000000000..bb9cb66ca7e --- /dev/null +++ b/src/editors/LevelEditor/Tools/Details/ESceneDOTools_Generate.cpp @@ -0,0 +1,598 @@ +#include "stdafx.h" +#include + +static Fvector down_vec = {0.f, -1.f, 0.f}; +static Fvector left_vec = {-1.f, 0.f, 0.f}; +static Fvector right_vec = {1.f, 0.f, 0.f}; +static Fvector fwd_vec = {0.f, 0.f, 1.f}; +static Fvector back_vec = {0.f, 0.f, -1.f}; + +static CRandom DetailRandom(0x26111975); + +DetailSlot &EDetailManager::GetSlot(u32 sx, u32 sz) +{ + VERIFY(sx < dtH.x_size()); + VERIFY(sz < dtH.z_size()); + return dtSlots[sz * dtH.x_size() + sx]; +} + +void EDetailManager::FindClosestIndex(const Fcolor &C, SIndexDistVec &best) +{ + u32 index; + float dist = flt_max; + Fcolor src; + float inv_a = 1 - C.a; + bool bRes = false; + ColorIndexPairIt S = m_ColorIndices.begin(); + ColorIndexPairIt E = m_ColorIndices.end(); + ColorIndexPairIt it = S; + for (; it != E; it++) + { + src.set(it->first); + float d = inv_a + sqrtf((C.r - src.r) * (C.r - src.r) + (C.g - src.g) * (C.g - src.g) + (C.b - src.b) * (C.b - src.b)); + if (d < dist) + { + dist = d; + index = it->first; + bRes = true; + } + } + + if (bRes) + { + if (best.size() < 4) + { + bool bFound = false; + for (u32 k = 0; k < best.size(); k++) + { + if (best[k].index == index) + { + if (dist < best[k].dist) + { + best[k].dist = dist; + best[k].index = index; + } + bFound = true; + break; + } + } + if (!bFound) + { + best.inc(); + best[best.size() - 1].dist = dist; + best[best.size() - 1].index = index; + } + } + else + { + int i = -1; + float dd = flt_max; + bool bFound = false; + for (int k = 0; k < 4; k++) + { + float d = dist - best[k].dist; + if ((d < 0) && (d < dd)) + { + i = k; + dd = d; + } + if (best[k].index == index) + { + if (dist < best[k].dist) + { + best[k].dist = dist; + best[k].index = index; + } + bFound = true; + break; + } + } + if (!bFound && (i >= 0)) + { + best[i].dist = dist; + best[i].index = index; + } + } + } +} + +bool EDetailManager::Initialize() +{ + if (m_SnapObjects.empty()) + { + ELog.DlgMsg(mtError, "Snap list empty!"); + return false; + } + if (!m_Base.Valid()) + { + ELog.DlgMsg(mtError, "Base texture empty!"); + return false; + } + if (!UpdateHeader()) + return false; + m_Base.CreateRMFromObjects(m_BBox, m_SnapObjects); + if (!UpdateSlots()) + return false; + if (!objects.empty() && !UpdateObjects(false, false)) + return false; + return true; +} + +bool EDetailManager::Reinitialize() +{ + if (m_SnapObjects.empty()) + { + ELog.DlgMsg(mtError, "Snap list empty!"); + return false; + } + if (!m_Base.Valid()) + { + ELog.DlgMsg(mtError, "Base texture empty!"); + return false; + } + InvalidateCache(); + + if (!UpdateHeader()) + return false; + m_Base.CreateRMFromObjects(m_BBox, m_SnapObjects); + //. if (!UpdateBaseTexture(0)) return false; + if (!UpdateSlots()) + return false; + if (!objects.empty() && !UpdateObjects(false, false)) + return false; + + return true; +} + +bool EDetailManager::UpdateHeader() +{ + // get bounding box + if (!Scene->GetBox(m_BBox, m_SnapObjects)) + return false; + + // fill header + int mn_x = iFloor(m_BBox.vMin.x / DETAIL_SLOT_SIZE); + int mn_z = iFloor(m_BBox.vMin.z / DETAIL_SLOT_SIZE); + int mx_x = iFloor(m_BBox.vMax.x / DETAIL_SLOT_SIZE) + 1; + int mx_z = iFloor(m_BBox.vMax.z / DETAIL_SLOT_SIZE) + 1; + dtH.offs_x = -mn_x; + dtH.offs_z = -mn_z; + dtH.size_x = mx_x - mn_x; + dtH.size_z = mx_z - mn_z; + return true; +} + +#define EPS_L_VAR 0.0012345f +void EDetailManager::UpdateSlotBBox(int sx, int sz, DetailSlot &slot) +{ + Fbox bbox; + Frect rect; + GetSlotRect(rect, sx, sz); + bbox.vMin.set(rect.x1, m_BBox.vMin.y, rect.y1); + bbox.vMax.set(rect.x2, m_BBox.vMax.y, rect.y2); + + SBoxPickInfoVec pinf; + ETOOLS::box_options(0); + if (Scene->BoxPickObjects(bbox, pinf, &m_SnapObjects)) + { + bbox.grow(EPS_L_VAR); + Fplane frustum_planes[4]; + frustum_planes[0].build(bbox.vMin, left_vec); + frustum_planes[1].build(bbox.vMin, back_vec); + frustum_planes[2].build(bbox.vMax, right_vec); + frustum_planes[3].build(bbox.vMax, fwd_vec); + + CFrustum frustum; + frustum.CreateFromPlanes(frustum_planes, 4); + + float y_min = flt_max; + float y_max = flt_min; + for (SBoxPickInfoIt it = pinf.begin(); it != pinf.end(); it++) + { + for (int k = 0; k < (int)it->inf.size(); k++) + { + float range; + Fvector verts[3]; + it->e_obj->GetFaceWorld(it->s_obj->_Transform(), it->e_mesh, it->inf[k].id, verts); + sPoly sSrc(verts, 3); + sPoly sDest; + sPoly *sRes = frustum.ClipPoly(sSrc, sDest); + if (sRes) + { + for (u32 k = 0; k < sRes->size(); k++) + { + float H = (*sRes)[k].y; + if (H > y_max) + y_max = H + 0.03f; + if (H < y_min) + y_min = H - 0.03f; + } + slot.w_y(y_min, y_max - y_min); + slot.w_id(0, DetailSlot::ID_Empty); + slot.w_id(1, DetailSlot::ID_Empty); + slot.w_id(2, DetailSlot::ID_Empty); + slot.w_id(3, DetailSlot::ID_Empty); + } + } + } + } + else + { + ZeroMemory(&slot, sizeof(DetailSlot)); + slot.w_id(0, DetailSlot::ID_Empty); + slot.w_id(1, DetailSlot::ID_Empty); + slot.w_id(2, DetailSlot::ID_Empty); + slot.w_id(3, DetailSlot::ID_Empty); + } +} + +bool EDetailManager::UpdateSlots() +{ + // clear previous slots + xr_free(dtSlots); + dtSlots = xr_alloc(dtH.x_size() * dtH.z_size()); + + SPBItem* pb = UI->ProgressStart(static_cast(dtH.z_size() * dtH.z_size()), "Updating bounding boxes..."); + for (u32 z = 0; z < dtH.z_size(); z++) + { + for (u32 x = 0; x < dtH.x_size(); x++) + { + DetailSlot* slot = dtSlots + z * dtH.x_size() + x; + UpdateSlotBBox(x, z, *slot); + pb->Inc(); + } + } + UI->ProgressEnd(pb); + + m_Selected.resize(dtH.x_size() * dtH.z_size()); + + return true; +} + +void EDetailManager::GetSlotRect(Frect &rect, int sx, int sz) +{ + float x = fromSlotX(sx); + float z = fromSlotZ(sz); + rect.x1 = x - DETAIL_SLOT_SIZE_2 + EPS_L; + rect.y1 = z - DETAIL_SLOT_SIZE_2 + EPS_L; + rect.x2 = x + DETAIL_SLOT_SIZE_2 - EPS_L; + rect.y2 = z + DETAIL_SLOT_SIZE_2 - EPS_L; +} + +void EDetailManager::GetSlotTCRect(Irect &rect, int sx, int sz) +{ + Frect R; + GetSlotRect(R, sx, sz); + rect.x1 = m_Base.GetPixelUFromX(R.x1, m_BBox); + rect.x2 = m_Base.GetPixelUFromX(R.x2, m_BBox); + rect.y2 = m_Base.GetPixelVFromZ(R.y1, m_BBox); // v - координата флипнута + rect.y1 = m_Base.GetPixelVFromZ(R.y2, m_BBox); +} + +void EDetailManager::CalcClosestCount(int part, const Fcolor &C, SIndexDistVec &best) +{ + float dist = flt_max; + Fcolor src; + float inv_a = 1 - C.a; + int idx = -1; + + for (u32 k = 0; k < best.size(); k++) + { + src.set(best[k].index); + float d = inv_a + sqrtf((C.r - src.r) * (C.r - src.r) + (C.g - src.g) * (C.g - src.g) + (C.b - src.b) * (C.b - src.b)); + if (d < dist) + { + dist = d; + idx = k; + } + } + if (idx >= 0) + best[idx].cnt[part]++; +} + +u8 EDetailManager::GetRandomObject(u32 color_index) +{ + ColorIndexPairIt CI = m_ColorIndices.find(color_index); + R_ASSERT(CI != m_ColorIndices.end()); + int k = DetailRandom.randI(0, CI->second.size()); + DetailIt it = std::find(objects.begin(), objects.end(), CI->second[k]); + VERIFY(it != objects.end()); + return u8(it - objects.begin()); +} + +u8 EDetailManager::GetObject(ColorIndexPairIt &CI, u8 id) +{ + VERIFY(CI != m_ColorIndices.end()); + DetailIt it = std::find(objects.begin(), objects.end(), (CDetail *)CI->second[id]); + VERIFY(it != objects.end()); + return u8(it - objects.begin()); +} + +bool CompareWeightFunc(SIndexDist &d0, SIndexDist &d1) +{ + return d0.dist < d1.dist; +} + +struct best_rand +{ + CRandom gen; + best_rand(CRandom &A) { gen = A; } + int operator()(int n) { return gen.randI(n); } +}; + +bool EDetailManager::UpdateSlotObjects(int x, int z) +{ + srand(time(NULL)); + + DetailSlot* slot = dtSlots + z * dtH.x_size() + x; + Irect R; + GetSlotTCRect(R, x, z); + // ELog.Msg(mtInformation,"TC [%d,%d]-[%d,%d]",R.x1,R.y1,R.x2,R.y2); + SIndexDistVec best; + // find best color index + { + for (int v = R.y1; v <= R.y2; v++) + { + for (int u = R.x1; u <= R.x2; u++) + { + u32 clr; + if (m_Base.GetColor(clr, u, v)) + { + Fcolor C; + C.set(clr); + FindClosestIndex(C, best); + } + } + } + } + std::sort(best.begin(), best.end(), CompareWeightFunc); + // пройдем по 4 частям слота и определим плотность заполнения (учесть переворот V) + Irect P[4]; + float dx = float(R.x2 - R.x1) / 2.f; + float dy = float(R.y2 - R.y1) / 2.f; + + // 2 3 + // 0 1 + P[0].x1 = R.x1; + P[0].y1 = iFloor(R.y1 + dy + 0.501f); + P[0].x2 = iFloor(R.x1 + dx + .499f); + P[0].y2 = R.y2; + P[1].x1 = iFloor(R.x1 + dx + 0.501f); + P[1].y1 = iFloor(R.y1 + dy + 0.501f); + P[1].x2 = R.x2; + P[1].y2 = R.y2; + P[2].x1 = R.x1; + P[2].y1 = R.y1; + P[2].x2 = iFloor(R.x1 + dx + .499f); + P[2].y2 = iFloor(R.y1 + dy + .499f); + P[3].x1 = iFloor(R.x1 + dx + 0.501f); + P[3].y1 = R.y1; + P[3].x2 = R.x2; + P[3].y2 = iFloor(R.y1 + dx + .499f); + + for (int part = 0; part < 4; part++) + { + float alpha = 0; + int cnt = 0; + for (int v = P[part].y1; v <= P[part].y2; v++) + { + for (int u = P[part].x1; u <= P[part].x2; u++) + { + u32 clr; + if (m_Base.GetColor(clr, u, v)) + { + Fcolor C; + C.set(clr); + CalcClosestCount(part, C, best); + alpha += C.a; + cnt++; + } + } + } + alpha /= (cnt ? float(cnt) : 1); + alpha *= 0.5f; + for (u32 i = 0; i < best.size(); i++) + best[i].dens[part] = cnt ? (best[i].cnt[part] * alpha) / float(cnt) : 0; + } + + // fill empty slots + R_ASSERT(best.size()); + int id = -1; + u32 o_cnt = 0; + for (u32 i = 0; i < best.size(); i++) + o_cnt += m_ColorIndices[best[i].index].size(); + // равномерно заполняем пустые слоты + if (o_cnt > best.size()) + { + while (best.size() < 4) + { + do + { + id++; + if (id > 3) + id = 0; + } while (m_ColorIndices[best[id].index].size() <= 1); + best.push_back(SIndexDist()); + best.back() = best[id]; + if (best.size() == o_cnt) + break; + } + } + + // заполним палитру и установим Random'ы + // Msg("Slot: %d %d",x,z); + for (u32 k = 0; k < best.size(); k++) + { + // objects + ColorIndexPairIt CI = m_ColorIndices.find(best[k].index); + R_ASSERT(CI != m_ColorIndices.end()); + U8Vec elem; + elem.resize(CI->second.size()); + for (U8It b_it = elem.begin(); b_it != elem.end(); b_it++) + *b_it = u8(b_it - elem.begin()); + + std::random_device rd; + std::mt19937 g(rd()); + std::shuffle(elem.begin(), elem.end(), g); + + for (auto b_it = elem.begin(); b_it != elem.end(); b_it++) + { + bool bNotFound = true; + slot->w_id(k, GetObject(CI, *b_it)); + for (u32 j = 0; j < k; j++) + if (slot->r_id(j) == slot->r_id(k)) + { + bNotFound = false; + break; + } + if (bNotFound) + break; + } + + slot->color_editor(); + // density + float f = ((EDetail *)objects[slot->r_id(k)])->m_fDensityFactor; + + slot->palette[k].a0 = (u16)iFloor(best[k].dens[0] * f * 15.f + .5f); + slot->palette[k].a1 = (u16)iFloor(best[k].dens[1] * f * 15.f + .5f); + slot->palette[k].a2 = (u16)iFloor(best[k].dens[2] * f * 15.f + .5f); + slot->palette[k].a3 = (u16)iFloor(best[k].dens[3] * f * 15.f + .5f); + } + + // определим ID незаполненных слотов как пустышки + for (u32 k = best.size(); k < 4; k++) + slot->w_id(k, DetailSlot::ID_Empty); + return true; +} + +bool EDetailManager::UpdateObjects(bool bUpdateTex, bool bUpdateSelectedOnly) +{ + m_Base.ReloadImage(); + if (!m_Base.Valid()) + { + ELog.DlgMsg(mtError, "Invalid base texture!"); + return false; + } + if (objects.empty()) + { + ELog.DlgMsg(mtError, "Object list empty!"); + return false; + } + // update objects + SPBItem* pb = UI->ProgressStart(static_cast(dtH.x_size() * dtH.z_size()), "Updating objects..."); + for (u32 z = 0; z < dtH.z_size(); z++) + for (u32 x = 0; x < dtH.x_size(); x++) + { + if (!bUpdateSelectedOnly || (bUpdateSelectedOnly && m_Selected[z * dtH.x_size() + x])) + UpdateSlotObjects(x, z); + pb->Inc(); + } + UI->ProgressEnd(pb); + + InvalidateCache(); + + return true; +} + +CDetailManager::DetailIt EDetailManager::FindDOByNameIt(LPCSTR name) +{ + for (DetailIt it = objects.begin(); it != objects.end(); it++) + if (stricmp(((EDetail *)(*it))->GetName(), name) == 0) + return it; + return objects.end(); +} + +EDetail *EDetailManager::FindDOByName(LPCSTR name) +{ + DetailIt it = FindDOByNameIt(name); + return (it != objects.end()) ? (EDetail *)*it : 0; +} + +bool EDetailManager::RemoveDO(LPCSTR name) +{ + DetailIt it = FindDOByNameIt(name); + if (it != objects.end()) + { + xr_delete(*it); + objects.erase(it); + InvalidateSlots(); + return true; + } + else + return false; +} + +EDetail *EDetailManager::AppendDO(LPCSTR name, bool bTestUnique) +{ + EDetail *D = 0; + if (bTestUnique && (0 != (D = FindDOByName(name)))) + return D; + + D = xr_new(); + if (!D->Update(name)) + { + xr_delete(D); + return 0; + } + objects.push_back(D); + InvalidateCache(); + return D; +} + +void EDetailManager::InvalidateSlots() +{ + int slot_cnt = dtH.x_size() * dtH.z_size(); + for (int k = 0; k < slot_cnt; k++) + { + DetailSlot *it = &dtSlots[k]; + it->w_id(0, DetailSlot::ID_Empty); + it->w_id(1, DetailSlot::ID_Empty); + it->w_id(2, DetailSlot::ID_Empty); + it->w_id(3, DetailSlot::ID_Empty); + } + InvalidateCache(); +} + +int EDetailManager::RemoveDOs() +{ + int cnt = 0; + for (DetailIt it = objects.begin(); it != objects.end(); it++) + xr_delete(*it); + cnt = objects.size(); + objects.clear(); + return cnt; +} + +void EDetailManager::RemoveColorIndices() +{ + m_ColorIndices.clear(); +} + +EDetail *EDetailManager::FindObjectInColorIndices(u32 index, LPCSTR name) +{ + ColorIndexPairIt CI = m_ColorIndices.find(index); + if (CI != m_ColorIndices.end()) + { + DOVec &lst = CI->second; + for (DOIt it = lst.begin(); it != lst.end(); it++) + if (stricmp((*it)->GetName(), name) == 0) + return *it; + } + return 0; +} + +void EDetailManager::AppendIndexObject(u32 color, LPCSTR name, bool bTestUnique) +{ + if (bTestUnique) + { + EDetail *DO = FindObjectInColorIndices(color, name); + if (DO) + m_ColorIndices[color].push_back(DO); + } + else + { + EDetail *DO = FindDOByName(name); + R_ASSERT(DO); + m_ColorIndices[color].push_back(DO); + } +} diff --git a/src/editors/LevelEditor/Tools/Details/ESceneDOTools_Pick.cpp b/src/editors/LevelEditor/Tools/Details/ESceneDOTools_Pick.cpp new file mode 100644 index 00000000000..f7a8d9730b4 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Details/ESceneDOTools_Pick.cpp @@ -0,0 +1,120 @@ +#include "stdafx.h" + +int EDetailManager::RaySelect(int flag, float &dist, const Fvector &start, const Fvector &direction, BOOL bDistanceOnly) +{ + // box selected only + + if (!m_Flags.is(flSlotBoxesDraw)) + return 0; + + float fx, fz; + Fbox bbox; + Fvector P; + int sx = -1, sz = -1; + + int count = 0; + + for (u32 z = 0; z < dtH.z_size(); z++) + { + fz = fromSlotZ(z); + for (u32 x = 0; x < dtH.x_size(); x++) + { + DetailSlot* slot = dtSlots + z * dtH.z_size() + x; + fx = fromSlotX(x); + bbox.vMin.set(fx - DETAIL_SLOT_SIZE_2, slot->r_ybase(), fz - DETAIL_SLOT_SIZE_2); + bbox.vMax.set(fx + DETAIL_SLOT_SIZE_2, slot->r_ybase() + slot->r_yheight(), fz + DETAIL_SLOT_SIZE_2); + if (bbox.Pick2(start, direction, P)) + { + float d = start.distance_to(P); + if (d < dist) + { + dist = d; + sx = x; + sz = z; + } + } + } + } + if ((sx >= 0) || (sz >= 0)) + { + if (!bDistanceOnly) + { + if (flag == -1) + m_Selected[sz * dtH.x_size() + sx] = !m_Selected[sz * dtH.x_size() + sx]; + else + m_Selected[sz * dtH.x_size() + sx] = (u8)flag; + count++; + UI->RedrawScene(); + } + } + return count; +} + +int EDetailManager::FrustumSelect(int flag, const CFrustum &frustum) +{ + // box selected only + + if (!m_Flags.is(flSlotBoxesDraw)) + return 0; + + int count = 0; + + float fx, fz; + Fbox bbox; + for (u32 z = 0; z < dtH.z_size(); z++) + { + fz = fromSlotZ(z); + for (u32 x = 0; x < dtH.x_size(); x++) + { + DetailSlot *slot = dtSlots + z * dtH.x_size() + x; + fx = fromSlotX(x); + + bbox.vMin.set(fx - DETAIL_SLOT_SIZE_2, slot->r_ybase(), fz - DETAIL_SLOT_SIZE_2); + bbox.vMax.set(fx + DETAIL_SLOT_SIZE_2, slot->r_ybase() + slot->r_yheight(), fz + DETAIL_SLOT_SIZE_2); + u32 mask = 0xff; + bool bRes = !!frustum.testAABB(bbox.data(), mask); + if (bRes) + { + if (flag == -1) + m_Selected[z * dtH.x_size() + x] = !m_Selected[z * dtH.x_size() + x]; + else + m_Selected[z * dtH.x_size() + x] = (u8)flag; + + count++; + } + } + } + UI->RedrawScene(); + return count; +} + +void EDetailManager::SelectObjects(bool flag) +{ + // for (int i=0; i ObjectList; +typedef ObjectList::iterator ObjectIt; +typedef xr_map ObjectMap; +typedef ObjectMap::iterator ObjectPairIt; + +#endif diff --git a/src/editors/LevelEditor/Tools/FogVolume/ESceneFogVolumeTools.cpp b/src/editors/LevelEditor/Tools/FogVolume/ESceneFogVolumeTools.cpp new file mode 100644 index 00000000000..0b8e3d830a2 --- /dev/null +++ b/src/editors/LevelEditor/Tools/FogVolume/ESceneFogVolumeTools.cpp @@ -0,0 +1,294 @@ +#include "stdafx.h" + +static const u16 FOG_VOL_TOOLS_VERSION = 0x0000; +static const u16 FOG_VOL_VERSION = 0x0002; + +enum +{ + TOOL_CHUNK_VERSION = 0x1001ul, + OBJ_CHUNK_VERSION = 0x1002ul, + OBJ_CHUNK_DATA = 0x1003ul +}; + +xr_token fog_vol_type[] = { + {"Emitter", fvEmitter}, + {"Occlusion", fvOcclusion}, + {NULL, 0}, +}; + +void ESceneFogVolumeTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); + pForm = xr_new(); + ((UIFogVolTool *)pForm)->ParentTools = this; +} + +void ESceneFogVolumeTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +void ESceneFogVolumeTool::Clear(bool bSpecific) +{ + inherited::Clear(bSpecific); + m_group_counter = 0; +} + +CCustomObject *ESceneFogVolumeTool::CreateObject(LPVOID data, LPCSTR name) +{ + + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + + return O; +} + +bool ESceneFogVolumeTool::LoadStream(IReader &F) +{ + u16 version = 0; + if (F.r_chunk(TOOL_CHUNK_VERSION, &version)) + if (version != FOG_VOL_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + if (!inherited::LoadStream(F)) + return false; + return true; +} + +void ESceneFogVolumeTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + F.w_chunk(TOOL_CHUNK_VERSION, (u16 *)&FOG_VOL_TOOLS_VERSION, sizeof(FOG_VOL_TOOLS_VERSION)); +} + +bool ESceneFogVolumeTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(TOOL_CHUNK_VERSION, &version)); + if (version != FOG_VOL_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} + +void ESceneFogVolumeTool::SaveSelection(IWriter &F) +{ + F.w_chunk(TOOL_CHUNK_VERSION, (u16 *)&FOG_VOL_TOOLS_VERSION, sizeof(FOG_VOL_TOOLS_VERSION)); + + inherited::SaveSelection(F); +} + +bool ESceneFogVolumeTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + if (version != FOG_VOL_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + + return true; +} + +void ESceneFogVolumeTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + ini.w_u32("main", "version", FOG_VOL_TOOLS_VERSION); +} + +void ESceneFogVolumeTool::GroupSelected() +{ + ++m_group_counter; + + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); ++it) + { + if ((*it)->Selected()) + { + EFogVolume *fv = (EFogVolume *)(*it); + fv->m_group_id = m_group_counter; + } + } +} + +void ESceneFogVolumeTool::UnGroupCurrent() +{ + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); ++it) + { + if ((*it)->Selected()) + { + EFogVolume *fv = (EFogVolume *)(*it); + fv->m_group_id = u32(-1); + } + } +} + +void ESceneFogVolumeTool::RegisterGroup(u32 group) +{ + m_group_counter = _max(m_group_counter, group); +} + +void ESceneFogVolumeTool::Selected(EFogVolume *fv) +{ + u32 grp = fv->m_group_id; + bool b_sel = !!fv->Selected(); + + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); ++it) + { + EFogVolume *fv_it = (EFogVolume *)(*it); + + if (b_sel && (fv_it->m_group_id == grp) && (grp != u32(-1))) + { + fv_it->m_DrawEdgeColor = 0xFFFF2020; + } + else + { + fv_it->m_DrawEdgeColor = 0xFF202020; + } + } +} + +//--------------------------------------- +EFogVolume::EFogVolume(LPVOID data, LPCSTR name) + : CEditShape(data, name) +{ + Construct(data); +} + +void EFogVolume::Construct(LPVOID data) +{ + FClassID = OBJCLASS_FOG_VOL; + m_volumeType = fvEmitter; + m_group_id = u32(-1); + m_volume_profile = "environment\\fog\\default.ltx"; + add_box(Fidentity); + SetDrawColor(0x205050FF, 0xFF202020); +} + +EFogVolume::~EFogVolume() +{ +} + +void EFogVolume::OnUpdateTransform() +{ + inherited::OnUpdateTransform(); +} + +bool EFogVolume::LoadLTX(CInifile &ini, LPCSTR sect_name) +{ + u32 version = ini.r_u32(sect_name, "version"); + + inherited::LoadLTX(ini, sect_name); + + if (version > 0) + { + m_volumeType = ini.r_u8(sect_name, "folume_type"); + m_group_id = ini.r_u32(sect_name, "group_id"); + } + if (version > 1 && m_volumeType == fvEmitter) + m_volume_profile = ini.r_string(sect_name, "profile"); + + OnChangeEnvs(NULL); + + return true; +} + +void EFogVolume::SaveLTX(CInifile &ini, LPCSTR sect_name) +{ + inherited::SaveLTX(ini, sect_name); + + ini.w_u32(sect_name, "version", FOG_VOL_VERSION); + ini.w_u8(sect_name, "folume_type", m_volumeType); + ini.w_u32(sect_name, "group_id", m_group_id); + + if (m_volumeType == fvEmitter) + ini.w_string(sect_name, "profile", m_volume_profile.c_str()); +} + +bool EFogVolume::LoadStream(IReader &F) +{ + u16 version = 0; + + R_ASSERT(F.r_chunk(OBJ_CHUNK_VERSION, &version)); + + inherited::LoadStream(F); + + if (F.find_chunk(OBJ_CHUNK_DATA)) + { + m_volumeType = F.r_u8(); + m_group_id = F.r_u32(); + } + if (version > 1 && m_volumeType == fvEmitter) + F.r_stringZ(m_volume_profile); + + OnChangeEnvs(NULL); + return true; +} + +void EFogVolume::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.open_chunk(OBJ_CHUNK_VERSION); + F.w_u16(FOG_VOL_VERSION); + F.close_chunk(); + + F.open_chunk(OBJ_CHUNK_DATA); + F.w_u8(m_volumeType); + F.w_u32(m_group_id); + if (m_volumeType == fvEmitter) + F.w_stringZ(m_volume_profile.c_str()); + + F.close_chunk(); +} + +void EFogVolume::OnChangeEnvs(PropValue *prop) +{ + if (m_volumeType == fvEmitter) + SetDrawColor(0x205050FF, 0xFF202020); + else if (m_volumeType == fvOcclusion) + SetDrawColor(0x2050A050, 0xFF202020); + + ((ESceneFogVolumeTool *)FParentTools)->RegisterGroup(m_group_id); + + LTools->UpdateProperties(FALSE); +} + +void EFogVolume::FillProp(LPCSTR pref, PropItemVec &values) +{ + inherited::FillProp(pref, values); + + PropValue *P; + P = PHelper().CreateToken8(values, PrepareKey(pref, "VolumeType"), &m_volumeType, fog_vol_type); + P->OnChangeEvent.bind(this, &EFogVolume::OnChangeEnvs); + + if (m_volumeType == fvEmitter) + P = PHelper().CreateRText(values, PrepareKey(pref, "profile (ltx)"), &m_volume_profile); +} +//---------------------------------------------------- + +bool EFogVolume::GetSummaryInfo(SSceneSummary *inf) +{ + inherited::GetSummaryInfo(inf); + return true; +} + +void EFogVolume::OnSceneUpdate() +{ + inherited::OnSceneUpdate(); +} + +void EFogVolume::Select(int flag) +{ + inherited::Select(flag); + + if (Selected()) + ((ESceneFogVolumeTool *)FParentTools)->Selected(this); +} diff --git a/src/editors/LevelEditor/Tools/FogVolume/ESceneFogVolumeTools.h b/src/editors/LevelEditor/Tools/FogVolume/ESceneFogVolumeTools.h new file mode 100644 index 00000000000..1b010f47400 --- /dev/null +++ b/src/editors/LevelEditor/Tools/FogVolume/ESceneFogVolumeTools.h @@ -0,0 +1,73 @@ +#pragma once + +class EFogVolume; + +enum +{ + fvEmitter = 0, + fvOcclusion = 1, +}; + +class ESceneFogVolumeTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + +protected: + u32 m_group_counter; + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + ESceneFogVolumeTool() : ESceneCustomOTool(OBJCLASS_FOG_VOL) { ; } + // definition + IC LPCSTR ClassName() { return "fog_volume"; } + IC LPCSTR ClassDesc() { return "Scene fog volumes"; } + IC int RenderPriority() { return 11; } + + virtual void Clear(bool bSpecific = false); + // IO + virtual bool IsNeedSave() { return inherited::IsNeedSave(); } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); + + void GroupSelected(); + void UnGroupCurrent(); + void RegisterGroup(u32 group); + void Selected(EFogVolume *fv); +}; + +class EFogVolume : public CEditShape +{ + typedef CCustomObject inherited; + void OnChangeEnvs(PropValue *prop); + +public: + u8 m_volumeType; + u32 m_group_id; + shared_str m_volume_profile; + + EFogVolume(LPVOID data, LPCSTR name); + void Construct(LPVOID data); + virtual ~EFogVolume(); + virtual bool CanAttach() { return true; } + virtual void OnUpdateTransform(); + + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &ini, LPCSTR sect_name); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &ini, LPCSTR sect_name); + + virtual void FillProp(LPCSTR pref, PropItemVec &values); + virtual bool GetSummaryInfo(SSceneSummary *inf); + virtual void OnSceneUpdate(); + +protected: + virtual void Select(int flag); +}; diff --git a/src/editors/LevelEditor/Tools/Glow/ESceneGlowTools.cpp b/src/editors/LevelEditor/Tools/Glow/ESceneGlowTools.cpp new file mode 100644 index 00000000000..9b61e41443f --- /dev/null +++ b/src/editors/LevelEditor/Tools/Glow/ESceneGlowTools.cpp @@ -0,0 +1,27 @@ +#include "stdafx.h" + +void ESceneGlowTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); + m_Flags.zero(); +} + +void ESceneGlowTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +void ESceneGlowTool::FillProp(LPCSTR pref, PropItemVec &items) +{ + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Test Visibility"), &m_Flags, flTestVisibility); + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Draw Cross"), &m_Flags, flDrawCross); + inherited::FillProp(pref, items); +} + +CCustomObject *ESceneGlowTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Tools/Glow/ESceneGlowTools.h b/src/editors/LevelEditor/Tools/Glow/ESceneGlowTools.h new file mode 100644 index 00000000000..4f6004168b1 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Glow/ESceneGlowTools.h @@ -0,0 +1,43 @@ +#pragma once + +class ESceneGlowTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + friend class CGlow; + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + enum + { + flDrawCross = (1 << 30), + flTestVisibility = (1 << 31), + }; + Flags32 m_Flags; + +public: + ESceneGlowTool() : ESceneCustomOTool(OBJCLASS_GLOW) { ; } + // definition + IC LPCSTR ClassName() { return "glow"; } + IC LPCSTR ClassDesc() { return "Glow"; } + IC int RenderPriority() { return 20; } + + void FillProp(LPCSTR pref, PropItemVec &items); + + virtual void Clear(bool bSpecific = false) + { + inherited::Clear(bSpecific); + m_Flags.zero(); + }; + // IO + virtual bool IsNeedSave() { return true; } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); +}; diff --git a/src/editors/LevelEditor/Tools/Glow/ESceneGlowToolsIO.cpp b/src/editors/LevelEditor/Tools/Glow/ESceneGlowToolsIO.cpp new file mode 100644 index 00000000000..0a87ec11bae --- /dev/null +++ b/src/editors/LevelEditor/Tools/Glow/ESceneGlowToolsIO.cpp @@ -0,0 +1,90 @@ +#include "stdafx.h" + +// chunks +static const u16 GLOW_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, + CHUNK_FLAGS = 0x1002ul, +}; + +bool ESceneGlowTool::LoadLTX(CInifile &ini) +{ + u16 version = ini.r_u32("main", "glow_tool_version"); + + if (version != GLOW_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + if (!inherited::LoadLTX(ini)) + return false; + + m_Flags.assign(ini.r_u32("main", "flags")); + + return true; +} + +void ESceneGlowTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + + ini.w_u32("main", "glow_tool_version", GLOW_TOOLS_VERSION); + ini.w_u32("main", "flags", m_Flags.get()); +} + +bool ESceneGlowTool::LoadStream(IReader &F) +{ + u16 version = 0; + if (F.r_chunk(CHUNK_VERSION, &version)) + if (version != GLOW_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + if (!inherited::LoadStream(F)) + return false; + + if (F.find_chunk(CHUNK_FLAGS)) + m_Flags.assign(F.r_u32()); + + return true; +} +//---------------------------------------------------- + +void ESceneGlowTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.w_chunk(CHUNK_VERSION, (u16 *)&GLOW_TOOLS_VERSION, sizeof(GLOW_TOOLS_VERSION)); + + F.open_chunk(CHUNK_FLAGS); + F.w_u32(m_Flags.get()); + F.close_chunk(); +} +//---------------------------------------------------- + +bool ESceneGlowTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + if (version != GLOW_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} +//---------------------------------------------------- + +void ESceneGlowTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&GLOW_TOOLS_VERSION, sizeof(GLOW_TOOLS_VERSION)); + + inherited::SaveSelection(F); +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Tools/Group/ESceneGroupControls.cpp b/src/editors/LevelEditor/Tools/Group/ESceneGroupControls.cpp new file mode 100644 index 00000000000..7a4eaf201a1 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Group/ESceneGroupControls.cpp @@ -0,0 +1,37 @@ +#include "stdafx.h" + +TUI_ControlGroupAdd::TUI_ControlGroupAdd(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} + +bool TUI_ControlGroupAdd::AfterAppendCallback(TShiftState Shift, CCustomObject *obj) +{ + bool result = false; + ESceneGroupTool *ot = dynamic_cast(parent_tool); + if (ot->GetCurrentObject()) + { + CGroupObject *group = dynamic_cast(obj); + R_ASSERT(group); + LPCSTR short_name = ot->GetCurrentObject(); + result = group->SetReference(short_name); + if (result) + { + string256 namebuffer; + Scene->GenObjectName(OBJCLASS_GROUP, namebuffer, short_name); + group->SetName(namebuffer); + } + } + return result; +} +bool TUI_ControlGroupAdd::Start(TShiftState Shift) +{ + DefaultAddObject(Shift, 0, TAfterAppendCallback(this, &TUI_ControlGroupAdd::AfterAppendCallback)); + return false; +} +void TUI_ControlGroupAdd::Move(TShiftState _Shift) +{ +} +bool TUI_ControlGroupAdd::End(TShiftState _Shift) +{ + return true; +} diff --git a/src/editors/LevelEditor/Tools/Group/ESceneGroupControls.h b/src/editors/LevelEditor/Tools/Group/ESceneGroupControls.h new file mode 100644 index 00000000000..7100782a496 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Group/ESceneGroupControls.h @@ -0,0 +1,13 @@ +#pragma once + +class TUI_ControlGroupAdd : public TUI_CustomControl +{ + bool AfterAppendCallback(TShiftState Shift, CCustomObject *obj); + +public: + TUI_ControlGroupAdd(int st, int act, ESceneToolBase *parent); + virtual ~TUI_ControlGroupAdd() {} + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); +}; diff --git a/src/editors/LevelEditor/Tools/Group/ESceneGroupTools.cpp b/src/editors/LevelEditor/Tools/Group/ESceneGroupTools.cpp new file mode 100644 index 00000000000..e59a92b2019 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Group/ESceneGroupTools.cpp @@ -0,0 +1,316 @@ +#include "stdafx.h" + +void ESceneGroupTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); + AddControl(xr_new(estDefault, etaAdd, this)); + // frame + pForm = xr_new(); + ((UIGroupTool *)pForm)->ParentTools = this; +} + +void ESceneGroupTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +void ESceneGroupTool::UngroupObjects(bool bUndo) +{ + ObjectList lst = m_Objects; + int sel_cnt = 0; + if (!lst.empty()) + { + bool bModif = false; + for (ObjectIt it = lst.begin(); it != lst.end(); ++it) + { + if ((*it)->Selected()) + { + sel_cnt++; + CGroupObject *obj = dynamic_cast(*it); + VERIFY(obj); + if (obj->CanUngroup(true)) + { + obj->UngroupObjects(); + Scene->RemoveObject(obj, false, true); + xr_delete(obj); + bModif = true; + } + else + ELog.DlgMsg(mtError, "Can't ungroup object: '%s'.", obj->GetName()); + } + } + if (bUndo && bModif) + Scene->UndoSave(); + } + if (0 == sel_cnt) + ELog.Msg(mtError, "Nothing selected."); +} +//---------------------------------------------------- + +BOOL ESceneGroupTool::_RemoveObject(CCustomObject *object) +{ + inherited::_RemoveObject(object); + + CGroupObject *go = dynamic_cast(object); + go->Clear1(); + return TRUE; +} + +void ESceneGroupTool::GroupObjects(bool bUndo) +{ + string256 namebuffer; + Scene->GenObjectName(OBJCLASS_GROUP, namebuffer); + CGroupObject *group = xr_new((LPVOID)0, namebuffer); + + // validate objects + ObjectList lst; + if (Scene->GetQueryObjects(lst, OBJCLASS_DUMMY, 1, 1, 0)) + group->GroupObjects(lst); + + if (group->ObjectInGroupCount()) + { + ELog.DlgMsg(mtInformation, "Group '%s' successfully created.\nContain %d object(s)", group->GetName(), group->ObjectInGroupCount()); + Scene->AppendObject(group, bUndo); + } + else + { + ELog.DlgMsg(mtError, "Group can't be created."); + xr_delete(group); + } +} + +void ESceneGroupTool::CenterToGroup() +{ + ObjectList &lst = m_Objects; + if (!lst.empty()) + { + for (ObjectIt it = lst.begin(); it != lst.end(); ++it) + ((CGroupObject *)(*it))->UpdatePivot(0, true); + + Scene->UndoSave(); + } +} +//---------------------------------------------------- + +void FillGroupItems(ChooseItemVec &items, void *param) +{ + CGroupObject *group = (CGroupObject *)param; + ObjectList grp_lst; + group->GetObjects(grp_lst); + + for (ObjectIt it = grp_lst.begin(); it != grp_lst.end(); ++it) + items.push_back(SChooseItem((*it)->GetName(), "")); +} +void ESceneGroupTool::OnDrawUI() +{ + if ((*m_ChooseIt)->Selected()) + { + if (UIChooseForm::IsActive()) + { + bool ok; + xr_string name; + if (UIChooseForm::GetResult(ok, name)) + { + m_ChooseCnt++; + if (ok) + { + ((CGroupObject *)(*m_ChooseIt))->UpdatePivot(name.c_str(), false); + } + m_ChooseIt++; + } + UIChooseForm::Update(); + } + else + { + UIChooseForm::SelectItem(smCustom, 1, "", FillGroupItems, *m_ChooseIt); + } + } + else + { + m_ChooseIt++; + } + if (m_ChooseIt == m_Objects.end()) + { + if (0 == m_ChooseCnt) + ELog.Msg(mtError, "Nothing selected."); + else + Scene->UndoSave(); + EDevice.seqDrawUI.Remove(this); + } +} +void ESceneGroupTool::AlignToObject() +{ + m_ChooseIt = m_Objects.begin(); + m_ChooseCnt = 0; + EDevice.seqDrawUI.Add(this); +} +//---------------------------------------------------- + +CCustomObject *ESceneGroupTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} + +void ESceneGroupTool::ReloadRefsSelectedObject() +{ + ObjectList lst = m_Objects; + int sel_cnt = 0; + if (!lst.empty()) + { + string_path temp_file_name_sector, temp_file_name_portal; + GetTempFileName(FS.get_path(_temp_)->m_Path, "tmp_sector", 0, temp_file_name_sector); + Scene->SaveToolLTX(OBJCLASS_SECTOR, temp_file_name_sector); + + GetTempFileName(FS.get_path(_temp_)->m_Path, "tmp_portal", 0, temp_file_name_portal); + Scene->SaveToolLTX(OBJCLASS_PORTAL, temp_file_name_portal); + + bool bModif = false; + for (ObjectIt it = lst.begin(); it != lst.end(); ++it) + { + if ((*it)->Selected()) + { + sel_cnt++; + CGroupObject *obj = dynamic_cast(*it); + VERIFY(obj); + if (obj->UpdateReference(true)) + { + bModif = true; + } + else + { + ELog.Msg(mtError, "Can't reload group: '%s'.", obj->GetName()); + } + } + } + if (bModif) + Scene->UndoSave(); + + Scene->LoadToolLTX(OBJCLASS_SECTOR, temp_file_name_sector); + Scene->LoadToolLTX(OBJCLASS_PORTAL, temp_file_name_portal); + } + if (0 == sel_cnt) + ELog.Msg(mtError, "Nothing selected."); +} +//---------------------------------------------------- + +void ESceneGroupTool::SaveSelectedObject() +{ + u32 scnt = SelectionCount(true); + if (scnt == 0) + { + ELog.DlgMsg(mtError, "No object(s) selected."); + return; + } + else if (scnt > 1) + { + if (mrYes != ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Process multiple objects?")) + return; + } + + CGroupObject *obj = 0; + // find single selected object + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); ++it) + { + if ((*it)->Selected()) + { + obj = dynamic_cast(*it); + + xr_string fn; + if (scnt == 1) + { + fn = obj->RefName(); + if (!EFS.GetSaveName(_groups_, fn)) + return; + } + else + { + string_path S; + FS.update_path(S, _groups_, obj->RefName()); + fn = S; + fn += ".group"; + } + + IWriter *W = FS.w_open(fn.c_str()); + if (W) + { + obj->SaveStream(*W); + FS.w_close(W); + } + else + ELog.DlgMsg(mtError, "Cant write file [%s]", fn.c_str()); + } + } +} +//---------------------------------------------------- + +void ESceneGroupTool::SetCurrentObject(LPCSTR nm) +{ + m_CurrentObject = nm; + /* TfraGroup* frame =(TfraGroup*)pFrame; + frame->lbCurrent->Caption = m_CurrentObject.c_str();*/ +} +//---------------------------------------------------- + +void ESceneGroupTool::OnActivate() +{ + inherited::OnActivate(); + /*TfraGroup* frame = (TfraGroup*)pFrame; + frame->lbCurrent->Caption = m_CurrentObject.c_str();*/ +} +//---------------------------------------------------- + +void ESceneGroupTool::MakeThumbnail() +{ + if (SelectionCount(true) == 1) + { + CGroupObject *object = 0; + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + { + if ((*it)->Selected()) + { + object = dynamic_cast(*it); + break; + } + } + VERIFY(object); + object->Select(false); + // save render params + Flags32 old_flag = psDeviceFlags; + // set render params + psDeviceFlags.set(rsStatistic | rsDrawGrid, FALSE); + + U32Vec pixels; + u32 w = 512, h = 512; + if (EDevice.MakeScreenshot(pixels, w, h)) + { + xr_string tex_name = ChangeFileExt(object->GetName(), ".thm"); + SStringVec lst; + + ObjectList grp_lst; + object->GetObjects(grp_lst); + + for (ObjectIt it = grp_lst.begin(); it != grp_lst.end(); ++it) + lst.push_back((*it)->GetName()); + + EGroupThumbnail tex(tex_name.c_str(), false); + tex.CreateFromData(pixels.data(), w, h, lst); + string_path fn; + FS.update_path(fn, _groups_, object->RefName()); + strcat(fn, ".group"); + tex.Save(FS.get_file_age(fn)); + } + else + { + ELog.DlgMsg(mtError, "Can't make screenshot."); + } + object->Select(true); + // restore render params + psDeviceFlags = old_flag; + } + else + { + ELog.DlgMsg(mtError, "Select 1 GroupObject."); + } +} diff --git a/src/editors/LevelEditor/Tools/Group/ESceneGroupTools.h b/src/editors/LevelEditor/Tools/Group/ESceneGroupTools.h new file mode 100644 index 00000000000..cf9e882dbc4 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Group/ESceneGroupTools.h @@ -0,0 +1,53 @@ +#pragma once + +class ESceneGroupTool : public ESceneCustomOTool, private pureDrawUI +{ + typedef ESceneCustomOTool inherited; + xr_string m_CurrentObject; + xr_vector m_stored_state; + ObjectIt m_ChooseIt; + int m_ChooseCnt; + virtual void OnDrawUI(); + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + ESceneGroupTool() : ESceneCustomOTool(OBJCLASS_GROUP) { ; } + // definition + IC LPCSTR ClassName() { return "group"; } + IC LPCSTR ClassDesc() { return "Group"; } + IC int RenderPriority() { return 1; } + + virtual void Clear(bool bSpecific = false) { inherited::Clear(bSpecific); } + // IO + virtual int SaveFileCount() const { return 2; } + virtual bool IsNeedSave() { return inherited::IsNeedSave(); } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + virtual void OnActivate(); + + // group function + void UngroupObjects(bool bUndo = true); + void GroupObjects(bool bUndo = true); + + void CenterToGroup(); + void AlignToObject(); + + void MakeThumbnail(); + + void SaveSelectedObject(); + void ReloadRefsSelectedObject(); + void SetCurrentObject(LPCSTR nm); + LPCSTR GetCurrentObject() { return m_CurrentObject.c_str(); } + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); + virtual BOOL _RemoveObject(CCustomObject *object); +}; diff --git a/src/editors/LevelEditor/Tools/Group/ESceneGroupToolsIO.cpp b/src/editors/LevelEditor/Tools/Group/ESceneGroupToolsIO.cpp new file mode 100644 index 00000000000..d1d3a5f794d --- /dev/null +++ b/src/editors/LevelEditor/Tools/Group/ESceneGroupToolsIO.cpp @@ -0,0 +1,78 @@ +#include "stdafx.h" + +// chunks +static const u16 GROUP_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, +}; + +bool ESceneGroupTool::LoadStream(IReader &F) +{ + u16 version = 0; + if (F.r_chunk(CHUNK_VERSION, &version)) + if (version != GROUP_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + if (!inherited::LoadStream(F)) + return false; + + return true; +} +//---------------------------------------------------- +bool ESceneGroupTool::LoadLTX(CInifile &ini) +{ + LPCSTR section = "main"; + u16 version = ini.r_u16(section, "version"); + + if (version != GROUP_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + if (!inherited::LoadLTX(ini)) + return false; + + return true; +} + +void ESceneGroupTool::SaveLTX(CInifile &ini, int id) +{ + LPCSTR section = "main"; + ini.w_u16(section, "version", GROUP_TOOLS_VERSION); + + inherited::SaveLTX(ini, id); +} + +void ESceneGroupTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.w_chunk(CHUNK_VERSION, (u16 *)&GROUP_TOOLS_VERSION, sizeof(GROUP_TOOLS_VERSION)); +} +//---------------------------------------------------- + +bool ESceneGroupTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + if (version != GROUP_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} +//---------------------------------------------------- + +void ESceneGroupTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&GROUP_TOOLS_VERSION, sizeof(GROUP_TOOLS_VERSION)); + + inherited::SaveSelection(F); +} diff --git a/src/editors/LevelEditor/Tools/Light/ESceneLightTools.cpp b/src/editors/LevelEditor/Tools/Light/ESceneLightTools.cpp new file mode 100644 index 00000000000..85472f76a02 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Light/ESceneLightTools.cpp @@ -0,0 +1,534 @@ +#include "stdafx.h" + +ESceneLightTool::ESceneLightTool() : ESceneCustomOTool(OBJCLASS_LIGHT) +{ + Clear(); + m_Flags.zero(); +} + +ESceneLightTool::~ESceneLightTool() +{ +} + +void ESceneLightTool::Clear(bool bSpecific) +{ + inherited::Clear(bSpecific); + + m_SunShadowDir.set(deg2rad(-25.f), deg2rad(292.f)); + + lcontrol_last_idx = 0; + lcontrols.clear(); + AppendLightControl(LCONTROL_STATIC); + AppendLightControl(LCONTROL_HEMI); + AppendLightControl(LCONTROL_SUN); + m_HemiControl = FindLightControl(LCONTROL_HEMI)->id; + m_Flags.zero(); +} +//------------------------------------------------------------------------------ + +void ESceneLightTool::SelectLightsForObject(CCustomObject *obj) +{ + for (u32 i = 0; i < frame_light.size(); i++) + { + CLight *l = frame_light[i]; + // if (obj->IsDynamic()&&!l->m_Flags.is(CLight::flAffectDynamic)) continue; + // if (!obj->IsDynamic()&&!l->m_Flags.is(CLight::flAffectStatic)) continue; + Fbox bb; + obj->GetBox(bb); + Fvector C; + float R; + bb.getsphere(C, R); + float d = C.distance_to(l->GetPosition()) - l->m_Range - R; + EDevice.LightEnable(i, (d < 0)); + } +} + +void ESceneLightTool::AppendFrameLight(CLight *src) +{ + Flight L; + ZeroMemory(&L, sizeof(Flight)); + L.type = static_cast(src->m_Type); + L.diffuse.mul_rgb(src->m_Color, src->m_Brightness); + L.specular.set(L.diffuse); + L.position.set(src->GetPosition()); + Fvector dir; + dir.setHP(src->GetRotation().y, src->GetRotation().x); + L.direction.set(dir); + L.range = src->m_Range; + L.attenuation0 = src->m_Attenuation0 + EPS_S; + L.attenuation1 = src->m_Attenuation1; + L.attenuation2 = src->m_Attenuation2; + L.phi = src->m_Cone; + L.falloff = 1.f; + EDevice.SetLight(frame_light.size(), L); + frame_light.push_back(src); +} + +void ESceneLightTool::BeforeRender() +{ + if (psDeviceFlags.is(rsLighting)) + { + int l_cnt = 0; + // set scene lights + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + { + CLight *l = (CLight *)(*_F); + l_cnt++; + if (l->Visible() && l->m_UseInD3D && l->m_Flags.is_any(ELight::flAffectDynamic | ELight::flAffectStatic)) + if (::Render->ViewBase.testSphere_dirty(l->GetPosition(), l->m_Range)) + AppendFrameLight(l); + } + // set sun + if (m_Flags.is(flShowSun)) + { + Flight L; + Fvector C; + // if (psDeviceFlags.is(rsEnvironment)){ + // C = g_pGamePersistent->Environment().CurrentEnv->sun_color; + // }else{ + C.set(1.f, 1.f, 1.f); + // } + L.direction.setHP(m_SunShadowDir.y, m_SunShadowDir.x); + L.diffuse.set(C.x, C.y, C.z, 1.f); + L.ambient.set(0.f, 0.f, 0.f, 0.f); + L.specular.set(C.x, C.y, C.z, 1.f); + L.type = Flight::Type::Directional; + EDevice.SetLight(frame_light.size(), L); + EDevice.LightEnable(frame_light.size(), TRUE); + } + // ambient + // if (psDeviceFlags.is(rsEnvironment)){ + // Fvector& V = g_pGamePersistent->Environment().CurrentEnv->ambient; + // Fcolor C; C.set(V.x,V.y,V.z,1.f); + // EDevice.SetRS (D3DRS_AMBIENT,C.get()); + // }else + EDevice.SetRS(D3DRS_AMBIENT, 0x00000000); + + EDevice.Statistic->dwTotalLight = l_cnt; + EDevice.Statistic->dwLightInScene = frame_light.size(); + } +} +//------------------------------------------------------------------------------ + +void ESceneLightTool::AfterRender() +{ + if (m_Flags.is(flShowSun)) + EDevice.LightEnable(frame_light.size(), FALSE); // sun - last light! + for (u32 i = 0; i < frame_light.size(); i++) + EDevice.LightEnable(i, FALSE); + frame_light.clear(); +} +//------------------------------------------------------------------------------ + +#define VIS_RADIUS 0.03f +void ESceneLightTool::OnRender(int priority, bool strictB2F) +{ + inherited::OnRender(priority, strictB2F); + if (m_Flags.is(flShowSun)) + { + if ((true == strictB2F) && (1 == priority)) + { + EDevice.SetShader(EDevice.m_WireShader); + RCache.set_xform_world(Fidentity); + Fvector dir; + dir.setHP(m_SunShadowDir.y, m_SunShadowDir.x); + Fvector p; + float fd = UI->ZFar() * 0.95f; + p.mad(EDevice.vCameraPosition, dir, -fd); + DU_impl.DrawPointLight(p, VIS_RADIUS * fd, 0x00FFE020); + DU_impl.DrawLineSphere(p, VIS_RADIUS * fd * 0.3f, 0x00FF3000, false); + } + } +} +//------------------------------------------------------------------------------ + +void ESceneLightTool::OnControlAppendClick(ButtonValue *sender, bool &bDataModified, bool &bSafe) +{ + AppendLightControl(GenLightControlName().c_str()); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + bDataModified = true; +} +//------------------------------------------------------------------------------ + +void ESceneLightTool::OnControlRenameRemoveClick(ButtonValue *V, bool &bDataModified, bool &bSafe) +{ + R_ASSERT(!"Выведено из эксплотации"); + /* xr_string item_name = V->Owner()->Item()->Text; + switch (V->btn_num){ + case 0:{ + xr_string new_name=item_name; + if (TfrmText::RunEditor(new_name,"Control name")){ + if (FindLightControl(new_name.c_str())){ + ELog.DlgMsg(mtError,"Duplicate name found."); + }else if (new_name.IsEmpty()||new_name.Pos("\\")){ + ELog.DlgMsg(mtError,"Invalid control name."); + }else{ + RTokenVecIt it = FindLightControlIt(item_name.c_str()); + it->rename (new_name.c_str()); + } + } + }break; + case 1: RemoveLightControl(item_name.c_str()); break; + } + ExecCommand(COMMAND_UPDATE_PROPERTIES); + bDataModified = true;*/ +} +//------------------------------------------------------------------------------ +void ESceneLightTool::FillProp(LPCSTR pref, PropItemVec &items) +{ + ButtonValue *B = 0; + // hemisphere + //. PHelper().CreateRToken32(items, PrepareKey(pref,"Common\\Hemisphere\\Light Control"), &m_HemiControl, &*lcontrols.begin(), lcontrols.size()); + + // sun + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Sun Shadow\\Visible"), &m_Flags, flShowSun); + PHelper().CreateAngle(items, PrepareKey(pref, "Common\\Sun Shadow\\Altitude"), &m_SunShadowDir.x, -PI_DIV_2, 0); + PHelper().CreateAngle(items, PrepareKey(pref, "Common\\Sun Shadow\\Longitude"), &m_SunShadowDir.y, 0, PI_MUL_2); + // light controls + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Controls\\Draw Name"), &m_Flags, flShowControlName); + PHelper().CreateCaption(items, PrepareKey(pref, "Common\\Controls\\Count"), shared_str().printf("%d", lcontrols.size())); + // B=PHelper().CreateButton(items,PHelper().PrepareKey(pref,"Common\\Controls\\Edit"), "Append", ButtonValue::flFirstOnly); + // B->OnBtnClickEvent = OnControlAppendClick; + RTokenVecIt _I = lcontrols.begin(); + RTokenVecIt _E = lcontrols.end(); + for (; _I != _E; _I++) + { + if (_I->equal(LCONTROL_HEMI) || _I->equal(LCONTROL_STATIC) || _I->equal(LCONTROL_SUN)) + { + PHelper().CreateCaption(items, PrepareKey(pref, "Common\\Controls\\System", *_I->name), ""); + } + else + { + B = PHelper().CreateButton(items, PrepareKey(pref, "Common\\Controls\\User", *_I->name), "Rename,Remove", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &ESceneLightTool::OnControlRenameRemoveClick); + } + } + inherited::FillProp(pref, items); +} +//------------------------------------------------------------------------------ + +xr_string ESceneLightTool::GenLightControlName() +{ + xr_string name; + int idx = 0; + do + { + name = make_string("control_%02d", idx++).c_str(); + } while (FindLightControl(name.c_str())); + return name; +} +//------------------------------------------------------------------------------ + +xr_rtoken *ESceneLightTool::FindLightControl(int id) +{ + RTokenVecIt _I = lcontrols.begin(); + RTokenVecIt _E = lcontrols.end(); + for (; _I != _E; _I++) + if (_I->id == id) + return &*_I; + return 0; +} +//------------------------------------------------------------------------------ + +RTokenVecIt ESceneLightTool::FindLightControlIt(LPCSTR name) +{ + RTokenVecIt _I = lcontrols.begin(); + RTokenVecIt _E = lcontrols.end(); + for (; _I != _E; _I++) + if (_I->equal(name)) + return _I; + return lcontrols.end(); +} +//------------------------------------------------------------------------------ + +void ESceneLightTool::AppendLightControl(LPCSTR nm, u32 *idx) +{ + xr_string name = nm; + _Trim(name); + if (name.empty()) + return; + if (FindLightControl(name.c_str())) + return; + lcontrols.push_back(xr_rtoken(name.c_str(), idx ? *idx : lcontrol_last_idx++)); +} +//------------------------------------------------------------------------------ + +void ESceneLightTool::RemoveLightControl(LPCSTR name) +{ + RTokenVecIt it = FindLightControlIt(name); + if (it != lcontrols.end()) + lcontrols.erase(it); +} +//------------------------------------------------------------------------------ + +bool ESceneLightTool::Validate(bool full_test) +{ + if (!inherited::Validate(full_test)) + return false; + bool bRes = !m_Objects.empty(); + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + { + CLight *L = dynamic_cast(*it); + if (!L->GetLControlName()) + { + bRes = false; + ELog.Msg(mtError, "%s: '%s' - Invalid light control.", ClassDesc(), L->GetName()); + } + } + return bRes; +} + +void ESceneLightTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); + // frame + pForm = xr_new(); +} + +void ESceneLightTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +CCustomObject *ESceneLightTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} +void ESceneLightTool::OnDrawUI() +{ + xr_string result; + bool ok = false; + if (UITextForm::GetResult(ok, result)) + { + if (ok) + { + if (FindLightControl(result.c_str())) + { + ELog.DlgMsg(mtError, "Duplicate name found."); + } + else if (result.empty() || result.find("\\") != result.npos) + { + ELog.DlgMsg(mtError, "Invalid control name."); + } + else + { + RTokenVecIt it = FindLightControlIt(result.c_str()); + it->rename(result.c_str()); + } + } + } + UITextForm::Update(); +} +//---------------------------------------------------- + +/* + m_D3D.direction.setHP(GetRotation().y,GetRotation().x); + if (D3DLIGHT_DIRECTIONAL==m_D3D.type) m_LensFlare.Update(m_D3D.direction, m_D3D.diffuse); + +//render + case D3DLIGHT_DIRECTIONAL: + if (Selected()) DU.DrawDirectionalLight( m_D3D.position, m_D3D.direction, VIS_RADIUS, DIR_SELRANGE, clr ); + else DU.DrawDirectionalLight( m_D3D.position, m_D3D.direction, VIS_RADIUS, DIR_RANGE, clr ); + break; +else if ((3==priority)&&(true==strictB2F)){ + if (D3DLIGHT_DIRECTIONAL==m_D3D.type) m_LensFlare.Render(); + } +// update + if (D3DLIGHT_DIRECTIONAL==m_D3D.type){ + m_LensFlare.Update(m_D3D.direction, m_D3D.diffuse); + m_LensFlare.DeleteShaders(); + m_LensFlare.CreateShaders(); + } +// load + m_LensFlare.Load(F); +// save + if (D3DLIGHT_DIRECTIONAL==m_D3D.type) m_LensFlare.Save(F); + + +void CLight:xr_token sun_quality[]={ + { "Low", 1 }, + { "Normal", 2 }, + { "Final", 3 }, + { 0, 0 } +}; + +:FillSunProp(LPCSTR pref, PropItemVec& items) +{ + CEditFlare& F = m_LensFlare; + PropValue* prop = 0; + PHelper().CreateToken (items, PHelper().PrepareKey(pref,"Sun\\Quality"), &m_SunQuality, sun_quality); + + PHelper().CreateFlag32 (items, PHelper().PrepareKey(pref,"Sun\\Source\\Enabled"), &F.m_Flags, CEditFlare::flSource); + PHelper().CreateFloat (items, PHelper().PrepareKey(pref,"Sun\\Source\\Radius"), &F.m_Source.fRadius, 0.f,10.f); + prop = PHelper().CreateTexture (items, PHelper().PrepareKey(pref,"Sun\\Source\\Texture"), F.m_Source.texture, sizeof(F.m_Source.texture)); + prop->OnChangeEvent = OnNeedUpdate; + + PHelper().CreateFlag32 (items, PHelper().PrepareKey(pref,"Sun\\Gradient\\Enabled"), &F.m_Flags, CEditFlare::flGradient); + PHelper().CreateFloat (items, PHelper().PrepareKey(pref,"Sun\\Gradient\\Radius"), &F.m_Gradient.fRadius, 0.f,100.f); + PHelper().CreateFloat (items, PHelper().PrepareKey(pref,"Sun\\Gradient\\Opacity"), &F.m_Gradient.fOpacity, 0.f,1.f); + prop = PHelper().CreateTexture (items, PHelper().PrepareKey(pref,"Sun\\Gradient\\Texture"), F.m_Gradient.texture, sizeof(F.m_Gradient.texture)); + prop->OnChangeEvent = OnNeedUpdate; + + PHelper().CreateFlag32 (items, PHelper().PrepareKey(pref,"Sun\\Flares\\Enabled"), &F.m_Flags, CEditFlare::flFlare); + for (CEditFlare::FlareIt it=F.m_Flares.begin(); it!=F.m_Flares.end(); it++){ + xr_string nm; nm.sprintf("%s\\Sun\\Flares\\Flare %d",pref,it-F.m_Flares.begin()); + PHelper().CreateFloat (items, PHelper().PrepareKey(nm.c_str(),"Radius"), &it->fRadius, 0.f,10.f); + PHelper().CreateFloat (items, PHelper().PrepareKey(nm.c_str(),"Opacity"), &it->fOpacity, 0.f,1.f); + PHelper().CreateFloat (items, PHelper().PrepareKey(nm.c_str(),"Position"), &it->fPosition, -10.f,10.f); + prop = PHelper().CreateTexture (items, PHelper().PrepareKey(nm.c_str(),"Texture"), it->texture, sizeof(it->texture)); + prop->OnChangeEvent = OnNeedUpdate; + } +} +//---------------------------------------------------- +void CLight::OnDeviceCreate() +{ + if (D3DLIGHT_DIRECTIONAL==m_D3D.type) m_LensFlare.DDLoad(); +} +void CLight::OnDeviceDestroy() +{ +// if (D3DLIGHT_DIRECTIONAL==m_D3D.type) + m_LensFlare.DDUnload(); +} +//---------------------------------------------------- + +//---------------------------------------------------- +// Edit Flare +//---------------------------------------------------- +CEditFlare::CEditFlare() +{ + m_Flags.set(flFlare|flSource|flGradient,TRUE); + // flares + m_Flares.resize (6); + FlareIt it=m_Flares.begin(); + it->fRadius=0.08f; it->fOpacity=0.18f; it->fPosition=1.3f; strcpy(it->texture,"fx\\fx_flare1"); it++; + it->fRadius=0.12f; it->fOpacity=0.12f; it->fPosition=1.0f; strcpy(it->texture,"fx\\fx_flare2"); it++; + it->fRadius=0.04f; it->fOpacity=0.30f; it->fPosition=0.5f; strcpy(it->texture,"fx\\fx_flare2"); it++; + it->fRadius=0.08f; it->fOpacity=0.24f; it->fPosition=-0.3f; strcpy(it->texture,"fx\\fx_flare2"); it++; + it->fRadius=0.12f; it->fOpacity=0.12f; it->fPosition=-0.6f; strcpy(it->texture,"fx\\fx_flare3"); it++; + it->fRadius=0.30f; it->fOpacity=0.12f; it->fPosition=-1.0f; strcpy(it->texture,"fx\\fx_flare1"); it++; + // source + strcpy(m_Source.texture,"fx\\fx_sun"); + m_Source.fRadius = 0.15f; + // gradient + strcpy(m_Gradient.texture,"fx\\fx_gradient"); + m_Gradient.fOpacity = 0.9f; + m_Gradient.fRadius = 4.f; +} + +void CEditFlare::Load(IReader& F){ + if (!F.find_chunk(FLARE_CHUNK_FLAG)) return; + + R_ASSERT(F.find_chunk(FLARE_CHUNK_FLAG)); + F.r (&m_Flags.flags,sizeof(m_Flags)); + + R_ASSERT(F.find_chunk(FLARE_CHUNK_SOURCE)); + F.r_stringZ (m_Source.texture); + m_Source.fRadius= F.r_float(); + + if (F.find_chunk(FLARE_CHUNK_GRADIENT2)){ + F.r_stringZ (m_Gradient.texture); + m_Gradient.fOpacity = F.r_float(); + m_Gradient.fRadius = F.r_float(); + }else{ + R_ASSERT(F.find_chunk(FLARE_CHUNK_GRADIENT)); + m_Gradient.fOpacity = F.r_float(); + } + + // flares + if (F.find_chunk(FLARE_CHUNK_FLARES2)){ + DeleteShaders(); + u32 deFCnt = F.r_u32(); VERIFY(deFCnt==6); + F.r (m_Flares.begin(),m_Flares.size()*sizeof(SFlare)); + for (FlareIt it=m_Flares.begin(); it!=m_Flares.end(); it++) it->hShader._clear(); + CreateShaders(); + } +} +//---------------------------------------------------- + +void CEditFlare::Save(IWriter& F) +{ + F.open_chunk (FLARE_CHUNK_FLAG); + F.w (&m_Flags.flags,sizeof(m_Flags)); + F.close_chunk (); + + F.open_chunk (FLARE_CHUNK_SOURCE); + F.w_stringZ (m_Source.texture); + F.w_float (m_Source.fRadius); + F.close_chunk (); + + F.open_chunk (FLARE_CHUNK_GRADIENT2); + F.w_stringZ (m_Gradient.texture); + F.w_float (m_Gradient.fOpacity); + F.w_float (m_Gradient.fRadius); + F.close_chunk (); + + F.open_chunk (FLARE_CHUNK_FLARES2); + F.w_u32 (m_Flares.size()); + F.w (m_Flares.begin(),m_Flares.size()*sizeof(SFlare)); + F.close_chunk (); +} +//---------------------------------------------------- + +void CEditFlare::Render() +{ + CLensFlare::Render(m_Flags.is(flSource),m_Flags.is(flFlare),m_Flags.is(flGradient)); +} +//---------------------------------------------------- + +void CEditFlare::DeleteShaders() +{ + CLensFlare::DDUnload(); +} + +void CEditFlare::CreateShaders() +{ + CLensFlare::DDLoad(); +} +//---------------------------------------------------- + + + xr_string suns; + for (ObjectIt it=lst.begin(); it!=lst.end(); it++){ + switch ((*it)->ClassID){ + case OBJCLASS_LIGHT:{ + CLight *l = (CLight *)(*it); + if (l->m_D3D.type==D3DLIGHT_DIRECTIONAL){ + if (suns.Length()) suns += ", "; + suns += l->Name; + pIni->w_fcolor (l->Name, "sun_color", l->m_D3D.diffuse); + pIni->w_fvector3(l->Name, "sun_dir", l->m_D3D.direction); + pIni->w_string (l->Name, "gradient", l->m_LensFlare.m_Flags.is(CLensFlare::flGradient)?"on":"off"); + pIni->w_string (l->Name, "source", l->m_LensFlare.m_Flags.is(CLensFlare::flSource)?"on":"off"); + pIni->w_string (l->Name, "flares", l->m_LensFlare.m_Flags.is(CLensFlare::flFlare)?"on":"off"); + pIni->w_float (l->Name, "gradient_opacity", l->m_LensFlare.m_Gradient.fOpacity); + pIni->w_string (l->Name, "gradient_texture", l->m_LensFlare.m_Gradient.texture); + pIni->w_float (l->Name, "gradient_radius", l->m_LensFlare.m_Gradient.fRadius); + pIni->w_string (l->Name, "source_texture", l->m_LensFlare.m_Source.texture); + pIni->w_float (l->Name, "source_radius", l->m_LensFlare.m_Source.fRadius); + xr_string FT=""; xr_string FR=""; xr_string FO=""; xr_string FP=""; + xr_string T=""; + int i=l->m_LensFlare.m_Flares.size(); + for (CEditFlare::FlareIt it = l->m_LensFlare.m_Flares.begin(); it!=l->m_LensFlare.m_Flares.end(); it++,i--){ + FT += it->texture; + T.sprintf("%.3f",it->fRadius); FR += T; + T.sprintf("%.3f",it->fOpacity); FO += T; + T.sprintf("%.3f",it->fPosition);FP += T; + if (i>1){FT+=","; FR+=","; FO+=","; FP+=",";} + } + pIni->w_string (l->Name, "flare_textures", FT.c_str()); + pIni->w_string (l->Name, "flare_radius", FR.c_str()); + pIni->w_string (l->Name, "flare_opacity", FO.c_str()); + pIni->w_string (l->Name, "flare_position", FP.c_str()); + } + }break; + case OBJCLASS_GROUP:{ + CGroupObject* group = (CGroupObject*)(*it); + bResult = ParseLTX(pIni,group->GetObjects(),group->Name); + }break; + } + if (!bResult) return FALSE; + if (suns.Length()) pIni->w_string("environment", "suns", suns.c_str()); + } +*/ diff --git a/src/editors/LevelEditor/Tools/Light/ESceneLightTools.h b/src/editors/LevelEditor/Tools/Light/ESceneLightTools.h new file mode 100644 index 00000000000..bbcc0dd69be --- /dev/null +++ b/src/editors/LevelEditor/Tools/Light/ESceneLightTools.h @@ -0,0 +1,94 @@ +#pragma once + +class CEditFlare : public CLensFlare +{ +public: + CEditFlare(); + void Load(IReader &F); + void Save(IWriter &F); + void Render(); + void DeleteShaders(); + void CreateShaders(); +}; + +class ESceneLightTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + friend class SceneBuilder; + friend class CLight; + +protected: + enum + { + flShowSun = (1 << 31), + flShowControlName = (1 << 30), + }; + Flags32 m_Flags; + // hemisphere + u32 m_HemiControl; + // sun + Fvector2 m_SunShadowDir; + + // run time + xr_vector frame_light; + void AppendFrameLight(CLight *L); + +protected: + // light control + int lcontrol_last_idx; + RTokenVec lcontrols; + void OnControlAppendClick(ButtonValue *sender, bool &bDataModified, bool &bSafe); + void OnControlRenameRemoveClick(ButtonValue *sender, bool &bDataModified, bool &bSafe); + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + ESceneLightTool(); + virtual ~ESceneLightTool(); + + virtual void Clear(bool bSpecific = false); + + // definition + IC LPCSTR ClassName() { return "light"; } + IC LPCSTR ClassDesc() { return "Light"; } + IC int RenderPriority() { return 10; } + + // IO + virtual bool IsNeedSave() { return true; } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + // utils + virtual bool Validate(bool full_build); + + virtual void BeforeRender(); + virtual void OnRender(int priority, bool strictB2F); + virtual void AfterRender(); + + void SelectLightsForObject(CCustomObject *obj); + + virtual void FillProp(LPCSTR pref, PropItemVec &items); + + xr_string GenLightControlName(); + xr_rtoken *FindLightControl(int id); + RTokenVecIt FindLightControlIt(LPCSTR name); + xr_rtoken *FindLightControl(LPCSTR name) + { + RTokenVecIt it = FindLightControlIt(name); + return it != lcontrols.end() ? &*it : 0; + } + void AppendLightControl(LPCSTR name, u32 *idx = 0); + void RemoveLightControl(LPCSTR name); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); + +private: + virtual void OnDrawUI(); +}; diff --git a/src/editors/LevelEditor/Tools/Light/ESceneLightToolsIO.cpp b/src/editors/LevelEditor/Tools/Light/ESceneLightToolsIO.cpp new file mode 100644 index 00000000000..c00f4d724e3 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Light/ESceneLightToolsIO.cpp @@ -0,0 +1,156 @@ +#include "stdafx.h" + +// chunks +static const u16 LIGHT_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, + CHUNK_LCONTROLS = 0x1002ul, + CHUNK_LCONTROLS_LAST = 0x1003ul, + CHUNK_FLAGS = 0x1004ul, + // CHUNK_HEMI = 0x1005ul, // obsolette + CHUNK_SUN_SHADOW = 0x1006ul, + CHUNK_HEMI2 = 0x1007ul, +}; + +bool ESceneLightTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + if (version != LIGHT_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + + m_Flags.assign(ini.r_u32("main", "flags")); + + m_SunShadowDir = ini.r_fvector2("main", "sun_shadow_dir"); + lcontrol_last_idx = ini.r_u32("main", "lcontrol_last_idx"); + + CInifile::Sect S = ini.r_section("lcontrols"); + auto it = S.Data.begin(); + auto it_e = S.Data.end(); + for (; it != it_e; ++it) + { + u32 idx = ini.r_u32("lcontrols", it->first.c_str()); + AppendLightControl(it->first.c_str(), &idx); + } + return true; +} + +void ESceneLightTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + + ini.w_u32("main", "version", LIGHT_TOOLS_VERSION); + ini.w_u32("main", "flags", m_Flags.get()); + + ini.w_fvector2("main", "sun_shadow_dir", m_SunShadowDir); + + ini.w_u32("main", "lcontrol_last_idx", lcontrol_last_idx); + + RTokenVecIt _I = lcontrols.begin(); + RTokenVecIt _E = lcontrols.end(); + for (; _I != _E; ++_I) + { + ini.w_u32("lcontrols", _I->name.c_str(), _I->id); + } +} + +bool ESceneLightTool::LoadStream(IReader &F) +{ + u16 version = 0; + if (F.r_chunk(CHUNK_VERSION, &version)) + if (version != LIGHT_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + if (!inherited::LoadStream(F)) + return false; + + if (F.find_chunk(CHUNK_FLAGS)) + m_Flags.assign(F.r_u32()); + + if (F.find_chunk(CHUNK_SUN_SHADOW)) + { + F.r_u8(); + F.r_fvector2(m_SunShadowDir); + } + + if (F.find_chunk(CHUNK_LCONTROLS_LAST)) + lcontrol_last_idx = F.r_u32(); + + IReader *R = F.open_chunk(CHUNK_LCONTROLS); + if (R) + { + while (!R->eof()) + { + shared_str l_name; + R->r_stringZ(l_name); + u32 l_idx = R->r_u32(); + AppendLightControl(l_name.c_str(), &l_idx); + } + R->close(); + } + + return true; +} +//---------------------------------------------------- + +void ESceneLightTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.w_chunk(CHUNK_VERSION, (u16 *)&LIGHT_TOOLS_VERSION, sizeof(LIGHT_TOOLS_VERSION)); + + F.open_chunk(CHUNK_FLAGS); + F.w_u32(m_Flags.get()); + F.close_chunk(); + + F.open_chunk(CHUNK_SUN_SHADOW); + F.w_u8(0); + F.w_fvector2(m_SunShadowDir); + F.close_chunk(); + + F.open_chunk(CHUNK_LCONTROLS_LAST); + F.w_u32(lcontrol_last_idx); + F.close_chunk(); + + F.open_chunk(CHUNK_LCONTROLS); + RTokenVecIt _I = lcontrols.begin(); + RTokenVecIt _E = lcontrols.end(); + for (; _I != _E; _I++) + { + F.w_stringZ(_I->name); + F.w_u32(_I->id); + } + F.close_chunk(); +} +//---------------------------------------------------- + +bool ESceneLightTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + if (version != LIGHT_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} +//---------------------------------------------------- + +void ESceneLightTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&LIGHT_TOOLS_VERSION, sizeof(LIGHT_TOOLS_VERSION)); + + inherited::SaveSelection(F); +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Tools/Particles/EScenePSControls.cpp b/src/editors/LevelEditor/Tools/Particles/EScenePSControls.cpp new file mode 100644 index 00000000000..927a361650c --- /dev/null +++ b/src/editors/LevelEditor/Tools/Particles/EScenePSControls.cpp @@ -0,0 +1,37 @@ +#include "stdafx.h" + +TUI_ControlPSAdd::TUI_ControlPSAdd(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} + +bool TUI_ControlPSAdd::AfterAppendCallback(TShiftState Shift, CCustomObject *obj) +{ + EParticlesObject *pg = dynamic_cast(obj); + R_ASSERT(pg); + LPCSTR ref_name = ((UIParticlesTool *)parent_tool->pForm)->Current(); + if (!ref_name) + { + ELog.DlgMsg(mtInformation, "Nothing selected."); + return false; + } + if (!pg->Compile(ref_name)) + { + ELog.DlgMsg(mtInformation, "Can't compile particle system '%s'.", ref_name); + return false; + } + return true; +} + +bool TUI_ControlPSAdd::Start(TShiftState Shift) +{ + DefaultAddObject(Shift, 0, TAfterAppendCallback(this, &TUI_ControlPSAdd::AfterAppendCallback)); + return false; +} + +void TUI_ControlPSAdd::Move(TShiftState _Shift) +{ +} +bool TUI_ControlPSAdd::End(TShiftState _Shift) +{ + return true; +} diff --git a/src/editors/LevelEditor/Tools/Particles/EScenePSControls.h b/src/editors/LevelEditor/Tools/Particles/EScenePSControls.h new file mode 100644 index 00000000000..9ea8331da06 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Particles/EScenePSControls.h @@ -0,0 +1,13 @@ +#pragma once + +class TUI_ControlPSAdd : public TUI_CustomControl +{ + bool AfterAppendCallback(TShiftState Shift, CCustomObject *obj); + +public: + TUI_ControlPSAdd(int st, int act, ESceneToolBase *parent); + virtual ~TUI_ControlPSAdd() { ; } + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); +}; diff --git a/src/editors/LevelEditor/Tools/Particles/EScenePSTools.cpp b/src/editors/LevelEditor/Tools/Particles/EScenePSTools.cpp new file mode 100644 index 00000000000..78fcf7794f7 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Particles/EScenePSTools.cpp @@ -0,0 +1,26 @@ +#include "stdafx.h" + +void EScenePSTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); + AddControl(xr_new(estDefault, etaAdd, this)); + // frame + pForm = xr_new(); +} + +void EScenePSTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +CCustomObject *EScenePSTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} +//---------------------------------------------------- +bool EScenePSTool::ExportGame(SExportStreams *F) +{ + return inherited::ExportGame(F); +} diff --git a/src/editors/LevelEditor/Tools/Particles/EScenePSTools.h b/src/editors/LevelEditor/Tools/Particles/EScenePSTools.h new file mode 100644 index 00000000000..d43ae68bf83 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Particles/EScenePSTools.h @@ -0,0 +1,31 @@ +#pragma once + +class EScenePSTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + EScenePSTool() : ESceneCustomOTool(OBJCLASS_PS) { ; } + // definition + IC LPCSTR ClassName() { return "ps"; } + IC LPCSTR ClassDesc() { return "Particle System"; } + IC int RenderPriority() { return 30; } + + virtual void Clear(bool bSpecific = false) { inherited::Clear(bSpecific); } + // IO + virtual bool IsNeedSave() { return inherited::IsNeedSave(); } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + virtual bool ExportGame(SExportStreams *F); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); +}; diff --git a/src/editors/LevelEditor/Tools/Particles/EScenePSToolsIO.cpp b/src/editors/LevelEditor/Tools/Particles/EScenePSToolsIO.cpp new file mode 100644 index 00000000000..93465a72d54 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Particles/EScenePSToolsIO.cpp @@ -0,0 +1,73 @@ +#include "stdafx.h" + +// chunks +static const u16 PS_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, +}; + +bool EScenePSTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + if (version != PS_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + return true; +} + +void EScenePSTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + ini.w_u32("main", "version", PS_TOOLS_VERSION); +} + +bool EScenePSTool::LoadStream(IReader &F) +{ + u16 version = 0; + if (F.r_chunk(CHUNK_VERSION, &version)) + if (version != PS_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + if (!inherited::LoadStream(F)) + return false; + + return true; +} + +void EScenePSTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.w_chunk(CHUNK_VERSION, (u16 *)&PS_TOOLS_VERSION, sizeof(PS_TOOLS_VERSION)); +} + +bool EScenePSTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + if (version != PS_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} +//---------------------------------------------------- + +void EScenePSTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&PS_TOOLS_VERSION, sizeof(PS_TOOLS_VERSION)); + + inherited::SaveSelection(F); +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Tools/Portal/EScenePortalControls.cpp b/src/editors/LevelEditor/Tools/Portal/EScenePortalControls.cpp new file mode 100644 index 00000000000..f3ae18cc0c6 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Portal/EScenePortalControls.cpp @@ -0,0 +1,20 @@ +#include "stdafx.h" + +TUI_ControlPortalSelect::TUI_ControlPortalSelect(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} + +bool TUI_ControlPortalSelect::Start(TShiftState Shift) +{ + return SelectStart(Shift); +} + +void TUI_ControlPortalSelect::Move(TShiftState Shift) +{ + SelectProcess(Shift); +} + +bool TUI_ControlPortalSelect::End(TShiftState Shift) +{ + return SelectEnd(Shift); +} diff --git a/src/editors/LevelEditor/Tools/Portal/EScenePortalControls.h b/src/editors/LevelEditor/Tools/Portal/EScenePortalControls.h new file mode 100644 index 00000000000..62636456113 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Portal/EScenePortalControls.h @@ -0,0 +1,10 @@ +#pragma once + +class TUI_ControlPortalSelect : public TUI_CustomControl +{ +public: + TUI_ControlPortalSelect(int st, int act, ESceneToolBase *parent); + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); +}; diff --git a/src/editors/LevelEditor/Tools/Portal/EScenePortalTools.cpp b/src/editors/LevelEditor/Tools/Portal/EScenePortalTools.cpp new file mode 100644 index 00000000000..320b5a09d7a --- /dev/null +++ b/src/editors/LevelEditor/Tools/Portal/EScenePortalTools.cpp @@ -0,0 +1,136 @@ +#include "stdafx.h" + +/* TODO 1 -oAlexMX -cTODO: Create tools as AI Map */ + +void EScenePortalTool::CreateControls() +{ + // inherited::CreateControls(); + AddControl(xr_new(estDefault, etaSelect, this)); + // frame + pForm = xr_new(); + ((UIPortalTool *)pForm)->tool = this; +} + +void EScenePortalTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +void EScenePortalTool::FillProp(LPCSTR pref, PropItemVec &items) +{ + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Draw Simple Model"), &m_Flags, flDrawSimpleModel); + inherited::FillProp(pref, items); +} + +CCustomObject *EScenePortalTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} +//---------------------------------------------------- +float plane_dot(const Fplane &P0, const Fplane &P1) +{ + return P0.n.x * P1.n.x + P0.n.y * P1.n.y + P0.n.z * P1.n.z + P0.d * P1.d; +} + +bool contains(Fbox P, const Fbox &P0) +{ + if (P.contains(P0)) + return true; + else + { + P.grow(0.001f); + if (P.contains(P0)) + return true; + else + return false; + } +} + +struct co_plane_pred +{ + CPortal *m_portal; + Fplane m_plane; + co_plane_pred(CPortal *p) : m_portal(p) + { + Fvector rkOffset, rkNormal; + Mgc::OrthogonalPlaneFit(m_portal->m_Vertices.size(), (Mgc::Vector3 *)m_portal->m_Vertices.data(), (Mgc::Vector3 &)rkOffset, (Mgc::Vector3 &)rkNormal); + m_plane.build(rkOffset, rkNormal); + float plane_magn = sqrt(plane_dot(m_plane, m_plane)); + m_plane.n.div(plane_magn); + m_plane.d /= plane_magn; + } + bool operator()(CCustomObject *p) + { + CPortal *P = (CPortal *)p; + if (m_portal == P) + return false; + + if (P->m_SectorFront == m_portal->m_SectorFront && P->m_SectorBack == m_portal->m_SectorBack) + { + Fvector rkOffset, rkNormal; + Fplane p_plane; + Mgc::OrthogonalPlaneFit(P->m_Vertices.size(), (Mgc::Vector3 *)P->m_Vertices.data(), (Mgc::Vector3 &)rkOffset, (Mgc::Vector3 &)rkNormal); + p_plane.build(rkOffset, rkNormal); + float plane_magn = sqrt(plane_dot(p_plane, p_plane)); + p_plane.n.div(plane_magn); + p_plane.d /= plane_magn; + + float dot = _abs(plane_dot(m_plane, p_plane)); + if (fsimilar(dot, 1.0f, EPS_L)) + { + Fbox m_box, p_box; + m_portal->GetBox(m_box); + P->GetBox(p_box); + return contains(m_box, p_box); + } + else + return false; + } + else + return false; + } +}; + +template +bool int_greater(int val) +{ + return val > I; +} + +void EScenePortalTool::RemoveSimilar() +{ + ObjectList &p_lst = Scene->ListObj(OBJCLASS_PORTAL); + ObjectList p_lst_del; + ObjectList p_lst_dup = p_lst; + + ObjectIt it = p_lst_dup.begin(); + ObjectIt it_e = p_lst_dup.end(); + + while (it != p_lst_dup.end()) + { + CPortal *p = (CPortal *)(*it); + if (std::find(p_lst_del.begin(), p_lst_del.end(), *it) != p_lst_del.end()) + { + ++it; + continue; + } + ObjectIt pit = std::find_if(p_lst.begin(), p_lst.end(), co_plane_pred(p)); + if (pit != p_lst.end()) + { + p_lst_del.push_back(*pit); + p_lst.erase(pit); + it = p_lst_dup.begin(); + } + else + ++it; + } + + for (ObjectIt p_del = p_lst_del.begin(); p_del != p_lst_del.end(); ++p_del) + { + xr_delete(*p_del); + } + ELog.DlgMsg(mtInformation, "Removed '%d' portal(s).", p_lst_del.size()); + p_lst_del.clear(); +} diff --git a/src/editors/LevelEditor/Tools/Portal/EScenePortalTools.h b/src/editors/LevelEditor/Tools/Portal/EScenePortalTools.h new file mode 100644 index 00000000000..3ea30fd352a --- /dev/null +++ b/src/editors/LevelEditor/Tools/Portal/EScenePortalTools.h @@ -0,0 +1,42 @@ +#pragma once + +class EScenePortalTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + friend class CPortal; + +protected: + enum + { + flDrawSimpleModel = (1 << 31), + }; + Flags32 m_Flags; + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + EScenePortalTool() : ESceneCustomOTool(OBJCLASS_PORTAL) { m_Flags.zero(); } + // definition + IC LPCSTR ClassName() { return "portal"; } + IC LPCSTR ClassDesc() { return "Portal"; } + IC int RenderPriority() { return 20; } + + virtual void FillProp(LPCSTR pref, PropItemVec &items); + + virtual void Clear(bool bSpecific = false) + { + inherited::Clear(bSpecific); + m_Flags.zero(); + } + // IO + virtual bool IsNeedSave() { return true; } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + void RemoveSimilar(); + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); +}; diff --git a/src/editors/LevelEditor/Tools/Portal/EScenePortalToolsIO.cpp b/src/editors/LevelEditor/Tools/Portal/EScenePortalToolsIO.cpp new file mode 100644 index 00000000000..fe8a66f088e --- /dev/null +++ b/src/editors/LevelEditor/Tools/Portal/EScenePortalToolsIO.cpp @@ -0,0 +1,82 @@ +#include "stdafx.h" + +// chunks +static const u16 PORTAL_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, + CHUNK_FLAGS = 0x1002ul, +}; + +bool EScenePortalTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + if (version != PORTAL_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + + m_Flags.assign(ini.r_u32("main", "flags")); + return true; +} + +void EScenePortalTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + ini.w_u32("main", "version", PORTAL_TOOLS_VERSION); + ini.w_u32("main", "flags", m_Flags.get()); +} + +bool EScenePortalTool::LoadStream(IReader &F) +{ + u16 version = 0; + if (F.r_chunk(CHUNK_VERSION, &version)) + if (version != PORTAL_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + if (!inherited::LoadStream(F)) + return false; + + if (F.find_chunk(CHUNK_FLAGS)) + m_Flags.assign(F.r_u32()); + + return true; +} + +void EScenePortalTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.w_chunk(CHUNK_VERSION, (u16 *)&PORTAL_TOOLS_VERSION, sizeof(PORTAL_TOOLS_VERSION)); + + F.open_chunk(CHUNK_FLAGS); + F.w_u32(m_Flags.get()); + F.close_chunk(); +} + +bool EScenePortalTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + if (version != PORTAL_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} + +void EScenePortalTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&PORTAL_TOOLS_VERSION, sizeof(PORTAL_TOOLS_VERSION)); + + inherited::SaveSelection(F); +} diff --git a/src/editors/LevelEditor/Tools/Sector/ESceneSectorControls.cpp b/src/editors/LevelEditor/Tools/Sector/ESceneSectorControls.cpp new file mode 100644 index 00000000000..3282071ae82 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sector/ESceneSectorControls.cpp @@ -0,0 +1,262 @@ +#include "stdafx.h" + +// add +TUI_ControlSectorAdd::TUI_ControlSectorAdd(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} + +void TUI_ControlSectorAdd::OnEnter() +{ + m_Action = saNone; + UISectorTool *fraSector = (UISectorTool *)parent_tool->pForm; + VERIFY(fraSector); + fraSector->ShowEdit(); +} + +void TUI_ControlSectorAdd::OnExit() +{ + UISectorTool *fraSector = (UISectorTool *)parent_tool->pForm; + VERIFY(fraSector); + fraSector->HideEdit(); +} + +void TUI_ControlSectorAdd::AddMesh() +{ + m_Action = saAddMesh; + CSector *sector = PortalUtils.GetSelectedSector(); + if (!sector) + return; + SRayPickInfo pinf; + if (Scene->RayPickObject(pinf.inf.range, UI->m_CurrentRStart, UI->m_CurrentRDir, OBJCLASS_SCENEOBJECT, &pinf, 0)) + sector->AddMesh(dynamic_cast(pinf.s_obj), pinf.e_mesh); + else if (Scene->RayPickObject(pinf.inf.range, UI->m_CurrentRStart, UI->m_CurrentRDir, OBJCLASS_GROUP, &pinf, 0)) + { + CSceneObject *so = dynamic_cast(pinf.s_obj); + if (so) + { + sector->AddMesh(so, pinf.e_mesh); + } + } +} + +void TUI_ControlSectorAdd::DelMesh() +{ + m_Action = saDelMesh; + CSector *sector = PortalUtils.GetSelectedSector(); + if (!sector) + return; + SRayPickInfo pinf; + if (Scene->RayPickObject(pinf.inf.range, UI->m_CurrentRStart, UI->m_CurrentRDir, OBJCLASS_SCENEOBJECT, &pinf, 0)) + sector->DelMesh(dynamic_cast(pinf.s_obj), pinf.e_mesh); +} + +bool TUI_ControlSectorAdd::AddSector() +{ + string256 namebuffer; + Scene->GenObjectName(OBJCLASS_SECTOR, namebuffer); + CSector *_O = xr_new((LPVOID)0, namebuffer); + SRayPickInfo pinf; + if (Scene->RayPickObject(pinf.inf.range, UI->m_CurrentRStart, UI->m_CurrentRDir, OBJCLASS_SCENEOBJECT, &pinf, 0) && + (_O->AddMesh(dynamic_cast(pinf.s_obj), pinf.e_mesh))) + { + Scene->SelectObjects(false, OBJCLASS_SECTOR); + Scene->AppendObject(_O); + return true; + } + else + { + xr_delete(_O); + return false; + } +} + +bool valid_color(u32 clr) +{ + u32 _r = color_get_R(clr); + u32 _g = color_get_G(clr); + u32 _b = color_get_B(clr); + if ((_r == 255) && (_g == 255) && (_b == 255)) + return false; + if ((_r == 127) && (_g == 127) && (_b == 127)) + return false; + if ((_r == 0) && (_g == 0) && (_b == 0)) + return false; + if ((_r == 255) && (_g == 0) && (_b == 0)) + return false; + if ((_r == 127) && (_g == 0) && (_b == 0)) + return false; + return true; +} + +bool TUI_ControlSectorAdd::AddSectors() +{ + int cnt = 0; + SRayPickInfo pinf; + if (Scene->RayPickObject(pinf.inf.range, UI->m_CurrentRStart, UI->m_CurrentRDir, OBJCLASS_SCENEOBJECT, &pinf, 0)) + { + CSceneObject *S = dynamic_cast(pinf.s_obj); + VERIFY(S); + EditMeshVec *meshes = S->Meshes(); + for (EditMeshIt it = meshes->begin(); it != meshes->end(); it++) + { + string256 namebuffer; + Scene->GenObjectName(OBJCLASS_SECTOR, namebuffer); + CSector *_O = xr_new((LPVOID)0, namebuffer); + if (_O->AddMesh(S, *it)) + { + cnt++; + u32 clr = 0; + do + { + } while (!valid_color(clr = color_rgba(Random.randI(0, 3) * 255 / 2, Random.randI(0, 3) * 255 / 2, Random.randI(0, 3) * 255 / 2, 0))); + _O->SetColor(clr); + Scene->SelectObjects(false, OBJCLASS_SECTOR); + Scene->AppendObject(_O); + } + else + { + xr_delete(_O); + } + } + } + return cnt != 0; +} + +bool TUI_ControlSectorAdd::Start(TShiftState Shift) +{ + if (Shift == ssRBOnly) + { + ExecCommand(COMMAND_SHOWCONTEXTMENU, OBJCLASS_SECTOR); + return false; + } + UISectorTool *fraSector = (UISectorTool *)parent_tool->pForm; + VERIFY(fraSector); + if (fraSector->IsCreateNewSingle()) + { + if (AddSector() && (!(Shift & ssAlt))) + fraSector->SetCreateNewSingle(false); + return false; + } + if (fraSector->IsCreateNewMultiple()) + { + AddSectors(); + return false; + } + bool bBoxSelection = fraSector->IsBoxPick(); + if (bBoxSelection) + { + UI->EnableSelectionRect(true); + UI->UpdateSelectionRect(UI->m_StartCp, UI->m_CurrentCp); + m_Action = saMeshBoxSelection; + return true; + } + else + { + if (fraSector->IsMeshAdd()) + AddMesh(); + else + DelMesh(); + return false; + } +} + +void TUI_ControlSectorAdd::Move(TShiftState _Shift) +{ + switch (m_Action) + { + case saAddMesh: + AddMesh(); + break; + case saDelMesh: + DelMesh(); + break; + case saMeshBoxSelection: + UI->UpdateSelectionRect(UI->m_StartCp, UI->m_CurrentCp); + break; + } +} + +bool TUI_ControlSectorAdd::End(TShiftState _Shift) +{ + UISectorTool *fraSector = (UISectorTool *)parent_tool->pForm; + VERIFY(fraSector); + CSector *sector = PortalUtils.GetSelectedSector(); + if (sector) + { + if (m_Action == saMeshBoxSelection) + { + UI->EnableSelectionRect(false); + Fmatrix matrix; + CSceneObject *O_ref = NULL; + CEditableObject *O_lib = NULL; + + CFrustum frustum; + ObjectList lst; + if (LUI->SelectionFrustum(frustum)) + { + ; + Scene->FrustumPick(frustum, OBJCLASS_SCENEOBJECT, lst); + for (ObjectIt _F = lst.begin(); _F != lst.end(); _F++) + { + O_ref = (CSceneObject *)(*_F); + O_lib = O_ref->GetReference(); + for (EditMeshIt m_def = O_lib->m_Meshes.begin(); m_def != O_lib->m_Meshes.end(); m_def++) + { + O_ref->GetFullTransformToWorld(matrix); + if ((*m_def)->FrustumPick(frustum, matrix)) + { + if (fraSector->IsMeshAdd()) + sector->AddMesh(O_ref, *m_def); + else if (sector->DelMesh(O_ref, *m_def)) + break; + } + } + } + } + } + switch (m_Action) + { + case saAddMesh: + case saDelMesh: + case saMeshBoxSelection: + Scene->UndoSave(); + break; + } + } + m_Action = saNone; + return true; +} + +//------------------------------------------------------------------------------ +// +//------------------------------------------------------------------------------ +TUI_ControlSectorSelect::TUI_ControlSectorSelect(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ + pFrame = 0; +} +void TUI_ControlSectorSelect::OnEnter() +{ + pFrame = (UISectorTool *)parent_tool->pForm; + VERIFY(pFrame); +} +void TUI_ControlSectorSelect::OnExit() +{ + pFrame = 0; +} +bool TUI_ControlSectorSelect::Start(TShiftState Shift) +{ + bool bRes = SelectStart(Shift); + // if(!bBoxSelection) pFrame->OnChange(); + return bRes; +} +void TUI_ControlSectorSelect::Move(TShiftState Shift) +{ + SelectProcess(Shift); +} + +bool TUI_ControlSectorSelect::End(TShiftState Shift) +{ + bool bRes = SelectEnd(Shift); + // if (bBoxSelection) pFrame->OnChange(); + return bRes; +} diff --git a/src/editors/LevelEditor/Tools/Sector/ESceneSectorControls.h b/src/editors/LevelEditor/Tools/Sector/ESceneSectorControls.h new file mode 100644 index 00000000000..2c537965d47 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sector/ESceneSectorControls.h @@ -0,0 +1,42 @@ +#pragma once + +// refs +class UISectorTool; +enum ESectorAction +{ + saNone, + saAddMesh, + saDelMesh, + saMeshBoxSelection +}; + +class TUI_ControlSectorAdd : public TUI_CustomControl +{ + ESectorAction m_Action; + bool AddSectors(); + bool AddSector(); + void AddMesh(); + void DelMesh(); + +public: + TUI_ControlSectorAdd(int st, int act, ESceneToolBase *parent); + virtual ~TUI_ControlSectorAdd() { ; } + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); + virtual void OnEnter(); + virtual void OnExit(); +}; + +class TUI_ControlSectorSelect : public TUI_CustomControl +{ + UISectorTool *pFrame; + +public: + TUI_ControlSectorSelect(int st, int act, ESceneToolBase *parent); + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); + virtual void OnEnter(); + virtual void OnExit(); +}; diff --git a/src/editors/LevelEditor/Tools/Sector/ESceneSectorTools.cpp b/src/editors/LevelEditor/Tools/Sector/ESceneSectorTools.cpp new file mode 100644 index 00000000000..3e482ac215d --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sector/ESceneSectorTools.cpp @@ -0,0 +1,102 @@ +#include "stdafx.h" + +/* TODO 1 -oAlexMX -cTODO: Create tools as AI Map */ + +void ESceneSectorTool::CreateControls() +{ + // inherited::CreateControls(); + AddControl(xr_new(estDefault, etaSelect, this)); + AddControl(xr_new(estDefault, etaAdd, this)); + // frame + pForm = xr_new(); +} + +void ESceneSectorTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +void ESceneSectorTool::_OnObjectRemove(CSceneObject *obj) +{ + if (obj && !m_Objects.empty()) + { + EditMeshVec *meshes = obj->Meshes(); + for (EditMeshIt m_it = meshes->begin(); m_it != meshes->end(); ++m_it) + { + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); ++_F) + { + CSector *sector = dynamic_cast(*_F); + VERIFY(sector); + if (sector->DelMesh(obj, *m_it)) + break; + } + } + } +} + +void ESceneSectorTool::OnObjectRemove(CCustomObject *O, bool bDeleting) +{ + inherited::OnObjectRemove(O, bDeleting); + + if (bDeleting) + { + CSceneObject *obj = dynamic_cast(O); + if (!obj) + { /* + CGroupObject* go = dynamic_cast(O); + if(go && !go->IsOpened()) + { + ObjectList lst; + go->GetObjects (lst); + + ObjectList::iterator it = lst.begin(); + ObjectList::iterator it_e = lst.end(); + for(; it!=it_e; ++it) + { + CSceneObject* obj2 = dynamic_cast(*it); + _OnObjectRemove(obj2); + } + } */ + } + else + _OnObjectRemove(obj); + } +} + +void ESceneSectorTool::OnBeforeObjectChange(CCustomObject *O) +{ + inherited::OnBeforeObjectChange(O); + + CSceneObject *obj = dynamic_cast(O); + if (obj && !m_Objects.empty()) + { + EditMeshVec *meshes = obj->Meshes(); + for (EditMeshIt m_it = meshes->begin(); m_it != meshes->end(); m_it++) + { + for (ObjectIt _F = m_Objects.begin(); _F != m_Objects.end(); _F++) + { + CSector *sector = dynamic_cast(*_F); + VERIFY(sector); + if (sector->DelMesh(obj, *m_it)) + break; + } + } + } +} + +//---------------------------------------------------- + +void ESceneSectorTool::FillProp(LPCSTR pref, PropItemVec &items) +{ + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Draw Solid"), &m_Flags, flDrawSolid); + inherited::FillProp(pref, items); +} +//---------------------------------------------------- + +CCustomObject *ESceneSectorTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Tools/Sector/ESceneSectorTools.h b/src/editors/LevelEditor/Tools/Sector/ESceneSectorTools.h new file mode 100644 index 00000000000..9c2eb826bd6 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sector/ESceneSectorTools.h @@ -0,0 +1,48 @@ +#pragma once + +class CSceneObject; + +class ESceneSectorTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + friend class CSector; + +protected: + enum + { + flDrawSolid = (1 << 31), + }; + Flags32 m_Flags; + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + ESceneSectorTool() : ESceneCustomOTool(OBJCLASS_SECTOR) { m_Flags.zero(); } + // definition + IC LPCSTR ClassName() { return "sector"; } + IC LPCSTR ClassDesc() { return "Sector"; } + IC int RenderPriority() { return 20; } + + virtual void OnObjectRemove(CCustomObject *O, bool bDeleting); + void _OnObjectRemove(CSceneObject *O); + virtual void OnBeforeObjectChange(CCustomObject *O); + + virtual void FillProp(LPCSTR pref, PropItemVec &items); + + virtual void Clear(bool bSpecific = false) + { + inherited::Clear(bSpecific); + m_Flags.zero(); + } + // IO + virtual bool IsNeedSave() { return true; } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); +}; diff --git a/src/editors/LevelEditor/Tools/Sector/ESceneSectorToolsIO.cpp b/src/editors/LevelEditor/Tools/Sector/ESceneSectorToolsIO.cpp new file mode 100644 index 00000000000..240ef29b957 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sector/ESceneSectorToolsIO.cpp @@ -0,0 +1,82 @@ +#include "stdafx.h" + +// chunks +static const u16 SECTOR_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, + CHUNK_FLAGS = 0x1002ul, +}; + +bool ESceneSectorTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + if (version != SECTOR_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + m_Flags.assign(ini.r_u32("main", "flags")); + + return true; +} + +void ESceneSectorTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + ini.w_u32("main", "version", SECTOR_TOOLS_VERSION); + ini.w_u32("main", "flags", m_Flags.get()); +} + +bool ESceneSectorTool::LoadStream(IReader &F) +{ + u16 version = 0; + if (F.r_chunk(CHUNK_VERSION, &version)) + if (version != SECTOR_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + if (!inherited::LoadStream(F)) + return false; + + if (F.find_chunk(CHUNK_FLAGS)) + m_Flags.assign(F.r_u32()); + + return true; +} + +void ESceneSectorTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.w_chunk(CHUNK_VERSION, (u16 *)&SECTOR_TOOLS_VERSION, sizeof(SECTOR_TOOLS_VERSION)); + + F.open_chunk(CHUNK_FLAGS); + F.w_u32(m_Flags.get()); + F.close_chunk(); +} + +bool ESceneSectorTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + if (version != SECTOR_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} + +void ESceneSectorTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&SECTOR_TOOLS_VERSION, sizeof(SECTOR_TOOLS_VERSION)); + + inherited::SaveSelection(F); +} diff --git a/src/editors/LevelEditor/Tools/Shape/ESceneShapeControls.cpp b/src/editors/LevelEditor/Tools/Shape/ESceneShapeControls.cpp new file mode 100644 index 00000000000..74f2dc67a8b --- /dev/null +++ b/src/editors/LevelEditor/Tools/Shape/ESceneShapeControls.cpp @@ -0,0 +1,62 @@ +#include "stdafx.h" + +TUI_ControlShapeAdd::TUI_ControlShapeAdd(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} + +bool TUI_ControlShapeAdd::AfterAppendCallback(TShiftState Shift, CCustomObject *obj) +{ + CEditShape *shape = dynamic_cast(obj); + R_ASSERT(shape); + UIShapeTool *F = (UIShapeTool *)parent_tool->pForm; + if (F->IsSphereMode()) + { + Fsphere S; + S.identity(); + shape->add_sphere(S); + // if (!(Shift&ssAlt)) F->SetSphereMode(false); + return true; + } + else + { + Fmatrix M; + M.identity(); + shape->add_box(M); + // if (!(Shift&ssAlt)) F->SetSphereMode(true); + return true; + } + return false; +} + +bool TUI_ControlShapeAdd::Start(TShiftState Shift) +{ + UIShapeTool *F = (UIShapeTool *)parent_tool->pForm; + if (F->IsAttachShape()) + { + CEditShape *from = dynamic_cast(Scene->RayPickObject(UI->ZFar(), UI->m_CurrentRStart, UI->m_CurrentRDir, OBJCLASS_SHAPE, 0, 0)); + if (from) + { + ObjectList lst; + int cnt = Scene->GetQueryObjects(lst, OBJCLASS_SHAPE, 1, 1, 0); + if (1 != cnt) + ELog.DlgMsg(mtError, "Select one shape."); + else + { + CEditShape *base = dynamic_cast(lst.back()); + R_ASSERT(base); + if (base != from) + { + base->Attach(from); + if (!(Shift & ssAlt)) + { + F->SetAttachShape(false); + ResetActionToSelect(); + } + } + } + } + } + else + DefaultAddObject(Shift, 0, TAfterAppendCallback(this, &TUI_ControlShapeAdd::AfterAppendCallback)); + return false; +} diff --git a/src/editors/LevelEditor/Tools/Shape/ESceneShapeControls.h b/src/editors/LevelEditor/Tools/Shape/ESceneShapeControls.h new file mode 100644 index 00000000000..a927c03f0ca --- /dev/null +++ b/src/editors/LevelEditor/Tools/Shape/ESceneShapeControls.h @@ -0,0 +1,11 @@ +#pragma once + +class TUI_ControlShapeAdd : public TUI_CustomControl +{ + bool AfterAppendCallback(TShiftState _Shift, CCustomObject *obj); + +public: + TUI_ControlShapeAdd(int st, int act, ESceneToolBase *parent); + virtual ~TUI_ControlShapeAdd() { ; } + virtual bool Start(TShiftState _Shift); +}; diff --git a/src/editors/LevelEditor/Tools/Shape/ESceneShapeTools.cpp b/src/editors/LevelEditor/Tools/Shape/ESceneShapeTools.cpp new file mode 100644 index 00000000000..1ec9341ba79 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Shape/ESceneShapeTools.cpp @@ -0,0 +1,81 @@ +#include "stdafx.h" + +void ESceneShapeTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); + AddControl(xr_new(estDefault, etaAdd, this)); + pForm = xr_new(); + ((UIShapeTool *)pForm)->Tool = this; +} + +void ESceneShapeTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +CCustomObject *ESceneShapeTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} + +void ESceneShapeTool::OnEditLevelBounds(bool recalc) +{ + ObjectList::iterator it = m_Objects.begin(); + ObjectList::iterator it_e = m_Objects.end(); + + CEditShape *level_shape = NULL; + + for (; it != it_e; ++it) + { + CEditShape *es = dynamic_cast(*it); + R_ASSERT(es); + if (es->m_shape_type == eShapeLevelBound) + { + level_shape = es; + break; + } + } + bool b_recalc = recalc || (level_shape == NULL); + + if (!level_shape) + { + level_shape = dynamic_cast(CreateObject(NULL, "level_bbox")); + level_shape->m_shape_type = eShapeLevelBound; + Fmatrix M; + M.identity(); + level_shape->add_box(M); + + Scene->AppendObject(level_shape); + } + + if (b_recalc) + { + Fbox bg, br; + Scene->GetBox(br, OBJCLASS_SCENEOBJECT); + bool r1 = Scene->GetBox(bg, OBJCLASS_GROUP); + if (r1) + br.merge(bg); + + Fvector vec; + br.getsize(vec); + level_shape->FScale = vec; + // level_shape->OnUpdateTransform(); + // level_shape->ApplyScale(); + + br.getcenter(vec); + level_shape->FPosition = vec; + } +} +void ESceneShapeTool::OnActivate() +{ + inherited::OnActivate(); + ((UIShapeTool *)pForm)->EditLevelBound = false; +} + +void ESceneShapeTool::OnDeactivate() +{ + inherited::OnDeactivate(); + ((UIShapeTool *)pForm)->EditLevelBound = false; +} diff --git a/src/editors/LevelEditor/Tools/Shape/ESceneShapeTools.h b/src/editors/LevelEditor/Tools/Shape/ESceneShapeTools.h new file mode 100644 index 00000000000..af1a7c7e7f8 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Shape/ESceneShapeTools.h @@ -0,0 +1,34 @@ +#pragma once + +class ESceneShapeTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + ESceneShapeTool() : ESceneCustomOTool(OBJCLASS_SHAPE) { ; } + // definition + IC LPCSTR ClassName() { return "shape"; } + IC LPCSTR ClassDesc() { return "Shape"; } + IC int RenderPriority() { return 20; } + + virtual void Clear(bool bSpecific = false) { inherited::Clear(bSpecific); } + // IO + virtual bool IsNeedSave() { return inherited::IsNeedSave(); } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); + void OnEditLevelBounds(bool recalc); + + virtual void OnActivate(); + virtual void OnDeactivate(); +}; diff --git a/src/editors/LevelEditor/Tools/Shape/ESceneShapeToolsIO.cpp b/src/editors/LevelEditor/Tools/Shape/ESceneShapeToolsIO.cpp new file mode 100644 index 00000000000..e9b4c27046f --- /dev/null +++ b/src/editors/LevelEditor/Tools/Shape/ESceneShapeToolsIO.cpp @@ -0,0 +1,70 @@ +#include "stdafx.h" + +// chunks +static const u16 SHAPE_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, +}; + +bool ESceneShapeTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + if (version != SHAPE_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + return true; +} + +void ESceneShapeTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + ini.w_u32("main", "version", SHAPE_TOOLS_VERSION); +} + +bool ESceneShapeTool::LoadStream(IReader &F) +{ + u16 version = 0; + if (F.r_chunk(CHUNK_VERSION, &version)) + if (version != SHAPE_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + if (!inherited::LoadStream(F)) + return false; + + return true; +} + +void ESceneShapeTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + F.w_chunk(CHUNK_VERSION, (u16 *)&SHAPE_TOOLS_VERSION, sizeof(SHAPE_TOOLS_VERSION)); +} + +bool ESceneShapeTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + if (version != SHAPE_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} + +void ESceneShapeTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&SHAPE_TOOLS_VERSION, sizeof(SHAPE_TOOLS_VERSION)); + + inherited::SaveSelection(F); +} diff --git a/src/editors/LevelEditor/Tools/Sound/ESceneSoundEnvTools.cpp b/src/editors/LevelEditor/Tools/Sound/ESceneSoundEnvTools.cpp new file mode 100644 index 00000000000..ecfc513328d --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sound/ESceneSoundEnvTools.cpp @@ -0,0 +1,24 @@ +#include "stdafx.h" + +void ESceneSoundEnvTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); +} + +void ESceneSoundEnvTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +void ESceneSoundEnvTool::Clear(bool bSpecific) +{ + inherited::Clear(bSpecific); + LSndLib->RefreshEnvGeometry(); +} + +CCustomObject *ESceneSoundEnvTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} diff --git a/src/editors/LevelEditor/Tools/Sound/ESceneSoundEnvTools.h b/src/editors/LevelEditor/Tools/Sound/ESceneSoundEnvTools.h new file mode 100644 index 00000000000..3d659c1987f --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sound/ESceneSoundEnvTools.h @@ -0,0 +1,30 @@ +#pragma once + +class ESceneSoundEnvTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + ESceneSoundEnvTool() : ESceneCustomOTool(OBJCLASS_SOUND_ENV) { ; } + // definition + IC LPCSTR ClassName() { return "sound_env"; } + IC LPCSTR ClassDesc() { return "Sound Environment"; } + IC int RenderPriority() { return 10; } + + virtual void Clear(bool bSpecific = false); + // IO + virtual bool IsNeedSave() { return inherited::IsNeedSave(); } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); +}; diff --git a/src/editors/LevelEditor/Tools/Sound/ESceneSoundEnvToolsIO.cpp b/src/editors/LevelEditor/Tools/Sound/ESceneSoundEnvToolsIO.cpp new file mode 100644 index 00000000000..1460eaf72ad --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sound/ESceneSoundEnvToolsIO.cpp @@ -0,0 +1,76 @@ +#include "stdafx.h" + +// chunks +static const u16 SOUND_ENV_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, +}; + +bool ESceneSoundEnvTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + + if (version != SOUND_ENV_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + + return true; +} + +void ESceneSoundEnvTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + ini.w_u32("main", "version", SOUND_ENV_TOOLS_VERSION); +} + +bool ESceneSoundEnvTool::LoadStream(IReader &F) +{ + u16 version = 0; + + if (F.r_chunk(CHUNK_VERSION, &version)) + { + if (version != SOUND_ENV_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + } + + if (!inherited::LoadStream(F)) + return false; + + return true; +} + +void ESceneSoundEnvTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + F.w_chunk(CHUNK_VERSION, (u16 *)&SOUND_ENV_TOOLS_VERSION, sizeof(SOUND_ENV_TOOLS_VERSION)); +} + +bool ESceneSoundEnvTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + + if (version != SOUND_ENV_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} + +void ESceneSoundEnvTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&SOUND_ENV_TOOLS_VERSION, sizeof(SOUND_ENV_TOOLS_VERSION)); + + inherited::SaveSelection(F); +} diff --git a/src/editors/LevelEditor/Tools/Sound/ESceneSoundSrcTools.cpp b/src/editors/LevelEditor/Tools/Sound/ESceneSoundSrcTools.cpp new file mode 100644 index 00000000000..d8dddaddfad --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sound/ESceneSoundSrcTools.cpp @@ -0,0 +1,18 @@ +#include "stdafx.h" + +void ESceneSoundSrcTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); +} + +void ESceneSoundSrcTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +CCustomObject *ESceneSoundSrcTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} diff --git a/src/editors/LevelEditor/Tools/Sound/ESceneSoundSrcTools.h b/src/editors/LevelEditor/Tools/Sound/ESceneSoundSrcTools.h new file mode 100644 index 00000000000..2bd99a9b86f --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sound/ESceneSoundSrcTools.h @@ -0,0 +1,30 @@ +#pragma once + +class ESceneSoundSrcTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + ESceneSoundSrcTool() : ESceneCustomOTool(OBJCLASS_SOUND_SRC) { ; } + // definition + IC LPCSTR ClassName() { return "sound_src"; } + IC LPCSTR ClassDesc() { return "Sound Source"; } + IC int RenderPriority() { return 10; } + + virtual void Clear(bool bSpecific = false) { inherited::Clear(bSpecific); } + // IO + virtual bool IsNeedSave() { return inherited::IsNeedSave(); } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); +}; diff --git a/src/editors/LevelEditor/Tools/Sound/ESceneSoundSrcToolsIO.cpp b/src/editors/LevelEditor/Tools/Sound/ESceneSoundSrcToolsIO.cpp new file mode 100644 index 00000000000..583717067e7 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Sound/ESceneSoundSrcToolsIO.cpp @@ -0,0 +1,74 @@ +#include "stdafx.h" + +// chunks +static const u16 SOUND_SRC_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, +}; + +bool ESceneSoundSrcTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + + if (version != SOUND_SRC_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + return true; +} + +void ESceneSoundSrcTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + ini.w_u32("main", "version", SOUND_SRC_TOOLS_VERSION); +} + +bool ESceneSoundSrcTool::LoadStream(IReader &F) +{ + u16 version = 0; + + if (F.r_chunk(CHUNK_VERSION, &version)) + { + if (version != SOUND_SRC_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + } + + if (!inherited::LoadStream(F)) + return false; + + return true; +} + +void ESceneSoundSrcTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + F.w_chunk(CHUNK_VERSION, (u16 *)&SOUND_SRC_TOOLS_VERSION, sizeof(SOUND_SRC_TOOLS_VERSION)); +} + +bool ESceneSoundSrcTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + + if (version != SOUND_SRC_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} + +void ESceneSoundSrcTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&SOUND_SRC_TOOLS_VERSION, sizeof(SOUND_SRC_TOOLS_VERSION)); + inherited::SaveSelection(F); +} diff --git a/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnControls.cpp b/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnControls.cpp new file mode 100644 index 00000000000..2942d190e38 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnControls.cpp @@ -0,0 +1,65 @@ +#include "stdafx.h" + +TUI_ControlSpawnAdd::TUI_ControlSpawnAdd(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} + +bool TUI_ControlSpawnAdd::AppendCallback(SBeforeAppendCallbackParams *p) +{ + LPCSTR ref_name = ((UISpawnTool *)parent_tool->pForm)->Current(); + if (!ref_name) + { + ELog.DlgMsg(mtInformation, "Nothing selected."); + return false; + } + if (Scene->LevelPrefix().c_str()) + { + p->name_prefix = Scene->LevelPrefix().c_str(); + p->name_prefix += "_"; + } + p->name_prefix += ref_name; + p->data = (void *)ref_name; + return (0 != p->name_prefix.length()); +} + +bool TUI_ControlSpawnAdd::Start(TShiftState Shift) +{ + UISpawnTool *F = (UISpawnTool *)parent_tool->pForm; + if (F->IsAttachObject()) + { + CCustomObject *from = Scene->RayPickObject(UI->ZFar(), UI->m_CurrentRStart, UI->m_CurrentRDir, OBJCLASS_DUMMY, 0, 0); + if (from->FClassID != OBJCLASS_SPAWNPOINT) + { + ObjectList lst; + int cnt = Scene->GetQueryObjects(lst, OBJCLASS_SPAWNPOINT, 1, 1, 0); + if (1 != cnt) + ELog.DlgMsg(mtError, "Select one shape."); + else + { + CSpawnPoint *base = dynamic_cast(lst.back()); + R_ASSERT(base); + if (base->AttachObject(from)) + { + if (!(Shift & ssAlt)) + { + F->SetAttachObject(false); + ResetActionToSelect(); + } + } + else + { + ELog.DlgMsg(mtError, "Attach impossible."); + } + } + } + else + { + ELog.DlgMsg(mtError, "Attach impossible."); + } + } + else + { + DefaultAddObject(Shift, TBeforeAppendCallback(this, &TUI_ControlSpawnAdd::AppendCallback)); + } + return false; +} diff --git a/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnControls.h b/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnControls.h new file mode 100644 index 00000000000..90f7f3f8c68 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnControls.h @@ -0,0 +1,14 @@ +#pragma once + +// refs +class TfraRPoint; + +class TUI_ControlSpawnAdd : public TUI_CustomControl +{ + bool AppendCallback(SBeforeAppendCallbackParams *p); + +public: + TUI_ControlSpawnAdd(int st, int act, ESceneToolBase *parent); + virtual ~TUI_ControlSpawnAdd() { ; } + virtual bool Start(TShiftState _Shift); +}; diff --git a/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnTools.cpp b/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnTools.cpp new file mode 100644 index 00000000000..5f9c6e27aa9 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnTools.cpp @@ -0,0 +1,263 @@ +#include "stdafx.h" + +static HMODULE hXRSE_FACTORY = 0; + +CEditableObject *ESceneSpawnTool::get_draw_visual(u8 _RP_TeamID, u8 _RP_Type, const GameTypeChooser &_GameType) +{ + if (Core.SocSdk) + return nullptr; + + CEditableObject *ret = nullptr; + + if (m_draw_RP_visuals.empty()) + { + m_draw_RP_visuals.push_back(Lib.CreateEditObject("editor\\artefakt_ah")); // 0 + m_draw_RP_visuals.push_back(Lib.CreateEditObject("editor\\artefakt_cta_blue")); // 1 + m_draw_RP_visuals.push_back(Lib.CreateEditObject("editor\\artefakt_cta_green")); // 2 + m_draw_RP_visuals.push_back(Lib.CreateEditObject("editor\\telo_ah_cta_blue")); // 3 + m_draw_RP_visuals.push_back(Lib.CreateEditObject("editor\\telo_ah_cta_green")); // 4 + m_draw_RP_visuals.push_back(Lib.CreateEditObject("editor\\telo_dm")); // 5 + m_draw_RP_visuals.push_back(Lib.CreateEditObject("editor\\telo_tdm_blue")); // 6 + m_draw_RP_visuals.push_back(Lib.CreateEditObject("editor\\telo_tdm_green")); // 7 + m_draw_RP_visuals.push_back(Lib.CreateEditObject("editor\\spectator")); // 8 + m_draw_RP_visuals.push_back(Lib.CreateEditObject("editor\\item_spawn")); // 9 + } + + switch (_RP_Type) + { + case rptActorSpawn: // actor spawn + { + if (_GameType.MatchType(eGameIDDeathmatch)) + { + if (_RP_TeamID == 0) + ret = m_draw_RP_visuals[5]; + } + + if (_GameType.MatchType(eGameIDTeamDeathmatch)) + { + if (_RP_TeamID == 2) + ret = m_draw_RP_visuals[7]; + else if (_RP_TeamID == 1) + ret = m_draw_RP_visuals[6]; + } + + if (_GameType.MatchType(eGameIDCaptureTheArtefact)) + { + if (!_RP_TeamID) + Msg("! incorrect ActorRP teamID [%d] for CTA", _RP_TeamID); + else if (_RP_TeamID == 1) + ret = m_draw_RP_visuals[4]; + else if (_RP_TeamID == 2) + ret = m_draw_RP_visuals[3]; + } + + if (_GameType.MatchType(eGameIDArtefactHunt)) + { + if (!_RP_TeamID) + ret = m_draw_RP_visuals[8]; // spactator + else if (_RP_TeamID == 1) + ret = m_draw_RP_visuals[4]; + else if (_RP_TeamID == 2) + ret = m_draw_RP_visuals[3]; + } + } + break; + + case rptArtefactSpawn: // AF spawn + { + if (_GameType.MatchType(eGameIDCaptureTheArtefact)) + { + if (_RP_TeamID == 1) + ret = m_draw_RP_visuals[2]; + else if (_RP_TeamID == 2) + ret = m_draw_RP_visuals[1]; + else + Msg("! incorrect AF teamID [%d] for CTA", _RP_TeamID); + } + else if (_GameType.MatchType(eGameIDArtefactHunt)) + ret = m_draw_RP_visuals[0]; + } + break; + + case rptItemSpawn: + { + ret = m_draw_RP_visuals[9]; + } + break; + } + + return ret; +} + +void FillSpawnItems(ChooseItemVec &lst, void *param) +{ + LPCSTR gcs = (LPCSTR)param; + ObjectList objects; + Scene->GetQueryObjects(objects, OBJCLASS_SPAWNPOINT, -1, -1, -1); + + xr_string itm; + int cnt = _GetItemCount(gcs); + for (int k = 0; k < cnt; k++) + { + _GetItem(gcs, k, itm); + for (ObjectIt it = objects.begin(); it != objects.end(); it++) + if ((*it)->OnChooseQuery(itm.c_str())) + lst.push_back(SChooseItem((*it)->GetName(), "")); + } +} + +ESceneSpawnTool::ESceneSpawnTool() : ESceneCustomOTool(OBJCLASS_SPAWNPOINT) +{ + m_Flags.zero(); + UIChooseForm::AppendEvents(smSpawnItem, "Select Spawn Item", FillSpawnItems, 0, 0, 0, 0); + m_Classes.clear(); + CInifile::Root const &data = pSettings->sections(); + for (auto it = data.begin(); it != data.end(); it++) + { + LPCSTR val; + if ((*it)->line_exist("$spawn", &val)) + { + CLASS_ID cls_id = pSettings->r_clsid((*it)->Name, "class"); + shared_str v = pSettings->r_string_wb((*it)->Name, "$spawn"); + m_Classes[cls_id].push_back(SChooseItem(*v, *(*it)->Name)); + } + } +} + +ESceneSpawnTool::~ESceneSpawnTool() +{ + FreeLibrary(hXRSE_FACTORY); + m_Icons.clear(); + + xr_vector::iterator it = m_draw_RP_visuals.begin(); + xr_vector::iterator it_e = m_draw_RP_visuals.end(); + for (; it != it_e; ++it) + { + Lib.RemoveEditObject(*it); + } + m_draw_RP_visuals.clear(); +} + +void ESceneSpawnTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); + AddControl(xr_new(estDefault, etaAdd, this)); + // frame + + pForm = xr_new(); +} +//---------------------------------------------------- + +void ESceneSpawnTool::RemoveControls() +{ + inherited::RemoveControls(); +} +//---------------------------------------------------- + +void ESceneSpawnTool::FillProp(LPCSTR pref, PropItemVec &items) +{ + //. PHelper().CreateFlag32(items, PrepareKey(pref,"Common\\Show Spawn Type"), &m_Flags, flShowSpawnType); + //. PHelper().CreateFlag32(items, PrepareKey(pref,"Common\\Trace Visibility"), &m_Flags, flPickSpawnType); + inherited::FillProp(pref, items); +} +//------------------------------------------------------------------------------ + +ref_shader ESceneSpawnTool::CreateIcon(shared_str name) +{ + ref_shader S; + if (pSettings->line_exist(name, "$ed_icon")) + { + LPCSTR tex_name = pSettings->r_string(name, "$ed_icon"); + S.create("editor\\spawn_icon", tex_name); + m_Icons[name] = S; + } + else + { + S = 0; + } + return S; +} + +ref_shader ESceneSpawnTool::GetIcon(shared_str name) +{ + ShaderPairIt it = m_Icons.find(name); + if (it == m_Icons.end()) + return CreateIcon(name); + else + return it->second; +} + +CCustomObject *ESceneSpawnTool::CreateObject(LPVOID data, LPCSTR name) +{ + CSpawnPoint *O = xr_new(data, name); + O->FParentTools = this; + + if (data && name) + { + if (pSettings->line_exist((LPCSTR)data, "$def_sphere")) + { + float size = pSettings->r_float((LPCSTR)data, "$def_sphere"); + + CCustomObject *S = Scene->GetOTool(OBJCLASS_SHAPE)->CreateObject(0, 0); + CEditShape *shape = dynamic_cast(S); + R_ASSERT(shape); + + Fsphere Sph; + Sph.identity(); + Sph.R = size; + shape->add_sphere(Sph); + O->AttachObject(S); + } + } + return O; +} +//---------------------------------------------------- + +int ESceneSpawnTool::MultiRenameObjects() +{ + int cnt = 0; + for (ObjectIt o_it = m_Objects.begin(); o_it != m_Objects.end(); o_it++) + { + CCustomObject *obj = *o_it; + if (obj->Selected()) + { + string256 pref; + strconcat(sizeof(pref), pref, Scene->LevelPrefix().c_str(), "_", obj->RefName()); + string256 buf; + Scene->GenObjectName(obj->FClassID, buf, pref); + if (xr_strcmp(obj->GetName(), buf) == 0) + { + obj->SetName(buf); + cnt++; + } + } + } + return cnt; +} +/* +void ESceneSpawnTool::GetStaticDesc(int& v_cnt, int& f_cnt, bool b_selected_only) +{ + for (ObjectIt it=m_Objects.begin(); it!=m_Objects.end(); it++){ + CSceneObject* obj = (CSceneObject*)(*it); + + if(b_selected_only && !obj->Selected()) + continue; + + CSpawnPoint* sp = dynamic_cast(obj); + if(!sp){ + Msg("! ghm/ not a spawn object"); + continue; + } + if(sp->m_SpawnData.Valid()) + { + f_cnt += obj->GetFaceCount(); + v_cnt += obj->GetVertexCount(); + } + } +} + +bool ESceneSpawnTool::ExportStatic(SceneBuilder* B, bool b_selected_only) +{ + return B->ParseStaticObjects(m_Objects, NULL, b_selected_only); +} +*/ diff --git a/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnTools.h b/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnTools.h new file mode 100644 index 00000000000..734eb959a50 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnTools.h @@ -0,0 +1,67 @@ +#pragma once + +class CEditableObject; + +class ESceneSpawnTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + friend class CSpawnPoint; + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + enum + { + flPickSpawnType = (1 << 30), + flShowSpawnType = (1 << 31), + }; + Flags32 m_Flags; + + // class + DEFINE_VECTOR(SChooseItem, SSVec, SSVecIt); + DEFINE_MAP(CLASS_ID, SSVec, ClassSpawnMap, ClassSpawnMapIt); + ClassSpawnMap m_Classes; + + // icon list + DEFINE_MAP(shared_str, ref_shader, ShaderMap, ShaderPairIt); + ShaderMap m_Icons; + ref_shader CreateIcon(shared_str name); + ref_shader GetIcon(shared_str name); + xr_vector m_draw_RP_visuals; + +public: + ESceneSpawnTool(); + virtual ~ESceneSpawnTool(); + + // definition + IC LPCSTR ClassName() { return "spawn"; } + IC LPCSTR ClassDesc() { return "Spawn"; } + IC int RenderPriority() { return 1; } + + void FillProp(LPCSTR pref, PropItemVec &items); + + virtual void Clear(bool bSpecific = false) + { + inherited::Clear(bSpecific); + m_Flags.zero(); + } + + // IO + virtual bool IsNeedSave() { return true; } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool can_use_inifile() { return true; } + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + virtual int MultiRenameObjects(); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); + CEditableObject *get_draw_visual(u8 _RP_TeamID, u8 _RP_Type, const GameTypeChooser &_GameType); +}; + +// refs +class IServerEntity; diff --git a/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnToolsIO.cpp b/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnToolsIO.cpp new file mode 100644 index 00000000000..2cc5de47d6d --- /dev/null +++ b/src/editors/LevelEditor/Tools/Spawn/ESceneSpawnToolsIO.cpp @@ -0,0 +1,85 @@ +#include "stdafx.h" + +// chunks +static const u16 SPAWN_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, + CHUNK_FLAGS = 0x1002ul, +}; + +bool ESceneSpawnTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + + if (version != SPAWN_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + m_Flags.assign(ini.r_u32("main", "flags")); + return true; +} + +void ESceneSpawnTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + ini.w_u32("main", "version", SPAWN_TOOLS_VERSION); + ini.w_u32("main", "flags", m_Flags.get()); +} + +bool ESceneSpawnTool::LoadStream(IReader &F) +{ + u16 version = 0; + + if (F.r_chunk(CHUNK_VERSION, &version)) + { + if (version != SPAWN_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + } + + if (!inherited::LoadStream(F)) + return false; + + if (F.find_chunk(CHUNK_FLAGS)) + m_Flags.assign(F.r_u32()); + + return true; +} + +void ESceneSpawnTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.w_chunk(CHUNK_VERSION, (u16 *)&SPAWN_TOOLS_VERSION, sizeof(SPAWN_TOOLS_VERSION)); + + F.open_chunk(CHUNK_FLAGS); + F.w_u32(m_Flags.get()); + F.close_chunk(); +} + +bool ESceneSpawnTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + + if (version != SPAWN_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} + +void ESceneSpawnTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&SPAWN_TOOLS_VERSION, sizeof(SPAWN_TOOLS_VERSION)); + inherited::SaveSelection(F); +} diff --git a/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectControls.cpp b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectControls.cpp new file mode 100644 index 00000000000..c1f6af1c1e4 --- /dev/null +++ b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectControls.cpp @@ -0,0 +1,98 @@ +#include "stdafx.h" + +TUI_ControlObjectAdd::TUI_ControlObjectAdd(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} + +bool TUI_ControlObjectAdd::Start(TShiftState Shift) +{ + if (Shift == ssRBOnly) + { + ExecCommand(COMMAND_SHOWCONTEXTMENU, OBJCLASS_SCENEOBJECT); + return false; + } + UIObjectTool *fraObject = (UIObjectTool *)parent_tool->pForm; + VERIFY(fraObject); + Fvector p, n; + if (!LUI->PickGround(p, UI->m_CurrentRStart, UI->m_CurrentRDir, 1, &n)) + return false; + { // pick already executed (see top) + ESceneObjectTool *ot = dynamic_cast(parent_tool); + LPCSTR N; + if (ot->IsAppendRandomActive() && ot->m_AppendRandomObjects.size()) + { + N = ot->m_AppendRandomObjects[Random.randI(ot->m_AppendRandomObjects.size())].c_str(); + } + else + { + N = ((UIObjectTool *)parent_tool->pForm)->Current(); + if (!N) + { + ELog.DlgMsg(mtInformation, "Nothing selected."); + return false; + } + } + + string256 namebuffer; + Scene->GenObjectName(OBJCLASS_SCENEOBJECT, namebuffer, N); + CSceneObject *obj = xr_new((LPVOID)0, namebuffer); + CEditableObject *ref = obj->SetReference(N); + if (!ref) + { + ELog.DlgMsg(mtError, "TUI_ControlObjectAdd:: Can't load reference object."); + xr_delete(obj); + return false; + } + /* if (ref->IsDynamic()){ + ELog.DlgMsg(mtError,"TUI_ControlObjectAdd:: Can't assign dynamic object."); + xr_delete(obj); + return false; + } + */ + if (ot->IsAppendRandomActive()) + { + Fvector S; + if (ot->IsAppendRandomRotationActive()) + { + Fvector p; + p.set(Random.randF(ot->m_AppendRandomMinRotation.x, ot->m_AppendRandomMaxRotation.x), + Random.randF(ot->m_AppendRandomMinRotation.y, ot->m_AppendRandomMaxRotation.y), + Random.randF(ot->m_AppendRandomMinRotation.z, ot->m_AppendRandomMaxRotation.z)); + obj->SetRotation(p); + } + if (ot->IsAppendRandomScaleActive()) + { + Fvector s; + if (ot->IsAppendRandomScaleProportional()) + { + s.x = Random.randF(ot->m_AppendRandomMinScale.x, ot->m_AppendRandomMaxScale.x); + s.set(s.x, s.x, s.x); + } + else + { + s.set(Random.randF(ot->m_AppendRandomMinScale.x, ot->m_AppendRandomMaxScale.x), + Random.randF(ot->m_AppendRandomMinScale.y, ot->m_AppendRandomMaxScale.y), + Random.randF(ot->m_AppendRandomMinScale.z, ot->m_AppendRandomMaxScale.z)); + } + obj->SetScale(s); + } + } + obj->MoveTo(p, n); + + Scene->SelectObjects(false, OBJCLASS_SCENEOBJECT); + Scene->AppendObject(obj); + if (Shift & ssCtrl) + ExecCommand(COMMAND_SHOW_PROPERTIES); + if (!(Shift & ssAlt)) + ResetActionToSelect(); + } + return false; +} + +void TUI_ControlObjectAdd::Move(TShiftState _Shift) +{ +} +bool TUI_ControlObjectAdd::End(TShiftState _Shift) +{ + return true; +} diff --git a/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectControls.h b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectControls.h new file mode 100644 index 00000000000..9733d6217d3 --- /dev/null +++ b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectControls.h @@ -0,0 +1,11 @@ +#pragma once + +class TUI_ControlObjectAdd : public TUI_CustomControl +{ +public: + TUI_ControlObjectAdd(int st, int act, ESceneToolBase *parent); + virtual ~TUI_ControlObjectAdd() { ; } + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); +}; diff --git a/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectTools.cpp b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectTools.cpp new file mode 100644 index 00000000000..41b0db4ed77 --- /dev/null +++ b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectTools.cpp @@ -0,0 +1,241 @@ +#include "stdafx.h" + +ESceneObjectTool::ESceneObjectTool() : ESceneCustomOTool(OBJCLASS_SCENEOBJECT) +{ + m_AppendRandomMinScale.set(1.f, 1.f, 1.f); + m_AppendRandomMaxScale.set(1.f, 1.f, 1.f); + m_AppendRandomMinRotation.set(0.f, 0.f, 0.f); + m_AppendRandomMaxRotation.set(0.f, 0.f, 0.f); + m_Flags.zero(); +} + +void ESceneObjectTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); + AddControl(xr_new(estDefault, etaAdd, this)); + // frame + pForm = xr_new(); + ((UIObjectTool *)pForm)->ParentTools = this; +} + +void ESceneObjectTool::RemoveControls() +{ + inherited::RemoveControls(); +} + +bool ESceneObjectTool::Validate(bool full_test) +{ + bool bRes = inherited::Validate(full_test); + // verify position & refs duplicate + CSceneObject *A, *B; + for (ObjectIt a_it = m_Objects.begin(); a_it != m_Objects.end(); a_it++) + { + A = (CSceneObject *)(*a_it); + for (ObjectIt b_it = m_Objects.begin(); b_it != m_Objects.end(); b_it++) + { + B = (CSceneObject *)(*b_it); + if (A == B) + continue; + if (A->RefCompare(B->GetReference())) + { + if (A->GetPosition().similar(B->GetPosition(), EPS_L)) + { + bRes = false; + ELog.Msg(mtError, "Duplicate object position '%s'-'%s' with reference '%s'.", A->GetName(), B->GetName(), A->RefName()); + } + } + } + // validate lods + if (full_test && A->IsMUStatic()) + { + CEditableObject *E = A->GetReference(); + VERIFY(E); + xr_string lod_name = E->GetLODTextureName(); + xr_string l_name = lod_name.c_str(); + string_path fn; + int age, age_nm; + //. FS.update_path (fn,_textures_,EFS.ChangeFileExt(l_name,".tga").c_str()); + FS.update_path(fn, _game_textures_, EFS.ChangeFileExt(l_name, ".dds").c_str()); + age = FS.get_file_age(fn); + if (age == -1) + Msg("!There is no texture '%s'", fn); + l_name += "_nm"; + //. FS.update_path (fn,_textures_,EFS.ChangeFileExt(l_name,".tga").c_str()); + FS.update_path(fn, _game_textures_, EFS.ChangeFileExt(l_name, ".dds").c_str()); + age_nm = FS.get_file_age(fn); + if (age_nm == -1) + Msg("!There is no texture '%s'", fn); + + if (age_nm == -1 || age == -1) + bRes = false; + /* + if ((age!=E->Version()) || (age_nm!=E->Version()) ) + { + Msg ("!Invalid LOD texture version: '%s'",E->GetName()); + Msg ("tex=%d obj=%d", age, E->Version()); + Msg ("tex=%d obj=%d", age_nm, E->Version()); + bRes = false; + } + */ + } + } + + return bRes; +} +//---------------------------------------------------- + +void ESceneObjectTool::OnChangeAppendRandomFlags(PropValue *prop) +{ + m_Flags.set(flAppendRandomUpdateProps, TRUE); + _SequenceToList(m_AppendRandomObjects, *m_AppendRandomObjectsStr); +} + +void ESceneObjectTool::FillAppendRandomPropertiesBegin(bool bUpdateOnly) +{ + + m_AppendRandomObjectsStr = _ListToSequence(m_AppendRandomObjects).c_str(); + + PropValue *V; + PropItemVec items; + V = PHelper().CreateFlag32(items, "Scale", &m_Flags, flAppendRandomScale); + V->OnChangeEvent.bind(this, &ESceneObjectTool::OnChangeAppendRandomFlags); + if (m_Flags.is(flAppendRandomScale)) + { + V = PHelper().CreateFlag32(items, "Scale\\Proportional", &m_Flags, flAppendRandomScaleProportional); + V->OnChangeEvent.bind(this, &ESceneObjectTool::OnChangeAppendRandomFlags); + if (m_Flags.is(flAppendRandomScaleProportional)) + { + PHelper().CreateFloat(items, "Scale\\Minimum", &m_AppendRandomMinScale.x, 0.001f, 1000.f, 0.001f, 3); + PHelper().CreateFloat(items, "Scale\\Maximum", &m_AppendRandomMaxScale.x, 0.001f, 1000.f, 0.001f, 3); + } + else + { + PHelper().CreateVector(items, "Scale\\Minimum", &m_AppendRandomMinScale, 0.001f, 1000.f, 0.001f, 3); + PHelper().CreateVector(items, "Scale\\Maximum", &m_AppendRandomMaxScale, 0.001f, 1000.f, 0.001f, 3); + } + } + + V = PHelper().CreateFlag32(items, "Rotate", &m_Flags, flAppendRandomRotation); + V->OnChangeEvent.bind(this, &ESceneObjectTool::OnChangeAppendRandomFlags); + if (m_Flags.is(flAppendRandomRotation)) + { + PHelper().CreateAngle3(items, "Rotate\\Minimum", &m_AppendRandomMinRotation); + PHelper().CreateAngle3(items, "Rotate\\Maximum", &m_AppendRandomMaxRotation); + } + V = PHelper().CreateChoose(items, "Objects", &m_AppendRandomObjectsStr, smObject, 0, 0, 32); + V->OnChangeEvent.bind(this, &ESceneObjectTool::OnChangeAppendRandomFlags); + if (bUpdateOnly) + UIPropertiesModal::GetProperties()->AssignItems(items); + else + UIPropertiesModal::Show(items); +} +bool ESceneObjectTool::FillAppendRandomPropertiesEnd() +{ + bool ok; + if (UIPropertiesModal::GetResult(ok)) + { + if (ok) + Scene->UndoSave(); + return true; + } + return false; +} +//---------------------------------------------------- + +void ESceneObjectTool::Clear(bool bSpecific) +{ + inherited::Clear(bSpecific); + m_AppendRandomMinScale.set(1.f, 1.f, 1.f); + m_AppendRandomMaxScale.set(1.f, 1.f, 1.f); + m_AppendRandomMinRotation.set(0.f, 0.f, 0.f); + m_AppendRandomMaxRotation.set(0.f, 0.f, 0.f); + m_AppendRandomObjects.clear(); + m_Flags.zero(); +} + +bool ESceneObjectTool::GetBox(Fbox &bb) +{ + bb.invalidate(); + Fbox bbo; + for (ObjectIt a_it = m_Objects.begin(); a_it != m_Objects.end(); a_it++) + { + (*a_it)->GetBox(bbo); + bb.merge(bbo); + } + return bb.is_valid(); +} + +void ESceneObjectTool::OnFrame() +{ + inherited::OnFrame(); + if (m_Flags.is(flAppendRandomUpdateProps)) + { + m_Flags.set(flAppendRandomUpdateProps, FALSE); + FillAppendRandomPropertiesBegin(true); + } +} + +CCustomObject *ESceneObjectTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} +//---------------------------------------------------- + +void ESceneObjectTool::HighlightTexture(LPCSTR tex_name, bool allow_ratio, u32 t_width, u32 t_height, BOOL mark) +{ + if (tex_name && tex_name[0]) + { + for (ObjectIt a_it = m_Objects.begin(); a_it != m_Objects.end(); a_it++) + { + CSceneObject *s_obj = dynamic_cast(*a_it); + if (s_obj->Visible()) + { + CEditableObject *e_obj = s_obj->GetReference(); + VERIFY(e_obj); + SurfaceVec &s_vec = e_obj->Surfaces(); + for (SurfaceIt it = s_vec.begin(); it != s_vec.end(); it++) + { + if (0 == stricmp((*it)->_Texture(), tex_name)) + { + Fvector verts[3]; + for (EditMeshIt mesh_it = e_obj->FirstMesh(); mesh_it != e_obj->LastMesh(); mesh_it++) + { + const SurfFaces &surf_faces = (*mesh_it)->GetSurfFaces(); + SurfFaces::const_iterator sf_it = surf_faces.find(*it); + if (sf_it != surf_faces.end()) + { + const IntVec &lst = sf_it->second; + for (IntVec::const_iterator i_it = lst.begin(); i_it != lst.end(); i_it++) + { + e_obj->GetFaceWorld(s_obj->_Transform(), *mesh_it, *i_it, verts); + u32 clr = 0x80FFFFFF; + if (allow_ratio) + { + // select color + const Fvector2 *tc[3]; + Fvector c, e01, e02; + e01.sub(verts[1], verts[0]); + e02.sub(verts[2], verts[0]); + float area = c.crossproduct(e01, e02).magnitude() / 2.f; + (*mesh_it)->GetFaceTC(*i_it, tc); + e01.sub(Fvector().set(tc[1]->x, tc[1]->y, 0), Fvector().set(tc[0]->x, tc[0]->y, 0)); + e02.sub(Fvector().set(tc[2]->x, tc[2]->y, 0), Fvector().set(tc[0]->x, tc[0]->y, 0)); + float p_area = c.crossproduct(e01, e02).magnitude() / 2.f; + float pm = _sqrt((p_area * t_width * t_height) / area); + clr = SSceneSummary::SelectPMColor(pm); + } + Tools->m_DebugDraw.AppendSolidFace(verts[0], verts[1], verts[2], clr, false); + if (mark) + Tools->m_DebugDraw.AppendWireFace(verts[0], verts[1], verts[2], clr, false); + } + } + } + } + } + } + } + } +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectTools.h b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectTools.h new file mode 100644 index 00000000000..113fc9d3731 --- /dev/null +++ b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectTools.h @@ -0,0 +1,78 @@ +#pragma once + +class ESceneObjectTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + + enum + { + flAppendRandomUpdateProps = (1 << 27), + flAppendRandomScaleProportional = (1 << 28), + flAppendRandom = (1 << 29), + flAppendRandomScale = (1 << 30), + flAppendRandomRotation = (1 << 31), + }; + Flags32 m_Flags; + bool ExportBreakableObjects(SExportStreams *F); + bool ExportClimableObjects(SExportStreams *F); + + void OnChangeAppendRandomFlags(PropValue *prop); + +public: + Fvector m_AppendRandomMinScale; + Fvector m_AppendRandomMaxScale; + Fvector m_AppendRandomMinRotation; + Fvector m_AppendRandomMaxRotation; + shared_str m_AppendRandomObjectsStr; + RStringVec m_AppendRandomObjects; + +public: + ESceneObjectTool(); + + virtual bool AllowEnabling() { return false; } + + virtual bool Validate(bool full_build); + + virtual void OnFrame(); + + // definition + IC LPCSTR ClassName() { return "scene_object"; } + IC LPCSTR ClassDesc() { return "Scene Object"; } + IC int RenderPriority() { return 1; } + + bool GetBox(Fbox &bb); + + virtual void Clear(bool bSpecific = false); + // IO + virtual bool IsNeedSave() { return true; } + + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + // append random + void FillAppendRandomPropertiesBegin(bool bUpdateOnly = false); + bool FillAppendRandomPropertiesEnd(); + void ActivateAppendRandom(BOOL val) { m_Flags.set(flAppendRandom, val); } + BOOL IsAppendRandomActive() { return m_Flags.is(flAppendRandom); } + BOOL IsAppendRandomScaleActive() { return m_Flags.is(flAppendRandomScale); } + BOOL IsAppendRandomRotationActive() { return m_Flags.is(flAppendRandomRotation); } + BOOL IsAppendRandomScaleProportional() { return m_Flags.is(flAppendRandomScaleProportional); } + + // tools + virtual bool ExportGame(SExportStreams *F); + virtual void GetStaticDesc(int &v_cnt, int &f_cnt, bool b_selected_only, bool b_cform); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); + + virtual void HighlightTexture(LPCSTR tex_name, bool allow_ratio, u32 t_width, u32 t_height, BOOL mark); +}; diff --git a/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectToolsExportBreakable.cpp b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectToolsExportBreakable.cpp new file mode 100644 index 00000000000..09c48aa75ec --- /dev/null +++ b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectToolsExportBreakable.cpp @@ -0,0 +1,334 @@ +#include "stdafx.h" + +static bool s_draw_dbg = false; + +IC bool build_mesh(const Fmatrix &parent, CEditableMesh *mesh, CGeomPartExtractor *extractor, u32 game_mtl_mask, BOOL ignore_shader) +{ + bool bResult = true; + mesh->GenerateVNormals(&parent); + // fill faces + for (SurfFaces::const_iterator sp_it = mesh->GetSurfFaces().begin(); sp_it != mesh->GetSurfFaces().end(); sp_it++) + { + const IntVec &face_lst = sp_it->second; + CSurface *surf = sp_it->first; + int gm_id = surf->_GameMtl(); + if (gm_id == GAMEMTL_NONE_ID) + { + ELog.DlgMsg(mtError, "Object '%s', surface '%s' contain invalid game material.", mesh->Parent()->m_LibName.c_str(), surf->_Name()); + bResult = FALSE; + break; + } + SGameMtl *M = GMLib.GetMaterialByID(gm_id); + if (0 == M) + { + ELog.DlgMsg(mtError, "Object '%s', surface '%s' contain undefined game material.", mesh->Parent()->m_LibName.c_str(), surf->_Name()); + bResult = FALSE; + break; + } + if (!M->Flags.is(game_mtl_mask)) + continue; + + // check engine shader compatibility + if (!ignore_shader) + { + IBlender *B = EDevice.Resources->_FindBlender(surf->_ShaderName()); + if (FALSE == B) + { + ELog.Msg(mtError, "Can't find engine shader '%s'. Object '%s', surface '%s'. Export interrupted.", surf->_ShaderName(), mesh->Parent()->m_LibName.c_str(), surf->_Name()); + bResult = FALSE; + break; + } + if (TRUE == B->canBeLMAPped()) + { + ELog.Msg(mtError, "Object '%s', surface '%s' contain static engine shader - '%s'. Export interrupted.", mesh->Parent()->m_LibName.c_str(), surf->_Name(), surf->_ShaderName()); + bResult = FALSE; + break; + } + } + + const st_Face *faces = mesh->GetFaces(); + VERIFY(faces); + const Fvector *vn = mesh->GetVNormals(); + VERIFY(vn); + const Fvector *pts = mesh->GetVertices(); + VERIFY(pts); + for (IntVec::const_iterator f_it = face_lst.begin(); f_it != face_lst.end(); f_it++) + { + const st_Face &face = faces[*f_it]; + Fvector v[3], n[3]; + parent.transform_tiny(v[0], pts[face.pv[0].pindex]); + parent.transform_tiny(v[1], pts[face.pv[1].pindex]); + parent.transform_tiny(v[2], pts[face.pv[2].pindex]); + parent.transform_dir(n[0], vn[*f_it * 3 + 0]); + n[0].normalize(); + parent.transform_dir(n[1], vn[*f_it * 3 + 1]); + n[1].normalize(); + parent.transform_dir(n[2], vn[*f_it * 3 + 2]); + n[2].normalize(); + const Fvector2 *uv[3]; + mesh->GetFaceTC(*f_it, uv); + extractor->AppendFace(surf, v, n, uv); + } + if (!bResult) + break; + } + mesh->UnloadVNormals(); + return bResult; +} + +bool ESceneObjectTool::ExportBreakableObjects(SExportStreams *F) +{ + bool bResult = true; + CGeomPartExtractor *extractor = 0; + + Fbox bb; + if (!GetBox(bb)) + return false; + + extractor = xr_new(); + extractor->Initialize(bb, EPS_L, 2); + + UI->SetStatus("Export breakable objects..."); + // collect verts&&faces + { + SPBItem *pb = UI->ProgressStart(static_cast(m_Objects.size()), "Prepare geometry..."); + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + { + pb->Inc(); + CSceneObject *obj = dynamic_cast(*it); + VERIFY(obj); + if (obj->IsStatic()) + { + CEditableObject *O = obj->GetReference(); + const Fmatrix &T = obj->_Transform(); + for (EditMeshIt M = O->FirstMesh(); M != O->LastMesh(); M++) + if (!build_mesh(T, *M, extractor, SGameMtl::flBreakable, FALSE)) + { + bResult = false; + break; + } + } + } + UI->ProgressEnd(pb); + } + if (!extractor->Process()) + bResult = false; + // export parts + if (bResult) + { + SBPartVec &parts = extractor->GetParts(); + SPBItem *pb = UI->ProgressStart(static_cast(parts.size()), "Export Parts..."); + for (SBPartVecIt p_it = parts.begin(); p_it != parts.end(); p_it++) + { + pb->Inc(); + SBPart *P = *p_it; + if (P->Valid()) + { + // export visual + xr_string sn = make_string("meshes\\brkbl#%d.ogf", (p_it - parts.begin())).c_str(); + xr_string fn = Scene->LevelPath() + sn.c_str(); + IWriter *W = FS.w_open(fn.c_str()); + R_ASSERT(W); + if (!P->Export(*W, 1)) + { + ELog.DlgMsg(mtError, "Invalid breakable object."); + bResult = false; + break; + } + FS.w_close(W); + // export spawn object + { + xr_string entity_ref = "breakable_object"; + IServerEntity* m_Data = xrSE_Factory::create_entity(entity_ref.c_str()); + VERIFY(m_Data); + CSE_Visual *m_Visual = m_Data->visual(); + VERIFY(m_Visual); + // set params + m_Data->set_name(entity_ref.c_str()); + m_Data->set_name_replace(sn.c_str()); + m_Data->position().set(P->m_RefOffset); + m_Data->angle().set(P->m_RefRotate); + m_Visual->set_visual(sn.c_str(), false); + + if (s_draw_dbg) + { + Fmatrix MX; + MX.setXYZi(P->m_RefRotate); + MX.translate_over(P->m_RefOffset); + Fvector DR = {0, 0, 1}; + MX.transform_dir(DR); + Tools->m_DebugDraw.AppendLine(P->m_RefOffset, Fvector().mad(P->m_RefOffset, MX.k, 1.f), 0xFF0000FF, false, false); + } + + NET_Packet Packet; + m_Data->Spawn_Write(Packet, TRUE); + + F->spawn.stream.open_chunk(F->spawn.chunk++); + F->spawn.stream.w(Packet.B.data, Packet.B.count); + F->spawn.stream.close_chunk(); + xrSE_Factory::destroy_entity(m_Data); + } + } + else + { + ELog.Msg(mtError, "Can't export invalid part #%d", p_it - parts.begin()); + } + } + UI->ProgressEnd(pb); + } + // clean up + xr_delete(extractor); + + return bResult; +} +//---------------------------------------------------- + +IC BOOL OrientToNorm(Fvector &local_norm, Fmatrix33 &form, Fvector &hs) +{ + Fvector *ax_pointer = (Fvector *)&form; + int max_proj = 0, min_size = 0; + for (u32 k = 1; k < 3; k++) + { + if (_abs(local_norm[k]) > _abs(local_norm[max_proj])) + max_proj = k; + if (hs[k] < hs[min_size]) + min_size = k; + } + if (min_size != max_proj) + return FALSE; + if (local_norm[max_proj] < 0.f) + { + local_norm.invert(); + ax_pointer[max_proj].invert(); + ax_pointer[(max_proj + 1) % 3].invert(); + } + return TRUE; +} + +bool ESceneObjectTool::ExportClimableObjects(SExportStreams *F) +{ + bool bResult = true; + CGeomPartExtractor *extractor = 0; + + Fbox bb; + if (!GetBox(bb)) + return false; + + extractor = xr_new(); + extractor->Initialize(bb, EPS_L, int_max); + + UI->SetStatus("Export climable objects..."); + // collect verts&&faces + { + SPBItem *pb = UI->ProgressStart(static_cast(m_Objects.size()), "Prepare geometry..."); + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + { + pb->Inc(); + CSceneObject *obj = dynamic_cast(*it); + VERIFY(obj); + if (obj->IsStatic()) + { + CEditableObject *O = obj->GetReference(); + const Fmatrix &T = obj->_Transform(); + + for (EditMeshIt M = O->FirstMesh(); M != O->LastMesh(); M++) + if (!build_mesh(T, *M, extractor, SGameMtl::flClimable, TRUE)) + { + bResult = false; + break; + } + } + } + UI->ProgressEnd(pb); + } + if (!extractor->Process()) + bResult = false; + + // export parts + if (bResult) + { + SBPartVec &parts = extractor->GetParts(); + SPBItem *pb = UI->ProgressStart(static_cast(parts.size()), "Export Parts..."); + for (SBPartVecIt p_it = parts.begin(); p_it != parts.end(); p_it++) + { + pb->Inc(); + SBPart *P = *p_it; + if (P->Valid()) + { + // export visual + xr_string sn = make_string("clmbl#%d", (p_it - parts.begin())).c_str(); + + Fvector local_normal = {0, 0, 0}; + + LPCSTR mat_name = NULL; + for (SBFaceVecIt it = P->m_Faces.begin(); it != P->m_Faces.end(); it++) + { + for (u32 k = 0; k < 3; k++) + local_normal.add((*it)->n[k]); + + mat_name = (*it)->surf->_GameMtlName(); + } + + local_normal.normalize_safe(); + + // export spawn object + { + xr_string entity_ref = "climable_object"; + IServerEntity* m_Data = xrSE_Factory::create_entity(entity_ref.c_str()); + VERIFY(m_Data); + IServerEntityShape* m_Shape = m_Data->shape(); + VERIFY(m_Shape); + // CSE_Visual* m_Visual = m_Data->visual(); VERIFY(m_Visual); + // set params + m_Data->set_name(entity_ref.c_str()); + m_Data->set_name_replace(sn.c_str()); + // set shape + CShapeData::shape_def shape; + shape.type = CShapeData::cfBox; + shape.data.box.scale((P->m_BBox.vMax.x - P->m_BBox.vMin.x) * 0.5f, + (P->m_BBox.vMax.y - P->m_BBox.vMin.y) * 0.5f, + (P->m_BBox.vMax.z - P->m_BBox.vMin.z) * 0.5f); + m_Shape->assign_shapes(&shape, 1); + // orientate object + if (!OrientToNorm(local_normal, P->m_OBB.m_rotate, P->m_OBB.m_halfsize)) + { + ELog.Msg(mtError, "Invalid climable object found. [%3.2f, %3.2f, %3.2f]", VPUSH(P->m_RefOffset)); + } + else + { + Fmatrix M; + M.set(P->m_OBB.m_rotate.i, P->m_OBB.m_rotate.j, P->m_OBB.m_rotate.k, P->m_OBB.m_translate); + M.getXYZ(P->m_RefRotate); // не i потому что в движке так + m_Data->position().set(P->m_RefOffset); + m_Data->angle().set(P->m_RefRotate); + + m_Data->set_additional_info((void *)mat_name); + NET_Packet Packet; + m_Data->Spawn_Write(Packet, TRUE); + + F->spawn.stream.open_chunk(F->spawn.chunk++); + F->spawn.stream.w(Packet.B.data, Packet.B.count); + F->spawn.stream.close_chunk(); + + if (s_draw_dbg) + { + Tools->m_DebugDraw.AppendOBB(P->m_OBB); + M.transform_dir(local_normal); + Tools->m_DebugDraw.AppendLine(P->m_RefOffset, Fvector().mad(P->m_RefOffset, local_normal, 1.f)); + } + } + xrSE_Factory::destroy_entity(m_Data); + } + } + else + { + ELog.Msg(mtError, "Can't export invalid part #%d", p_it - parts.begin()); + } + } + UI->ProgressEnd(pb); + } + // clean up + xr_delete(extractor); + + return bResult; +} diff --git a/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectToolsIO.cpp b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectToolsIO.cpp new file mode 100644 index 00000000000..fc2ee74761e --- /dev/null +++ b/src/editors/LevelEditor/Tools/StaticObject/ESceneObjectToolsIO.cpp @@ -0,0 +1,190 @@ +#include "stdafx.h" + +// chunks +static const u16 OBJECT_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, + CHUNK_APPEND_RANDOM = 0x1002ul, + CHUNK_FLAGS = 0x1003ul, +}; +bool ESceneObjectTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + if (version != OBJECT_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + + m_Flags.assign(ini.r_u32("main", "flags")); + + m_AppendRandomMinScale = ini.r_fvector3("AppendRandom", "AppendRandomMinScale"); + m_AppendRandomMaxScale = ini.r_fvector3("AppendRandom", "AppendRandomMaxScale"); + m_AppendRandomMinRotation = ini.r_fvector3("AppendRandom", "AppendRandomMinRotation"); + m_AppendRandomMaxRotation = ini.r_fvector3("AppendRandom", "AppendRandomMaxRotation"); + u32 cnt = ini.r_u32("AppendRandom", "AppendRandomObjects_size"); + + for (int i = 0; i < cnt; ++i) + { + string128 buff; + sprintf(buff, "object_name_%d", i); + shared_str s = ini.r_string("AppendRandom", buff); + m_AppendRandomObjects.push_back(s); + } + + m_Flags.set(flAppendRandom, FALSE); + + return true; +} + +void ESceneObjectTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + + ini.w_u32("main", "version", OBJECT_TOOLS_VERSION); + + ini.w_u32("main", "flags", m_Flags.get()); + + ini.w_fvector3("AppendRandom", "AppendRandomMinScale", m_AppendRandomMinScale); + ini.w_fvector3("AppendRandom", "AppendRandomMaxScale", m_AppendRandomMaxScale); + ini.w_fvector3("AppendRandom", "AppendRandomMinRotation", m_AppendRandomMinRotation); + ini.w_fvector3("AppendRandom", "AppendRandomMaxRotation", m_AppendRandomMaxRotation); + ini.w_u32("AppendRandom", "AppendRandomObjects_size", m_AppendRandomObjects.size()); + + if (m_AppendRandomObjects.size()) + { + u32 i = 0; + for (RStringVecIt it = m_AppendRandomObjects.begin(); it != m_AppendRandomObjects.end(); ++it, ++i) + { + string128 buff; + sprintf(buff, "object_name_%d", i); + ini.w_string("AppendRandom", buff, (*it).c_str()); + } + } +} + +bool ESceneObjectTool::LoadStream(IReader &F) +{ + u16 version = 0; + if (F.r_chunk(CHUNK_VERSION, &version)) + { + if (version != OBJECT_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + } + if (!inherited::LoadStream(F)) + return false; + + if (F.find_chunk(CHUNK_FLAGS)) + m_Flags.assign(F.r_u32()); + + if (F.find_chunk(CHUNK_APPEND_RANDOM)) + { + F.r_fvector3(m_AppendRandomMinScale); + F.r_fvector3(m_AppendRandomMaxScale); + F.r_fvector3(m_AppendRandomMinRotation); + F.r_fvector3(m_AppendRandomMaxRotation); + int cnt = F.r_u32(); + if (cnt) + { + shared_str buf; + for (int i = 0; i < cnt; i++) + { + F.r_stringZ(buf); + m_AppendRandomObjects.push_back(buf); + } + } + }; + + m_Flags.set(flAppendRandom, FALSE); + + return true; +} +//---------------------------------------------------- + +void ESceneObjectTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.w_chunk(CHUNK_VERSION, (u16 *)&OBJECT_TOOLS_VERSION, sizeof(OBJECT_TOOLS_VERSION)); + + F.open_chunk(CHUNK_FLAGS); + F.w_u32(m_Flags.get()); + F.close_chunk(); + + F.open_chunk(CHUNK_APPEND_RANDOM); + F.w_fvector3(m_AppendRandomMinScale); + F.w_fvector3(m_AppendRandomMaxScale); + F.w_fvector3(m_AppendRandomMinRotation); + F.w_fvector3(m_AppendRandomMaxRotation); + F.w_u32(m_AppendRandomObjects.size()); + if (m_AppendRandomObjects.size()) + { + for (RStringVecIt it = m_AppendRandomObjects.begin(); it != m_AppendRandomObjects.end(); ++it) + F.w_stringZ(*it); + } + F.close_chunk(); +} +//---------------------------------------------------- + +bool ESceneObjectTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + if (version != OBJECT_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} +//---------------------------------------------------- + +void ESceneObjectTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&OBJECT_TOOLS_VERSION, sizeof(OBJECT_TOOLS_VERSION)); + + inherited::SaveSelection(F); +} + +//---------------------------------------------------- + +bool ESceneObjectTool::ExportGame(SExportStreams *F) +{ + if (!inherited::ExportGame(F)) + return false; + + // export breakable objects + if (!ExportBreakableObjects(F)) + return false; + if (!ExportClimableObjects(F)) + return false; + + return true; +} +//---------------------------------------------------- + +void ESceneObjectTool::GetStaticDesc(int &v_cnt, int &f_cnt, bool b_selected_only, bool b_cform) +{ + for (ObjectIt it = m_Objects.begin(); it != m_Objects.end(); it++) + { + CSceneObject *obj = (CSceneObject *)(*it); + + if (b_selected_only && !obj->Selected()) + continue; + + if (obj->IsStatic() || (b_cform && obj->IsMUStatic())) + { + f_cnt += obj->GetFaceCount(); + v_cnt += obj->GetVertexCount(); + } + } +} +//---------------------------------------------------- diff --git a/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkControls.cpp b/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkControls.cpp new file mode 100644 index 00000000000..1f91045584c --- /dev/null +++ b/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkControls.cpp @@ -0,0 +1,64 @@ +#include "stdafx.h" + +// Node Add +TUI_ControlWallmarkAdd::TUI_ControlWallmarkAdd(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} + +bool TUI_ControlWallmarkAdd::Start(TShiftState Shift) +{ + ESceneWallmarkTool *S = (ESceneWallmarkTool *)parent_tool; + + S->SelectObjects(false); + wm_cnt = 0; + if (S->AddWallmark(UI->m_CurrentRStart, UI->m_CurrentRDir)) + { + wm_cnt++; + if (!(Shift & ssAlt)) + { + Scene->UndoSave(); + ResetActionToSelect(); + return false; + } + else + return true; + } + return false; +} +void TUI_ControlWallmarkAdd::Move(TShiftState _Shift) +{ +} +bool TUI_ControlWallmarkAdd::End(TShiftState _Shift) +{ + if (!(_Shift & ssAlt)) + ResetActionToSelect(); + if (wm_cnt) + Scene->UndoSave(); + return true; +} + +//------------------------------------------------------------------------------------ +// WM Move +//------------------------------------------------------------------------------------ +TUI_ControlWallmarkMove::TUI_ControlWallmarkMove(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} +bool TUI_ControlWallmarkMove::Start(TShiftState Shift) +{ + if ((Shift & ssCtrl)) + { + ESceneWallmarkTool *S = (ESceneWallmarkTool *)parent_tool; + if (S->MoveSelectedWallmarkTo(UI->m_CurrentRStart, UI->m_CurrentRDir)) + Scene->UndoSave(); + } + return false; +} + +void TUI_ControlWallmarkMove::Move(TShiftState _Shift) +{ +} + +bool TUI_ControlWallmarkMove::End(TShiftState _Shift) +{ + return false; +} diff --git a/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkControls.h b/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkControls.h new file mode 100644 index 00000000000..a033af25b8a --- /dev/null +++ b/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkControls.h @@ -0,0 +1,26 @@ +#pragma once + +// refs +class ESceneWallmarkTools; + +class TUI_ControlWallmarkAdd : public TUI_CustomControl +{ + u32 wm_cnt; + +public: + TUI_ControlWallmarkAdd(int st, int act, ESceneToolBase *parent); + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); +}; + +class TUI_ControlWallmarkMove : public TUI_CustomControl +{ + u32 wm_cnt; + +public: + TUI_ControlWallmarkMove(int st, int act, ESceneToolBase *parent); + virtual bool Start(TShiftState _Shift); + virtual bool End(TShiftState _Shift); + virtual void Move(TShiftState _Shift); +}; diff --git a/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkTools.cpp b/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkTools.cpp new file mode 100644 index 00000000000..b22a6f78d09 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkTools.cpp @@ -0,0 +1,1025 @@ +#include "stdafx.h" + +// chunks +#define WM_VERSION 0x0004 + +#define WM_CHUNK_VERSION 0x0001 +#define WM_CHUNK_FLAGS 0x0002 +#define WM_CHUNK_PARAMS 0x0003 +#define WM_CHUNK_ITEMS 0x0004 +#define WM_CHUNK_ITEMS2 0x0005 +//---------------------------------------------------- + +#define MAX_WALLMARK_COUNT 500 +#define MAX_WALLMARK_VERTEX_COUNT 8192 +#define COMPILER_SHADER "def_shaders\\def_vertex_ghost_no_shadow" + +ESceneWallmarkTool::ESceneWallmarkTool() : ESceneToolBase(OBJCLASS_WM) +{ + m_MarkWidth = 1.f; + m_MarkHeight = 1.f; + m_MarkRotate = 0.f; + m_Flags.assign(flDrawWallmark); + //. m_ShName = "effects\\wallmarkblend"; + m_ShName = "effects\\wallmarkmult"; + m_TxName = ""; +} + +ESceneWallmarkTool::~ESceneWallmarkTool() +{ +} + +int ESceneWallmarkTool::RaySelect(int flag, float &distance, const Fvector &start, const Fvector &direction, BOOL bDistanceOnly) +{ + if (!m_Flags.is(flDrawWallmark)) + return 0; + + wallmark *W = 0; + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + wm_slot *slot = *slot_it; + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + Fvector pt; + if (Fbox::rpOriginOutside == (*w_it)->bbox.Pick2(start, direction, pt)) + { + float range = start.distance_to(pt); + if (range < distance) + { + W = *w_it; + distance = range; + } + } + } + } + if (W && !bDistanceOnly) + { + if (flag == -1) + W->flags.invert(wallmark::flSelected); + W->flags.set(wallmark::flSelected, flag); + return 1; + } + return 0; +} + +int ESceneWallmarkTool::FrustumSelect(int flag, const CFrustum &frustum) +{ + if (!m_Flags.is(flDrawWallmark)) + return 0; + + int count = 0; + for (WMSVecIt p_it = marks.begin(); p_it != marks.end(); p_it++) + { + for (WMVecIt m_it = (*p_it)->items.begin(); m_it != (*p_it)->items.end(); m_it++) + { + wallmark *W = *m_it; + u32 mask = 0xffff; + if (frustum.testSAABB(W->bounds.P, W->bounds.R, W->bbox.data(), mask)) + { + if (-1 == flag) + W->flags.invert(wallmark::flSelected); + else + W->flags.set(wallmark::flSelected, flag); + count++; + } + } + } + UI->RedrawScene(); + return count; +} + +void ESceneWallmarkTool::SelectObjects(bool flag) +{ + if (!m_Flags.is(flDrawWallmark)) + return; + for (WMSVecIt p_it = marks.begin(); p_it != marks.end(); p_it++) + { + for (WMVecIt m_it = (*p_it)->items.begin(); m_it != (*p_it)->items.end(); m_it++) + (*m_it)->flags.set(wallmark::flSelected, flag); + } + UI->RedrawScene(); +} + +void ESceneWallmarkTool::InvertSelection() +{ + if (!m_Flags.is(flDrawWallmark)) + return; + for (WMSVecIt p_it = marks.begin(); p_it != marks.end(); p_it++) + { + for (WMVecIt m_it = (*p_it)->items.begin(); m_it != (*p_it)->items.end(); m_it++) + (*m_it)->flags.invert(wallmark::flSelected); + } + UI->RedrawScene(); +} + +void ESceneWallmarkTool::RemoveSelection() +{ + if (!m_Flags.is(flDrawWallmark)) + return; + for (WMSVecIt p_it = marks.begin(); p_it != marks.end(); p_it++) + { + for (WMVecIt m_it = (*p_it)->items.begin(); m_it != (*p_it)->items.end();) + if ((*m_it)->flags.is(wallmark::flSelected)) + { + wm_destroy(*m_it); + *m_it = (*p_it)->items.back(); + (*p_it)->items.pop_back(); + } + else + { + m_it++; + } + } + UI->RedrawScene(); +} + +int ESceneWallmarkTool::SelectionCount(bool testflag) +{ + if (!m_Flags.is(flDrawWallmark)) + return 0; + int count = 0; + for (WMSVecIt p_it = marks.begin(); p_it != marks.end(); p_it++) + for (WMVecIt m_it = (*p_it)->items.begin(); m_it != (*p_it)->items.end(); m_it++) + if ((*m_it)->flags.is(wallmark::flSelected)) + count++; + return count; +} + +void ESceneWallmarkTool::Clear(bool bOnlyNodes) +{ + inherited::Clear(); + { + for (WMSVecIt p_it = marks.begin(); p_it != marks.end(); p_it++) + { + for (WMVecIt m_it = (*p_it)->items.begin(); m_it != (*p_it)->items.end(); m_it++) + wm_destroy(*m_it); + xr_delete(*p_it); + } + marks.clear(); + } + { + for (u32 it = 0; it < pool.size(); it++) + xr_delete(pool[it]); + pool.clear(); + } +} + +bool ESceneWallmarkTool::Valid() { return !marks.empty(); } +bool ESceneWallmarkTool::IsNeedSave() { return marks.size(); } +void ESceneWallmarkTool::OnFrame() {} + +struct zero_slot_pred +{ + template + bool operator()(const C x) { return x == 0; } +}; +void ESceneWallmarkTool::RefiningSlots() +{ + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + wm_slot *&slot = *slot_it; + if (slot->items.empty()) + xr_delete(slot); + } + WMSVecIt new_end = std::remove_if(marks.begin(), marks.end(), zero_slot_pred()); + marks.erase(new_end, marks.end()); +} + +extern ECORE_API float r_ssaDISCARD; +const int MAX_R_VERTEX = 4096; + +void ESceneWallmarkTool::OnRender(int priority, bool strictB2F) +{ + if (!m_Flags.is(flDrawWallmark)) + return; + if (marks.empty()) + return; + + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + wm_slot *slot = *slot_it; + VERIFY(slot->shader); + if ((u32(priority) == slot->shader->E[0]->flags.iPriority) && (strictB2F == !!(slot->shader->E[0]->flags.bStrictB2F))) + { + // Projection and xform + float _43 = EDevice.mProject._43; + EDevice.mProject._43 -= 0.01f; + RCache.set_xform_world(Fidentity); + RCache.set_xform_project(EDevice.mProject); + + float ssaCLIP = r_ssaDISCARD / 4; + + u32 w_offset = 0; + FVF::LIT* w_verts = (FVF::LIT*)RImplementation.Vertex.Lock(MAX_R_VERTEX, hGeom->vb_stride, w_offset); + FVF::LIT *w_start = w_verts; + + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + wallmark *W = *w_it; + VERIFY3(W->verts.size() <= MAX_R_VERTEX, "ERROR: Invalid wallmark.", *slot->tx_name); + if (RImplementation.ViewBase.testSphere_dirty(W->bounds.P, W->bounds.R)) + { + float dst = EDevice.vCameraPosition.distance_to_sqr(W->bounds.P); + float ssa = W->bounds.R * W->bounds.R / dst; + if (ssa >= ssaCLIP) + { + // fill wallmark + u32 C = color_rgba(255, 255, 255, 255); + int t_cnt = W->verts.size() / 3; + for (int t_idx = 0; t_idx < t_cnt; t_idx++) + { + u32 w_count = u32(w_verts - w_start); + if (w_count + 3 > MAX_R_VERTEX) + { + // Flush stream + RImplementation.Vertex.Unlock(w_count, hGeom->vb_stride); + RCache.set_Shader(slot->shader); + RCache.set_Geometry(hGeom); + RCache.Render(D3DPT_TRIANGLELIST, w_offset, w_count / 3); + // Restart (re-lock/re-calc) + w_verts = + (FVF::LIT*)RImplementation.Vertex.Lock(MAX_R_VERTEX, hGeom->vb_stride, w_offset); + w_start = w_verts; + } + // real fill buffer + FVF::LIT *S = W->verts.data() + t_idx * 3; + for (int k = 0; k < 3; k++, S++, w_verts++) + { + w_verts->p.set(S->p); + w_verts->color = C; + w_verts->t.set(S->t); + } + } + } + } + } + // Flush stream + u32 w_count = u32(w_verts - w_start); + RImplementation.Vertex.Unlock(w_count, hGeom->vb_stride); + if (w_count) + { + RCache.set_Shader(slot->shader); + RCache.set_Geometry(hGeom); + RCache.Render(D3DPT_TRIANGLELIST, w_offset, w_count / 3); + } + // Projection + EDevice.mProject._43 = _43; + RCache.set_xform_project(EDevice.mProject); + } + if ((1 == priority) && (false == strictB2F)) + { + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + wallmark *W = *w_it; + if (W->flags.is(wallmark::flSelected)) + if (RImplementation.ViewBase.testSphere_dirty(W->bounds.P, W->bounds.R)) + DU_impl.DrawSelectionBoxB(W->bbox); + } + } + } +} + +struct zero_item_pred +{ + template + bool operator()(const C x) { return x == 0; } +}; +bool ESceneWallmarkTool::LoadLTX(CInifile &ini) +{ + R_ASSERT(0); + return true; +} +void ESceneWallmarkTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + + ini.w_u32("main", "version", WM_VERSION); + + ini.w_u32("main", "flags", m_Flags.get()); + + ini.w_float("main", "mark_width", m_MarkWidth); + ini.w_float("main", "mark_height", m_MarkHeight); + ini.w_float("main", "mark_rotate", m_MarkRotate); + ini.w_string("main", "sh_name", m_ShName.c_str()); + ini.w_string("main", "tx_name", m_TxName.c_str()); + + u32 i = 0; + string128 buff, buff2; + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); ++slot_it, ++i) + { + wm_slot *slot = *slot_it; + + sprintf(buff, "slot_%d", i); + ini.w_u32(buff, "items_count", slot->items.size()); + if (slot->items.size() == 0) + continue; + + ini.w_string(buff, "sh_name", slot->sh_name.c_str()); + ini.w_string(buff, "tx_name", slot->tx_name.c_str()); + + u32 ii = 0; + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); ++w_it, ++ii) + { + wallmark *W = *w_it; + sprintf(buff2, "itm_%d_flags", ii); + ini.w_u32(buff, buff2, W->flags.get()); + + sprintf(buff2, "itm_%d_bb_min", ii); + ini.w_fvector3(buff, buff2, W->bbox.vMin); + sprintf(buff2, "itm_%d_bb_max", ii); + ini.w_fvector3(buff, buff2, W->bbox.vMax); + + sprintf(buff2, "itm_%d_bsphere_p", ii); + ini.w_fvector3(buff, buff2, W->bounds.P); + sprintf(buff2, "itm_%d_bsphere_r", ii); + ini.w_float(buff, buff2, W->bounds.R); + + sprintf(buff2, "itm_%d_w", ii); + ini.w_float(buff, buff2, W->w); + sprintf(buff2, "itm_%d_h", ii); + ini.w_float(buff, buff2, W->h); + sprintf(buff2, "itm_%d_r", ii); + ini.w_float(buff, buff2, W->r); + + sprintf(buff2, "itm_%d_vert_cnt", ii); + ini.w_u32(buff, buff2, W->verts.size()); + + R_ASSERT2(0, "not_implemented"); + //. F.w (&*W->verts.begin(),sizeof(FVF::LIT)*W->verts.size()); + } + } +} + +bool ESceneWallmarkTool::LoadStream(IReader &F) +{ + inherited::LoadStream(F); + u16 version = 0; + R_ASSERT(F.r_chunk(WM_CHUNK_VERSION, &version)); + + if (version != 0x0003 && version != WM_VERSION) + { + ELog.Msg(mtError, "Static Wallmark: Unsupported version."); + return false; + } + + R_ASSERT(F.find_chunk(WM_CHUNK_FLAGS)); + F.r(&m_Flags, sizeof(m_Flags)); + + R_ASSERT(F.find_chunk(WM_CHUNK_PARAMS)); + m_MarkWidth = F.r_float(); + m_MarkHeight = F.r_float(); + m_MarkRotate = F.r_float(); + F.r_stringZ(m_ShName); + + if (version == 0x0003) + m_ShName = "effects\\wallmarkmult"; + + F.r_stringZ(m_TxName); + + IReader *OBJ = F.open_chunk(WM_CHUNK_ITEMS); + if (OBJ) + { + IReader *O = OBJ->open_chunk(0); + for (int count = 1; O; count++) + { + u32 item_count = O->r_u32(); + if (item_count) + { + shared_str tex_name, sh_name; + O->r_stringZ(sh_name); + O->r_stringZ(tex_name); + wm_slot *slot = AppendSlot(sh_name, tex_name); + if (slot) + { + slot->items.resize(item_count); + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + *w_it = wm_allocate(); + wallmark *W = *w_it; + O->r(&W->flags, sizeof(W->flags)); + O->r(&W->bbox, sizeof(W->bbox)); + O->r(&W->bounds, sizeof(W->bounds)); + W->parent = slot; + W->w = 1.f; + W->h = 1.f; + W->r = 1.f; + W->verts.resize(O->r_u32()); + O->r(&*W->verts.begin(), sizeof(FVF::LIT) * W->verts.size()); + } + } + } + O->close(); + O = OBJ->open_chunk(count); + } + OBJ->close(); + } + else + { + IReader *OBJ = F.open_chunk(WM_CHUNK_ITEMS2); + if (OBJ) + { + IReader *O = OBJ->open_chunk(0); + for (int count = 1; O; count++) + { + u32 item_count = O->r_u32(); + if (item_count) + { + shared_str tex_name, sh_name; + O->r_stringZ(sh_name); + O->r_stringZ(tex_name); + wm_slot *slot = AppendSlot(sh_name, tex_name); + if (slot) + { + slot->items.resize(item_count); + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + *w_it = wm_allocate(); + wallmark *W = *w_it; + O->r(&W->flags, sizeof(W->flags)); + O->r(&W->bbox, sizeof(W->bbox)); + O->r(&W->bounds, sizeof(W->bounds)); + W->parent = slot; + W->w = O->r_float(); + W->h = O->r_float(); + W->r = O->r_float(); + W->verts.resize(O->r_u32()); + O->r(&*W->verts.begin(), sizeof(FVF::LIT) * W->verts.size()); + } + } + } + O->close(); + O = OBJ->open_chunk(count); + } + OBJ->close(); + } + } + + // validate wallmarks + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + wm_slot *slot = *slot_it; + + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + wallmark *&W = *w_it; + if (W->verts.size() > MAX_WALLMARK_VERTEX_COUNT) + { + ELog.Msg(mtError, "ERROR: Invalid wallmark (Contain more than %d vertices). Removed.", MAX_WALLMARK_VERTEX_COUNT); + wm_destroy(W); + W = 0; + } + } + + WMVecIt new_end = std::remove_if(slot->items.begin(), slot->items.end(), zero_item_pred()); + slot->items.erase(new_end, slot->items.end()); + } + + return true; +} + +void ESceneWallmarkTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + + F.open_chunk(WM_CHUNK_VERSION); + + if (Core.SocSdk) + F.w_u16(WM_VERSION - 1); + else + F.w_u16(WM_VERSION); + + F.close_chunk(); + + F.open_chunk(WM_CHUNK_FLAGS); + F.w(&m_Flags, sizeof(m_Flags)); + F.close_chunk(); + + F.open_chunk(WM_CHUNK_PARAMS); + F.w_float(m_MarkWidth); + F.w_float(m_MarkHeight); + F.w_float(m_MarkRotate); + F.w_stringZ(m_ShName); + F.w_stringZ(m_TxName); + F.close_chunk(); + + F.open_chunk(WM_CHUNK_ITEMS2); + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + F.open_chunk(slot_it - marks.begin()); + wm_slot *slot = *slot_it; + F.w_u32(slot->items.size()); + if (slot->items.size()) + { + F.w_stringZ(slot->sh_name); + F.w_stringZ(slot->tx_name); + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + wallmark *W = *w_it; + F.w(&W->flags, sizeof(W->flags)); + F.w(&W->bbox, sizeof(W->bbox)); + F.w(&W->bounds, sizeof(W->bounds)); + F.w_float(W->w); + F.w_float(W->h); + F.w_float(W->r); + F.w_u32(W->verts.size()); + F.w(&*W->verts.begin(), sizeof(FVF::LIT) * W->verts.size()); + } + } + F.close_chunk(); + } + F.close_chunk(); +} + +bool ESceneWallmarkTool::LoadSelection(IReader &F) +{ + Clear(); + return LoadStream(F); +} + +void ESceneWallmarkTool::SaveSelection(IWriter &F) +{ + SaveStream(F); +} + +bool ESceneWallmarkTool::Export(LPCSTR path) +{ + RefiningSlots(); + + xr_string fn = xr_string(path) + "level.wallmarks"; + IWriter *F = FS.w_open(fn.c_str()); + R_ASSERT(F); + + F->open_chunk(1); + F->w_u32(marks.size()); + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + wm_slot *slot = *slot_it; + F->w_u32(slot->items.size()); + if (slot->items.size()) + { + F->w_stringZ(slot->sh_name); + F->w_stringZ(slot->tx_name); + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + wallmark *W = *w_it; + F->w(&W->bounds, sizeof(W->bounds)); + F->w_u32(W->verts.size()); + F->w(&*W->verts.begin(), sizeof(FVF::LIT) * W->verts.size()); + } + } + } + F->close_chunk(); + + FS.w_close(F); + + return true; +} + +void ESceneWallmarkTool::OnDeviceCreate() +{ hGeom.create(FVF::F_LIT, RImplementation.Vertex.Buffer(), NULL); } + +void ESceneWallmarkTool::OnDeviceDestroy() +{ + hGeom.destroy(); +} + +void ESceneWallmarkTool::OnSynchronize() +{ +} + +// allocate +ESceneWallmarkTool::wallmark *ESceneWallmarkTool::wm_allocate() +{ + wallmark *W = 0; + if (pool.empty()) + W = xr_new(); + else + { + W = pool.back(); + pool.pop_back(); + } + + W->verts.clear(); + return W; +} +// destroy +void ESceneWallmarkTool::wm_destroy(wallmark *W) +{ + pool.push_back(W); +} + +struct SWMSlotFindPredicate +{ + shared_str sh_name; + shared_str tx_name; + SWMSlotFindPredicate(shared_str sh, shared_str tx) : sh_name(sh), tx_name(tx) {} + bool operator()(const ESceneWallmarkTool::wm_slot *slot) const + { + return (slot->tx_name == tx_name) && (slot->sh_name == sh_name); + } +}; +ESceneWallmarkTool::wm_slot *ESceneWallmarkTool::FindSlot(shared_str sh_name, shared_str tx_name) +{ + WMSVecIt it = std::find_if(marks.begin(), marks.end(), SWMSlotFindPredicate(sh_name, tx_name)); + return (it != marks.end()) ? *it : 0; +} +ESceneWallmarkTool::wm_slot *ESceneWallmarkTool::AppendSlot(shared_str sh_name, shared_str tx_name) +{ + wm_slot *slot = xr_new(sh_name, tx_name); + if (0 == slot->shader) + xr_delete(slot); + else + marks.push_back(slot); + return slot; +} + +void ESceneWallmarkTool::RecurseTri(u32 t, Fmatrix &mView, wallmark &W) +{ + CDB::TRI *T = sml_collector.getT() + t; + if (T->dummy) + return; + T->dummy = 0xffffffff; + + // Some vars + u32 *v_ids = T->verts; + Fvector *v_data = sml_collector.getV(); + sml_poly_src.clear(); + sml_poly_src.push_back(v_data[v_ids[0]]); + sml_poly_src.push_back(v_data[v_ids[1]]); + sml_poly_src.push_back(v_data[v_ids[2]]); + sml_poly_dest.clear(); + + sPoly *P = sml_clipper.ClipPoly(sml_poly_src, sml_poly_dest); + + if (P) + { + // Create vertices and triangulate poly (tri-fan style triangulation) + FVF::LIT V0, V1, V2; + Fvector UV; + + mView.transform_tiny(UV, (*P)[0]); + V0.set((*P)[0], 0, (1 + UV.x) * .5f, (1 - UV.y) * .5f); + mView.transform_tiny(UV, (*P)[1]); + V1.set((*P)[1], 0, (1 + UV.x) * .5f, (1 - UV.y) * .5f); + + for (u32 i = 2; i < P->size(); i++) + { + mView.transform_tiny(UV, (*P)[i]); + V2.set((*P)[i], 0, (1 + UV.x) * .5f, (1 - UV.y) * .5f); + W.verts.push_back(V0); + W.verts.push_back(V1); + W.verts.push_back(V2); + V1 = V2; + } + + // recurse + for (u32 i = 0; i < 3; i++) + { + u32 adj = sml_adjacency[3 * t + i]; + if (0xffffffff == adj) + continue; + CDB::TRI *SML = sml_collector.getT() + adj; + v_ids = SML->verts; + + Fvector test_normal; + test_normal.mknormal(v_data[v_ids[0]], v_data[v_ids[1]], v_data[v_ids[2]]); + float cosa = test_normal.dotproduct(sml_normal); + if (cosa < EPS) + continue; + RecurseTri(adj, mView, W); + } + } +} + +void ESceneWallmarkTool::BuildMatrix(Fmatrix &mView, float inv_w, float inv_h, float angle, const Fvector &from) +{ + // build projection + Fmatrix mScale, mRot; + Fvector at, up, right, y; + at.sub(from, sml_normal); + y.set(EDevice.vCameraTop); + + if (m_Flags.is(flAxisAlign)) + { + y.set(0, 1, 0); + if (_abs(sml_normal.y) > 0.99f) + y.set(1, 0, 0); + } + else + { + y.set(EDevice.vCameraTop); + if (fsimilar(y.dotproduct(sml_normal), 1.f, EPS)) + y.set(EDevice.vCameraRight); + } + right.crossproduct(y, sml_normal); + up.crossproduct(sml_normal, right); + mView.build_camera(from, at, up); + mRot.rotateZ(angle); + mView.mulA_43(mRot); + mScale.scale(inv_w, inv_h, _max(inv_w, inv_h)); + mView.mulA_43(mScale); +} + +int ESceneWallmarkTool::ObjectCount() +{ + int count = 0; + for (WMSVecIt p_it = marks.begin(); p_it != marks.end(); p_it++) + count += (*p_it)->items.size(); + return count; +} + +BOOL ESceneWallmarkTool::AddWallmark_internal(const Fvector &start, const Fvector &dir, shared_str sh, shared_str tx, float width, float height, float rotate) +{ + /* + if (ObjectCount()>=MAX_WALLMARK_COUNT){ + ELog.DlgMsg (mtError,"Maximum wallmark per level is reached [Max: %d].",MAX_WALLMARK_COUNT); + return FALSE; + } + */ + + if (0 == sh.size()) + { + ELog.DlgMsg(mtError, "Select texture before add wallmark."); + return FALSE; + } + if (0 == tx.size()) + { + ELog.DlgMsg(mtError, "Select texture before add wallmark."); + return FALSE; + } + // pick contact poly + Fvector contact_pt; + float dist = UI->ZFar(); + ObjectList *snap_list = Scene->GetSnapList(false); + if (!snap_list) + { + ELog.DlgMsg(mtError, "Fill and activate snap list."); + return FALSE; + } + // pick contact poly + SPickQuery PQ; + sml_collector.clear(); + if (Scene->RayQuery(PQ, start, dir, dist, CDB::OPT_ONLYNEAREST | CDB::OPT_CULL, snap_list)) + { + contact_pt.mad(PQ.m_Start, PQ.m_Direction, PQ.r_begin()->range); + sml_normal.mknormal(PQ.r_begin()->verts[0], PQ.r_begin()->verts[1], PQ.r_begin()->verts[2]); + sml_collector.add_face_packed_D(PQ.r_begin()->verts[0], PQ.r_begin()->verts[1], PQ.r_begin()->verts[2], 0); + } + else + return FALSE; + + // box pick poly + Fbox bbox; + bbox.set(contact_pt, contact_pt); + bbox.grow(_max(height, width) * 2); + SPickQuery BQ; + if (Scene->BoxQuery(BQ, bbox, CDB::OPT_FULL_TEST, snap_list)) + { + for (u32 k = 0; k < (u32)BQ.r_count(); k++) + { + SPickQuery::SResult *R = BQ.r_begin() + k; + Fvector test_normal; + test_normal.mknormal(R->verts[0], R->verts[1], R->verts[2]); + float cosa = test_normal.dotproduct(sml_normal); + if (cosa < 0.1) + continue; + sml_collector.add_face_packed_D(R->verts[0], R->verts[1], R->verts[2], 0); + } + } + + // remove duplicate poly + sml_collector.remove_duplicate_T(); + // calculate adjacency + sml_collector.calc_adjacency(sml_adjacency); + + // build 3D ortho-frustum + Fmatrix mView; + BuildMatrix(mView, 2 / width, 2 / height, rotate, contact_pt); // width/2 height/2 (BuildMatrix need radius) + sml_clipper.CreateFromMatrix(mView, FRUSTUM_P_LRTB); + + // create wallmark + wallmark *W = wm_allocate(); + W->w = width; + W->h = height; + W->r = rotate; + + RecurseTri(0, mView, *W); + + // calc sphere + if ((W->verts.size() < 3) || (W->verts.size() > MAX_WALLMARK_VERTEX_COUNT)) + { + ELog.DlgMsg(mtError, "Invalid wallmark vertex count. [Min: %d. Max: %d].", 3, MAX_WALLMARK_VERTEX_COUNT); + wm_destroy(W); + return FALSE; + } + else + { + W->bbox.invalidate(); + FVF::LIT *I = &*W->verts.begin(); + FVF::LIT *E = &*W->verts.end(); + for (; I != E; I++) + W->bbox.modify(I->p); + W->bbox.getsphere(W->bounds.P, W->bounds.R); + W->flags.assign(wallmark::flSelected); + W->bbox.grow(EPS_L); + } + + // search if similar wallmark exists + wm_slot *slot = FindSlot(sh, tx); + if (slot) + { + W->parent = slot; + WMVecIt it = slot->items.begin(); + WMVecIt end = slot->items.end(); + for (; it != end; it++) + { + wallmark *wm = *it; + if (wm->bounds.P.similar(W->bounds.P, 0.02f)) + { // replace + wm_destroy(wm); + *it = W; + return TRUE; + } + } + } + else + { + slot = AppendSlot(sh, tx); + W->parent = slot; + } + + // no similar - register _new_ + if (slot) + slot->items.push_back(W); + return TRUE; +} + +BOOL ESceneWallmarkTool::AddWallmark(const Fvector &start, const Fvector &dir) +{ + return AddWallmark_internal(start, dir, m_ShName, m_TxName, m_MarkWidth, m_MarkHeight, m_MarkRotate); +} + +BOOL ESceneWallmarkTool::MoveSelectedWallmarkTo(const Fvector &start, const Fvector &dir) +{ + if (!m_Flags.is(flDrawWallmark)) + return 0; + wallmark *wm = 0; + for (WMSVecIt p_it = marks.begin(); p_it != marks.end(); p_it++) + { + for (WMVecIt m_it = (*p_it)->items.begin(); m_it != (*p_it)->items.end(); m_it++) + { + if ((*m_it)->flags.is(wallmark::flSelected)) + { + if (wm) + return FALSE; + wm = *m_it; + } + } + } + if ((0 != wm) && AddWallmark_internal(start, dir, wm->parent->sh_name, wm->parent->tx_name, wm->w, wm->h, wm->r)) + { + // remove wm + for (WMSVecIt p_it = marks.begin(); p_it != marks.end(); p_it++) + { + for (WMVecIt m_it = (*p_it)->items.begin(); m_it != (*p_it)->items.end();) + { + if (*m_it == wm) + { + wm_destroy(wm); + *m_it = (*p_it)->items.back(); + (*p_it)->items.pop_back(); + return TRUE; + } + } + } + } + return FALSE; +} + +void ESceneWallmarkTool::FillProp(LPCSTR pref, PropItemVec &items) +{ + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Draw Wallmarks"), &m_Flags, flDrawWallmark); + PHelper().CreateFlag32(items, PrepareKey(pref, "Common\\Alignment"), &m_Flags, flAxisAlign, "By Camera", "By World Axis"); + PHelper().CreateFloat(items, PrepareKey(pref, "Common\\Width"), &m_MarkWidth, 0.01f, 10.f); + PHelper().CreateFloat(items, PrepareKey(pref, "Common\\Height"), &m_MarkHeight, 0.01f, 10.f); + PHelper().CreateAngle(items, PrepareKey(pref, "Common\\Rotate"), &m_MarkRotate); + PHelper().CreateChoose(items, PrepareKey(pref, "Common\\Shader"), &m_ShName, smEShader); + PHelper().CreateChoose(items, PrepareKey(pref, "Common\\Texture"), &m_TxName, smTexture); +} +//---------------------------------------------------- + +bool ESceneWallmarkTool::Validate(bool) +{ + bool bRes = true; + + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + wm_slot *slot = *slot_it; + if (slot->items.size()) + { + IBlender *B = EDevice.Resources->_FindBlender(*slot->sh_name); + if (!B || B->canBeLMAPped()) + { + ELog.Msg(mtError, "Wallmarks: Invalid or missing shader '%s'.", *slot->sh_name); + bRes = false; + } + } + } + + return bRes; +} +//---------------------------------------------------- + +void ESceneWallmarkTool::GetStaticDesc(int &v_cnt, int &f_cnt, bool b_selected_only, bool b_cform) +{ + if (b_cform) + return; + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + wm_slot *slot = *slot_it; + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + wallmark *W = *w_it; + + if (b_selected_only && !W->flags.test(wallmark::flSelected)) + continue; + + v_cnt += W->verts.size(); + f_cnt += W->verts.size() / 3; + } + } +} +//---------------------------------------------------- + +bool ESceneWallmarkTool::ExportStatic(SceneBuilder *B, bool b_selected_only) +{ + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + wm_slot *slot = *slot_it; + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + wallmark *W = *w_it; + int sect_num = B->CalculateSector(W->bounds.P, W->bounds.R); + int m_id = B->BuildMaterial(*slot->sh_name, COMPILER_SHADER, *slot->tx_name, 1, sect_num, false); + u32 f_cnt = W->verts.size() / 3; + for (u32 f_it = 0; f_it < f_cnt; f_it++, B->l_face_it++) + { + R_ASSERT(B->l_face_it < B->l_face_cnt); + b_face &dst_f = B->l_faces[B->l_face_it]; + for (u32 k = 0; k < 3; k++, B->l_vert_it++) + { + R_ASSERT(B->l_vert_it < B->l_vert_cnt); + FVF::LIT &src = W->verts[f_it * 3 + k]; + Fvector &dst_v = B->l_verts[B->l_vert_it]; + dst_v.set(src.p); + dst_f.v[k] = B->l_vert_it; + dst_f.t[k].set(src.t); + dst_f.dwMaterial = (u16)m_id; + } + } + } + } + return true; +} +//---------------------------------------------------- + +void ESceneWallmarkTool::CreateControls() +{ + inherited::CreateDefaultControls(estDefault); + // node tools + AddControl(xr_new(0, etaAdd, this)); + AddControl(xr_new(0, etaMove, this)); +} +//---------------------------------------------------- + +void ESceneWallmarkTool::RemoveControls() +{ + inherited::RemoveControls(); +} +//---------------------------------------------------- + +void ESceneWallmarkTool::GetBBox(Fbox &bb, bool bSelOnly) +{ + if (bSelOnly) + { + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + wm_slot *slot = *slot_it; + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + { + wallmark *W = *w_it; + if (W->flags.is(wallmark::flSelected)) + bb.merge(W->bbox); + } + } + } + else + { + for (WMSVecIt slot_it = marks.begin(); slot_it != marks.end(); slot_it++) + { + wm_slot *slot = *slot_it; + for (WMVecIt w_it = slot->items.begin(); w_it != slot->items.end(); w_it++) + bb.merge((*w_it)->bbox); + } + } +} diff --git a/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkTools.h b/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkTools.h new file mode 100644 index 00000000000..ef44f95cf98 --- /dev/null +++ b/src/editors/LevelEditor/Tools/Wallmark/ESceneWallmarkTools.h @@ -0,0 +1,158 @@ +#pragma once + +class ESceneWallmarkTool : public ESceneToolBase +{ + typedef ESceneToolBase inherited; + +public: + DEFINE_VECTOR(FVF::LIT, LITVertVec, LITVertVecIt); + struct wm_slot; + struct wallmark + { + enum + { + flSelected = (1 << 0) + }; + wm_slot *parent; + float w, h, r; + Flags8 flags; + Fbox bbox; + Fsphere bounds; + LITVertVec verts; + wallmark() + { + flags.zero(); + parent = 0; + w = 0; + h = 0; + r = 0; + } + }; + DEFINE_VECTOR(wallmark *, WMVec, WMVecIt); + struct wm_slot + { + shared_str sh_name; + shared_str tx_name; + ref_shader shader; + WMVec items; + wm_slot(shared_str sh, shared_str tx) + { + sh_name = sh; + tx_name = tx; + shader.create(*sh_name, *tx_name); + items.reserve(256); + } + }; + DEFINE_VECTOR(wm_slot *, WMSVec, WMSVecIt); + WMSVec marks; + WMVec pool; + +private: + ref_geom hGeom; + + Fvector sml_normal; + CFrustum sml_clipper; + sPoly sml_poly_dest; + sPoly sml_poly_src; + + CDB::Collector sml_collector; + xr_vector sml_adjacency; + + wm_slot *FindSlot(shared_str sh_name, shared_str tx_name); + wm_slot *AppendSlot(shared_str sh_name, shared_str tx_name); + + void RecurseTri(u32 t, Fmatrix &mView, wallmark &W); + void BuildMatrix(Fmatrix &mView, float inv_w, float inv_h, float angle, const Fvector &from); + BOOL AddWallmark_internal(const Fvector &S, const Fvector &D, shared_str s, shared_str t, float w, float h, float r); + + void RefiningSlots(); + +private: + wallmark *wm_allocate(); + void wm_destroy(wallmark *W); + +private: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + enum + { + flDrawWallmark = (1 << 0), + flAxisAlign = (1 << 1) + }; + Flags32 m_Flags; + + float m_MarkWidth; + float m_MarkHeight; + float m_MarkRotate; + shared_str m_ShName; + shared_str m_TxName; + + int ObjectCount(); + +public: + ESceneWallmarkTool(); + virtual ~ESceneWallmarkTool(); + + virtual bool AllowEnabling() { return true; } + virtual BOOL AllowMouseStart() { return true; } + + virtual void OnObjectRemove(CCustomObject *O, bool bDeleting) {} + virtual void UpdateSnapList() {} + virtual ObjectList *GetSnapList() { return 0; } + + // selection manipulate + virtual int RaySelect(int flag, float &distance, const Fvector &start, const Fvector &direction, BOOL bDistanceOnly); + virtual int FrustumSelect(int flag, const CFrustum &frustum); + virtual void SelectObjects(bool flag); + virtual void InvertSelection(); + virtual void RemoveSelection(); + virtual int SelectionCount(bool testflag); + virtual void ShowObjects(bool flag, bool bAllowSelectionFlag = false, bool bSelFlag = true) {} + + virtual void Clear(bool bOnlyNodes = false); + + // definition + IC LPCSTR ClassName() { return "wallmark"; } + IC LPCSTR ClassDesc() { return "Wallmark"; } + IC int RenderPriority() { return 10; } + + // validation + virtual bool Valid(); + virtual bool Validate(bool full_test); + virtual bool IsNeedSave(); + + // events + virtual void OnFrame(); + virtual void OnRender(int priority, bool strictB2F); + + // IO + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool can_use_inifile() { return false; } + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + virtual bool Export(LPCSTR fn); + virtual bool ExportStatic(SceneBuilder *B, bool b_selected_only); + virtual void GetStaticDesc(int &v_cnt, int &f_cnt, bool b_selected_only, bool b_cform); + + // device dependent funcs + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + + virtual void OnSynchronize(); + + virtual bool GetSummaryInfo(SSceneSummary *inf) { return false; } + + // properties + virtual void FillProp(LPCSTR pref, PropItemVec &items); + + // utils + virtual void GetBBox(Fbox &bb, bool bSelOnly); + BOOL AddWallmark(const Fvector &start, const Fvector &dir); + BOOL MoveSelectedWallmarkTo(const Fvector &start, const Fvector &dir); +}; diff --git a/src/editors/LevelEditor/Tools/WayPoint/ESceneWayControls.cpp b/src/editors/LevelEditor/Tools/WayPoint/ESceneWayControls.cpp new file mode 100644 index 00000000000..369e5b81bed --- /dev/null +++ b/src/editors/LevelEditor/Tools/WayPoint/ESceneWayControls.cpp @@ -0,0 +1,65 @@ +#include "stdafx.h" + +void ESceneWayTool::OnActivate() +{ + inherited::OnActivate(); + UIWayTool *frame = (UIWayTool *)pForm; + if (sub_target == estWayModePoint) + frame->SetWayMode(false); + else + frame->SetWayMode(true); +} + +void ESceneWayTool::CreateControls() +{ + inherited::CreateDefaultControls(estWayModeWay); + inherited::CreateDefaultControls(estWayModePoint); + AddControl(xr_new(estWayModePoint, etaAdd, this)); + // frame + pForm = xr_new(); +} + +void ESceneWayTool::RemoveControls() +{ + inherited::RemoveControls(); +} +//---------------------------------------------------- + +//--------------------------------------------------------------------------- +TUI_ControlWayPointAdd::TUI_ControlWayPointAdd(int st, int act, ESceneToolBase *parent) : TUI_CustomControl(st, act, parent) +{ +} + +bool TUI_ControlWayPointAdd::Start(TShiftState Shift) +{ + ObjectList lst; + Scene->GetQueryObjects(lst, OBJCLASS_WAY, 1, 1, -1); + UIWayTool *frame = (UIWayTool *)parent_tool->pForm; + if (1 != lst.size()) + { + ELog.DlgMsg(mtInformation, "Select one WayObject."); + return false; + } + Fvector p; + if (LUI->PickGround(p, UI->m_CurrentRStart, UI->m_CurrentRDir, 1)) + { + CWayObject *obj = (CWayObject *)lst.front(); + R_ASSERT(obj); + CWayPoint *last_wp = obj->GetFirstSelected(); + CWayPoint *wp = obj->AppendWayPoint(); + wp->MoveTo(p); + if (frame->IsAutoLink()) + { + if (last_wp) + last_wp->AddSingleLink(wp); + } + Scene->UndoSave(); + } + if (!(Shift & ssAlt)) + ResetActionToSelect(); + return false; +} + +void TUI_ControlWayPointAdd::OnEnter() +{ +} diff --git a/src/editors/LevelEditor/Tools/WayPoint/ESceneWayControls.h b/src/editors/LevelEditor/Tools/WayPoint/ESceneWayControls.h new file mode 100644 index 00000000000..4cee01506ff --- /dev/null +++ b/src/editors/LevelEditor/Tools/WayPoint/ESceneWayControls.h @@ -0,0 +1,19 @@ +#pragma once + +// refs +class CWayPoint; + +enum +{ + estWayModeWay, + estWayModePoint +}; + +class TUI_ControlWayPointAdd : public TUI_CustomControl +{ +public: + TUI_ControlWayPointAdd(int st, int act, ESceneToolBase *parent); + virtual ~TUI_ControlWayPointAdd() { ; } + virtual bool Start(TShiftState _Shift); + virtual void OnEnter(); +}; diff --git a/src/editors/LevelEditor/Tools/WayPoint/ESceneWayTools.cpp b/src/editors/LevelEditor/Tools/WayPoint/ESceneWayTools.cpp new file mode 100644 index 00000000000..2592d9aeb2e --- /dev/null +++ b/src/editors/LevelEditor/Tools/WayPoint/ESceneWayTools.cpp @@ -0,0 +1,8 @@ +#include "stdafx.h" + +CCustomObject *ESceneWayTool::CreateObject(LPVOID data, LPCSTR name) +{ + CCustomObject *O = xr_new(data, name); + O->FParentTools = this; + return O; +} diff --git a/src/editors/LevelEditor/Tools/WayPoint/ESceneWayTools.h b/src/editors/LevelEditor/Tools/WayPoint/ESceneWayTools.h new file mode 100644 index 00000000000..946a532e4a2 --- /dev/null +++ b/src/editors/LevelEditor/Tools/WayPoint/ESceneWayTools.h @@ -0,0 +1,32 @@ +#pragma once + +class ESceneWayTool : public ESceneCustomOTool +{ + typedef ESceneCustomOTool inherited; + +protected: + // controls + virtual void CreateControls(); + virtual void RemoveControls(); + +public: + ESceneWayTool() : ESceneCustomOTool(OBJCLASS_WAY) { ; } + // definition + IC LPCSTR ClassName() { return "way"; } + IC LPCSTR ClassDesc() { return "Way"; } + IC int RenderPriority() { return 1; } + + virtual void Clear(bool bSpecific = false) { inherited::Clear(bSpecific); } + // IO + virtual bool IsNeedSave() { return inherited::IsNeedSave(); } + virtual bool LoadStream(IReader &); + virtual bool LoadLTX(CInifile &); + virtual void SaveStream(IWriter &); + virtual void SaveLTX(CInifile &, int id); + virtual bool LoadSelection(IReader &); + virtual void SaveSelection(IWriter &); + + virtual void OnActivate(); + + virtual CCustomObject *CreateObject(LPVOID data, LPCSTR name); +}; diff --git a/src/editors/LevelEditor/Tools/WayPoint/ESceneWayToolsIO.cpp b/src/editors/LevelEditor/Tools/WayPoint/ESceneWayToolsIO.cpp new file mode 100644 index 00000000000..0c94fff2e46 --- /dev/null +++ b/src/editors/LevelEditor/Tools/WayPoint/ESceneWayToolsIO.cpp @@ -0,0 +1,75 @@ +#include "stdafx.h" + +// chunks +static const u16 WAY_TOOLS_VERSION = 0x0000; + +enum +{ + CHUNK_VERSION = 0x1001ul, +}; + +bool ESceneWayTool::LoadLTX(CInifile &ini) +{ + u32 version = ini.r_u32("main", "version"); + + if (version != WAY_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + inherited::LoadLTX(ini); + return true; +} + +void ESceneWayTool::SaveLTX(CInifile &ini, int id) +{ + inherited::SaveLTX(ini, id); + + ini.w_u32("main", "version", WAY_TOOLS_VERSION); +} + +bool ESceneWayTool::LoadStream(IReader &F) +{ + u16 version = 0; + + if (F.r_chunk(CHUNK_VERSION, &version)) + { + if (version != WAY_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + } + + if (!inherited::LoadStream(F)) + return false; + + return true; +} + +void ESceneWayTool::SaveStream(IWriter &F) +{ + inherited::SaveStream(F); + F.w_chunk(CHUNK_VERSION, (u16 *)&WAY_TOOLS_VERSION, sizeof(WAY_TOOLS_VERSION)); +} + +bool ESceneWayTool::LoadSelection(IReader &F) +{ + u16 version = 0; + R_ASSERT(F.r_chunk(CHUNK_VERSION, &version)); + + if (version != WAY_TOOLS_VERSION) + { + ELog.DlgMsg(mtError, "%s tools: Unsupported version.", ClassDesc()); + return false; + } + + return inherited::LoadSelection(F); +} + +void ESceneWayTool::SaveSelection(IWriter &F) +{ + F.w_chunk(CHUNK_VERSION, (u16 *)&WAY_TOOLS_VERSION, sizeof(WAY_TOOLS_VERSION)); + inherited::SaveSelection(F); +} diff --git a/src/editors/LevelEditor/UI/Tools/UIAIMapTool.cpp b/src/editors/LevelEditor/UI/Tools/UIAIMapTool.cpp new file mode 100644 index 00000000000..272d678323d --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIAIMapTool.cpp @@ -0,0 +1,257 @@ +#include "stdafx.h" + +UIAIMapTool::UIAIMapTool() +{ + m_Mode = mdAppend; + m_AutoLink = true; + m_IgnoreConstraints = false; + m_IgnoreMaterialsListSelected = 0; + m_ChooseIgnoreMaterials = false; +} + +UIAIMapTool::~UIAIMapTool() +{ +} + +void UIAIMapTool::Draw() +{ + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Commands")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Button("Generate Full", ImVec2(-1, 0))) + { + tool->GenerateMap(false); + } + if (ImGui::Button("Generate Selected", ImVec2(-1, 0))) + { + tool->GenerateMap(true); + } + if (ImGui::Button("Clear AI Map", ImVec2(-1, 0))) + { + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to clear AI Map?") == mrYes) + { + tool->Clear(); + Scene->UndoSave(); + } + } + } + ImGui::Separator(); + { + if (ImGui::Button("Smooth Selected", ImVec2(-1, 0))) + tool->SmoothNodes(); + if (ImGui::Button("Reset Selected", ImVec2(-1, 0))) + tool->ResetNodes(); + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("AI Map Nodes")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + ImGui::Checkbox("Ignore Constraints", &m_IgnoreConstraints); + ImGui::Checkbox("Auto Link", &m_AutoLink); + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Ignore materials")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Button("Add")) + { + UIChooseForm::SelectItem(smGameMaterial, 1, 0, 0, 0, 0, 0, 0); + m_ChooseIgnoreMaterials = true; + } + ImGui::SameLine(0, -1); + if (ImGui::Button("X")) + { + m_IgnoreMaterialsListSelected = 0; + m_IgnoreMaterialsList.clear(); + tool->m_ignored_materials.clear(); + } + ImGui::SetNextItemWidth(-1); + ImGui::ListBox( + "##mat_list_box", &m_IgnoreMaterialsListSelected, [](void *data, int ind, const char **out) -> bool + {*out = reinterpret_cast*>(data)->at(ind).c_str(); return true; }, + reinterpret_cast(&this->m_IgnoreMaterialsList), m_IgnoreMaterialsList.size(), 7); + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Link Commands")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::PushItemWidth(-1); + float size = float(ImGui::CalcItemWidth()); + { + float my_tex_w = (float)ImGui::GetIO().Fonts->TexWidth; + float my_tex_h = (float)ImGui::GetIO().Fonts->TexHeight; + + { + if (ImGui::RadioButton("Add ", m_Mode == mdAppend)) + { + m_Mode = mdAppend; + } + ImGui::SameLine(0, -1); + ImGui::InvisibleButton("none1", ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight())); + ImGui::SameLine(0, -1); + if (ImGui::ArrowButton("Up", ImGuiDir_Up)) + { + SideClick(1); + } + ImGui::SameLine(0, -1); + ImGui::InvisibleButton("none2", ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight())); + ImGui::SameLine(0, -1); + ImGui::InvisibleButton("none3", ImVec2(ImGui::GetFrameHeight() * 2, ImGui::GetFrameHeight())); + ImGui::SameLine(0, -1); + if (ImGui::Button("Select 0-Link", ImVec2(-1, 0))) + { + tool->SelectNodesByLink(0); + Scene->UndoSave(); + } + } + { + if (ImGui::RadioButton("Delete ", m_Mode == mdRemove)) + { + m_Mode = mdRemove; + } + ImGui::SameLine(0, -1); + if (ImGui::ArrowButton("Left", ImGuiDir_Left)) + { + SideClick(0); + } + ImGui::SameLine(0, -1); + if (ImGui::Button("X", ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight()))) + { + SideClick(4); + } + ImGui::SameLine(0, -1); + if (ImGui::ArrowButton("Right", ImGuiDir_Right)) + { + SideClick(2); + } + ImGui::SameLine(0, -1); + ImGui::InvisibleButton("none4", ImVec2(ImGui::GetFrameHeight() * 2, ImGui::GetFrameHeight())); + ImGui::SameLine(0, -1); + if (ImGui::Button("Select 1-Link", ImVec2(-1, 0))) + { + tool->SelectNodesByLink(1); + Scene->UndoSave(); + } + } + { + if (ImGui::RadioButton("Invert ", m_Mode == mdInvert)) + { + m_Mode = mdInvert; + } + ImGui::SameLine(0, -1); + ImGui::InvisibleButton("none5", ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight())); + ImGui::SameLine(0, -1); + if (ImGui::ArrowButton("Down", ImGuiDir_Down)) + { + SideClick(3); + } + ImGui::SameLine(0, -1); + ImGui::InvisibleButton("none6", ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight())); + ImGui::SameLine(0, -1); + ImGui::InvisibleButton("none7", ImVec2(ImGui::GetFrameHeight() * 2, ImGui::GetFrameHeight())); + ImGui::SameLine(0, -1); + if (ImGui::Button("Select 2-Link", ImVec2(-1, 0))) + { + tool->SelectNodesByLink(2); + Scene->UndoSave(); + } + } + } + + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} + +//--------------------------------------------------------------------------- + +static const int idx[5][4] = { + {0, 1, 2, 3}, + {1, 2, 3, 0}, + {2, 3, 0, 1}, + {3, 0, 1, 2}, + {4, 4, 4, 4}, +}; + +int ConvertV2L(int side) +{ + if (side < 4) + { + const Fvector &HPB = EDevice.m_Camera.GetHPB(); + float h = angle_normalize(HPB.x) / PI; + R_ASSERT((h >= 0.f) && (h <= 2.f)); + if (h > 0.25f && h <= 0.75f) + return idx[3][side]; + else if (h > 0.75f && h <= 1.25f) + return idx[2][side]; + else if (h > 1.25f && h <= 1.75f) + return idx[1][side]; + else + return idx[0][side]; + } + else + return side; +} + +static const u8 fl[5] = { + SAINode::flN1, SAINode::flN2, SAINode::flN3, SAINode::flN4, + SAINode::flN1 | SAINode::flN2 | SAINode::flN3 | SAINode::flN4, + // SAINode::flN1|SAINode::flN2,SAINode::flN2|SAINode::flN3, + // SAINode::flN3|SAINode::flN4,SAINode::flN4|SAINode::flN1 +}; +void UIAIMapTool::SideClick(int tag) +{ + ESceneAIMapTool::EMode mode; + switch (m_Mode) + { + case UIAIMapTool::mdAppend: + mode = ESceneAIMapTool::mdAppend; + break; + case UIAIMapTool::mdRemove: + mode = ESceneAIMapTool::mdRemove; + break; + case UIAIMapTool::mdInvert: + mode = ESceneAIMapTool::mdInvert; + break; + } + + tool->MakeLinks(fl[ConvertV2L(tag)], mode, m_IgnoreConstraints); + Scene->UndoSave(); + UI->RedrawScene(); +} +//--------------------------------------------------------------------------- +void UIAIMapTool::OnDrawUI() +{ + if (m_ChooseIgnoreMaterials) + { + bool result = false; + xr_string name; + if (UIChooseForm::GetResult(result, name)) + { + if (result) + { + m_IgnoreMaterialsList.push_back(name); + SGameMtl *mtl = GMLib.GetMaterial(name.c_str()); + tool->m_ignored_materials.push_back(mtl->GetID()); + } + m_ChooseIgnoreMaterials = false; + } + UIChooseForm::Update(); + } +} \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UIAIMapTool.h b/src/editors/LevelEditor/UI/Tools/UIAIMapTool.h new file mode 100644 index 00000000000..b100645e301 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIAIMapTool.h @@ -0,0 +1,30 @@ +#pragma once +class ESceneAIMapTool; +class UIAIMapTool : public UIToolCustom +{ +public: + UIAIMapTool(); + virtual ~UIAIMapTool(); + virtual void Draw(); + virtual void OnDrawUI(); + ESceneAIMapTool *tool; + IC bool IsIgnoreConstraints() const { return m_IgnoreConstraints; } + IC bool IsAutoLink() const { return m_AutoLink; } + +private: + enum EMode + { + mdAppend, + mdRemove, + mdInvert, + }; + EMode m_Mode; + bool m_IgnoreConstraints; + bool m_AutoLink; + xr_vector m_IgnoreMaterialsList; + int m_IgnoreMaterialsListSelected; + bool m_ChooseIgnoreMaterials; + +private: + void SideClick(int tag); +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UIDOTool.cpp b/src/editors/LevelEditor/UI/Tools/UIDOTool.cpp new file mode 100644 index 00000000000..10e603abd54 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIDOTool.cpp @@ -0,0 +1,86 @@ +#include "stdafx.h" + +UIDOTool::UIDOTool() +{ + m_DOShuffle = false; +} + +UIDOTool::~UIDOTool() +{ +} + +void UIDOTool::Draw() +{ + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Commands")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Button("First Initialize", ImVec2(-1, 0))) + { + if (DM->Initialize()) + Scene->UndoSave(); + } + if (ImGui::Button("Reinitialize All", ImVec2(-1, 0))) + { + if (DM->Reinitialize()) + Scene->UndoSave(); + } + if (ImGui::Button("Reinitialize Objects Only", ImVec2(-1, 0))) + { + if (DM->UpdateObjects(true, false)) + Scene->UndoSave(); + } + if (ImGui::Button("Reinitialize Selected Slot Objects", ImVec2(-1, 0))) + { + if (DM->UpdateObjects(false, true)) + Scene->UndoSave(); + } + ImGui::Separator(); + if (ImGui::Button("Update Renderer", ImVec2(-1, 0))) + { + DM->InvalidateCache(); + Scene->UndoSave(); + } + ImGui::Separator(); + if (ImGui::Button("Clear Slots", ImVec2(-1, 0))) + { + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to reset slots?") == mrYes) + { + DM->ClearSlots(); + Scene->UndoSave(); + } + } + if (ImGui::Button("Clear Details", ImVec2(-1, 0))) + { + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to clear details?") == mrYes) + { + ExecCommand(COMMAND_UPDATE_PROPERTIES); + DM->Clear(); + Scene->UndoSave(); + } + } + ImGui::Separator(); + if (ImGui::Button("Object List", ImVec2(-1, 0))) + { + m_DOShuffle = true; + UIDOShuffle::Show(DM); + } + } + + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} + +void UIDOTool::OnDrawUI() +{ + if (m_DOShuffle) + { + if (UIDOShuffle::GetResult()) + { + m_DOShuffle = false; + } + UIDOShuffle::Update(); + } +} diff --git a/src/editors/LevelEditor/UI/Tools/UIDOTool.h b/src/editors/LevelEditor/UI/Tools/UIDOTool.h new file mode 100644 index 00000000000..1a9809c3383 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIDOTool.h @@ -0,0 +1,14 @@ +#pragma once +class EDetailManager; +class UIDOTool : public UIToolCustom +{ +public: + UIDOTool(); + virtual ~UIDOTool(); + virtual void Draw(); + virtual void OnDrawUI(); + EDetailManager *DM; + +private: + bool m_DOShuffle; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UIFogVolTool.cpp b/src/editors/LevelEditor/UI/Tools/UIFogVolTool.cpp new file mode 100644 index 00000000000..50661472115 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIFogVolTool.cpp @@ -0,0 +1,29 @@ +#include "stdafx.h" + +UIFogVolTool::UIFogVolTool() {} +UIFogVolTool::~UIFogVolTool() {} + +void UIFogVolTool::Draw() +{ + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + + if (ImGui::TreeNode("Commands")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::PushItemWidth(-1); + float size = float(ImGui::CalcItemWidth()); + + { + if (ImGui::Button("Group Selected", ImVec2(size / 2, 0))) + ParentTools->GroupSelected(); + + ImGui::SameLine(0, 2); + + if (ImGui::Button("UnGroup Selected", ImVec2(size / 2, 0))) + ParentTools->UnGroupCurrent(); + } + + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} diff --git a/src/editors/LevelEditor/UI/Tools/UIFogVolTool.h b/src/editors/LevelEditor/UI/Tools/UIFogVolTool.h new file mode 100644 index 00000000000..8f4430ffc0d --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIFogVolTool.h @@ -0,0 +1,10 @@ +#pragma once +class ESceneFogVolumeTool; +class UIFogVolTool : public UIToolCustom +{ +public: + UIFogVolTool(); + virtual ~UIFogVolTool(); + virtual void Draw(); + ESceneFogVolumeTool *ParentTools; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UIGroupTool.cpp b/src/editors/LevelEditor/UI/Tools/UIGroupTool.cpp new file mode 100644 index 00000000000..3d1b9a835f0 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIGroupTool.cpp @@ -0,0 +1,211 @@ +#include "stdafx.h" +#include + +UIGroupTool::UIGroupTool() +{ + m_ChooseGroup = false; + m_selPercent = true; +} + +UIGroupTool::~UIGroupTool() +{ +} + +void UIGroupTool::Draw() +{ + ImGui::Separator(); + { + ImGui::BulletText("Commands", ImGuiDir_Left); + if (ImGui::BeginPopupContextItem("Commands", 1)) + { + if (ImGui::MenuItem("Group")) + { + ParentTools->GroupObjects(); + } + if (ImGui::MenuItem("Ungroup")) + { + ParentTools->UngroupObjects(); + } + ImGui::Separator(); + if (ImGui::MenuItem("Make Thumbnail")) + { + ParentTools->MakeThumbnail(); + } + ImGui::Separator(); + if (ImGui::MenuItem("Save As ...")) + { + ParentTools->SaveSelectedObject(); + } + ImGui::EndPopup(); + } + ImGui::OpenPopupOnItemClick("Commands", 0); + } + ImGui::Separator(); + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Current Object")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + ImGui::SetNextItemWidth(-1); + float size = float(ImGui::CalcItemWidth()); + { + if (ImGui::Button("Select ...", ImVec2(size / 2, 0))) + { + UIChooseForm::SelectItem(smGroup, 1, m_Current.c_str()); + m_ChooseGroup = true; + } + ImGui::SameLine(0, 2); + if (ImGui::Button("Reload Refs", ImVec2(size / 2, 0))) + { + ParentTools->ReloadRefsSelectedObject(); + // bForceInitListBox = TRUE; + Tools->UpdateProperties(TRUE); + } + } + ImGui::Text("Current:%s", m_Current.c_str() ? m_Current.c_str() : ""); + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Reference Select")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + ImGui::Text("Select by Current: "); + ImGui::SameLine(); + if (ImGui::Button(" +")) + { + SelByRefObject(true); + } + ImGui::SameLine(); + if (ImGui::Button(" -")) + { + SelByRefObject(false); + } + ImGui::Text("Select by Selected:"); + ImGui::SameLine(); + if (ImGui::Button("=%")) + { + MultiSelByRefObject(true); + } + ImGui::SameLine(); + if (ImGui::Button("+%")) + { + MultiSelByRefObject(false); + } + ImGui::SameLine(); + ImGui::SetNextItemWidth(-ImGui::GetTextLineHeight() - 8); + ImGui::DragFloat("%", &m_selPercent, 1, 0, 100, "%.1f"); + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Pivot Alignment")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Button("Center To Group", ImVec2(-1, 0))) + { + ParentTools->CenterToGroup(); + } + if (ImGui::Button("Align To Object...", ImVec2(-1, 0))) + { + ParentTools->AlignToObject(); + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} + +void UIGroupTool::OnDrawUI() +{ + if (m_ChooseGroup) + { + xr_string in; + bool resutl; + if (UIChooseForm::GetResult(resutl, in)) + { + if (resutl) + { + m_Current = in; + ParentTools->SetCurrentObject(m_Current.c_str()); + } + m_ChooseGroup = false; + } + UIChooseForm::Update(); + } +} + +void UIGroupTool::MultiSelByRefObject(bool clear_prev) +{ + ObjectList objlist; + LPU32Vec sellist; + if (Scene->GetQueryObjects(objlist, OBJCLASS_GROUP, 1, 1, -1)) + { + for (ObjectIt it = objlist.begin(); it != objlist.end(); it++) + { + LPCSTR N = ((CGroupObject *)*it)->RefName(); + ObjectIt _F = Scene->FirstObj(OBJCLASS_GROUP); + ObjectIt _E = Scene->LastObj(OBJCLASS_GROUP); + for (; _F != _E; _F++) + { + CGroupObject *_O = (CGroupObject *)(*_F); + if ((*_F)->Visible() && _O->RefCompare(N)) + { + if (clear_prev) + { + _O->Select(false); + sellist.push_back((u32 *)_O); + } + else + { + if (!_O->Selected()) + sellist.push_back((u32 *)_O); + } + } + } + } + + std::sort(sellist.begin(), sellist.end()); + sellist.erase(std::unique(sellist.begin(), sellist.end()), sellist.end()); + + std::random_device rd; + std::mt19937 g(rd()); + std::shuffle(sellist.begin(), sellist.end(), g); + + int max_k = iFloor(float(sellist.size()) / 100.f * float(m_selPercent) + 0.5f); + int k = 0; + for (LPU32It o_it = sellist.begin(); k < max_k; o_it++, k++) + { + CGroupObject *_O = (CGroupObject *)(*o_it); + _O->Select(true); + } + } +} + +void UIGroupTool::SelByRefObject(bool flag) +{ + ObjectList objlist; + + if (m_Current.empty()) + { + LPCSTR N = m_Current.c_str(); + ObjectIt _F = Scene->FirstObj(OBJCLASS_GROUP); + ObjectIt _E = Scene->LastObj(OBJCLASS_GROUP); + for (; _F != _E; _F++) + { + if ((*_F)->Visible()) + { + CGroupObject *_O = (CGroupObject *)(*_F); + if (_O->RefCompare(N)) + _O->Select(flag); + } + } + } +} diff --git a/src/editors/LevelEditor/UI/Tools/UIGroupTool.h b/src/editors/LevelEditor/UI/Tools/UIGroupTool.h new file mode 100644 index 00000000000..6e5acc09c3c --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIGroupTool.h @@ -0,0 +1,18 @@ +#pragma once +class ESceneGroupTool; +class UIGroupTool : public UIToolCustom +{ +public: + UIGroupTool(); + virtual ~UIGroupTool(); + virtual void Draw(); + virtual void OnDrawUI(); + ESceneGroupTool *ParentTools; + +private: + void MultiSelByRefObject(bool clear_prev); + void SelByRefObject(bool flag); + float m_selPercent; + xr_string m_Current; + bool m_ChooseGroup; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UILightTool.cpp b/src/editors/LevelEditor/UI/Tools/UILightTool.cpp new file mode 100644 index 00000000000..b651fb47184 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UILightTool.cpp @@ -0,0 +1,56 @@ +#include "stdafx.h" + +UILightTool::UILightTool() +{ +} + +UILightTool::~UILightTool() +{ +} + +void UILightTool::Draw() +{ + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Affect in D3D")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::PushItemWidth(-1); + float size = float(ImGui::CalcItemWidth()); + { + if (ImGui::Button("Enable Sel", ImVec2(size / 2, 0))) + UseInD3D(false, true); + ImGui::SameLine(0, 2); + if (ImGui::Button("Enable All", ImVec2(size / 2, 0))) + UseInD3D(true, true); + + if (ImGui::Button("Disable Sel", ImVec2(size / 2, 0))) + UseInD3D(false, false); + ImGui::SameLine(0, 2); + if (ImGui::Button("Disable All", ImVec2(size / 2, 0))) + UseInD3D(true, false); + } + + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} + +void UILightTool::UseInD3D(bool bAll, bool bFlag) +{ + ObjectIt _F = Scene->FirstObj(OBJCLASS_LIGHT); + ObjectIt _E = Scene->LastObj(OBJCLASS_LIGHT); + for (; _F != _E; _F++) + { + CLight *L = (CLight *)*_F; + if (bAll) + { + L->AffectD3D(bFlag); + } + else + { + if (L->Selected() && L->Visible()) + L->AffectD3D(bFlag); + } + } + UI->RedrawScene(); +} diff --git a/src/editors/LevelEditor/UI/Tools/UILightTool.h b/src/editors/LevelEditor/UI/Tools/UILightTool.h new file mode 100644 index 00000000000..efaa38df9bf --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UILightTool.h @@ -0,0 +1,11 @@ +#pragma once +class UILightTool : public UIToolCustom +{ +public: + UILightTool(); + virtual ~UILightTool(); + virtual void Draw(); + +private: + void UseInD3D(bool bAll, bool bFlag); +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UIObjectTool.cpp b/src/editors/LevelEditor/UI/Tools/UIObjectTool.cpp new file mode 100644 index 00000000000..0cbe39f72a9 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIObjectTool.cpp @@ -0,0 +1,389 @@ +#include "stdafx.h" +#include +#include +#include + +static std::atomic RefreshInProgress; + +UIObjectTool::UIObjectTool() +{ + m_selPercent = 0.f; + m_MultiAppend = false; + m_PropRandom = false; + m_Current = nullptr; + m_RandomAppend = false; + m_Selection = false; + m_RealTexture = nullptr; + m_RemoveTexture = nullptr; + RefreshInProgress = false; + m_ObjectList = xr_new(); + m_ObjectList->SetOnItemFocusedEvent(TOnILItemFocused(this, &UIObjectTool::OnItemFocused)); + m_TextureNull.create("ed\\ed_nodata"); + m_TextureNull->Load(); + m_Props = xr_new(); + RefreshList(); +} + +UIObjectTool::~UIObjectTool() +{ + while (RefreshInProgress) + std::this_thread::yield(); + + if (m_RemoveTexture) + m_RemoveTexture->Release(); + if (m_RealTexture) + m_RealTexture->Release(); + xr_delete(m_Props); + m_TextureNull.destroy(); + xr_delete(m_ObjectList); +} + +void UIObjectTool::Draw() +{ + if (m_RemoveTexture) + m_RemoveTexture->Release(); + m_RemoveTexture = nullptr; + static bool bbool = false; + float a = 1; + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Commands")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Button("Multiple Append", ImVec2(-1, 0))) + { + UIChooseForm::SelectItem(smObject, 512, 0); + m_MultiAppend = true; + } + } + ImGui::Separator(); + { + float size = float(ImGui::CalcItemWidth()); + { + if (ImGui::Checkbox("Random Append", &m_RandomAppend)) + { + ParentTools->ActivateAppendRandom(m_RandomAppend); + } + ImGui::SameLine(0, 10); + if (ImGui::Button("Random Props...", ImVec2(-1, 0))) + { + m_PropRandom = true; + ParentTools->FillAppendRandomPropertiesBegin(); + } + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Reference Select")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + ImGui::Text("Select by Current: "); + ImGui::SameLine(); + if (ImGui::Button(" +")) + { + SelByRefObject(true); + } + ImGui::SameLine(); + if (ImGui::Button(" -")) + { + SelByRefObject(false); + } + ImGui::Text("Select by Selected:"); + ImGui::SameLine(); + if (ImGui::Button("=%")) + { + MultiSelByRefObject(true); + } + ImGui::SameLine(); + if (ImGui::Button("+%")) + { + MultiSelByRefObject(false); + } + ImGui::SameLine(); + ImGui::SetNextItemWidth(-ImGui::GetTextLineHeight() - 8); + ImGui::DragFloat("%", &m_selPercent, 1, 0, 100, "%.1f"); + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Surface")) + { + + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Button("Clear Surface in select", ImVec2(-1, 0))) + { + Scene->UndoSave(); + ClearSurface(true); + } + if (ImGui::Button("Clear Surface in level", ImVec2(-1, 0))) + { + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to reset surface in level?") == mrYes) + { + Scene->UndoSave(); + ClearSurface(false); + } + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Current Object")) + { + + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Button("Select ...", ImVec2(-1, 0))) + { + UIChooseForm::SelectItem(smObject, 1, m_Current, 0, 0, 0, 0, 0); + m_Selection = true; + } + if (ImGui::Button("Refresh List", ImVec2(-1, 0))) + { + RefreshList(); + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Preview")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::Image(m_RealTexture ? m_RealTexture : (m_TextureNull->surface_get()), ImVec2(128, 128)); + ImGui::SameLine(); + ImGui::BeginChild("Props", ImVec2(0, 128)); + m_Props->Draw(); + ImGui::EndChild(); + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + + if (!RefreshInProgress) + { + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Object List")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::BeginChild("Object List"); + ImGui::Separator(); + m_ObjectList->Draw(); + ImGui::Separator(); + ImGui::EndChild(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + } + else + ImGui::Text("Loading..."); +} + +void UIObjectTool::RefreshList() +{ + if (RefreshInProgress) + return; + + std::thread refreshThread(&UIObjectTool::RefreshListInternal, this); + refreshThread.detach(); +} + +void UIObjectTool::RefreshListInternal() +{ + Msg("UIObjectTool refresh started"); + RefreshInProgress = true; + ListItemsVec items; + FS_FileSet lst; + + if (Lib.GetObjects(lst)) + { + auto it = lst.begin(); + auto _E = lst.end(); + for (; it != _E; it++) + { + xr_string fn; + ListItem *I = LHelper().CreateItem(items, it->name.c_str(), 0, ListItem::flDrawThumbnail, 0); + } + } + if (m_RealTexture) + m_RemoveTexture = m_RealTexture; + m_RealTexture = nullptr; + m_Props->ClearProperties(); + m_ObjectList->AssignItems(items); + RefreshInProgress = false; + Msg("UIObjectTool refresh finished"); +} + +void UIObjectTool::OnDrawUI() +{ + if (m_Selection) + { + bool change = false; + xr_string lst; + if (UIChooseForm::GetResult(change, lst)) + { + if (change) + { + m_ObjectList->SelectItem(lst.c_str()); + } + m_Selection = false; + } + + UIChooseForm::Update(); + } + if (m_MultiAppend) + { + bool change = false; + SStringVec lst; + if (UIChooseForm::GetResult(change, lst)) + { + if (change) + { + Fvector pos = {0.f, 0.f, 0.f}; + Fvector up = {0.f, 1.f, 0.f}; + Scene->SelectObjects(false, OBJCLASS_SCENEOBJECT); + + SPBItem *pb = UI->ProgressStart(static_cast(lst.size()), "Append object: "); + for (AStringIt it = lst.begin(); it != lst.end(); it++) + { + string256 namebuffer; + Scene->GenObjectName(OBJCLASS_SCENEOBJECT, namebuffer, it->c_str()); + CSceneObject *obj = xr_new((LPVOID)0, namebuffer); + CEditableObject *ref = obj->SetReference(it->c_str()); + if (!ref) + { + ELog.DlgMsg(mtError, "TfraObject:: Can't load reference object."); + xr_delete(obj); + return; + } + obj->MoveTo(pos, up); + Scene->AppendObject(obj); + } + UI->ProgressEnd(pb); + } + m_MultiAppend = false; + } + UIChooseForm::Update(); + } + if (m_PropRandom) + { + if (ParentTools->FillAppendRandomPropertiesEnd()) + { + m_PropRandom = false; + } + UIPropertiesModal::Update(); + } +} +void UIObjectTool::OnItemFocused(ListItem *item) +{ + if (m_RealTexture) + m_RemoveTexture = m_RealTexture; + m_RealTexture = nullptr; + m_Props->ClearProperties(); + m_Current = nullptr; + if (item) + { + m_Current = item->Key(); + auto *m_Thm = ImageLib.CreateThumbnail(m_Current, EImageThumbnail::ETObject); + if (m_Thm) + { + m_Thm->Update(m_RealTexture); + PropItemVec Info; + m_Thm->FillInfo(Info); + m_Props->AssignItems(Info); + } + } +} + +void UIObjectTool::SelByRefObject(bool flag) +{ + LPCSTR N = Current(); + if (N) + { + ObjectIt _F = Scene->FirstObj(OBJCLASS_SCENEOBJECT); + ObjectIt _E = Scene->LastObj(OBJCLASS_SCENEOBJECT); + for (; _F != _E; _F++) + { + if ((*_F)->Visible()) + { + CSceneObject *_O = (CSceneObject *)(*_F); + if (_O->RefCompare(N)) + _O->Select(flag); + } + } + } +} + +void UIObjectTool::MultiSelByRefObject(bool clear_prev) +{ + ObjectList objlist; + LPU32Vec sellist; + if (Scene->GetQueryObjects(objlist, OBJCLASS_SCENEOBJECT, 1, 1, -1)) + { + for (ObjectIt it = objlist.begin(); it != objlist.end(); it++) + { + LPCSTR N = ((CSceneObject *)*it)->RefName(); + ObjectIt _F = Scene->FirstObj(OBJCLASS_SCENEOBJECT); + ObjectIt _E = Scene->LastObj(OBJCLASS_SCENEOBJECT); + for (; _F != _E; _F++) + { + CSceneObject *_O = (CSceneObject *)(*_F); + if ((*_F)->Visible() && _O->RefCompare(N)) + { + if (clear_prev) + { + _O->Select(false); + sellist.push_back((u32 *)_O); + } + else + { + if (!_O->Selected()) + sellist.push_back((u32 *)_O); + } + } + } + } + std::sort(sellist.begin(), sellist.end()); + sellist.erase(std::unique(sellist.begin(), sellist.end()), sellist.end()); + + std::random_device rd; + std::mt19937 g(rd()); + std::shuffle(sellist.begin(), sellist.end(), g); + + int max_k = iFloor(float(sellist.size()) / 100.f * float(m_selPercent) + 0.5f); + int k = 0; + for (LPU32It o_it = sellist.begin(); k < max_k; o_it++, k++) + { + CSceneObject *_O = (CSceneObject *)(*o_it); + _O->Select(true); + } + } +} + +void UIObjectTool::ClearSurface(bool selected) +{ + { + ObjectIt _F = Scene->FirstObj(OBJCLASS_SCENEOBJECT); + ObjectIt _E = Scene->LastObj(OBJCLASS_SCENEOBJECT); + for (; _F != _E; _F++) + { + if ((*_F)->Visible()) + { + CSceneObject *_O = (CSceneObject *)(*_F); + if ((_O->Selected() && _O->Visible()) || !selected) + { + _O->ClearSurface(); + } + } + } + } +} diff --git a/src/editors/LevelEditor/UI/Tools/UIObjectTool.h b/src/editors/LevelEditor/UI/Tools/UIObjectTool.h new file mode 100644 index 00000000000..c82af980430 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIObjectTool.h @@ -0,0 +1,33 @@ +#pragma once +class ESceneObjectTool; + +class UIObjectTool : public UIToolCustom +{ +public: + UIObjectTool(); + virtual ~UIObjectTool(); + virtual void Draw(); + void RefreshList(); + const char *Current() { return m_Current; } + virtual void OnDrawUI(); + ESceneObjectTool *ParentTools; + +private: + void OnItemFocused(ListItem *item); + void SelByRefObject(bool flag); + void MultiSelByRefObject(bool flag); + void ClearSurface(bool selected); + void RefreshListInternal(); + const char *m_Current; + UIItemListForm *m_ObjectList; + bool m_MultiAppend; + bool m_PropRandom; + bool m_RandomAppend; + float m_selPercent; + bool m_Selection; + + ref_texture m_TextureNull; + ImTextureID m_RealTexture; + ImTextureID m_RemoveTexture; + UIPropertiesForm *m_Props; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UIParticlesTool.cpp b/src/editors/LevelEditor/UI/Tools/UIParticlesTool.cpp new file mode 100644 index 00000000000..8709fe28605 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIParticlesTool.cpp @@ -0,0 +1,111 @@ +#include "stdafx.h" + +UIParticlesTool::UIParticlesTool() +{ + m_Current = nullptr; + m_ParticlesList = xr_new(); + m_ParticlesList->SetOnItemFocusedEvent(TOnILItemFocused(this, &UIParticlesTool::OnItemFocused)); + ListItemsVec items; + for (PS::PEDIt E = ::Render->PSLibrary.FirstPED(); E != ::Render->PSLibrary.LastPED(); E++) + { + ListItem *I = LHelper().CreateItem(items, *(*E)->m_Name, 0, 0, *E); + I->SetIcon(1); + } + for (PS::PGDIt G = ::Render->PSLibrary.FirstPGD(); G != ::Render->PSLibrary.LastPGD(); G++) + { + ListItem *I = LHelper().CreateItem(items, *(*G)->m_Name, 0, 0, *G); + I->SetIcon(2); + } + + m_ParticlesList->AssignItems(items); +} + +UIParticlesTool::~UIParticlesTool() +{ + xr_delete(m_ParticlesList); +} + +void UIParticlesTool::Draw() +{ + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Commands")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + ImGui::Text("Ref's Select: "); + ImGui::SameLine(); + if (ImGui::Button("+", ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight()))) + { + SelByRef(true); + }; + ImGui::SameLine(); + if (ImGui::Button("-", ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight()))) + { + SelByRef(false); + }; + ImGui::Text("Selected: "); + ImGui::SameLine(); + if (ImGui::ArrowButton("play", ImGuiDir_Right)) + { + ObjectIt _F = Scene->FirstObj(OBJCLASS_PS); + ObjectIt _E = Scene->LastObj(OBJCLASS_PS); + for (; _F != _E; _F++) + { + if ((*_F)->Visible() && (*_F)->Selected()) + ((EParticlesObject *)(*_F))->Play(); + } + } + ImGui::SameLine(); + if (ImGui::Button("stop", ImVec2(0, ImGui::GetFrameHeight()))) + { + ObjectIt _F = Scene->FirstObj(OBJCLASS_PS); + ObjectIt _E = Scene->LastObj(OBJCLASS_PS); + for (; _F != _E; _F++) + { + if ((*_F)->Visible() && (*_F)->Selected()) + ((EParticlesObject *)(*_F))->Stop(); + } + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Particles")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::Separator(); + m_ParticlesList->Draw(); + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} + +void UIParticlesTool::SelByRef(bool flag) +{ + if (m_Current) + { + ObjectIt _F = Scene->FirstObj(OBJCLASS_PS); + ObjectIt _E = Scene->LastObj(OBJCLASS_PS); + for (; _F != _E; _F++) + { + if ((*_F)->Visible()) + { + EParticlesObject *_O = (EParticlesObject *)(*_F); + if (_O->RefCompare(m_Current)) + _O->Select(flag); + } + } + } +} + +void UIParticlesTool::OnItemFocused(ListItem *item) +{ + m_Current = nullptr; + if (item) + { + m_Current = item->Key(); + } +} diff --git a/src/editors/LevelEditor/UI/Tools/UIParticlesTool.h b/src/editors/LevelEditor/UI/Tools/UIParticlesTool.h new file mode 100644 index 00000000000..2725b3d285e --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIParticlesTool.h @@ -0,0 +1,15 @@ +#pragma once +class UIParticlesTool : public UIToolCustom +{ +public: + UIParticlesTool(); + virtual ~UIParticlesTool(); + virtual void Draw(); + IC const char *Current() const { return m_Current; } + +private: + void SelByRef(bool flag); + void OnItemFocused(ListItem *item); + UIItemListForm *m_ParticlesList; + const char *m_Current; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UIPortalTool.cpp b/src/editors/LevelEditor/UI/Tools/UIPortalTool.cpp new file mode 100644 index 00000000000..9914d19290c --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIPortalTool.cpp @@ -0,0 +1,57 @@ +#include "stdafx.h" + +UIPortalTool::UIPortalTool() +{ +} + +UIPortalTool::~UIPortalTool() +{ +} + +void UIPortalTool::Draw() +{ + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Command")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Button("Invert Orientation", ImVec2(-1, 0))) + { + ObjectList lst; + if (Scene->GetQueryObjects(lst, OBJCLASS_PORTAL, 1, 1, 0)) + { + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + CPortal *_O = (CPortal *)*it; + _O->InvertOrientation(true); + } + } + } + if (ImGui::Button("Compute All Portals", ImVec2(-1, 0))) + { + if (mrYes == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure want to destroy all existing portals and compute them again?")) + { + int cnt = PortalUtils.CalculateAllPortals(); + if (cnt) + ELog.DlgMsg(mtInformation, "Calculated '%d' portal(s).", cnt); + } + } + if (ImGui::Button("Compute Sel. Portals", ImVec2(-1, 0))) + { + if (mrYes == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure want to destroy all existing portals and compute them again?")) + { + int cnt = PortalUtils.CalculateSelectedPortals(); + if (cnt) + ELog.DlgMsg(mtInformation, "Calculated '%d' portal(s).", cnt); + } + } + if (ImGui::Button("Remove Similar", ImVec2(-1, 0))) + { + tool->RemoveSimilar(); + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} diff --git a/src/editors/LevelEditor/UI/Tools/UIPortalTool.h b/src/editors/LevelEditor/UI/Tools/UIPortalTool.h new file mode 100644 index 00000000000..741dac240e9 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIPortalTool.h @@ -0,0 +1,10 @@ +#pragma once +class EScenePortalTool; +class UIPortalTool : public UIToolCustom +{ +public: + UIPortalTool(); + virtual ~UIPortalTool(); + virtual void Draw(); + EScenePortalTool *tool; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UISectorTool.cpp b/src/editors/LevelEditor/UI/Tools/UISectorTool.cpp new file mode 100644 index 00000000000..a8c21216fd4 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UISectorTool.cpp @@ -0,0 +1,103 @@ +#include "stdafx.h" + +UISectorTool::UISectorTool() +{ + m_Edit = false; + m_CreateNewMultiple = false; + m_CreateNewSingle = false; + m_MeshAdd = true; + m_BoxPick = false; +} + +UISectorTool::~UISectorTool() +{ +} +void UISectorTool::Draw() +{ + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Command")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Button("Validate Sectors", ImVec2(-1, 0))) + { + PortalUtils.Validate(true); + } + if (ImGui::Button("Capture Volume", ImVec2(-1, 0))) + { + CSector *S = PortalUtils.GetSelectedSector(); + if (S) + { + S->CaptureInsideVolume(); + Scene->UndoSave(); + } + } + if (ImGui::Button("Distribute Objects", ImVec2(-1, 0))) + { + CSector *S = PortalUtils.GetSelectedSector(); + if (S) + { + S->DistributeInsideObjects(); + Scene->UndoSave(); + } + } + ImGui::Separator(); + if (ImGui::Button("Create Default", ImVec2(-1, 0))) + { + CCustomObject *O = Scene->FindObjectByName(DEFAULT_SECTOR_NAME, OBJCLASS_SECTOR); + if (O) + ELog.DlgMsg(mtInformation, "Default sector already present. Remove this and try again."); + else + { + if (!PortalUtils.CreateDefaultSector()) + ELog.DlgMsg(mtInformation, "Default can't created."); + } + } + if (ImGui::Button("Remove Default", ImVec2(-1, 0))) + { + if (!PortalUtils.RemoveDefaultSector()) + ELog.DlgMsg(mtInformation, "Default sector not found."); + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + if (m_Edit) + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (m_Edit && ImGui::TreeNode("Edit")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Checkbox("Create New Single (From Mesh)", &m_CreateNewSingle)) + { + m_CreateNewMultiple = false; + } + if (ImGui::Checkbox("Create New Multiple (From Object)", &m_CreateNewMultiple)) + { + m_CreateNewSingle = false; + } + ImGui::Separator(); + ImGui::Text("Meshes"); + ImGui::SameLine(); + if (ImGui::RadioButton("M+", m_MeshAdd)) + { + m_MeshAdd = true; + } + ImGui::SameLine(); + if (ImGui::RadioButton("M-", !m_MeshAdd)) + { + m_MeshAdd = false; + } + if (ImGui::Checkbox("Box Pick", &m_BoxPick)) + ; + if (m_CreateNewSingle || m_CreateNewMultiple) + { + m_BoxPick = false; + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} diff --git a/src/editors/LevelEditor/UI/Tools/UISectorTool.h b/src/editors/LevelEditor/UI/Tools/UISectorTool.h new file mode 100644 index 00000000000..8696dcccf19 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UISectorTool.h @@ -0,0 +1,22 @@ +#pragma once +class UISectorTool : public UIToolCustom +{ +public: + UISectorTool(); + virtual ~UISectorTool(); + virtual void Draw(); + IC void ShowEdit() { m_Edit = true; } + IC void HideEdit() { m_Edit = false; } + IC bool IsCreateNewMultiple() const { return m_CreateNewMultiple; } + IC bool IsCreateNewSingle() const { return m_CreateNewSingle; } + IC void SetCreateNewSingle(bool mode) { m_CreateNewSingle = mode; } + IC bool IsMeshAdd() const { return m_MeshAdd; } + IC bool IsBoxPick() const { return m_BoxPick; } + +private: + bool m_CreateNewMultiple; + bool m_CreateNewSingle; + bool m_MeshAdd; + bool m_BoxPick; + bool m_Edit; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UIShapeTool.cpp b/src/editors/LevelEditor/UI/Tools/UIShapeTool.cpp new file mode 100644 index 00000000000..24f3082909a --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIShapeTool.cpp @@ -0,0 +1,80 @@ +#include "stdafx.h" + +UIShapeTool::UIShapeTool() +{ + Tool = nullptr; + m_AttachShape = false; +} + +UIShapeTool::~UIShapeTool() +{ +} + +void UIShapeTool::Draw() +{ + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Commands")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::RadioButton("Sphere", m_SphereMode)) + { + m_SphereMode = true; + } + ImGui::SameLine(); + if (ImGui::RadioButton("Box", m_SphereMode == false)) + { + m_SphereMode = false; + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Edit")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Checkbox("Attach Shape...", &m_AttachShape)) + { + if (m_AttachShape) + ExecCommand(COMMAND_CHANGE_ACTION, etaAdd); + } + ImGui::SameLine(0, 10); + if (ImGui::Button("Detach All", ImVec2(-1, 0))) + { + ObjectList lst; + if (Scene->GetQueryObjects(lst, OBJCLASS_SHAPE, 1, 1, 0)) + { + Scene->SelectObjects(false, OBJCLASS_SHAPE); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + ((CEditShape *)*it)->Detach(); + } + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Level Bound")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Checkbox("Edit Level Bound", &EditLevelBound)) + { + if (EditLevelBound) + Tool->OnEditLevelBounds(false); + } + if (EditLevelBound) + if (ImGui::Button("Recalc", ImVec2(-1, 0))) + { + Tool->OnEditLevelBounds(true); + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} diff --git a/src/editors/LevelEditor/UI/Tools/UIShapeTool.h b/src/editors/LevelEditor/UI/Tools/UIShapeTool.h new file mode 100644 index 00000000000..fe1ad44b443 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIShapeTool.h @@ -0,0 +1,19 @@ +#pragma once +class ESceneShapeTool; +class UIShapeTool : public UIToolCustom +{ +public: + ESceneShapeTool *Tool; + UIShapeTool(); + virtual ~UIShapeTool(); + virtual void Draw(); + IC bool IsAttachShape() const { return m_AttachShape; } + IC bool IsSphereMode() const { return m_SphereMode; } + bool EditLevelBound; + IC void SetSphereMode(bool mode) { m_SphereMode = mode; } + IC void SetAttachShape(bool mode) { m_AttachShape = mode; } + +private: + bool m_AttachShape; + bool m_SphereMode; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UISpawnTool.cpp b/src/editors/LevelEditor/UI/Tools/UISpawnTool.cpp new file mode 100644 index 00000000000..d2791f1acb2 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UISpawnTool.cpp @@ -0,0 +1,198 @@ +#include "stdafx.h" +#include + +UISpawnTool::UISpawnTool() +{ + m_selPercent = 100; + m_Current = nullptr; + m_SpawnList = xr_new(); + m_SpawnList->SetOnItemFocusedEvent(TOnILItemFocused(this, &UISpawnTool::OnItemFocused)); + RefreshList(); + m_AttachObject = false; +} + +UISpawnTool::~UISpawnTool() +{ + xr_delete(m_SpawnList); +} + +void UISpawnTool::Draw() +{ + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Reference Select")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + ImGui::Text("Select by Current: "); + ImGui::SameLine(); + if (ImGui::Button(" +")) + { + SelByRefObject(true); + } + ImGui::SameLine(); + if (ImGui::Button(" -")) + { + SelByRefObject(false); + } + ImGui::Text("Select by Selected:"); + ImGui::SameLine(); + if (ImGui::Button("=%")) + { + MultiSelByRefObject(true); + } + ImGui::SameLine(); + if (ImGui::Button("+%")) + { + MultiSelByRefObject(false); + } + ImGui::SameLine(); + ImGui::SetNextItemWidth(-ImGui::GetTextLineHeight() - 8); + ImGui::DragFloat("%", &m_selPercent, 1, 0, 100, "%.1f"); + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Commands")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + float size = float(ImGui::CalcItemWidth()); + { + if (ImGui::Checkbox("Attach Object...", &m_AttachObject)) + { + if (m_AttachObject) + ExecCommand(COMMAND_CHANGE_ACTION, etaAdd); + } + ImGui::SameLine(0, 10); + if (ImGui::Button("Detach Object", ImVec2(-1, 0))) + { + ObjectList lst; + if (Scene->GetQueryObjects(lst, OBJCLASS_SPAWNPOINT, 1, 1, 0)) + { + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + CSpawnPoint *O = dynamic_cast(*it); + R_ASSERT(O); + O->DetachObject(); + } + } + } + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Object List")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::Separator(); + m_SpawnList->Draw(); + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} + +void UISpawnTool::SelByRefObject(bool flag) +{ + ObjectList objlist; + LPCSTR N = Current(); + if (N) + { + ObjectIt _F = Scene->FirstObj(OBJCLASS_SPAWNPOINT); + ObjectIt _E = Scene->LastObj(OBJCLASS_SPAWNPOINT); + for (; _F != _E; _F++) + { + if ((*_F)->Visible()) + { + CSpawnPoint *_O = (CSpawnPoint *)(*_F); + if (_O->RefCompare(N)) + _O->Select(flag); + } + } + } +} + +void UISpawnTool::MultiSelByRefObject(bool clear_prev) +{ + ObjectList objlist; + LPU32Vec sellist; + if (Scene->GetQueryObjects(objlist, OBJCLASS_SPAWNPOINT, 1, 1, -1)) + { + for (ObjectIt it = objlist.begin(); it != objlist.end(); it++) + { + LPCSTR N = ((CSpawnPoint *)*it)->RefName(); + ObjectIt _F = Scene->FirstObj(OBJCLASS_SPAWNPOINT); + ObjectIt _E = Scene->LastObj(OBJCLASS_SPAWNPOINT); + for (; _F != _E; _F++) + { + CSpawnPoint *_O = (CSpawnPoint *)(*_F); + if ((*_F)->Visible() && _O->RefCompare(N)) + { + if (clear_prev) + { + _O->Select(false); + sellist.push_back((u32 *)_O); + } + else + { + if (!_O->Selected()) + sellist.push_back((u32 *)_O); + } + } + } + } + + std::sort(sellist.begin(), sellist.end()); + sellist.erase(std::unique(sellist.begin(), sellist.end()), sellist.end()); + + std::random_device rd; + std::mt19937 g(rd()); + std::shuffle(sellist.begin(), sellist.end(), g); + + int max_k = iFloor(float(sellist.size()) / 100.f * float(m_selPercent) + 0.5f); + int k = 0; + for (LPU32It o_it = sellist.begin(); k < max_k; o_it++, k++) + { + CSpawnPoint *_O = (CSpawnPoint *)(*o_it); + _O->Select(true); + } + } +} + +void UISpawnTool::RefreshList() +{ + ListItemsVec items; + LHelper().CreateItem(items, RPOINT_CHOOSE_NAME, 0, 0, const_cast(RPOINT_CHOOSE_NAME)); + LHelper().CreateItem(items, ENVMOD_CHOOSE_NAME, 0, 0, const_cast(ENVMOD_CHOOSE_NAME)); + CInifile::Root &data = ((CInifile *)pSettings)->sections(); + for (auto it = data.begin(); it != data.end(); it++) + { + LPCSTR val; + if ((*it)->line_exist("$spawn", &val)) + { + shared_str caption = pSettings->r_string_wb((*it)->Name, "$spawn"); + shared_str sect = (*it)->Name; + if (caption.size()) + { + ListItem *I = LHelper().CreateItem(items, caption.c_str(), 0, ListItem::flDrawThumbnail, (LPVOID) * (*it)->Name); + // m_caption_to_sect[caption] = sect; + } + } + } + m_SpawnList->AssignItems(items); +} + +void UISpawnTool::OnItemFocused(ListItem *item) +{ + m_Current = 0; + if (item) + { + m_Current = (LPCSTR)item->m_Object; + } + ExecCommand(COMMAND_RENDER_FOCUS); +} diff --git a/src/editors/LevelEditor/UI/Tools/UISpawnTool.h b/src/editors/LevelEditor/UI/Tools/UISpawnTool.h new file mode 100644 index 00000000000..d74740d7118 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UISpawnTool.h @@ -0,0 +1,21 @@ +#pragma once +class UISpawnTool : public UIToolCustom +{ +public: + UISpawnTool(); + virtual ~UISpawnTool(); + virtual void Draw(); + void SelByRefObject(bool flag); + void MultiSelByRefObject(bool clear_prev); + IC const char *Current() { return m_Current; } + IC void SetAttachObject(bool AttachObject) { m_AttachObject = AttachObject; } + IC bool IsAttachObject() const { return m_AttachObject; } + +private: + void RefreshList(); + void OnItemFocused(ListItem *item); + const char *m_Current; + UIItemListForm *m_SpawnList; + float m_selPercent; + bool m_AttachObject; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UIToolCustom.h b/src/editors/LevelEditor/UI/Tools/UIToolCustom.h new file mode 100644 index 00000000000..8032be8d55c --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIToolCustom.h @@ -0,0 +1,6 @@ +#pragma once +class UIToolCustom : public xrUI +{ +public: + virtual void OnDrawUI() {} +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/Tools/UIWayTool.cpp b/src/editors/LevelEditor/UI/Tools/UIWayTool.cpp new file mode 100644 index 00000000000..9059b576be5 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIWayTool.cpp @@ -0,0 +1,144 @@ +#include "stdafx.h" + +UIWayTool::UIWayTool() +{ + m_WayMode = true; + m_AutoLink = true; +} + +UIWayTool::~UIWayTool() +{ +} + +void UIWayTool::Draw() +{ + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Commands")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::RadioButton("Way Mode", m_WayMode)) + { + LTools->SetTarget(OBJCLASS_WAY, 0); + m_WayMode = true; + } + ImGui::SameLine(); + if (ImGui::RadioButton("Way Point", m_WayMode == false)) + { + LTools->SetTarget(OBJCLASS_WAY, 1); + m_WayMode = false; + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Link Command")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + { + if (ImGui::Checkbox("Auto Link", &m_AutoLink)) + { + } + ImGui::PushItemWidth(-1); + float size = float(ImGui::CalcItemWidth()); + { + if (ImGui::Button("Create 1-Link", ImVec2(size / 2, 0))) + { + if (m_WayMode) + { + ELog.DlgMsg(mtInformation, "Before editing enter Point Mode."); + return; + } + bool bRes = false; + ObjectList lst; + Scene->GetQueryObjects(lst, OBJCLASS_WAY, 1, 1, 0); + // remove links + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + ((CWayObject *)(*it))->RemoveLink(); + bRes |= ((CWayObject *)(*it))->Add1Link(); + } + if (bRes) + Scene->UndoSave(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + ImGui::SameLine(0, 2); + if (ImGui::Button("Convert to 1-Link", ImVec2(size / 2, 0))) + { + ObjectList lst; + int cnt = Scene->GetQueryObjects(lst, OBJCLASS_WAY, 1, 1, 0); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + ((CWayObject *)(*it))->Convert1Link(); + if (cnt) + Scene->UndoSave(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + + if (ImGui::Button("Create 2-Link", ImVec2(size / 2, 0))) + { + if (m_WayMode) + { + ELog.DlgMsg(mtInformation, "Before editing enter Point Mode."); + return; + } + bool bRes = false; + ObjectList lst; + Scene->GetQueryObjects(lst, OBJCLASS_WAY, 1, 1, 0); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + bRes |= ((CWayObject *)(*it))->Add2Link(); + if (bRes) + Scene->UndoSave(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + ImGui::SameLine(0, 2); + if (ImGui::Button("Convert to 2-Link", ImVec2(size / 2, 0))) + { + ObjectList lst; + int cnt = Scene->GetQueryObjects(lst, OBJCLASS_WAY, 1, 1, 0); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + ((CWayObject *)(*it))->Convert2Link(); + if (cnt) + Scene->UndoSave(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + + if (ImGui::Button("Invert Link", ImVec2(size / 2, 0))) + { + if (m_WayMode) + { + ELog.DlgMsg(mtInformation, "Before editing enter Point Mode."); + return; + } + ObjectList lst; + int cnt = Scene->GetQueryObjects(lst, OBJCLASS_WAY, 1, 1, 0); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + ((CWayObject *)(*it))->InvertLink(); + if (cnt) + Scene->UndoSave(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + ImGui::SameLine(0, 2); + if (ImGui::Button("Remove Link", ImVec2(size / 2, 0))) + { + if (m_WayMode) + { + ELog.DlgMsg(mtInformation, "Before editing enter Point Mode."); + return; + } + ObjectList lst; + int cnt = Scene->GetQueryObjects(lst, OBJCLASS_WAY, 1, 1, 0); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + ((CWayObject *)(*it))->RemoveLink(); + if (cnt) + Scene->UndoSave(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + } + } + ImGui::Separator(); + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } +} diff --git a/src/editors/LevelEditor/UI/Tools/UIWayTool.h b/src/editors/LevelEditor/UI/Tools/UIWayTool.h new file mode 100644 index 00000000000..91e579bc825 --- /dev/null +++ b/src/editors/LevelEditor/UI/Tools/UIWayTool.h @@ -0,0 +1,14 @@ +#pragma once +class UIWayTool : public UIToolCustom +{ +public: + UIWayTool(); + virtual ~UIWayTool(); + virtual void Draw(); + IC bool IsAutoLink() const { return m_AutoLink; } + IC void SetWayMode(bool mode) { m_WayMode = mode; } + +private: + bool m_WayMode; + bool m_AutoLink; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/UIDOOneColor.cpp b/src/editors/LevelEditor/UI/UIDOOneColor.cpp new file mode 100644 index 00000000000..8e42a0353d7 --- /dev/null +++ b/src/editors/LevelEditor/UI/UIDOOneColor.cpp @@ -0,0 +1,79 @@ +#include "stdafx.h" +#include "UIDOOneColor.h" +#include "UIDOShuffle.h" + +UIDOOneColor::UIDOOneColor() +{ + list_index = 0; +} + +UIDOOneColor::~UIDOOneColor() +{ +} + +void UIDOOneColor::Draw() +{ + ImGui::BeginChild("ColorIndex", ImVec2(0, ImGui::GetFrameHeight() * 4), false, ImGuiWindowFlags_NoScrollbar); + ImGui::BeginGroup(); + + if (ImGui::ColorEdit3("##value", Color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel)) + DOShuffle->bModif = true; + + if (ImGui::Button("X", ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight()))) + { + DOShuffle->bModif = true; + bOpen = false; + } + + if (ImGui::Button(">", ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight()))) + { + if (DOShuffle->m_list_selected >= 0 && DOShuffle->m_list_selected < DOShuffle->m_list.size()) + { + AppendItem(DOShuffle->m_list[DOShuffle->m_list_selected]); + DOShuffle->bModif = true; + } + } + + if (ImGui::Button("<", ImVec2(ImGui::GetFrameHeight(), ImGui::GetFrameHeight()))) + { + if (list_index >= 0 && list_index < list.size()) + { + list.erase(list.begin() + list_index); + list_index = -1; + DOShuffle->bModif = true; + } + } + + ImGui::EndGroup(); + ImGui::SameLine(); + ImGui::SetNextItemWidth(-1); + ImGui::ListBox( + "##list", &list_index, [](void *data, int ind, const char **out) -> bool + {auto item = reinterpret_cast*>(data)->at(ind).c_str();; *out = item; return true; }, + reinterpret_cast(&list), list.size(), 4); + + ImGui::EndChild(); + ImGui::Separator(); +} + +void UIDOOneColor::RemoveObject(const xr_string &str) +{ + for (auto b = list.begin(), e = list.end(); b != e; b++) + { + if (*b == str) + { + list.erase(b); + return; + } + } +} + +void UIDOOneColor::AppendItem(const xr_string &item) +{ + for (xr_string &i : list) + { + if (i == item) + return; + } + list.push_back(item); +} diff --git a/src/editors/LevelEditor/UI/UIDOOneColor.h b/src/editors/LevelEditor/UI/UIDOOneColor.h new file mode 100644 index 00000000000..4a0d521d7a4 --- /dev/null +++ b/src/editors/LevelEditor/UI/UIDOOneColor.h @@ -0,0 +1,17 @@ +#pragma once +class UIDOShuffle; +class UIDOOneColor : public xrUI +{ +public: + UIDOOneColor(); + virtual ~UIDOOneColor(); + virtual void Draw(); + void RemoveObject(const xr_string &str); + float Color[3]; + xr_vector list; + int list_index; + UIDOShuffle *DOShuffle; + +private: + void AppendItem(const xr_string &item); +}; diff --git a/src/editors/LevelEditor/UI/UIDOShuffle.cpp b/src/editors/LevelEditor/UI/UIDOShuffle.cpp new file mode 100644 index 00000000000..aa101a2a12c --- /dev/null +++ b/src/editors/LevelEditor/UI/UIDOShuffle.cpp @@ -0,0 +1,299 @@ +#include "stdafx.h" + +UIDOShuffle* UIDOShuffle::Form = nullptr; +UIDOShuffle::UIDOShuffle() +{ + bModif = false; + m_ChooseObject = false; + m_Texture = nullptr; + m_TextureNull.create("ed\\ed_nodata"); + m_TextureNull->Load(); + m_Props = xr_new< UIPropertiesForm>(); + m_RealTexture = nullptr; +} + +UIDOShuffle::~UIDOShuffle() +{ + m_TextureNull.destroy(); + ApplyChanges(); + xr_delete(m_Props); + if (m_Texture) m_Texture->Release(); + ClearIndexForms(); + if (m_RealTexture)m_RealTexture->Release(); +} + +void UIDOShuffle::Draw() +{ + ImGui::Columns(2); + ImGui::BeginChild("Left"); + { + VERIFY(m_TextureNull->surface_get()); + if (m_RealTexture != m_Texture) + { + if (m_RealTexture)m_RealTexture->Release(); + m_RealTexture = m_Texture; + if(m_RealTexture) m_RealTexture->AddRef(); + + + } + ImGui::Image(m_RealTexture ? m_RealTexture :m_TextureNull->surface_get(), ImVec2(128, 128)); + + { + int selected = m_list_selected; + ImGui::SetNextItemWidth(-1); + if (ImGui::ListBox("##list", &selected, [](void* data, int ind, const char** out)->bool {auto item = reinterpret_cast*>(data)->at(ind).c_str();; *out = item; return true; }, reinterpret_cast(&m_list), m_list.size(), 15)) + { + if (m_list_selected != selected) + { + m_list_selected = selected; + OnItemFocused(m_list[selected].c_str()); + } + } + } + { + if (ImGui::Button("+", ImVec2(0, ImGui::GetFrameHeight()))) { UIChooseForm::SelectItem(smObject, 8); m_ChooseObject = true; }; ImGui::SameLine(); + if (ImGui::Button("-", ImVec2(0, ImGui::GetFrameHeight()))) + { + if (m_list_selected >= 0 && m_list.size() > m_list_selected) + { + DM->RemoveDO(m_list[m_list_selected].c_str()); + for (UIDOOneColor* one_color : m_color_indices) { one_color->RemoveObject(m_list[m_list_selected]); } + m_list.erase(m_list.begin() + m_list_selected); + OnItemFocused(nullptr); + bModif = true; + } + } + ImGui::SameLine(); + if (ImGui::Button("X", ImVec2(0, ImGui::GetFrameHeight()))) + { + m_list.clear(); + DM->InvalidateSlots(); + DM->ClearColorIndices(); + ClearIndexForms(); + UI->RedrawScene(); + OnItemFocused(nullptr); + bModif = true; + } + ImGui::SameLine(); + if (ImGui::Button("Load..", ImVec2(0, ImGui::GetFrameHeight()))) + { + xr_string fname; + if (EFS.GetOpenName(EDevice.m_hWnd,_detail_objects_, fname)) { + if (DM->ImportColorIndices(fname.c_str())) { + DM->InvalidateSlots(); + FillData(); + bModif = true; + } + } + } + ImGui::SameLine(); + if (ImGui::Button("Save..", ImVec2(-1, ImGui::GetFrameHeight()))) + { + xr_string fname; + if (EFS.GetSaveName(_detail_objects_, fname)) + { + ApplyChanges(false); + DM->ExportColorIndices(fname.c_str()); + } + + } + } + { + ImGui::BeginChild("Props", ImVec2(0, 0), false); + m_Props->Draw(); + ImGui::EndChild(); + } + + } + ImGui::EndChild(); + ImGui::NextColumn(); + ImGui::BeginChild("Right"); + { + if (ImGui::Button("X")) { ClearIndexForms(); } + ImGui::SameLine(); + if (ImGui::Button("Append Color Index", ImVec2(-1,0))) + { + m_color_indices.push_back(xr_new()); + m_color_indices.back()->DOShuffle = this; + } + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + { + int index = 0; + + for (UIDOOneColor* one_color : m_color_indices) + { + ImGui::PushID(index); + one_color->Draw(); + ImGui::PopID(); + index++; + } + for (auto b = m_color_indices.begin(), e = m_color_indices.end(); b != e; b++) + { + if ((*b)->IsClosed()) + { + auto ptr = *b; + xr_delete(ptr); + m_color_indices.erase(b); + b = m_color_indices.begin(); + } + } + } + ImGui::PopStyleVar(2); + } + ImGui::EndChild(); + ImGui::Columns(); + if (m_ChooseObject) + { + bool ok = false; + xr_vector list; + if (UIChooseForm::GetResult(ok,list)) + { + if (ok) + { + for (xr_string& l : list) + { + if (!FindItem(l.c_str())) + { + if (m_list.size() >= dm_max_objects) { + ELog.DlgMsg(mtInformation, "Maximum detail objects in scene '%d'", dm_max_objects); + return; + } + DM->AppendDO(l.c_str()); + m_list_selected = m_list.size(); + m_list.push_back(l); + } + } + OnItemFocused(list.back().c_str()); + bModif = true; + } + m_ChooseObject = false; + } + UIChooseForm::Update(); + } +} + +void UIDOShuffle::Update() +{ + if (Form && !Form->IsClosed()) + { + ImGui::SetNextWindowSize(ImVec2(400, 500), ImGuiCond_::ImGuiCond_FirstUseEver); + if (ImGui::BeginPopupModal("Detail Object List", &Form->bOpen,0,true)) + { + Form->Draw(); + ImGui::EndPopup(); + } + } + +} + +bool UIDOShuffle::GetResult() +{ + if (!Form->bOpen) + { + xr_delete(Form); + return true; + } + return false; +} + +void UIDOShuffle::Show(EDetailManager* DM) +{ + VERIFY(!Form); + Form = xr_new(); + Form->DM = DM; + Form->FillData(); +} + +void UIDOShuffle::FillData() +{ + m_list.clear(); + OnItemFocused(nullptr); + for (CDetailManager::DetailIt d_it = DM->objects.begin(); d_it != DM->objects.end(); d_it++) + m_list.push_back(((EDetail*)(*d_it))->GetName()); + ClearIndexForms(); + ColorIndexPairIt S = DM->m_ColorIndices.begin(); + ColorIndexPairIt E = DM->m_ColorIndices.end(); + ColorIndexPairIt it = S; + for (; it != E; it++) { + UIDOOneColor* OneColor = xr_new(); + OneColor->DOShuffle = this; + m_color_indices.push_back(OneColor); + OneColor->Color[0] = color_get_R(it->first)/255.f; + OneColor->Color[1] = color_get_G(it->first) / 255.f; + OneColor->Color[2] = color_get_B(it->first) / 255.f; + for (DOIt do_it = it->second.begin(); do_it != it->second.end(); do_it++) + { + EDetail* dd = 0; + for (CDetailManager::DetailIt d_it = DM->objects.begin(); d_it != DM->objects.end(); d_it++) + if (0 == strcmp(((EDetail*)(*d_it))->GetName(), (*do_it)->GetName())) { dd = (EDetail*)*d_it; break; } + VERIFY(dd); + OneColor->list.push_back(dd->GetName()); + } + } +} + +void UIDOShuffle::OnItemFocused(const char* name) +{ + + if (!name) + { + if (m_Texture) m_Texture->Release(); m_Texture = nullptr; + m_Props->ClearProperties(); + m_list_selected = -1; + return; + } + m_Thm = ImageLib.CreateThumbnail(name, EImageThumbnail::ETObject); + if (m_Texture) m_Texture->Release(); m_Texture = nullptr; + if (m_Thm)m_Thm->Update(m_Texture); + if (m_Thm)xr_delete(m_Thm); + EDetail *dd= DM->FindDOByName(name); + VERIFY(dd); + PropItemVec items; + + //PHelper().CreateCaption(items, "Ref Name", dd->GetName()); + PHelper().CreateFloat(items, "Density", &dd->m_fDensityFactor, 0.1f, 1.0f); + PHelper().CreateFloat(items, "Min Scale", &dd->m_fMinScale, 0.1f, 100.0f); + PHelper().CreateFloat(items, "Max Scale", &dd->m_fMaxScale, 0.1f, 100.f); + PHelper().CreateFlag32(items, "No Waving", &dd->m_Flags, DO_NO_WAVING); + + m_Props->AssignItems(items); +} + +bool UIDOShuffle::FindItem(const char* name) +{ + for (xr_string& nm : m_list) + { + if (nm == name)return true; + } + return false; +} + +void UIDOShuffle::ClearIndexForms() +{ + for (int i = 0; i < m_color_indices.size(); i++)xr_delete(m_color_indices[i]); + m_color_indices.clear(); +} + +bool UIDOShuffle::ApplyChanges(bool msg ) +{ + DM->RemoveColorIndices(); + for (u32 k = 0; k < m_color_indices.size(); k++) { + UIDOOneColor* OneColor = m_color_indices[k]; + if (OneColor->list.size()) + { + u32 clr = color_rgba_f(OneColor->Color[0], OneColor->Color[1], OneColor->Color[2], 1.f); + for (xr_string&i:OneColor->list) + DM->AppendIndexObject(clr, i.c_str(), false); + } + } + if (/*bNeedUpdate||*/bModif&& msg) + { + ELog.DlgMsg(mtInformation, "Object or object list changed. Reinitialize needed!"); + DM->InvalidateSlots(); + return true; + } + return false; +} + diff --git a/src/editors/LevelEditor/UI/UIDOShuffle.h b/src/editors/LevelEditor/UI/UIDOShuffle.h new file mode 100644 index 00000000000..8e905122436 --- /dev/null +++ b/src/editors/LevelEditor/UI/UIDOShuffle.h @@ -0,0 +1,47 @@ +#pragma once +class EDetailManager; +class EImageThumbnail; +class UIDOOneColor; +class UIDOShuffle : public xrUI +{ + friend UIDOOneColor; + +public: + UIDOShuffle(); + virtual ~UIDOShuffle(); + virtual void Draw(); + static void Update(); + static bool GetResult(); + static void Show(EDetailManager *DM); + +private: + static UIDOShuffle *Form; + +private: + EDetailManager *DM; + void FillData(); + +private: + UIPropertiesForm *m_Props; + +private: + EImageThumbnail *m_Thm; + ref_texture m_TextureNull; + ImTextureID m_Texture; + ImTextureID m_RealTexture; + +private: + void OnItemFocused(const char *name); + xr_vector m_list; + int m_list_selected; + bool FindItem(const char *name); + +private: + bool bModif; + bool m_ChooseObject; + +private: + void ClearIndexForms(); + xr_vector m_color_indices; + bool ApplyChanges(bool msg = true); +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/UIEditLibrary.cpp b/src/editors/LevelEditor/UI/UIEditLibrary.cpp new file mode 100644 index 00000000000..7c71884cdb9 --- /dev/null +++ b/src/editors/LevelEditor/UI/UIEditLibrary.cpp @@ -0,0 +1,738 @@ +#include "stdafx.h" + +UIEditLibrary *UIEditLibrary::Form = nullptr; + +UIEditLibrary::UIEditLibrary() +{ + { + ref_texture texture_null; + texture_null.create("ed\\ed_nodata"); + texture_null->Load(); + VERIFY(texture_null->surface_get()); + texture_null->surface_get()->AddRef(); + m_NullTexture = texture_null->surface_get(); + m_RealTexture = nullptr; + } + + m_ObjectList = xr_new(); + InitObjects(); + m_ObjectList->SetOnItemFocusedEvent(TOnILItemFocused(this, &UIEditLibrary::OnItemFocused)); + m_Props = xr_new(); + m_Selected = nullptr; + m_Preview = false; + m_SelectLods = false; +} + +void UIEditLibrary::OnItemFocused(ListItem *item) +{ + // TODO: возможно нужно текстуру удалять + // if (m_RealTexture)m_RemoveTexture = m_RealTexture; + m_RealTexture = nullptr; + m_Props->ClearProperties(); + m_Current = nullptr; + if (item) + { + m_Selected = item; + m_Current = item->Key(); + auto *m_Thm = ImageLib.CreateThumbnail(m_Current, EImageThumbnail::ETObject); + if (m_Thm) + { + m_Thm->Update(m_RealTexture); + PropItemVec Info; + m_Thm->FillInfo(Info); + m_Props->AssignItems(Info); + } + + if (m_Preview) + { + ListItemsVec vec; + vec.push_back(item); + SelectionToReference(&vec); + } + } + + // UpdateObjectProperties(); + UI->RedrawScene(); +} + +UIEditLibrary::~UIEditLibrary() +{ +} + +void UIEditLibrary::InitObjects() +{ + ListItemsVec items; + FS_FileSet lst; + + if (Lib.GetObjects(lst)) + { + auto it = lst.begin(); + auto _E = lst.end(); + for (; it != _E; it++) + { + xr_string fn; + ListItem *I = LHelper().CreateItem(items, it->name.c_str(), 0, ListItem::flDrawThumbnail, 0); + } + } + // if (m_RealTexture)m_RemoveTexture = m_RealTexture; + // m_RealTexture = nullptr; + // m_Props->ClearProperties(); + m_ObjectList->AssignItems(items); + + // m_Items.clear(); + // //ListItemsVec items; + // FS_FileSet lst; + // Lib.GetObjects(lst); + // auto it = lst.begin(); + // auto _E = lst.end(); + // for (; it != _E; it++) + // LHelper().CreateItem(m_Items, it->name.c_str(), 0, 0, 0); + // //m_Items->AssignItems(items, false, true); +} + +void UIEditLibrary::Update() +{ + if (!Form) + return; + + if (!Form->IsClosed()) + Form->Draw(); + else + Close(); +} + +void UIEditLibrary::Show() +{ + UI->BeginEState(esEditLibrary); + + if (!Form) + Form = xr_new(); +} + +void UIEditLibrary::Close() +{ + UI->EndEState(esEditLibrary); + // TODO: возможно еще кого то надо грохнуть + xr_delete(Form); +} + +void UIEditLibrary::DrawObjects() +{ + // if (ImGui::TreeNode("Object List")) + //{ + // ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::BeginChild("Object List"); + ImGui::Separator(); + // m_ObjectList->m_Flags.set(m_ObjectList->fMultiSelect, true); + m_ObjectList->Draw(); + ImGui::Separator(); + ImGui::EndChild(); + // ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + // ImGui::TreePop(); + //} + + /*for (ListItem *item : m_Items) + { + item->m_Object + } + + + if (it->first == OBJCLASS_DUMMY) + continue; + ObjectList& lst = ot->GetObjects(); + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("folder", ("%ss", it->second->ClassDesc()))) + { + if (OBJCLASS_GROUP == it->first) + { + for (ObjectIt _F = lst.begin(); _F != lst.end(); ++_F) + { + switch (m_Mode) + { + case UIObjectList::M_All: + break; + case UIObjectList::M_Visible: + if (!(*_F)->Visible())continue; + break; + case UIObjectList::M_Inbvisible: + if ((*_F)->Visible())continue; + break; + default: + break; + } + { + strcpy(str_name, ((CGroupObject*)(*_F))->GetName()); + } + DrawObject(*_F, str_name); + ImGui::PushID(str_name); + if (ImGui::TreeNode(str_name)) + { + ObjectList grp_lst; + + ((CGroupObject*)(*_F))->GetObjects(grp_lst); + + for (ObjectIt _G = grp_lst.begin(); _G != grp_lst.end(); _G++) + { + DrawObject(*_G, 0); + } + ImGui::TreePop(); + } + ImGui::PopID(); + } + } + else + { + bool FindSelectedObj = false; + for (ObjectIt _F = lst.begin(); _F != lst.end(); ++_F) + { + switch (m_Mode) + { + case UIObjectList::M_All: + break; + case UIObjectList::M_Visible: + if (!(*_F)->Visible())continue; + break; + case UIObjectList::M_Inbvisible: + if ((*_F)->Visible())continue; + break; + default: + break; + } + DrawObject(*_F, 0); + FindSelectedObj = FindSelectedObj | (*_F) == m_SelectedObject; + } + if (!FindSelectedObj)m_SelectedObject = nullptr; + + } + ImGui::TreePop(); + } + }*/ + + // m_cur_cls = LTools->CurrentClassID(); + // string1024 str_name; + + // for (SceneToolsMapPairIt it = Scene->FirstTool(); it != Scene->LastTool(); ++it) + //{ + // ESceneCustomOTool* ot = dynamic_cast(it->second); + // if (ot && ((m_cur_cls == OBJCLASS_DUMMY) || (it->first == m_cur_cls))) + // { + // if (it->first == OBJCLASS_DUMMY) + // continue; + // ObjectList& lst = ot->GetObjects(); + // ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + // if (ImGui::TreeNode("folder", ("%ss", it->second->ClassDesc()))) + // { + // if (OBJCLASS_GROUP == it->first) + // { + // for (ObjectIt _F = lst.begin(); _F != lst.end(); ++_F) + // { + // switch (m_Mode) + // { + // case UIObjectList::M_All: + // break; + // case UIObjectList::M_Visible: + // if (!(*_F)->Visible())continue; + // break; + // case UIObjectList::M_Inbvisible: + // if ((*_F)->Visible())continue; + // break; + // default: + // break; + // } + // { + // strcpy(str_name, ((CGroupObject*)(*_F))->GetName()); + // } + // DrawObject(*_F, str_name); + // ImGui::PushID(str_name); + // if (ImGui::TreeNode(str_name)) + // { + // ObjectList grp_lst; + + // ((CGroupObject*)(*_F))->GetObjects(grp_lst); + + // for (ObjectIt _G = grp_lst.begin(); _G != grp_lst.end(); _G++) + // { + // DrawObject(*_G, 0); + // } + // ImGui::TreePop(); + // } + // ImGui::PopID(); + // } + // } + // else + // { + // bool FindSelectedObj = false; + // for (ObjectIt _F = lst.begin(); _F != lst.end(); ++_F) + // { + // switch (m_Mode) + // { + // case UIObjectList::M_All: + // break; + // case UIObjectList::M_Visible: + // if (!(*_F)->Visible())continue; + // break; + // case UIObjectList::M_Inbvisible: + // if ((*_F)->Visible())continue; + // break; + // default: + // break; + // } + // DrawObject(*_F, 0); + // FindSelectedObj = FindSelectedObj | (*_F) == m_SelectedObject; + // } + // if (!FindSelectedObj)m_SelectedObject = nullptr; + + // } + // ImGui::TreePop(); + // } + // } + //} +} + +void UIEditLibrary::DrawObject(CCustomObject *obj, const char *name) +{ + /*if (m_Filter[0]) + { + if (name) + { + if (strstr(name, m_Filter) == 0)return; + } + else + { + if (strstr(obj->GetName(), m_Filter) == 0)return; + } + } + ImGuiTreeNodeFlags Flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; + + if (obj->Selected()) + { + Flags |= ImGuiTreeNodeFlags_Bullet; + } + if (m_SelectedObject == obj) + { + Flags |= ImGuiTreeNodeFlags_Selected; + } + if (name) + ImGui::TreeNodeEx(name, Flags); + else + ImGui::TreeNodeEx(obj->GetName(), Flags); + if (ImGui::IsItemClicked()) + { + if (!ImGui::GetIO().KeyCtrl) + Scene->SelectObjects(false, OBJCLASS_DUMMY); + obj->Select(true); + m_SelectedObject = obj; + }*/ +} + +void UIEditLibrary::GenerateLOD(RStringVec &props, bool bHighQuality) +{ + u32 lodsCnt = 0; + SPBItem* pb = UI->ProgressStart(static_cast(props.size()), "Making LOD"); + + for (const shared_str &str: props) + { + RStringVec reference; + reference.push_back(str); + ChangeReference(reference); // select item + + R_ASSERT(m_pEditObjects.size() == 1); + CSceneObject* SO = m_pEditObjects[0]; + CEditableObject* O = SO->GetReference(); + + if (O && O->IsMUStatic()) + { + pb->Inc(O->GetName()); + BOOL bLod = O->m_objectFlags.is(CEditableObject::eoUsingLOD); + O->m_objectFlags.set(CEditableObject::eoUsingLOD, FALSE); + xr_string tex_name; + tex_name = EFS.ChangeFileExt(O->GetName(), ""); + + string_path tmp; + strcpy(tmp, tex_name.c_str()); + _ChangeSymbol(tmp, '\\', '_'); + tex_name = xr_string("lod_") + tmp; + tex_name = ImageLib.UpdateFileName(tex_name); + ImageLib.CreateLODTexture(O, tex_name.c_str(), LOD_IMAGE_SIZE, LOD_IMAGE_SIZE, LOD_SAMPLE_COUNT, O->Version(), bHighQuality ? 4/*7*/ : 1); + O->OnDeviceDestroy(); + O->m_objectFlags.set(CEditableObject::eoUsingLOD, bLod); + ELog.Msg(mtInformation, "LOD for object '%s' successfully created.", O->GetName()); + lodsCnt++; + } + else + ELog.Msg(mtError, "Can't create LOD texture from non 'Multiple Usage' object.", SO->RefName()); + + if (UI->NeedAbort()) + break; + } + + UI->ProgressEnd(pb); + + if(lodsCnt) + ELog.DlgMsg(mtInformation, "'%u' LOD's succesfully created.", lodsCnt); +} + +void UIEditLibrary::MakeLOD(bool bHighQuality) +{ + //if (ebSave->Enabled) + //{ + // ELog.DlgMsg(mtError, "Save library changes before generating LOD."); + // return; + //} + + int res = ELog.DlgMsg(mtConfirmation, TMsgDlgButtons() | mbYes | mbNo | mbCancel, "Do you want to select multiple objects?"); + + if (res == mrCancel) + return; + + if (res == mrNo) + { + RStringVec sel_items; + sel_items.push_back(m_Selected->Key()); + GenerateLOD(sel_items, bHighQuality); + return; + } + + R_ASSERT(res == mrYes); + UIChooseForm::SelectItem(smObject, 512, 0); + m_SelectLods = true; + m_HighQualityLod = true; + // answer is handled in DrawRightBar +} + +void UIEditLibrary::OnMakeThmClick() +{ + U32Vec pixels; + ListItemsVec sel_items; + + if (!m_Selected) + return; + + sel_items.push_back(m_Selected); + //m_Items->GetSelected(NULL, sel_items, false); + ListItemsIt it = sel_items.begin(); + ListItemsIt it_e = sel_items.end(); + + for (; it != it_e; ++it) + { + ListItem* item = *it; + CEditableObject* obj = Lib.CreateEditObject(item->Key()); + + if (obj && m_Preview) + { + string_path fn; + FS.update_path(fn, _objects_, ChangeFileExt(obj->GetName(), ".thm").c_str()); + + //m_Items->SelectItem(item->Key(), true, false, true); + if (ImageLib.CreateOBJThumbnail(fn, obj, obj->Version())) + ELog.Msg(mtInformation, "Thumbnail successfully created."); + } + else + ELog.DlgMsg(mtError, "Can't create thumbnail. Set preview mode."); + + Lib.RemoveEditObject(obj); + } + + ELog.DlgMsg(mtInformation, "Done."); +} + +void UIEditLibrary::OnPropertiesClick() +{ + MessageBoxA(0, 0, 0, 0); +} + +void UIEditLibrary::DrawRightBar() +{ + if (ImGui::BeginChild("Right", ImVec2(192, 0))) + { + if (m_NullTexture || m_RealTexture) + { + if (m_RealTexture) + ImGui::Image(m_RealTexture, ImVec2(192, 192)); + else + ImGui::Image(m_NullTexture, ImVec2(192, 192)); + } + else + ImGui::InvisibleButton("Image", ImVec2(192, 192)); + + m_Props->Draw(); + + // if (disabled) + { + ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); + } + + if (ImGui::Button("Properties", ImVec2(-1, 0))) + OnPropertiesClick(); + + //if (disabled) + { + ImGui::PopItemFlag(); + ImGui::PopStyleVar(); + } + + // Make Thumbnail & Lod + { + bool enableMakeThumbnailAndLod = m_Selected && m_Preview; + + if (!enableMakeThumbnailAndLod) + { + ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); + } + + if (ImGui::Button("Make Thumbnail", ImVec2(-1, 0))) + OnMakeThmClick(); + + if (ImGui::Button("Make LOD (High Quality)", ImVec2(-1, 0))) + MakeLOD(true); + + if (ImGui::Button("Make LOD (Low Quality)", ImVec2(-1, 0))) + MakeLOD(false); + + if (!enableMakeThumbnailAndLod) + { + ImGui::PopItemFlag(); + ImGui::PopStyleVar(); + } + } + + if (ImGui::Checkbox("Preview", &m_Preview)) + OnPreviewClick(); + + // if (disabled) + { + ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); + } + + if (ImGui::Button("Rename Object", ImVec2(-1, 0))) + { + } + if (ImGui::Button("Remove Object", ImVec2(-1, 0))) + { + } + + if (ImGui::Button("Import Object", ImVec2(-1, 0))) + { + } + if (ImGui::Button("Export LWO", ImVec2(-1, 0))) + { + } + + if (ImGui::Button("Save", ImVec2(-1, 0))) + { + } + + // if (disabled) + { + ImGui::PopItemFlag(); + ImGui::PopStyleVar(); + } + + if (ImGui::Button("Close", ImVec2(-1, 0))) + Close(); + + ImGui::EndChild(); + } + + if (m_SelectLods) + { + bool change = false; + SStringVec lst; + + if (UIChooseForm::GetResult(change, lst)) + { + if (change) + { + RStringVec selItems; + + for (const xr_string &xrStr: lst) + selItems.push_back(xrStr.c_str()); + + GenerateLOD(selItems, m_HighQualityLod); + } + + m_SelectLods = false; + } + + UIChooseForm::Update(); + } +} + +void UIEditLibrary::OnPreviewClick() +{ + RefreshSelected(); +} + +void UIEditLibrary::RefreshSelected() +{ + bool mt = false; + + if (m_Preview) + { + if (m_Selected) + { + ListItemsVec vec; + vec.push_back(m_Selected); + mt = SelectionToReference(&vec); + } + else + mt = SelectionToReference(nullptr); + } + + //ebMakeThm->Enabled = !bReadOnly && mt; + //ebMakeLOD_high->Enabled = !bReadOnly && cbPreview->Checked; + //ebMakeLOD_low->Enabled = !bReadOnly && cbPreview->Checked; + UI->RedrawScene(); +} + +bool UIEditLibrary::SelectionToReference(ListItemsVec *props) +{ + RStringVec sel_strings; + ListItemsVec sel_items; + + if(props) + sel_items = *props; + // else + // m_Items->GetSelected(NULL, sel_items, false /*true*/); + + ListItemsIt it = sel_items.begin(); + ListItemsIt it_e = sel_items.end(); + + for (; it != it_e; ++it) + { + ListItem *item = *it; + sel_strings.push_back(item->Key()); + } + ChangeReference(sel_strings); + return sel_strings.size() > 0; +} + +void UIEditLibrary::ChangeReference(const RStringVec &items) +{ + xr_vector::iterator it = m_pEditObjects.begin(); + xr_vector::iterator it_e = m_pEditObjects.end(); + for (; it != it_e; ++it) + { + CSceneObject *SO = *it; + xr_delete(SO); + } + + m_pEditObjects.clear(); + + RStringVec::const_iterator sit = items.begin(); + RStringVec::const_iterator sit_e = items.end(); + + for (; sit != sit_e; ++sit) + { + CSceneObject *SO = xr_new((LPVOID)0, (LPSTR)0); + m_pEditObjects.push_back(SO); + SO->SetReference((*sit).c_str()); + + CEditableObject *NE = SO->GetReference(); + if (NE) + { + SO->FPosition = NE->t_vPosition; + SO->FScale = NE->t_vScale; + SO->FRotation = NE->t_vRotate; + } + // update transformation + SO->UpdateTransform(); + + /* + // save new position + CEditableObject* E = m_pEditObject->GetReference(); + + if (E && new_name && (stricmp(E->GetName(),new_name))==0 ) return; + + if (E) + { + E->t_vPosition.set (m_pEditObject->PPosition); + E->t_vScale.set (m_pEditObject->PScale); + E->t_vRotate.set (m_pEditObject->PRotation); + } + m_pEditObject->SetReference (new_name); + // get old position + E = m_pEditObject->GetReference(); + if (E) + { + m_pEditObject->PPosition = E->t_vPosition; + m_pEditObject->PScale = E->t_vScale; + m_pEditObject->PRotation = E->t_vRotate; + } + // update transformation + m_pEditObject->UpdateTransform (); + */ + } + + ExecCommand(COMMAND_EVICT_OBJECTS); + ExecCommand(COMMAND_EVICT_TEXTURES); +} + +void UIEditLibrary::OnRender() +{ + if (!Form) + return; + + if (!Form->m_Preview) + return; + + for (auto &it : Form->m_pEditObjects) + { + CSceneObject *SO = it; + CSceneObject *S = SO; + + CEditableObject *O = SO->GetReference(); + if (O) + { + S->m_RT_Flags.set(S->flRT_Visible, true); + + if (!S->FPosition.similar(O->t_vPosition)) + S->FPosition = O->t_vPosition; + + if (!S->FRotation.similar(O->t_vRotate)) + S->FRotation = O->t_vRotate; + + if (!S->FScale.similar(O->t_vScale)) + S->FScale = O->t_vScale; + + SO->OnFrame(); + SO->RenderSingle(); + // static bool strict = true; + // SO->Render(0, strict); + } + } +} + +void UIEditLibrary::Draw() +{ + ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(600, 600)); + + if (!ImGui::Begin("Object Library", &bOpen)) + { + ImGui::PopStyleVar(1); + ImGui::End(); + return; + } + + { + ImGui::BeginGroup(); + + if (ImGui::BeginChild("Left", ImVec2(-192, -ImGui::GetFrameHeight() - 4), true)) + DrawObjects(); + + ImGui::EndChild(); + ImGui::SetNextItemWidth(-192); + ImGui::Text(" Items count: %u", m_ObjectList->m_Items.size()); + // ImGui::InputText("##value", m_Filter, sizeof(m_Filter)); + ImGui::EndGroup(); + } + + ImGui::SameLine(); + DrawRightBar(); + + ImGui::PopStyleVar(1); + ImGui::End(); +} diff --git a/src/editors/LevelEditor/UI/UIEditLibrary.h b/src/editors/LevelEditor/UI/UIEditLibrary.h new file mode 100644 index 00000000000..82a1149417f --- /dev/null +++ b/src/editors/LevelEditor/UI/UIEditLibrary.h @@ -0,0 +1,69 @@ +#pragma once + +class UIEditLibrary : public xrUI +{ +public: + UIEditLibrary(); + virtual ~UIEditLibrary(); + + static void Update(); + static void Show(); + static void Close(); + static void OnRender(); + + ImTextureID m_NullTexture; + ImTextureID m_RealTexture; + + void OnItemFocused(ListItem *item); + +private: + static UIEditLibrary *Form; + + virtual void Draw(); + void DrawObjects(); + + void DrawRightBar(); + void DrawObject(CCustomObject *obj, const char *name); + void InitObjects(); + void OnPropertiesClick(); + void OnMakeThmClick(); + void OnPreviewClick(); + + void MakeLOD(bool highQuality); + void GenerateLOD(RStringVec &props, bool bHighQuality); + + void RefreshSelected(); + void ChangeReference(const RStringVec &items); + bool SelectionToReference(ListItemsVec *props); + + UIItemListForm* m_ObjectList; + UIPropertiesForm* m_Props; + LPCSTR m_Current; + bool m_Preview; + ListItem* m_Selected; + + bool m_SelectLods; + bool m_HighQualityLod; + + xr_vector m_pEditObjects; + + /* + + static IC bool IsOpen() { return Form; } +private: + static UIObjectList* Form; +private: + void DrawObjects(); + void DrawObject(CCustomObject* obj, const char* name); +private: + ObjClassID m_cur_cls; + enum EMode + { + M_All, + M_Visible, + M_Inbvisible + }; + EMode m_Mode; + CCustomObject* m_SelectedObject; + string_path m_Filter;*/ +}; diff --git a/src/editors/LevelEditor/UI/UILPropertiesFrom.cpp b/src/editors/LevelEditor/UI/UILPropertiesFrom.cpp new file mode 100644 index 00000000000..3861e2c544e --- /dev/null +++ b/src/editors/LevelEditor/UI/UILPropertiesFrom.cpp @@ -0,0 +1,21 @@ +#include "stdafx.h" + +UILPropertiesFrom::UILPropertiesFrom() +{ +} + +UILPropertiesFrom::~UILPropertiesFrom() +{ +} + +void UILPropertiesFrom::Draw() +{ + if (bOpen) + { + if (ImGui::Begin("Properties", &bOpen)) + { + LTools->GetProperties()->Draw(); + } + ImGui::End(); + } +} diff --git a/src/editors/LevelEditor/UI/UILPropertiesFrom.h b/src/editors/LevelEditor/UI/UILPropertiesFrom.h new file mode 100644 index 00000000000..1546258d635 --- /dev/null +++ b/src/editors/LevelEditor/UI/UILPropertiesFrom.h @@ -0,0 +1,10 @@ +#pragma once +class UILPropertiesFrom : public xrUI +{ +public: + UILPropertiesFrom(); + virtual ~UILPropertiesFrom(); + virtual void Draw(); + IC void Open() { bOpen = true; } + IC void Close() { bOpen = false; } +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/UILeftBarForm.cpp b/src/editors/LevelEditor/UI/UILeftBarForm.cpp new file mode 100644 index 00000000000..099d277a8da --- /dev/null +++ b/src/editors/LevelEditor/UI/UILeftBarForm.cpp @@ -0,0 +1,145 @@ +#include "stdafx.h" + +UILeftBarForm::UILeftBarForm() +{ + m_UseSnapList = false; + m_SnapListMode = false; + m_SnapItem_Current = 0; +} + +UILeftBarForm::~UILeftBarForm() +{ +} + +void UILeftBarForm::Draw() +{ + ImGui::Begin("LeftBar", 0); + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Tools")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + static ObjClassID Tools[OBJCLASS_COUNT + 1] = { + OBJCLASS_SCENEOBJECT, + OBJCLASS_LIGHT, + OBJCLASS_SOUND_SRC, + OBJCLASS_SOUND_ENV, OBJCLASS_GLOW, + OBJCLASS_SHAPE, + OBJCLASS_SPAWNPOINT, + OBJCLASS_WAY, + OBJCLASS_SECTOR, + OBJCLASS_PORTAL, + OBJCLASS_GROUP, + OBJCLASS_PS, + OBJCLASS_DO, + OBJCLASS_AIMAP, + OBJCLASS_WM, + OBJCLASS_FOG_VOL, + OBJCLASS_force_dword}; + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 1)); + ImGui::Columns(2); + ImGui::Separator(); + for (u32 i = 0; Tools[i] != OBJCLASS_force_dword; i++) + { + u32 id = 0; + if (i % 2) + id = ((OBJCLASS_COUNT + 1) / 2) + (i / 2); + else + id = (i / 2); + ESceneToolBase *tool = Scene->GetTool(Tools[id]); + bool visble = tool->IsVisible(); + ImGui::PushID(tool->ClassName()); + if (ImGui::Checkbox("##value", &visble)) + { + tool->m_EditFlags.set(ESceneToolBase::flVisible, visble); + UI->RedrawScene(); + }; + ImGui::SameLine(); + + if (ImGui::RadioButton(tool->ClassDesc(), LTools->GetTarget() == Tools[id])) + { + ExecCommand(COMMAND_CHANGE_TARGET, Tools[id]); + } + ImGui::PopID(); + ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + ImGui::PopStyleVar(2); + ImGui::TreePop(); + + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + } + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("Snap List")) + { + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 1)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 4)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4, 0)); + ImGui::Separator(); + { + ImGui::BulletText("Commands", ImGuiDir_Left); + if (ImGui::BeginPopupContextItem("Commands", 1)) + { + if (ImGui::MenuItem("Make List From Selected")) + { + ExecCommand(COMMAND_SET_SNAP_OBJECTS); + } + if (ImGui::MenuItem("Select Object From List")) + { + ExecCommand(COMMAND_SELECT_SNAP_OBJECTS); + } + ImGui::Separator(); + if (ImGui::MenuItem("Add Selected To List")) + { + ExecCommand(COMMAND_ADD_SEL_SNAP_OBJECTS); + } + if (ImGui::MenuItem("Remove Selected From List")) + { + ExecCommand(COMMAND_DEL_SEL_SNAP_OBJECTS); + } + ImGui::EndPopup(); + } + ImGui::OpenPopupOnItemClick("Commands", 0); + } + // ImGui::Checkbox("Enable/Show Snap List", &test); + ImGui::Checkbox("Enable/Show Snap List", &m_UseSnapList); + + ImGui::Separator(); + ImGui::Checkbox("+/- Mode", &m_SnapListMode); + ImGui::SameLine(0, 10); + if (ImGui::Button("X")) + { + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to clear snap objects?") == mrYes) + ExecCommand(COMMAND_CLEAR_SNAP_OBJECTS); + } + ImGui::PopStyleVar(2); + /* + + if (lst&&!lst->empty()){ + int idx=0; + ObjectIt _F=lst->begin(); + for (;_F!=lst->end(); _F++,idx++){ + AnsiString s; s.sprintf("%d: %s",idx,(*_F)->Name); + lbSnapList->Items->Add(s); + } + }*/ + ObjectList *lst = Scene->GetSnapList(true); + + ImGui::SetNextItemWidth(-1); + ImGui::ListBox( + "##snap_list_box", &m_SnapItem_Current, [](void *data, int ind, const char **out) -> bool + {auto item = reinterpret_cast(data)->begin(); std::advance(item, ind); *out = (*item)->GetName(); return true; }, + reinterpret_cast(lst), lst->size(), 7); + ImGui::TreePop(); + ImGui::PopStyleVar(2); + + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + } + if (LTools->GetToolForm()) + LTools->GetToolForm()->Draw(); + ImGui::End(); +} diff --git a/src/editors/LevelEditor/UI/UILeftBarForm.h b/src/editors/LevelEditor/UI/UILeftBarForm.h new file mode 100644 index 00000000000..165a4410f08 --- /dev/null +++ b/src/editors/LevelEditor/UI/UILeftBarForm.h @@ -0,0 +1,15 @@ +#pragma once +class UILeftBarForm : public xrUI +{ +public: + UILeftBarForm(); + virtual ~UILeftBarForm(); + virtual void Draw(); + IC bool IsUseSnapList() const { return m_UseSnapList; } + IC bool IsSnapListMode() const { return m_SnapListMode; } + +private: + bool m_UseSnapList; + bool m_SnapListMode; + int m_SnapItem_Current; +}; diff --git a/src/editors/LevelEditor/UI/UIMainForm.cpp b/src/editors/LevelEditor/UI/UIMainForm.cpp new file mode 100644 index 00000000000..55d1147446a --- /dev/null +++ b/src/editors/LevelEditor/UI/UIMainForm.cpp @@ -0,0 +1,115 @@ +#include "stdafx.h" +#include "../xrECore/Editor/EditorChooseEvents.h" + +void resptrcode_texture::create(LPCSTR _name) { _set(RImplementation.Resources->_CreateTexture(_name)); } + +UIMainForm *MainForm = nullptr; + +UIMainForm::UIMainForm() +{ + EnableReceiveCommands(); + if (!ExecCommand(COMMAND_INITIALIZE, (u32)0, (u32)0)) + { + FlushLog(); + exit(-1); + } + ExecCommand(COMMAND_UPDATE_GRID); + ExecCommand(COMMAND_RENDER_FOCUS); + FillChooseEvents(); + m_TopBar = xr_new(); + m_Render = xr_new(); + m_MainMenu = xr_new(); + m_LeftBar = xr_new(); + m_Properties = xr_new(); + m_Render->SetContextMenuEvent(TOnRenderContextMenu(this, &UIMainForm::DrawContextMenu)); + if (dynamic_cast(EPrefs)->OpenObjectList) + { + UIObjectList::Show(); + } + if (!dynamic_cast(EPrefs)->OpenProperties) + { + m_Properties->Close(); + } +} + +UIMainForm::~UIMainForm() +{ + dynamic_cast(EPrefs)->OpenProperties = !m_Properties->IsClosed(); + dynamic_cast(EPrefs)->OpenObjectList = UIObjectList::IsOpen(); + ClearChooseEvents(); + xr_delete(m_Properties); + xr_delete(m_LeftBar); + xr_delete(m_MainMenu); + xr_delete(m_Render); + xr_delete(m_TopBar); + ExecCommand(COMMAND_DESTROY, (u32)0, (u32)0); +} + +void UIMainForm::Draw() +{ + m_MainMenu->Draw(); + m_TopBar->Draw(); + m_LeftBar->Draw(); + m_Properties->Draw(); + // ImGui::ShowDemoWindow(&bOpen); + m_Render->Draw(); +} + +bool UIMainForm::Frame() +{ + if (UI) + return UI->Idle(); + return false; +} + +void UIMainForm::DrawContextMenu() +{ + if (ImGui::BeginMenu("Edit")) + { + if (ImGui::MenuItem("Copy")) + { + ExecCommand(COMMAND_COPY); + } + if (ImGui::MenuItem("Paste")) + { + ExecCommand(COMMAND_PASTE); + } + ImGui::Separator(); + if (ImGui::MenuItem("Cut")) + { + ExecCommand(COMMAND_CUT); + } + ImGui::Separator(); + if (ImGui::MenuItem("Delete")) + { + ExecCommand(COMMAND_DELETE_SELECTION); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Visiblity")) + { + if (ImGui::MenuItem("Hide Selected")) + { + ExecCommand(COMMAND_HIDE_SEL, FALSE); + } + if (ImGui::MenuItem("Hide Unselected")) + { + ExecCommand(COMMAND_HIDE_UNSEL); + } + if (ImGui::MenuItem("Hide All")) + { + ExecCommand(COMMAND_HIDE_ALL, FALSE); + } + ImGui::Separator(); + if (ImGui::MenuItem("Unhide All")) + { + ExecCommand(COMMAND_HIDE_ALL, TRUE); + } + ImGui::EndMenu(); + } + ImGui::Separator(); + if (ImGui::MenuItem("Properties")) + { + ExecCommand(COMMAND_SHOW_PROPERTIES); + } +} diff --git a/src/editors/LevelEditor/UI/UIMainForm.h b/src/editors/LevelEditor/UI/UIMainForm.h new file mode 100644 index 00000000000..369db054821 --- /dev/null +++ b/src/editors/LevelEditor/UI/UIMainForm.h @@ -0,0 +1,24 @@ +#pragma once +class UIMainForm : public xrUI +{ +public: + UIMainForm(); + virtual ~UIMainForm(); + virtual void Draw(); + bool Frame(); + IC UILeftBarForm *GetLeftBarForm() { return m_LeftBar; } + IC UITopBarForm *GetTopBarForm() { return m_TopBar; } + IC UIRenderForm *GetRenderForm() { return m_Render; } + IC UILPropertiesFrom *GetPropertiesFrom() { return m_Properties; } + +private: + UITopBarForm *m_TopBar; + UIRenderForm *m_Render; + UIMainMenuForm *m_MainMenu; + UILeftBarForm *m_LeftBar; + UILPropertiesFrom *m_Properties; + +private: + void DrawContextMenu(); +}; +extern UIMainForm *MainForm; diff --git a/src/editors/LevelEditor/UI/UIMainMenuForm.cpp b/src/editors/LevelEditor/UI/UIMainMenuForm.cpp new file mode 100644 index 00000000000..08d0657b043 --- /dev/null +++ b/src/editors/LevelEditor/UI/UIMainMenuForm.cpp @@ -0,0 +1,428 @@ +#include "stdafx.h" + +UIMainMenuForm::UIMainMenuForm() +{ +} + +UIMainMenuForm::~UIMainMenuForm() +{ +} + +void UIMainMenuForm::Draw() +{ + + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Clear", "")) + { + ExecCommand(COMMAND_CLEAR); + } + if (ImGui::MenuItem("Open...", "")) + { + ExecCommand(COMMAND_LOAD); + } + if (ImGui::MenuItem("Save", "")) + { + ExecCommand(COMMAND_SAVE, xr_string(LTools->m_LastFileName.c_str())); + } + if (ImGui::MenuItem("Save As ...", "")) + { + ExecCommand(COMMAND_SAVE, 0, 1); + } + ImGui::Separator(); + if (ImGui::MenuItem("Open Selection...", "")) + { + ExecCommand(COMMAND_LOAD_SELECTION); + } + if (ImGui::MenuItem("Save Selection As...", "")) + { + ExecCommand(COMMAND_SAVE_SELECTION); + } + ImGui::Separator(); + if (ImGui::BeginMenu("Open Recent", "")) + { + for (auto &str : EPrefs->scene_recent_list) + { + if (ImGui::MenuItem(str.c_str(), "")) + { + ExecCommand(COMMAND_LOAD, str); + } + } + ImGui::EndMenu(); + } + ImGui::Separator(); + if (ImGui::MenuItem("Quit", "")) + { + ExecCommand(COMMAND_QUIT); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Scene")) + { + if (ImGui::MenuItem("Validate", "")) + { + ExecCommand(COMMAND_VALIDATE_SCENE); + } + ImGui::Separator(); + if (ImGui::MenuItem("Summary Info", "")) + { + ExecCommand(COMMAND_CLEAR_SCENE_SUMMARY); + ExecCommand(COMMAND_COLLECT_SCENE_SUMMARY); + ExecCommand(COMMAND_SHOW_SCENE_SUMMARY); + } + if (ImGui::MenuItem("Highlight Texture...", "")) + { + ExecCommand(COMMAND_SCENE_HIGHLIGHT_TEXTURE); + } + ImGui::Separator(); + if (ImGui::MenuItem("Clear Debug Draw", "")) + { + ExecCommand(COMMAND_CLEAR_DEBUG_DRAW); + } + ImGui::Separator(); + if (ImGui::MenuItem("Export entire Scene as Obj", "")) + { + Scene->ExportObj(false); + } + if (ImGui::MenuItem("Export selection as Obj", "")) + { + Scene->ExportObj(true); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Compile")) + { + if (ImGui::MenuItem("Build", "")) + { + ExecCommand(COMMAND_BUILD); + } + ImGui::Separator(); + if (ImGui::MenuItem("Make Game", "")) + { + ExecCommand(COMMAND_MAKE_GAME); + } + if (ImGui::MenuItem("Make Details", "")) + { + ExecCommand(COMMAND_MAKE_DETAILS); + } + if (ImGui::MenuItem("Make Hom", "")) + { + ExecCommand(COMMAND_MAKE_HOM); + } + if (ImGui::MenuItem("Make ", "")) + { + ExecCommand(COMMAND_MAKE_SOM); + } + if (ImGui::MenuItem("Make AI-Map", "")) + { + ExecCommand(COMMAND_MAKE_AIMAP); + } + ImGui::Separator(); + if (ImGui::MenuItem("Import Error List", "")) + { + ExecCommand(COMMAND_IMPORT_COMPILER_ERROR); + } + if (ImGui::MenuItem("Export Error List", "")) + { + ExecCommand(COMMAND_EXPORT_COMPILER_ERROR); + } + if (ImGui::MenuItem("Clear Error List", "")) + { + ExecCommand(COMMAND_CLEAR_DEBUG_DRAW); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Editors")) + { + if (ImGui::BeginMenu("Objects")) + { + if (ImGui::MenuItem("Reload")) + { + ExecCommand(COMMAND_RELOAD_OBJECTS); + } + ImGui::Separator(); + if (ImGui::MenuItem("Library editor")) + { + ExecCommand(COMMAND_LIBRARY_EDITOR); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Images")) + { + if (ImGui::MenuItem("Image Editor", "")) + { + ExecCommand(COMMAND_IMAGE_EDITOR); + } + ImGui::Separator(); + if (ImGui::MenuItem("Reload Textures", "")) + { + ExecCommand(COMMAND_RELOAD_TEXTURES); + } + ImGui::Separator(); + if (ImGui::MenuItem("Synchronize Textures", "")) + { + ExecCommand(COMMAND_REFRESH_TEXTURES); + } + if (ImGui::MenuItem("Check New Textures", "")) + { + ExecCommand(COMMAND_CHECK_TEXTURES); + } + ImGui::Separator(); + if (ImGui::MenuItem("Sync THM", "")) + { + FS_FileSet files; + FS.file_list(files, _textures_, FS_ListFiles, "*.thm"); + FS_FileSet::iterator I = files.begin(); + FS_FileSet::iterator E = files.end(); + + for (; I != E; ++I) + { + ETextureThumbnail *TH = xr_new((*I).name.c_str(), false); + TH->Load((*I).name.c_str(), _textures_); + TH->Save(); + xr_delete(TH); + } + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Sounds")) + { + if (ImGui::MenuItem("Sound Editor", "")) + { + ExecCommand(COMMAND_SOUND_EDITOR); + } + ImGui::Separator(); + if (ImGui::MenuItem("Synchronize Sounds", "")) + { + ExecCommand(COMMAND_SYNC_SOUNDS); + } + ImGui::Separator(); + if (ImGui::MenuItem("Refresh Environment Library", "")) + { + ExecCommand(COMMAND_REFRESH_SOUND_ENVS); + } + if (ImGui::MenuItem("Refresh Environment Geometry", "")) + { + ExecCommand(COMMAND_REFRESH_SOUND_ENV_GEOMETRY); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Light Anim Editor", "")) + { + ExecCommand(COMMAND_LIGHTANIM_EDITOR); + } + if (ImGui::MenuItem("Minimap Editor", "")) + { + ExecCommand(COMMAND_MINIMAP_EDITOR); + } + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu("Options")) + { + if (ImGui::BeginMenu("Render")) + { + if (ImGui::BeginMenu("Quality")) + { + static bool selected[4] = {false, false, true, false}; + if (ImGui::MenuItem("25%", "", &selected[0])) + { + selected[1] = selected[2] = selected[3] = false; + UI->SetRenderQuality(1 / 4.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("50%", "", &selected[1])) + { + selected[0] = selected[2] = selected[3] = false; + UI->SetRenderQuality(1 / 2.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("100%", "", &selected[2])) + { + selected[1] = selected[0] = selected[3] = false; + UI->SetRenderQuality(1.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("200%", "", &selected[3])) + { + selected[1] = selected[2] = selected[0] = false; + UI->SetRenderQuality(2.f); + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Fill Mode")) + { + bool selected[3] = {EDevice.dwFillMode == D3DFILL_POINT, EDevice.dwFillMode == D3DFILL_WIREFRAME, EDevice.dwFillMode == D3DFILL_SOLID}; + if (ImGui::MenuItem("Point", "", &selected[0])) + { + EDevice.dwFillMode = D3DFILL_POINT; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Wireframe", "", &selected[1])) + { + EDevice.dwFillMode = D3DFILL_WIREFRAME; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Solid", "", &selected[2])) + { + EDevice.dwFillMode = D3DFILL_SOLID; + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Shader Mode")) + { + bool selected[2] = {EDevice.dwShadeMode == D3DSHADE_FLAT, EDevice.dwShadeMode == D3DSHADE_GOURAUD}; + if (ImGui::MenuItem("Flat", "", &selected[0])) + { + EDevice.dwShadeMode = D3DSHADE_FLAT; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Gouraud", "", &selected[1])) + { + EDevice.dwShadeMode = D3DSHADE_GOURAUD; + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + { + bool selected = psDeviceFlags.test(rsEdgedFaces); + if (ImGui::MenuItem("Edged Faces", "", &selected)) + { + psDeviceFlags.set(rsEdgedFaces, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = !HW.Caps.bForceGPU_SW; + if (ImGui::MenuItem("RenderHW", "", &selected)) + { + HW.Caps.bForceGPU_SW = !selected; + UI->Resize(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsFilterLinear); + if (ImGui::MenuItem("Filter Linear", "", &selected)) + { + psDeviceFlags.set(rsFilterLinear, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsRenderTextures); + if (ImGui::MenuItem("Textures", "", &selected)) + { + psDeviceFlags.set(rsRenderTextures, selected); + UI->RedrawScene(); + } + } + ImGui::EndMenu(); + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsDrawSafeRect); + if (ImGui::MenuItem("Draw Safe Rect", "", &selected)) + { + psDeviceFlags.set(rsDrawSafeRect, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsDrawGrid); + if (ImGui::MenuItem("Draw Grid", "", &selected)) + { + psDeviceFlags.set(rsDrawGrid, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsFog); + if (ImGui::MenuItem("Fog", "", &selected)) + { + psDeviceFlags.set(rsFog, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsLighting); + ; + if (ImGui::MenuItem("Lighting", "", &selected)) + { + psDeviceFlags.set(rsLighting, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsMuteSounds); + if (ImGui::MenuItem("Mute Sounds", "", &selected)) + { + psDeviceFlags.set(rsMuteSounds, selected); + } + } + { + bool selected = psDeviceFlags.test(rsRenderRealTime); + if (ImGui::MenuItem("Real Time", "", &selected)) + { + psDeviceFlags.set(rsRenderRealTime, selected); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsStatistic); + if (ImGui::MenuItem("Stats", "", &selected)) + { + psDeviceFlags.set(rsStatistic, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + if (ImGui::MenuItem("Preferences", "")) + { + ExecCommand(COMMAND_EDITOR_PREF); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Windows")) + { + { + bool selected = UIObjectList::IsOpen(); + if (ImGui::MenuItem("Object List", "", &selected)) + { + if (selected) + UIObjectList::Show(); + else + UIObjectList::Close(); + } + } + { + bool selected = !MainForm->GetPropertiesFrom()->IsClosed(); + if (ImGui::MenuItem("Properties", "", &selected)) + { + if (selected) + MainForm->GetPropertiesFrom()->Open(); + else + MainForm->GetPropertiesFrom()->Close(); + } + } + { + bool selected = AllowLogCommands(); + + if (ImGui::MenuItem("Log", "", &selected)) + { + ExecCommand(COMMAND_LOG_COMMANDS); + } + } + + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } +} diff --git a/src/editors/LevelEditor/UI/UIMainMenuForm.h b/src/editors/LevelEditor/UI/UIMainMenuForm.h new file mode 100644 index 00000000000..a44b6606609 --- /dev/null +++ b/src/editors/LevelEditor/UI/UIMainMenuForm.h @@ -0,0 +1,8 @@ +#pragma once +class UIMainMenuForm : public xrUI +{ +public: + UIMainMenuForm(); + virtual ~UIMainMenuForm(); + virtual void Draw(); +}; diff --git a/src/editors/LevelEditor/UI/UIObjectList.cpp b/src/editors/LevelEditor/UI/UIObjectList.cpp new file mode 100644 index 00000000000..f0b1a564276 --- /dev/null +++ b/src/editors/LevelEditor/UI/UIObjectList.cpp @@ -0,0 +1,226 @@ +#include "stdafx.h" + +UIObjectList *UIObjectList::Form = nullptr; + +UIObjectList::UIObjectList() +{ + m_Mode = M_Visible; + m_Filter[0] = 0; + m_SelectedObject = nullptr; +} + +UIObjectList::~UIObjectList() +{ +} + +void UIObjectList::Draw() +{ + ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(400, 400)); + + if (!ImGui::Begin("Object List", &bOpen)) + { + ImGui::PopStyleVar(1); + ImGui::End(); + return; + } + { + ImGui::BeginGroup(); + if (ImGui::BeginChild("Left", ImVec2(-130, -ImGui::GetFrameHeight() - 4), true)) + { + DrawObjects(); + } + ImGui::EndChild(); + + ImGui::SetNextItemWidth(-130); + ImGui::InputText("##value", m_Filter, sizeof(m_Filter)); + ImGui::EndGroup(); + } + ImGui::SameLine(); + if (ImGui::BeginChild("Right", ImVec2(130, 0))) + { + if (ImGui::RadioButton("All", m_Mode == M_All)) + { + m_Mode = M_All; + } + if (ImGui::RadioButton("Visible Only", m_Mode == M_Visible)) + { + m_Mode = M_Visible; + } + if (ImGui::RadioButton("Invisible Only", m_Mode == M_Inbvisible)) + { + m_Mode = M_Inbvisible; + } + ImGui::Separator(); + if (ImGui::Button("Show Selected", ImVec2(-1, 0))) + { + if (m_SelectedObject) + { + m_SelectedObject->Show(true); + m_SelectedObject->Select(true); + } + } + if (ImGui::Button("Hide Selected", ImVec2(-1, 0))) + { + if (m_SelectedObject) + { + m_SelectedObject->Show(false); + } + } + } + ImGui::EndChild(); + + ImGui::PopStyleVar(1); + ImGui::End(); +} + +void UIObjectList::Update() +{ + if (Form) + { + if (!Form->IsClosed()) + { + Form->Draw(); + } + else + { + xr_delete(Form); + } + } +} + +void UIObjectList::Show() +{ + if (Form == nullptr) + Form = xr_new(); +} + +void UIObjectList::Close() +{ + xr_delete(Form); +} + +void UIObjectList::DrawObjects() +{ + + m_cur_cls = LTools->CurrentClassID(); + string1024 str_name; + + for (SceneToolsMapPairIt it = Scene->FirstTool(); it != Scene->LastTool(); ++it) + { + ESceneCustomOTool *ot = dynamic_cast(it->second); + if (ot && ((m_cur_cls == OBJCLASS_DUMMY) || (it->first == m_cur_cls))) + { + if (it->first == OBJCLASS_DUMMY) + continue; + ObjectList &lst = ot->GetObjects(); + ImGui::SetNextItemOpen(true, ImGuiCond_FirstUseEver); + if (ImGui::TreeNode("folder", ("%ss", it->second->ClassDesc()))) + { + if (OBJCLASS_GROUP == it->first) + { + for (ObjectIt _F = lst.begin(); _F != lst.end(); ++_F) + { + switch (m_Mode) + { + case UIObjectList::M_All: + break; + case UIObjectList::M_Visible: + if (!(*_F)->Visible()) + continue; + break; + case UIObjectList::M_Inbvisible: + if ((*_F)->Visible()) + continue; + break; + default: + break; + } + { + strcpy(str_name, ((CGroupObject *)(*_F))->GetName()); + } + DrawObject(*_F, str_name); + ImGui::PushID(str_name); + if (ImGui::TreeNode(str_name)) + { + ObjectList grp_lst; + + ((CGroupObject *)(*_F))->GetObjects(grp_lst); + + for (ObjectIt _G = grp_lst.begin(); _G != grp_lst.end(); _G++) + { + DrawObject(*_G, 0); + } + ImGui::TreePop(); + } + ImGui::PopID(); + } + } + else + { + bool FindSelectedObj = false; + for (ObjectIt _F = lst.begin(); _F != lst.end(); ++_F) + { + switch (m_Mode) + { + case UIObjectList::M_All: + break; + case UIObjectList::M_Visible: + if (!(*_F)->Visible()) + continue; + break; + case UIObjectList::M_Inbvisible: + if ((*_F)->Visible()) + continue; + break; + default: + break; + } + DrawObject(*_F, 0); + FindSelectedObj = FindSelectedObj | (*_F) == m_SelectedObject; + } + if (!FindSelectedObj) + m_SelectedObject = nullptr; + } + ImGui::TreePop(); + } + } + } +} + +void UIObjectList::DrawObject(CCustomObject *obj, const char *name) +{ + if (m_Filter[0]) + { + if (name) + { + if (strstr(name, m_Filter) == 0) + return; + } + else + { + if (strstr(obj->GetName(), m_Filter) == 0) + return; + } + } + ImGuiTreeNodeFlags Flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; + + if (obj->Selected()) + { + Flags |= ImGuiTreeNodeFlags_Bullet; + } + if (m_SelectedObject == obj) + { + Flags |= ImGuiTreeNodeFlags_Selected; + } + if (name) + ImGui::TreeNodeEx(name, Flags); + else + ImGui::TreeNodeEx(obj->GetName(), Flags); + if (ImGui::IsItemClicked()) + { + if (!ImGui::GetIO().KeyCtrl) + Scene->SelectObjects(false, OBJCLASS_DUMMY); + obj->Select(true); + m_SelectedObject = obj; + } +} diff --git a/src/editors/LevelEditor/UI/UIObjectList.h b/src/editors/LevelEditor/UI/UIObjectList.h new file mode 100644 index 00000000000..04760a8dcf2 --- /dev/null +++ b/src/editors/LevelEditor/UI/UIObjectList.h @@ -0,0 +1,32 @@ +#pragma once +class CCustomObject; +class UIObjectList : public xrUI +{ +public: + UIObjectList(); + virtual ~UIObjectList(); + virtual void Draw(); + static void Update(); + static void Show(); + static void Close(); + static IC bool IsOpen() { return Form; } + +private: + static UIObjectList *Form; + +private: + void DrawObjects(); + void DrawObject(CCustomObject *obj, const char *name); + +private: + ObjClassID m_cur_cls; + enum EMode + { + M_All, + M_Visible, + M_Inbvisible + }; + EMode m_Mode; + CCustomObject *m_SelectedObject; + string_path m_Filter; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/UIPropertiesModal.cpp b/src/editors/LevelEditor/UI/UIPropertiesModal.cpp new file mode 100644 index 00000000000..a3964f64316 --- /dev/null +++ b/src/editors/LevelEditor/UI/UIPropertiesModal.cpp @@ -0,0 +1,58 @@ +#include "stdafx.h" +UIPropertiesModal *UIPropertiesModal::Form = nullptr; +UIPropertiesModal::UIPropertiesModal() +{ + m_Props = xr_new(); + m_Result = R_Cancel; +} + +UIPropertiesModal::~UIPropertiesModal() +{ + xr_delete(m_Props); +} + +void UIPropertiesModal::Draw() +{ + m_Props->Draw(); + if (ImGui::Button("Ok")) + { + m_Result = R_Ok; + bOpen = false; + } + ImGui::SameLine(); + if (ImGui::Button("Cancel")) + { + bOpen = false; + } +} + +void UIPropertiesModal::Update() +{ + if (Form && !Form->IsClosed()) + { + ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver); + if (ImGui::BeginPopupModal("Properties Modal", &Form->bOpen, 0, true)) + { + Form->Draw(); + ImGui::EndPopup(); + } + } +} + +bool UIPropertiesModal::GetResult(bool &ok) +{ + if (!Form->bOpen) + { + ok = Form->m_Result == R_Ok; + xr_delete(Form); + return true; + } + return false; +} + +void UIPropertiesModal::Show(PropItemVec &items) +{ + VERIFY(!Form); + Form = xr_new(); + Form->m_Props->AssignItems(items); +} diff --git a/src/editors/LevelEditor/UI/UIPropertiesModal.h b/src/editors/LevelEditor/UI/UIPropertiesModal.h new file mode 100644 index 00000000000..428f035d26c --- /dev/null +++ b/src/editors/LevelEditor/UI/UIPropertiesModal.h @@ -0,0 +1,26 @@ +#pragma once +class UIPropertiesModal : public xrUI +{ +public: + UIPropertiesModal(); + virtual ~UIPropertiesModal(); + virtual void Draw(); + static void Update(); + static bool GetResult(bool &ok); + static void Show(PropItemVec &items); + static IC UIPropertiesForm *GetProperties() { return Form->m_Props; } + +private: + static UIPropertiesModal *Form; + +private: + UIPropertiesForm *m_Props; + +private: + enum Result + { + R_Ok, + R_Cancel + }; + Result m_Result; +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/UITopBarForm.cpp b/src/editors/LevelEditor/UI/UITopBarForm.cpp new file mode 100644 index 00000000000..00b07223cf4 --- /dev/null +++ b/src/editors/LevelEditor/UI/UITopBarForm.cpp @@ -0,0 +1,313 @@ +#include "stdafx.h" + +UITopBarForm::UITopBarForm() +{ + +#define ADD_BUTTON_IMAGE_T1(Class, Name) +#define ADD_BUTTON_IMAGE_T2(Class, Name) +#define ADD_BUTTON_IMAGE_S(Name) \ + m_t##Name = EDevice.Resources->_CreateTexture("ed\\bar\\" #Name); \ + m_time##Name = 0; +#define ADD_BUTTON_IMAGE_D(Name) \ + m_t##Name = EDevice.Resources->_CreateTexture("ed\\bar\\" #Name); \ + m_b##Name = false; +#include "UITopBarForm_ButtonList.h" + RefreshBar(); +} + +UITopBarForm::~UITopBarForm() +{ +} + +void UITopBarForm::Draw() +{ + ImGuiViewport *viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + UI->GetMenuBarHeight())); + ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, UIToolBarSize)); + ImGui::SetNextWindowViewport(viewport->ID); + + ImGuiWindowFlags window_flags = 0 | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings; + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(2, 2)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(2, 2)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 2)); + ImGui::Begin("TOOLBAR", NULL, window_flags); + { +#define ADD_BUTTON_IMAGE_S(Name) \ + m_t##Name->Load(); \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_time##Name > EDevice.TimerAsync() ? 0.5 : 0, 0), ImVec2(m_time##Name > EDevice.TimerAsync() ? 1 : 0.5, 1), 0)) \ + { \ + m_time##Name = EDevice.TimerAsync() + 130; \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_D(Name) \ + m_t##Name->Load(); \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_b##Name ? 0.5 : 0, 0), ImVec2(m_b##Name ? 1 : 0.5, 1), 0)) \ + { \ + m_b##Name = !m_b##Name; \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_P(Name) \ + m_t##Name->Load(); \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_b##Name ? 0.5 : 0, 0), ImVec2(m_b##Name ? 1 : 0.5, 1), 0)) \ + { \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_T1(Class, Name) \ + ImGui::PushID("" #Class); \ + ImGui::PushStyleColor(ImGuiCol_Text, (ImVec4)ImColor::HSV(0, 0, 0)); \ + if (ImGui::Button("" #Name, ImVec2(20, 20))) \ + { \ + Click##Class##Name(); \ + } \ + ImGui::SameLine(); \ + ImGui::PopStyleColor(1); \ + ImGui::PopID(); +#define ADD_BUTTON_IMAGE_T2(Class, Name) \ + ImGui::PushID("" #Class); \ + if (ImGui::Button("" #Name, ImVec2(20, 20))) \ + { \ + Click##Class##Name(); \ + } \ + ImGui::SameLine(); \ + ImGui::PopID(); +//#define ADD_BUTTON_IMAGE_T1_1(Class, Name, T) \ +// ImGui::PushStyleColor(ImGuiCol_Text, (ImVec4)ImColor::HSV(0, 0, 0)); \ +// if (ImGui::Button("" #T, ImVec2(20, 20))) \ +// { \ +// Click##Class##Name(); \ +// } \ +// ImGui::SameLine(); \ +// ImGui::PopStyleColor(1); +#include "UITopBarForm_ButtonList.h" + } + ImGui::End(); + ImGui::PopStyleVar(5); +} +void UITopBarForm::RefreshBar() +{ + { + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = false; + + switch (Tools->GetAction()) + { + case etaSelect: + m_bSelect = true; + break; + case etaAdd: + m_bAdd = true; + break; + case etaMove: + m_bMove = true; + break; + case etaRotate: + m_bRotate = true; + break; + case etaScale: + m_bScale = true; + break; + default: + THROW; + } + } + { + m_bX = false; + m_bY = false; + m_bZ = false; + m_bZX = false; + // axis + switch (Tools->GetAxis()) + { + case etAxisX: + m_bX = true; + break; + case etAxisY: + m_bY = true; + break; + case etAxisZ: + m_bZ = true; + break; + case etAxisZX: + m_bZX = true; + break; + default: + THROW; + } + } + // settings + m_bCsLocal = Tools->GetSettings(etfCSParent); + m_bNuScale = Tools->GetSettings(etfNUScale); + m_bNSnap = Tools->GetSettings(etfNormalAlign); + m_bGSnap = Tools->GetSettings(etfGSnap); + m_bOSnap = Tools->GetSettings(etfOSnap); + m_bMoveToSnap = Tools->GetSettings(etfMTSnap); + m_bVSnap = Tools->GetSettings(etfVSnap); + m_bASnap = Tools->GetSettings(etfASnap); + m_bMSnap = Tools->GetSettings(etfMSnap); +} + +void UITopBarForm::ClickUndo() +{ + ExecCommand(COMMAND_UNDO); +} + +void UITopBarForm::ClickRedo() +{ + ExecCommand(COMMAND_REDO); +} +void UITopBarForm::ClickZoom() +{ + ExecCommand(COMMAND_ZOOM_EXTENTS, FALSE); +} + +void UITopBarForm::ClickZoomSel() +{ + ExecCommand(COMMAND_ZOOM_EXTENTS, TRUE); +} +void UITopBarForm::ClickSelect() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + m_bSelect = true; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickAdd() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaAdd); + m_bSelect = false; + m_bAdd = true; + m_bMove = false; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickMove() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaMove); + m_bSelect = false; + m_bAdd = false; + m_bMove = true; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickRotate() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaRotate); + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = true; + m_bScale = false; +} +void UITopBarForm::ClickScale() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaScale); + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = true; +} +void UITopBarForm::ClickX() +{ + ExecCommand(COMMAND_CHANGE_AXIS, etAxisX); + m_bX = true; + m_bY = false; + m_bZ = false; + m_bZX = false; +} +void UITopBarForm::ClickY() +{ + ExecCommand(COMMAND_CHANGE_AXIS, etAxisY); + m_bX = false; + m_bY = true; + m_bZ = false; + m_bZX = false; +} +void UITopBarForm::ClickZ() +{ + ExecCommand(COMMAND_CHANGE_AXIS, etAxisZ); + m_bX = false; + m_bY = false; + m_bZ = true; + m_bZX = false; +} +void UITopBarForm::ClickZX() +{ + ExecCommand(COMMAND_CHANGE_AXIS, etAxisZX); + m_bX = false; + m_bY = false; + m_bZ = false; + m_bZX = true; +} + +void UITopBarForm::ClickCsLocal() { ExecCommand(COMMAND_SET_SETTINGS, etfCSParent, m_bCsLocal); } +void UITopBarForm::ClickNuScale() { ExecCommand(COMMAND_SET_SETTINGS, etfNUScale, m_bNuScale); } +void UITopBarForm::ClickGSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfGSnap, m_bGSnap); } +void UITopBarForm::ClickOSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfOSnap, m_bOSnap); } +void UITopBarForm::ClickMoveToSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfMTSnap, m_bMoveToSnap); } +void UITopBarForm::ClickNSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfNormalAlign, m_bNSnap); } +void UITopBarForm::ClickVSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfVSnap, m_bVSnap); } +void UITopBarForm::ClickASnap() { ExecCommand(COMMAND_SET_SETTINGS, etfASnap, m_bASnap); } +void UITopBarForm::ClickMSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfMSnap, m_bMSnap); } + +void UITopBarForm::ClickCameraP() +{ + EDevice.m_Camera.SetStyle(csPlaneMove); + UI->RedrawScene(); +} +void UITopBarForm::ClickCameraA() +{ + EDevice.m_Camera.SetStyle(cs3DArcBall); + UI->RedrawScene(); +} +void UITopBarForm::ClickCameraF() +{ + EDevice.m_Camera.SetStyle(csFreeFly); + UI->RedrawScene(); +} + +void UITopBarForm::ClickViewB1() +{ + EDevice.m_Camera.ViewBack(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewB2() +{ + EDevice.m_Camera.ViewBottom(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewF() +{ + EDevice.m_Camera.ViewFront(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewL() +{ + EDevice.m_Camera.ViewLeft(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewR() +{ + EDevice.m_Camera.ViewRight(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewT() +{ + EDevice.m_Camera.ViewTop(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewX() +{ + EDevice.m_Camera.ViewReset(); + UI->RedrawScene(); +} diff --git a/src/editors/LevelEditor/UI/UITopBarForm.h b/src/editors/LevelEditor/UI/UITopBarForm.h new file mode 100644 index 00000000000..d03033bf987 --- /dev/null +++ b/src/editors/LevelEditor/UI/UITopBarForm.h @@ -0,0 +1,26 @@ +#pragma once +class UITopBarForm : public xrUI +{ +public: + UITopBarForm(); + virtual ~UITopBarForm(); + virtual void Draw(); + void RefreshBar(); + +private: +#define ADD_BUTTON_IMAGE_T1(Class, Name) void Click##Class##Name(); +#define ADD_BUTTON_IMAGE_T2(Class, Name) void Click##Class##Name(); +#define ADD_BUTTON_IMAGE_S(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + u32 m_time##Name; +#define ADD_BUTTON_IMAGE_D(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + bool m_b##Name; +#define ADD_BUTTON_IMAGE_P(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + bool m_b##Name; +#include "UITopBarForm_ButtonList.h" +}; \ No newline at end of file diff --git a/src/editors/LevelEditor/UI/UITopBarForm_ButtonList.h b/src/editors/LevelEditor/UI/UITopBarForm_ButtonList.h new file mode 100644 index 00000000000..526ba68bbf2 --- /dev/null +++ b/src/editors/LevelEditor/UI/UITopBarForm_ButtonList.h @@ -0,0 +1,50 @@ +#ifndef ADD_BUTTON_IMAGE_P +#define ADD_BUTTON_IMAGE_P(Name) ADD_BUTTON_IMAGE_D(Name) +#endif +#ifndef ADD_BUTTON_IMAGE_T1_1 +#define ADD_BUTTON_IMAGE_T1_1(Class, Name, T) ADD_BUTTON_IMAGE_T1(Class, Name) +#endif +ADD_BUTTON_IMAGE_S(Undo) +ADD_BUTTON_IMAGE_S(Redo) + +ADD_BUTTON_IMAGE_P(Select) +ADD_BUTTON_IMAGE_P(Add) +ADD_BUTTON_IMAGE_P(Move) +ADD_BUTTON_IMAGE_P(Rotate) +ADD_BUTTON_IMAGE_P(Scale) + +ADD_BUTTON_IMAGE_P(X) +ADD_BUTTON_IMAGE_P(Y) +ADD_BUTTON_IMAGE_P(Z) +ADD_BUTTON_IMAGE_P(ZX) + +ADD_BUTTON_IMAGE_D(CsLocal) +ADD_BUTTON_IMAGE_D(NuScale) +ADD_BUTTON_IMAGE_D(GSnap) +ADD_BUTTON_IMAGE_D(OSnap) +ADD_BUTTON_IMAGE_D(MoveToSnap) +ADD_BUTTON_IMAGE_D(NSnap) +ADD_BUTTON_IMAGE_D(VSnap) +ADD_BUTTON_IMAGE_D(ASnap) +ADD_BUTTON_IMAGE_D(MSnap) + +ADD_BUTTON_IMAGE_S(Zoom) +ADD_BUTTON_IMAGE_S(ZoomSel) + +ADD_BUTTON_IMAGE_T1(View, F) +ADD_BUTTON_IMAGE_T1_1(View, B1, B) +ADD_BUTTON_IMAGE_T1(View, L) +ADD_BUTTON_IMAGE_T1(View, R) +ADD_BUTTON_IMAGE_T1(View, T) +ADD_BUTTON_IMAGE_T1_1(View, B2, B) +ADD_BUTTON_IMAGE_T1(View, X) + +ADD_BUTTON_IMAGE_T2(Camera, P) +ADD_BUTTON_IMAGE_T2(Camera, A) +ADD_BUTTON_IMAGE_T2(Camera, F) + +#undef ADD_BUTTON_IMAGE_D +#undef ADD_BUTTON_IMAGE_S +#undef ADD_BUTTON_IMAGE_P +#undef ADD_BUTTON_IMAGE_T1 +#undef ADD_BUTTON_IMAGE_T2 diff --git a/src/editors/LevelEditor/Utils/Cursor3D.cpp b/src/editors/LevelEditor/Utils/Cursor3D.cpp new file mode 100644 index 00000000000..8d3fa137ca9 --- /dev/null +++ b/src/editors/LevelEditor/Utils/Cursor3D.cpp @@ -0,0 +1,164 @@ +#include "stdafx.h" + +static WORD CrossIndices[4] = {0, 2, 1, 3}; + +C3DCursor::C3DCursor() +{ + m_Visible = false; + brush_radius = 1.f; + brush_up_depth = 1.f; + brush_dn_depth = 20.f; + SetBrushSegment(); + eStyle = csLasso; +} + +C3DCursor::~C3DCursor() +{ + m_RenderBuffer.clear(); +} +//--------------------------------------------------------------------------- + +void C3DCursor::SetBrushSegment(float segment) +{ + m_RenderBuffer.resize(static_cast(segment)); + d_angle = PI_MUL_2 / segment; +} +//--------------------------------------------------------------------------- + +void C3DCursor::SetColor(Fcolor &c) +{ + dwColor = c.get(); +} +//--------------------------------------------------------------------------- + +void C3DCursor::GetPickPoint(Fvector &src, Fvector &dst, Fvector *N) +{ + Fvector start; + SRayPickInfo pinf; + start.set(src); + start.y += brush_up_depth; + pinf.inf.range = brush_up_depth + brush_dn_depth; + pinf.pt.set(src); + Fvector pick_dir; + pick_dir.set(0, -1, 0); + if (Scene->RayPickObject(pinf.inf.range, start, pick_dir, OBJCLASS_SCENEOBJECT, &pinf, Scene->GetSnapList(false))) + { + dst.set(pinf.pt); + if (N) + { + Fvector verts[3]; + pinf.e_obj->GetFaceWorld(pinf.s_obj->_Transform(), pinf.e_mesh, pinf.inf.id, verts); + N->mknormal(verts[0], verts[1], verts[2]); + } + } + else + { + dst.set(src); + if (N) + N->set(0, 1, 0); + } +} +//--------------------------------------------------------------------------- + +void C3DCursor::Render() +{ + if (m_Visible && !EDevice.m_Camera.IsMoving()) + { + SRayPickInfo pinf; + Fvector start, dir, N, D; + Ivector2 pt; + // start_pt=UI->GetD3DWindow()->ScreenToClient(start_pt); + pt = MainForm->GetRenderForm()->GetMousePos(); + EDevice.m_Camera.MouseRayFromPoint(start, dir, pt); + if (LUI->PickGround(pinf.pt, start, dir, -1)) + { + N.set(0, 1, 0); + D.set(0, 0, 1); + + switch (eStyle) + { + case csLasso: + { + Fmatrix m_ViewMat; + Fvector at; + at.sub(pinf.pt, N); + m_ViewMat.build_camera(pinf.pt, at, D); + m_ViewMat.invert(); + Fvector p; + float s_a = 0; + for (u32 idx = 0; idx < m_RenderBuffer.size(); s_a += d_angle, idx++) + { + p.set(cosf(s_a) * brush_radius, sinf(s_a) * brush_radius, 0); + m_ViewMat.transform(p); + GetPickPoint(p, m_RenderBuffer[idx], NULL); + } + + // UI->D3D_RenderNearer(0.0001); + RCache.set_xform_world(Fidentity); + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawPrimitiveL(D3DPT_LINESTRIP, m_RenderBuffer.size(), m_RenderBuffer.data(), m_RenderBuffer.size(), dwColor, true, true); + // UI->D3D_ResetNearer(); + } + break; + case csPoint: + { + FVF::TL pt[5]; + pt[0].transform(pinf.pt, EDevice.mFullTransform); + pt[0].color = dwColor; + pt[0].p.x = EDevice._x2real(pt[0].p.x); + pt[0].p.y = EDevice._y2real(pt[0].p.y); + pt[1].set(pt[0].p.x - 1, pt[0].p.y, pt[0].p.z, pt[0].p.w, dwColor, 0, 0); + pt[2].set(pt[0].p.x + 1, pt[0].p.y, pt[0].p.z, pt[0].p.w, dwColor, 0, 0); + pt[3].set(pt[0].p.x, pt[0].p.y - 1, pt[0].p.z, pt[0].p.w, dwColor, 0, 0); + pt[4].set(pt[0].p.x, pt[0].p.y + 1, pt[0].p.z, pt[0].p.w, dwColor, 0, 0); + EDevice.RenderNearer(0.001); + RCache.set_xform_world(Fidentity); + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawPrimitiveTL(D3DPT_POINTLIST, 5, pt, 5, true, true); + EDevice.ResetNearer(); + } + break; + } + } + } +} +//--------------------------------------------------------------------------- + +bool C3DCursor::PrepareBrush() +{ + SRayPickInfo pinf; + bool bPickObject, bPickGround; + Fvector N, D; + POINT start_pt; + Ivector2 pt; + // GetCursorPos(&start_pt); start_pt=UI->GetD3DWindow()->ScreenToClient(start_pt); + pt.set(iFloor((float)start_pt.x), iFloor((float)start_pt.y)); + EDevice.m_Camera.MouseRayFromPoint(brush_start, brush_dir, pt); + bPickObject = !!Scene->RayPickObject(pinf.inf.range, brush_start, brush_dir, OBJCLASS_SCENEOBJECT, &pinf, Scene->GetSnapList(false)); + if (!bPickObject) + bPickGround = LUI->PickGround(pinf.pt, brush_start, brush_dir); + if (bPickObject || bPickGround) + { + N.set(0, 1, 0); + D.set(0, 0, 1); + Fvector at; + at.sub(pinf.pt, N); + brush_mat.build_camera(pinf.pt, at, D); + brush_mat.invert(); + return true; + } + return false; +} +//--------------------------------------------------------------------------- + +void C3DCursor::GetRandomBrushPos(Fvector &pos, Fvector &norm) +{ + Fvector p, start, dir; + SRayPickInfo pinf; + float s_a = Random.randF(PI_MUL_2); + float dist = sqrtf(Random.randF()) * brush_radius; + p.set(cosf(s_a) * dist, sinf(s_a) * dist, 0); + brush_mat.transform(p); + GetPickPoint(p, pos, &norm); +} +//--------------------------------------------------------------------------- diff --git a/src/editors/LevelEditor/Utils/Cursor3D.h b/src/editors/LevelEditor/Utils/Cursor3D.h new file mode 100644 index 00000000000..9658abbcddb --- /dev/null +++ b/src/editors/LevelEditor/Utils/Cursor3D.h @@ -0,0 +1,48 @@ +//--------------------------------------------------------------------------- +#ifndef Cursor3DH +#define Cursor3DH +//--------------------------------------------------------------------------- +#define CURSOR_PRECISION_SEGMENT 16 + +enum ECursorStyle +{ + csLasso, + csPoint +}; + +class C3DCursor +{ + float d_angle; + u32 dwColor; + FvectorVec m_RenderBuffer; + + Fvector brush_start, brush_dir; + Fmatrix brush_mat; + float brush_radius; + float brush_up_depth, brush_dn_depth; + + bool m_Visible; + void GetPickPoint(Fvector &src, Fvector &dst, Fvector *N); + ECursorStyle eStyle; + +public: + C3DCursor(); + virtual ~C3DCursor(); + void SetBrushSegment(float segment = CURSOR_PRECISION_SEGMENT); + void Render(); + bool GetVisible() { return m_Visible; } + + float GetBrushSize() { return brush_radius; } + void SetBrushRadius(float r) { brush_radius = r; } + void SetBrushDepth(float up_d, float dn_d) + { + brush_up_depth = up_d; + brush_dn_depth = dn_d; + } + void SetColor(Fcolor &c); + bool PrepareBrush(); + void GetRandomBrushPos(Fvector &pos, Fvector &norm); + //. void Visible (bool b){m_Visible = b;} + void Style(ECursorStyle st) { eStyle = st; } +}; +#endif diff --git a/src/editors/LevelEditor/Utils/Custom2DProjector.cpp b/src/editors/LevelEditor/Utils/Custom2DProjector.cpp new file mode 100644 index 00000000000..44b0f23cc19 --- /dev/null +++ b/src/editors/LevelEditor/Utils/Custom2DProjector.cpp @@ -0,0 +1,106 @@ +#include "stdafx.h" + +// SBase +#define MAX_BUF_SIZE 0xFFFF + +CCustom2DProjector::CCustom2DProjector() +{ + name = ""; + shader_overlap = 0; + shader_blended = 0; +} + +bool CCustom2DProjector::LoadImage(LPCSTR nm) +{ + name = nm; + ImageLib.LoadTextureData(*name, data, w, h); + return Valid(); +} + +void CCustom2DProjector::CreateRMFromObjects(const Fbox &box, ObjectList &lst) +{ + geom.destroy(); + mesh.clear(); + for (ObjectIt it = lst.begin(); it != lst.end(); it++) + { + CSceneObject *S = (CSceneObject *)(*it); + CEditableObject *O = S->GetReference(); + VERIFY(O); + + Fmatrix T; + S->GetFullTransformToWorld(T); + mesh.reserve(mesh.size() + S->GetFaceCount() * 3); + for (EditMeshIt m_it = O->FirstMesh(); m_it != O->LastMesh(); m_it++) + { + for (u32 f_id = 0; f_id != (*m_it)->GetFCount(); f_id++) + { + FVF::V v; + for (int k = 0; k < 3; k++) + { + T.transform_tiny(v.p, (*m_it)->GetVertices()[(*m_it)->GetFaces()[f_id].pv[k].pindex]); + v.t.x = GetUFromX(v.p.x, box); + v.t.y = GetVFromZ(v.p.z, box); + mesh.push_back(v); + } + } + } + } + geom.create(FVF::F_V, RImplementation.Vertex.Buffer(), 0); +} + +void CCustom2DProjector::Render(bool blended) +{ + if (!Valid()) + return; + EDevice.RenderNearer(0.001f); + RCache.set_xform_world(Fidentity); + EDevice.SetShader(blended ? shader_blended : shader_overlap); + div_t cnt = div(mesh.size(), MAX_BUF_SIZE); + u32 vBase; + _VertexStream* Stream = &RImplementation.Vertex; + for (int k = 0; k < cnt.quot; k++) + { + FVF::V *pv = (FVF::V *)Stream->Lock(MAX_BUF_SIZE, geom->vb_stride, vBase); + CopyMemory(pv, mesh.data() + k * MAX_BUF_SIZE, sizeof(FVF::V) * MAX_BUF_SIZE); + Stream->Unlock(MAX_BUF_SIZE, geom->vb_stride); + EDevice.DP(D3DPT_TRIANGLELIST, geom, vBase, MAX_BUF_SIZE / 3); + } + if (cnt.rem) + { + FVF::V *pv = (FVF::V *)Stream->Lock(cnt.rem, geom->vb_stride, vBase); + CopyMemory(pv, mesh.data() + cnt.quot * MAX_BUF_SIZE, sizeof(FVF::V) * cnt.rem); + Stream->Unlock(cnt.rem, geom->vb_stride); + EDevice.DP(D3DPT_TRIANGLELIST, geom, vBase, cnt.rem / 3); + } + EDevice.ResetNearer(); +} + +void CCustom2DProjector::CreateShader() +{ + DestroyShader(); + if (Valid()) + { + shader_blended.create("editor\\do_base", *name); + shader_overlap.create("default", *name); + geom.create(FVF::F_V, RImplementation.Vertex.Buffer(), 0); + } +} + +void CCustom2DProjector::DestroyShader() +{ + geom.destroy(); + shader_blended.destroy(); + shader_overlap.destroy(); +} + +void CCustom2DProjector::OnImageChange(PropValue *prop) +{ + LoadImage(*name); + DestroyShader(); + CreateShader(); +} + +void CCustom2DProjector::ReloadImage() +{ + LoadImage(*name); +} diff --git a/src/editors/LevelEditor/Utils/Custom2DProjector.h b/src/editors/LevelEditor/Utils/Custom2DProjector.h new file mode 100644 index 00000000000..b297a7ca0c2 --- /dev/null +++ b/src/editors/LevelEditor/Utils/Custom2DProjector.h @@ -0,0 +1,74 @@ +#pragma once + +class CCustom2DProjector +{ +protected: + ref_shader shader_blended; + ref_shader shader_overlap; + u32 w; + u32 h; + U32Vec data; + DEFINE_VECTOR(FVF::V, TVertVec, TVertIt); + TVertVec mesh; + ref_geom geom; + +public: + void OnImageChange(PropValue *prop); + +public: + shared_str name; + +public: + CCustom2DProjector(); + IC bool Valid() { return (w > 0) && (h > 0) && (!!data.size()); } + IC void Clear() + { + name = ""; + w = 0; + h = 0; + geom = 0; + data.clear(); + mesh.clear(); + DestroyShader(); + } + bool LoadImage(LPCSTR nm); + void ReloadImage(); + void CreateRMFromObjects(const Fbox &box, ObjectList &lst); + void Render(bool blended); + void CreateShader(); + void DestroyShader(); + IC LPCSTR GetName() { return *name; } + IC bool GetColor(u32 &color, int U, int V) + { + if (Valid() && (U < (int)w) && (V < (int)h)) + { + color = data[V * w + U]; + return true; + } + return false; + } + IC float GetUFromX(float x, const Fbox &box) + { + R_ASSERT(Valid()); + return (x - box.vMin.x) / (box.vMax.x - box.vMin.x); + } + IC int GetPixelUFromX(float x, const Fbox &box) + { + int U = iFloor(GetUFromX(x, box) * (w - 1) + 0.5f); + if (U < 0) + U = 0; + return U; + } + IC float GetVFromZ(float z, const Fbox &box) + { + R_ASSERT(Valid()); + return 1.f - (z - box.vMin.z) / (box.vMax.z - box.vMin.z); + } + IC int GetPixelVFromZ(float z, const Fbox &box) + { + int V = iFloor(GetVFromZ(z, box) * (h - 1) + 0.5f); + if (V < 0) + V = 0; + return V; + } +}; diff --git a/src/editors/LevelEditor/Utils/FS2.cpp b/src/editors/LevelEditor/Utils/FS2.cpp new file mode 100644 index 00000000000..49e603ba9ee --- /dev/null +++ b/src/editors/LevelEditor/Utils/FS2.cpp @@ -0,0 +1,27 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "FS2.h" + +// memory +CMemoryStream::~CMemoryStream() +{ + xr_free(data); +} + +void CMemoryStream::write(const void *ptr, u32 count) +{ + if (position + count > mem_size) + { + // reallocate + if (mem_size == 0) + mem_size = 128; + while (mem_size <= (position + count)) + mem_size *= 2; + data = (u8 *)xr_realloc(data, mem_size); + } + CopyMemory(data + position, ptr, count); + position += count; + if (position > file_size) + file_size = position; +} diff --git a/src/editors/LevelEditor/Utils/FS2.h b/src/editors/LevelEditor/Utils/FS2.h new file mode 100644 index 00000000000..3dcf6886198 --- /dev/null +++ b/src/editors/LevelEditor/Utils/FS2.h @@ -0,0 +1,358 @@ +#pragma once +#include +#include +#include "lwchunks.h" + +class IBasicStream +{ +private: + std::stack chunk_pos; + std::stack subchunk_pos; + + void revbytes(void *bp, int elsize, int elcount) + { + register unsigned char *p, *q; + + p = (unsigned char *)bp; + + if (elsize == 2) + { + q = p + 1; + while (elcount--) + { + *p ^= *q; + *q ^= *p; + *p ^= *q; + p += 2; + q += 2; + } + return; + } + + while (elcount--) + { + q = p + elsize - 1; + while (p < q) + { + *p ^= *q; + *q ^= *p; + *p ^= *q; + ++p; + --q; + } + p += elsize >> 1; + } + } + +public: + virtual ~IBasicStream() + { + R_ASSERT(subchunk_pos.empty()); + while (!chunk_pos.empty()) + close_chunk(); + } + + // kernel + virtual void write(const void *ptr, u32 count) = 0; + virtual void seek(u32 pos) = 0; + virtual u32 tell() = 0; + + // generalized writing functions + IC void w_u32(u32 d) + { + revbytes(&d, 4, 1); + write(&d, sizeof(u32)); + } + + IC void w_u16(u16 d) + { + revbytes(&d, 2, 1); + write(&d, sizeof(u16)); + } + + IC void w_float(float d) + { + revbytes(&d, 4, 1); + write(&d, sizeof(float)); + } + + IC void w_u8(u8 d) { write(&d, sizeof(u8)); } + + IC void w_string(const char *p) + { + write(p, xr_strlen(p)); + w_u8(13); + w_u8(10); + } + + IC void w_stringZ(const char *p) + { + write(p, xr_strlen(p) + 1); + if (!(xr_strlen(p) & 1)) + w_u8(0); + } + + IC void w_vector(Fvector v) + { + revbytes(&v, 4, 3); + write(&v, 3 * sizeof(float)); + } + + IC void w_color(Fcolor c) + { + revbytes(&c, 4, 4); + write(&c, 4 * sizeof(float)); + } + + // generalized chunking + IC void open_chunk(u32 type) + { + w_u32(type); + chunk_pos.push(tell()); + w_u32(0); // the place for 'size' + } + + IC void close_chunk() + { + VERIFY(!chunk_pos.empty()); + + int pos = tell(); + seek(chunk_pos.top()); + w_u32(pos - chunk_pos.top() - 4); + seek(pos); + chunk_pos.pop(); + } + + // generalized chunking + IC void open_subchunk(u32 type) + { + w_u32(type); + subchunk_pos.push((u16)tell()); + w_u16(0); // the place for 'size' + } + + IC void close_subchunk() + { + VERIFY(!subchunk_pos.empty()); + + int pos = tell(); + seek(subchunk_pos.top()); + w_u16(u16(pos - subchunk_pos.top() - 2)); + seek(pos); + subchunk_pos.pop(); + } + + IC void write_chunk(u32 type, void *data, u32 size) + { + open_chunk(type); + write(data, size); + close_chunk(); + } +}; + +class CMemoryStream : public IBasicStream +{ + u8 *data; + u32 position; + u32 mem_size; + u32 file_size; + +public: + CMemoryStream() + { + data = 0; + position = 0; + mem_size = 0; + file_size = 0; + } + + virtual ~CMemoryStream(); + + // kernel + virtual void write(const void *ptr, u32 count); + + virtual void seek(u32 pos) + { + position = pos; + } + + virtual u32 tell() + { + return position; + } + + // specific + u8 *pointer() { return data; } + u32 size() { return file_size; } + + void clear() + { + file_size = 0; + position = 0; + } + + void SaveTo(const char *fn) + { +#ifdef M_BORLAND + int H = open(fn, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IREAD | S_IWRITE); +#else + int H = _open(fn, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IREAD | S_IWRITE); +#endif + R_ASSERT(H > 0); + _write(H, pointer(), size()); + _close(H); + } +}; + + + +class CLWMemoryStream : public CMemoryStream +{ + IC void make_ord(int nbloks, int index, unsigned char *ord) + { + int i, d; + + for (i = 8, d = 16; i < 128; i *= 2) + { + if (i >= nbloks) + break; + d /= 2; + } + ord[0] = u8(128 + index * d); + ord[1] = 0; + } + +public: + IC void begin_save() + { + open_chunk(ID_FORM); + w_u32(ID_LWO2); + } + + IC void end_save(LPCSTR name) + { + close_chunk(); + SaveTo(name); + } + + IC void w_layer(u16 number, LPCSTR name) + { + open_chunk(ID_LAYR); + w_u16(number); // num + w_u16(0); + w_float(0); // pivot + w_float(0); + w_float(0); + w_stringZ(name); + close_chunk(); + } + + IC void w_vx(int idx) + { + if (idx >= 0xFF00) + { + idx |= 0xff000000; + w_u32(idx); + } + else + w_u16((u16)idx); + } + + IC void w_face3(int i0, int i1, int i2) + { + w_u16(3); + w_vx(i0); + w_vx(i1); + w_vx(i2); + } + + IC void begin_vmap(BOOL polymap, u32 type, int dim, LPCSTR name) + { + open_chunk(polymap ? ID_VMAD : ID_VMAP); + w_u32(type); + w_u16((u16)dim); + R_ASSERT2(name && name[0], "Empty vmap name!"); + w_stringZ(name); + } + IC void end_vmap() + { + close_chunk(); + } + + IC void w_vmap(int v_index, int dim, float *uv) + { + w_vx(v_index); + w_float(uv[0]); + if (dim == 2) + w_float(1.f - uv[1]); + } + + IC void w_vmad(int v_index, int f_index, int dim, float *uv) + { + w_vx(v_index); + w_vx(f_index); + w_float(uv[0]); + if (dim == 2) + w_float(1.f - uv[1]); + } + + IC void Wsurface(LPCSTR name, BOOL b2Sided, u16 image, LPCSTR vmap, LPCSTR sh_eng, LPCSTR sh_comp) + { + // surf screen + char ord[2]; + open_chunk(ID_SURF); + w_stringZ(name); + w_stringZ(""); + open_subchunk(ID_COLR); + w_float(1.f); + w_float(1.f); + w_float(1.f); + w_u16(0); + close_subchunk(); + open_subchunk(ID_SIDE); + w_u16(u16(b2Sided ? 3 : 1)); + close_subchunk(); + open_subchunk(ID_BLOK); + open_subchunk(ID_IMAP); + make_ord(128, 0, (u8 *)ord); + w_stringZ(ord); + open_subchunk(ID_CHAN); + w_u32(ID_COLR); + close_subchunk(); + open_subchunk(ID_OPAC); + w_u16(0); + w_float(1.f); + w_u16(0); + close_subchunk(); + open_subchunk(ID_ENAB); + w_u16(1); + close_subchunk(); + close_subchunk(); + open_subchunk(ID_PROJ); + w_u16(5); + close_subchunk(); + open_subchunk(ID_IMAG); + w_u16(image); + close_subchunk(); + open_subchunk(ID_VMAP); + w_stringZ(vmap); + close_subchunk(); + open_subchunk(ID_AAST); + w_u16(1); + w_float(1.f); + close_subchunk(); + open_subchunk(ID_PIXB); + w_u16(1); + close_subchunk(); + open_subchunk(ID_STCK); + w_float(0.f); + w_u16(0); + close_subchunk(); + open_subchunk(ID_TAMP); + w_float(1.f); + w_u16(0); + close_subchunk(); + close_subchunk(); + close_chunk(); + } +}; diff --git a/src/editors/LevelEditor/Utils/GeometryPartExtractor.cpp b/src/editors/LevelEditor/Utils/GeometryPartExtractor.cpp new file mode 100644 index 00000000000..d8f41d43b46 --- /dev/null +++ b/src/editors/LevelEditor/Utils/GeometryPartExtractor.cpp @@ -0,0 +1,488 @@ +#include "stdafx.h" + +// Parts +void SBPart::append_face(SBFace *F) +{ + m_Faces.push_back(F); +} + +void SBPart::use_face(SBFace *F, u32 &cnt, u32 bone_id, float &area) +{ + VERIFY(F->bone_id == -1); + F->marked = true; + F->bone_id = bone_id; + area += F->CalcArea(); + cnt++; +} + +void SBPart::recurse_fragment(SBFace *F, u32 &cnt, u32 bone_id, u32 max_faces, float &area) +{ + if (F) + { + if (!F->marked) + use_face(F, cnt, bone_id, area); + // fill nearest + SBFaceVec r_vec; + for (SBFaceVecIt n_it = F->adjs.begin(); n_it != F->adjs.end(); n_it++) + { + if (cnt >= max_faces) + break; + if ((*n_it)->marked) + continue; + use_face(*n_it, cnt, bone_id, area); + r_vec.push_back(*n_it); + } + // recurse adjs + for (SBFaceVecIt a_it = r_vec.begin(); a_it != r_vec.end(); a_it++) + { + if (cnt >= max_faces) + break; + if ((*a_it)->bone_id != (int)bone_id) + continue; + recurse_fragment(*a_it, cnt, bone_id, max_faces, area); + } + } +} + +bool SBPart::prepare(SBAdjVec &adjs, u32 bone_face_min) +{ + m_bValid = true; + // compute OBB + FvectorVec pts; + pts.reserve(m_Faces.size() * 3); + for (SBFaceVecIt f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + { + (*f_it)->marked = false; + for (int k = 0; k < 3; k++) + pts.push_back((*f_it)->o[k]); + } + ComputeOBB_RAPID(m_OBB, pts, pts.size() / 3); + // fill adjacent + for (SBFaceVecIt a_it = m_Faces.begin(); a_it != m_Faces.end(); a_it++) + { + SBFace *A = *a_it; + for (int k = 0; k < 3; k++) + { + SBFaceVec &b_vec = adjs[A->vert_id[k]]; + for (SBFaceVecIt b_it = b_vec.begin(); b_it != b_vec.end(); b_it++) + { + SBFace *B = *b_it; + if (A != B) + { + int cnt = 0; + for (int a = 0; a < 3; a++) + for (int b = 0; b < 3; b++) + if (A->vert_id[a] == B->vert_id[b]) + cnt++; + if (cnt >= 2) + { + if (std::find(A->adjs.begin(), A->adjs.end(), B) == A->adjs.end()) + A->adjs.push_back(B); + if (std::find(B->adjs.begin(), B->adjs.end(), A) == B->adjs.end()) + B->adjs.push_back(A); + } + } + } + } + } + // prepare transform matrix + m_BBox.invalidate(); + Fmatrix M; + M.set(m_OBB.m_rotate.i, m_OBB.m_rotate.j, m_OBB.m_rotate.k, m_OBB.m_translate); + m_RefOffset.set(m_OBB.m_translate); + M.getXYZ(m_RefRotate); // не i потому что в движке так + M.invert(); + + // transform vertices & calculate bounding box + for (auto f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + { + SBFace *F = (*f_it); + if (F->adjs.empty()) + { + ELog.Msg(mtError, "Error face found at pos: [%3.2f,%3.2f,%3.2f]", VPUSH(F->o[0])); + Tools->m_DebugDraw.AppendWireFace(F->o[0], F->o[1], F->o[2]); + m_bValid = false; + } + for (int k = 0; k < 3; k++) + { + M.transform_dir(F->n[k]); + M.transform_tiny(F->o[k]); + m_BBox.modify(F->o[k]); + } + } + if (m_bValid) + { + // calculate bone params + int bone_cnt_calc = iFloor(float(m_Faces.size()) / bone_face_min); + int bone_cnt_max = (bone_cnt_calc < 62) ? (bone_cnt_calc <= 0 ? 1 : bone_cnt_calc) : 62; + int bone_face_max = iFloor(float(m_Faces.size()) / bone_cnt_max + 0.5f); + bone_face_max *= 4; + int bone_idx = 0; + // create big fragment + u32 face_accum_total = 0; + xr_string parent_bone = ""; + do + { + SBFace *F = 0; + // find unused face + for (SBFaceVecIt f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + { + if (!(*f_it)->marked) + { + F = *f_it; + int cnt = 0; + for (SBFaceVecIt a_it = F->adjs.begin(); a_it != F->adjs.end(); a_it++) + cnt += (*a_it)->marked ? 0 : 1; + if ((cnt == 0) || (cnt >= 2)) + break; + } + } + if (!F) + break; + float area = 0; + u32 face_accum = 0; + u32 face_max_count = Random.randI(bone_face_min, bone_face_max + 1); + // fill faces + recurse_fragment(F, face_accum, bone_idx, face_max_count, area); + if (face_accum == 1) + { + // F->marked = false; + F->bone_id = -1; + } + else + { + m_Bones.push_back( + SBBone(std::to_string(bone_idx).c_str(), parent_bone, F->surf->_GameMtlName(), face_accum, area)); + parent_bone = "0"; + bone_idx++; + face_accum_total += face_accum; + } + // create bone + } while (bone_idx < bone_cnt_max); + + // attach small single face to big fragment + u32 face_accum_total_saved = face_accum_total; + while (face_accum_total < m_Faces.size()) + { + if (face_accum_total_saved != face_accum_total) + { + face_accum_total_saved = face_accum_total; + } + else + { + // если проход оказался безрезультатным (т.е. не смогли добавить хоть один фейс) - добавляем + // все неприаттаченные фейсы к 0-кости (иначе зацикливается (mike - L03_agroprom)) + for (SBFaceVecIt f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + { + SBFace *F = *f_it; + if (-1 == F->bone_id) + { + F->marked = true; + F->bone_id = 0; + face_accum_total++; + } + } + } + for (SBFaceVecIt f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + { + SBFace *F = *f_it; + if (-1 == F->bone_id) + { + SBFace *P = 0; + if (F->adjs.empty()) + { + F->marked = true; + F->bone_id = 0; + face_accum_total++; + } + else + { + for (SBFaceVecIt a_it = F->adjs.begin(); a_it != F->adjs.end(); a_it++) + { + if (-1 != (*a_it)->bone_id) + { + P = *a_it; + break; + } + } + } + if (P) + { + VERIFY(-1 != P->bone_id); + F->marked = true; + F->bone_id = P->bone_id; + face_accum_total++; + } + } + } + } + + // calculate bone offset + for (auto f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + { + SBFace *F = *f_it; + VERIFY(F->bone_id != -1); + SBBone &B = m_Bones[F->bone_id]; + for (int k = 0; k < 3; k++) + B.offset.add(F->o[k]); + } + for (SBBoneVecIt b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + { + SBBone &B = *b_it; + VERIFY(0 != B.f_cnt); + B.offset.div(static_cast(B.f_cnt * 3)); + } + Fvector &offs = m_Bones.front().offset; + for (SBBoneVecIt b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + b_it->offset.sub(offs); + } + return m_bValid; +} + +bool SBPart::Export(IWriter &F, u8 infl) +{ + VERIFY(!m_Bones.empty()); + if (m_Bones.size() > 63) + { + ELog.Msg(mtError, "Breakable object cannot handle more than 63 parts."); + return false; + } + + bool bRes = true; + + u32 bone_count = m_Bones.size(); + + xr_vector bone_points; + bone_points.resize(bone_count); + + u32 mtl_cnt = 0; + + for (SBFaceVecIt pf_it = m_Faces.begin(); pf_it != m_Faces.end(); pf_it++) + { + SBFace *face = *pf_it; + int mtl_idx = FindSplit(face->surf->_ShaderName(), face->surf->_Texture(), 0); + if (mtl_idx < 0) + { + m_Splits.push_back(SSplit(face->surf, m_BBox, 0)); + mtl_idx = mtl_cnt++; + } + SSplit &split = m_Splits[mtl_idx]; + SSkelVert v[3]; + for (int k = 0; k < 3; k++) + { + st_SVert::bone b[1]; + b[0].id = face->bone_id; + b[0].w = 1.f; + v[k].set(face->o[k], face->n[k], face->uv[k], 1, b); + } + split.add_face(v[0], v[1], v[2]); + + if (face->surf->m_Flags.is(CSurface::sf2Sided)) + { + v[0].norm.invert(); + v[1].norm.invert(); + v[2].norm.invert(); + if (!split.add_face(v[0], v[2], v[1])) + split.invalid_faces++; + } + } + + // fill per bone vertices + for (SplitIt split_it = m_Splits.begin(); split_it != m_Splits.end(); split_it++) + { + if (!split_it->valid()) + { + ELog.Msg(mtError, "Degenerate part found (Texture '%s').", *split_it->m_Texture); + bRes = false; + break; + } + if (0 != split_it->invalid_faces) + { + ELog.Msg(mtError, "Part [texture '%s'] have %d duplicate(degenerate) face(s).", *split_it->m_Texture, split_it->invalid_faces); + } + // calculate T&B components + split_it->CalculateTB(); + // subtract offset + SkelVertVec &lst = split_it->getV_Verts(); + for (SkelVertIt sv_it = lst.begin(); sv_it != lst.end(); sv_it++) + { + bone_points[sv_it->bones[0].id].push_back(sv_it->offs); + bone_points[sv_it->bones[0].id].back().sub(m_Bones[sv_it->bones[0].id].offset); + } + } + + if (!bRes) + return false; + + // compute bounding + ComputeBounding(); + + // create OGF + // Header + ogf_header H; + H.format_version = xrOGF_FormatVersion; + H.type = MT_SKELETON_RIGID; + H.shader_id = 0; + H.bb.min = m_Box.vMin; + H.bb.max = m_Box.vMax; + m_Box.getsphere(H.bs.c, H.bs.r); + F.w_chunk(OGF_HEADER, &H, sizeof(H)); + + // Desc + ogf_desc desc; + F.open_chunk(OGF_S_DESC); + desc.Save(F); + F.close_chunk(); + + // OGF_CHILDREN + F.open_chunk(OGF_CHILDREN); + int chield = 0; + for (auto split_it = m_Splits.begin(); split_it != m_Splits.end(); split_it++) + { + F.open_chunk(chield++); + split_it->Save(F); + F.close_chunk(); + } + F.close_chunk(); + + // BoneNames + F.open_chunk(OGF_S_BONE_NAMES); + F.w_u32(bone_count); + // write other bones + for (u32 bone_idx = 0; bone_idx < bone_count; bone_idx++) + { + SBBone &bone = m_Bones[bone_idx]; + F.w_stringZ(bone.name.c_str()); + F.w_stringZ(bone.parent.c_str()); + Fobb obb; + ComputeOBB_WML(obb, bone_points[bone_idx]); + F.w(&obb, sizeof(Fobb)); + } + F.close_chunk(); + + F.open_chunk(OGF_S_IKDATA); + for (u32 bone_idx = 0; bone_idx < bone_count; bone_idx++) + { + SBBone &bone = m_Bones[bone_idx]; + + F.w_u32(0x0001); + VERIFY(0x0001 == OGF_IKDATA_VERSION); + // material + F.w_stringZ(bone.mtl.c_str()); + // shape + SBoneShape shape; + shape.type = SBoneShape::stBox; + shape.flags.assign(SBoneShape::sfRemoveAfterBreak); + ComputeOBB_WML(shape.box, bone_points[bone_idx]); + F.w(&shape, sizeof(SBoneShape)); + // IK data + SJointIKData ik_data; + ik_data.Reset(); + ik_data.type = jtNone; + ik_data.ik_flags.set(SJointIKData::flBreakable, TRUE); + ik_data.Export(F); + + Fvector rot = {0, 0, 0}; + F.w_fvector3(rot); + F.w_fvector3(bone.offset); + F.w_float(bone.area); // mass (для Кости посчитал площадь) + F.w_fvector3(shape.box.m_translate); // center of mass + } + F.close_chunk(); + + return bRes; +} + +// Extractor +IC void recurse_tri(SBPart *P, SBFaceVec &faces, SBAdjVec &adjs, SBFace *F) +{ + if (F->marked) + return; + + P->append_face(F); + F->marked = true; + + // recurse + for (int k = 0; k < 3; k++) + { + SBFaceVec &PL = adjs[F->vert_id[k]]; + for (SBFaceVecIt pl_it = PL.begin(); pl_it != PL.end(); pl_it++) + recurse_tri(P, faces, adjs, *pl_it); + } +} + +void CGeomPartExtractor::AppendFace(CSurface *surf, const Fvector *v, const Fvector *n, const Fvector2 *uvs[3]) +{ + SBFace *F = xr_new(surf, uvs); + // insert verts + for (int k = 0; k < 3; k++) + { + F->vert_id[k] = m_Verts->add_vert(v[k]); + F->o[k].set(v[k]); + F->n[k].set(n[k]); + } + m_Faces.push_back(F); +} + +CGeomPartExtractor::CGeomPartExtractor() +{ + m_Verts = 0; +} + +void CGeomPartExtractor::Initialize(const Fbox &bb, float eps, u32 per_bone_face_count_min) +{ + VERIFY(0 == m_Verts); + m_Verts = xr_new(bb, eps); + m_PerBoneFaceCountMin = per_bone_face_count_min; + VERIFY(m_PerBoneFaceCountMin > 0); +} + +void CGeomPartExtractor::Clear() +{ + xr_delete(m_Verts); + for (SBFaceVecIt f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + xr_delete(*f_it); + m_Faces.clear(); + for (SBPartVecIt p_it = m_Parts.begin(); p_it != m_Parts.end(); p_it++) + xr_delete(*p_it); + m_Parts.clear(); + m_Adjs.clear(); +} + +BOOL CGeomPartExtractor::Process() +{ + // make adjacement + { + m_Adjs.resize(m_Verts->getVS()); + for (SBFaceVecIt f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + for (int k = 0; k < 3; k++) + m_Adjs[(*f_it)->vert_id[k]].push_back(*f_it); + } + // extract parts + { + SPBItem *pb = UI->ProgressStart(static_cast(m_Faces.size()), "Extract Parts..."); + for (SBFaceVecIt f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + { + pb->Inc(); + SBFace *F = *f_it; + if (!F->marked) + { + SBPart *P = xr_new(); + recurse_tri(P, m_Faces, m_Adjs, *f_it); + m_Parts.push_back(P); + } + } + UI->ProgressEnd(pb); + } + // simplify parts + { + SPBItem *pb = UI->ProgressStart(static_cast(m_Parts.size()), "Simplify Parts..."); + for (SBPartVecIt p_it = m_Parts.begin(); p_it != m_Parts.end(); p_it++) + { + pb->Inc(); + (*p_it)->prepare(m_Adjs, m_PerBoneFaceCountMin); + } + UI->ProgressEnd(pb); + } + return TRUE; +} diff --git a/src/editors/LevelEditor/Utils/GeometryPartExtractor.h b/src/editors/LevelEditor/Utils/GeometryPartExtractor.h new file mode 100644 index 00000000000..71e48f228d0 --- /dev/null +++ b/src/editors/LevelEditor/Utils/GeometryPartExtractor.h @@ -0,0 +1,113 @@ +#pragma once + +struct SBFace; +class CSurface; +DEFINE_VECTOR(SBFace *, SBFaceVec, SBFaceVecIt); + +struct SBFace +{ + // internal + int vert_id[3]; + bool marked; + SBFaceVec adjs; + // geom + Fvector o[3]; + Fvector n[3]; + Fvector2 uv[3]; + int bone_id; + CSurface *surf; + +public: + SBFace(CSurface *_surf, const Fvector2 *_uv[3]) : surf(_surf), marked(false), bone_id(-1) + { + vert_id[0] = -1; + vert_id[1] = -1; + vert_id[2] = -1; + uv[0] = *_uv[0]; + uv[1] = *_uv[1]; + uv[2] = *_uv[2]; + n[0].set(0, 0, 0); + n[1].set(0, 0, 0); + n[2].set(0, 0, 0); + } + float CalcArea() + { + Fvector V0, V1; + V0.sub(o[1], o[0]); + V1.sub(o[2], o[0]); + float sqm0 = V0.square_magnitude(); + float sqm1 = V1.square_magnitude(); + return 0.5f * _sqrt(sqm0 * sqm1 - _sqr(V0.dotproduct(V1))); + } +}; + +struct SBBone +{ + xr_string mtl; + xr_string name; + xr_string parent; + Fvector offset; + u32 f_cnt; + float area; + SBBone(xr_string _nm, xr_string _parent, xr_string _mtl, u32 _f_cnt, float _area) + : name(_nm), parent(_parent), mtl(_mtl), f_cnt(_f_cnt), area(_area) + { + offset.set(0, 0, 0); + } +}; +DEFINE_VECTOR(SBBone, SBBoneVec, SBBoneVecIt); +DEFINE_VECTOR(SBFaceVec, SBAdjVec, SBAdjVecIt); + +struct SBPart : public CExportSkeletonCustom +{ + SBFaceVec m_Faces; + SBBoneVec m_Bones; + + Fbox m_BBox; + Fobb m_OBB; + + SBPart *m_Reference; + + Fvector m_RefOffset; + Fvector m_RefRotate; + + bool m_bValid; + +public: + SBPart() + { + m_Reference = 0; + m_bValid = true; + } + bool Valid() { return m_bValid; } + virtual bool Export(IWriter &F, u8 infl); + void append_face(SBFace *F); + void use_face(SBFace *F, u32 &cnt, u32 bone_id, float &area); + void recurse_fragment(SBFace *F, u32 &cnt, u32 bone_id, u32 max_faces, float &area); + bool prepare(SBAdjVec &adjs, u32 bone_face_min); +}; +DEFINE_VECTOR(SBPart *, SBPartVec, SBPartVecIt); +//---------------------------------------------------- + +class CGeomPartExtractor +{ +protected: + VCPacked *m_Verts; + SBFaceVec m_Faces; + SBAdjVec m_Adjs; + SBPartVec m_Parts; + + u32 m_PerBoneFaceCountMin; + +public: + CGeomPartExtractor(); + ~CGeomPartExtractor() { Clear(); } + // init & clean up + void Initialize(const Fbox &bb, float eps, u32 per_bone_face_count_min); + void Clear(); + // I/O routines + void AppendFace(CSurface *surf, const Fvector *v, const Fvector *n, const Fvector2 *uvs[3]); + SBPartVec &GetParts() { return m_Parts; } + // utilities + BOOL Process(); +}; diff --git a/src/editors/LevelEditor/Utils/LevelPreferences.cpp b/src/editors/LevelEditor/Utils/LevelPreferences.cpp new file mode 100644 index 00000000000..e02719b1467 --- /dev/null +++ b/src/editors/LevelEditor/Utils/LevelPreferences.cpp @@ -0,0 +1,64 @@ +#include "stdafx.h" + +void CLevelPreferences::Load(CInifile *I) +{ + inherited::Load(I); + { + OpenObjectList = R_BOOL_SAFE("windows", "object_list", false); + } + { + OpenProperties = R_BOOL_SAFE("windows", "properties", true); + } + SceneToolsMapPairIt _I = Scene->FirstTool(); + SceneToolsMapPairIt _E = Scene->LastTool(); + + for (; _I != _E; _I++) + if (_I->second && (_I->first != OBJCLASS_DUMMY)) + _I->second->m_EditFlags.flags = R_U32_SAFE("targets", _I->second->ClassName(), _I->second->m_EditFlags.flags); +} + +void CLevelPreferences::Save(CInifile *I) +{ + inherited::Save(I); + I->w_bool("windows", "object_list", OpenObjectList); + I->w_bool("windows", "properties", OpenProperties); + SceneToolsMapPairIt _I = Scene->FirstTool(); + SceneToolsMapPairIt _E = Scene->LastTool(); + for (; _I != _E; _I++) + if (_I->second && (_I->first != OBJCLASS_DUMMY)) + I->w_u32("targets", _I->second->ClassName(), _I->second->m_EditFlags.get()); +} + +void CLevelPreferences::OnEnabledChange(PropValue *prop) +{ + ESceneToolBase *M = Scene->GetTool(prop->tag); + VERIFY(M); + ExecCommand(COMMAND_ENABLE_TARGET, prop->tag, M->IsEnabled()); +} + +void CLevelPreferences::OnReadonlyChange(PropValue *prop) +{ + ESceneToolBase *M = Scene->GetTool(prop->tag); + VERIFY(M); + ExecCommand(COMMAND_READONLY_TARGET, prop->tag, M->IsForceReadonly()); +} + +void CLevelPreferences::FillProp(PropItemVec &items) +{ + inherited::FillProp(items); + SceneToolsMapPairIt _I = Scene->FirstTool(); + SceneToolsMapPairIt _E = Scene->LastTool(); + for (; _I != _E; _I++) + if (_I->second && (_I->first != OBJCLASS_DUMMY)) + { + if (_I->second->AllowEnabling()) + { + PropValue *V = PHelper().CreateFlag32(items, PrepareKey("Scene\\Targets\\Enable", _I->second->ClassDesc()), &_I->second->m_EditFlags, ESceneToolBase::flEnable); + V->tag = _I->second->FClassID; + V->OnChangeEvent.bind(this, &CLevelPreferences::OnEnabledChange); + } + PropValue *V = PHelper().CreateFlag32(items, PrepareKey("Scene\\Targets\\Read Only", _I->second->ClassDesc()), &_I->second->m_EditFlags, ESceneToolBase::flForceReadonly); + V->tag = _I->second->FClassID; + V->OnChangeEvent.bind(this, &CLevelPreferences::OnReadonlyChange); + } +} diff --git a/src/editors/LevelEditor/Utils/LevelPreferences.h b/src/editors/LevelEditor/Utils/LevelPreferences.h new file mode 100644 index 00000000000..94d2a07d0c3 --- /dev/null +++ b/src/editors/LevelEditor/Utils/LevelPreferences.h @@ -0,0 +1,23 @@ +//--------------------------------------------------------------------------- +#ifndef LevelPreferencesH +#define LevelPreferencesH + +#include "../xrECore/Editor/EditorPreferences.h" + +class CLevelPreferences : public CCustomPreferences +{ + typedef CCustomPreferences inherited; + void OnEnabledChange(PropValue *prop); + void OnReadonlyChange(PropValue *prop); + +protected: + virtual void Load(CInifile *); + virtual void Save(CInifile *); + +public: + virtual void FillProp(PropItemVec &items); + bool OpenObjectList; + bool OpenProperties; +}; +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/LevelEditor/Utils/SoundManager_LE.cpp b/src/editors/LevelEditor/Utils/SoundManager_LE.cpp new file mode 100644 index 00000000000..7ab5d9d355c --- /dev/null +++ b/src/editors/LevelEditor/Utils/SoundManager_LE.cpp @@ -0,0 +1,125 @@ +#include "stdafx.h" + +CLevelSoundManager *LSndLib = (CLevelSoundManager *)SndLib; + +bool CLevelSoundManager::Validate() +{ + ObjectList &snd_envs = Scene->ListObj(OBJCLASS_SOUND_ENV); + for (ObjectIt it = snd_envs.begin(); it != snd_envs.end(); it++) + { + ESoundEnvironment *E = dynamic_cast(*it); + R_ASSERT(E); + if (E->m_EnvInner == E->m_EnvOuter) + { + ELog.DlgMsg(mtError, "SoundEnvironment: '%s' inner and outer environment must be different.", E->GetName()); + return false; + } + } + ObjectList &snd_src = Scene->ListObj(OBJCLASS_SOUND_SRC); + for (ObjectIt it = snd_src.begin(); it != snd_src.end(); it++) + { + ESoundSource *S = dynamic_cast(*it); + R_ASSERT(S); + if (!S->GetSourceWAV() || (0 == strlen(S->GetSourceWAV()))) + { + ELog.DlgMsg(mtError, "SoundSource: '%s' hasn't wave.", S->GetName()); + return false; + } + } + return true; +} +/* +void CLevelSoundManager::RealRefreshEnvGeometry() +{ + CMemoryWriter F; + if (MakeEnvGeometry(F,false)){ + IReader R(F.pointer(), F.size()); + ::Sound->set_geometry_env(&R); + } +} + +bool CLevelSoundManager::MakeEnvGeometry(CMemoryWriter& F, bool bErrMsg) +{ + ObjectList& snd_envs = Scene->ListObj(OBJCLASS_SOUND_ENV); + + if (snd_envs.empty()){ + if (bErrMsg) ELog.Msg(mtError,"Scene hasn't sound environment geometry."); + return false; + } + + RStringVec env_names; + + CDB::Collector CP; + Fbox aabb; aabb.invalidate(); + for (ObjectIt it=snd_envs.begin(); it!=snd_envs.end(); it++){ + ESoundEnvironment* E = dynamic_cast(*it); R_ASSERT(E); + Fbox bb; + R_ASSERT (E->GetBox(bb)); + aabb.merge (bb); + + // get env name indices + if (E->m_EnvInner==E->m_EnvOuter) continue; + if ((0==E->m_EnvInner.size())||(0==E->m_EnvOuter.size())) continue; + + int inner = -1; + int outer = -1; + for (RStringVecIt e_it=env_names.begin(); e_it!=env_names.end(); e_it++){ + if ((-1==inner)&&(E->m_EnvInner==*e_it)) inner = e_it-env_names.begin(); + if ((-1==outer)&&(E->m_EnvOuter==*e_it)) outer = e_it-env_names.begin(); + if ((inner>-1)&&(outer>-1)) break; + } + + if (-1==inner){ inner=env_names.size(); env_names.push_back(E->m_EnvInner);} + if (-1==outer){ outer=env_names.size(); env_names.push_back(E->m_EnvOuter);} + u32 idx = (inner<<16)|(outer); + + // append to collector + Fmatrix M; E->get_box (M); + + Fvector bv[DU_BOX_NUMVERTEX]; + for (int k=0; kc_str()); + F.close_chunk (); + + // write geom + F.open_chunk (1); + // write header + hdrCFORM H; + H.version = CFORM_CURRENT_VERSION; + H.vertcount = CP.getVS(); + H.facecount = CP.getTS(); + H.aabb = aabb; + F.w (&H,sizeof(hdrCFORM)); + // write vertices&TRIs + F.w (CP.getV(),sizeof(Fvector)*H.vertcount); + F.w (CP.getT(),sizeof(CDB::TRI)*H.facecount); + F.close_chunk (); + + return true; +} +*/ +void CLevelSoundManager::OnFrame() +{ + inherited::OnFrame(); + if (bNeedRefreshEnvGeom) + { + bNeedRefreshEnvGeom = false; + // RealRefreshEnvGeometry (); + } +} +/* +void CLevelSoundManager::RefreshEnvLibrary() +{ + Sound->refresh_env_library(); + RefreshEnvGeometry (); +} +*/ diff --git a/src/editors/LevelEditor/Utils/SoundManager_LE.h b/src/editors/LevelEditor/Utils/SoundManager_LE.h new file mode 100644 index 00000000000..66a66262fb7 --- /dev/null +++ b/src/editors/LevelEditor/Utils/SoundManager_LE.h @@ -0,0 +1,39 @@ +//--------------------------------------------------------------------------- +#ifndef SoundManager_LEH +#define SoundManager_LEH + +#include "../xrECore/Editor/SoundManager.h" + +// refs +class ESoundThumbnail; + +class CLevelSoundManager : public CSoundManager +{ + typedef CSoundManager inherited; + bool bNeedRefreshEnvGeom; + void RealRefreshEnvGeometry(); + void MakeGameSound(ESoundThumbnail *THM, LPCSTR src_name, LPCSTR game_name); + +public: + CLevelSoundManager() { bNeedRefreshEnvGeom = false; } + ~CLevelSoundManager() { ; } + + virtual void OnFrame(); + + void RefreshEnvLibrary(); + void RefreshEnvGeometry() { bNeedRefreshEnvGeom = true; } + + // bool MakeEnvGeometry (CMemoryWriter& F, bool bErrMsg=false); + + bool Validate(); + + void MuteSounds(BOOL bVal); + + void RefreshSounds(bool bSync); + + xr_string UpdateFileName(xr_string &fn); +}; + +extern CLevelSoundManager *LSndLib; +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/LevelEditor/Utils/iniStreamImpl.cpp b/src/editors/LevelEditor/Utils/iniStreamImpl.cpp new file mode 100644 index 00000000000..ca3bb8126db --- /dev/null +++ b/src/editors/LevelEditor/Utils/iniStreamImpl.cpp @@ -0,0 +1,129 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "iniStreamImpl.h" + +LPCSTR SIniFileStream::gen_name() +{ + ++counter; + sprintf(tmp_buff, "%06d", counter); + return tmp_buff; +} + +void SIniFileStream::w_float(float a) +{ + ini->w_float(sect.c_str(), gen_name(), a); +} + +void SIniFileStream::w_vec3(const Fvector &a) +{ + ini->w_fvector3(sect.c_str(), gen_name(), a); +} + +void SIniFileStream::w_vec4(const Fvector4 &a) +{ + ini->w_fvector4(sect.c_str(), gen_name(), a); +} +void SIniFileStream::w_u64(u64 a) +{ + ini->w_u64(sect.c_str(), gen_name(), a); +} +void SIniFileStream::w_s64(s64 a) +{ + ini->w_s64(sect.c_str(), gen_name(), a); +} +void SIniFileStream::w_u32(u32 a) +{ + ini->w_u32(sect.c_str(), gen_name(), a); +} +void SIniFileStream::w_s32(s32 a) +{ + ini->w_s32(sect.c_str(), gen_name(), a); +} +void SIniFileStream::w_u16(u16 a) +{ + ini->w_u16(sect.c_str(), gen_name(), a); +} +void SIniFileStream::w_s16(s16 a) +{ + ini->w_s16(sect.c_str(), gen_name(), a); +} +void SIniFileStream::w_u8(u8 a) +{ + ini->w_u8(sect.c_str(), gen_name(), a); +} +void SIniFileStream::w_s8(s8 a) +{ + ini->w_s8(sect.c_str(), gen_name(), a); +} +void SIniFileStream::w_stringZ(LPCSTR S) +{ + string4096 buff; + xr_sprintf(buff, sizeof(buff), "\"%s\"", (S) ? S : ""); + ini->w_string(sect.c_str(), gen_name(), buff); +} + +void SIniFileStream::r_vec3(Fvector &A) +{ + A = ini->r_fvector3(sect.c_str(), gen_name()); +} +void SIniFileStream::r_vec4(Fvector4 &A) +{ + A = ini->r_fvector4(sect.c_str(), gen_name()); +} +void SIniFileStream::r_float(float &A) +{ + A = ini->r_float(sect.c_str(), gen_name()); +} +void SIniFileStream::r_u8(u8 &A) +{ + A = ini->r_u8(sect.c_str(), gen_name()); +} +void SIniFileStream::r_u16(u16 &A) +{ + A = ini->r_u16(sect.c_str(), gen_name()); +} +void SIniFileStream::r_u32(u32 &A) +{ + A = ini->r_u32(sect.c_str(), gen_name()); +} +void SIniFileStream::r_u64(u64 &A) +{ + A = ini->r_u64(sect.c_str(), gen_name()); +} + +void SIniFileStream::r_s8(s8 &A) +{ + A = ini->r_s8(sect.c_str(), gen_name()); +} +void SIniFileStream::r_s16(s16 &A) +{ + A = ini->r_s16(sect.c_str(), gen_name()); +} +void SIniFileStream::r_s32(s32 &A) +{ + A = ini->r_s32(sect.c_str(), gen_name()); +} +void SIniFileStream::r_s64(s64 &A) +{ + A = ini->r_s64(sect.c_str(), gen_name()); +} + +void SIniFileStream::r_string(LPSTR dest, u32 dest_size) +{ + shared_str S; + S = ini->r_string_wb(sect.c_str(), gen_name()); + R_ASSERT(dest_size >= S.size()); + xr_strcpy(dest, dest_size, S.c_str()); + //. Msg("[%s] [%s]=[%s]",sect.c_str(),tmp_buff,dest); +} + +void SIniFileStream::r_string(xr_string &name) +{ + name = ini->r_string_wb(sect.c_str(), gen_name()).c_str(); +} + +void SIniFileStream::skip_stringZ() +{ + gen_name(); +} diff --git a/src/editors/LevelEditor/Utils/iniStreamImpl.h b/src/editors/LevelEditor/Utils/iniStreamImpl.h new file mode 100644 index 00000000000..c2699b39202 --- /dev/null +++ b/src/editors/LevelEditor/Utils/iniStreamImpl.h @@ -0,0 +1,48 @@ +#ifndef inistream_impl_h_included +#define inistream_impl_h_included + +#pragma pack(push, 1) + +struct SIniFileStream : public IIniFileStream +{ + CInifile *ini; + shared_str sect; + string128 tmp_buff; + u32 counter; + LPCSTR gen_name(); + + virtual void move_begin() { counter = 0; }; + + virtual void w_float(float a); + virtual void w_vec3(const Fvector &a); + virtual void w_vec4(const Fvector4 &a); + virtual void w_u64(u64 a); + virtual void w_s64(s64 a); + virtual void w_u32(u32 a); + virtual void w_s32(s32 a); + virtual void w_u16(u16 a); + virtual void w_s16(s16 a); + virtual void w_u8(u8 a); + virtual void w_s8(s8 a); + virtual void w_stringZ(LPCSTR S); + + virtual void r_vec3(Fvector &); + virtual void r_vec4(Fvector4 &); + virtual void r_float(float &); + virtual void r_u8(u8 &); + virtual void r_u16(u16 &); + virtual void r_u32(u32 &); + virtual void r_u64(u64 &); + virtual void r_s8(s8 &); + virtual void r_s16(s16 &); + virtual void r_s32(s32 &); + virtual void r_s64(s64 &); + + virtual void r_string(LPSTR dest, u32 dest_size); + virtual void r_string(xr_string &name); + virtual void skip_stringZ(); +}; + +#pragma pack(pop) + +#endif \ No newline at end of file diff --git a/src/editors/LevelEditor/Utils/portalutils.cpp b/src/editors/LevelEditor/Utils/portalutils.cpp new file mode 100644 index 00000000000..1a9473ba831 --- /dev/null +++ b/src/editors/LevelEditor/Utils/portalutils.cpp @@ -0,0 +1,690 @@ +#include "stdafx.h" + +CPortalUtils PortalUtils; +#define EPS_P 0.001f + +CSector *CPortalUtils::GetSelectedSector() +{ + ObjectList lst; + Scene->GetQueryObjects(lst, OBJCLASS_SECTOR, 1, 1, 0); + if (lst.size() == 0) + return 0; + if (lst.size() > 1) + { + ELog.DlgMsg(mtError, "Please select only one sector."); + return 0; + } + CSector *sector = (CSector *)*lst.begin(); + VERIFY(sector); + return sector; +} + +void CPortalUtils::RemoveSectorPortal(CSector *S) +{ + // remove existence sector portal + ObjectList &lst = Scene->ListObj(OBJCLASS_PORTAL); + ObjectIt _I = lst.begin(); + ObjectIt _E = lst.end(); + for (; _I != _E; _I++) + { + CPortal *P = (CPortal *)(*_I); + if ((P->m_SectorFront == S) || (P->m_SectorBack == S)) + xr_delete(*_I); + } + _I = remove(lst.begin(), lst.end(), (CCustomObject *)0); + lst.erase(_I, lst.end()); +} + +int CPortalUtils::CalculateSelectedPortals() +{ + int iPCount = 0; + if (Validate(false)) + { + // get selected sectors + ObjectList s_lst; + int s_cnt = Scene->GetQueryObjects(s_lst, OBJCLASS_SECTOR, 1, 1, -1); + if (s_cnt < 2) + { + ELog.DlgMsg(mtError, "Select at least 2 sectors."); + return 0; + } + // remove exists portals + ObjectList &p_lst = Scene->ListObj(OBJCLASS_PORTAL); + for (ObjectIt _F = p_lst.begin(); _F != p_lst.end(); _F++) + { + CSector *SF = ((CPortal *)(*_F))->m_SectorFront; + CSector *SB = ((CPortal *)(*_F))->m_SectorBack; + if ((std::find(s_lst.begin(), s_lst.end(), SF) != s_lst.end()) && (std::find(s_lst.begin(), s_lst.end(), SB) != s_lst.end())) + xr_delete(*_F); + } + ObjectIt _E = remove(p_lst.begin(), p_lst.end(), (CCustomObject *)0); + p_lst.erase(_E, p_lst.end()); + // transfer from list to vector + iPCount = CalculateSelectedPortals(s_lst); + } + else + { + ELog.DlgMsg(mtError, "*ERROR: Scene has non associated face (face without sector)!"); + } + + UI->SetStatus("..."); + return iPCount; +} +//--------------------------------------------------------------------------- + +void CPortalUtils::RemoveAllPortals() +{ + // remove all existence portal + ObjectList &p_lst = Scene->ListObj(OBJCLASS_PORTAL); + for (ObjectIt _F = p_lst.begin(); _F != p_lst.end(); _F++) + xr_delete(*_F); + p_lst.erase(p_lst.begin(), p_lst.end()); +} +//--------------------------------------------------------------------------- + +bool CPortalUtils::CreateDefaultSector() +{ + Fbox box; + if (Scene->GetBox(box, OBJCLASS_SCENEOBJECT)) + { + CSector *sector_def = xr_new((LPVOID)0, DEFAULT_SECTOR_NAME); + sector_def->sector_color.set(1, 0, 0, 0); + sector_def->m_bDefault = true; + sector_def->CaptureAllUnusedMeshes(); + if (!sector_def->IsEmpty()) + { + Scene->AppendObject(sector_def, true); + return true; + } + else + xr_delete(sector_def); + } + return false; +} +//--------------------------------------------------------------------------- + +bool CPortalUtils::RemoveDefaultSector() +{ + CCustomObject *O = Scene->FindObjectByName(DEFAULT_SECTOR_NAME, OBJCLASS_SECTOR); + if (O) + { + Scene->RemoveObject(O, false, true); + xr_delete(O); + Scene->UndoSave(); + UI->UpdateScene(); + return true; + } + return false; +} +//--------------------------------------------------------------------------- +/* +int CPortalUtils::CalculateAllPortals2() +{ + int bResult=0; + if (Validate(false)){ + RemoveAllPortals(); + // calculate 0-sector +// RemoveDefaultSector(); +// CreateDefaultSector(); + + // transfer from list to vector + ObjectList& s_lst=Scene->ListObj(OBJCLASS_SECTOR); + xr_vector sectors; + for(ObjectIt _F=s_lst.begin(); _F!=s_lst.end(); _F++) sectors.push_back((CSector*)(*_F)); + + // calculate all portals + for (u32 f=0; fSetStatus(t.c_str()); + } + + Scene->UndoSave(); + }else{ + ELog.DlgMsg(mtError,"*ERROR: Scene has non associated face (face without sector)!"); + } + + UI->SetStatus("..."); + return bResult; +} +*/ +//--------------------------------------------------------------------------- +CSector *CPortalUtils::FindSector(CSceneObject *o, CEditableMesh *m) +{ + ObjectIt _F = Scene->FirstObj(OBJCLASS_SECTOR); + ObjectIt _E = Scene->LastObj(OBJCLASS_SECTOR); + for (; _F != _E; _F++) + if (((CSector *)(*_F))->Contains(o, m)) + return (CSector *)(*_F); + return 0; +} + +bool CPortalUtils::Validate(bool bMsg) +{ + Fbox box; + bool bResult = false; + if (Scene->GetBox(box, OBJCLASS_SCENEOBJECT)) + { + bResult = true; + CSector *sector_def = xr_new((LPVOID)0, DEFAULT_SECTOR_NAME); + sector_def->CaptureAllUnusedMeshes(); + int f_cnt; + sector_def->GetCounts(0, 0, &f_cnt); + if (f_cnt != 0) + { + if (bMsg) + { + ELog.DlgMsg(mtError, "*ERROR: Scene has '%d' non associated face!", f_cnt); + for (SItemIt it = sector_def->sector_items.begin(); it != sector_def->sector_items.end(); it++) + Msg("! - scene object: '%s' [O:'%s', M:'%s']", it->object->GetName(), it->object->RefName(), it->mesh->Name().c_str()); + } + bResult = false; + } + xr_delete(sector_def); + + // verify sectors + ObjectList &s_lst = Scene->ListObj(OBJCLASS_SECTOR); + for (ObjectIt _F = s_lst.begin(); _F != s_lst.end(); _F++) + if (!((CSector *)(*_F))->Validate(bMsg)) + bResult = false; + } + else + { + if (bMsg) + ELog.DlgMsg(mtInformation, "Validation failed! Can't compute bbox."); + } + return bResult; +} +//-------------------------------------------------------------------------------------------------- +// calculate portals +//-------------------------------------------------------------------------------------------------- + +const int clpMX = 64, clpMY = 24, clpMZ = 64; + +class sCollector +{ + struct sFace + { + u32 v[3]; + CSector *sector; + + bool hasVertex(u32 vert) + { + return (v[0] == vert) || (v[1] == vert) || (v[2] == vert); + } + }; + struct sVert : public Fvector + { + U32Vec adj; + }; + struct sEdge + { + CSector *s[2]; + u32 v[2]; + u32 used; + u32 dummy; + + sEdge() { used = false; } + static bool c_less(const sEdge &E1, const sEdge &E2) + { + if (E1.s[0] < E2.s[0]) + return true; + if (E1.s[1] < E2.s[1]) + return true; + if (E1.v[0] < E2.v[0]) + return true; + if (E1.v[1] < E2.v[1]) + return true; + return false; + } + static bool c_equal(const sEdge &E1, const sEdge &E2) + { + return (E1.s[0] == E2.s[0]) && (E1.s[1] == E2.s[1]) && (E1.v[0] == E2.v[0]) && (E1.v[1] == E2.v[1]); + } + static int __cdecl compare(const void *arg1, const void *arg2) + { + return memcmp(arg1, arg2, sizeof(s) + sizeof(v)); + } + }; + struct sPortal + { + xr_deque e; + CSector *s[2]; + }; + + DEFINE_VECTOR(sVert, sVertVec, sVertIt); + DEFINE_VECTOR(sFace, sFaceVec, sFaceIt); + DEFINE_VECTOR(sEdge, sEdgeVec, sEdgeIt); + DEFINE_VECTOR(sPortal, sPortalVec, sPortalIt); + +public: + sVertVec verts; + sFaceVec faces; + sEdgeVec edges; + sPortalVec portals; + + Fvector VMmin, VMscale; + U32Vec VM[clpMX + 1][clpMY + 1][clpMZ + 1]; + Fvector VMeps; + + u32 VPack(Fvector &V) + { + u32 P = 0xffffffff; + + u32 ix, iy, iz; + ix = iFloor(float(V.x - VMmin.x) / VMscale.x * clpMX); + iy = iFloor(float(V.y - VMmin.y) / VMscale.y * clpMY); + iz = iFloor(float(V.z - VMmin.z) / VMscale.z * clpMZ); + R_ASSERT(ix <= clpMX && iy <= clpMY && iz <= clpMZ); + + { + U32Vec *vl; + vl = &(VM[ix][iy][iz]); + U32It it = vl->begin(); + U32It it_e = vl->end(); + xr_vector::iterator verts_begin = verts.begin(); + for (; it != it_e; ++it) + { + // if(verts[*it].similar(V) ) + if ((*(verts_begin + *it)).similar(V)) + { + P = *it; + break; + } + } + } + if (0xffffffff == P) + { + P = verts.size(); + sVert sV; + sV.set(V); + verts.push_back(sV); + + VM[ix][iy][iz].push_back(P); + + u32 ixE, iyE, izE; + ixE = iFloor(float(V.x + VMeps.x - VMmin.x) / VMscale.x * clpMX); + iyE = iFloor(float(V.y + VMeps.y - VMmin.y) / VMscale.y * clpMY); + izE = iFloor(float(V.z + VMeps.z - VMmin.z) / VMscale.z * clpMZ); + + R_ASSERT(ixE <= clpMX && iyE <= clpMY && izE <= clpMZ); + + if (ixE != ix) + VM[ixE][iy][iz].push_back(P); + + if (iyE != iy) + VM[ix][iyE][iz].push_back(P); + + if (izE != iz) + VM[ix][iy][izE].push_back(P); + + if ((ixE != ix) && (iyE != iy)) + VM[ixE][iyE][iz].push_back(P); + + if ((ixE != ix) && (izE != iz)) + VM[ixE][iy][izE].push_back(P); + + if ((iyE != iy) && (izE != iz)) + VM[ix][iyE][izE].push_back(P); + + if ((ixE != ix) && (iyE != iy) && (izE != iz)) + VM[ixE][iyE][izE].push_back(P); + } + return P; + } + + sCollector(const Fbox &bb) + { + VMscale.set(bb.vMax.x - bb.vMin.x, bb.vMax.y - bb.vMin.y, bb.vMax.z - bb.vMin.z); + VMmin.set(bb.vMin); + VMeps.set(VMscale.x / clpMX / 2, VMscale.y / clpMY / 2, VMscale.z / clpMZ / 2); + VMeps.x = (VMeps.x < EPS_L) ? VMeps.x : EPS_L; + VMeps.y = (VMeps.y < EPS_L) ? VMeps.y : EPS_L; + VMeps.z = (VMeps.z < EPS_L) ? VMeps.z : EPS_L; + } + + void add_face( + Fvector &v0, // vertices + Fvector &v1, + Fvector &v2, + CSector *sector) + { + sFace T; + T.v[0] = VPack(v0); + T.v[1] = VPack(v1); + T.v[2] = VPack(v2); + T.sector = sector; + faces.push_back(T); + } + void update_adjacency() + { + for (u32 i = 0; i < faces.size(); i++) + { + sFace &F = faces[i]; + verts[F.v[0]].adj.push_back(i); + verts[F.v[1]].adj.push_back(i); + verts[F.v[2]].adj.push_back(i); + } + } + void find_edges() + { + for (u32 i = 0; i < faces.size(); i++) + { + sFace &F = faces[i]; + U32It a_it; + sVert &v0 = verts[F.v[0]]; + sVert &v1 = verts[F.v[1]]; + sVert &v2 = verts[F.v[2]]; + + // 1 pair (0-1) + for (a_it = v0.adj.begin(); a_it != v0.adj.end(); a_it++) + { + if (*a_it == i) + continue; + + sFace &T = faces[*a_it]; + if (T.sector == F.sector) + continue; + + if (!T.hasVertex(F.v[1])) + continue; + + sEdge E; + E.v[0] = F.v[0]; + E.v[1] = F.v[1]; + E.s[0] = F.sector; + E.s[1] = T.sector; + edges.push_back(E); + } + // 2 pair (1-2) + for (a_it = v1.adj.begin(); a_it != v1.adj.end(); a_it++) + { + if (*a_it == i) + continue; + + sFace &T = faces[*a_it]; + if (T.sector == F.sector) + continue; + + if (!T.hasVertex(F.v[2])) + continue; + + sEdge E; + E.v[0] = F.v[1]; + E.v[1] = F.v[2]; + E.s[0] = F.sector; + E.s[1] = T.sector; + edges.push_back(E); + } + // 3 pair (2-0) + for (a_it = v2.adj.begin(); a_it != v2.adj.end(); a_it++) + { + if (*a_it == i) + continue; + + sFace &T = faces[*a_it]; + if (T.sector == F.sector) + continue; + + if (!T.hasVertex(F.v[0])) + continue; + + sEdge E; + E.v[0] = F.v[2]; + E.v[1] = F.v[0]; + E.s[0] = F.sector; + E.s[1] = T.sector; + edges.push_back(E); + } + } + } + void dump_edges() + { + ELog.Msg(mtInformation, "********* dump"); + for (u32 i = 0; i < edges.size(); i++) + { + sEdge &E = edges[i]; + ELog.Msg(mtInformation, "%d: %d,%d", i, E.v[0], E.v[1]); + } + } + void sort_edges() + { + // sort inside edges + for (u32 i = 0; i < edges.size(); i++) + { + sEdge &E = edges[i]; + if (E.v[0] > E.v[1]) + std::swap(E.v[0], E.v[1]); + if (E.s[0] > E.s[1]) + std::swap(E.s[0], E.s[1]); + } + + // remove equal + qsort(edges.data(), edges.size(), sizeof(sEdge), sEdge::compare); + sEdgeIt NewEnd = std::unique(edges.begin(), edges.end(), sEdge::c_equal); + edges.erase(NewEnd, edges.end()); + // dump_edges(); + } + + void make_portals() + { + for (u32 e_it = 0; e_it < edges.size(); e_it++) + { + if (edges[e_it].used) + continue; + + sPortal current; + current.e.push_back(e_it); + current.s[0] = edges[e_it].s[0]; + current.s[1] = edges[e_it].s[1]; + edges[e_it].used = true; + + for (;;) + { + sEdge &eFirst = edges[current.e[0]]; + sEdge &eLast = edges[current.e.back()]; + u32 vFirst = eFirst.v[0]; + u32 vLast = eLast.v[1]; + bool bFound = false; + for (u32 i = 0; i < edges.size(); i++) + { + sEdge &E = edges[i]; + if (E.used) + continue; + if (E.s[0] != current.s[0]) + continue; + if (E.s[1] != current.s[1]) + continue; + + if (vLast == E.v[0]) + { + E.used = true; + current.e.push_back(i); + bFound = true; + break; + } + if (vLast == E.v[1]) + { + E.used = true; + std::swap(E.v[0], E.v[1]); + current.e.push_back(i); + bFound = true; + break; + } + if (vFirst == E.v[0]) + { + E.used = true; + std::swap(E.v[0], E.v[1]); + current.e.push_front(i); + bFound = true; + break; + } + if (vFirst == E.v[1]) + { + E.used = true; + current.e.push_front(i); + bFound = true; + break; + } + } + if (!bFound) + break; + } + portals.push_back(current); + } + } + void export_portals() + { + Tools->ClearDebugDraw(); + int ps = portals.size(); + int curr = 0; + for (sPortalIt p_it = portals.begin(); p_it != portals.end(); ++p_it, ++curr) + { + if (p_it->e.size() > 1) + { + Msg("portal %d of %d", curr, ps); + // build vert-list + xr_vector vlist; + xr_deque &elist = p_it->e; + vlist.reserve(elist.size() * 2); + for (xr_deque::iterator e = elist.begin(); e != elist.end(); e++) + { + vlist.push_back(edges[*e].v[0]); + vlist.push_back(edges[*e].v[1]); + } + IntIt end = std::unique(vlist.begin(), vlist.end()); + vlist.erase(end, vlist.end()); + + // append portal + string256 namebuffer; + Scene->GenObjectName(OBJCLASS_PORTAL, namebuffer); + CPortal *_O = xr_new((LPVOID)0, namebuffer); + for (u32 i = 0; i < vlist.size(); i++) + { + _O->Vertices().push_back(verts[vlist[i]]); + } + _O->SetSectors(p_it->s[0], p_it->s[1]); + _O->Update(); + if (_O->Valid()) + { + Scene->AppendObject(_O, false); + } + else + { + xr_delete(_O); + ELog.Msg(mtError, "Can't simplify Portal :(\nPlease check geometry.\n'%s'<->'%s'", p_it->s[0]->GetName(), p_it->s[1]->GetName()); + } + } + else if (p_it->e.size() == 0) + { + ELog.Msg(mtError, "Can't create Portal from 0 edge :(\nPlease check geometry.\n'%s'<->'%s'\n", p_it->s[0]->GetName(), p_it->s[1]->GetName()); + } + else + { + Fvector &v0 = verts[edges[p_it->e[0]].v[0]]; + Fvector &v1 = verts[edges[p_it->e[0]].v[1]]; + ELog.Msg(mtError, "Can't create Portal from one edge :(\nPlease check geometry.\n'%s'<->'%s'", p_it->s[0]->GetName(), p_it->s[1]->GetName()); + Tools->m_DebugDraw.AppendLine(v0, v1); + } + } + } +}; + +int CPortalUtils::CalculateSelectedPortals(ObjectList §ors) +{ + // calculate portals + Fbox bb; + Scene->GetBox(bb, OBJCLASS_SCENEOBJECT); + sCollector *CL = xr_new(bb); + Fmatrix T; + + // 1. xform + weld + UI->SetStatus("xform + weld..."); + for (ObjectIt s_it = sectors.begin(); s_it != sectors.end(); s_it++) + { + CSector *S = (CSector *)(*s_it); + for (SItemIt s_it = S->sector_items.begin(); s_it != S->sector_items.end(); s_it++) + { + if (s_it->object->IsMUStatic()) + continue; + s_it->GetTransform(T); + Fvector *m_verts = s_it->mesh->m_Vertices; + for (u32 f_id = 0; f_id < s_it->mesh->GetFCount(); f_id++) + { + Fvector v0, v1, v2; + const st_Face &P = s_it->mesh->GetFaces()[f_id]; + T.transform_tiny(v0, m_verts[P.pv[0].pindex]); + T.transform_tiny(v1, m_verts[P.pv[1].pindex]); + T.transform_tiny(v2, m_verts[P.pv[2].pindex]); + CL->add_face(v0, v1, v2, S); + } + } + } + // 2. update pervertex adjacency + UI->SetStatus("updating per-vertex adjacency..."); + CL->update_adjacency(); + // 3. find edges + UI->SetStatus("searching edges..."); + CL->find_edges(); + // 4. sort edges + UI->SetStatus("sorting edges..."); + CL->sort_edges(); + // 5. make portals + UI->SetStatus("calculating portals..."); + CL->make_portals(); + // 6. export portals + UI->SetStatus("building portals..."); + CL->export_portals(); + + Scene->UndoSave(); + + int iRes = CL->portals.size(); + + xr_delete(CL); + + return iRes; +} + +int CPortalUtils::CalculateAllPortals() +{ + int iPCount = 0; + if (Validate(false)) + { + UI->SetStatus("Prepare..."); + RemoveAllPortals(); + ObjectList &s_lst = Scene->ListObj(OBJCLASS_SECTOR); + iPCount = CalculateSelectedPortals(s_lst); + } + else + { + ELog.DlgMsg(mtError, "*ERROR: Sector validation failed."); + } + + UI->ResetStatus(); + return iPCount; +} + +int CPortalUtils::CalculatePortals(CSector *SF, CSector *SB) +{ + int iPCount = 0; + if (Validate(false)) + { + UI->SetStatus("Prepare..."); + RemoveAllPortals(); + // transfer from list to vector + ObjectList sectors; + sectors.push_back(SF); + sectors.push_back(SB); + + iPCount = CalculateSelectedPortals(sectors); + } + else + { + ELog.DlgMsg(mtError, "*ERROR: Scene has non associated face (face without sector)!"); + } + + UI->ResetStatus(); + return iPCount; +} diff --git a/src/editors/LevelEditor/Utils/portalutils.h b/src/editors/LevelEditor/Utils/portalutils.h new file mode 100644 index 00000000000..2441eeaa6af --- /dev/null +++ b/src/editors/LevelEditor/Utils/portalutils.h @@ -0,0 +1,64 @@ +#pragma once +#include + +// refs +class CEditableMesh; +class CEditableObject; +class CSceneObject; +class CSector; + +struct SVertex : public Fvector +{ + IntVec link[2]; + IntVec ulink; + int portal; + SVertex(const Fvector &v) + { + set(v); + portal = -1; + } + IC void SetLink(int id, int i0, int i1) + { + if (i0 >= 0) + link[id].push_back(i0); + if (i1 >= 0) + link[id].push_back(i1); + } + IC void ConsolidateLink() + { + std::sort(link[0].begin(), link[0].end()); + std::sort(link[1].begin(), link[1].end()); + std::set_intersection(link[0].begin(), link[0].end(), + link[1].begin(), link[1].end(), + inserter(ulink, ulink.begin())); + VERIFY(ulink.size() <= 2); + } +}; + +DEFINE_VECTOR(SVertex, SVertexVec, SVertexIt) + +class CPortalUtils +{ + // void FindSVertexLinks(int id, CSector* S, SVertexVec& V); + int CalculateSelectedPortals(ObjectList §ors); + +public: + bool CalculateConvexHull(FvectorVec &points); + int CalculatePortals(CSector *SF, CSector *SB); + int CalculateSelectedPortals(); + int CalculateAllPortals(); + //. int CalculateAllPortals2(); + void RemoveAllPortals(); + void RemoveSectorPortal(CSector *S); + bool CreateDefaultSector(); + bool RemoveDefaultSector(); + + CSector *FindSector(CSceneObject *o, CEditableMesh *m); + + // void CreateDebugCollection(); + bool Validate(bool bMsg); + + CSector *GetSelectedSector(); +}; + +extern CPortalUtils PortalUtils; diff --git a/src/editors/ParticleEditor/PSLibraryEditor.cpp b/src/editors/ParticleEditor/PSLibraryEditor.cpp new file mode 100644 index 00000000000..df6365c5578 --- /dev/null +++ b/src/editors/ParticleEditor/PSLibraryEditor.cpp @@ -0,0 +1,101 @@ +#include "stdafx.h" +#include "Layers/xrRender/PSLibrary.h" +#include "Layers/xrRender/ParticleEffect.h" +#include "Layers/xrRender/ParticleGroup.h" + +void CPSLibrary::FindByName(LPCSTR new_name, bool &res) +{ + res = (FindPED(new_name) || FindPGD(new_name)); +} + +PS::CPEDef *CPSLibrary::AppendPED(PS::CPEDef *src) +{ + m_PEDs.push_back(xr_new()); +#ifdef _PARTICLE_EDITOR + if (src) + m_PEDs.back()->Copy(*src); +#endif + return m_PEDs.back(); +} + +PS::CPGDef *CPSLibrary::AppendPGD(PS::CPGDef *src) +{ + m_PGDs.push_back(xr_new()); + if (src) + m_PGDs.back()->Clone(src); + return m_PGDs.back(); +} +//------------------------------------------------------------------------------ + +bool CPSLibrary::Save() +{ + xr_string temp_fn; + if (EFS.GetSaveName("$game_data$", temp_fn)) + { + return Save(temp_fn.c_str()); + } + else + return false; +} +//------------------------------------------------------------------------------ +bool CPSLibrary::Save2() +{ + FS.dir_delete("$game_particles$", "", TRUE); + string_path fn; + SPBItem *pb = UI->ProgressStart(static_cast(m_PEDs.size() + m_PGDs.size()), "Saving particles..."); + for (PS::PEDIt it = m_PEDs.begin(); it != m_PEDs.end(); ++it) + { + pb->Inc(); + PS::CPEDef *pe = (*it); + FS.update_path(fn, "$game_particles$", pe->m_Name.c_str()); + strcat(fn, ".pe"); + CInifile ini(fn, FALSE, FALSE, FALSE); + pe->Save2(ini); + ini.save_as(fn); + } + + for (PS::PGDIt g_it = m_PGDs.begin(); g_it != m_PGDs.end(); ++g_it) + { + pb->Inc(); + PS::CPGDef *pg = (*g_it); + FS.update_path(fn, "$game_particles$", pg->m_Name.c_str()); + strcat(fn, ".pg"); + CInifile ini(fn, FALSE, FALSE, FALSE); + pg->Save2(ini); + ini.save_as(fn); + } + UI->ProgressEnd(pb); + return true; +} + +bool CPSLibrary::Save(const char *nm) +{ + CMemoryWriter F; + + F.open_chunk(PS_CHUNK_VERSION); + F.w_u16(PS_VERSION); + F.close_chunk(); + + F.open_chunk(PS_CHUNK_SECONDGEN); + u32 chunk_id = 0; + for (PS::PEDIt it = m_PEDs.begin(); it != m_PEDs.end(); ++it, ++chunk_id) + { + F.open_chunk(chunk_id); + (*it)->Save(F); + F.close_chunk(); + } + F.close_chunk(); + + F.open_chunk(PS_CHUNK_THIRDGEN); + chunk_id = 0; + for (PS::PGDIt g_it = m_PGDs.begin(); g_it != m_PGDs.end(); ++g_it, ++chunk_id) + { + F.open_chunk(chunk_id); + (*g_it)->Save(F); + F.close_chunk(); + } + F.close_chunk(); + + return F.save_to(nm); +} +//------------------------------------------------------------------------------ diff --git a/src/editors/ParticleEditor/ParticleEditor.cpp b/src/editors/ParticleEditor/ParticleEditor.cpp new file mode 100644 index 00000000000..1e06c0d4a85 --- /dev/null +++ b/src/editors/ParticleEditor/ParticleEditor.cpp @@ -0,0 +1,28 @@ +// ParticleEditor.cpp : Определяет точку входа для приложения. + +#include "stdafx.h" + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow) +{ + if (!IsDebuggerPresent()) + xrDebug::Initialize(pCmdLine); + + Core.Initialize("particle", pCmdLine, LogCallback(ELogCallback, nullptr), true, "fs.ltx", false, true); + PTools = xr_new(); + Tools = PTools; + + UI = xr_new(); + UI->RegisterCommands(); + + UIMainForm *MainForm = xr_new(); + ::MainForm = MainForm; + UI->Push(MainForm, false); + + while (MainForm->Frame()) + { + } + + xr_delete(MainForm); + Core._destroy(); + return 0; +} diff --git a/src/editors/ParticleEditor/ParticleEditor.vcxproj b/src/editors/ParticleEditor/ParticleEditor.vcxproj new file mode 100644 index 00000000000..c3c56f6002b --- /dev/null +++ b/src/editors/ParticleEditor/ParticleEditor.vcxproj @@ -0,0 +1,107 @@ + + + + + + + {19DC7E82-12AF-4110-93CA-E7C30500A3F5} + ParticleEditor + + + + + + + Application + + + + + + + + + + + + + + _EDITOR;_PARTICLE_EDITOR;_WINDOWS;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {1daec516-e52c-4a3c-a4da-ae3553e6e0f8} + + + {7885cf3c-ee04-4c67-9467-1fbf9a36b037} + + + {a0f7d1fb-59a7-4717-a7e4-96f37e91998e} + + + {94a1c366-3d19-48e6-8170-4adc2e70df97} + + + {ccca7859-eb86-493e-9b53-c4235f45b3c5} + + + {9187be98-531a-4276-b78e-dba3c8ab8447} + + + {6d47afc7-0557-4bbf-8902-b248f3621419} + + + {7e28883c-db86-4ee8-813a-991ba20c68c9} + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/editors/ParticleEditor/ParticleEditor.vcxproj.filters b/src/editors/ParticleEditor/ParticleEditor.vcxproj.filters new file mode 100644 index 00000000000..c72842c8d9c --- /dev/null +++ b/src/editors/ParticleEditor/ParticleEditor.vcxproj.filters @@ -0,0 +1,121 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы ресурсов + + + + + Файлы ресурсов + + + + + Файлы ресурсов + + + + + + \ No newline at end of file diff --git a/src/editors/ParticleEditor/ParticleEffectActionsImpl.cpp b/src/editors/ParticleEditor/ParticleEffectActionsImpl.cpp new file mode 100644 index 00000000000..4e505c92075 --- /dev/null +++ b/src/editors/ParticleEditor/ParticleEffectActionsImpl.cpp @@ -0,0 +1,1389 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "../xrECore/Editor/ParticleEffectActions.h" +#include "../../xrParticles/particle_actions_collection.h" + +using namespace PAPI; + +const u32 PARTICLE_ACTION_VERSION = 0x0001; +const u32 PARTICLE_ACTION_VERSION_SOC = 0x0000; + +xr_token2 actions_token[] = +{ + {"Avoid", "Steer particles away from a domain of space.", PAAvoidID}, + {"Bounce", "Bounce particles off a domain of space.", PABounceID}, + {"Copy VertexB", "Set the secondary position from current position.", PACopyVertexBID}, + {"Damping", "Simulate air by slowing down particle velocities.", PADampingID}, + {"Explosion", "An Explosion.", PAExplosionID}, + {"Follow", "Accelerate toward the next particle in the group.", PAFollowID}, + {"Gravitate", "Accelerate each particle toward each other particle.", PAGravitateID}, + {"Gravity", "Accelerate particles in the given direction.", PAGravityID}, + {"Jet", "Accelerate particles that are near the center of the jet.", PAJetID}, + {"Kill Old", "Remove old particles.", PAKillOldID}, + {"Match Velocity", "Modify each particle’s velocity to be similar to that of its neighbors.", PAMatchVelocityID}, + {"Move", "Move particle positions based on velocities.", PAMoveID}, + {"Orbit Line", "Accelerate toward the closest point on the given line.", PAOrbitLineID}, + {"Orbit Point", "Accelerate toward the given center point.", PAOrbitPointID}, + {"Random Accel", "Accelerate particles in random directions.", PARandomAccelID}, + {"Random Displace", "Immediately replace position with a position from the domain.", PARandomDisplaceID}, + {"Random Velocity", "Immediately replace velocity with a velocity from the domain.", PARandomVelocityID}, + {"Restore", "Over time, restore particles to their secondary positions.", PARestoreID}, + {"Scatter", "Scatter particles from center.", PAScatterID}, + {"Sink", "Kill particles with positions on wrong side of the specified domain.", PASinkID}, + {"Sink Velocity", "Kill particles with velocities on wrong side of the specified domain.", PASinkVelocityID}, + {"Source", "Add particles in the specified domain.", PASourceID}, + {"Speed Limit", "Clamp each particle’s speed to the given min and max.", PASpeedLimitID}, + {"Target Color", "Change color of all particles toward the specified color.", PATargetColorID}, + {"Target Size", "Change sizes of all particles toward the specified size.", PATargetSizeID}, + {"Target Rotate", "Change rotate of all particles toward the specified rotation.", PATargetRotateID}, + {"Target Velocity", "Change velocity of all particles toward the specified velocity.", PATargetVelocityID}, + {"Vortex", "Swirl particles around a vortex.", PAVortexID}, + {"Turbulence", "A Turbulence.", PATurbulenceID}, + {0, 0} +}; + +EParticleAction *pCreateEActionImpl(PAPI::PActionEnum type) +{ + EParticleAction *pa = 0; + switch (type) + { + case PAPI::PAAvoidID: + pa = xr_new(); + break; + case PAPI::PABounceID: + pa = xr_new(); + break; + case PAPI::PACopyVertexBID: + pa = xr_new(); + break; + case PAPI::PADampingID: + pa = xr_new(); + break; + case PAPI::PAExplosionID: + pa = xr_new(); + break; + case PAPI::PAFollowID: + pa = xr_new(); + break; + case PAPI::PAGravitateID: + pa = xr_new(); + break; + case PAPI::PAGravityID: + pa = xr_new(); + break; + case PAPI::PAJetID: + pa = xr_new(); + break; + case PAPI::PAKillOldID: + pa = xr_new(); + break; + case PAPI::PAMatchVelocityID: + pa = xr_new(); + break; + case PAPI::PAMoveID: + pa = xr_new(); + break; + case PAPI::PAOrbitLineID: + pa = xr_new(); + break; + case PAPI::PAOrbitPointID: + pa = xr_new(); + break; + case PAPI::PARandomAccelID: + pa = xr_new(); + break; + case PAPI::PARandomDisplaceID: + pa = xr_new(); + break; + case PAPI::PARandomVelocityID: + pa = xr_new(); + break; + case PAPI::PARestoreID: + pa = xr_new(); + break; + case PAPI::PAScatterID: + pa = xr_new(); + break; + case PAPI::PASinkID: + pa = xr_new(); + break; + case PAPI::PASinkVelocityID: + pa = xr_new(); + break; + case PAPI::PASourceID: + pa = xr_new(); + break; + case PAPI::PASpeedLimitID: + pa = xr_new(); + break; + case PAPI::PATargetColorID: + pa = xr_new(); + break; + case PAPI::PATargetSizeID: + pa = xr_new(); + break; + case PAPI::PATargetRotateID: + pa = xr_new(); + break; + case PAPI::PATargetRotateDID: + pa = xr_new(); + break; + case PAPI::PATargetVelocityID: + pa = xr_new(); + break; + case PAPI::PATargetVelocityDID: + pa = xr_new(); + break; + case PAPI::PAVortexID: + pa = xr_new(); + break; + case PAPI::PATurbulenceID: + pa = xr_new(); + break; + default: + NODEFAULT; + } + pa->type = type; + return pa; +} +//--------------------------------------------------------------------------- +void EParticleAction::Render(const Fmatrix &parent) +{ + for (PDomainMapIt it = domains.begin(); it != domains.end(); it++) + it->second.Render(it->second.clr, parent); +} +void EParticleAction::Load(IReader &F) +{ + u32 vers = F.r_u32(); + + if(Core.SocSdk) + R_ASSERT(vers == PARTICLE_ACTION_VERSION_SOC); + else + R_ASSERT(vers == PARTICLE_ACTION_VERSION); + + F.r_stringZ(actionName); + flags.assign(F.r_u32()); + for (PFloatMapIt f_it = floats.begin(); f_it != floats.end(); f_it++) + f_it->second.val = F.r_float(); + for (PVectorMapIt v_it = vectors.begin(); v_it != vectors.end(); v_it++) + F.r_fvector3(v_it->second.val); + for (PDomainMapIt d_it = domains.begin(); d_it != domains.end(); d_it++) + d_it->second.Load(F); + for (PBoolMapIt b_it = bools.begin(); b_it != bools.end(); b_it++) + b_it->second.val = F.r_u8(); + for (PIntMapIt i_it = ints.begin(); i_it != ints.end(); i_it++) + i_it->second.val = F.r_s32(); +} + +void EParticleAction::Load2(CInifile &ini, const shared_str §) +{ + u32 ver = ini.r_u32(sect.c_str(), "version"); + actionName = ini.r_string(sect.c_str(), "action_name"); + flags.assign(ini.r_u32(sect.c_str(), "flags")); + + u32 counter = 0; + string256 buff; + for (PFloatMapIt f_it = floats.begin(); f_it != floats.end(); ++f_it, ++counter) + { + xr_sprintf(buff, sizeof(buff), "flt_%04d", counter); + if (ver == 0) + { + if (ini.line_exist(sect.c_str(), buff)) + f_it->second.val = ini.r_float(sect.c_str(), buff); + } + else + f_it->second.val = ini.r_float(sect.c_str(), buff); + } + counter = 0; + for (PVectorMapIt v_it = vectors.begin(); v_it != vectors.end(); ++v_it, ++counter) + { + xr_sprintf(buff, sizeof(buff), "vec_%04d", counter); + v_it->second.val = ini.r_fvector3(sect.c_str(), buff); + } + + counter = 0; + for (PDomainMapIt d_it = domains.begin(); d_it != domains.end(); ++d_it, ++counter) + { + xr_sprintf(buff, sizeof(buff), "domain_%s_%04d", sect.c_str(), counter); + d_it->second.Load2(ini, buff); + } + + counter = 0; + for (PBoolMapIt b_it = bools.begin(); b_it != bools.end(); ++b_it, ++counter) + { + xr_sprintf(buff, sizeof(buff), "bool_%04d", counter); + b_it->second.val = ini.r_bool(sect.c_str(), buff); + } + + counter = 0; + for (PIntMapIt i_it = ints.begin(); i_it != ints.end(); ++i_it, ++counter) + { + xr_sprintf(buff, sizeof(buff), "int_%04d", counter); + i_it->second.val = ini.r_s32(sect.c_str(), buff); + } +} +void EParticleAction::Save(IWriter &F) +{ + F.w_u32(PARTICLE_ACTION_VERSION); + F.w_stringZ(actionName); + F.w_u32(flags.get()); + for (PFloatMapIt f_it = floats.begin(); f_it != floats.end(); f_it++) + F.w_float(f_it->second.val); + for (PVectorMapIt v_it = vectors.begin(); v_it != vectors.end(); v_it++) + F.w_fvector3(v_it->second.val); + for (PDomainMapIt d_it = domains.begin(); d_it != domains.end(); d_it++) + d_it->second.Save(F); + for (PBoolMapIt b_it = bools.begin(); b_it != bools.end(); b_it++) + F.w_u8((u8)b_it->second.val); + for (PIntMapIt i_it = ints.begin(); i_it != ints.end(); i_it++) + F.w_s32(i_it->second.val); +} + +void EParticleAction::Save2(CInifile &ini, const shared_str §) +{ + ini.w_u32(sect.c_str(), "version", PARTICLE_ACTION_VERSION); + ini.w_string(sect.c_str(), "action_name", actionName.c_str()); + ini.w_u32(sect.c_str(), "flags", flags.get()); + + u32 counter = 0; + string256 buff; + for (PFloatMapIt f_it = floats.begin(); f_it != floats.end(); ++f_it, ++counter) + { + xr_sprintf(buff, sizeof(buff), "flt_%04d", counter); + ini.w_float(sect.c_str(), buff, f_it->second.val); + } + counter = 0; + for (PVectorMapIt v_it = vectors.begin(); v_it != vectors.end(); ++v_it, ++counter) + { + xr_sprintf(buff, sizeof(buff), "vec_%04d", counter); + ini.w_fvector3(sect.c_str(), buff, v_it->second.val); + } + + counter = 0; + for (PDomainMapIt d_it = domains.begin(); d_it != domains.end(); ++d_it, ++counter) + { + xr_sprintf(buff, sizeof(buff), "domain_%s_%04d", sect.c_str(), counter); + d_it->second.Save2(ini, buff); + } + + counter = 0; + for (PBoolMapIt b_it = bools.begin(); b_it != bools.end(); ++b_it, ++counter) + { + xr_sprintf(buff, sizeof(buff), "bool_%04d", counter); + ini.w_bool(sect.c_str(), buff, b_it->second.val); + } + + counter = 0; + for (PIntMapIt i_it = ints.begin(); i_it != ints.end(); ++i_it, ++counter) + { + xr_sprintf(buff, sizeof(buff), "int_%04d", counter); + ini.w_s32(sect.c_str(), buff, i_it->second.val); + } +} + +void EParticleAction::FillProp(PropItemVec &items, LPCSTR pref, u32 clr) +{ + PropValue *V = 0; + for (OrderVecIt o_it = orders.begin(); o_it != orders.end(); o_it++) + { + LPCSTR name = o_it->name.c_str(); + switch (o_it->type) + { + case tpDomain: + domains[o_it->name].FillProp(items, PrepareKey(pref, name).c_str(), clr); + break; + case tpVector: + { + PVector &vect = vectors[o_it->name]; + switch (vect.type) + { + case PVector::vNum: + V = PHelper().CreateVector(items, PrepareKey(pref, name).c_str(), &vect.val, vect.mn, vect.mx, 0.001f, 3); + break; + case PVector::vAngle: + V = PHelper().CreateAngle3(items, PrepareKey(pref, name).c_str(), &vect.val, vect.mn, vect.mx, 0.001f, 3); + break; + case PVector::vColor: + V = PHelper().CreateVColor(items, PrepareKey(pref, name).c_str(), &vect.val); + break; + } + } + break; + case tpFloat: + { + PFloat &flt = floats[o_it->name]; + V = PHelper().CreateFloat(items, PrepareKey(pref, name).c_str(), &flt.val, flt.mn, flt.mx, 0.001f, 3); + } + break; + case tpInt: + { + PInt &el = ints[o_it->name]; + V = PHelper().CreateS32(items, PrepareKey(pref, name).c_str(), &el.val, el.mn, el.mx); + } + break; + case tpBool: + V = PHelper().CreateBOOL(items, PrepareKey(pref, name).c_str(), &bools[o_it->name].val); + break; + } + if (V) + V->Owner()->prop_color = clr; + } + V = PHelper().CreateFlag32(items, PrepareKey(pref, "Draw").c_str(), &flags, flDraw); + V->Owner()->prop_color = clr; + V = PHelper().CreateFlag32(items, PrepareKey(pref, "Enabled").c_str(), &flags, flEnabled); + V->Owner()->prop_color = clr; +} +void EParticleAction::appendFloat(LPCSTR name, float v, float mn, float mx) +{ + orders.push_back(SOrder(tpFloat, name)); + floats[name] = PFloat(v, mn, mx); +} +void EParticleAction::appendInt(LPCSTR name, int v, int mn, int mx) +{ + orders.push_back(SOrder(tpInt, name)); + ints[name] = PInt(v, mn, mx); +} +void EParticleAction::appendVector(LPCSTR name, PVector::EType type, float vx, float vy, float vz, float mn, float mx) +{ + orders.push_back(SOrder(tpVector, name)); + vectors[name] = PVector(type, Fvector().set(vx, vy, vz), mn, mx); +} +void EParticleAction::appendDomain(LPCSTR name, PDomain v) +{ + orders.push_back(SOrder(tpDomain, name)); + domains[name] = v; +} + +void EParticleAction::appendBool(LPCSTR name, BOOL v) +{ + orders.push_back(SOrder(tpBool, name)); + bools[name] = PBool(v); +} + +//--------------------------------------------------------------------------- +void pAvoid(IWriter &F, float magnitude, float epsilon, float look_ahead, pDomain D, BOOL allow_rotate) +{ + PAAvoid S; + S.type = PAAvoidID; + + S.positionL = D; + S.position = S.positionL; + S.magnitude = magnitude; + S.epsilon = epsilon; + S.look_ahead = look_ahead; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pBounce(IWriter &F, float friction, float resilience, float cutoff, pDomain D, BOOL allow_rotate) +{ + PABounce S; + S.type = PABounceID; + + S.positionL = D; + S.position = S.positionL; + S.oneMinusFriction = 1.0f - friction; + S.resilience = resilience; + S.cutoffSqr = _sqr(cutoff); + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pCopyVertexB(IWriter &F, BOOL copy_pos) +{ + PACopyVertexB S; + S.type = PACopyVertexBID; + + S.copy_pos = copy_pos; + + F.w_u32(S.type); + S.Save(F); +} + +void pDamping(IWriter &F, const Fvector &damping, + float vlow, float vhigh) +{ + PADamping S; + S.type = PADampingID; + + S.damping = pVector(damping.x, damping.y, damping.z); + S.vlowSqr = _sqr(vlow); + S.vhighSqr = _sqr(vhigh); + + F.w_u32(S.type); + S.Save(F); +} + +void pExplosion(IWriter &F, const Fvector ¢er, float velocity, + float magnitude, float stdev, float epsilon, float age, BOOL allow_rotate) +{ + PAExplosion S; + S.type = PAExplosionID; + + S.centerL = pVector(center.x, center.y, center.z); + S.center = S.centerL; + S.velocity = velocity; + S.magnitude = magnitude; + S.stdev = stdev; + S.epsilon = epsilon; + S.age = age; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + if (S.epsilon < 0.0f) + S.epsilon = EPS_L; + + F.w_u32(S.type); + S.Save(F); +} + +void pFollow(IWriter &F, float magnitude, float epsilon, float max_radius) +{ + PAFollow S; + S.type = PAFollowID; + + S.magnitude = magnitude; + S.epsilon = epsilon; + S.max_radius = max_radius; + + F.w_u32(S.type); + S.Save(F); +} + +void pGravitate(IWriter &F, float magnitude, float epsilon, float max_radius) +{ + PAGravitate S; + S.type = PAGravitateID; + + S.magnitude = magnitude; + S.epsilon = epsilon; + S.max_radius = max_radius; + + F.w_u32(S.type); + S.Save(F); +} + +void pGravity(IWriter &F, const Fvector &dir, BOOL allow_rotate) +{ + PAGravity S; + S.type = PAGravityID; + + S.directionL = pVector(dir.x, dir.y, dir.z); + S.direction = S.directionL; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pJet(IWriter &F, pDomain acc, const Fvector ¢er, + float magnitude, float epsilon, float max_radius, BOOL allow_rotate) +{ + PAJet S; + S.type = PAJetID; + + S.centerL = pVector(center.x, center.y, center.z); + S.center = S.centerL; + S.accL = acc; + S.acc = S.accL; + S.magnitude = magnitude; + S.epsilon = epsilon; + S.max_radius = max_radius; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pKillOld(IWriter &F, float age_limit, BOOL kill_less_than) +{ + PAKillOld S; + S.type = PAKillOldID; + + S.age_limit = age_limit; + S.kill_less_than = kill_less_than; + + F.w_u32(S.type); + S.Save(F); +} + +void pMove(IWriter &F) +{ + PAMove S; + S.type = PAMoveID; + + F.w_u32(S.type); + S.Save(F); +} + +void pMatchVelocity(IWriter &F, float magnitude, float epsilon, float max_radius) +{ + PAMatchVelocity S; + S.type = PAMatchVelocityID; + + S.magnitude = magnitude; + S.epsilon = epsilon; + S.max_radius = max_radius; + + F.w_u32(S.type); + S.Save(F); +} + +void pOrbitLine(IWriter &F, const Fvector &p, const Fvector &axis, + float magnitude, float epsilon, float max_radius, BOOL allow_rotate) +{ + PAOrbitLine S; + S.type = PAOrbitLineID; + + S.pL = pVector(p.x, p.y, p.z); + S.p = S.pL; + S.axisL = pVector(axis.x, axis.y, axis.z); + S.axisL.normalize_safe(); + S.axis = S.axisL; + S.magnitude = magnitude; + S.epsilon = epsilon; + S.max_radius = max_radius; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pOrbitPoint(IWriter &F, const Fvector ¢er, + float magnitude, float epsilon, float max_radius, BOOL allow_rotate) +{ + PAOrbitPoint S; + S.type = PAOrbitPointID; + + S.centerL = pVector(center.x, center.y, center.z); + S.center = S.centerL; + S.magnitude = magnitude; + S.epsilon = epsilon; + S.max_radius = max_radius; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pRandomAccel(IWriter &F, pDomain D, BOOL allow_rotate) +{ + PARandomAccel S; + S.type = PARandomAccelID; + + S.gen_accL = D; + S.gen_acc = S.gen_accL; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pRandomDisplace(IWriter &F, pDomain D, BOOL allow_rotate) +{ + PARandomDisplace S; + S.type = PARandomDisplaceID; + + S.gen_dispL = D; + S.gen_disp = S.gen_dispL; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pRandomVelocity(IWriter &F, pDomain D, BOOL allow_rotate) +{ + PARandomVelocity S; + S.type = PARandomVelocityID; + + S.gen_velL = D; + S.gen_vel = S.gen_velL; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pRestore(IWriter &F, float time_left) +{ + PARestore S; + S.type = PARestoreID; + + S.time_left = time_left; + + F.w_u32(S.type); + S.Save(F); +} + +void pScatter(IWriter &F, const Fvector ¢er, float magnitude, float epsilon, float max_radius, BOOL allow_rotate) +{ + PAScatter S; + S.type = PAScatterID; + + S.centerL = pVector(center.x, center.y, center.z); + S.center = S.centerL; + S.magnitude = magnitude; + S.epsilon = epsilon; + S.max_radius = max_radius; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pSink(IWriter &F, BOOL kill_inside, pDomain D, BOOL allow_rotate) +{ + PASink S; + S.type = PASinkID; + + S.kill_inside = kill_inside; + S.positionL = D; + S.position = S.positionL; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pSinkVelocity(IWriter &F, BOOL kill_inside, pDomain D, BOOL allow_rotate) +{ + PASinkVelocity S; + S.type = PASinkVelocityID; + + S.kill_inside = kill_inside; + S.velocityL = D; + S.velocity = S.velocityL; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pSource(IWriter &F, float particle_rate, pDomain pos, pDomain vel, pDomain rot, pDomain size, BOOL single_size, + pDomain color, float alpha, float age, float age_sigma, float parent_motion, + BOOL allow_rotate) +{ + PASource S; + S.type = PASourceID; + + S.particle_rate = particle_rate; + S.positionL = pos; + S.position = S.positionL; + S.velocityL = vel; + S.velocity = S.velocityL; + S.size = size; + S.rot = rot; + S.color = color; + S.alpha = alpha; + S.age = age; + S.age_sigma = age_sigma; + S.m_Flags.assign((single_size ? PASource::flSingleSize : 0) | PASource::flVertexB_tracks); + S.parent_vel = pVector(0, 0, 0); + S.parent_motion = parent_motion; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pSpeedLimit(IWriter &F, float min_speed, float max_speed) +{ + PASpeedLimit S; + S.type = PASpeedLimitID; + + S.min_speed = min_speed; + S.max_speed = max_speed; + + F.w_u32(S.type); + S.Save(F); +} + +void pTargetColor(IWriter &F, const Fvector &color, float alpha, float scale, float time_from, float time_to) +{ + PATargetColor S; + S.type = PATargetColorID; + + S.color = pVector(color.x, color.y, color.z); + S.alpha = alpha; + S.scale = scale; + S.timeFrom = time_from; + S.timeTo = time_to; + + F.w_u32(S.type); + S.Save(F); +} + +void pTargetSize(IWriter &F, const Fvector &size, const Fvector &scale) +{ + PATargetSize S; + S.type = PATargetSizeID; + + S.size = pVector(size.x, size.y, size.z); + S.scale = pVector(scale.x, scale.y, scale.z); + + F.w_u32(S.type); + S.Save(F); +} + +void pTargetRotate(IWriter &F, const Fvector &rot, float scale) +{ + PATargetRotate S; + S.type = PATargetRotateID; + + S.rot = pVector(rot.x, rot.y, rot.z); + S.scale = scale; + + F.w_u32(S.type); + S.Save(F); +} + +void pTargetVelocity(IWriter &F, const Fvector &vel, float scale, BOOL allow_rotate) +{ + PATargetVelocity S; + S.type = PATargetVelocityID; + + S.velocityL = pVector(vel.x, vel.y, vel.z); + S.velocity = S.velocityL; + S.scale = scale; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pVortex(IWriter &F, const Fvector ¢er, const Fvector &axis, + float magnitude, float epsilon, float max_radius, BOOL allow_rotate) +{ + PAVortex S; + S.type = PAVortexID; + + S.centerL = pVector(center.x, center.y, center.z); + S.center = S.centerL; + S.axisL = pVector(axis.x, axis.y, axis.z); + S.axisL.normalize_safe(); + S.axis = S.axisL; + S.magnitude = magnitude; + S.epsilon = epsilon; + S.max_radius = max_radius; + S.m_Flags.set(ParticleAction::ALLOW_ROTATE, allow_rotate); + + F.w_u32(S.type); + S.Save(F); +} + +void pTurbulence(IWriter &F, float freq, int octaves, float magnitude, float epsilon, const Fvector &offs) +{ + PATurbulence S; + S.type = PATurbulenceID; + + S.frequency = freq; + S.octaves = octaves; + S.magnitude = magnitude; + S.epsilon = epsilon; + S.offset.set(offs); + + S.age = 0.f; + + F.w_u32(S.type); + S.Save(F); +} + +//------------------------------------------------------------------------------ +#define EXPAND_DOMAIN(D) D.type, \ + D.f[0], D.f[1], D.f[2], \ + D.f[3], D.f[4], D.f[5], \ + D.f[6], D.f[7], D.f[8] + +EPAAvoid::EPAAvoid() : EParticleAction(PAPI::PAAvoidID) +{ + actionType = "Avoid"; + actionName = actionType; + appendDomain("Position", PDomain(PDomain::vNum, TRUE, 0x6096FF96)); + appendFloat("Magnitude", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Epsilon", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Look Ahead", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendBool("Allow Rotate", TRUE); +} +void EPAAvoid::Compile(IWriter &F) +{ + pAvoid(F, _float("Magnitude").val, _float("Epsilon").val, _float("Look Ahead").val, pDomain(EXPAND_DOMAIN(_domain("Position"))), _bool("Allow Rotate").val); +} + +EPABounce::EPABounce() : EParticleAction(PAPI::PABounceID) +{ + actionType = "Bounce"; + actionName = actionType; + appendDomain("Position", PDomain(PDomain::vNum, TRUE, 0x6096FEEC)); + appendFloat("Friction", 0.5f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Resilience", 0.1f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Cutoff", 1.f, -P_MAXFLOAT, P_MAXFLOAT); + appendBool("Allow Rotate", TRUE); +} +void EPABounce::Compile(IWriter &F) +{ + pBounce(F, _float("Friction").val, _float("Resilience").val, _float("Cutoff").val, pDomain(EXPAND_DOMAIN(_domain("Position"))), _bool("Allow Rotate").val); +} + +EPACopyVertexB::EPACopyVertexB() : EParticleAction(PAPI::PACopyVertexBID) +{ + actionType = "CopyVertexB"; + actionName = actionType; + appendBool("Copy Position", TRUE); +} +void EPACopyVertexB::Compile(IWriter &F) +{ + pCopyVertexB(F, _bool("Copy Position").val); +} + +EPADamping::EPADamping() : EParticleAction(PAPI::PADampingID) +{ + actionType = "Damping"; + actionName = actionType; + appendVector("Damping", PVector::vNum, 0.f, 0.f, 0.f); + appendFloat("V Low", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("V High", P_MAXFLOAT, -P_MAXFLOAT, P_MAXFLOAT); +} +void EPADamping::Compile(IWriter &F) +{ + pDamping(F, _vector("Damping").val, _float("V Low").val, _float("V High").val); +} + +EPAExplosion::EPAExplosion() : EParticleAction(PAPI::PAExplosionID) +{ + actionType = "Explosion"; + actionName = actionType; + appendVector("Center", PVector::vNum, 0.f, 0.f, 0.f); + appendFloat("Velocity", 1.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Magnitude", 2.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Standart Dev", 3.f, EPS, P_MAXFLOAT); + appendFloat("Epsilon", EPS_L, EPS, P_MAXFLOAT); + appendFloat("Age", 0.f, 0.f, P_MAXFLOAT); + appendBool("Allow Rotate", TRUE); +} +void EPAExplosion::Compile(IWriter &F) +{ + pExplosion(F, _vector("Center").val, _float("Velocity").val, _float("Magnitude").val, _float("Standart Dev").val, _float("Epsilon").val, _float("Age").val, _bool("Allow Rotate").val); +} + +EPAFollow::EPAFollow() : EParticleAction(PAPI::PAFollowID) +{ + actionType = "Follow"; + actionName = actionType; + appendFloat("Magnitude", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Epsilon", EPS_L, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Max Radius", P_MAXFLOAT, -P_MAXFLOAT, P_MAXFLOAT); +} +void EPAFollow::Compile(IWriter &F) +{ + pFollow(F, _float("Magnitude").val, _float("Epsilon").val, _float("Max Radius").val); +} + +EPAGravitate::EPAGravitate() : EParticleAction(PAPI::PAGravitateID) +{ + actionType = "Gravitate"; + actionName = actionType; + appendFloat("Magnitude", 1.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Epsilon", 0.001f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Max Radius", 10.0f, -P_MAXFLOAT, P_MAXFLOAT); +} +void EPAGravitate::Compile(IWriter &F) +{ + pGravitate(F, _float("Magnitude").val, _float("Epsilon").val, _float("Max Radius").val); +} + +EPAGravity::EPAGravity() : EParticleAction(PAPI::PAGravityID) +{ + actionType = "Gravity"; + actionName = actionType; + appendVector("Direction", PVector::vNum, 0.f, -9.8f, 0.f); + appendBool("Allow Rotate", TRUE); +} +void EPAGravity::Compile(IWriter &F) +{ + pGravity(F, _vector("Direction").val, _bool("Allow Rotate").val); +} + +EPAJet::EPAJet() : EParticleAction(PAPI::PAJetID) +{ + actionType = "Jet"; + actionName = actionType; + appendDomain("Accelerate", PDomain(PDomain::vNum, FALSE)); + appendVector("Center", PVector::vNum, 0.f, 0.f, 0.f); + appendFloat("Magnitude", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Epsilon", EPS_L, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Max Radius", P_MAXFLOAT, -P_MAXFLOAT, P_MAXFLOAT); + appendBool("Allow Rotate", TRUE); +} +void EPAJet::Compile(IWriter &F) +{ + pJet(F, pDomain(EXPAND_DOMAIN(_domain("Accelerate"))), _vector("Center").val, _float("Magnitude").val, _float("Epsilon").val, _float("Max Radius").val, _bool("Allow Rotate").val); +} +void EPAJet::Render(const Fmatrix &parent) +{ + EParticleAction::Render(parent); + RCache.set_xform_world(parent); + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawCross(_vector("Center").val, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0x600000ff); +} + +EPAKillOld::EPAKillOld() : EParticleAction(PAPI::PAKillOldID) +{ + actionType = "KillOld"; + actionName = actionType; + appendFloat("Age Limit", 5.f, 0.0f, P_MAXFLOAT); + appendBool("Kill Less Than", FALSE); +} +void EPAKillOld::Compile(IWriter &F) +{ + pKillOld(F, _float("Age Limit").val, _bool("Kill Less Than").val); +} + +EPAMatchVelocity::EPAMatchVelocity() : EParticleAction(PAPI::PAMatchVelocityID) +{ + actionType = "MatchVelocity"; + actionName = actionType; + appendFloat("Magnitude", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Epsilon", EPS_L, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Max Radius", P_MAXFLOAT, -P_MAXFLOAT, P_MAXFLOAT); +} +void EPAMatchVelocity::Compile(IWriter &F) +{ + pMatchVelocity(F, _float("Magnitude").val, _float("Epsilon").val, _float("Max Radius").val); +} + +EPAMove::EPAMove() : EParticleAction(PAPI::PAMoveID) +{ + actionType = "Move"; + actionName = actionType; +} +void EPAMove::Compile(IWriter &F) +{ + pMove(F); +} + +EPAOrbitLine::EPAOrbitLine() : EParticleAction(PAPI::PAOrbitLineID) +{ + actionType = "OrbitLine"; + actionName = actionType; + appendVector("Position", PVector::vNum, 0.f, 0.f, 0.f); + appendVector("Axis", PVector::vNum, 0.f, 0.f, 0.f); + appendFloat("Magnitude", 1.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Epsilon", EPS_L, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Max Radius", P_MAXFLOAT, -P_MAXFLOAT, P_MAXFLOAT); + appendBool("Allow Rotate", TRUE); +} +void EPAOrbitLine::Compile(IWriter &F) +{ + pOrbitLine(F, _vector("Position").val, _vector("Axis").val, _float("Magnitude").val, _float("Epsilon").val, _float("Max Radius").val, _bool("Allow Rotate").val); +} +void EPAOrbitLine::Render(const Fmatrix &parent) +{ + EParticleAction::Render(parent); + RCache.set_xform_world(parent); + EDevice.SetShader(EDevice.m_WireShader); + Fvector p0, p1; + p0 = _vector("Position").val; + p1.add(p0, _vector("Axis").val); + DU_impl.DrawCross(p0, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0x6000ff00); + DU_impl.DrawCross(p1, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0x6000ff00); + DU_impl.DrawLine(p0, p1, 0x6000ff00); +} + +EPAOrbitPoint::EPAOrbitPoint() : EParticleAction(PAPI::PAOrbitPointID) +{ + actionType = "OrbitPoint"; + actionName = actionType; + appendVector("Center", PVector::vNum, 0.f, 0.f, 0.f); + appendFloat("Magnitude", 400.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Epsilon", 0.1f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Max Radius", 100.0f, -P_MAXFLOAT, P_MAXFLOAT); + appendBool("Allow Rotate", TRUE); +} +void EPAOrbitPoint::Compile(IWriter &F) +{ + pOrbitPoint(F, _vector("Center").val, _float("Magnitude").val, _float("Epsilon").val, _float("Max Radius").val, _bool("Allow Rotate").val); +} +void EPAOrbitPoint::Render(const Fmatrix &parent) +{ + EParticleAction::Render(parent); + RCache.set_xform_world(parent); + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawCross(_vector("Center").val, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0x6000ff00); +} + +EPARandomAccel::EPARandomAccel() : EParticleAction(PAPI::PARandomAccelID) +{ + actionType = "RandomAccel"; + actionName = actionType; + appendDomain("Accelerate", PDomain(PDomain::vNum, FALSE)); + appendBool("Allow Rotate", TRUE); +} +void EPARandomAccel::Compile(IWriter &F) +{ + pRandomAccel(F, pDomain(EXPAND_DOMAIN(_domain("Accelerate"))), _bool("Allow Rotate").val); +} + +EPARandomDisplace::EPARandomDisplace() : EParticleAction(PAPI::PARandomDisplaceID) +{ + actionType = "RandomDisplace"; + actionName = actionType; + appendDomain("Displace", PDomain(PDomain::vNum, FALSE)); + appendBool("Allow Rotate", TRUE); +} +void EPARandomDisplace::Compile(IWriter &F) +{ + pRandomDisplace(F, pDomain(EXPAND_DOMAIN(_domain("Displace"))), _bool("Allow Rotate").val); +} + +EPARandomVelocity::EPARandomVelocity() : EParticleAction(PAPI::PARandomVelocityID) +{ + actionType = "RandomVelocity"; + actionName = actionType; + appendDomain("Velocity", PDomain(PDomain::vNum, FALSE)); + appendBool("Allow Rotate", TRUE); +} +void EPARandomVelocity::Compile(IWriter &F) +{ + pRandomVelocity(F, pDomain(EXPAND_DOMAIN(_domain("Velocity"))), _bool("Allow Rotate").val); +} + +EPARestore::EPARestore() : EParticleAction(PAPI::PARestoreID) +{ + actionType = "Restore"; + actionName = actionType; + appendFloat("Time", 0.f, 0.0f, P_MAXFLOAT); +} +void EPARestore::Compile(IWriter &F) +{ + pRestore(F, _float("Time").val); +} + +EPAScatter::EPAScatter() : EParticleAction(PAPI::PAScatterID) +{ + actionType = "Scatter"; + actionName = actionType; + appendVector("Center", PVector::vNum, 0.f, 0.f, 0.f); + appendFloat("Magnitude", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Epsilon", EPS_L, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Max Radius", P_MAXFLOAT, -P_MAXFLOAT, P_MAXFLOAT); + appendBool("Allow Rotate", TRUE); +} +void EPAScatter::Compile(IWriter &F) +{ + pScatter(F, _vector("Center").val, _float("Magnitude").val, _float("Epsilon").val, _float("Max Radius").val, _bool("Allow Rotate").val); +} +void EPAScatter::Render(const Fmatrix &parent) +{ + EParticleAction::Render(parent); + RCache.set_xform_world(parent); + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawCross(_vector("Center").val, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0x600000ff); +} + +EPASink::EPASink() : EParticleAction(PAPI::PASinkID) +{ + actionType = "Sink"; + actionName = actionType; + appendBool("Kill Inside", TRUE); + appendDomain("Domain", PDomain(PDomain::vNum, TRUE, 0x60ff0000)); + appendBool("Allow Rotate", TRUE); +} +void EPASink::Compile(IWriter &F) +{ + pSink(F, _bool("Kill Inside").val, pDomain(EXPAND_DOMAIN(_domain("Domain"))), _bool("Allow Rotate").val); +} + +EPASinkVelocity::EPASinkVelocity() : EParticleAction(PAPI::PASinkVelocityID) +{ + actionType = "SinkVelocity"; + actionName = actionType; + appendBool("Kill Inside", TRUE); + appendDomain("Domain", PDomain(PDomain::vNum, FALSE)); + appendBool("Allow Rotate", TRUE); +} +void EPASinkVelocity::Compile(IWriter &F) +{ + pSinkVelocity(F, _bool("Kill Inside").val, pDomain(EXPAND_DOMAIN(_domain("Domain"))), _bool("Allow Rotate").val); +} + +EPASource::EPASource() : EParticleAction(PAPI::PASourceID) +{ + actionType = "Source"; + actionName = actionType; + appendFloat("Rate", 100.f, -P_MAXFLOAT, P_MAXFLOAT); + appendDomain("Domain", PDomain(PDomain::vNum, TRUE, 0x60FFEBAA)); + appendDomain("Velocity", PDomain(PDomain::vNum, FALSE)); + appendDomain("Rotation", PDomain(PDomain::vAngle, FALSE)); + appendDomain("Size", PDomain(PDomain::vNum, FALSE)); + appendBool("Single Size", FALSE); + appendDomain("Color", PDomain(PDomain::vColor, FALSE, 0x00000000, PAPI::PDPoint, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f)); + appendFloat("Color\\Alpha", 0.f, 0.f, 1.f); + appendFloat("Starting Age", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Age Sigma", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Parent Motion", 0.f, -P_MAXFLOAT, P_MAXFLOAT); + appendBool("Allow Rotate", FALSE); +} +void EPASource::Compile(IWriter &F) +{ + pSource(F, _float("Rate").val, pDomain(EXPAND_DOMAIN(_domain("Domain"))), + pDomain(EXPAND_DOMAIN(_domain("Velocity"))), + pDomain(EXPAND_DOMAIN(_domain("Rotation"))), + pDomain(EXPAND_DOMAIN(_domain("Size"))), _bool("Single Size").val, + pDomain(EXPAND_DOMAIN(_domain("Color"))), _float("Color\\Alpha").val, + _float("Starting Age").val, _float("Age Sigma").val, _float("Parent Motion").val, + _bool("Allow Rotate").val); +} + +EPASpeedLimit::EPASpeedLimit() : EParticleAction(PAPI::PASpeedLimitID) +{ + actionType = "SpeedLimit"; + actionName = actionType; + appendFloat("Min Speed", -1.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Max Speed", 15.0f, -P_MAXFLOAT, P_MAXFLOAT); +} +void EPASpeedLimit::Compile(IWriter &F) +{ + pSpeedLimit(F, _float("Min Speed").val, _float("Max Speed").val); +} + +EPATargetColor::EPATargetColor() : EParticleAction(PAPI::PATargetColorID) +{ + actionType = "TargetColor"; + actionName = actionType; + appendVector("Color", PVector::vColor, 1.f, 1.f, 1.f, 0.f, 1.f); + appendFloat("Alpha", 1.f, 0.0f, 1.0f); + appendFloat("Scale", 1.f, 0.01f, P_MAXFLOAT); + + if (!Core.SocSdk) + { + appendFloat("TimeFrom", 0.0f, 0.0f, 1.0f); + appendFloat("TimeTo", 1.0f, 0.0f, 1.0f); + } +} + +void EPATargetColor::Compile(IWriter &F) +{ + if(Core.SocSdk) + pTargetColor(F, _vector("Color").val, _float("Alpha").val, _float("Scale").val, 0.f, 1.f); + else + pTargetColor(F, _vector("Color").val, _float("Alpha").val, _float("Scale").val, _float("TimeFrom").val, _float("TimeTo").val); +} + +EPATargetSize::EPATargetSize() : EParticleAction(PAPI::PATargetSizeID) +{ + actionType = "TargetSize"; + actionName = actionType; + appendVector("Size", PVector::vNum, 2.f, 2.f, 0.001f, EPS_L); + appendVector("Scale", PVector::vNum, 1.f, 1.f, 0.f); +} + +void EPATargetSize::Compile(IWriter &F) +{ + pTargetSize(F, _vector("Size").val, _vector("Scale").val); +} + +EPATargetRotate::EPATargetRotate() : EParticleAction(PAPI::PATargetRotateID) +{ + actionType = "TargetRotate"; + actionName = actionType; + appendVector("Rotation", PVector::vAngle, 0.f, 0.f, 0.f); + appendFloat("Scale", 1.f, 0.0f, P_MAXFLOAT); +} + +void EPATargetRotate::Compile(IWriter &F) +{ + pTargetRotate(F, _vector("Rotation").val, _float("Scale").val); +} + +EPATargetVelocity::EPATargetVelocity() : EParticleAction(PAPI::PATargetVelocityID) +{ + actionType = "TargetVelocity"; + actionName = actionType; + appendVector("Velocity", PVector::vNum, 0.f, 0.f, 0.f); + appendFloat("Scale", 1.f, 0.0f, P_MAXFLOAT); + appendBool("Allow Rotate", TRUE); +} +void EPATargetVelocity::Compile(IWriter &F) +{ + pTargetVelocity(F, _vector("Velocity").val, _float("Scale").val, _bool("Allow Rotate").val); +} + +EPAVortex::EPAVortex() : EParticleAction(PAPI::PAVortexID) +{ + actionType = "Vortex"; + actionName = actionType; + appendVector("Center", PVector::vNum, 0.f, 0.f, 0.f); + appendVector("Axis", PVector::vNum, 0.f, 1.f, 0.f); + appendFloat("Magnitude", 1.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Epsilon", EPS_L, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Max Radius", 1.0f, -P_MAXFLOAT, P_MAXFLOAT); + appendBool("Allow Rotate", TRUE); +} +void EPAVortex::Compile(IWriter &F) +{ + pVortex(F, _vector("Center").val, _vector("Axis").val, _float("Magnitude").val, _float("Epsilon").val, _float("Max Radius").val, _bool("Allow Rotate").val); +} +void EPAVortex::Render(const Fmatrix &parent) +{ + EParticleAction::Render(parent); +} + +EPATurbulence::EPATurbulence() : EParticleAction(PAPI::PATurbulenceID) +{ + actionType = "Turbulence"; + actionName = actionType; + appendFloat("Frequency", 2.f, -P_MAXFLOAT, P_MAXFLOAT); + appendInt("Octaves", 1, 1); + appendFloat("Magnitude", 10.f, -P_MAXFLOAT, P_MAXFLOAT); + appendFloat("Delta", 0.01f, -P_MAXFLOAT, P_MAXFLOAT); + appendVector("Movement", PVector::vNum, 1, 1, 1); + // - + nval = 0; + age = 0.f; +} + +static const int detail = 16; + +void EPATurbulence::Compile(IWriter &F) +{ + pTurbulence(F, _float("Frequency").val, _int("Octaves").val, _float("Magnitude").val, _float("Delta").val, _vector("Movement").val); + if (nval != 0) + { + for (int i = 0; i < detail; i++) + { + for (int j = 0; j < detail; j++) + delete[] nval[i][j]; + } + for (int i = 0; i < detail; i++) + delete[] nval[i]; + delete[] nval; + nval = 0; + } +} +#include "noise.h" +struct Stp +{ + Fvector p; + Fcolor c; + Stp(const Fvector &_p, const Fcolor &_c) : p(_p), c(_c) {} +}; +DEFINE_VECTOR(Stp, StpVec, StpVecIt); +static StpVec pts; +IC bool sort_tp_pred(const Stp &x, const Stp &y) +{ + float a = EDevice.vCameraPosition.distance_to_sqr(x.p); + float b = EDevice.vCameraPosition.distance_to_sqr(y.p); + return a > b; +} +void EPATurbulence::Render(const Fmatrix &parent) +{ + EParticleAction::Render(parent); + Fvector vec; + int i, j, k; + int kb; + int ke; + Fcolor clr; + + float draw_area = 1; + float csz = ((draw_area * 2.f) / detail) / 2.f; + bool draw_p = true, draw_n = true; + pts.clear(); + + age += EDevice.fTimeDelta; + // fill + if (nval == 0) + { + nval = new float **[detail]; + for (i = 0; i < detail; i++) + { + nval[i] = new float *[detail]; + for (j = 0; j < detail; j++) + nval[i][j] = new float[detail]; + } + } + { + for (i = 0; i < detail; i++) + { + for (j = 0; j < detail; j++) + { + for (k = 0; k < detail; k++) + { + Fvector &offs = _vector("Movement").val; + vec[0] = (((float)i / (float)detail) - 0.5) * 2.0 * (float)draw_area + offs.x * age; + vec[1] = (((float)j / (float)detail) - 0.5) * 2.0 * (float)draw_area + offs.y * age; + vec[2] = (((float)k / (float)detail) - 0.5) * 2.0 * (float)draw_area + offs.z * age; + nval[i][j][k] = fractalsum3(vec, _float("Frequency").val, _int("Octaves").val); + } + } + } + } + + for (i = 0; i < detail; i++) + { + for (j = 0; j < detail; j++) + { + // if(1){ + kb = 0; + ke = detail; + // }else{ + // kb = detail/2; + // ke = detail/2+1; + // } + for (k = kb; k < ke; k++) + { + vec[0] = (((float)i / (float)detail) - 0.5) * 2.0 * draw_area; + vec[1] = (((float)j / (float)detail) - 0.5) * 2.0 * draw_area; + vec[2] = (((float)k / (float)detail) - 0.5) * 2.0 * draw_area; + + clr.set(0, 0, 0, 0); + if (draw_p && draw_n) + { + if (nval[i][j][k] > 0.0) + { + clr.r = nval[i][j][k]; + clr.a = nval[i][j][k]; + } + else + { + clr.b = fabs(nval[i][j][k]); + clr.a = fabs(nval[i][j][k]); + } + } + else if (draw_p) + { + if (nval[i][j][k] > 0.0) + clr.set(static_cast(nval[i][j][k])); + } + else if (draw_n) + { + if (nval[i][j][k] < 0.0) + clr.set(static_cast(fabs(nval[i][j][k]))); + } + pts.push_back(Stp(vec, clr)); + } + } + } + std::sort(pts.begin(), pts.end(), sort_tp_pred); + EDevice.SetShader(EDevice.m_SelectionShader); + RCache.set_xform_world(Fidentity); + for (StpVecIt it = pts.begin(); it != pts.end(); it++) + DU_impl.DrawCross(it->p, csz, csz, csz, csz, csz, csz, it->c.get(), false); +} + +void PS::CPEDef::Render(const Fmatrix &parent) +{ + Fmatrix trans; + trans.translate(parent.c); + for (EPAVecIt it = m_EActionList.begin(); it != m_EActionList.end(); it++) + if ((*it)->flags.is(EParticleAction::flDraw | EParticleAction::flEnabled)) + { + PBool *ar = (*it)->_bool_safe("Allow Rotate"); + (*it)->Render((ar && ar->val) ? parent : trans); + } +} diff --git a/src/editors/ParticleEditor/ParticleEffectEditor.cpp b/src/editors/ParticleEditor/ParticleEffectEditor.cpp new file mode 100644 index 00000000000..c5d1b6f509e --- /dev/null +++ b/src/editors/ParticleEditor/ParticleEffectEditor.cpp @@ -0,0 +1,407 @@ +#include "stdafx.h" + +#ifdef _PARTICLE_EDITOR + +#include "Layers/xrRender/ParticleEffect.h" +#include "..\xrEcore\Editor\ParticleEffectActions.h" +#include "ui_particletools.h" + +BOOL PS::CPEDef::Equal(const CPEDef *pe) +{ + if (!m_Flags.equal(pe->m_Flags)) + return FALSE; + if (!m_ShaderName.equal(pe->m_ShaderName)) + return FALSE; + if (!m_TextureName.equal(pe->m_TextureName)) + return FALSE; + if (0 != memcmp(&m_Frame, &pe->m_Frame, sizeof(m_Frame))) + return FALSE; + if (!fsimilar(m_fTimeLimit, pe->m_fTimeLimit)) + return FALSE; + if (m_MaxParticles != pe->m_MaxParticles) + return FALSE; + if (m_Actions.size() != pe->m_Actions.size()) + return FALSE; + if (!m_VelocityScale.similar(pe->m_VelocityScale)) + return FALSE; + if (!fsimilar(m_fCollideOneMinusFriction, pe->m_fCollideOneMinusFriction)) + return FALSE; + if (!fsimilar(m_fCollideResilience, pe->m_fCollideResilience)) + return FALSE; + if (!fsimilar(m_fCollideSqrCutoff, pe->m_fCollideSqrCutoff)) + return FALSE; + return TRUE; +} + +void PS::CPEDef::Copy(const CPEDef &src) +{ + m_Name = src.m_Name; + m_Flags = src.m_Flags; + m_ShaderName = src.m_ShaderName; + m_TextureName = src.m_TextureName; + m_Frame = src.m_Frame; + m_fTimeLimit = src.m_fTimeLimit; + m_MaxParticles = src.m_MaxParticles; + m_CachedShader = src.m_CachedShader; + m_VelocityScale.set(src.m_VelocityScale); + m_fCollideOneMinusFriction = src.m_fCollideOneMinusFriction; + m_fCollideResilience = src.m_fCollideResilience; + m_fCollideSqrCutoff = src.m_fCollideSqrCutoff; + + m_EActionList.resize(src.m_EActionList.size()); + for (u32 k = 0; k < src.m_EActionList.size(); k++) + { + PAPI::PActionEnum type = src.m_EActionList[k]->type; + m_EActionList[k] = pCreateEAction(type); + *m_EActionList[k] = *src.m_EActionList[k]; + } + Compile(m_EActionList); +} + +void PS::CPEDef::OnControlClick(ButtonValue *B, bool &bDataModified, bool &bSafe) +{ + switch (B->btn_num) + { + case 0: + PTools->PlayCurrent(); + break; + case 1: + PTools->StopCurrent(false); + break; + case 2: + PTools->StopCurrent(true); + break; + } + bDataModified = false; +} + +void PS::CPEDef::FindActionByName(LPCSTR new_name, bool &res) +{ + res = false; + for (EPAVecIt s_it = m_EActionList.begin(); s_it != m_EActionList.end(); s_it++) + if (0 == stricmp(new_name, *(*s_it)->actionName)) + { + res = true; + break; + }; +} + +void PS::CPEDef::FillActionList(ChooseItemVec &items, void *param) +{ + for (int i = 0; actions_token[i].name; i++) + items.push_back(SChooseItem(actions_token[i].name, actions_token[i].info)); +} +void PS::CPEDef::OnDrawUI() +{ + if (m_EditChoose) + { + bool change; + shared_str result; + if (UIChooseForm::GetResult(change, result)) + { + if (change) + { + for (int i = 0; actions_token[i].name; i++) + { + if (0 == strcmp(actions_token[i].name, result.c_str())) + { + EParticleAction *A = pCreateEAction((PAPI::PActionEnum)actions_token[i].id); + xr_string pref = xr_string(*A->actionName); + strlwr((char *)pref.data()); + for (i = 0; true; i++) + { + bool result; + xr_string temp; + if (i == 0) + { + temp = pref; + } + else + { + temp = make_string("%s_%02d", pref.c_str(), i - 1); + } + FindActionByName(temp.c_str(), result); + if (!result) + { + pref = temp; + break; + } + } + A->actionName = pref.c_str(); + m_EActionList.push_back(A); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + + break; + } + } + } + + m_EditChoose = false; + } + UIChooseForm::Update(); + } +} +void PS::CPEDef::OnActionsClick(ButtonValue *B, bool &bDataModified, bool &bSafe) +{ + switch (B->btn_num) + { + case 0: + { + m_EditChoose = true; + UIChooseForm::SelectItem(smCustom, 1, 0, TOnChooseFillItems(this, &PS::CPEDef::FillActionList)); + } + break; + } + bDataModified = false; +} + +void PS::CPEDef::OnFlagChange(PropValue *sender) +{ + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void PS::CPEDef::OnShaderChange(PropValue *sender) +{ + m_CachedShader.destroy(); + if (m_ShaderName.size() && m_TextureName.size()) + m_CachedShader.create(m_ShaderName.c_str(), m_TextureName.c_str()); +} + +void PS::CPEDef::OnFrameResize(PropValue *sender) +{ + m_Frame.m_iFrameDimX = iFloor(1.f / m_Frame.m_fTexSize.x); +} + +void PS::CPEDef::CollisionFrictionOnBeforeEdit(PropValue *sender, float &edit_val) +{ + edit_val = 1.f - edit_val; +} +bool PS::CPEDef::CollisionFrictionOnAfterEdit(PropValue *sender, float &edit_val) +{ + edit_val = 1.f - edit_val; + return true; +} +void PS::CPEDef::CollisionFrictionOnDraw(PropValue *sender, xr_string &draw_val) +{ + FloatValue *V = dynamic_cast(sender); + VERIFY(V); + draw_sprintf(draw_val, 1.f - V->GetValue(), V->dec); +} +void PS::CPEDef::CollisionCutoffOnBeforeEdit(PropValue *sender, float &edit_val) +{ + edit_val = _sqrt(edit_val); +} +bool PS::CPEDef::CollisionCutoffOnAfterEdit(PropValue *sender, float &edit_val) +{ + edit_val = (edit_val) * (edit_val); + return true; +} +void PS::CPEDef::CollisionCutoffOnDraw(PropValue *sender, xr_string &draw_val) +{ + FloatValue *V = dynamic_cast(sender); + VERIFY(V); + draw_sprintf(draw_val, _sqrt(V->GetValue()), V->dec); +} + +void PS::CPEDef::OnActionEditClick(ButtonValue *B, bool &bDataModified, bool &bSafe) +{ + bDataModified = false; + int idx = B->tag; + switch (B->btn_num) + { + case 0: // up + if (idx > 0) + { + EParticleAction *E = m_EActionList[idx - 1]; + m_EActionList[idx - 1] = m_EActionList[idx]; + m_EActionList[idx] = E; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + bDataModified = true; + } + break; + case 1: // down + if (idx < (int(m_EActionList.size()) - 1)) + { + EParticleAction *E = m_EActionList[idx + 1]; + m_EActionList[idx + 1] = m_EActionList[idx]; + m_EActionList[idx] = E; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + bDataModified = true; + } + bDataModified = true; + break; + case 2: + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Remove action?") == mrYes) + { + PTools->RemoveAction(idx); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + bDataModified = true; + } + break; + } +} + +bool PS::CPEDef::OnAfterActionNameEdit(PropValue *sender, shared_str &edit_val) +{ + bool found = false; + xr_string tmp(edit_val.c_str()); + strlwr((char *)tmp.data()); + edit_val = tmp.c_str(); + FindActionByName(edit_val.c_str(), found); + return !found; +} + +xr_string _item_to_select_after_edit; + +bool PS::CPEDef::NameOnAfterEdit(PropValue *sender, shared_str &edit_val) +{ + for (PS::PGDIt g_it = ::Render->PSLibrary.FirstPGD(); g_it != ::Render->PSLibrary.LastPGD(); ++g_it) + { + PS::CPGDef *pg = (*g_it); + xr_vector::const_iterator pe_it = pg->m_Effects.begin(); + xr_vector::const_iterator pe_it_e = pg->m_Effects.end(); + + for (; pe_it != pe_it_e; ++pe_it) + { + PS::CPGDef::SEffect *Eff = (*pe_it); + if (Eff->m_EffectName == this->m_Name) + Eff->m_EffectName = edit_val; + + if (Eff->m_OnPlayChildName == this->m_Name) + Eff->m_OnPlayChildName = edit_val; + + if (Eff->m_OnBirthChildName == this->m_Name) + Eff->m_OnBirthChildName = edit_val; + + if (Eff->m_OnDeadChildName == this->m_Name) + Eff->m_OnDeadChildName = edit_val; + } + } + _item_to_select_after_edit = edit_val.c_str(); + return true; +} + +void PS::CPEDef::FillProp(LPCSTR pref, ::PropItemVec &items, ::ListItem *owner) +{ + ButtonValue *B; + PropValue *P = 0; + + B = PHelper().CreateButton(items, PrepareKey(pref, "Control"), "Play(F5),Stop(F6),Stop...(F7)", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &PS::CPEDef::OnControlClick); + RTextValue *R = PHelper().CreateRText(items, PrepareKey(pref, "Name"), &m_Name); + R->OnAfterEditEvent.bind(this, &PS::CPEDef::NameOnAfterEdit); + + // max particles + PHelper().CreateS32(items, PrepareKey(pref, "Max Particles"), &m_MaxParticles, 0, 100000); + // P->OnChangeEvent = OnFlagChange; + // time limit + P = PHelper().CreateFlag32(items, PrepareKey(pref, "Time Limit"), &m_Flags, dfTimeLimit); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnFlagChange); + if (m_Flags.is(dfTimeLimit)) + PHelper().CreateFloat(items, PrepareKey(pref, "Time Limit\\Value (sec)"), &m_fTimeLimit, 0, 10000.f); + // sprite + P = PHelper().CreateFlag32(items, PrepareKey(pref, "Sprite"), &m_Flags, dfSprite); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnFlagChange); + if (m_Flags.is(dfSprite)) + { + P = PHelper().CreateChoose(items, PrepareKey(pref, "Sprite\\Texture"), &m_TextureName, smTexture, 0, 0, 2); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnShaderChange); + P = PHelper().CreateChoose(items, PrepareKey(pref, "Sprite\\Shader"), &m_ShaderName, smEShader); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnShaderChange); + // frame + P = PHelper().CreateFlag32(items, PrepareKey(pref, "Sprite\\Culling"), &m_Flags, dfCulling); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnFlagChange); + if (m_Flags.is(CPEDef::dfCulling)) + PHelper().CreateFlag32(items, PrepareKey(pref, "Sprite\\Culling\\CCW"), &m_Flags, dfCullCCW); + P = PHelper().CreateFlag32(items, PrepareKey(pref, "Sprite\\Frame"), &m_Flags, dfFramed); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnFlagChange); + if (m_Flags.is(dfFramed)) + { + PHelper().CreateFlag32(items, PrepareKey(pref, "Sprite\\Frame\\Random Init"), &m_Flags, dfRandomFrame); + PHelper().CreateS32(items, PrepareKey(pref, "Sprite\\Frame\\Count"), &m_Frame.m_iFrameCount, 1, 256); + P = PHelper().CreateFloat(items, PrepareKey(pref, "Sprite\\Frame\\Size U (0..1)"), &m_Frame.m_fTexSize.x, EPS_S, 1.f, 0.001f, 8); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnFrameResize); + PHelper().CreateFloat(items, PrepareKey(pref, "Sprite\\Frame\\Size V (0..1)"), &m_Frame.m_fTexSize.y, EPS_S, 1.f, 0.001f, 8); + // animate + P = PHelper().CreateFlag32(items, PrepareKey(pref, "Sprite\\Animated"), &m_Flags, dfAnimated); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnFlagChange); + if (m_Flags.is(dfAnimated)) + { + PHelper().CreateFlag32(items, PrepareKey(pref, "Sprite\\Animated\\Random Playback"), &m_Flags, dfRandomPlayback); + PHelper().CreateFloat(items, PrepareKey(pref, "Sprite\\Animated\\Speed"), &m_Frame.m_fSpeed, 0.f, 1000.f); + } + } + } + // align to path + P = PHelper().CreateFlag32(items, PrepareKey(pref, "Movement\\Align To Path"), &m_Flags, dfAlignToPath); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnFlagChange); + if (m_Flags.is(dfAlignToPath)) + { + PHelper().CreateFlag32(items, PrepareKey(pref, "Movement\\Align To Path\\Face Align"), &m_Flags, dfFaceAlign); + PHelper().CreateFlag32(items, PrepareKey(pref, "Movement\\Align To Path\\Default World Align"), &m_Flags, dfWorldAlign); + PHelper().CreateAngle3(items, PrepareKey(pref, "Movement\\Align To Path\\Default Rotate"), &m_APDefaultRotation); + } + // velocity scale + P = PHelper().CreateFlag32(items, PrepareKey(pref, "Movement\\Velocity Scale"), &m_Flags, dfVelocityScale); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnFlagChange); + if (m_Flags.is(dfVelocityScale)) + PHelper().CreateVector(items, PrepareKey(pref, "Movement\\Velocity Scale\\Value"), &m_VelocityScale, -1000.f, 1000.f); + // collision + P = PHelper().CreateFlag32(items, PrepareKey(pref, "Movement\\Collision"), &m_Flags, dfCollision); + P->OnChangeEvent.bind(this, &PS::CPEDef::OnFlagChange); + FloatValue *V = 0; + if (m_Flags.is(dfCollision)) + { + PHelper().CreateFlag32(items, PrepareKey(pref, "Movement\\Collision\\Collide With Dynamic"), &m_Flags, dfCollisionDyn); + PHelper().CreateFlag32(items, PrepareKey(pref, "Movement\\Collision\\Destroy On Contact"), &m_Flags, dfCollisionDel); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Movement\\Collision\\Friction"), &m_fCollideOneMinusFriction, 0.f, 1.f); + V->OnBeforeEditEvent.bind(this, &PS::CPEDef::CollisionFrictionOnBeforeEdit); + V->OnAfterEditEvent.bind(this, &PS::CPEDef::CollisionFrictionOnAfterEdit); + V->Owner()->OnDrawTextEvent.bind(this, &PS::CPEDef::CollisionFrictionOnDraw); + PHelper().CreateFloat(items, PrepareKey(pref, "Movement\\Collision\\Resilence"), &m_fCollideResilience, 0.f, 1.f); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Movement\\Collision\\Cutoff"), &m_fCollideSqrCutoff, 0.f, P_MAXFLOAT); + V->OnBeforeEditEvent.bind(this, &PS::CPEDef::CollisionCutoffOnBeforeEdit); + V->OnAfterEditEvent.bind(this, &PS::CPEDef::CollisionCutoffOnAfterEdit); + V->Owner()->OnDrawTextEvent.bind(this, &PS::CPEDef::CollisionCutoffOnDraw); + } + // actions + B = ::PHelper().CreateButton(items, PrepareKey(pref, "Actions\\Edit"), "Append", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &PS::CPEDef::OnActionsClick); + for (EPAVecIt s_it = m_EActionList.begin(); s_it != m_EActionList.end(); s_it++) + { + u32 clr = (*s_it)->flags.is(EParticleAction::flEnabled) ? 0xFF000000 : 0xFFC0C0C0; + shared_str a_pref = PrepareKey(pref, "Actions", make_string("%s (%s)", *(*s_it)->actionType, *(*s_it)->actionName).c_str()); + + ButtonValue *B = PHelper().CreateButton(items, a_pref, "Up,Down,Remove", ButtonValue::flFirstOnly); + B->tag = (s_it - m_EActionList.begin()); + B->Owner()->prop_color = clr; + B->OnBtnClickEvent.bind(this, &PS::CPEDef::OnActionEditClick); + + RTextValue *R; + R = PHelper().CreateRText(items, PrepareKey(a_pref.c_str(), "Name"), &(*s_it)->actionName); + R->OnAfterEditEvent.bind(this, &PS::CPEDef::OnAfterActionNameEdit); + R->Owner()->prop_color = clr; + (*s_it)->FillProp(items, a_pref.c_str(), clr); + } +} +bool PS::CPEDef::Validate(bool bMsg) +{ + bool have_kill_old = false; + + u32 i = 0; + for (; i < m_EActionList.size(); ++i) + if (m_EActionList[i]->type == PAPI::PAKillOldID) + { + have_kill_old = true; + if (i != 0) + { + std::swap(m_EActionList[i], m_EActionList[0]); + } + break; + } + + if (bMsg && (false == have_kill_old)) + Msg("!.'%s': dosn't contains 'Kill Old' action.", *m_Name); + return have_kill_old; +} +#endif diff --git a/src/editors/ParticleEditor/ParticleGroupEditor.cpp b/src/editors/ParticleEditor/ParticleGroupEditor.cpp new file mode 100644 index 00000000000..637c5b57b79 --- /dev/null +++ b/src/editors/ParticleEditor/ParticleGroupEditor.cpp @@ -0,0 +1,213 @@ +#include "stdafx.h" +#include "Layers/xrRender/ParticleGroup.h" +#include "ui_particletools.h" + +BOOL PS::CPGDef::SEffect::Equal(const SEffect &src) +{ + if (!m_Flags.equal(src.m_Flags)) + return FALSE; + if (!m_EffectName.equal(src.m_EffectName)) + return FALSE; + if (!fsimilar(m_Time0, src.m_Time0)) + return FALSE; + if (!fsimilar(m_Time1, src.m_Time1)) + return FALSE; + return TRUE; +} + +BOOL PS::CPGDef::Equal(const CPGDef *pg) +{ + if (!m_Flags.equal(pg->m_Flags)) + return FALSE; + if (!fsimilar(m_fTimeLimit, pg->m_fTimeLimit)) + return FALSE; + if (m_Effects.size() != pg->m_Effects.size()) + return FALSE; + auto s_it = m_Effects.begin(); + for (auto d_it = m_Effects.begin(); d_it != m_Effects.end(); s_it++, d_it++) + if (!(*s_it)->Equal(**d_it)) + return FALSE; + return TRUE; +} + +bool PS::CPGDef::Validate(bool bMsg) +{ + bool failed = false; + + xr_vector::const_iterator pe_it = m_Effects.begin(); + xr_vector::const_iterator pe_it_e = m_Effects.end(); + + for (; pe_it != pe_it_e; ++pe_it) + { + PS::CPGDef::SEffect *Eff = (*pe_it); + PS::CPEDef *ped = ::Render->PSLibrary.FindPED(Eff->m_EffectName.c_str()); + if (!ped) + { + failed = failed || true; + Msg("Validation FAILED (non-existent effect used) group[%s] effect[%s]", m_Name.c_str(), Eff->m_EffectName.c_str()); + break; + } + + if (Eff->m_Flags.test(SEffect::flOnPlayChild) && Eff->m_OnPlayChildName.size() == 0) + failed = failed || true; + if (Eff->m_Flags.test(SEffect::flOnBirthChild) && Eff->m_OnBirthChildName.size() == 0) + failed = failed || true; + if (Eff->m_Flags.test(SEffect::flOnDeadChild) && Eff->m_OnDeadChildName.size() == 0) + failed = failed || true; + + if (failed && bMsg) + Msg("Validation FAILED (incorrect child event settings) group[%s] effect[%s]", m_Name.c_str(), Eff->m_EffectName.c_str()); + if (failed) + break; + } + return !failed; +} + +void PS::CPGDef::OnEffectsEditClick(ButtonValue *B, bool &bDataModified, bool &bSafe) +{ + switch (B->btn_num) + { + case 0: + m_Effects.push_back(xr_new()); + m_Effects.back()->m_Flags.set(CPGDef::SEffect::flEnabled, FALSE); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + OnParamsChange(B); + bDataModified = true; + break; + } +} + +void PS::CPGDef::OnEffectTypeChange(PropValue *sender) +{ + ExecCommand(COMMAND_UPDATE_PROPERTIES); + OnParamsChange(sender); +} + +void PS::CPGDef::OnControlClick(ButtonValue *B, bool &bDataModified, bool &bSafe) +{ + switch (B->btn_num) + { + case 0: + PTools->PlayCurrent(); + break; + case 1: + PTools->StopCurrent(false); + break; + case 2: + PTools->StopCurrent(true); + break; + } + bDataModified = false; +} + +void PS::CPGDef::OnEffectEditClick(ButtonValue *B, bool &bDataModified, bool &bSafe) +{ + switch (B->btn_num) + { + case 0: + PTools->PlayCurrent(B->tag); + bDataModified = false; + break; + case 1: + { + CPGDef::SEffect *eff = *(m_Effects.begin() + B->tag); + VERIFY(eff); + PTools->SelectEffect(*eff->m_EffectName); + bDataModified = false; + bSafe = true; + } + break; + case 2: + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Remove effect?") == mrYes) + { + SEffect *eff = *(m_Effects.begin() + B->tag); + xr_delete(eff); + m_Effects.erase(m_Effects.begin() + B->tag); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + OnParamsChange(B); + bDataModified = true; + bSafe = true; + } + else + { + bDataModified = false; + } + break; + } +} + +void PS::CPGDef::OnParamsChange(PropValue *sender) +{ + PTools->SetCurrentPG(0); + PTools->SetCurrentPG(this); +} + +void PS::CPGDef::FillProp(LPCSTR pref, ::PropItemVec &items, ::ListItem *owner) +{ + ButtonValue *B; + B = PHelper().CreateButton(items, PrepareKey(pref, "Control"), "Play,Stop,Stop...", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &PS::CPGDef::OnControlClick); + B = PHelper().CreateButton(items, PrepareKey(pref, "Edit"), "Append Effect", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &PS::CPGDef::OnEffectsEditClick); + PropValue *V; + PHelper().CreateName(items, PrepareKey(pref, "Name"), &m_Name, owner); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Time Limit (s)"), &m_fTimeLimit, -1.f, 1000.f); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + + u32 i = 0; + for (auto it = m_Effects.begin(); it != m_Effects.end(); ++it, ++i) + { + u32 clr = (*it)->m_Flags.is(CPGDef::SEffect::flEnabled) ? 0xFF000000 : 0xFFC0C0C0; + auto nm = make_string("Effect #%d", i + 1); + + B = PHelper().CreateButton(items, PrepareKey(pref, nm.c_str()), "Preview,Select,Remove", ButtonValue::flFirstOnly); + B->tag = it - m_Effects.begin(); + B->OnBtnClickEvent.bind(this, &PS::CPGDef::OnEffectEditClick); + B->Owner()->prop_color = clr; + V = PHelper().CreateChoose(items, PrepareKey(pref, nm.c_str(), "Name"), &(*it)->m_EffectName, smPE); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + V = PHelper().CreateFloat(items, PrepareKey(pref, nm.c_str(), "Start Time (s)"), &(*it)->m_Time0, 0.f, 1000.f); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + V = PHelper().CreateFloat(items, PrepareKey(pref, nm.c_str(), "End Time (s)"), &(*it)->m_Time1, 0.f, 1000.f); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + V = PHelper().CreateFlag32(items, PrepareKey(pref, nm.c_str(), "Deferred Stop"), &(*it)->m_Flags, SEffect::flDefferedStop); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + V = PHelper().CreateFlag32(items, PrepareKey(pref, nm.c_str(), "Enabled"), &(*it)->m_Flags, SEffect::flEnabled); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + V = PHelper().CreateFlag32(items, PrepareKey(pref, nm.c_str(), "Children\\On Birth"), &(*it)->m_Flags, SEffect::flOnBirthChild); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + if ((*it)->m_Flags.is(SEffect::flOnBirthChild)) + { + V = PHelper().CreateChoose(items, PrepareKey(pref, nm.c_str(), "Children\\On Birth\\Effect Name"), &(*it)->m_OnBirthChildName, smPE); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + } + V = PHelper().CreateFlag32(items, PrepareKey(pref, nm.c_str(), "Children\\On Play"), &(*it)->m_Flags, SEffect::flOnPlayChild); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + if ((*it)->m_Flags.is(SEffect::flOnPlayChild)) + { + V = PHelper().CreateChoose(items, PrepareKey(pref, nm.c_str(), "Children\\On Play\\Effect Name"), &(*it)->m_OnPlayChildName, smPE); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + V = PHelper().CreateFlag32(items, PrepareKey(pref, nm.c_str(), "Children\\On Play\\Play After Stop"), &(*it)->m_Flags, SEffect::flOnPlayChildRewind); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + } + V = PHelper().CreateFlag32(items, PrepareKey(pref, nm.c_str(), "Children\\On Dead"), &(*it)->m_Flags, SEffect::flOnDeadChild); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + if ((*it)->m_Flags.is(SEffect::flOnDeadChild)) + { + V = PHelper().CreateChoose(items, PrepareKey(pref, nm.c_str(), "Children\\On Dead\\Effect Name"), &(*it)->m_OnDeadChildName, smPE); + V->OnChangeEvent.bind(this, &PS::CPGDef::OnParamsChange); + V->Owner()->prop_color = clr; + } + } +} diff --git a/src/editors/ParticleEditor/StatGraph.cpp b/src/editors/ParticleEditor/StatGraph.cpp new file mode 100644 index 00000000000..c4b56fadf6d --- /dev/null +++ b/src/editors/ParticleEditor/StatGraph.cpp @@ -0,0 +1,377 @@ +#include "stdafx.h" +#include "xrCommon/xr_deque.h" +#include "StatGraph.h" + +CStatGraph::CStatGraph() +{ + EDevice.seqRender.Add(this, REG_PRIORITY_LOW - 1000); + OnDeviceCreate(); + mn = 0; + mx = 1; + max_item_count = 1; + lt.set(0, 0); + rb.set(200, 200); + grid.set(1, 1); + grid_color = 0xFF000000; + rect_color = 0xFF000000; + grid_step.set(1, 1); + + AppendSubGraph(stCurve); +} + +CStatGraph::~CStatGraph() +{ + EDevice.seqRender.Remove(this); + OnDeviceDestroy(); + m_Markers.clear(); +} + +void CStatGraph::OnDeviceCreate() +{ + hGeomLine.create(FVF::F_TL0uv, RImplementation.Vertex.Buffer(), RImplementation.Index.Buffer()); + hGeomTri.create(FVF::F_TL0uv, RImplementation.Vertex.Buffer(), RImplementation.QuadIB); +} + +void CStatGraph::OnDeviceDestroy() +{ + hGeomLine.destroy(); + hGeomTri.destroy(); +} + +void CStatGraph::RenderBack() +{ + // draw back + u32 dwOffset, dwCount; + FVF::TL0uv* pv_start = (FVF::TL0uv*)RImplementation.Vertex.Lock(4, hGeomTri->vb_stride, dwOffset); + FVF::TL0uv *pv = pv_start; + // base rect + pv->set(lt.x, rb.y, back_color); + pv++; // 0 + pv->set(lt.x, lt.y, back_color); + pv++; // 1 + pv->set(rb.x, rb.y, back_color); + pv++; // 2 + pv->set(rb.x, lt.y, back_color); + pv++; // 3 + // render + dwCount = u32(pv - pv_start); + RImplementation.Vertex.Unlock(dwCount, hGeomTri->vb_stride); + RCache.set_Geometry(hGeomTri); + RCache.Render(D3DPT_TRIANGLELIST, dwOffset, 0, dwCount, 0, dwCount / 2); + + // draw rect + pv_start = (FVF::TL0uv*)RImplementation.Vertex.Lock(5, hGeomLine->vb_stride, dwOffset); + pv = pv_start; + // base rect + pv->set(lt.x, lt.y, rect_color); + pv++; // 0 + pv->set(rb.x - 1, lt.y, rect_color); + pv++; // 1 + pv->set(rb.x - 1, rb.y, rect_color); + pv++; // 2 + pv->set(lt.x, rb.y, rect_color); + pv++; // 3 + pv->set(lt.x, lt.y, rect_color); + pv++; // 0 + // render + dwCount = u32(pv - pv_start); + RImplementation.Vertex.Unlock(dwCount, hGeomLine->vb_stride); + RCache.set_Geometry(hGeomLine); + RCache.Render(D3DPT_LINESTRIP, dwOffset, 4); + + // draw grid + float elem_factor = float(rb.y - lt.y) / float(mx - mn); + float base_y = float(rb.y) + (mn * elem_factor); + + int PNum_H_LinesUp = int((base_y - float(lt.y)) / (grid_step.y * elem_factor)); + int PNum_H_LinesDwn = u32((float(rb.y) - base_y) / (grid_step.y * elem_factor)); + int Num_H_LinesUp = (grid.y < PNum_H_LinesUp) ? grid.y : PNum_H_LinesUp; + int Num_H_LinesDwn = (grid.y < PNum_H_LinesUp) ? grid.y : PNum_H_LinesDwn; + + pv_start = (FVF::TL0uv*)RImplementation.Vertex.Lock( + 2 + 2 * grid.x + Num_H_LinesUp * 2 + Num_H_LinesDwn * 2, + hGeomLine->vb_stride, dwOffset); + pv = pv_start; + // base Coordinate Line + pv->set(lt.x, int(base_y), base_color); + pv++; // 0 + pv->set(rb.x, int(base_y), base_color); + pv++; // 0 + // grid + // float grid_offs_x = float(rb.x-lt.x)/float(grid.x+1); + // float grid_offs_y = float(rb.y-lt.y)/float(grid.y+1); + for (int g_x = 1; g_x <= grid.x; g_x++) + { + pv->set(int(lt.x + g_x * grid_step.x * elem_factor), lt.y, grid_color); + pv++; + pv->set(int(lt.x + g_x * grid_step.x * elem_factor), rb.y, grid_color); + pv++; + } + for (int g_y = 1; g_y <= Num_H_LinesDwn; g_y++) + { + pv->set(lt.x, int(base_y + g_y * grid_step.y * elem_factor), grid_color); + pv++; + pv->set(rb.x, int(base_y + g_y * grid_step.y * elem_factor), grid_color); + pv++; + }; + + for (int g_y = 1; g_y <= Num_H_LinesUp; g_y++) + { + pv->set(lt.x, int(base_y - g_y * grid_step.y * elem_factor), grid_color); + pv++; + pv->set(rb.x, int(base_y - g_y * grid_step.y * elem_factor), grid_color); + pv++; + } + + // for (int g_y=1; g_y<=grid.y; g_y++){ + // pv->set (lt.x,iFloor(g_y*grid_offs_y+lt.y),grid_color); pv++; + // pv->set (rb.x,iFloor(g_y*grid_offs_y+lt.y),grid_color); pv++; + // } + + dwCount = u32(pv - pv_start); + RImplementation.Vertex.Unlock(dwCount, hGeomLine->vb_stride); + RCache.set_Geometry(hGeomLine); + RCache.Render(D3DPT_LINELIST, dwOffset, dwCount / 2); +}; + +void CStatGraph::RenderBars(FVF::TL0uv **ppv, ElementsDeq *pelements) +{ + float elem_offs = float(rb.x - lt.x) / max_item_count; + float elem_factor = float(rb.y - lt.y) / float(mx - mn); + float base_y = float(rb.y) + (mn * elem_factor); + + float column_width = elem_offs; + if (column_width > 1) + column_width--; + for (ElementsDeqIt it = pelements->begin(); it != pelements->end(); it++) + { + float X = float(it - pelements->begin()) * elem_offs + lt.x; + float Y0 = base_y; + float Y1 = base_y - it->data * elem_factor; + + if (Y1 > Y0) + { + (*ppv)->set(X, Y1, it->color); + (*ppv)++; + (*ppv)->set(X, Y0, it->color); + (*ppv)++; + (*ppv)->set(X + column_width, Y1, it->color); + (*ppv)++; + (*ppv)->set(X + column_width, Y0, it->color); + (*ppv)++; + } + else + { + (*ppv)->set(X, Y0, it->color); + (*ppv)++; + (*ppv)->set(X, Y1, it->color); + (*ppv)++; + (*ppv)->set(X + column_width, Y0, it->color); + (*ppv)++; + (*ppv)->set(X + column_width, Y1, it->color); + (*ppv)++; + }; + }; +}; + +void CStatGraph::RenderLines(FVF::TL0uv **ppv, ElementsDeq *pelements) +{ + float elem_offs = float(rb.x - lt.x) / max_item_count; + float elem_factor = float(rb.y - lt.y) / float(mx - mn); + float base_y = float(rb.y) + (mn * elem_factor); + + for (ElementsDeqIt it = pelements->begin() + 1; it != pelements->end() && it != pelements->end() + 1; it++) + { + ElementsDeqIt it_prev = it - 1; + float X0 = float(it_prev - pelements->begin()) * elem_offs + lt.x; + float Y0 = base_y - it_prev->data * elem_factor; + (*ppv)->set(X0, Y0, it->color); + (*ppv)++; + float X1 = float(it - pelements->begin()) * elem_offs + lt.x; + float Y1 = base_y - it->data * elem_factor; + (*ppv)->set(X1, Y1, it->color); + (*ppv)++; + } +}; + +void CStatGraph::RenderBarLines(FVF::TL0uv **ppv, ElementsDeq *pelements) +{ + float elem_offs = float(rb.x - lt.x) / max_item_count; + float elem_factor = float(rb.y - lt.y) / float(mx - mn); + float base_y = float(rb.y) + (mn * elem_factor); + + for (ElementsDeqIt it = pelements->begin() + 1; it != pelements->end() && it != pelements->end() + 1; it++) + { + ElementsDeqIt it_prev = it - 1; + float X0 = float(it_prev - pelements->begin()) * elem_offs + lt.x + elem_offs; + float Y0 = base_y - it_prev->data * elem_factor; + (*ppv)->set(X0, Y0, it->color); + (*ppv)++; + float X1 = float(it - pelements->begin()) * elem_offs + lt.x; + float Y1 = base_y - it->data * elem_factor; + (*ppv)->set(X1, Y1, it->color); + (*ppv)++; + (*ppv)->set(X1, Y1, it->color); + (*ppv)++; + X1 += elem_offs; + (*ppv)->set(X1, Y1, it->color); + (*ppv)++; + } +}; + +/* +void CStatGraph::RenderPoints( FVF::TL0uv** ppv, ElementsDeq* pelements ) +{ + float elem_offs = float(rb.x-lt.x)/max_item_count; + float elem_factor = float(rb.y-lt.y)/float(mx-mn); + float base_y = float(rb.y)+(mn*elem_factor); + + for (ElementsDeqIt it=pelements->begin()+1; it!=pelements->end(); it++) + { + float X1 = float(it-pelements->begin())*elem_offs+lt.x; + float Y1 = base_y-it->data*elem_factor; + (*ppv)->set (X1,Y1,it->color); (*ppv)++; + } +}; +*/ + +void CStatGraph::RenderMarkers(FVF::TL0uv **ppv, MarkersDeq *pmarkers) +{ + float elem_offs = float(rb.x - lt.x) / max_item_count; + float elem_factor = float(rb.y - lt.y) / float(mx - mn); + float base_y = float(rb.y) + (mn * elem_factor); + + for (MarkersDeqIt it = pmarkers->begin(); it != pmarkers->end() && it != pmarkers->end() + 1; it++) + { + SMarker &CurMarker = *it; + float X0 = 0, Y0 = 0, X1 = 0, Y1 = 0; + switch (CurMarker.m_eStyle) + { + case stVert: + { + X0 = CurMarker.m_fPos * elem_offs + lt.x; + clamp(X0, float(lt.x), float(rb.x)); + X1 = X0; + Y0 = float(lt.y); + Y1 = float(rb.y); + } + break; + case stHor: + { + X0 = float(lt.x); + X1 = float(rb.x); + Y0 = base_y - CurMarker.m_fPos * elem_factor; + clamp(Y0, float(lt.y), float(rb.y)); + Y1 = Y0; + } + break; + } + (*ppv)->set(X0, Y0, CurMarker.m_dwColor); + (*ppv)++; + (*ppv)->set(X1, Y1, CurMarker.m_dwColor); + (*ppv)++; + } +} + +void CStatGraph::OnRender() +{ + RCache.OnFrameEnd(); + + RenderBack(); + + u32 TriElem = 0; + u32 LineElem = 0; + for (SubGraphVecIt it = subgraphs.begin(); it != subgraphs.end(); it++) + { + switch (it->style) + { + case stBar: + { + TriElem += it->elements.size() * 4; + } + break; + case stCurve: + { + LineElem += it->elements.size() * 2; + } + break; + case stBarLine: + { + LineElem += it->elements.size() * 4; + } + break; + case stPoint: + { + // TriElem += it->elements.size()*4; + } + break; + }; + }; + + u32 dwOffsetTri = 0, dwOffsetLine = 0, dwCount; + FVF::TL0uv *pv_Tri_start = NULL; + FVF::TL0uv *pv_Tri; + FVF::TL0uv *pv_Line_start = NULL; + FVF::TL0uv *pv_Line; + + if (TriElem) + { + pv_Tri_start = (FVF::TL0uv*)RImplementation.Vertex.Lock(TriElem, hGeomTri->vb_stride, dwOffsetTri); + pv_Tri = pv_Tri_start; + + pv_Tri = pv_Tri_start; + for (SubGraphVecIt it = subgraphs.begin(); it != subgraphs.end(); it++) + { + switch (it->style) + { + case stBar: + RenderBars(&pv_Tri, &(it->elements)); + break; + }; + }; + dwCount = u32(pv_Tri - pv_Tri_start); + RImplementation.Vertex.Unlock(dwCount, hGeomTri->vb_stride); + RCache.set_Geometry(hGeomTri); + RCache.Render(D3DPT_TRIANGLELIST, dwOffsetTri, 0, dwCount, 0, dwCount / 2); + }; + + if (LineElem) + { + pv_Line_start = (FVF::TL0uv*)RImplementation.Vertex.Lock(LineElem, hGeomLine->vb_stride, dwOffsetLine); + pv_Line = pv_Line_start; + + for (SubGraphVecIt it = subgraphs.begin(); it != subgraphs.end(); it++) + { + switch (it->style) + { + case stCurve: + RenderLines(&pv_Line, &(it->elements)); + break; + case stBarLine: + RenderBarLines(&pv_Line, &(it->elements)); + break; + }; + }; + + dwCount = u32(pv_Line - pv_Line_start); + RImplementation.Vertex.Unlock(dwCount, hGeomLine->vb_stride); + RCache.set_Geometry(hGeomLine); + RCache.Render(D3DPT_LINELIST, dwOffsetLine, dwCount / 2); + }; + + if (!m_Markers.empty()) + { + dwOffsetLine = 0; + LineElem = m_Markers.size() * 2; + + pv_Line_start = (FVF::TL0uv*)RImplementation.Vertex.Lock(LineElem, hGeomLine->vb_stride, dwOffsetLine); + pv_Line = pv_Line_start; + + RenderMarkers(&pv_Line, &(m_Markers)); + + dwCount = u32(pv_Line - pv_Line_start); + RImplementation.Vertex.Unlock(dwCount, hGeomLine->vb_stride); + RCache.set_Geometry(hGeomLine); + RCache.Render(D3DPT_LINELIST, dwOffsetLine, dwCount / 2); + } +}; diff --git a/src/editors/ParticleEditor/StatGraph.h b/src/editors/ParticleEditor/StatGraph.h new file mode 100644 index 00000000000..c5e2053c36e --- /dev/null +++ b/src/editors/ParticleEditor/StatGraph.h @@ -0,0 +1,175 @@ +//--------------------------------------------------------------------------- +#ifndef StatGraphH +#define StatGraphH +//--------------------------------------------------------------------------- +#ifdef _EDITOR +class CStatGraph +#else +class ENGINE_API CStatGraph +#endif + : public pureRender +{ +public: + enum EStyle + { + stBar, + stCurve, + stBarLine, + stPoint, + stVert, + stHor, + }; + +protected: + struct SElement + { + u32 color; + float data; + SElement(float d, u32 clr) + { + color = clr; + data = d; + } + }; + DEFINE_DEQUE(SElement, ElementsDeq, ElementsDeqIt); + struct SSubGraph + { + EStyle style; + ElementsDeq elements; + SSubGraph(EStyle s) + { + style = s; + }; + void SetStyle(EStyle s) + { + style = s; + }; + }; + DEFINE_VECTOR(SSubGraph, SubGraphVec, SubGraphVecIt); + SubGraphVec subgraphs; + + float mn, mx; + u32 max_item_count; + Ivector2 lt, rb; + Ivector2 grid; + Fvector2 grid_step; + u32 grid_color; + u32 base_color; + u32 rect_color; + u32 back_color; + ref_geom hGeomTri; + ref_geom hGeomLine; + + struct SMarker + { + EStyle m_eStyle; + float m_fPos; + u32 m_dwColor; + }; + + DEFINE_DEQUE(SMarker, MarkersDeq, MarkersDeqIt); + MarkersDeq m_Markers; + +protected: + virtual void RenderBack(); + + virtual void RenderBars(FVF::TL0uv **ppv, ElementsDeq *pelements); + virtual void RenderLines(FVF::TL0uv **ppv, ElementsDeq *pelements); + virtual void RenderBarLines(FVF::TL0uv **ppv, ElementsDeq *pelements); + // virtual void RenderPoints ( FVF::TL0uv** ppv, ElementsDeq* pelements ); + virtual void RenderMarkers(FVF::TL0uv **ppv, MarkersDeq *pmarkers); + +public: + CStatGraph(); + ~CStatGraph(); + virtual void OnRender(); + void OnDeviceCreate(); + void OnDeviceDestroy(); + + IC void SetStyle(EStyle s, u32 SubGraphID = 0) + { + if (SubGraphID >= subgraphs.size()) + return; + SubGraphVecIt it = subgraphs.begin() + SubGraphID; + it->SetStyle(s); + } + + IC void SetRect(int l, int t, int w, int h, u32 rect_clr, u32 back_clr) + { + lt.set(l, t); + rb.set(l + w, t + h); + rect_color = rect_clr; + back_color = back_clr; + } + IC void SetGrid(int w_div, float w_step, int h_div, float h_step, u32 grid_clr, u32 base_clr) + { + grid.set(w_div, h_div); + grid_step.set(w_step, h_step); + grid_color = grid_clr; + base_color = base_clr; + } + IC void SetMinMax(float _mn, float _mx, u32 item_count) + { + mn = _mn; + mx = _mx; + max_item_count = item_count; + for (SubGraphVecIt it = subgraphs.begin(); it != subgraphs.end(); it++) + { + while (it->elements.size() > max_item_count) + it->elements.pop_front(); + }; + } + IC void AppendItem(float d, u32 clr, u32 SubGraphID = 0) + { + if (SubGraphID >= subgraphs.size()) + return; + + clamp(d, mn, mx); + + SubGraphVecIt it = subgraphs.begin() + SubGraphID; + it->elements.push_back(SElement(d, clr)); + while (it->elements.size() > max_item_count) + it->elements.pop_front(); + }; + IC u32 AppendSubGraph(EStyle S) + { + subgraphs.push_back(SSubGraph(S)); + return subgraphs.size() - 1; + }; + + IC void AddMarker(EStyle Style, float pos, u32 Color) + { + SMarker NewMarker; + NewMarker.m_dwColor = Color; + NewMarker.m_eStyle = Style; + NewMarker.m_fPos = pos; + + m_Markers.push_back(NewMarker); + }; + + IC const SMarker &Marker(u32 ID) + { + VERIFY(ID < m_Markers.size()); + return m_Markers[ID]; + }; + + IC void UpdateMarkerPos(u32 ID, float NewPos) + { + if (ID >= m_Markers.size()) + return; + SMarker &pMarker = m_Markers[ID]; + pMarker.m_fPos = NewPos; + }; + IC void ClearMarkers() + { + m_Markers.clear(); + } + + IC void RemoveMarker(u32 ID) + { + if (ID >= m_Markers.size()) + return; + m_Markers.erase(m_Markers.begin() + ID); + } +}; +#endif diff --git a/src/editors/ParticleEditor/UILeftBarForm.cpp b/src/editors/ParticleEditor/UILeftBarForm.cpp new file mode 100644 index 00000000000..305155708a5 --- /dev/null +++ b/src/editors/ParticleEditor/UILeftBarForm.cpp @@ -0,0 +1,30 @@ +#include "stdafx.h" + +UILeftBarForm::UILeftBarForm() +{ +} + +UILeftBarForm::~UILeftBarForm() +{ +} + +void UILeftBarForm::Draw() +{ + ImGui::Begin("LeftBar", 0); + + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Items")) + { + ImGui::BeginGroup(); + PTools->m_PList->Draw(); + ImGui::EndGroup(); + ImGui::TreePop(); + } + if (ImGui::TreeNode("Reference List")) + { + PTools->DrawReferenceList(); + ImGui::TreePop(); + } + + ImGui::End(); +} diff --git a/src/editors/ParticleEditor/UILeftBarForm.h b/src/editors/ParticleEditor/UILeftBarForm.h new file mode 100644 index 00000000000..359df04371b --- /dev/null +++ b/src/editors/ParticleEditor/UILeftBarForm.h @@ -0,0 +1,10 @@ +#pragma once +class UILeftBarForm : public xrUI +{ +public: + UILeftBarForm(); + virtual ~UILeftBarForm(); + virtual void Draw(); + +private: +}; diff --git a/src/editors/ParticleEditor/UIMainForm.cpp b/src/editors/ParticleEditor/UIMainForm.cpp new file mode 100644 index 00000000000..bc51bba55b1 --- /dev/null +++ b/src/editors/ParticleEditor/UIMainForm.cpp @@ -0,0 +1,51 @@ +#include "stdafx.h" +#include "../xrECore/Editor/EditorChooseEvents.h" + +void resptrcode_texture::create(LPCSTR _name) { _set(RImplementation.Resources->_CreateTexture(_name)); } + +UIMainForm *MainForm = nullptr; + +UIMainForm::UIMainForm() +{ + EnableReceiveCommands(); + if (!ExecCommand(COMMAND_INITIALIZE, (u32)0, (u32)0)) + { + FlushLog(); + exit(-1); + } + ExecCommand(COMMAND_UPDATE_GRID); + ExecCommand(COMMAND_RENDER_FOCUS); + FillChooseEvents(); + m_TopBar = xr_new(); + m_Render = xr_new(); + m_MainMenu = xr_new(); + m_LeftBar = xr_new(); + m_RightBar = xr_new(); +} + +UIMainForm::~UIMainForm() +{ + ClearChooseEvents(); + xr_delete(m_RightBar); + xr_delete(m_LeftBar); + xr_delete(m_MainMenu); + xr_delete(m_Render); + xr_delete(m_TopBar); + ExecCommand(COMMAND_DESTROY, (u32)0, (u32)0); +} + +void UIMainForm::Draw() +{ + m_MainMenu->Draw(); + m_TopBar->Draw(); + m_RightBar->Draw(); + m_LeftBar->Draw(); + m_Render->Draw(); +} + +bool UIMainForm::Frame() +{ + if (UI) + return UI->Idle(); + return false; +} diff --git a/src/editors/ParticleEditor/UIMainForm.h b/src/editors/ParticleEditor/UIMainForm.h new file mode 100644 index 00000000000..e140de5f3f3 --- /dev/null +++ b/src/editors/ParticleEditor/UIMainForm.h @@ -0,0 +1,19 @@ +#pragma once +class UIMainForm : public xrUI +{ +public: + UIMainForm(); + virtual ~UIMainForm(); + virtual void Draw(); + bool Frame(); + IC UILeftBarForm *GetLeftBarForm() { return m_LeftBar; } + IC UITopBarForm *GetTopBarForm() { return m_TopBar; } + +private: + UITopBarForm *m_TopBar; + UIRenderForm *m_Render; + UIMainMenuForm *m_MainMenu; + UILeftBarForm *m_LeftBar; + UIRightBarForm *m_RightBar; +}; +extern UIMainForm *MainForm; diff --git a/src/editors/ParticleEditor/UIMainMenuForm.cpp b/src/editors/ParticleEditor/UIMainMenuForm.cpp new file mode 100644 index 00000000000..0ad873e3596 --- /dev/null +++ b/src/editors/ParticleEditor/UIMainMenuForm.cpp @@ -0,0 +1,272 @@ +#include "stdafx.h" + +UIMainMenuForm::UIMainMenuForm() +{ +} + +UIMainMenuForm::~UIMainMenuForm() +{ +} + +void UIMainMenuForm::Draw() +{ + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Save")) + { + ExecCommand(COMMAND_SAVE); + } + if (ImGui::MenuItem("Reload")) + { + ExecCommand(COMMAND_LOAD); + } + ImGui::Separator(); + if (ImGui::MenuItem("Save .xr")) + { + ExecCommand(COMMAND_SAVE_XR); + } + if (ImGui::MenuItem("Load .xr")) + { + ExecCommand(COMMAND_LOAD_XR); + } + ImGui::Separator(); + if (ImGui::MenuItem("Validate")) + { + ExecCommand(COMMAND_VALIDATE); + } + if (ImGui::MenuItem("Compact")) + { + ExecCommand(COMMAND_COMPACT_PARTICLES); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Editors")) + { + if (ImGui::BeginMenu("Image")) + { + if (ImGui::MenuItem("Image Editor", "")) + { + ExecCommand(COMMAND_IMAGE_EDITOR); + } + ImGui::Separator(); + if (ImGui::MenuItem("Synchronize Textures", "")) + { + ExecCommand(COMMAND_REFRESH_TEXTURES); + } + if (ImGui::MenuItem("Check New Textures", "")) + { + ExecCommand(COMMAND_CHECK_TEXTURES); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Sounds")) + { + if (ImGui::MenuItem("Sound Editor", "")) + { + ExecCommand(COMMAND_SOUND_EDITOR); + } + ImGui::Separator(); + if (ImGui::MenuItem("Synchronize Sounds", "")) + { + ExecCommand(COMMAND_SYNC_SOUNDS); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Light Anim Editor", "")) + { + ExecCommand(COMMAND_LIGHTANIM_EDITOR); + } + if (ImGui::MenuItem("Minimap Editor", "")) + { + ExecCommand(COMMAND_MINIMAP_EDITOR); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Options")) + { + if (ImGui::BeginMenu("Render")) + { + if (ImGui::BeginMenu("Quality")) + { + static bool selected[4] = {false, false, true, false}; + if (ImGui::MenuItem("25%", "", &selected[0])) + { + selected[1] = selected[2] = selected[3] = false; + UI->SetRenderQuality(1 / 4.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("50%", "", &selected[1])) + { + selected[0] = selected[2] = selected[3] = false; + UI->SetRenderQuality(1 / 2.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("100%", "", &selected[2])) + { + selected[1] = selected[0] = selected[3] = false; + UI->SetRenderQuality(1.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("200%", "", &selected[3])) + { + selected[1] = selected[2] = selected[0] = false; + UI->SetRenderQuality(2.f); + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Fill Mode")) + { + bool selected[3] = {EDevice.dwFillMode == D3DFILL_POINT, EDevice.dwFillMode == D3DFILL_WIREFRAME, EDevice.dwFillMode == D3DFILL_SOLID}; + if (ImGui::MenuItem("Point", "", &selected[0])) + { + EDevice.dwFillMode = D3DFILL_POINT; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Wireframe", "", &selected[1])) + { + EDevice.dwFillMode = D3DFILL_WIREFRAME; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Solid", "", &selected[2])) + { + EDevice.dwFillMode = D3DFILL_SOLID; + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Shader Mode")) + { + bool selected[2] = {EDevice.dwShadeMode == D3DSHADE_FLAT, EDevice.dwShadeMode == D3DSHADE_GOURAUD}; + if (ImGui::MenuItem("Flat", "", &selected[0])) + { + EDevice.dwShadeMode = D3DSHADE_FLAT; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Gouraud", "", &selected[1])) + { + EDevice.dwShadeMode = D3DSHADE_GOURAUD; + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + { + bool selected = psDeviceFlags.test(rsEdgedFaces); + if (ImGui::MenuItem("Edged Faces", "", &selected)) + { + psDeviceFlags.set(rsEdgedFaces, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = !HW.Caps.bForceGPU_SW; + if (ImGui::MenuItem("RenderHW", "", &selected)) + { + HW.Caps.bForceGPU_SW = !selected; + UI->Resize(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsFilterLinear); + if (ImGui::MenuItem("Filter Linear", "", &selected)) + { + psDeviceFlags.set(rsFilterLinear, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsRenderTextures); + if (ImGui::MenuItem("Textures", "", &selected)) + { + psDeviceFlags.set(rsRenderTextures, selected); + UI->RedrawScene(); + } + } + ImGui::EndMenu(); + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsDrawSafeRect); + if (ImGui::MenuItem("Draw Safe Rect", "", &selected)) + { + psDeviceFlags.set(rsDrawSafeRect, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsDrawGrid); + if (ImGui::MenuItem("Draw Grid", "", &selected)) + { + psDeviceFlags.set(rsDrawGrid, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsFog); + if (ImGui::MenuItem("Fog", "", &selected)) + { + psDeviceFlags.set(rsFog, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsLighting); + ; + if (ImGui::MenuItem("Lighting", "", &selected)) + { + psDeviceFlags.set(rsLighting, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsMuteSounds); + if (ImGui::MenuItem("Mute Sounds", "", &selected)) + { + psDeviceFlags.set(rsMuteSounds, selected); + } + } + { + bool selected = psDeviceFlags.test(rsRenderRealTime); + if (ImGui::MenuItem("Real Time", "", &selected)) + { + psDeviceFlags.set(rsRenderRealTime, selected); + } + } + + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsStatistic); + if (ImGui::MenuItem("Stats", "", &selected)) + { + psDeviceFlags.set(rsStatistic, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + if (ImGui::MenuItem("Preferences", "")) + { + ExecCommand(COMMAND_EDITOR_PREF); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Windows")) + { + { + bool selected = AllowLogCommands(); + + if (ImGui::MenuItem("Log", "", &selected)) + { + ExecCommand(COMMAND_LOG_COMMANDS); + } + } + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } +} diff --git a/src/editors/ParticleEditor/UIMainMenuForm.h b/src/editors/ParticleEditor/UIMainMenuForm.h new file mode 100644 index 00000000000..a44b6606609 --- /dev/null +++ b/src/editors/ParticleEditor/UIMainMenuForm.h @@ -0,0 +1,8 @@ +#pragma once +class UIMainMenuForm : public xrUI +{ +public: + UIMainMenuForm(); + virtual ~UIMainMenuForm(); + virtual void Draw(); +}; diff --git a/src/editors/ParticleEditor/UIRightBarForm.cpp b/src/editors/ParticleEditor/UIRightBarForm.cpp new file mode 100644 index 00000000000..f158c923f0c --- /dev/null +++ b/src/editors/ParticleEditor/UIRightBarForm.cpp @@ -0,0 +1,32 @@ +#include "stdafx.h" + +UIRightBarForm::UIRightBarForm() +{ +} + +UIRightBarForm::~UIRightBarForm() +{ +} + +void UIRightBarForm::Draw() +{ + ImGui::Begin("RightBar", 0); + + if (ImGui::TreeNode("Custom Object")) + { + ImGui::BeginGroup(); + PTools->m_ObjectProps->Draw(); + ImGui::EndGroup(); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Item Properties")) + { + ImGui::BeginGroup(); + PTools->m_ItemProps->Draw(); + ImGui::EndGroup(); + ImGui::TreePop(); + } + + ImGui::End(); +} diff --git a/src/editors/ParticleEditor/UIRightBarForm.h b/src/editors/ParticleEditor/UIRightBarForm.h new file mode 100644 index 00000000000..00109fd1ccb --- /dev/null +++ b/src/editors/ParticleEditor/UIRightBarForm.h @@ -0,0 +1,10 @@ +#pragma once +class UIRightBarForm : public xrUI +{ +public: + UIRightBarForm(); + virtual ~UIRightBarForm(); + virtual void Draw(); + +private: +}; diff --git a/src/editors/ParticleEditor/UITopBarForm.cpp b/src/editors/ParticleEditor/UITopBarForm.cpp new file mode 100644 index 00000000000..e27b96b7831 --- /dev/null +++ b/src/editors/ParticleEditor/UITopBarForm.cpp @@ -0,0 +1,312 @@ +#include "stdafx.h" + +UITopBarForm::UITopBarForm() +{ + +#define ADD_BUTTON_IMAGE_T1(Class, Name) +#define ADD_BUTTON_IMAGE_T2(Class, Name) +#define ADD_BUTTON_IMAGE_S(Name) \ + m_t##Name = EDevice.Resources->_CreateTexture("ed\\bar\\" #Name); \ + m_t##Name->Load(); \ + m_time##Name = 0; +#define ADD_BUTTON_IMAGE_D(Name) \ + m_t##Name = EDevice.Resources->_CreateTexture("ed\\bar\\" #Name); \ + m_t##Name->Load(); \ + m_b##Name = false; +#include "UITopBarForm_ButtonList.h" + RefreshBar(); +} + +UITopBarForm::~UITopBarForm() +{ +} + +void UITopBarForm::Draw() +{ + ImGuiViewport *viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + UI->GetMenuBarHeight())); + ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, UIToolBarSize)); + ImGui::SetNextWindowViewport(viewport->ID); + + ImGuiWindowFlags window_flags = 0 | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings; + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(2, 2)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(2, 2)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 2)); + ImGui::Begin("TOOLBAR", NULL, window_flags); + { +#define ADD_BUTTON_IMAGE_S(Name) \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_time##Name > EDevice.TimerAsync() ? 0.5 : 0, 0), ImVec2(m_time##Name > EDevice.TimerAsync() ? 1 : 0.5, 1), 0)) \ + { \ + m_time##Name = EDevice.TimerAsync() + 130; \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_D(Name) \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_b##Name ? 0.5 : 0, 0), ImVec2(m_b##Name ? 1 : 0.5, 1), 0)) \ + { \ + m_b##Name = !m_b##Name; \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_P(Name) \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_b##Name ? 0.5 : 0, 0), ImVec2(m_b##Name ? 1 : 0.5, 1), 0)) \ + { \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_T1(Class, Name) \ + ImGui::PushID("" #Class); \ + ImGui::PushStyleColor(ImGuiCol_Text, (ImVec4)ImColor::HSV(0, 0, 0)); \ + if (ImGui::Button("" #Name, ImVec2(20, 20))) \ + { \ + Click##Class##Name(); \ + } \ + ImGui::SameLine(); \ + ImGui::PopStyleColor(1); \ + ImGui::PopID(); +#define ADD_BUTTON_IMAGE_T2(Class, Name) \ + ImGui::PushID("" #Class); \ + if (ImGui::Button("" #Name, ImVec2(20, 20))) \ + { \ + Click##Class##Name(); \ + } \ + ImGui::SameLine(); \ + ImGui::PopID(); +//#define ADD_BUTTON_IMAGE_T1_1(Class, Name, T) \ +// ImGui::PushStyleColor(ImGuiCol_Text, (ImVec4)ImColor::HSV(0, 0, 0)); \ +// if (ImGui::Button("" #T, ImVec2(20, 20))) \ +// { \ +// Click##Class##Name(); \ +// } \ +// ImGui::SameLine(); \ +// ImGui::PopStyleColor(1); +#include "UITopBarForm_ButtonList.h" + } + ImGui::End(); + ImGui::PopStyleVar(5); +} +void UITopBarForm::RefreshBar() +{ + { + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = false; + + switch (Tools->GetAction()) + { + case etaSelect: + m_bSelect = true; + break; + case etaAdd: + m_bAdd = true; + break; + case etaMove: + m_bMove = true; + break; + case etaRotate: + m_bRotate = true; + break; + case etaScale: + m_bScale = true; + break; + default: + THROW; + } + } + { + m_bX = false; + m_bY = false; + m_bZ = false; + m_bZX = false; + // axis + switch (Tools->GetAxis()) + { + case etAxisX: + m_bX = true; + break; + case etAxisY: + m_bY = true; + break; + case etAxisZ: + m_bZ = true; + break; + case etAxisZX: + m_bZX = true; + break; + default: + THROW; + } + } + // settings + m_bCsLocal = Tools->GetSettings(etfCSParent); + m_bNuScale = Tools->GetSettings(etfNUScale); + m_bNSnap = Tools->GetSettings(etfNormalAlign); + m_bGSnap = Tools->GetSettings(etfGSnap); + m_bOSnap = Tools->GetSettings(etfOSnap); + m_bMoveToSnap = Tools->GetSettings(etfMTSnap); + m_bVSnap = Tools->GetSettings(etfVSnap); + m_bASnap = Tools->GetSettings(etfASnap); + m_bMSnap = Tools->GetSettings(etfMSnap); +} + +void UITopBarForm::ClickUndo() +{ + ExecCommand(COMMAND_UNDO); +} + +void UITopBarForm::ClickRedo() +{ + ExecCommand(COMMAND_REDO); +} +void UITopBarForm::ClickZoom() +{ + ExecCommand(COMMAND_ZOOM_EXTENTS, FALSE); +} + +void UITopBarForm::ClickZoomSel() +{ + ExecCommand(COMMAND_ZOOM_EXTENTS, TRUE); +} +void UITopBarForm::ClickSelect() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + m_bSelect = true; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickAdd() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaAdd); + m_bSelect = false; + m_bAdd = true; + m_bMove = false; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickMove() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaMove); + m_bSelect = false; + m_bAdd = false; + m_bMove = true; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickRotate() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaRotate); + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = true; + m_bScale = false; +} +void UITopBarForm::ClickScale() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaScale); + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = true; +} +void UITopBarForm::ClickX() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisX); + m_bX = true; + m_bY = false; + m_bZ = false; + m_bZX = false; +} +void UITopBarForm::ClickY() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisY); + m_bX = false; + m_bY = true; + m_bZ = false; + m_bZX = false; +} +void UITopBarForm::ClickZ() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisZ); + m_bX = false; + m_bY = false; + m_bZ = true; + m_bZX = false; +} +void UITopBarForm::ClickZX() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisZX); + m_bX = false; + m_bY = false; + m_bZ = false; + m_bZX = true; +} + +void UITopBarForm::ClickCsLocal() { ExecCommand(COMMAND_SET_SETTINGS, etfCSParent, m_bCsLocal); } +void UITopBarForm::ClickNuScale() { ExecCommand(COMMAND_SET_SETTINGS, etfNUScale, m_bNuScale); } +void UITopBarForm::ClickGSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfGSnap, m_bGSnap); } +void UITopBarForm::ClickOSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfOSnap, m_bOSnap); } +void UITopBarForm::ClickMoveToSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfMTSnap, m_bMoveToSnap); } +void UITopBarForm::ClickNSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfNormalAlign, m_bNSnap); } +void UITopBarForm::ClickVSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfVSnap, m_bVSnap); } +void UITopBarForm::ClickASnap() { ExecCommand(COMMAND_SET_SETTINGS, etfASnap, m_bASnap); } +void UITopBarForm::ClickMSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfMSnap, m_bMSnap); } + +void UITopBarForm::ClickCameraP() +{ + EDevice.m_Camera.SetStyle(csPlaneMove); + UI->RedrawScene(); +} +void UITopBarForm::ClickCameraA() +{ + EDevice.m_Camera.SetStyle(cs3DArcBall); + UI->RedrawScene(); +} +void UITopBarForm::ClickCameraF() +{ + EDevice.m_Camera.SetStyle(csFreeFly); + UI->RedrawScene(); +} + +void UITopBarForm::ClickViewB1() +{ + EDevice.m_Camera.ViewBack(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewB2() +{ + EDevice.m_Camera.ViewBottom(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewF() +{ + EDevice.m_Camera.ViewFront(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewL() +{ + EDevice.m_Camera.ViewLeft(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewR() +{ + EDevice.m_Camera.ViewRight(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewT() +{ + EDevice.m_Camera.ViewTop(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewX() +{ + EDevice.m_Camera.ViewReset(); + UI->RedrawScene(); +} diff --git a/src/editors/ParticleEditor/UITopBarForm.h b/src/editors/ParticleEditor/UITopBarForm.h new file mode 100644 index 00000000000..d03033bf987 --- /dev/null +++ b/src/editors/ParticleEditor/UITopBarForm.h @@ -0,0 +1,26 @@ +#pragma once +class UITopBarForm : public xrUI +{ +public: + UITopBarForm(); + virtual ~UITopBarForm(); + virtual void Draw(); + void RefreshBar(); + +private: +#define ADD_BUTTON_IMAGE_T1(Class, Name) void Click##Class##Name(); +#define ADD_BUTTON_IMAGE_T2(Class, Name) void Click##Class##Name(); +#define ADD_BUTTON_IMAGE_S(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + u32 m_time##Name; +#define ADD_BUTTON_IMAGE_D(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + bool m_b##Name; +#define ADD_BUTTON_IMAGE_P(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + bool m_b##Name; +#include "UITopBarForm_ButtonList.h" +}; \ No newline at end of file diff --git a/src/editors/ParticleEditor/UITopBarForm_ButtonList.h b/src/editors/ParticleEditor/UITopBarForm_ButtonList.h new file mode 100644 index 00000000000..526ba68bbf2 --- /dev/null +++ b/src/editors/ParticleEditor/UITopBarForm_ButtonList.h @@ -0,0 +1,50 @@ +#ifndef ADD_BUTTON_IMAGE_P +#define ADD_BUTTON_IMAGE_P(Name) ADD_BUTTON_IMAGE_D(Name) +#endif +#ifndef ADD_BUTTON_IMAGE_T1_1 +#define ADD_BUTTON_IMAGE_T1_1(Class, Name, T) ADD_BUTTON_IMAGE_T1(Class, Name) +#endif +ADD_BUTTON_IMAGE_S(Undo) +ADD_BUTTON_IMAGE_S(Redo) + +ADD_BUTTON_IMAGE_P(Select) +ADD_BUTTON_IMAGE_P(Add) +ADD_BUTTON_IMAGE_P(Move) +ADD_BUTTON_IMAGE_P(Rotate) +ADD_BUTTON_IMAGE_P(Scale) + +ADD_BUTTON_IMAGE_P(X) +ADD_BUTTON_IMAGE_P(Y) +ADD_BUTTON_IMAGE_P(Z) +ADD_BUTTON_IMAGE_P(ZX) + +ADD_BUTTON_IMAGE_D(CsLocal) +ADD_BUTTON_IMAGE_D(NuScale) +ADD_BUTTON_IMAGE_D(GSnap) +ADD_BUTTON_IMAGE_D(OSnap) +ADD_BUTTON_IMAGE_D(MoveToSnap) +ADD_BUTTON_IMAGE_D(NSnap) +ADD_BUTTON_IMAGE_D(VSnap) +ADD_BUTTON_IMAGE_D(ASnap) +ADD_BUTTON_IMAGE_D(MSnap) + +ADD_BUTTON_IMAGE_S(Zoom) +ADD_BUTTON_IMAGE_S(ZoomSel) + +ADD_BUTTON_IMAGE_T1(View, F) +ADD_BUTTON_IMAGE_T1_1(View, B1, B) +ADD_BUTTON_IMAGE_T1(View, L) +ADD_BUTTON_IMAGE_T1(View, R) +ADD_BUTTON_IMAGE_T1(View, T) +ADD_BUTTON_IMAGE_T1_1(View, B2, B) +ADD_BUTTON_IMAGE_T1(View, X) + +ADD_BUTTON_IMAGE_T2(Camera, P) +ADD_BUTTON_IMAGE_T2(Camera, A) +ADD_BUTTON_IMAGE_T2(Camera, F) + +#undef ADD_BUTTON_IMAGE_D +#undef ADD_BUTTON_IMAGE_S +#undef ADD_BUTTON_IMAGE_P +#undef ADD_BUTTON_IMAGE_T1 +#undef ADD_BUTTON_IMAGE_T2 diff --git a/src/editors/ParticleEditor/UI_ParticleMain.cpp b/src/editors/ParticleEditor/UI_ParticleMain.cpp new file mode 100644 index 00000000000..072c48e7270 --- /dev/null +++ b/src/editors/ParticleEditor/UI_ParticleMain.cpp @@ -0,0 +1,254 @@ +#include "stdafx.h" +#include "UI_ParticleMain.h" +#include "UI_ParticleTools.h" +#include "xrEngine/xr_input.h" + +CParticleMain *PUI = (CParticleMain *)UI; + +CParticleMain::CParticleMain() +{ + EPrefs = xr_new(); +} + +CParticleMain::~CParticleMain() +{ + xr_delete(EPrefs); +} + +CCommandVar CParticleTool::CommandSelectPreviewObj(CCommandVar p1, CCommandVar p2) +{ + SelectPreviewObject(p1); + return TRUE; +} + +CCommandVar CParticleTool::CommandEditPreviewProps(CCommandVar p1, CCommandVar p2) +{ + return TRUE; +} + +CCommandVar CParticleTool::CommandSaveXR(CCommandVar p1, CCommandVar p2) +{ + Save(true); + ExecCommand(COMMAND_UPDATE_CAPTION); + return TRUE; +} + +CCommandVar CParticleTool::CommandLoadXR(CCommandVar p1, CCommandVar p2) +{ + xr_string temp_fn; + if (EFS.GetOpenName(EDevice.m_hWnd, "$game_data$", temp_fn, false, NULL, 0)) + { + ::Render->PSLibrary.OnDestroy(); + ::Render->PSLibrary.Load(temp_fn.c_str()); + ResetCurrent(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + ExecCommand(COMMAND_UPDATE_CAPTION); + } + return TRUE; +} + +CCommandVar CParticleTool::CommandSave(CCommandVar p1, CCommandVar p2) +{ + Save(false); + ExecCommand(COMMAND_UPDATE_CAPTION); + return TRUE; +} +CCommandVar CParticleTool::CommandSaveBackup(CCommandVar p1, CCommandVar p2) +{ + ExecCommand(COMMAND_SAVE); + return TRUE; +} +CCommandVar CParticleTool::CommandReload(CCommandVar p1, CCommandVar p2) +{ + if (!IfModified()) + return FALSE; + Reload(); + ExecCommand(COMMAND_UPDATE_CAPTION); + return TRUE; +} +CCommandVar CParticleTool::CommandValidate(CCommandVar p1, CCommandVar p2) +{ + Validate(true); + return TRUE; +} +CCommandVar CParticleTool::CommandClear(CCommandVar p1, CCommandVar p2) +{ + EDevice.m_Camera.Reset(); + ResetPreviewObject(); + ExecCommand(COMMAND_UPDATE_CAPTION); + return TRUE; +} +CCommandVar CParticleTool::CommandPlayCurrent(CCommandVar p1, CCommandVar p2) +{ + PlayCurrent(); + return TRUE; +} +CCommandVar CParticleTool::CommandStopCurrent(CCommandVar p1, CCommandVar p2) +{ + StopCurrent(p1); + return TRUE; +} + +CCommandVar CommandRefreshUIBar(CCommandVar p1, CCommandVar p2) +{ + /*fraTopBar->RefreshBar (); + fraLeftBar->RefreshBar (); + fraBottomBar->RefreshBar();*/ + return TRUE; +} +CCommandVar CommandRestoreUIBar(CCommandVar p1, CCommandVar p2) +{ + /* fraTopBar->fsStorage->RestoreFormPlacement(); + fraLeftBar->fsStorage->RestoreFormPlacement(); + fraBottomBar->fsStorage->RestoreFormPlacement();*/ + return TRUE; +} +CCommandVar CommandSaveUIBar(CCommandVar p1, CCommandVar p2) +{ + /* fraTopBar->fsStorage->SaveFormPlacement(); + fraLeftBar->fsStorage->SaveFormPlacement(); + fraBottomBar->fsStorage->SaveFormPlacement();*/ + return TRUE; +} +CCommandVar CommandUpdateToolBar(CCommandVar p1, CCommandVar p2) +{ + /*fraLeftBar->UpdateBar();*/ + return TRUE; +} +CCommandVar CommandUpdateCaption(CCommandVar p1, CCommandVar p2) +{ + /*frmMain->UpdateCaption();*/ + return TRUE; +} + +CCommandVar CommandJumpToItem(CCommandVar p1, CCommandVar p2) +{ + PTools->CommandJumpToItem(); + return TRUE; +} + +void CParticleMain::RegisterCommands() +{ + inherited::RegisterCommands(); + // tools + // REGISTER_CMD_CE (COMMAND_SELECT_PREVIEW_OBJ,"Select Preview Object",PTools,CParticleTool::CommandSelectPreviewObj, true); + // REGISTER_CMD_CE (COMMAND_EDIT_PREVIEW_PROPS,"Select Preview Props", PTools,CParticleTool::CommandEditPreviewProps, true); + REGISTER_CMD_CE(COMMAND_SAVE, "File\\Save", PTools, CParticleTool::CommandSave, true); + REGISTER_CMD_C(COMMAND_SAVE_BACKUP, PTools, CParticleTool::CommandSaveBackup); + REGISTER_CMD_CE(COMMAND_LOAD, "File\\Reload", PTools, CParticleTool::CommandReload, true); + REGISTER_CMD_C(COMMAND_VALIDATE, PTools, CParticleTool::CommandValidate); + REGISTER_CMD_CE(COMMAND_CLEAR, "File\\Clear", PTools, CParticleTool::CommandClear, true); + REGISTER_CMD_CE(COMMAND_PLAY_CURRENT, "Particles\\Play", PTools, CParticleTool::CommandPlayCurrent, true); + REGISTER_SUB_CMD_CE(COMMAND_STOP_CURRENT, "Particles", PTools, CParticleTool::CommandStopCurrent, true); + APPEND_SUB_CMD("Stop Immediate", 0, 0); + APPEND_SUB_CMD("Stop Deffered", 1, 0); + REGISTER_SUB_CMD_END; + REGISTER_CMD_S(COMMAND_REFRESH_UI_BAR, CommandRefreshUIBar); + REGISTER_CMD_S(COMMAND_RESTORE_UI_BAR, CommandRestoreUIBar); + REGISTER_CMD_S(COMMAND_SAVE_UI_BAR, CommandSaveUIBar); + REGISTER_CMD_S(COMMAND_UPDATE_TOOLBAR, CommandUpdateToolBar); + REGISTER_CMD_S(COMMAND_UPDATE_CAPTION, CommandUpdateCaption); + REGISTER_CMD_S(COMMAND_JUMP_TO_ITEM, CommandJumpToItem); + REGISTER_CMD_C(COMMAND_SAVE_XR, PTools, CParticleTool::CommandSaveXR); + REGISTER_CMD_C(COMMAND_LOAD_XR, PTools, CParticleTool::CommandLoadXR); + REGISTER_CMD_C(COMMAND_COMPACT_PARTICLES, PTools, CParticleTool::Compact); + REGISTER_CMD_CE(COMMAND_CREATE_GROUP_FROM_SELECTED, "Particles\\CreateGroupFromEffect", PTools, CParticleTool::CreateGroupFromSelected, true); +} + +void CParticleMain::OnDrawUI() +{ + inherited::OnDrawUI(); + PTools->OnDrawUI(); +} + +const char *CParticleMain::GetCaption() +{ + return "particles"; +} + +bool CParticleMain::ApplyShortCut(DWORD Key, TShiftState Shift) +{ + return inherited::ApplyShortCut(Key, Shift); +} +//--------------------------------------------------------------------------- + +bool CParticleMain::ApplyGlobalShortCut(DWORD Key, TShiftState Shift) +{ + return inherited::ApplyGlobalShortCut(Key, Shift); +} +//--------------------------------------------------------------------------- + +void CParticleMain::RealUpdateScene() +{ + inherited::RealUpdateScene(); +} +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// Common +//--------------------------------------------------------------------------- +void CParticleMain::ResetStatus() +{ + /*VERIFY(m_bReady); + if (fraBottomBar->paStatus->Caption!=""){ + fraBottomBar->paStatus->Caption=""; fraBottomBar->paStatus->Repaint(); + }*/ +} +void CParticleMain::SetStatus(LPCSTR s, bool bOutLog) +{ + /*VERIFY(m_bReady); + if (fraBottomBar->paStatus->Caption!=s){ + fraBottomBar->paStatus->Caption=s; fraBottomBar->paStatus->Repaint(); + if (bOutLog&&s&&s[0]) ELog.Msg(mtInformation,s); + }*/ +} +void CParticleMain::ProgressDraw() +{ + inherited::ProgressDraw(); + /* fraBottomBar->RedrawBar();*/ +} +//--------------------------------------------------------------------------- +void CParticleMain::OutCameraPos() +{ + VERIFY(m_bReady); + /* xr_string s; + const Fvector& c = EDevice.m_Camera.GetPosition(); + s.sprintf("C: %3.1f, %3.1f, %3.1f",c.x,c.y,c.z); + // const Fvector& hpb = EDevice.m_Camera.GetHPB(); + // s.sprintf(" Cam: %3.1f�, %3.1f�, %3.1f�",rad2deg(hpb.y),rad2deg(hpb.x),rad2deg(hpb.z)); + fraBottomBar->paCamera->Caption=s; fraBottomBar->paCamera->Repaint();*/ +} +//--------------------------------------------------------------------------- +void CParticleMain::OutUICursorPos() +{ + VERIFY(m_bReady); + /*xr_string s; POINT pt; + GetCursorPos(&pt); + s.sprintf("Cur: %d, %d",pt.x,pt.y); + fraBottomBar->paUICursor->Caption=s; fraBottomBar->paUICursor->Repaint();*/ +} +//--------------------------------------------------------------------------- +void CParticleMain::OutGridSize() +{ + /*VERIFY(fraBottomBar); + xr_string s; + s.sprintf("Grid: %1.1f",EPrefs->grid_cell_size); + fraBottomBar->paGridSquareSize->Caption=s; fraBottomBar->paGridSquareSize->Repaint();*/ +} +//--------------------------------------------------------------------------- +void CParticleMain::OutInfo() +{ + /*fraBottomBar->paSel->Caption = Tools->GetInfo();*/ +} +//--------------------------------------------------------------------------- +void CParticleMain::RealQuit() +{ + inherited::Quit(); +} + +#include "Resources\resource.h" + +HICON CParticleMain::EditorIcon() +{ + return LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(MAINICON)); +} diff --git a/src/editors/ParticleEditor/UI_ParticleMain.h b/src/editors/ParticleEditor/UI_ParticleMain.h new file mode 100644 index 00000000000..d3f1eb3e872 --- /dev/null +++ b/src/editors/ParticleEditor/UI_ParticleMain.h @@ -0,0 +1,57 @@ +#ifndef UI_ParticleMainH +#define UI_ParticleMainH + +enum +{ + COMMAND_EXTFIRST_EXT = COMMAND_MAIN_LAST - 1, + + COMMAND_VALIDATE, + + COMMAND_SELECT_PREVIEW_OBJ, + COMMAND_EDIT_PREVIEW_PROPS, + + COMMAND_PLAY_CURRENT, + COMMAND_STOP_CURRENT, + COMMAND_JUMP_TO_ITEM, + COMMAND_SAVE_XR, + COMMAND_LOAD_XR, + COMMAND_COMPACT_PARTICLES, + COMMAND_CREATE_GROUP_FROM_SELECTED +}; +//------------------------------------------------------------------------------ + +class CParticleMain : public TUI +{ + typedef TUI inherited; + + virtual void RealUpdateScene(); + virtual void RealQuit(); + +public: + CParticleMain(); + virtual ~CParticleMain(); + + virtual const char* GetCaption(); + + virtual void ResetStatus(); + virtual void SetStatus(LPCSTR s, bool bOutLog); + virtual void ProgressDraw(); + virtual void OutCameraPos(); + virtual void OutUICursorPos(); + virtual void OutGridSize(); + virtual void OutInfo(); + + virtual LPCSTR EditorName() { return "particle"; } + virtual LPCSTR EditorDesc() { return "Particle Editor"; } + HICON EditorIcon() override; + + virtual bool ApplyShortCut(DWORD Key, TShiftState Shift); + virtual bool ApplyGlobalShortCut(DWORD Key, TShiftState Shift); + + // commands + virtual void RegisterCommands(); + virtual void OnDrawUI(); +}; +extern CParticleMain *PUI; +//--------------------------------------------------------------------------- +#endif // UI_MainCommandH diff --git a/src/editors/ParticleEditor/UI_ParticleTools.cpp b/src/editors/ParticleEditor/UI_ParticleTools.cpp new file mode 100644 index 00000000000..4ecb0ef6517 --- /dev/null +++ b/src/editors/ParticleEditor/UI_ParticleTools.cpp @@ -0,0 +1,991 @@ +#include "stdafx.h" +#include "UI_ParticleTools.h" +#include "xrEngine/ObjectAnimator.h" +#include "..\xrECore\Editor\ParticleEffectActions.h" +#include "xrEngine/igame_persistent.h" + +CParticleTool *PTools = (CParticleTool *)Tools; + +#define CHECK_SNAP(R, A, C) \ + { \ + R += A; \ + if (fabsf(R) >= C) \ + { \ + A = snapto(R, C); \ + R = 0; \ + } \ + else \ + { \ + A = 0; \ + } \ + } +// static Fvector zero_vec={0.f,0.f,0.f}; + +EParticleAction *pCreateEActionImpl(PAPI::PActionEnum type); + +CParticleTool::CParticleTool() +{ + m_CreatingParticle = false; + m_EditMode = emNone; + m_ItemProps = 0; + m_EditObject = 0; + m_bModified = false; + m_bReady = false; + m_Transform.identity(); + m_Vel.set(0, 0, 0); + fFogness = 0.9f; + dwFogColor = 0xffffffff; + m_Flags.zero(); + pCreateEAction = pCreateEActionImpl; + m_LibPED = 0; + m_EditPG = 0; + m_EditPE = 0; +} +//--------------------------------------------------------------------------- + +CParticleTool::~CParticleTool() +{ +} +//--------------------------------------------------------------------------- + +bool CParticleTool::OnCreate() +{ + + m_bReady = true; + + Load(0); + + SetAction(etaSelect); + + m_EditPE = (PS::CParticleEffect *)::Render->Models->CreatePE(0); + m_EditPG = (PS::CParticleGroup *)::Render->Models->CreatePG(0); + m_ItemProps = xr_new(); + m_ItemProps->SetModifiedEvent(TOnModifiedEvent(this, &CParticleTool::OnItemModified)); + + // item list + m_PList = xr_new(); + m_PList->m_Flags.set(UIItemListForm::fMenuEdit, true); + m_PList->SetOnItemFocusedEvent(TOnILItemFocused(this, &CParticleTool::OnParticleItemFocused)); + m_PList->SetOnItemCloneEvent(TOnItemClone(this, &CParticleTool::OnParticleCloneItem)); + m_PList->SetOnItemCreaetEvent(TOnItemCreate(this, &CParticleTool::OnParticleCreateItem)); + m_PList->SetOnItemRenameEvent(TOnItemRename(this, &CParticleTool::OnParticleItemRename)); + m_PList->SetOnItemRemoveEvent(TOnItemRemove(this, &CParticleTool::OnParticleItemRemove)); + + m_ParentAnimator = xr_new(); + + m_ObjectProps = xr_new(); + FillObjectPrefs(); + return true; +} + +void CParticleTool::OnDestroy() +{ + VERIFY(m_bReady); + m_bReady = false; + + xr_delete(m_ParentAnimator); + + Lib.RemoveEditObject(m_EditObject); + + xr_delete(m_ObjectProps); + xr_delete(m_ItemProps); + xr_delete(m_PList); + xr_delete(m_EditPG); + xr_delete(m_EditPE); +} +//--------------------------------------------------------------------------- + +bool CParticleTool::IfModified() +{ + if (m_bModified) + { + int mr = ELog.DlgMsg(mtConfirmation, "The particles has been modified.\nDo you want to save your changes?"); + switch (mr) + { + case mrYes: + if (!ExecCommand(COMMAND_SAVE)) + return false; + else + m_bModified = FALSE; + break; + case mrNo: + m_bModified = FALSE; + break; + case mrCancel: + return false; + } + } + return true; +} + +void CParticleTool::Modified() +{ + m_bModified = true; + ExecCommand(COMMAND_UPDATE_CAPTION); +} +//--------------------------------------------------------------------------- + +void CParticleTool::OnItemModified() +{ + Modified(); + if (m_LibPED) + CompileEffect(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CParticleTool::RenderEnvironment() +{ + /* + if (psDeviceFlags.is(rsEnvironment)){ + g_pGamePersistent->Environment().RenderSky (); + g_pGamePersistent->Environment().RenderClouds (); + } + */ +} + +void CParticleTool::Render() +{ + if (!m_bReady) + return; + + PrepareLighting(); + + if (m_EditObject) + m_EditObject->RenderSingle(Fidentity); + // draw parent axis + DU_impl.DrawObjectAxis(m_Transform, 0.05f, true); + // draw domains + switch (m_EditMode) + { + case emNone: + break; + case emEffect: + { + if (m_EditPE && m_EditPE->GetDefinition()) + m_EditPE->GetDefinition()->Render(m_Transform); + } + break; + case emGroup: + { + if (m_EditPG) + { + int cnt = m_EditPG->items.size(); + for (int k = 0; k < cnt; k++) + { + PS::CParticleEffect *E = (PS::CParticleEffect *)m_EditPG->items[k]._effect; + if (E && E->GetDefinition() && m_LibPGD->m_Effects[k]->m_Flags.is(PS::CPGDef::SEffect::flEnabled)) + E->GetDefinition()->Render(m_Transform); + } + } + } + break; + default: + THROW; + } + // Draw the particles. + ::Render->Models->RenderSingle(m_EditPG, Fidentity, 1.f); + ::Render->Models->RenderSingle(m_EditPE, Fidentity, 1.f); + + if (m_Flags.is(flAnimatedPath)) + m_ParentAnimator->DrawPath(); + + //. if (psDeviceFlags.is(rsEnvironment)) g_pGamePersistent->Environment().RenderLast (); + inherited::Render(); +} + +void CParticleTool::OnFrame() +{ + if (!m_bReady) + return; + if (m_EditObject) + m_EditObject->OnFrame(); + + if (m_Flags.is(flAnimatedParent)) + { + m_ParentAnimator->Update(EDevice.fTimeDelta); + if (m_ParentAnimator->IsPlaying()) + { + Fvector new_vel; + new_vel.sub(m_ParentAnimator->XFORM().c, m_Transform.c); + new_vel.div(EDevice.fTimeDelta); + m_Vel.lerp(m_Vel, new_vel, 0.9); + m_Transform = m_ParentAnimator->XFORM(); + m_Flags.set(flApplyParent, TRUE); + } + } + + if (m_Flags.is(flRemoveAction)) + RealRemoveAction(); + if (m_Flags.is(flApplyParent)) + RealApplyParent(); + if (m_Flags.is(flCompileEffect)) + RealCompileEffect(); + + m_EditPE->OnFrame(EDevice.dwTimeDelta); + m_EditPG->OnFrame(EDevice.dwTimeDelta); + + if (m_Flags.is(flRefreshProps)) + RealUpdateProperties(); + + if (m_Flags.is(flSelectEffect)) + { + m_PList->SelectItem(sel_eff_name.c_str()); + m_Flags.set(flSelectEffect, FALSE); + sel_eff_name = ""; + } + + xr_string tmp; + switch (m_EditMode) + { + case emNone: + break; + case emEffect: + if (m_EditPE->IsPlaying()) + { + auto nn = make_string(" PE Playing...[%d]", m_EditPE->ParticlesCount()); + UI->SetStatus(nn.c_str(), false); + } + + else + UI->SetStatus(" Stopped.", false); + break; + case emGroup: + if (m_EditPG->IsPlaying()) + UI->SetStatus(make_string(" PE Playing...[%d]", m_EditPG->ParticlesCount()).c_str(), false); + else + UI->SetStatus(" Stopped.", false); + break; + default: + THROW; + } +} + +void CParticleTool::ZoomObject(BOOL bSelOnly) +{ + VERIFY(m_bReady); + if (!bSelOnly && m_EditObject) + { + EDevice.m_Camera.ZoomExtents(m_EditObject->GetBox()); + } + else + { + Fbox box; + box.invalidate(); + switch (m_EditMode) + { + case emNone: + break; + case emEffect: + box.set(m_EditPE->vis.box); + break; + case emGroup: + box.set(m_EditPG->vis.box); + break; + default: + THROW; + } + if (box.is_valid()) + { + box.grow(1.f); + EDevice.m_Camera.ZoomExtents(box); + } + } +} + +void CParticleTool::PrepareLighting() +{ + // add directional light + Flight L; + ZeroMemory(&L, sizeof(Flight)); + L.type = Flight::Type::Directional; + L.diffuse.set(1, 1, 1, 1); + L.direction.set(1, -1, 1); + L.direction.normalize(); + EDevice.SetLight(0, L); + EDevice.LightEnable(0, true); + + L.diffuse.set(0.3, 0.3, 0.3, 1); + L.direction.set(-1, -1, -1); + L.direction.normalize(); + EDevice.SetLight(1, L); + EDevice.LightEnable(1, true); + + L.diffuse.set(0.3, 0.3, 0.3, 1); + L.direction.set(1, -1, -1); + L.direction.normalize(); + EDevice.SetLight(2, L); + EDevice.LightEnable(2, true); + + L.diffuse.set(0.3, 0.3, 0.3, 1); + L.direction.set(-1, -1, 1); + L.direction.normalize(); + EDevice.SetLight(3, L); + EDevice.LightEnable(3, true); + + L.diffuse.set(1.0, 0.8, 0.7, 1); + L.direction.set(0, 1, 0); + L.direction.normalize(); + EDevice.SetLight(4, L); + EDevice.LightEnable(4, true); +} + +void CParticleTool::OnDeviceCreate() +{ +} + +void CParticleTool::OnDeviceDestroy() +{ +} + +void CParticleTool::SelectPreviewObject(int p) +{ +} + +void CParticleTool::ResetPreviewObject() +{ + VERIFY(m_bReady); + UI->RedrawScene(); +} + +bool CParticleTool::Load(LPCSTR name) +{ + VERIFY(m_bReady); + UpdateProperties(); + return true; +} + +bool CParticleTool::Save(bool bAsXR) +{ + VERIFY(m_bReady); + + // validate + if (!Validate(true)) + { + ELog.DlgMsg(mtError, "Invalid particle's found. Validate library and try again."); + return false; + } + bool bRes = false; + if (bAsXR) + { + bRes = ::Render->PSLibrary.Save(); + } + else + { + bRes = ::Render->PSLibrary.Save2(); + } + + if (bRes) + m_bModified = false; + + return bRes; +} + +void CParticleTool::Reload() +{ + VERIFY(m_bReady); + ResetCurrent(); + ::Render->PSLibrary.Reload(); + // visual part + m_ItemProps->ClearProperties(); + UpdateProperties(true); +} + +void CheckEffect(const xr_string &group_path, const shared_str &eff_full_name, xr_string &res_name, bool bRenameOnly) +{ + res_name = group_path + "effects\\" + EFS.ExtractFileName(eff_full_name.c_str()); + + if (0 != stricmp(res_name.c_str(), eff_full_name.c_str())) + { + PS::CPEDef *old_ped = ::Render->PSLibrary.FindPED(eff_full_name.c_str()); + PS::CPEDef *new_ped = ::Render->PSLibrary.FindPED(res_name.c_str()); + if (bRenameOnly) + { + ::Render->PSLibrary.Remove(res_name.c_str()); + new_ped = NULL; + } + + if (!new_ped) + { + new_ped = (bRenameOnly) ? old_ped : ::Render->PSLibrary.AppendPED(old_ped); + new_ped->m_Name = res_name.c_str(); + if (bRenameOnly) + Msg("rename effect [%s]->[%s]", eff_full_name.c_str(), res_name.c_str()); + else + Msg("create new effect [%s]", res_name.c_str()); + } + VERIFY(0 == stricmp(new_ped->m_Name.c_str(), res_name.c_str())); + } +} + +CCommandVar CParticleTool::CreateGroupFromSelected(CCommandVar p1, CCommandVar p2) +{ + /*PS::CPEDef* curr = m_LibPED; + if(!curr) + { + ELog.DlgMsg (mtError,"Select Effect first."); + return false; + } + const shared_str& eff_name = curr->m_Name; + PS::CPGDef* pg = AppendPG(0); + + xr_string grp_name = eff_name.c_str(); + pg->m_Name = grp_name.c_str(); + + pg->m_fTimeLimit = 0.0f; + PS::CPGDef::SEffect* eff = xr_new(); + pg->m_Effects.push_back (eff); + eff->m_EffectName = eff_name; + + eff->m_Flags.set (PS::CPGDef::SEffect::flEnabled,TRUE); + eff->m_Time0 = 0.0f; + eff->m_Time1 = 0.0f; + + + xr_string tmp; + xr_string group_path = EFS.ExtractFilePath(grp_name.c_str()); + CheckEffect (group_path, eff->m_EffectName, tmp, true); + + eff->m_EffectName = tmp.c_str(); + + curr->m_Name = tmp.c_str(); + + ExecCommand (COMMAND_UPDATE_PROPERTIES); + + m_PList->SelectItem (grp_name.c_str());*/ + + return TRUE; +} + +CCommandVar CParticleTool::Compact(CCommandVar p1, CCommandVar p2) +{ + if (!Validate(true)) + { + ELog.DlgMsg(mtError, "Invalid particle's found. Validate library and try again."); + return false; + } + + for (PS::PGDIt g_it = ::Render->PSLibrary.FirstPGD(); g_it != ::Render->PSLibrary.LastPGD(); ++g_it) + { + PS::CPGDef *pg = (*g_it); + shared_str &group_name = pg->m_Name; + xr_string group_path = EFS.ExtractFilePath(group_name.c_str()); + + xr_vector::const_iterator pe_it = pg->m_Effects.begin(); + xr_vector::const_iterator pe_it_e = pg->m_Effects.end(); + + xr_string tmp; + + for (; pe_it != pe_it_e; ++pe_it) + { + PS::CPGDef::SEffect *Eff = (*pe_it); + CheckEffect(group_path, Eff->m_EffectName, tmp, false); + Eff->m_EffectName = tmp.c_str(); + + if (Eff->m_Flags.test(PS::CPGDef::SEffect::flOnPlayChild)) + { + CheckEffect(group_path, Eff->m_OnPlayChildName, tmp, false); + Eff->m_OnPlayChildName = tmp.c_str(); + } + if (Eff->m_Flags.test(PS::CPGDef::SEffect::flOnBirthChild)) + { + CheckEffect(group_path, Eff->m_OnBirthChildName, tmp, false); + Eff->m_OnBirthChildName = tmp.c_str(); + } + if (Eff->m_Flags.test(PS::CPGDef::SEffect::flOnDeadChild)) + { + CheckEffect(group_path, Eff->m_OnDeadChildName, tmp, false); + Eff->m_OnDeadChildName = tmp.c_str(); + } + } + } + + ResetCurrent(); + UpdateProperties(true); + + return TRUE; +} + +bool CParticleTool::Validate(bool bMsg) +{ + if (bMsg) + ELog.Msg(mtInformation, "Begin validation..."); + PS::PEDIt _eI = ::Render->PSLibrary.FirstPED(); + PS::PEDIt _eE = ::Render->PSLibrary.LastPED(); + u32 error_cnt = 0; + for (; _eI != _eE; ++_eI) + { + if (!(*_eI)->Validate(bMsg)) + error_cnt++; + } + for (PS::PGDIt g_it = ::Render->PSLibrary.FirstPGD(); g_it != ::Render->PSLibrary.LastPGD(); ++g_it) + { + PS::CPGDef *pg = (*g_it); + if (!pg->Validate(bMsg)) + error_cnt++; + } + + if (bMsg) + { + if (error_cnt > 0) + ELog.DlgMsg(mtError, "Validation FAILED! Found %d error's.", error_cnt); + else + ELog.DlgMsg(mtInformation, "Validation OK."); + } + return error_cnt == 0; +} + +void CParticleTool::Rename(LPCSTR old_full_name, LPCSTR ren_part, int level) +{ + VERIFY(level < _GetItemCount(old_full_name, '\\')); + xr_string new_full_name; + Rename(old_full_name, new_full_name.c_str()); +} + +void CParticleTool::Rename(LPCSTR old_full_name, LPCSTR new_full_name) +{ + VERIFY(m_bReady); + // is effect + PS::CPEDef *E = ::Render->PSLibrary.FindPED(old_full_name); + if (E) + { + ::Render->PSLibrary.RenamePED(E, new_full_name); + return; + } + // is group + PS::CPGDef *G = ::Render->PSLibrary.FindPGD(old_full_name); + if (G) + { + ::Render->PSLibrary.RenamePGD(G, new_full_name); + return; + } +} + +void CParticleTool::Remove(LPCSTR name) +{ + + if (::Render->PSLibrary.FindPED(name) == m_LibPED || ::Render->PSLibrary.FindPGD(name) == m_LibPGD) + { + m_ItemProps->ClearProperties(); + } + + VERIFY(m_bReady); + SetCurrentPE(0); + SetCurrentPG(0); + ::Render->PSLibrary.Remove(name); +} + +void CParticleTool::RemoveCurrent() +{ + R_ASSERT(0); +} + +void CParticleTool::CloneCurrent() +{ + R_ASSERT(0); +} + +void CParticleTool::ResetCurrent() +{ + VERIFY(m_bReady); + if (m_LibPED) + m_EditPE->Stop(FALSE); + if (m_LibPGD) + m_EditPG->Stop(FALSE); + m_LibPED = 0; + m_LibPGD = 0; +} + +void CParticleTool::SetCurrentPE(PS::CPEDef *P) +{ + VERIFY(m_bReady); + m_EditPG->Compile(0); + if (m_LibPED != P) + { + m_LibPED = P; + m_EditPE->Compile(m_LibPED); + if (m_LibPED) + m_EditMode = emEffect; + } +} + +void CParticleTool::SetCurrentPG(PS::CPGDef *P) +{ + VERIFY(m_bReady); + m_EditPE->Compile(0); + if (m_LibPGD != P) + { + m_LibPGD = P; + m_EditPG->Compile(m_LibPGD); + if (m_LibPGD) + m_EditMode = emGroup; + } +} + +void CParticleTool::DrawReferenceList() +{ + if (m_EditMode == emGroup) + { + if (m_EditPG->GetDefinition()) + { + xr_vector::const_iterator pe_it = m_EditPG->GetDefinition()->m_Effects.begin(); + xr_vector::const_iterator pe_it_e = m_EditPG->GetDefinition()->m_Effects.end(); + for (; pe_it != pe_it_e; ++pe_it) + { + ImGui::Text((*pe_it)->m_EffectName.c_str() ? (*pe_it)->m_EffectName.c_str() : 0); + } + if (m_EditPG->GetDefinition()->m_Flags.test(PS::CPGDef::SEffect::flOnPlayChild)) + ImGui::Text((*pe_it)->m_OnPlayChildName.c_str()); + if (m_EditPG->GetDefinition()->m_Flags.test(PS::CPGDef::SEffect::flOnBirthChild)) + ImGui::Text((*pe_it)->m_OnBirthChildName.c_str()); + if (m_EditPG->GetDefinition()->m_Flags.test(PS::CPGDef::SEffect::flOnDeadChild)) + ImGui::Text((*pe_it)->m_OnDeadChildName.c_str()); + } + } + else + { + if (m_EditPE->GetDefinition()) + { + PS::PGDIt G = ::Render->PSLibrary.FirstPGD(); + PS::PGDIt G_e = ::Render->PSLibrary.LastPGD(); + for (; G != G_e; ++G) + { + PS::CPGDef *def = (*G); + auto pe_it = def->m_Effects.begin(); + auto pe_it_e = def->m_Effects.end(); + for (; pe_it != pe_it_e; ++pe_it) + { + if ((*pe_it)->m_EffectName == m_EditPE->Name()) + ImGui::Text(def->m_Name.c_str()); + else if ((*pe_it)->m_OnPlayChildName == m_EditPE->Name()) + ImGui::Text(def->m_Name.c_str()); + else if ((*pe_it)->m_OnBirthChildName == m_EditPE->Name()) + ImGui::Text(def->m_Name.c_str()); + else if ((*pe_it)->m_OnDeadChildName == m_EditPE->Name()) + ImGui::Text(def->m_Name.c_str()); + } + } + } + } +} + +void CParticleTool::CommandJumpToItem() +{ + /* for(int i=0; irefLB->Count; ++i) + { + if(fraLeftBar->refLB->Selected[i]) + { + m_PList->SelectItem((fraLeftBar->refLB->Items->Strings[i]).c_str(),true,false,true); + break; + } + }*/ +} + +PS::CPEDef *CParticleTool::FindPE(LPCSTR name) +{ + return ::Render->PSLibrary.FindPED(name); +} + +PS::CPGDef *CParticleTool::FindPG(LPCSTR name) +{ + return ::Render->PSLibrary.FindPGD(name); +} + +void CParticleTool::PlayCurrent(int idx) +{ + VERIFY(m_bReady); + StopCurrent(false); + switch (m_EditMode) + { + case emNone: + break; + case emEffect: + m_EditPE->Play(); + break; + case emGroup: + if (idx > -1) + { + VERIFY(idx < (int)m_EditPG->items.size()); + m_LibPED = ((PS::CParticleEffect *)m_EditPG->items[idx]._effect)->GetDefinition(); + m_EditPE->Compile(m_LibPED); + m_EditPE->Play(); + } + else + { + // play all + m_EditPG->Play(); + } + break; + default: + THROW; + } + ApplyParent(); +} + +void CParticleTool::StopCurrent(bool bFinishPlaying) +{ + VERIFY(m_bReady); + m_EditPE->Stop(bFinishPlaying); + m_EditPG->Stop(bFinishPlaying); +} + +void CParticleTool::SelectEffect(LPCSTR name) +{ + sel_eff_name = name; + m_Flags.set(flSelectEffect, TRUE); +} + +void CParticleTool::OnShowHint(AStringVec &SS) +{ +} + +bool CParticleTool::MouseStart(TShiftState Shift) +{ + inherited::MouseStart(Shift); + switch (m_Action) + { + case etaSelect: + break; + case etaAdd: + break; + case etaMove: + { + if (Shift | ssCtrl) + { + if (m_EditObject) + { + float dist = UI->ZFar(); + SRayPickInfo pinf; + if (m_EditObject->RayPick(dist, UI->m_CurrentRStart, UI->m_CurrentRDir, Fidentity, &pinf)) + m_Transform.c.set(pinf.pt); + } + else + { + // pick grid + Fvector normal = {0.f, 1.f, 0.f}; + float clcheck = UI->m_CurrentRDir.dotproduct(normal); + if (fis_zero(clcheck)) + return false; + float alpha = -UI->m_CurrentRStart.dotproduct(normal) / clcheck; + if (alpha <= 0) + return false; + + m_Transform.c.mad(UI->m_CurrentRStart, UI->m_CurrentRDir, alpha); + + if (m_Settings.is(etfGSnap)) + { + m_Transform.c.x = snapto(m_Transform.c.x, m_MoveSnap); + m_Transform.c.z = snapto(m_Transform.c.z, m_MoveSnap); + m_Transform.c.y = 0.f; + } + } + } + } + break; + case etaRotate: + break; + case etaScale: + break; + } + ApplyParent(); + return m_bHiddenMode; +} + +bool CParticleTool::MouseEnd(TShiftState Shift) +{ + inherited::MouseEnd(Shift); + return true; +} + +void CParticleTool::MouseMove(TShiftState Shift) +{ + inherited::MouseMove(Shift); + switch (m_Action) + { + case etaSelect: + break; + case etaAdd: + break; + case etaMove: + m_Transform.c.add(m_MovedAmount); + break; + case etaRotate: + { + Fmatrix mR; + mR.identity(); + if (!fis_zero(m_RotateVector.x)) + mR.rotateX(m_RotateAmount); + else if (!fis_zero(m_RotateVector.y)) + mR.rotateY(m_RotateAmount); + else if (!fis_zero(m_RotateVector.z)) + mR.rotateZ(m_RotateAmount); + m_Transform.mulB_43(mR); + } + break; + case etaScale: + break; + } + ApplyParent(); +} +//------------------------------------------------------------------------------ + +void CParticleTool::RealApplyParent() +{ + switch (m_EditMode) + { + case emNone: + break; + case emEffect: + m_EditPE->UpdateParent(m_Transform, m_Vel, m_Flags.is(flSetXFORM)); + break; + case emGroup: + m_EditPG->UpdateParent(m_Transform, m_Vel, m_Flags.is(flSetXFORM)); + break; + default: + THROW; + } + m_Flags.set(flApplyParent, FALSE); +} + +void CParticleTool::RealCompileEffect() +{ + if (m_LibPED) + m_LibPED->Compile(m_LibPED->m_EActionList); + m_Flags.set(flCompileEffect, FALSE); +} + +void CParticleTool::RealRemoveAction() +{ + if (m_LibPED) + { + xr_delete(m_LibPED->m_EActionList[remove_action_num]); + m_LibPED->m_EActionList.erase(m_LibPED->m_EActionList.begin() + remove_action_num); + } + m_Flags.set(flRemoveAction, FALSE); +} + +LPCSTR CParticleTool::GetInfo() +{ + return 0; +} +//------------------------------------------------------------------------------ + +void CParticleTool::SelectListItem(LPCSTR pref, LPCSTR name, bool bVal, bool bLeaveSel, bool bExpand) +{ + xr_string nm = (name && name[0]) ? PrepareKey(pref, name).c_str() : pref; + m_PList->SelectItem(nm.c_str()); + if (pref) + { + m_PList->SelectItem(pref); + } +} +//------------------------------------------------------------------------------ + +PS::CPEDef *CParticleTool::AppendPE(PS::CPEDef *src, const char *path) +{ + VERIFY(m_bReady); + PS::CPEDef *S = ::Render->PSLibrary.AppendPED(src); + S->m_Name = path; + ExecCommand(COMMAND_UPDATE_PROPERTIES, true); + SelectListItem(0, path, true, false, true); + return S; +} + +PS::CPGDef *CParticleTool::AppendPG(PS::CPGDef *src, const char *path) +{ + VERIFY(m_bReady); + PS::CPGDef *S = ::Render->PSLibrary.AppendPGD(src); + S->m_Name = path; + + ExecCommand(COMMAND_UPDATE_PROPERTIES, true); + SelectListItem(0, path, true, false, true); + return S; +} + +#include "../xrECore/Editor/EditMesh.h" + +bool CParticleTool::RayPick(const Fvector &start, const Fvector &dir, float &dist, Fvector *pt, Fvector *n) +{ + if (m_EditObject) + { + SRayPickInfo pinf; + if (m_EditObject->RayPick(dist, start, dir, Fidentity, &pinf)) + { + if (pt) + pt->set(pinf.pt); + if (n) + { + const Fvector *PT[3]; + pinf.e_mesh->GetFacePT(pinf.inf.id, PT); + n->mknormal(*PT[0], *PT[1], *PT[2]); + } + return true; + } + else + return false; + } + else + { + Fvector np; + np.mad(start, dir, dist); + if ((start.y > 0) && (np.y < 0.f)) + { + if (pt) + pt->set(start); + if (n) + n->set(0.f, 1.f, 0.f); + return true; + } + else + return false; + } +} + +void CParticleTool::OnChangeMotion(PropValue *sender) +{ + ChooseValue *V = dynamic_cast(sender); + if (V) + { + m_ParentAnimator->Clear(); + if (V->value->size()) + m_ParentAnimator->Load(V->value->c_str()); + } + if (m_Flags.is(flAnimatedParent)) + m_ParentAnimator->Play(true); + FillObjectPrefs(); +} + +void CParticleTool::OnChangeObject(PropValue *sender) +{ + ChooseValue *V = dynamic_cast(sender); + if (V) + { + Lib.RemoveEditObject(m_EditObject); + m_EditObject = V->value->c_str() ? Lib.CreateEditObject(V->value->c_str()) : 0; + // ZoomObject(TRUE); + + UI->RedrawScene(); + } + FillObjectPrefs(); +} + +void CParticleTool::FillObjectPrefs() +{ + PropItemVec items; + m_MotionName = m_ParentAnimator->Name(); + PropValue *V; + V = PHelper().CreateChoose(items, "Object", &m_ObjectName, smObject); + V->OnChangeEvent.bind(this, &CParticleTool::OnChangeObject); + V = PHelper().CreateFlag32(items, "Parent\\Allow Animated", &m_Flags, flAnimatedParent); + V->OnChangeEvent.bind(this, &CParticleTool::OnChangeMotion); + PHelper().CreateFlag32(items, "Parent\\Draw Path", &m_Flags, flAnimatedPath); + V = PHelper().CreateChoose(items, "Parent\\Motion", &m_MotionName, smGameAnim); + V->OnChangeEvent.bind(this, &CParticleTool::OnChangeMotion); + PHelper().CreateFloat(items, "Parent\\Motion Speed", &m_ParentAnimator->Speed(), 0.f, 10000.f); + m_ObjectProps->AssignItems(items); +} + +bool CParticleTool::GetSelectionPosition(Fmatrix &result) +{ + result = m_Transform; + return true; +} diff --git a/src/editors/ParticleEditor/UI_ParticleTools.h b/src/editors/ParticleEditor/UI_ParticleTools.h new file mode 100644 index 00000000000..33b8bee183d --- /dev/null +++ b/src/editors/ParticleEditor/UI_ParticleTools.h @@ -0,0 +1,211 @@ +#pragma once +#include "Layers/xrRender/ParticleEffect.h" +#include "Layers/xrRender/ParticleGroup.h" + +// refs +class CEditableObject; +class CObjectAnimator; + +enum EEditMode +{ + emNone, + emEffect, + emGroup +}; + +class CParticleTool : public CToolCustom +{ + typedef CToolCustom inherited; + void FillChooseParticleType(ChooseItemVec &items, void *param); + bool m_CreatingParticle; + xr_string m_CreatingParticlePath; + CEditableObject *m_EditObject; + bool m_bModified; + + shared_str m_MotionName; + shared_str m_ObjectName; + // PE variables + PS::CPEDef *m_LibPED; + PS::CParticleEffect *m_EditPE; + + // PG variables + PS::CPGDef *m_LibPGD; + PS::CParticleGroup *m_EditPG; + + Fmatrix m_Transform; + Fvector m_Vel; + + void OnItemModified(void); + + void OnParticleItemFocused(ListItem *items); + void OnParticleCloneItem(LPCSTR parent_path, LPCSTR new_full_name); + void OnParticleCreateItem(LPCSTR path); + void OnParticleItemRename(LPCSTR old_name, LPCSTR new_name, EItemType type); + void OnParticleItemRemove(LPCSTR name, EItemType type); + + void RealUpdateProperties(); + void SelectListItem(LPCSTR pref, LPCSTR name, bool bVal, bool bLeaveSel, bool bExpand); + + void RealApplyParent(); + void ApplyParent(bool bForce = false) + { + m_Flags.set(flApplyParent, TRUE); + if (bForce) + RealApplyParent(); + } + void RealCompileEffect(); + void CompileEffect(bool bForced = false) + { + m_Flags.set(flCompileEffect, TRUE); + if (bForced) + RealCompileEffect(); + } + u32 remove_action_num; + void RealRemoveAction(); + + void OnControlClick(ButtonValue *sender, bool &bDataModified, bool &bSafe); + +public: + void RemoveAction(u32 idx, bool bForced = false) + { + remove_action_num = idx; + m_Flags.set(flRemoveAction, TRUE); + if (bForced) + RealRemoveAction(); + } + +public: + EEditMode m_EditMode; + UIPropertiesForm *m_ObjectProps; + UIPropertiesForm *m_ItemProps; + UIItemListForm *m_PList; + UIItemListForm *m_RList; + +public: + // flags + enum + { + flRefreshProps = (1 << 0), + flApplyParent = (1 << 1), + flCompileEffect = (1 << 2), + flRemoveAction = (1 << 3), + flAnimatedParent = (1 << 4), + flAnimatedPath = (1 << 5), + flSelectEffect = (1 << 6), + flSetXFORM = (1 << 7), + }; + Flags32 m_Flags; + +protected: + xr_string sel_eff_name; + + void OnChangeMotion(PropValue *sender); + void OnChangeObject(PropValue *sender); + CObjectAnimator *m_ParentAnimator; + + void PrepareLighting(); + +public: + CParticleTool(); + virtual ~CParticleTool(); + + virtual void Render(); + virtual void RenderEnvironment(); + virtual void OnFrame(); + + virtual bool OnCreate(); + virtual void OnDestroy(); + + virtual bool IfModified(); + virtual bool IsModified() { return m_bModified; } + virtual void Modified(); + + virtual LPCSTR GetInfo(); + + virtual void ZoomObject(BOOL bSelOnly); + + virtual bool Load(LPCSTR name); + virtual bool Save(LPCSTR name, bool bInternal = false) + { + R_ASSERT(0); + return true; + }; + bool Save(bool bAsXR); + virtual void Reload(); + + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + + virtual void Clear() { inherited::Clear(); } + + virtual void OnShowHint(AStringVec &SS); + + virtual bool MouseStart(TShiftState Shift); + virtual bool MouseEnd(TShiftState Shift); + virtual void MouseMove(TShiftState Shift); + + virtual bool Pick(TShiftState Shift) { return false; } + virtual bool RayPick(const Fvector &start, const Fvector &dir, float &dist, Fvector *pt, Fvector *n); + + virtual void ShowProperties(LPCSTR) { ; } + virtual void UpdateProperties(BOOL bForced = FALSE) + { + m_Flags.set(flRefreshProps, TRUE); + if (bForced) + RealUpdateProperties(); + } + virtual void RefreshProperties() { ; } + + void PlayCurrent(int idx = -1); + void StopCurrent(bool bFinishPlaying); + void SelectEffect(LPCSTR name); + + void Rename(LPCSTR src_name, LPCSTR part_name, int part_idx); + void Rename(LPCSTR src_name, LPCSTR dest_name); + + // PS routine + void CloneCurrent(); + void ResetCurrent(); + void RemoveCurrent(); + void Remove(LPCSTR name); + + // PG routine + PS::CPEDef *FindPE(LPCSTR name); + PS::CPEDef *AppendPE(PS::CPEDef *src, const char *path); + void SetCurrentPE(PS::CPEDef *P); + void CommandJumpToItem(); + + // PG routine + PS::CPGDef *FindPG(LPCSTR name); + PS::CPGDef *AppendPG(PS::CPGDef *src, const char *path); + void SetCurrentPG(PS::CPGDef *P); + void DrawReferenceList(); + + void SelectPreviewObject(int p); + void ResetPreviewObject(); + void FillObjectPrefs(); + + bool Validate(bool bMsg); + + virtual bool GetSelectionPosition(Fmatrix &result); + + CCommandVar Compact(CCommandVar p1, CCommandVar p2); + CCommandVar CreateGroupFromSelected(CCommandVar p1, CCommandVar p2); + // commands + CCommandVar CommandSelectPreviewObj(CCommandVar p1, CCommandVar p2); + CCommandVar CommandEditPreviewProps(CCommandVar p1, CCommandVar p2); + CCommandVar CommandSave(CCommandVar p1, CCommandVar p2); + CCommandVar CommandSaveXR(CCommandVar p1, CCommandVar p2); + CCommandVar CommandLoadXR(CCommandVar p1, CCommandVar p2); + CCommandVar CommandSaveBackup(CCommandVar p1, CCommandVar p2); + CCommandVar CommandReload(CCommandVar p1, CCommandVar p2); + CCommandVar CommandValidate(CCommandVar p1, CCommandVar p2); + CCommandVar CommandClear(CCommandVar p1, CCommandVar p2); + CCommandVar CommandPlayCurrent(CCommandVar p1, CCommandVar p2); + CCommandVar CommandStopCurrent(CCommandVar p1, CCommandVar p2); + void OnDrawUI(); +}; +#define SYSTEM_PREFIX "Systems" +#define EFFECT_PREFIX "Effects" +#define GROUP_PREFIX "Groups" +extern CParticleTool *PTools; diff --git a/src/editors/ParticleEditor/UI_ParticleToolsProps.cpp b/src/editors/ParticleEditor/UI_ParticleToolsProps.cpp new file mode 100644 index 00000000000..01d6d203622 --- /dev/null +++ b/src/editors/ParticleEditor/UI_ParticleToolsProps.cpp @@ -0,0 +1,165 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "UI_ParticleTools.h" + +void CParticleTool::OnDrawUI() +{ + if (m_LibPED) + m_LibPED->OnDrawUI(); + if (m_CreatingParticle) + { + bool change; + shared_str result; + if (UIChooseForm::GetResult(change, result)) + { + if (change) + { + if (result == "Effect") + { + AppendPE(0, m_CreatingParticlePath.c_str()); + } + else + { + AppendPG(0, m_CreatingParticlePath.c_str()); + } + } + m_CreatingParticle = FALSE; + } + UIChooseForm::Update(); + } +} +void CParticleTool::FillChooseParticleType(ChooseItemVec &items, void *param) +{ + items.push_back(SChooseItem("Effect", "Effect Patricle")); + items.push_back(SChooseItem("Group", "Group Patricle")); +} +void CParticleTool::OnParticleCreateItem(LPCSTR path) +{ + UIChooseForm::SelectItem(smCustom, 1, 0, TOnChooseFillItems(this, &CParticleTool::FillChooseParticleType), 0, 0, 0, 0); + m_CreatingParticle = TRUE; + m_CreatingParticlePath = path; +} +void CParticleTool::OnParticleCloneItem(LPCSTR parent_path, LPCSTR new_full_name) +{ + PS::CPEDef *PE = FindPE(parent_path); + if (PE) + { + AppendPE(PE, new_full_name); + Modified(); + } + else + { + PS::CPGDef *PG = FindPG(parent_path); + if (PG) + { + AppendPG(PG, new_full_name); + Modified(); + } + } +} + +void CParticleTool::OnParticleItemRename(LPCSTR old_name, LPCSTR new_name, EItemType type) +{ + Rename(old_name, new_name); + Modified(); +} + +void CParticleTool::OnParticleItemRemove(LPCSTR name, EItemType type) +{ + Remove(name); + Modified(); +} + +void CParticleTool::OnControlClick(ButtonValue *sender, bool &bDataModified, bool &bSafe) +{ + m_Transform.identity(); + bDataModified = false; +} + +void CParticleTool::OnParticleItemFocused(ListItem *items) +{ + PropItemVec props; + m_EditMode = emEffect; + + ButtonValue *B; + B = PHelper().CreateButton(props, "Transform\\Edit", "Reset", ButtonValue::flFirstOnly); + B->OnBtnClickEvent = ButtonValue::TOnBtnClick(this, &CParticleTool::OnControlClick); + PHelper().CreateFlag32(props, "Transform\\Type", &m_Flags, flSetXFORM, "Update", "Set"); + + // reset to default + ResetCurrent(); + + if (items) + { + + ListItem *item = items; + if (item) + { + m_EditMode = EEditMode(item->Type()); + switch (m_EditMode) + { + case emEffect: + { + PS::CPEDef *def = ((PS::CPEDef *)item->m_Object); + SetCurrentPE(def); + def->FillProp(EFFECT_PREFIX, props, item); + } + break; + case emGroup: + { + PS::CPGDef *def = ((PS::CPGDef *)item->m_Object); + SetCurrentPG(def); + def->FillProp(GROUP_PREFIX, props, item); + } + break; + default: + THROW; + } + } + } + m_ItemProps->AssignItems(props); + UI->RedrawScene(); +} + +//------------------------------------------------------------------------------ +extern xr_string _item_to_select_after_edit; + +void CParticleTool::RealUpdateProperties() +{ + m_Flags.set(flRefreshProps, FALSE); + + ListItemsVec items; + { + PS::PEDIt Pe = ::Render->PSLibrary.FirstPED(); + PS::PEDIt Ee = ::Render->PSLibrary.LastPED(); + for (; Pe != Ee; Pe++) + { + ListItem *I = LHelper().CreateItem(items, *(*Pe)->m_Name, emEffect, 0, *Pe); + I->SetIcon(1); + } + } + { + PS::PGDIt Pg = ::Render->PSLibrary.FirstPGD(); + PS::PGDIt Eg = ::Render->PSLibrary.LastPGD(); + for (; Pg != Eg; Pg++) + { + ListItem *I = LHelper().CreateItem(items, *(*Pg)->m_Name, emGroup, 0, *Pg); + I->SetIcon(2); + } + } + m_PList->AssignItems(items, nullptr, false, true); + if (_item_to_select_after_edit.size()) + { + m_PList->SelectItem(_item_to_select_after_edit.c_str()); + _item_to_select_after_edit = ""; + } + else + { + if (m_EditPG && m_EditPG->GetDefinition()) + m_PList->SelectItem(m_EditPG->Name().c_str()); + if (m_EditPE && m_EditPE->GetDefinition()) + m_PList->SelectItem(m_EditPE->Name().c_str()); + } +} diff --git a/src/editors/ParticleEditor/noise.cpp b/src/editors/ParticleEditor/noise.cpp new file mode 100644 index 00000000000..14df58582e0 --- /dev/null +++ b/src/editors/ParticleEditor/noise.cpp @@ -0,0 +1,181 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "noise.h" + +//============================================================================== +// Perlin's noise from Texturing and Modeling... +#define B 256 + +#define DOT(a, b) (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]) +#define AT(rx, ry, rz) (rx * q[0] + ry * q[1] + rz * q[2]); +#define S_CURVE(t) (t * t * (3.f - 2.f * t)) +#define LERP(t, a, b) (a + t * (b - a)) +#define PN_SETUP(i, b0, b1, r0, r1) \ + t = vec[i] + 10000.f; \ + b0 = iFloor(t) & (B - 1); \ + b1 = (b0 + 1) & (B - 1); \ + r0 = t - iFloor(t); \ + r1 = r0 - 1.f; + +static int start = 1; +static int p[B + B + 2]; +static float g[B + B + 2][3]; + +void noise3Init(); + +//-------------------------------------------------------------------- +float noise3(const Fvector &vec) +{ + int bx0, bx1; + int by0, by1; + int bz0, bz1; + int b00, b10, b01, b11; + float rx0, rx1; + float ry0, ry1; + float rz0, rz1; + float *q; + float sx, sy, sz; + float a, b, c, d, t, u, v; + int i, j; + + if (start) + { + start = 0; + noise3Init(); + } + + PN_SETUP(0, bx0, bx1, rx0, rx1); + PN_SETUP(1, by0, by1, ry0, ry1); + PN_SETUP(2, bz0, bz1, rz0, rz1); + + i = p[bx0]; + j = p[bx1]; + + b00 = p[i + by0]; + b10 = p[j + by0]; + b01 = p[i + by1]; + b11 = p[j + by1]; + + sx = S_CURVE(rx0); + sy = S_CURVE(ry0); + sz = S_CURVE(rz0); + + q = g[b00 + bz0]; + u = AT(rx0, ry0, rz0); + q = g[b10 + bz0]; + v = AT(rx1, ry0, rz0); + a = LERP(sx, u, v); + + q = g[b01 + bz0]; + u = AT(rx0, ry1, rz0); + q = g[b11 + bz0]; + v = AT(rx1, ry1, rz0); + b = LERP(sx, u, v); + + c = LERP(sy, a, b); + + q = g[b00 + bz1]; + u = AT(rx0, ry0, rz1); + q = g[b10 + bz1]; + v = AT(rx1, ry0, rz1); + a = LERP(sx, u, v); + + q = g[b01 + bz1]; + u = AT(rx0, ry1, rz1); + q = g[b11 + bz1]; + v = AT(rx1, ry1, rz1); + b = LERP(sx, u, v); + + d = LERP(sy, a, b); + + return 1.5f * LERP(sz, c, d); +} + +//-------------------------------------------------------------------- +void noise3Init() +{ + int i, j, k; + float v[3], s; + int rnd; + + srand(1); + + for (i = 0; i < B; i++) + { + do + { + for (j = 0; j < 3; j++) + { + rnd = rand(); + v[j] = float((rnd % (B + B)) - B) / B; + } + s = DOT(v, v); + } while (s > 1.0); + s = _sqrt(s); + for (j = 0; j < 3; j++) + g[i][j] = v[j] / s; + } + + for (i = 0; i < B; i++) + p[i] = i; + + for (i = B; i > 0; i -= 2) + { + rnd = rand(); + k = p[i]; + p[i] = p[(j = rnd % B)]; + p[j] = k; + } + + for (i = 0; i < B + 2; i++) + { + p[B + i] = p[i]; + for (j = 0; j < 3; j++) + g[B + i][j] = g[i][j]; + } +} + +//-------------------------------------------------------------------- +float fractalsum3(const Fvector &v, float freq, int octaves) +{ + int i; + float sum = 0.0; + Fvector v_; + float boost = freq; + v_[0] = v[0] * freq; + v_[1] = v[1] * freq; + v_[2] = v[2] * freq; + + for (i = 0; i < octaves; i++) + { + sum += noise3(v_) / freq; + freq *= 2.059f; + v_[0] = v[0] * freq; + v_[1] = v[1] * freq; + v_[2] = v[2] * freq; + } + return sum * boost; +} + +//-------------------------------------------------------------------- +float turbulence3(const Fvector &v, float freq, int octaves) +{ + int i; + float sum = 0.0; + Fvector v_; + float boost = freq; + v_[0] = v[0] * freq; + v_[1] = v[1] * freq; + v_[2] = v[2] * freq; + + for (i = 0; i < octaves; i++) + { + sum += _abs(noise3(v_)) / freq; + freq *= 2.059f; + v_[0] = v[0] * freq; + v_[1] = v[1] * freq; + v_[2] = v[2] * freq; + } + return sum * boost; +} diff --git a/src/editors/ParticleEditor/noise.h b/src/editors/ParticleEditor/noise.h new file mode 100644 index 00000000000..b5c83c917f1 --- /dev/null +++ b/src/editors/ParticleEditor/noise.h @@ -0,0 +1,8 @@ +#ifndef noiseH +#define noiseH + +float noise3(const Fvector &vec); +float fractalsum3(const Fvector &v, float freq, int octaves); +float turbulence3(const Fvector &v, float freq, int octaves); + +#endif diff --git a/src/editors/ParticleEditor/resources/ParticleEditor.rc b/src/editors/ParticleEditor/resources/ParticleEditor.rc new file mode 100644 index 00000000000..7ef65f67d39 --- /dev/null +++ b/src/editors/ParticleEditor/resources/ParticleEditor.rc @@ -0,0 +1,71 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// () resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_RUS) +LANGUAGE LANG_RUSSIAN, SUBLANG_DEFAULT +#pragma code_page(1251) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +MAINICON ICON "resources\\pe.ico" + +#endif // () resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/editors/ParticleEditor/resources/pe.ico b/src/editors/ParticleEditor/resources/pe.ico new file mode 100644 index 00000000000..92a2adb295c Binary files /dev/null and b/src/editors/ParticleEditor/resources/pe.ico differ diff --git a/src/editors/ParticleEditor/resources/resource.h b/src/editors/ParticleEditor/resources/resource.h new file mode 100644 index 00000000000..6208502b73f --- /dev/null +++ b/src/editors/ParticleEditor/resources/resource.h @@ -0,0 +1,17 @@ +//{{NO_DEPENDENCIES}} +// , Microsoft Visual C++. +// ParticleEditor.rc +// +#define MAINICON 5 +#define IDI_ICON1 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/editors/ParticleEditor/stdafx.cpp b/src/editors/ParticleEditor/stdafx.cpp new file mode 100644 index 00000000000..7c723d4178b --- /dev/null +++ b/src/editors/ParticleEditor/stdafx.cpp @@ -0,0 +1,4 @@ +#include "stdafx.h" +#pragma hdrstop + +// external dependencies diff --git a/src/editors/ParticleEditor/stdafx.h b/src/editors/ParticleEditor/stdafx.h new file mode 100644 index 00000000000..fbcb36a3c1d --- /dev/null +++ b/src/editors/ParticleEditor/stdafx.h @@ -0,0 +1,22 @@ +#pragma once +#include "..\xrECore\stdafx.h" +#include "..\xrECore\Editor\device.h" +#include "..\xrECore\Editor\UI_MainCommand.h" +#include "..\xrECore\Editor\UI_ToolsCustom.h" +#include "..\xrECore\Editor\ui_main.h" +#include "..\xrECore\Editor\EditorPreferences.h" +#include "..\xrECore\Editor\render.h" +#include "..\xrECore\Editor\UIRenderForm.h" +#include "..\xrECore\Editor\ELog.h" +#include "..\xrECore\Editor\Library.h" + +#include "../xrECore/Editor/D3DUtils.h" + +#include "UI_ParticleMain.h" +#include "UI_ParticleTools.h" + +#include "UITopBarForm.h" +#include "UILeftBarForm.h" +#include "UIRightBarForm.h" +#include "UIMainMenuForm.h" +#include "UIMainForm.h" diff --git a/src/editors/Public/NVMeshMender.h b/src/editors/Public/NVMeshMender.h new file mode 100644 index 00000000000..63dbebe8bef --- /dev/null +++ b/src/editors/Public/NVMeshMender.h @@ -0,0 +1,363 @@ +/*********************************************************************NVMH4**** +Path: +File: + +Copyright NVIDIA Corporation 2003 +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED +*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS +BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES +WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, +BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) +ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS +BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + +Comments: + send questions or comments to sdietrich@nvidia.com, cbrewer@nvidia.com + + MeshMender's main purpose is to generate a tangent space basis for + per pixel lighting. Given a set of vertices and normal map texture coordinates, + MeshMender will return a set of normals, binormals, and tangents taking into + account texture mirroring. + + Meshmender also lets you choose a minimum angle between neighboring + triangles vectors to determine whether or not they can smooth together. + If they can't smooth together, then MeshMender automagically mends the mesh + so that each unsmoothable neighbor has it's own set of vectors in a unique vertex. + + + +How to use MeshMender: + assumes that you have an array of vertices in myVerts and an array + of indices in myIndices. + the verts should be of the format + float x, float y, float z, + float s, + float t + +------------------------ + + + std::vector< MeshMender::Vertex > theVerts; + std::vector< unsigned int > theIndices; + std::vector< unsigned int > mappingNewToOld; + + //fill up the vectors with your mesh's data + for(DWORD i = 0; i < numVerts; ++i) + { + MeshMender::Vertex v; + v.pos = myVerts[i].pos; + v.s = myVerts[i].s; + v.t = myVerts[i].t; + //meshmender will computer normals, tangents, and binormals, no need to fill those in. + //however, if you do not have meshmender compute the normals, you _must_ pass in valid + //normals to meshmender + theVerts.push_back(v); + } + + for(DWORD ind= 0 ; ind< numIndices; ++ind) + { + theIndices.push_back(myIndices[ind]); + } + + //pass it in to the mender to do it's stuff + mender.Mend( theVerts, theIndices, mappingNewToOld, + minNormalCreaseCos, + minTangentCreaseCos, + minBinormalCreaseCos, + weightNormalsByArea, + MeshMender::CALCULATE_NORMALS, + MeshMender::DONT_RESPECT_SPLITS + MeshMender::DONT_FIX_CYLINDRICAL); + + //then update your mesh with the data provided in the Vertex vector + //NOTE that MeshMender may add vertices to your mesh if needs to split + //because of smoothing groups. So you can't just reuse your old vertex + //and index data. you have to update it. + //to help associate any special per vertex data you had in your original mesh + //you can use the mappingNewToOld ( see notes in comments below for Mend ) + + + + +******************************************************************************/ +#ifndef NV_MESH_MENDER_H +#define NV_MESH_MENDER_H + +#pragma warning(disable : 4786) +#pragma warning(disable : 4100) + +#include "directx/d3dx9.h" +//#include +//#include +//#include + +class MeshMender +{ + +public: + class Vertex + { + public: + D3DXVECTOR3 pos; + D3DXVECTOR3 normal; + float s; + float t; + D3DXVECTOR3 tangent; + D3DXVECTOR3 binormal; + enum + { + FVF = D3DFVF_XYZ | + D3DFVF_NORMAL | + D3DFVF_TEX3 | + D3DFVF_TEXCOORDSIZE2(0) | + D3DFVF_TEXCOORDSIZE3(1) | + D3DFVF_TEXCOORDSIZE3(2) + }; + Vertex::Vertex() : pos(0.0f, 0.0f, 0.0f), normal(0.0f, 0.0f, 0.0f), s(0.0f), t(0.0f), tangent(0.0f, 0.0f, 0.0f), binormal(0.0f, 0.0f, 0.0f) {} + }; + + enum NormalCalcOption + { + DONT_CALCULATE_NORMALS, + CALCULATE_NORMALS + }; + enum ExistingSplitOption + { + DONT_RESPECT_SPLITS, + RESPECT_SPLITS + }; + enum CylindricalFixOption + { + DONT_FIX_CYLINDRICAL, + FIX_CYLINDRICAL + }; + + // Mend - given a mesh, output the new data complete with smoothed + // normals, binormals, and tangents + // + // RETURNS true on success, false on failure + // + // theVerts - should be initialized with your mesh data, NOTE that when + // mesh mender is done with it, the number of vertices may grow + // and it will be filled with normals, tangents and binormals + // + // theIndices - should be initialized with your mesh indices + // will contain the new indices..we are not adding triangles, + // so the number of indices passed back should be the same as the + // number of indices passed in, but they may point to new vertices now. + // + // mappingNewToOldVert - this should be passed in as an empty vector. after mending + // it will contain a mapping of newvertexindex -> oldvertexindex + // so it could be used to map any per vertex data you had in your original + // mesh to the new mesh like so: + // + // for each new vertex index + // newVert[index]->myData = oldVert[ mappingNewToOldVert[index]]->myData; + // + // where myData is some custom vertex data in your original mesh. + // + // minNormalsCreaseCosAngle - the minimum cosine of the angle between normals + // so that they are allowed to be smoothed together + // ranges between -1.0 and +1.0 + // this is ignored if computeNormals is set to DONT_CALCULATE_NORMALS + // + // + // minTangentsCreaseCosAngle - the minimum cosine of the angle between tangents + // so that they are allowed to be smoothed together + // ranges between -1.0 and +1.0 + // + // minBinormalsCreaseCosAngle - the minimum cosine of the angle between binormals + // so that they are allowed to be smoothed together + // ranges between -1.0 and +1.0 + // + // weightNormalsByArea - an ammount to blend the normalized face normal, and the + // unnormalized face normal together. Thus weighting the + // normal by the face area by a given ammount + // ranges between 0.0 and +1.0 + // 0.0 means use the normalized face normals (not weighted by area) + // 1.0 means use the unnormalized face normal(weighted by area) + // this is ignored if computeNormals is set to DONT_CALCULATE_NORMALS + // + // computeNormals - should mesh mender calculate normals? If this is set to DONT_CALCULATE_NORMALS + // then the vertex normals after mesh mender is called will be the + // same ones you pass in. If you are automatically calculating normals yourself, + // you may find that meshmender provides greater control over how normals are smoothed + // together. I've been able to get better results using the Crease angle with + // meshmender's smoothing groups + // + // respectExistingSplits - DONT_RESPECT_SPLITS means that neighboring triangles for smoothing will be determined + // based on position and not on indices. + // RESPECT_SPLITS means that neighboring triangles will be determined based on the indices of the + // triangle and not the positions of the vertices. + // you can usually get better smoothing by not respecting existing splits + // only respect them if you know they should be respected. + // + // fixCylindricalWrapping - DONT_FIX_CYLINDRICAL means take the texture coordinates as they come + // FIX_CYLINDRICAL means we might need to split the verts + // at that point and generate the proper texture coordinate. + // for instance, if we have tex coords 0.9 -> 0.0-> 0.2 we would need to add + // a new vert so that we have 0.9 -> 1.0 0.0-> 0.2 + // this is only supported for texture coordinates in the range [ 0.0f , 1.0f ] + // NOTE: don't leave this on for all meshes, only use it when you know + // you need it. If you have polygons that map to a large area in texture space + // this option could mess up the texture coordinates + bool Mend(xr_vector &theVerts, + xr_vector &theIndices, + xr_vector &mappingNewToOldVert, + const float minNormalsCreaseCosAngle = 0.0f, + const float minTangentsCreaseCosAngle = 0.0f, + const float minBinormalsCreaseCosAngle = 0.0f, + const float weightNormalsByArea = 1.0f, + const NormalCalcOption computeNormals = CALCULATE_NORMALS, + const ExistingSplitOption respectExistingSplits = DONT_RESPECT_SPLITS, + const CylindricalFixOption fixCylindricalWrapping = DONT_FIX_CYLINDRICAL); + + MeshMender(); + + ~MeshMender(); + +protected: + float MinNormalsCreaseCosAngle; + float MinTangentsCreaseCosAngle; + float MinBinormalsCreaseCosAngle; + float WeightNormalsByArea; + ExistingSplitOption m_RespectExistingSplits; + + class CanSmoothChecker; + friend class CanSmoothChecker; + friend class CanSmoothNormalsChecker; + friend class CanSmoothTangentsChecker; + friend class CanSmoothBinormalsChecker; + + // sets up any internal data structures needed + void SetUpData(xr_vector &theVerts, + const xr_vector &theIndices, + xr_vector &mappingNewToOldVert, + const NormalCalcOption computeNormals); + + typedef size_t NeighborhoodID; + typedef size_t TriID; + typedef xr_vector TriangleList; + + struct Triangle + { + size_t indices[3]; + + // per face values + D3DXVECTOR3 normal; + D3DXVECTOR3 tangent; + D3DXVECTOR3 binormal; + + // helper flags + bool handled; + NeighborhoodID group; + void Reset(); + + TriID myID; // a global id used to keep track of tris' + }; + + xr_vector m_Triangles; + + // each vertex has a set of triangles that contain it. + // those triangles are considered to be that vertex's children + typedef xr_map VertexChildrenMap; + VertexChildrenMap m_VertexChildrenMap; + + // a neighbor group is defined to be the list of traingles + // that all fall arround a single vertex, and can smooth with + // eachother + typedef xr_vector NeighborGroupList; + + size_t m_originalNumVerts; + + // sets up the normal, binormal, and tangent for a triangle + // assumes the triangle indices are set to match whats in the verts + void SetUpFaceVectors(Triangle &t, + const xr_vector &verts, + const NormalCalcOption computeNormals); + + // function responsible for growing the neighbor hood groups + // arround a vertex + void BuildGroups(Triangle *tri, // the tri of interest + TriangleList &possibleNeighbors, // all tris arround a vertex + NeighborGroupList &neighborGroups, // the neighbor groups to be updated + xr_vector &theVerts, + CanSmoothChecker *smoothChecker, + const float &minCreaseAngle); + + // given 2 triangles, fill the two neighbor pointers with either + // null or valid Triangle pointers. + void FindNeighbors(Triangle *tri, + TriangleList &possibleNeighbors, + Triangle **neighbor1, + Triangle **neighbor2, + xr_vector &theVerts); + + bool SharesEdge(Triangle *triA, + Triangle *triB, + xr_vector &theVerts); + + bool SharesEdgeRespectSplits(Triangle *triA, + Triangle *triB, + xr_vector &theVerts); + + // calculates the tangent and binormal per face + void GetGradients(const MeshMender::Vertex &v0, + const MeshMender::Vertex &v1, + const MeshMender::Vertex &v2, + D3DXVECTOR3 &tangent, + D3DXVECTOR3 &binormal) const; + + void OrthogonalizeTangentsAndBinormals( + xr_vector &theVerts); + + void UpdateTheIndicesWithFinalIndices(xr_vector &theIndices); + + void FixCylindricalWrapping(xr_vector &theVerts, + xr_vector &theIndices, + xr_vector &mappingNewToOldVert); + + bool TriHasEdge(const D3DXVECTOR3 &p0, + const D3DXVECTOR3 &p1, + const D3DXVECTOR3 &triA, + const D3DXVECTOR3 &triB, + const D3DXVECTOR3 &triC); + + bool TriHasEdge(const size_t &p0, + const size_t &p1, + const size_t &triA, + const size_t &triB, + const size_t &triC); + + void ProcessNormals(TriangleList &possibleNeighbors, + xr_vector &theVerts, + xr_vector &mappingNewToOldVert, + D3DXVECTOR3 workingPosition); + + void ProcessTangents(TriangleList &possibleNeighbors, + xr_vector &theVerts, + xr_vector &mappingNewToOldVert, + D3DXVECTOR3 workingPosition); + + void ProcessBinormals(TriangleList &possibleNeighbors, + xr_vector &theVerts, + xr_vector &mappingNewToOldVert, + D3DXVECTOR3 workingPosition); + + // make any triangle that used the oldIndex use the newIndex instead + void UpdateIndices(const size_t oldIndex, + const size_t newIndex, + TriangleList &curGroup); + + // adds a new mapping entry, + // takes into account that we may be mapping a new vertex to another new vertex, + // and uses the original old vertex index....is that confusing? + void AppendToMapping(const size_t oldIndex, + const size_t originalNumVerts, + xr_vector &mappingNewToOldVert); +}; + +#endif diff --git a/src/editors/Public/NVMeshMenderTwo.cpp b/src/editors/Public/NVMeshMenderTwo.cpp new file mode 100644 index 00000000000..7823902ce1a --- /dev/null +++ b/src/editors/Public/NVMeshMenderTwo.cpp @@ -0,0 +1,1102 @@ +/*********************************************************************NVMH4**** +Path: +File: + +Copyright NVIDIA Corporation 2003 +TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED +*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS +BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES +WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, +BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) +ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS +BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + +Comments: + + Todo + - Performance improvements, right now for each vertex I am building the list + of it's neighbors, when we could do a single pass and build the full adjacency + map in the beginning. Note: I tried this and didn't see a real perf improvement. + + - I'd like to provide a non c++ standard library interface, probably + a simple c interface for all those simple c folks. or the + old nvMeshMender interface for all those using it already + +*/ + +#include "stdafx.h" +#include "nvMeshMender.h" +#include "assert.h" + +namespace +{ + const unsigned int NO_GROUP = 0xFFFFFFFF; + + // IC: Replacement for D3DXVec3Normalize so that we don't have dll dependancies. + static D3DXVECTOR3 *Vec3Normalize(D3DXVECTOR3 *pOut, CONST D3DXVECTOR3 *pV) + { + assert(pOut != NULL); + assert(pV != NULL); + + float v = 1.0f / _sqrt(pV->x * pV->x + pV->y * pV->y + pV->z * pV->z); + pOut->x *= v; + pOut->y *= v; + pOut->z *= v; + return pOut; + } +}; + +void MeshMender::Triangle::Reset() +{ + handled = false; + group = NO_GROUP; +} + +class MeshMender::CanSmoothChecker +{ +public: + virtual bool CanSmooth(MeshMender::Triangle *t1, MeshMender::Triangle *t2, const float &minCreaseAngle) = 0; +}; + +class CanSmoothNormalsChecker : public MeshMender::CanSmoothChecker +{ +public: + virtual bool CanSmooth(MeshMender::Triangle *t1, MeshMender::Triangle *t2, const float &minCreaseAngle) + { + + assert(t1 && t2); + // for checking the angle, we want these to be normalized, + // they may not be for whatever reason + D3DXVECTOR3 tmp1 = t1->normal; + D3DXVECTOR3 tmp2 = t2->normal; + Vec3Normalize(&tmp1, &tmp1); + Vec3Normalize(&tmp2, &tmp2); + + if (D3DXVec3Dot(&tmp1, &tmp2) >= minCreaseAngle) + { + return true; + } + else if ((tmp1 == D3DXVECTOR3(0, 0, 0)) && (tmp2 == D3DXVECTOR3(0, 0, 0))) + { + // check for them both being null, then they are + // welcome to smooth no matter what the minCreaseAngle is + return true; + } + return false; + } +}; + +class CanSmoothTangentsChecker : public MeshMender::CanSmoothChecker +{ +public: + virtual bool CanSmooth(MeshMender::Triangle *t1, MeshMender::Triangle *t2, const float &minCreaseAngle) + { + + assert(t1 && t2); + // for checking the angle, we want these to be normalized, + // they may not be for whatever reason + D3DXVECTOR3 tmp1 = t1->tangent; + D3DXVECTOR3 tmp2 = t2->tangent; + Vec3Normalize(&tmp1, &tmp1); + Vec3Normalize(&tmp2, &tmp2); + + if (D3DXVec3Dot(&tmp1, &tmp2) >= minCreaseAngle) + { + return true; + } + else if ((tmp1 == D3DXVECTOR3(0, 0, 0)) && (tmp2 == D3DXVECTOR3(0, 0, 0))) + { + // check for them both being null, then they are + // welcome to smooth no matter what the minCreaseAngle is + return true; + } + return false; + } +}; + +class CanSmoothBinormalsChecker : public MeshMender::CanSmoothChecker +{ +public: + virtual bool CanSmooth(MeshMender::Triangle *t1, MeshMender::Triangle *t2, const float &minCreaseAngle) + { + + assert(t1 && t2); + // for checking the angle, we want these to be normalized, + // they may not be for whatever reason + D3DXVECTOR3 tmp1 = t1->binormal; + D3DXVECTOR3 tmp2 = t2->binormal; + Vec3Normalize(&tmp1, &tmp1); + Vec3Normalize(&tmp2, &tmp2); + + if (D3DXVec3Dot(&tmp1, &tmp2) >= minCreaseAngle) + return true; + else if ((tmp1 == D3DXVECTOR3(0, 0, 0)) && (tmp2 == D3DXVECTOR3(0, 0, 0))) + { + // check for them both being null, then they are + // welcome to smooth no matter what the minCreaseAngle is + return true; + } + return false; + } +}; + +bool operator<(const D3DXVECTOR3 &lhs, const D3DXVECTOR3 &rhs) +{ + // needed to have a vertex in a map. + // must be an absolute sort so that we can reliably find the exact + // position again, not a fuzzy compare for equality based on an epsilon. + if (lhs.x == rhs.x) + { + if (lhs.y == rhs.y) + { + if (lhs.z == rhs.z) + { + return false; + } + else + { + return (lhs.z < rhs.z); + } + } + else + { + return (lhs.y < rhs.y); + } + } + else + { + return (lhs.x < rhs.x); + } +} + +MeshMender::MeshMender() +{ + MinNormalsCreaseCosAngle = 0.3f; + MinTangentsCreaseCosAngle = 0.0f; + MinBinormalsCreaseCosAngle = 0.0f; + WeightNormalsByArea = 0.0f; + m_RespectExistingSplits = DONT_RESPECT_SPLITS; +} +MeshMender::~MeshMender() +{ +} + +void MeshMender::UpdateIndices(const size_t oldIndex, const size_t newIndex, TriangleList &curGroup) +{ + // make any triangle that used the oldIndex use the newIndex instead + + for (size_t t = 0; t < curGroup.size(); ++t) + { + TriID tID = curGroup[t]; + for (size_t indx = 0; indx < 3; ++indx) + { + if (m_Triangles[tID].indices[indx] == oldIndex) + { + m_Triangles[tID].indices[indx] = newIndex; + } + } + } +} +void MeshMender::ProcessNormals(TriangleList &possibleNeighbors, + xr_vector &theVerts, + xr_vector &mappingNewToOldVert, + D3DXVECTOR3 workingPosition) +{ + NeighborGroupList neighborGroups; // a fresh group for each pass + + // reset each triangle to prepare for smoothing group building + for (unsigned int i = 0; i < possibleNeighbors.size(); ++i) + { + m_Triangles[possibleNeighbors[i]].Reset(); + } + + // now start building groups + CanSmoothNormalsChecker canSmoothNormalsChecker; + for (unsigned int i = 0; i < possibleNeighbors.size(); ++i) + { + Triangle *currTri = &(m_Triangles[possibleNeighbors[i]]); + assert(currTri); + if (!currTri->handled) + { + BuildGroups(currTri, possibleNeighbors, + neighborGroups, theVerts, + &canSmoothNormalsChecker, MinNormalsCreaseCosAngle); + } + } + + xr_vector groupNormalVectors; + + for (unsigned int i = 0; i < neighborGroups.size(); ++i) + { + // for each group, calculate the group normal + TriangleList &curGroup = neighborGroups[i]; + D3DXVECTOR3 gnorm(0.0f, 0.0f, 0.0f); + + assert(curGroup.size() != 0 && "should not be a zero group here."); + for (size_t t = 0; t < curGroup.size(); ++t) // for each triangle in the group, + { + TriID tID = curGroup[t]; + gnorm += m_Triangles[tID].normal; + } + Vec3Normalize(&gnorm, &gnorm); + groupNormalVectors.push_back(gnorm); + } + + // next step, ensure that triangles in different groups are not + // sharing vertices. and give the shared vertex their new group vector + xr_set otherGroupsIndices; + for (unsigned int i = 0; i < neighborGroups.size(); ++i) + { + TriangleList &curGroup = neighborGroups[i]; + xr_set thisGroupIndices; + + for (size_t t = 0; t < curGroup.size(); ++t) // for each tri + { + TriID tID = curGroup[t]; + for (size_t indx = 0; indx < 3; ++indx) // for each vert in that tri + { + // if it is at the positions in question + if (theVerts[m_Triangles[tID].indices[indx]].pos == workingPosition) + { + // see if another group is already using this vert + if (otherGroupsIndices.find(m_Triangles[tID].indices[indx]) != otherGroupsIndices.end()) + { + // then we need to make a new vertex + Vertex ov; + ov = theVerts[m_Triangles[tID].indices[indx]]; + ov.normal = groupNormalVectors[i]; + size_t oldIndex = m_Triangles[tID].indices[indx]; + size_t newIndex = theVerts.size(); + theVerts.push_back(ov); + AppendToMapping(oldIndex, m_originalNumVerts, mappingNewToOldVert); + UpdateIndices(oldIndex, newIndex, curGroup); + } + else + { + // otherwise, just update it with the new vector + theVerts[m_Triangles[tID].indices[indx]].normal = groupNormalVectors[i]; + } + + // store that we have used this index, so other groups can check + thisGroupIndices.insert(m_Triangles[tID].indices[indx]); + } + } + } + + for (xr_set::iterator it = thisGroupIndices.begin(); it != thisGroupIndices.end(); ++it) + { + otherGroupsIndices.insert(*it); + } + } +} + +void MeshMender::ProcessTangents(TriangleList &possibleNeighbors, + xr_vector &theVerts, + xr_vector &mappingNewToOldVert, + D3DXVECTOR3 workingPosition) +{ + NeighborGroupList neighborGroups; // a fresh group for each pass + + // reset each triangle to prepare for smoothing group building + for (unsigned int i = 0; i < possibleNeighbors.size(); ++i) + { + m_Triangles[possibleNeighbors[i]].Reset(); + } + + // now start building groups + CanSmoothTangentsChecker canSmoothTangentsChecker; + for (unsigned int i = 0; i < possibleNeighbors.size(); ++i) + { + Triangle *currTri = &(m_Triangles[possibleNeighbors[i]]); + assert(currTri); + if (!currTri->handled) + { + BuildGroups(currTri, possibleNeighbors, + neighborGroups, theVerts, + &canSmoothTangentsChecker, MinTangentsCreaseCosAngle); + } + } + + xr_vector groupTangentVectors; + + for (unsigned int i = 0; i < neighborGroups.size(); ++i) + { + D3DXVECTOR3 gtang(0, 0, 0); + for (unsigned int t = 0; t < neighborGroups[i].size(); ++t) // for each triangle in the group, + { + TriID tID = neighborGroups[i][t]; + gtang += m_Triangles[tID].tangent; + } + Vec3Normalize(>ang, >ang); + groupTangentVectors.push_back(gtang); + } + + // next step, ensure that triangles in different groups are not + // sharing vertices. and give the shared vertex their new group vector + xr_set otherGroupsIndices; + for (unsigned int i = 0; i < neighborGroups.size(); ++i) + { + TriangleList &curGroup = neighborGroups[i]; + xr_set thisGroupIndices; + + for (size_t t = 0; t < curGroup.size(); ++t) // for each tri + { + TriID tID = curGroup[t]; + for (size_t indx = 0; indx < 3; indx++) // for each vert in that tri + { + // if it is at the positions in question + if (theVerts[m_Triangles[tID].indices[indx]].pos == workingPosition) + { + // see if another group is already using this vert + if (otherGroupsIndices.find(m_Triangles[tID].indices[indx]) != otherGroupsIndices.end()) + { + // then we need to make a new vertex + Vertex ov; + ov = theVerts[m_Triangles[tID].indices[indx]]; + ov.tangent = groupTangentVectors[i]; + size_t oldIndex = m_Triangles[tID].indices[indx]; + size_t newIndex = theVerts.size(); + theVerts.push_back(ov); + AppendToMapping(oldIndex, m_originalNumVerts, mappingNewToOldVert); + UpdateIndices(oldIndex, newIndex, curGroup); + } + else + { + // otherwise, just update it with the new vector + theVerts[m_Triangles[tID].indices[indx]].tangent = groupTangentVectors[i]; + } + + // store that we have used this index, so other groups can check + thisGroupIndices.insert(m_Triangles[tID].indices[indx]); + } + } + } + + for (xr_set::iterator it = thisGroupIndices.begin(); it != thisGroupIndices.end(); ++it) + { + otherGroupsIndices.insert(*it); + } + } +} + +void MeshMender::ProcessBinormals(TriangleList &possibleNeighbors, + xr_vector &theVerts, + xr_vector &mappingNewToOldVert, + D3DXVECTOR3 workingPosition) +{ + NeighborGroupList neighborGroups; // a fresh group for each pass + + // reset each triangle to prepare for smoothing group building + for (unsigned int i = 0; i < possibleNeighbors.size(); ++i) + { + m_Triangles[possibleNeighbors[i]].Reset(); + } + + // now start building groups + CanSmoothBinormalsChecker canSmoothBinormalsChecker; + for (unsigned int i = 0; i < possibleNeighbors.size(); ++i) + { + Triangle *currTri = &(m_Triangles[possibleNeighbors[i]]); + assert(currTri); + if (!currTri->handled) + { + BuildGroups(currTri, possibleNeighbors, + neighborGroups, theVerts, + &canSmoothBinormalsChecker, MinBinormalsCreaseCosAngle); + } + } + + xr_vector groupBinormalVectors; + + for (unsigned int i = 0; i < neighborGroups.size(); ++i) + { + D3DXVECTOR3 gbinormal(0, 0, 0); + for (unsigned int t = 0; t < neighborGroups[i].size(); ++t) // for each triangle in the group, + { + TriID tID = neighborGroups[i][t]; + gbinormal += m_Triangles[tID].binormal; + } + Vec3Normalize(&gbinormal, &gbinormal); + groupBinormalVectors.push_back(gbinormal); + } + + // next step, ensure that triangles in different groups are not + // sharing vertices. and give the shared vertex their new group vector + xr_set otherGroupsIndices; + for (unsigned int i = 0; i < neighborGroups.size(); ++i) + { + TriangleList &curGroup = neighborGroups[i]; + xr_set thisGroupIndices; + + for (size_t t = 0; t < curGroup.size(); ++t) // for each tri + { + TriID tID = curGroup[t]; + for (size_t indx = 0; indx < 3; ++indx) // for each vert in that tri + { + // if it is at the positions in question + if (theVerts[m_Triangles[tID].indices[indx]].pos == workingPosition) + { + // see if another group is already using this vert + if (otherGroupsIndices.find(m_Triangles[tID].indices[indx]) != otherGroupsIndices.end()) + { + // then we need to make a new vertex + Vertex ov; + ov = theVerts[m_Triangles[tID].indices[indx]]; + ov.binormal = groupBinormalVectors[i]; + size_t oldIndex = m_Triangles[tID].indices[indx]; + size_t newIndex = theVerts.size(); + theVerts.push_back(ov); + AppendToMapping(oldIndex, m_originalNumVerts, mappingNewToOldVert); + UpdateIndices(oldIndex, newIndex, curGroup); + } + else + { + // otherwise, just update it with the new vector + theVerts[m_Triangles[tID].indices[indx]].binormal = groupBinormalVectors[i]; + } + + // store that we have used this index, so other groups can check + thisGroupIndices.insert(m_Triangles[tID].indices[indx]); + } + } + } + + for (xr_set::iterator it = thisGroupIndices.begin(); it != thisGroupIndices.end(); ++it) + { + otherGroupsIndices.insert(*it); + } + } +} + +bool MeshMender::Mend( + xr_vector &theVerts, + xr_vector &theIndices, + xr_vector &mappingNewToOldVert, + const float minNormalsCreaseCosAngle, + const float minTangentsCreaseCosAngle, + const float minBinormalsCreaseCosAngle, + const float weightNormalsByArea, + const NormalCalcOption computeNormals, + const ExistingSplitOption respectExistingSplits, + const CylindricalFixOption fixCylindricalWrapping) +{ + MinNormalsCreaseCosAngle = minNormalsCreaseCosAngle; + MinTangentsCreaseCosAngle = minTangentsCreaseCosAngle; + MinBinormalsCreaseCosAngle = minBinormalsCreaseCosAngle; + WeightNormalsByArea = weightNormalsByArea; + m_RespectExistingSplits = respectExistingSplits; + + // fix cylindrical should happen before we do any other calculations + if (fixCylindricalWrapping == FIX_CYLINDRICAL) + { + FixCylindricalWrapping(theVerts, theIndices, mappingNewToOldVert); + } + + SetUpData(theVerts, theIndices, mappingNewToOldVert, computeNormals); + + // for each unique position + for (VertexChildrenMap::iterator vert = m_VertexChildrenMap.begin(); + vert != m_VertexChildrenMap.end(); + ++vert) + { + D3DXVECTOR3 workingPosition = vert->first; + + TriangleList &possibleNeighbors = vert->second; + if (computeNormals == CALCULATE_NORMALS) + { + ProcessNormals(possibleNeighbors, theVerts, mappingNewToOldVert, workingPosition); + } + ProcessTangents(possibleNeighbors, theVerts, mappingNewToOldVert, workingPosition); + ProcessBinormals(possibleNeighbors, theVerts, mappingNewToOldVert, workingPosition); + } + + UpdateTheIndicesWithFinalIndices(theIndices); + OrthogonalizeTangentsAndBinormals(theVerts); + + return true; +} + +void MeshMender::BuildGroups(Triangle *tri, // the tri of interest + TriangleList &possibleNeighbors, // all tris arround a vertex + NeighborGroupList &neighborGroups, // the neighbor groups to be updated + xr_vector &theVerts, + CanSmoothChecker *smoothChecker, + const float &minCreaseAngle) +{ + if ((!tri) || (tri->handled)) + return; + + Triangle *neighbor1 = NULL; + Triangle *neighbor2 = NULL; + + FindNeighbors(tri, possibleNeighbors, &neighbor1, &neighbor2, theVerts); + + // see if I can join my first neighbors group + if (neighbor1 && (neighbor1->group != NO_GROUP)) + { + if (smoothChecker->CanSmooth(tri, neighbor1, minCreaseAngle)) + { + neighborGroups[neighbor1->group].push_back(tri->myID); + tri->group = neighbor1->group; + } + } + + // see if I can join my second neighbors group + if (neighbor2 && (neighbor2->group != NO_GROUP)) + { + if (smoothChecker->CanSmooth(tri, neighbor2, minCreaseAngle)) + { + neighborGroups[neighbor2->group].push_back(tri->myID); + tri->group = neighbor2->group; + } + } + // I either couldn't join, or they weren't in a group, so I think I'll + // just go and start my own group...right here we go. + if (tri->group == NO_GROUP) + { + tri->group = neighborGroups.size(); + neighborGroups.push_back(TriangleList()); + neighborGroups.back().push_back(tri->myID); + } + assert((tri->group != NO_GROUP) && "error!: tri should have a group set"); + tri->handled = true; + + // continue growing our group with each neighbor. + BuildGroups(neighbor1, possibleNeighbors, neighborGroups, theVerts, smoothChecker, minCreaseAngle); + BuildGroups(neighbor2, possibleNeighbors, neighborGroups, theVerts, smoothChecker, minCreaseAngle); +} + +void MeshMender::FindNeighbors(Triangle *tri, + TriangleList &possibleNeighbors, + Triangle **neighbor1, + Triangle **neighbor2, + xr_vector &theVerts) +{ + *neighbor1 = NULL; + *neighbor2 = NULL; + + xr_vector theNeighbors; + for (unsigned int n = 0; n < possibleNeighbors.size(); ++n) + { + TriID tID = possibleNeighbors[n]; + Triangle *possible = &(m_Triangles[tID]); + if (possible != tri) // check for myself + { + if (SharesEdge(tri, possible, theVerts)) + { + theNeighbors.push_back(possible); + } + } + } + + if (theNeighbors.size() > 0) + *neighbor1 = theNeighbors[0]; + if (theNeighbors.size() > 1) + *neighbor2 = theNeighbors[1]; +} + +bool MeshMender::TriHasEdge(const size_t &p0, + const size_t &p1, + const size_t &triA, + const size_t &triB, + const size_t &triC) +{ + if (((p0 == triB) && (p1 == triA)) || + ((p0 == triA) && (p1 == triB))) + { + return true; + } + + if (((p0 == triB) && (p1 == triC)) || + ((p0 == triC) && (p1 == triB))) + { + return true; + } + + if (((p0 == triC) && (p1 == triA)) || + ((p0 == triA) && (p1 == triC))) + { + return true; + } + return false; +} + +bool MeshMender::TriHasEdge(const D3DXVECTOR3 &p0, + const D3DXVECTOR3 &p1, + const D3DXVECTOR3 &triA, + const D3DXVECTOR3 &triB, + const D3DXVECTOR3 &triC) +{ + if (((p0 == triB) && (p1 == triA)) || + ((p0 == triA) && (p1 == triB))) + { + return true; + } + + if (((p0 == triB) && (p1 == triC)) || + ((p0 == triC) && (p1 == triB))) + { + return true; + } + + if (((p0 == triC) && (p1 == triA)) || + ((p0 == triA) && (p1 == triC))) + { + return true; + } + return false; +} + +bool MeshMender::SharesEdgeRespectSplits(Triangle *triA, + Triangle *triB, + xr_vector &theVerts) +{ + assert(triA && triB && "invalid data passed to SharesEdgeNoSplit"); + // here we want to compare based solely on indices. + + size_t a1 = triA->indices[0]; + size_t b1 = triA->indices[1]; + size_t c1 = triA->indices[2]; + + size_t a2 = triB->indices[0]; + size_t b2 = triB->indices[1]; + size_t c2 = triB->indices[2]; + + // edge B1->A1 + if (TriHasEdge(b1, a1, a2, b2, c2)) + return true; + + // edge A1->C1 + if (TriHasEdge(a1, c1, a2, b2, c2)) + return true; + + // edge C1->B1 + if (TriHasEdge(c1, b1, a2, b2, c2)) + return true; + + return false; +} + +bool MeshMender::SharesEdge(Triangle *triA, + Triangle *triB, + xr_vector &theVerts) +{ + assert(triA && triB && "invalid data passed to SharesEdge"); + + // check based on position not on indices, because there may be splits + // we don't care about. unless the user has told us they care about those + // splits + if (m_RespectExistingSplits == RESPECT_SPLITS) + { + return SharesEdgeRespectSplits(triA, triB, theVerts); + } + + D3DXVECTOR3 a1 = theVerts[triA->indices[0]].pos; + D3DXVECTOR3 b1 = theVerts[triA->indices[1]].pos; + D3DXVECTOR3 c1 = theVerts[triA->indices[2]].pos; + + D3DXVECTOR3 a2 = theVerts[triB->indices[0]].pos; + D3DXVECTOR3 b2 = theVerts[triB->indices[1]].pos; + D3DXVECTOR3 c2 = theVerts[triB->indices[2]].pos; + + // edge B1->A1 + if (TriHasEdge(b1, a1, a2, b2, c2)) + return true; + + // edge A1->C1 + if (TriHasEdge(a1, c1, a2, b2, c2)) + return true; + + // edge C1->B1 + if (TriHasEdge(c1, b1, a2, b2, c2)) + return true; + + return false; +} + +void MeshMender::SetUpData( + xr_vector &theVerts, + const xr_vector &theIndices, + xr_vector &mappingNewToOldVert, + const NormalCalcOption computeNormals) +{ + assert(((theIndices.size() % 3) == 0) && "expected the indices to be a multiple of 3"); + unsigned int i; + + // initialize the mapping + for (i = 0; i < theVerts.size(); ++i) + mappingNewToOldVert.push_back(i); + + m_originalNumVerts = theVerts.size(); + + // set up our triangles + for (i = 0; i < theIndices.size(); i += 3) + { + Triangle t; + + t.indices[0] = theIndices[i + 0]; + t.indices[1] = theIndices[i + 1]; + t.indices[2] = theIndices[i + 2]; + + // set up bin, norm, and tan + SetUpFaceVectors(t, theVerts, computeNormals); + + t.myID = m_Triangles.size(); // set id, to my index into m_Triangles + m_Triangles.push_back(t); + } + + // build vertex position/traingle pairings. + // we use the position and not the actual vertex, because there may + // be multiple coppies of the same vertex for textureing + // but we don't want that to + // effect our decisions about normal smoothing. + // note: maybe this should be an option, the position thing. + for (i = 0; i < m_Triangles.size(); ++i) + { + + for (size_t indx = 0; indx < 3; ++indx) + { + D3DXVECTOR3 v = theVerts[m_Triangles[i].indices[indx]].pos; + VertexChildrenMap::iterator iter = m_VertexChildrenMap.find(v); + if (iter != m_VertexChildrenMap.end()) + { + // we found it, so just add ourselves to it. + iter->second.push_back(TriID(i)); + } + else + { + // we didn't find it so join whatever was there. + xr_vector tmp; + m_VertexChildrenMap[v] = tmp; + m_VertexChildrenMap[v].push_back(TriID(i)); + } + } + } +} + +// sets up the normal, binormal, and tangent for a triangle +// assumes the triangle indices are set to match whats in the verts +void MeshMender::SetUpFaceVectors(Triangle &t, + const xr_vector &verts, + const NormalCalcOption computeNormals) +{ + + if (computeNormals == CALCULATE_NORMALS) + { + D3DXVECTOR3 edge0 = verts[t.indices[1]].pos - verts[t.indices[0]].pos; + D3DXVECTOR3 edge1 = verts[t.indices[2]].pos - verts[t.indices[0]].pos; + + D3DXVec3Cross(&t.normal, &edge0, &edge1); + + if (WeightNormalsByArea < 1.0f) + { + + D3DXVECTOR3 normalizedNorm; + Vec3Normalize(&normalizedNorm, &t.normal); + D3DXVECTOR3 finalNorm = (normalizedNorm * (1.0f - WeightNormalsByArea)) + (t.normal * WeightNormalsByArea); + t.normal = finalNorm; + } + } + // need to set up tangents, and binormals here + GetGradients(verts[t.indices[0]], + verts[t.indices[1]], + verts[t.indices[2]], + t.tangent, + t.binormal); +} + +void MeshMender::OrthogonalizeTangentsAndBinormals( + xr_vector &theVerts) +{ + // put our tangents and binormals through the final orthogonalization + // with the final processed normals + size_t len = theVerts.size(); + for (size_t i = 0; i < len; ++i) + { + + assert(D3DXVec3Length(&(theVerts[i].normal)) > 0.00001f && + "found zero length normal when calculating tangent basis!,\ + if you are not using mesh mender to compute normals, you\ + must still pass in valid normals to be used when calculating\ + tangents and binormals."); + + // now with T and B and N we can get from tangent space to object space + // but we want to go the other way, so we need the inverse + // of the T, B,N matrix + // we can use the Gram-Schmidt algorithm to find the newTangent and the newBinormal + // newT = T - (N dot T)N + // newB = B - (N dot B)N - (newT dot B)newT + + // NOTE: this should maybe happen with the final smoothed N, T, and B + // will try it here and see what the results look like + + D3DXVECTOR3 tmpTan = theVerts[i].tangent; + D3DXVECTOR3 tmpNorm = theVerts[i].normal; + D3DXVECTOR3 tmpBin = theVerts[i].binormal; + + D3DXVECTOR3 newT = tmpTan - (D3DXVec3Dot(&tmpNorm, &tmpTan) * tmpNorm); + D3DXVECTOR3 newB = tmpBin - (D3DXVec3Dot(&tmpNorm, &tmpBin) * tmpNorm) - (D3DXVec3Dot(&newT, &tmpBin) * newT); + + Vec3Normalize(&(theVerts[i].tangent), &newT); + Vec3Normalize(&(theVerts[i].binormal), &newB); + + // this is where we can do a final check for zero length vectors + // and set them to something appropriate + float lenTan = D3DXVec3Length(&(theVerts[i].tangent)); + float lenBin = D3DXVec3Length(&(theVerts[i].binormal)); + + if ((lenTan <= 0.001f) || (lenBin <= 0.001f)) // should be approx 1.0f + { + // the tangent space is ill defined at this vertex + // so we can generate a valid one based on the normal vector, + // which I'm assuming is valid! + + if (lenTan > 0.5f) + { + // the tangent is valid, so we can just use that + // to calculate the binormal + D3DXVec3Cross(&(theVerts[i].binormal), &(theVerts[i].normal), &(theVerts[i].tangent)); + } + else if (lenBin > 0.5) + { + // the binormal is good and we can use it to calculate + // the tangent + D3DXVec3Cross(&(theVerts[i].tangent), &(theVerts[i].binormal), &(theVerts[i].normal)); + } + else + { + // both vectors are invalid, so we should create something + // that is at least valid if not correct + D3DXVECTOR3 xAxis(1.0f, 0.0f, 0.0f); + D3DXVECTOR3 yAxis(0.0f, 1.0f, 0.0f); + // I'm checking two possible axis, because the normal could be one of them, + // and we want to chose a different one to start making our valid basis. + // I can find out which is further away from it by checking the dot product + D3DXVECTOR3 startAxis; + + if (D3DXVec3Dot(&xAxis, &(theVerts[i].normal)) < D3DXVec3Dot(&yAxis, &(theVerts[i].normal))) + { + // the xAxis is more different than the yAxis when compared to the normal + startAxis = xAxis; + } + else + { + // the yAxis is more different than the xAxis when compared to the normal + startAxis = yAxis; + } + + D3DXVec3Cross(&(theVerts[i].tangent), &(theVerts[i].normal), &startAxis); + D3DXVec3Cross(&(theVerts[i].binormal), &(theVerts[i].normal), &(theVerts[i].tangent)); + } + } + else + { + // one final sanity check, make sure that they tangent and binormal are different enough + if (D3DXVec3Dot(&(theVerts[i].binormal), &(theVerts[i].tangent)) > 0.999f) + { + // then they are too similar lets make them more different + D3DXVec3Cross(&(theVerts[i].binormal), &(theVerts[i].normal), &(theVerts[i].tangent)); + } + } + } +} + +void MeshMender::GetGradients(const MeshMender::Vertex &v0, + const MeshMender::Vertex &v1, + const MeshMender::Vertex &v2, + D3DXVECTOR3 &tangent, + D3DXVECTOR3 &binormal) const +{ + // using Eric Lengyel's approach with a few modifications + // from Mathematics for 3D Game Programmming and Computer Graphics + // want to be able to trasform a vector in Object Space to Tangent Space + // such that the x-axis cooresponds to the 's' direction and the + // y-axis corresponds to the 't' direction, and the z-axis corresponds + // to <0,0,1>, straight up out of the texture map + + // let P = v1 - v0 + D3DXVECTOR3 P = v1.pos - v0.pos; + // let Q = v2 - v0 + D3DXVECTOR3 Q = v2.pos - v0.pos; + float s1 = v1.s - v0.s; + float t1 = v1.t - v0.t; + float s2 = v2.s - v0.s; + float t2 = v2.t - v0.t; + + // we need to solve the equation + // P = s1*T + t1*B + // Q = s2*T + t2*B + // for T and B + + // this is a linear system with six unknowns and six equatinos, for TxTyTz BxByBz + //[px,py,pz] = [s1,t1] * [Tx,Ty,Tz] + // qx,qy,qz s2,t2 Bx,By,Bz + + // multiplying both sides by the inverse of the s,t matrix gives + //[Tx,Ty,Tz] = 1/(s1t2-s2t1) * [t2,-t1] * [px,py,pz] + // Bx,By,Bz -s2,s1 qx,qy,qz + + // solve this for the unormalized T and B to get from tangent to object space + + float tmp = 0.0f; + if (_abs(s1 * t2 - s2 * t1) <= 0.0001f) + { + tmp = (s1 * t2 - s2 * t1) > 0.f ? 1.0f : -1.f; + } + else + { + tmp = 1.0f / (s1 * t2 - s2 * t1); + } + + tangent.x = (t2 * P.x - t1 * Q.x); + tangent.y = (t2 * P.y - t1 * Q.y); + tangent.z = (t2 * P.z - t1 * Q.z); + + tangent = tmp * tangent; + + binormal.x = (s1 * Q.x - s2 * P.x); + binormal.y = (s1 * Q.y - s2 * P.y); + binormal.z = (s1 * Q.z - s2 * P.z); + + binormal = tmp * binormal; + + // after these vectors are smoothed together, + // they must be again orthogonalized with the final normals + // see OrthogonalizeTangentsAndBinormals +} + +void MeshMender::UpdateTheIndicesWithFinalIndices(xr_vector &theIndices) +{ + // theIndices is assumed to be filled with a copy of the in Indices. + + assert(((theIndices.size() / 3) == m_Triangles.size()) && "invalid number of tris, or indices."); + // Note that we do not change the number or the order of indices at all, + // so we just need to copy the triangles indices to the output. + size_t oIndex = 0; + + for (size_t i = 0; i < m_Triangles.size(); ++i) + { + theIndices[oIndex + 0] = (u32)m_Triangles[i].indices[0]; + theIndices[oIndex + 1] = (u32)m_Triangles[i].indices[1]; + theIndices[oIndex + 2] = (u32)m_Triangles[i].indices[2]; + oIndex += 3; + } +} + +void MeshMender::FixCylindricalWrapping(xr_vector &theVerts, + xr_vector &theIndices, + xr_vector &mappingNewToOldVert) +{ + // when using cylindrical texture coordinate generation, + // you can end up with triangles that have coordinates like + // <0,0.9> -------------> <0,0> + // and + // <0,0.9> -------------> <0,0.1> + // this will cause the texture to be mapped from 0.9 back to 0.0 or 0.1 when + // what you really want it to do is + // wrap arround to 1.0, then start from 0.0 again. + // to fix this, we can duplicate a vertex and add 1.0 to the wrapped texture coordinate + // we need to do this for both the S and the T directions. + + size_t index; + for (index = 0; index < theIndices.size(); index += 3) + { + // for each triangle + xr_set alreadyDuped; + + for (unsigned int begin = 0; begin < 3; ++begin) + { + + unsigned int end = begin + 1; + if (begin == 2) + end = 0; + // for each begin -> end edge + + float sBegin = theVerts[theIndices[index + begin]].s; + float sEnd = theVerts[theIndices[index + end]].s; + + if (sBegin <= 1.0f && sEnd <= 1.0f && sBegin >= 0.0f && sEnd >= 0.0f) + { + // we only handle coordinates between 0 and 1 for the cylindrical wrappign fix + if (_abs(sBegin - sEnd) > 0.5f) + { + unsigned int theOneToDupe = begin; + // we have some wrapping going on. + if (sBegin > sEnd) + theOneToDupe = end; + + if (alreadyDuped.find(theOneToDupe) == alreadyDuped.end()) + { + size_t oldIndex = theIndices[index + theOneToDupe]; + Vertex theDupe = theVerts[oldIndex]; + alreadyDuped.insert(theOneToDupe); + theDupe.s += 1.0f; + theIndices[index + theOneToDupe] = theVerts.size(); + theVerts.push_back(theDupe); + AppendToMapping(oldIndex, m_originalNumVerts, mappingNewToOldVert); + } + else + { + theVerts[theIndices[index + theOneToDupe]].s += 1.0f; + } + } + } + + float tBegin = theVerts[theIndices[index + begin]].t; + float tEnd = theVerts[theIndices[index + end]].t; + + if (tBegin <= 1.0f && tEnd <= 1.0f && tBegin >= 0.0f && tEnd >= 0.0f) + { + // we only handle coordinates between 0 and 1 for the cylindrical wrappign fix + if (_abs(tBegin - tEnd) > 0.5f) + { + unsigned int theOneToDupe = begin; + // we have some wrapping going on. + if (tBegin > tEnd) + theOneToDupe = end; + + if (alreadyDuped.find(theOneToDupe) == alreadyDuped.end()) + { + size_t oldIndex = theIndices[index + theOneToDupe]; + Vertex theDupe = theVerts[oldIndex]; + alreadyDuped.insert(theOneToDupe); + theDupe.t += 1.0f; + theIndices[index + theOneToDupe] = theVerts.size(); + theVerts.push_back(theDupe); + AppendToMapping(oldIndex, m_originalNumVerts, mappingNewToOldVert); + } + else + { + theVerts[theIndices[index + theOneToDupe]].t += 1.0f; + } + } + } + } + } +} + +void MeshMender::AppendToMapping(const size_t oldIndex, + const size_t originalNumVerts, + xr_vector &mappingNewToOldVert) +{ + if (oldIndex >= originalNumVerts) + { + // then this is a newer vertex we are mapping to another vertex we created in meshmender. + // we need to find the original old vertex index to map to. + // so we can just use the mapping + + // that is to say, just keep the same mapping for this new one. + unsigned int originalVertIndex = mappingNewToOldVert[oldIndex]; + assert(originalVertIndex < originalNumVerts); + + mappingNewToOldVert.push_back(originalVertIndex); + } + else + { + // this is mapping to an original vertex + mappingNewToOldVert.push_back(oldIndex); + } +} \ No newline at end of file diff --git a/src/editors/Public/ReadMe.txt b/src/editors/Public/ReadMe.txt new file mode 100644 index 00000000000..3f6f1a23476 --- /dev/null +++ b/src/editors/Public/ReadMe.txt @@ -0,0 +1,17 @@ +======================================================================== + STATIC LIBRARY : nv_meshmender +======================================================================== + +revision history + +2-05-2004 + - added the mapping from new to old vertices + +1-26-2004 + - grouped parameters to Mend() differently + - added default values to Mend() parameters + - renamed MeshMender::MenderVertex to MeshMender::Vertex since the extra mender was redundant + - added some more comments in the options section with advice on usage + - turned bool parameters into enums so that they aren't easily mixed up. + + \ No newline at end of file diff --git a/src/editors/Public/Shader_xrLC.h b/src/editors/Public/Shader_xrLC.h new file mode 100644 index 00000000000..fbf7c457ebb --- /dev/null +++ b/src/editors/Public/Shader_xrLC.h @@ -0,0 +1,175 @@ +#ifndef SHADER_XRLC_H +#define SHADER_XRLC_H +#pragma once +struct Shader_xrLC; +struct Shader_xrLC +{ +public: + enum + { + flCollision = 1 << 0, + flRendering = 1 << 1, + flOptimizeUV = 1 << 2, + flLIGHT_Vertex = 1 << 3, + flLIGHT_CastShadow = 1 << 4, + flLIGHT_Sharp = 1 << 5, + }; + struct Flags + { + u32 bCollision : 1; + u32 bRendering : 1; + u32 bOptimizeUV : 1; + u32 bLIGHT_Vertex : 1; + u32 bLIGHT_CastShadow : 1; + u32 bLIGHT_Sharp : 1; + }; + +public: + char Name[128]; + union + { + Flags32 m_Flags; + Flags flags; + }; + float vert_translucency; + float vert_ambient; + float lm_density; + + Shader_xrLC() + { + xr_strcpy(Name, "unknown"); + m_Flags.assign(0); + flags.bCollision = TRUE; + flags.bRendering = TRUE; + flags.bOptimizeUV = TRUE; + flags.bLIGHT_Vertex = FALSE; + flags.bLIGHT_CastShadow = TRUE; + flags.bLIGHT_Sharp = TRUE; + vert_translucency = .5f; + vert_ambient = .0f; + lm_density = 1.f; + } +}; + +DEFINE_VECTOR(Shader_xrLC, Shader_xrLCVec, Shader_xrLCIt); +class Shader_xrLC_LIB +{ + Shader_xrLCVec library; + +public: + void Load(LPCSTR name) + { + IReader *fs = FS.r_open(name); + if (NULL == fs) + { + string256 inf; + extern HWND logWindow; + xr_sprintf(inf, "Build failed!\nCan't load shaders library: '%s'", name); + // clMsg (inf); + // MessageBox (logWindow,inf,"Error!",MB_OK|MB_ICONERROR); + FATAL(inf); + return; + }; + + int count = fs->length() / sizeof(Shader_xrLC); + R_ASSERT(int(fs->length()) == int(count * sizeof(Shader_xrLC))); + library.resize(count); + fs->r(&*library.begin(), fs->length()); + FS.r_close(fs); + } + bool Save(LPCSTR name) + { + IWriter *F = FS.w_open(name); + if (F) + { + F->w(&*library.begin(), (u32)library.size() * sizeof(Shader_xrLC)); + FS.w_close(F); + return true; + } + else + { + return false; + } + } + void Unload() + { + library.clear(); + } + u32 GetID(LPCSTR name) const + { + for (Shader_xrLCVec::const_iterator it = library.begin(); it != library.end(); it++) + if (0 == stricmp(name, it->Name)) + return u32(it - library.begin()); + return u32(-1); + } + Shader_xrLC *Get(LPCSTR name) + { + for (Shader_xrLCIt it = library.begin(); it != library.end(); it++) + if (0 == stricmp(name, it->Name)) + return &(*it); + return NULL; + } + IC Shader_xrLC *Get(int id) + { + return &library[id]; + } + IC const Shader_xrLC *Get(int id) const + { + return &library[id]; + } + Shader_xrLC *Append(Shader_xrLC *parent = 0) + { + library.push_back(parent ? Shader_xrLC(*parent) : Shader_xrLC()); + return &library.back(); + } + void Remove(LPCSTR name) + { + for (Shader_xrLCIt it = library.begin(); it != library.end(); it++) + if (0 == stricmp(name, it->Name)) + { + library.erase(it); + break; + } + } + void Remove(int id) + { + library.erase(library.begin() + id); + } + + Shader_xrLCVec &Library() { return library; } + const Shader_xrLCVec &Library() const { return library; } +}; + +IC void post_process_materials(const Shader_xrLC_LIB &shaders, const xr_vector &shader_compile, xr_vector &materials) +{ + for (u32 m = 0; m < materials.size(); m++) + { + b_material &M = materials[m]; + + if (65535 == M.shader_xrlc) + { + // No compiler shader + M.reserved = u16(-1); + // clMsg (" * %20s",shader_render[M.shader].name); + } + else + { + // clMsg (" * %20s / %-20s",shader_render[M.shader].name, shader_compile[M.shader_xrlc].name); + int id = shaders.GetID(shader_compile[M.shader_xrlc].name); + if (id < 0) + { + clMsg("ERROR: Shader '%s' not found in library", shader_compile[M.shader].name); + R_ASSERT(id >= 0); + } + M.reserved = u16(id); + } + } +} + +IC const Shader_xrLC &shader(u16 dwMaterial, const Shader_xrLC_LIB &shaders, const xr_vector &materials) +{ + u32 shader_id = materials[dwMaterial].reserved; + return *(shaders.Get(shader_id)); +} + +#endif diff --git a/src/editors/Public/convert.h b/src/editors/Public/convert.h new file mode 100644 index 00000000000..d3381507041 --- /dev/null +++ b/src/editors/Public/convert.h @@ -0,0 +1,19 @@ +#ifndef _CONVERT_H_ +#define _CONVERT_H_ +IC D3DXVECTOR3 &cv_vector(D3DXVECTOR3 &l, const Fvector &r) +{ + l.x = r.x; + l.y = r.y; + l.z = r.z; + return l; +} + +IC Fvector &cv_vector(Fvector &l, const D3DXVECTOR3 &r) +{ + l.x = r.x; + l.y = r.y; + l.z = r.z; + return l; +} + +#endif \ No newline at end of file diff --git a/src/editors/Public/hxGridInterface.cpp b/src/editors/Public/hxGridInterface.cpp new file mode 100644 index 00000000000..1d153ab90f7 --- /dev/null +++ b/src/editors/Public/hxGridInterface.cpp @@ -0,0 +1,50 @@ +#include "hxgrid/Interface/hxGridInterface.h" +#include "assert.h" + +typedef IGridUser *(__cdecl TCreateGridUserObject)(DWORD version); + +typedef IGenericStream *(__cdecl TCreateGenericStream)(); + +//============================================================== +//============================================================== +IGridUser *CreateGridUserObject(DWORD version) +{ + static HINSTANCE DLLHandle(0); + + if (DLLHandle == 0) + { + DLLHandle = LoadLibrary("hxGridUserDLL.dll"); + assert(DLLHandle != 0); + } + + static TCreateGridUserObject *pProc(NULL); + + if (pProc == NULL) + { + pProc = (TCreateGridUserObject *)GetProcAddress(DLLHandle, "CreateGridUserObject"); + assert(pProc != NULL); + } + return pProc(version); +} + +//============================================================== +//============================================================== +IGenericStream *CreateGenericStream() +{ + static HINSTANCE DLLHandle(0); + + if (DLLHandle == 0) + { + DLLHandle = LoadLibrary("hxGridUserDLL.dll"); + assert(DLLHandle != 0); + } + + static TCreateGenericStream *pProc(NULL); + + if (pProc == NULL) + { + pProc = (TCreateGenericStream *)GetProcAddress(DLLHandle, "CreateGenericStream"); + assert(pProc != NULL); + } + return pProc(); +} diff --git a/src/editors/Public/mender_input_output.h b/src/editors/Public/mender_input_output.h new file mode 100644 index 00000000000..596a35bb01a --- /dev/null +++ b/src/editors/Public/mender_input_output.h @@ -0,0 +1,67 @@ +#ifndef _MENDER_INPUT_OUTPUT_H_ +#define _MENDER_INPUT_OUTPUT_H_ + +#include "convert.h" + +template +IC void add_face(xr_vector &theIndices, const type_face &iF) +{ + theIndices.push_back(face_vertex(iF, 0)); + theIndices.push_back(face_vertex(iF, 1)); + theIndices.push_back(face_vertex(iF, 2)); +} + +template +IC void set_face(type_face &iF, unsigned int v0, unsigned int v1, unsigned int v2) +{ + face_vertex(iF, 0) = v0; + face_vertex(iF, 1) = v1; + face_vertex(iF, 2) = v2; +} + +template +static void fill_mender_input(const xr_vector &vertices, + const xr_vector &faces, + xr_vector &theVerts, + xr_vector &theIndices) +{ + theVerts.clear(); + theIndices.clear(); + // fill inputs ( verts ) + const u32 vertices_number = vertices.size(); + theVerts.resize(vertices_number); + for (u32 i = 0; i < vertices_number; ++i) + set_vertex(theVerts[i], vertices[i]); + // fill inputs ( indices ) + for (xr_vector::const_iterator face_it = faces.begin(); face_it != faces.end(); face_it++) + add_face(theIndices, *face_it); +} + +template +static void retrive_data_from_mender_otput(xr_vector &vertices, // in-out + xr_vector &faces, + const xr_vector &theVerts, + const xr_vector &theIndices, + const xr_vector &mappingNewToOldVert) +{ + xr_vector old_vertices; + { + old_vertices.clear(); + old_vertices = vertices; // save old vertices to retrive through mappingNewToOldVert data that missing in MeshMender::Vertex + // retriving data + const u32 face_count = faces.size(); + for (u32 i = 0; i < face_count; ++i) + set_face(faces[i], theIndices[3 * i + 0], + theIndices[3 * i + 1], + theIndices[3 * i + 2]); + } + { + const u32 vertex_count = theVerts.size(); + vertices.clear(); + vertices.resize(vertex_count); + for (u32 i = 0; i < vertex_count; i++) + set_vertex(vertices[i], old_vertices[mappingNewToOldVert[i]], theVerts[i]); + } +} + +#endif \ No newline at end of file diff --git a/src/editors/Public/remove_isolated_verts.h b/src/editors/Public/remove_isolated_verts.h new file mode 100644 index 00000000000..6741cc883bc --- /dev/null +++ b/src/editors/Public/remove_isolated_verts.h @@ -0,0 +1,59 @@ +#ifndef _REMOVE_ISOLATED_VERTS_H_ +#define _REMOVE_ISOLATED_VERTS_H_ + +template +static void add_face(const type_face &F, + xr_vector &new_vertices, + xr_vector &new_faces, + const xr_vector &vertices, + xr_vector &remap) +{ + type_face new_face; + for (u32 v = 0; v < 3; v++) + { + u32 old_id = face_vertex(F, v); + u32 new_id = remap[old_id]; + // Register new if not found + if (new_id == u32(-1)) + { + new_vertices.push_back(vertices[old_id]); + new_id = new_vertices.size() - 1; + remap[old_id] = new_id; + } + face_vertex(new_face, v) = new_id; + } + new_faces.push_back(new_face); +} + +template +static void t_remove_isolated_verts(xr_vector &new_vertices, xr_vector &new_faces, const xr_vector &vertices, const xr_vector &faces) +{ + new_vertices.clear(); + new_faces.clear(); + xr_vector remap; + remap.resize(vertices.size(), u32(-1)); + for (u32 f = 0; f < faces.size(); f++) + add_face(faces[f], new_vertices, new_faces, vertices, remap); + remap.clear(); +} + +// static vecOGF_V old_vertices; +// static vecOGF_F old_faces; +template +void t_remove_isolated_verts(xr_vector &vertices, xr_vector &faces) +{ + xr_vector old_vertices; + xr_vector old_faces; + old_vertices.clear(); + old_faces.clear(); + + old_vertices = vertices; + old_faces = faces; + + t_remove_isolated_verts(vertices, faces, old_vertices, old_faces); + + old_vertices.clear(); + old_faces.clear(); +} + +#endif \ No newline at end of file diff --git a/src/editors/ShaderEditor/SHCompilerTools.cpp b/src/editors/ShaderEditor/SHCompilerTools.cpp new file mode 100644 index 00000000000..46155458b62 --- /dev/null +++ b/src/editors/ShaderEditor/SHCompilerTools.cpp @@ -0,0 +1,173 @@ +//--------------------------------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +#include "SHCompilerTools.h" +#include "ui_shadermain.h" +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +CSHCompilerTools::CSHCompilerTools(const ISHInit &init) : ISHTools(init) +{ + m_Shader = 0; +} + +CSHCompilerTools::~CSHCompilerTools() +{ +} +//--------------------------------------------------------------------------- + +void CSHCompilerTools::OnActivate() +{ + // fill items + FillItemList(); + + // Ext.m_Items->SetOnModifiedEvent (TOnModifiedEvent(this,&CSHCompilerTools::Modified)); + Ext.m_Items->SetOnItemCreaetEvent(TOnItemCreate(this, &CSHCompilerTools::OnCreateItem)); + Ext.m_Items->SetOnItemCloneEvent(TOnItemClone(this, &CSHCompilerTools::OnCloneItem)); + Ext.m_Items->SetOnItemRenameEvent(TOnItemRename(this, &CSHCompilerTools::OnRenameItem)); + Ext.m_Items->SetOnItemRemoveEvent(TOnItemRemove(this, &CSHCompilerTools::OnRemoveItem)); + + inherited::OnActivate(); +} +void CSHCompilerTools::OnDeactivate() +{ + inherited::OnDeactivate(); +} + +void CSHCompilerTools::OnFrame() +{ + inherited::OnFrame(); +} +//--------------------------------------------------------------------------- + +bool CSHCompilerTools::OnCreate() +{ + Load(); + return true; +} + +void CSHCompilerTools::OnDestroy() +{ + m_bModified = FALSE; +} + +void CSHCompilerTools::ApplyChanges(bool bForced) +{ +} + +void CSHCompilerTools::Reload() +{ + ResetCurrentItem(); + Load(); + FillItemList(); +} + +void CSHCompilerTools::Load() +{ + string_path fn; + FS.update_path(fn, _game_data_, "shaders_xrlc.xr"); + + if (FS.exist(fn)) + { + m_Library.Load(fn); + } + else + { + ELog.DlgMsg(mtInformation, "Can't find file '%s'", fn); + } +} + +bool CSHCompilerTools::Save() +{ + ApplyChanges(); + + // save + string_path fn; + FS.update_path(fn, _game_data_, "shaders_xrlc.xr"); + + EFS.MarkFile(fn, false); + bool bRes = m_Library.Save(fn); + + if (bRes) + m_bModified = FALSE; + return bRes; +} + +Shader_xrLC *CSHCompilerTools::FindItem(LPCSTR name) +{ + if (name && name[0]) + { + return m_Library.Get(name); + } + else + return 0; +} + +void CSHCompilerTools::AppendItem(LPCSTR path, LPCSTR parent_name) +{ + Shader_xrLC *parent = FindItem(parent_name); + xr_string pref = path; + Shader_xrLC *S = m_Library.Append(parent); + m_LastSelection = pref; + strcpy(S->Name, m_LastSelection.c_str()); + ExecCommand(COMMAND_UPDATE_LIST); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + Modified(); +} + +void CSHCompilerTools::OnRenameItem(LPCSTR old_full_name, LPCSTR new_full_name, EItemType type) +{ + if (type == TYPE_OBJECT) + { + ApplyChanges(); + Shader_xrLC *S = FindItem(old_full_name); + R_ASSERT(S); + strcpy(S->Name, new_full_name); + if (S == m_Shader) + { + ExecCommand(COMMAND_UPDATE_PROPERTIES); + ExecCommand(COMMAND_UPDATE_LIST); + + m_LastSelection = m_Shader->Name; + + m_Shader = 0; + } + } +} + +void CSHCompilerTools::OnRemoveItem(LPCSTR name, EItemType type) +{ + if (type == TYPE_OBJECT) + { + R_ASSERT(name && name[0]); + if (m_Shader && stricmp(m_Shader->Name, name) == 0) + { + m_Shader = 0; + Tools->UpdateProperties(true); + } + m_Library.Remove(name); + } +} + +void CSHCompilerTools::SetCurrentItem(LPCSTR name, bool bView) +{ + if (m_bLockUpdate) + return; + + Shader_xrLC *S = FindItem(name); + // load shader + if (m_Shader != S) + { + m_Shader = S; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + if (bView) + ViewSetCurrentItem(name); + } +} + +void CSHCompilerTools::ResetCurrentItem() +{ + m_Shader = 0; +} diff --git a/src/editors/ShaderEditor/SHCompilerTools.h b/src/editors/ShaderEditor/SHCompilerTools.h new file mode 100644 index 00000000000..0f8d43e9c1b --- /dev/null +++ b/src/editors/ShaderEditor/SHCompilerTools.h @@ -0,0 +1,51 @@ +#pragma once +#include "utils/Shader_xrLC.h" +#include "SHToolsInterface.h" + +// refs +class PropValue; + +class CSHCompilerTools : public ISHTools +{ + void ItemExist(LPCSTR name, bool &res) { res = !!FindItem(name); } + Shader_xrLC *FindItem(LPCSTR name); + Shader_xrLC_LIB m_Library; + + ListItem *m_Selected; + +public: + Shader_xrLC *m_Shader; + virtual void OnRemoveItem(LPCSTR name, EItemType type); + virtual void OnRenameItem(LPCSTR old_full_name, LPCSTR new_full_name, EItemType type); + virtual void AppendItem(LPCSTR path, LPCSTR parent = 0); + virtual void FillItemList(); + +public: + CSHCompilerTools(const ISHInit &init); + virtual ~CSHCompilerTools(); + + virtual LPCSTR ToolsName() { return "Compiler Shader"; } + + virtual void Reload(); + virtual void Load(); + virtual bool Save(); + + virtual bool OnCreate(); + virtual void OnDestroy(); + virtual void OnActivate(); + virtual void OnDeactivate(); + + // misc + virtual void ResetCurrentItem(); + virtual void SetCurrentItem(LPCSTR name, bool bView); + virtual void ApplyChanges(bool bForced = false); + + virtual void RealUpdateProperties(); + virtual void RealUpdateList(); + + virtual void OnFrame(); + virtual void OnRender() { ; } + + virtual void OnDeviceCreate() { ; } + virtual void OnDeviceDestroy() { ; } +}; diff --git a/src/editors/ShaderEditor/SHCompilerToolsProperties.cpp b/src/editors/ShaderEditor/SHCompilerToolsProperties.cpp new file mode 100644 index 00000000000..ccd3eedb5d4 --- /dev/null +++ b/src/editors/ShaderEditor/SHCompilerToolsProperties.cpp @@ -0,0 +1,45 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "SHCompilerTools.h" +//#include "../xrEProps/ItemList.h" +//------------------------------------------------------------------------------ + +void CSHCompilerTools::FillItemList() +{ + ListItemsVec items; + Shader_xrLCVec &lst = m_Library.Library(); + for (auto it = lst.begin(); it != lst.end(); it++) + LHelper().CreateItem(items, it->Name, 0); + Ext.m_Items->AssignItems(items, nullptr, false); +} + +//------------------------------------------------------------------------------ +void CSHCompilerTools::RealUpdateList() +{ + FillItemList(); +} +//------------------------------------------------------------------------------ + +void CSHCompilerTools::RealUpdateProperties() +{ + PropItemVec items; + if (m_Shader) + { + Shader_xrLC &L = *m_Shader; + PHelper().CreateFloat(items, "Translucency", &L.vert_translucency); + PHelper().CreateFloat(items, "Ambient", &L.vert_ambient); + PHelper().CreateFloat(items, "LM density", &L.lm_density, 0.01f, 20.f); + + PHelper().CreateFlag32(items, "Flags\\Collision", &L.m_Flags, Shader_xrLC::flCollision); + PHelper().CreateFlag32(items, "Flags\\Rendering", &L.m_Flags, Shader_xrLC::flRendering); + PHelper().CreateFlag32(items, "Flags\\OptimizeUV", &L.m_Flags, Shader_xrLC::flOptimizeUV); + PHelper().CreateFlag32(items, "Flags\\Vertex light", &L.m_Flags, Shader_xrLC::flLIGHT_Vertex); + PHelper().CreateFlag32(items, "Flags\\Cast shadow", &L.m_Flags, Shader_xrLC::flLIGHT_CastShadow); + //. PHelper().CreateFlag32 (items, "Flags\\Sharp", &L.m_Flags, Shader_xrLC::flLIGHT_Sharp); + } + Ext.m_ItemProps->AssignItems(items); + Ext.m_ItemProps->SetModifiedEvent(TOnModifiedEvent(this, &CSHCompilerTools::Modified)); +} +//--------------------------------------------------------------------------- diff --git a/src/editors/ShaderEditor/SHEngineTools.cpp b/src/editors/ShaderEditor/SHEngineTools.cpp new file mode 100644 index 00000000000..172ad9bc3eb --- /dev/null +++ b/src/editors/ShaderEditor/SHEngineTools.cpp @@ -0,0 +1,1083 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "SHEngineTools.h" +#include "ui_shadermain.h" +#include "..\xrECore\Editor\EditMesh.h" +//------------------------------------------------------------------------------ +class CCollapseBlender : public CParseBlender +{ +public: + virtual void Parse(CSHEngineTools *owner, DWORD type, LPCSTR key, LPVOID data) + { + switch (type) + { + case xrPID_MATRIX: + owner->CollapseMatrix((LPSTR)data); + break; + case xrPID_CONSTANT: + owner->CollapseConstant((LPSTR)data); + break; + }; + } +}; + +class CRefsBlender : public CParseBlender +{ +public: + virtual void Parse(CSHEngineTools *owner, DWORD type, LPCSTR key, LPVOID data) + { + switch (type) + { + case xrPID_MATRIX: + owner->UpdateMatrixRefs((LPSTR)data); + break; + case xrPID_CONSTANT: + owner->UpdateConstantRefs((LPSTR)data); + break; + }; + } +}; + +class CRemoveBlender : public CParseBlender +{ +public: + virtual void Parse(CSHEngineTools *owner, DWORD type, LPCSTR key, LPVOID data) + { + switch (type) + { + case xrPID_MATRIX: + owner->RemoveMatrix((LPSTR)data); + break; + case xrPID_CONSTANT: + owner->RemoveConstant((LPSTR)data); + break; + }; + } +}; + +static CCollapseBlender ST_CollapseBlender; +static CRefsBlender ST_UpdateBlenderRefs; +static CRemoveBlender ST_RemoveBlender; + +//------------------------------------------------------------------------------ +CSHEngineTools::CSHEngineTools(const ISHInit &init) : ISHTools(init) +{ + m_PreviewObjectType = pvoNone; + m_PreviewObject = NULL; + m_bCustomEditObject = FALSE; + m_bFreezeUpdate = FALSE; + m_CurrentBlender = 0; + m_BlenderStream.clear(); + m_bNeedResetShaders = TRUE; + m_RemoteRenBlender = FALSE; + m_CreatingBlender = FALSE; + m_SetCustomObject = FALSE; + MCString.push_back("Custom..."); + MCString.push_back("$null"); + MCString.push_back("$base0"); + MCString.push_back("$base1"); + MCString.push_back("$base2"); + MCString.push_back("$base3"); + MCString.push_back("$base4"); + MCString.push_back("$base5"); + MCString.push_back("$base6"); + MCString.push_back("$base7"); +} + +CSHEngineTools::~CSHEngineTools() +{ + MCString.clear(); +} + +bool CSHEngineTools::OnCreate() +{ + IBlender::CreatePalette(m_TemplatePalette); + Load(); + return true; +} + +void CSHEngineTools::OnDestroy() +{ + Lib.RemoveEditObject(m_PreviewObject); + // free palette + for (TemplateIt it = m_TemplatePalette.begin(); it != m_TemplatePalette.end(); it++) + xr_delete(*it); + m_TemplatePalette.clear(); + + ClearData(); + + m_bModified = FALSE; +} + +xr_token preview_obj_token[] = { + {"None", pvoNone}, + {"Plane", pvoPlane}, + {"Box", pvoBox}, + {"Sphere", pvoSphere}, + {"Teapot", pvoTeapot}, + {"Custom...", pvoCustom}, + {0, 0}}; + +bool CSHEngineTools::OnPreviewObjectRefChange(PropValue *sender, u32 &new_val) +{ + LPCSTR fn = ""; + m_bCustomEditObject = false; + switch (new_val) + { + case pvoPlane: + fn = "editor\\ShaderTest_Plane"; + break; + case pvoBox: + fn = "editor\\ShaderTest_Box"; + break; + case pvoSphere: + fn = "editor\\ShaderTest_Sphere"; + break; + case pvoTeapot: + fn = "editor\\ShaderTest_Teapot"; + break; + case pvoCustom: + { + m_SetCustomObject = TRUE; + UIChooseForm::SelectItem(smObject, 1, 0, 0, 0, 0, 0, 0); + return true; + } + break; + } + + OnPreviewObjectRefChange(fn); + return true; +} + +void CSHEngineTools::OnPreviewObjectRefChange(const char *fn) +{ + string_path m_current; + string_path m_new; + xr_strcpy(m_current, fn); + xr_strcpy(m_new, m_PreviewObject ? m_PreviewObject->GetName() : ""); + _strlwr_s(m_current); + _strlwr_s(m_new); + + if (xr_strcmp(m_current, m_new) != 0) + { + Lib.RemoveEditObject(m_PreviewObject); + m_PreviewObject = (fn && fn[0]) ? Lib.CreateEditObject(fn) : 0; + ZoomObject(false); + UpdateObjectShader(); + UI->RedrawScene(); + } +} + +void CSHEngineTools::OnActivate() +{ + PropItemVec items; + TokenValue *V = PHelper().CreateToken32(items, PrepareKey("Object", "Reference"), &m_PreviewObjectType, preview_obj_token); + V->OnAfterEditEvent.bind(this, &CSHEngineTools::OnPreviewObjectRefChange); + Ext.m_PreviewProps->AssignItems(items); + // fill items*/ + FillItemList(); + /* Ext.m_Items->SetOnModifiedEvent (TOnModifiedEvent(this,&CSHEngineTools::Modified));*/ + Ext.m_Items->SetOnItemRenameEvent(TOnItemRename(this, &CSHEngineTools::OnRenameItem)); + Ext.m_Items->SetOnItemRemoveEvent(TOnItemRemove(this, &CSHEngineTools::OnRemoveItem)); + Ext.m_Items->SetOnItemCloneEvent(TOnItemClone(this, &CSHEngineTools::OnCloneItem)); + Ext.m_Items->SetOnItemCreaetEvent(TOnItemCreate(this, &CSHEngineTools::OnCreateItem)); + + inherited::OnActivate(); +} +//--------------------------------------------------------------------------- + +void CSHEngineTools::OnDeactivate() +{ + inherited::OnDeactivate(); +} + +void FreeStr(LPSTR str) +{ + xr_free(str); +} + +void CSHEngineTools::ClearData() +{ + // free constants, matrices, blenders + // Blender + for (BlenderPairIt b = m_Blenders.begin(); b != m_Blenders.end(); b++) + { + FreeStr(b->first); + xr_delete(b->second); + } + m_Blenders.clear(); + + // Matrices + for (MatrixPairIt m = m_Matrices.begin(); m != m_Matrices.end(); m++) + { + FreeStr(m->first); + xr_delete(m->second); + } + m_Matrices.clear(); + + // Constants + for (ConstantPairIt c = m_Constants.begin(); c != m_Constants.end(); c++) + { + LPSTR temp = (LPSTR)c->first; + xr_free(temp); + xr_delete(c->second); + } + m_Constants.clear(); +} + +void CSHEngineTools::OnFrame() +{ + if (m_bNeedResetShaders) + { + RealResetShaders(); + // ExecCommand (COMMAND_UPDATE_LIST); + } + if (m_RemoteRenBlender) + { + RealRenameItem(m_RenBlenderOldName.c_str(), m_RenBlenderNewName.c_str()); + m_RemoteRenBlender = FALSE; + } + + if (m_PreviewObject) + m_PreviewObject->OnFrame(); + inherited::OnFrame(); + if (m_SetCustomObject) + { + bool change = true; + shared_str result; + if (UIChooseForm::GetResult(change, result)) + { + if (change) + { + OnPreviewObjectRefChange(result.c_str()); + } + else + { + + m_PreviewObjectType = 0; + OnPreviewObjectRefChange(""); + } + m_SetCustomObject = FALSE; + } + } + if (m_CreatingBlender) + { + bool change = true; + shared_str result; + if (UIChooseForm::GetResult(change, result)) + { + if (change) + { + CLASS_ID cls_id = 0; + for (TemplateIt it = m_TemplatePalette.begin(); it != m_TemplatePalette.end(); it++) + { + if (0 == strcmp((*it)->getComment(), result.c_str())) + { + cls_id = (*it)->getDescription().CLS; + break; + } + } + R_ASSERT(cls_id); + AppendItem(m_CreatingBlenderPath.c_str(), cls_id); + } + + m_CreatingBlender = FALSE; + } + } +} + +void CSHEngineTools::OnRender() +{ + if (m_PreviewObject) + m_PreviewObject->RenderSingle(Fidentity); +} + +void CSHEngineTools::ZoomObject(bool bOnlySel) +{ + if (m_PreviewObject) + { + Fbox bb = m_PreviewObject->GetBox(); + EDevice.m_Camera.ZoomExtents(bb); + } + else + { + ISHTools::ZoomObject(bOnlySel); + } +} +//--------------------------------------------------------------------------- + +void CSHEngineTools::RealResetShaders() +{ + // disable props vis update + m_bFreezeUpdate = TRUE; + UpdateStreamFromObject(); + + UpdateObjectShader(); + // save to temp file + PrepareRender(); + // reset device shaders from temp file + IReader data(m_RenderShaders.pointer(), m_RenderShaders.size()); + EDevice.Reset(&data, TRUE); + // enable props vis update + m_bFreezeUpdate = FALSE; + m_bNeedResetShaders = FALSE; +} + +void CSHEngineTools::FillItemList() +{ + ListItemsVec items; + for (BlenderPairIt b = m_Blenders.begin(); b != m_Blenders.end(); b++) + LHelper().CreateItem(items, b->first, 0); + Ext.m_Items->AssignItems(items, m_LastSelection.size() ? m_LastSelection.c_str() : 0, false); +} + +void CSHEngineTools::ApplyChanges(bool bForced) +{ + if (m_CurrentBlender && (Ext.m_ItemProps->IsModified() || bForced)) + { + UpdateObjectFromStream(); + // Ext.m_ItemProps->ResetModified(); + ResetShaders(false); // required 'false' for matrix + } +} + +void CSHEngineTools::Reload() +{ + ResetCurrentItem(); + ClearData(); + Load(); + FillItemList(); + ResetShaders(false); // required 'false' for matrix +} + +void CSHEngineTools::Load() +{ + string_path fn; + FS.update_path(fn, _game_data_, "shaders.xr"); + + m_bFreezeUpdate = TRUE; + m_bLockUpdate = TRUE; + + if (FS.exist(fn)) + { + IReader *F = FS.r_open(fn); + char name[256]; + + // Load constants + { + IReader *fs = F->open_chunk(0); + while (fs && !fs->eof()) + { + fs->r_stringZ(name, sizeof(name)); + CConstant *C = xr_new(); + C->Load(fs); + m_Constants.insert(std::make_pair(xr_strdup(name), C)); + } + fs->close(); + } + + // Load matrices + { + IReader *fs = F->open_chunk(1); + while (fs && !fs->eof()) + { + fs->r_stringZ(name, sizeof(name)); + CMatrix *M = xr_new(); + M->Load(fs); + m_Matrices.insert(std::make_pair(xr_strdup(name), M)); + } + fs->close(); + } + + // Load blenders + { + IReader *fs = F->open_chunk(2); + IReader *chunk = NULL; + int chunk_id = 0; + + while ((chunk = fs->open_chunk(chunk_id)) != NULL) + { + CBlender_DESC desc; + chunk->r(&desc, sizeof(desc)); + IBlender *B = IBlender::Create(desc.CLS); + if (B) + { + if (B->getDescription().version != desc.version) + { + Msg("! Version conflict in shader '%s'", desc.cName); + } + chunk->seek(0); + B->Load(*chunk, desc.version); + + LPSTR blender_name = xr_strdup(desc.cName); + std::pair I = m_Blenders.insert(std::make_pair(blender_name, B)); + R_ASSERT2(I.second, "shader.xr - found duplicate name!!!"); + } + chunk->close(); + chunk_id++; + } + fs->close(); + } + FS.r_close(F); + UpdateRefCounters(); + ResetCurrentItem(); + } + else + { + ELog.DlgMsg(mtInformation, "Can't find file '%s'", fn); + } + m_bLockUpdate = FALSE; + m_bFreezeUpdate = FALSE; +} + +void CSHEngineTools::Save(CMemoryWriter &F) +{ + // Save constants + { + F.open_chunk(0); + for (ConstantPairIt c = m_Constants.begin(); c != m_Constants.end(); c++) + { + F.w_stringZ(c->first); + c->second->Save(&F); + } + F.close_chunk(); + } + + // Save matrices + { + F.open_chunk(1); + for (MatrixPairIt m = m_Matrices.begin(); m != m_Matrices.end(); m++) + { + F.w_stringZ(m->first); + m->second->Save(&F); + } + F.close_chunk(); + } + + // Save blenders + { + F.open_chunk(2); + int chunk_id = 0; + for (BlenderPairIt b = m_Blenders.begin(); b != m_Blenders.end(); b++) + { + F.open_chunk(chunk_id++); + b->second->Save(F); + F.close_chunk(); + } + F.close_chunk(); + } + // Save blender names + { + F.open_chunk(3); + F.w_u32(m_Blenders.size()); + for (BlenderPairIt b = m_Blenders.begin(); b != m_Blenders.end(); b++) + F.w_stringZ(b->first); + F.close_chunk(); + } +} + +bool CSHEngineTools::Save() +{ + // set name + string_path fn; + FS.update_path(fn, _game_data_, "shaders.xr"); + + // collapse reference + CollapseReferences(); + + // save to stream + CMemoryWriter F; + + Save(F); + + // save new file + EFS.MarkFile(fn, false); + bool bRes = F.save_to(fn); + + if (bRes) + { + m_bModified = FALSE; + // Ext.m_ItemProps->ResetModified(); + // restore shader + ResetShaders(); + } + return bRes; +} + +void CSHEngineTools::PrepareRender() +{ + CollapseReferences(); + m_RenderShaders.clear(); + Save(m_RenderShaders); +} + +IBlender *CSHEngineTools::FindItem(LPCSTR name) +{ + if (name && name[0]) + { + LPSTR N = LPSTR(name); + BlenderPairIt I = m_Blenders.find(N); + if (I == m_Blenders.end()) + return 0; + else + return I->second; + } + else + return 0; +} + +CMatrix *CSHEngineTools::FindMatrix(LPCSTR name) +{ + R_ASSERT(name && name[0]); + MatrixPairIt I = m_Matrices.find((LPSTR)name); + if (I == m_Matrices.end()) + return 0; + else + return I->second; +} + +CMatrix *CSHEngineTools::AppendMatrix(LPSTR name) +{ + CMatrix *M = FindMatrix(name); + VERIFY(M); + if (M->ref_count > 1) + { + M->ref_count--; + strcpy(name, AppendMatrix(M, &M)); + } + return M; +} + +CConstant *CSHEngineTools::FindConstant(LPCSTR name) +{ + R_ASSERT(name && name[0]); + ConstantPairIt I = m_Constants.find((LPSTR)name); + if (I == m_Constants.end()) + return 0; + else + return I->second; +} + +CConstant *CSHEngineTools::AppendConstant(LPSTR name) +{ + CConstant *C = FindConstant(name); + if (C->ref_count > 1) + { + C->ref_count--; + strcpy(name, AppendConstant(C, &C)); + } + return C; +} + +LPCSTR CSHEngineTools::GenerateMatrixName(LPSTR name) +{ + int cnt = 0; + do + sprintf(name, "%04x", cnt++); + while (FindMatrix(name)); + return name; +} + +LPCSTR CSHEngineTools::GenerateConstantName(LPSTR name) +{ + int cnt = 0; + do + sprintf(name, "%04x", cnt++); + while (FindConstant(name)); + return name; +} + +void CSHEngineTools::FillChooseTemplate(ChooseItemVec &items, void *param) +{ + for (TemplateIt it = m_TemplatePalette.begin(); it != m_TemplatePalette.end(); it++) + items.push_back(SChooseItem((*it)->getComment(), "")); +} + +void CSHEngineTools::AppendItem(LPCSTR path, LPCSTR parent_name) +{ + IBlender *parent = FindItem(parent_name); + CLASS_ID cls_id; + if (!parent) + { + UIChooseForm::SelectItem(smCustom, 1, 0, TOnChooseFillItems(this, &CSHEngineTools::FillChooseTemplate), 0, 0, 0, 0); + m_CreatingBlender = TRUE; + m_CreatingBlenderPath = path; + return; + } + else + { + cls_id = parent->getDescription().CLS; + } + AppendItem(path, cls_id, parent); +} + +void CSHEngineTools::RealRenameItem(LPCSTR old_full_name, LPCSTR new_full_name) +{ + ApplyChanges(); + LPSTR N = LPSTR(old_full_name); + BlenderPairIt I = m_Blenders.find(N); + R_ASSERT(I != m_Blenders.end()); + FreeStr(I->first); + IBlender *B = I->second; + m_Blenders.erase(I); + // rename + B->getDescription().Setup(new_full_name); + std::pair RES = m_Blenders.insert(std::make_pair(xr_strdup(new_full_name), B)); + R_ASSERT2(RES.second, "shader.xr - found duplicate name!!!"); + + if (B == m_CurrentBlender) + UpdateStreamFromObject(); + ApplyChanges(); + ResetShaders(); + if (B == m_CurrentBlender) + SetCurrentItem(B->getName(), true); + + //. RealUpdateProperties(); +} + +void CSHEngineTools::AddMatrixRef(LPSTR name) +{ + CMatrix *M = FindMatrix(name); + R_ASSERT(M); + M->ref_count++; +} + +void CSHEngineTools::AddConstantRef(LPSTR name) +{ + CConstant *C = FindConstant(name); + R_ASSERT(C); + C->ref_count++; +} + +LPCSTR CSHEngineTools::AppendConstant(CConstant *src, CConstant **dest) +{ + CConstant *C = xr_new(); + if (src) + *C = *src; + C->ref_count = 1; + char name[128]; + std::pair I = m_Constants.insert(std::make_pair(xr_strdup(GenerateConstantName(name)), C)); + VERIFY(I.second); + if (dest) + *dest = C; + return I.first->first; +} + +LPCSTR CSHEngineTools::AppendMatrix(CMatrix *src, CMatrix **dest) +{ + CMatrix *M = xr_new(); + if (src) + *M = *src; + M->ref_count = 1; + char name[128]; + std::pair I = m_Matrices.insert(std::make_pair(xr_strdup(GenerateMatrixName(name)), M)); + VERIFY(I.second); + if (dest) + *dest = M; + return I.first->first; +} + +void CSHEngineTools::OnRenameItem(LPCSTR old_full_name, LPCSTR new_full_name, EItemType type) +{ + + if (type == TYPE_OBJECT) + RealRenameItem(old_full_name, new_full_name); + m_bFreezeUpdate = TRUE; +} + +void CSHEngineTools::OnRemoveItem(LPCSTR name, EItemType type) +{ + if (type == TYPE_OBJECT) + { + R_ASSERT(name && name[0]); + IBlender *B = FindItem(name); + R_ASSERT(B); + // remove refs + ParseBlender(B, ST_RemoveBlender); + LPSTR N = LPSTR(name); + BlenderPairIt I = m_Blenders.find(N); + FreeStr(I->first); + if (m_CurrentBlender == I->second) + { + m_CurrentBlender = 0; + Tools->UpdateProperties(true); + } + xr_delete(I->second); + + m_Blenders.erase(I); + + ApplyChanges(); + ResetShaders(); + } +} + +void CSHEngineTools::RemoveMatrix(LPCSTR name) +{ + if (*name == '$') + return; + R_ASSERT(name && name[0]); + CMatrix *M = FindMatrix(name); + VERIFY(M); + M->ref_count--; + if (M->ref_count == 0) + { + LPSTR N = LPSTR(name); + MatrixPairIt I = m_Matrices.find(N); + FreeStr(I->first); + xr_delete(I->second); + m_Matrices.erase(I); + } +} + +void CSHEngineTools::RemoveConstant(LPCSTR name) +{ + if (*name == '$') + return; + R_ASSERT(name && name[0]); + CConstant *C = FindConstant(name); + VERIFY(C); + C->ref_count--; + if (C->ref_count == 0) + { + LPSTR N = LPSTR(name); + ConstantPairIt I = m_Constants.find(N); + FreeStr(I->first); + xr_delete(I->second); + m_Constants.erase(I); + } +} + +void CSHEngineTools::UpdateStreamFromObject() +{ + m_BlenderStream.clear(); + if (m_CurrentBlender) + m_CurrentBlender->Save(m_BlenderStream); + // init properties + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CSHEngineTools::UpdateObjectFromStream() +{ + if (m_CurrentBlender) + { + IReader data(m_BlenderStream.pointer(), m_BlenderStream.size()); + m_CurrentBlender->Load(data, m_CurrentBlender->getDescription().version); + } +} + +void CSHEngineTools::SetCurrentItem(LPCSTR name, bool bView) +{ + if (m_bLockUpdate) + return; + + IBlender *B = FindItem(name); + if (m_CurrentBlender != B) + { + m_CurrentBlender = B; + UpdateStreamFromObject(); + // apply this shader to non custom object + UpdateObjectShader(); + if (bView) + ViewSetCurrentItem(name); + } +} + +void CSHEngineTools::ResetCurrentItem() +{ + m_CurrentBlender = 0; + UpdateStreamFromObject(); +} + +void CSHEngineTools::CollapseMatrix(LPSTR name) +{ + if (*name == '$') + return; + R_ASSERT(name && name[0]); + CMatrix *M = FindMatrix(name); + VERIFY(M); + M->ref_count--; + for (MatrixPairIt m = m_OptMatrices.begin(); m != m_OptMatrices.end(); m++) + { + if (m->second->Similar(*M)) + { + strcpy(name, m->first); + m->second->ref_count++; + return; + } + } + // append new optimized matrix + CMatrix *N = xr_new(*M); + N->ref_count = 1; + m_OptMatrices.insert(std::make_pair(xr_strdup(name), N)); +} + +void CSHEngineTools::CollapseConstant(LPSTR name) +{ + if (*name == '$') + return; + R_ASSERT(name && name[0]); + CConstant *C = FindConstant(name); + VERIFY(C); + C->ref_count--; + for (ConstantPairIt c = m_OptConstants.begin(); c != m_OptConstants.end(); c++) + { + if (c->second->Similar(*C)) + { + strcpy(name, c->first); + c->second->ref_count++; + return; + } + } + // append opt constant + CConstant *N = xr_new(*C); + N->ref_count = 1; + m_OptConstants.insert(std::make_pair(xr_strdup(name), N)); +} + +void CSHEngineTools::UpdateMatrixRefs(LPSTR name) +{ + if (*name == '$') + return; + R_ASSERT(name && name[0]); + CMatrix *M = FindMatrix(name); + R_ASSERT(M); + M->ref_count++; +} + +void CSHEngineTools::UpdateConstantRefs(LPSTR name) +{ + if (*name == '$') + return; + R_ASSERT(name && name[0]); + CConstant *C = FindConstant(name); + R_ASSERT(C); + C->ref_count++; +} + +void CSHEngineTools::ParseBlender(IBlender *B, CParseBlender &P) +{ + CMemoryWriter M; + B->Save(M); + + IReader data(M.pointer(), M.size()); + data.advance(sizeof(CBlender_DESC)); + DWORD type; + string256 key; + + while (!data.eof()) + { + int sz = 0; + type = data.r_u32(); + data.r_stringZ(key, sizeof(key)); + switch (type) + { + case xrPID_MARKER: + break; + case xrPID_MATRIX: + sz = sizeof(string64); + break; + case xrPID_CONSTANT: + sz = sizeof(string64); + break; + case xrPID_TEXTURE: + sz = sizeof(string64); + break; + case xrPID_INTEGER: + sz = sizeof(xrP_Integer); + break; + case xrPID_FLOAT: + sz = sizeof(xrP_Float); + break; + case xrPID_BOOL: + sz = sizeof(xrP_BOOL); + break; + case xrPID_TOKEN: + sz = sizeof(xrP_TOKEN) + sizeof(xrP_TOKEN::Item) * (((xrP_TOKEN *)data.pointer())->Count); + break; + default: + THROW2("xrPID_????"); + } + P.Parse(this, type, key, data.pointer()); + data.advance(sz); + } + + data.seek(0); + B->Load(data, B->getDescription().version); +} + +void CSHEngineTools::CollapseReferences() +{ + for (BlenderPairIt b = m_Blenders.begin(); b != m_Blenders.end(); b++) + ParseBlender(b->second, ST_CollapseBlender); + for (MatrixPairIt m = m_Matrices.begin(); m != m_Matrices.end(); m++) + { + VERIFY(m->second->dwReference == 0); + FreeStr(m->first); + xr_delete(m->second); + } + for (ConstantPairIt c = m_Constants.begin(); c != m_Constants.end(); c++) + { + VERIFY(c->second->dwReference == 0); + FreeStr(c->first); + xr_delete(c->second); + } + m_Matrices.clear(); + m_Constants.clear(); + m_Matrices = m_OptMatrices; + m_Constants = m_OptConstants; + m_OptConstants.clear(); + m_OptMatrices.clear(); +} + +void CSHEngineTools::UpdateRefCounters() +{ + for (BlenderPairIt b = m_Blenders.begin(); b != m_Blenders.end(); b++) + ParseBlender(b->second, ST_UpdateBlenderRefs); +} + +void CSHEngineTools::OnDeviceCreate() +{ + ResetShaders(); +} + +void CSHEngineTools::UpdateObjectShader() +{ + // apply this shader to non custom object + CEditableObject *E = m_PreviewObject; + if (E && !m_bCustomEditObject) + { + CSurface *surf = *E->FirstSurface(); + R_ASSERT(surf); + /* + u32 cnt = _GetItemCount(surf->_Texture()); + string512 tex; + string128 elem; + if (0==cnt){ + strcpy (elem,"$shadertest"); + }else{ + _GetItem(surf->_Texture(),0,elem); + } + strcpy (tex,surf->_Texture()); + for (int i=cnt; i<8; i++){ strcat(tex,","); strcat(tex,elem);} + surf->SetTexture(tex); + */ + if (m_CurrentBlender) + surf->SetShader(m_CurrentBlender->getName()); + else + surf->SetShader("editor\\wire"); + UI->RedrawScene(); + E->OnDeviceDestroy(); + } +} + +void CSHEngineTools::OnShowHint(AStringVec &ss) +{ + if (m_PreviewObject) + { + float dist = UI->ZFar(); + SRayPickInfo pinf; + if (m_PreviewObject->RayPick(dist, UI->m_CurrentRStart, UI->m_CurrentRDir, Fidentity, &pinf)) + { + R_ASSERT(pinf.e_mesh); + CSurface *surf = pinf.e_mesh->GetSurfaceByFaceID(pinf.inf.id); + ss.push_back(xr_string("Surface: ") + xr_string(surf->_Name())); + ss.push_back(xr_string("Texture: ") + xr_string(surf->_Texture())); + ss.push_back(xr_string("Shader: ") + xr_string(surf->_ShaderName())); + ss.push_back(xr_string("LC Shader: ") + xr_string(surf->_ShaderXRLCName())); + ss.push_back(xr_string("Game Mtl: ") + xr_string(surf->_GameMtlName())); + ss.push_back(xr_string("2 Sided: ") + xr_string(surf->m_Flags.is(CSurface::sf2Sided) ? "on" : "off")); + } + } +} + +void CSHEngineTools::OnDrawUI() +{ + if (m_CreatingBlender || m_SetCustomObject) + { + UIChooseForm::Update(); + } +} + +void CSHEngineTools::AppendItem(LPCSTR path, CLASS_ID cls_id, IBlender *parent) +{ + R_ASSERT2(cls_id, "Invalid CLASS_ID."); + // append blender + IBlender *B = IBlender::Create(cls_id); + // append matrix& constant + CMemoryWriter M; + if (parent) + parent->Save(M); + else + B->Save(M); + // parse data + IReader data(M.pointer(), M.size()); + data.advance(sizeof(CBlender_DESC)); + DWORD type; + string256 key; + + while (!data.eof()) + { + int sz = 0; + type = data.r_u32(); + data.r_stringZ(key, sizeof(key)); + switch (type) + { + case xrPID_MARKER: + break; + case xrPID_MATRIX: + sz = sizeof(string64); + if (strcmp((LPSTR)data.pointer(), "$null") != 0) + { + if (!parent) + strcpy((LPSTR)data.pointer(), AppendMatrix()); + else + AddMatrixRef((LPSTR)data.pointer()); + } + break; + case xrPID_CONSTANT: + sz = sizeof(string64); + if (strcmp((LPSTR)data.pointer(), "$null") != 0) + { + if (!parent) + strcpy((LPSTR)data.pointer(), AppendConstant()); + else + AddConstantRef((LPSTR)data.pointer()); + } + break; + case xrPID_TEXTURE: + sz = sizeof(string64); + break; + case xrPID_INTEGER: + sz = sizeof(xrP_Integer); + break; + case xrPID_FLOAT: + sz = sizeof(xrP_Float); + break; + case xrPID_BOOL: + sz = sizeof(xrP_BOOL); + break; + case xrPID_TOKEN: + sz = sizeof(xrP_TOKEN) + sizeof(xrP_TOKEN::Item) * (((xrP_TOKEN *)data.pointer())->Count); + break; + default: + THROW2("xrPID_????"); + } + data.advance(sz); + } + data.seek(0); + B->Load(data, B->getDescription().version); + // set name + m_LastSelection = path; + B->getDescription().Setup(m_LastSelection.c_str()); + // insert blender + std::pair I = m_Blenders.insert(std::make_pair(xr_strdup(m_LastSelection.c_str()), B)); + R_ASSERT2(I.second, "shader.xr - found duplicate name!!!"); + // insert to TreeView + ExecCommand(COMMAND_UPDATE_LIST); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + + ResetShaders(true); + Modified(); +} diff --git a/src/editors/ShaderEditor/SHEngineTools.h b/src/editors/ShaderEditor/SHEngineTools.h new file mode 100644 index 00000000000..c49ef9ea1b1 --- /dev/null +++ b/src/editors/ShaderEditor/SHEngineTools.h @@ -0,0 +1,186 @@ +//--------------------------------------------------------------------------- +#ifndef SHEngineToolsH +#define SHEngineToolsH + +#include "SHToolsInterface.h" + +DEFINE_VECTOR(IBlender *, TemplateVec, TemplateIt); +DEFINE_MAP_PRED(LPSTR, CConstant *, ConstantMap, ConstantPairIt, str_pred); +DEFINE_MAP_PRED(LPSTR, CMatrix *, MatrixMap, MatrixPairIt, str_pred); +DEFINE_MAP_PRED(LPSTR, IBlender *, BlenderMap, BlenderPairIt, str_pred); + +// refs +class CSHEngineTools; +class CEditableObject; + +class CParseBlender +{ +public: + virtual void Parse(CSHEngineTools *owner, DWORD type, LPCSTR key, LPVOID data) = 0; +}; + +enum EPreviewObj +{ + pvoNone, + pvoPlane, + pvoBox, + pvoSphere, + pvoTeapot, + pvoCustom, + pvo_force_dword = u32(-1) +}; + +class CSHEngineTools : public ISHTools +{ + SStringVec MCString; + + u32 m_PreviewObjectType; + CEditableObject *m_PreviewObject; + bool m_bCustomEditObject; + + BOOL m_bFreezeUpdate; + BOOL m_bNeedResetShaders; + BOOL m_RemoteRenBlender; + BOOL m_CreatingBlender; + xr_string m_CreatingBlenderPath; + BOOL m_SetCustomObject; + + xr_string m_RenBlenderOldName; + xr_string m_RenBlenderNewName; + + TemplateVec m_TemplatePalette; + + ConstantMap m_OptConstants; + MatrixMap m_OptMatrices; + ConstantMap m_Constants; + MatrixMap m_Matrices; + BlenderMap m_Blenders; + + void ItemExist(LPCSTR name, bool &res) { res = !!FindItem(name); } + IBlender *FindItem(LPCSTR name); + + void AddMatrixRef(LPSTR name); + CMatrix *FindMatrix(LPCSTR name); + CMatrix *AppendMatrix(LPSTR name); + LPCSTR GenerateMatrixName(LPSTR name); + LPCSTR AppendMatrix(CMatrix *src = 0, CMatrix **dest = 0); + void RemoveMatrix(LPCSTR name); + + void AddConstantRef(LPSTR name); + CConstant *FindConstant(LPCSTR name); + CConstant *AppendConstant(LPSTR name); + LPCSTR GenerateConstantName(LPSTR name); + LPCSTR AppendConstant(CConstant *src = 0, CConstant **dest = 0); + void RemoveConstant(LPCSTR name); + + friend class CCollapseBlender; + friend class CRefsBlender; + friend class CRemoveBlender; + friend class TfrmShaderProperties; + void CollapseMatrix(LPSTR name); + void CollapseConstant(LPSTR name); + void CollapseReferences(); + void UpdateMatrixRefs(LPSTR name); + void UpdateConstantRefs(LPSTR name); + void UpdateRefCounters(); + + void ParseBlender(IBlender *B, CParseBlender &P); + + CMemoryWriter m_BlenderStream; // ������������ ��������� ���������� ������ ��� ������������� + bool m_bUpdateCurrent; // ���� ������� ������ ��������������� Update____From___() + bool m_bCurBlenderChanged; + + void Save(CMemoryWriter &F); + void PrepareRender(); + + // template + void FillChooseTemplate(ChooseItemVec &items, void *param); + // matrix props + bool MatrixOnAfterEdit(PropValue *sender, xr_string &edit_val); + void FillMatrixProps(PropItemVec &items, LPCSTR pref, LPSTR name); + void MCOnDraw(PropValue *sender, xr_string &draw_val); + // constant props + bool ConstOnAfterEdit(PropValue *sender, xr_string &edit_val); + void FillConstProps(PropItemVec &items, LPCSTR pref, LPSTR name); + // name + bool NameOnAfterEdit(PropValue *sender, xr_string &edit_val); + + void RealResetShaders(); + + void FillMatrix(PropItemVec &values, LPCSTR pref, CMatrix *m); + void FillConst(PropItemVec &values, LPCSTR pref, CConstant *c); + void RefreshProperties(); + + void ResetShaders(bool bForced = false) + { + m_bNeedResetShaders = true; + if (bForced) + RealResetShaders(); + } + void UpdateObjectShader(); + + bool OnPreviewObjectRefChange(PropValue *sender, u32 &edit_val); + void OnPreviewObjectRefChange(const char *name); + +public: + CMemoryWriter m_RenderShaders; + + IBlender *m_CurrentBlender; + void RemoteRenameBlender(LPCSTR old_full_name, LPCSTR new_full_name) + { + m_RemoteRenBlender = TRUE; + m_RenBlenderOldName = old_full_name; + m_RenBlenderNewName = new_full_name; + } + + Shader_xrLC *m_Shader; + + virtual void AppendItem(LPCSTR path, LPCSTR parent = 0); + virtual void RealRenameItem(LPCSTR old_full_name, LPCSTR new_full_name); + virtual void OnRemoveItem(LPCSTR name, EItemType type); + virtual void OnRenameItem(LPCSTR old_full_name, LPCSTR new_full_name, EItemType type); + virtual void FillItemList(); + + void UpdateStreamFromObject(); + void UpdateObjectFromStream(); + + void ClearData(); + +public: + CSHEngineTools(const ISHInit &init); + virtual ~CSHEngineTools(); + + virtual LPCSTR ToolsName() { return "Engine Shader"; } + + virtual void Reload(); + virtual void Load(); + virtual bool Save(); + + virtual bool OnCreate(); + virtual void OnDestroy(); + virtual void OnActivate(); + virtual void OnDeactivate(); + + // misc + virtual void ResetCurrentItem(); + virtual void SetCurrentItem(LPCSTR name, bool bView); + virtual void ApplyChanges(bool bForced = false); + + virtual void RealUpdateProperties(); + virtual void RealUpdateList(); + + virtual void OnFrame(); + virtual void OnRender(); + + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy() { ; } + + virtual void ZoomObject(bool bOnlySel); + virtual void OnShowHint(AStringVec &ss); + virtual void OnDrawUI(); + +private: + void AppendItem(LPCSTR path, CLASS_ID cls, IBlender *parent = nullptr); +}; +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/ShaderEditor/SHEngineToolsProperties.cpp b/src/editors/ShaderEditor/SHEngineToolsProperties.cpp new file mode 100644 index 00000000000..9b9e2772f36 --- /dev/null +++ b/src/editors/ShaderEditor/SHEngineToolsProperties.cpp @@ -0,0 +1,236 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "SHEngineTools.h" + +//--------------------------------------------------------------------------- +xr_token mode_token[] = { + {"Programmable", CMatrix::modeProgrammable}, + {"TCM", CMatrix::modeTCM}, + {"Spherical Reflection", CMatrix::modeS_refl}, + {"Cube Reflection", CMatrix::modeC_refl}, + {0, 0}}; +//--------------------------------------------------------------------------- +void CSHEngineTools::FillMatrixProps(PropItemVec &items, LPCSTR pref, LPSTR name) +{ + CMatrix *M = AppendMatrix(name); + R_ASSERT(M); + + PHelper().CreateToken32(items, PrepareKey(pref, "Mode"), &M->dwMode, mode_token); + + if (M->dwMode == CMatrix::modeTCM) + { + PHelper().CreateFlag32(items, PrepareKey(pref, "Scale enabled"), &M->tcm_flags, CMatrix::tcmScale); + PHelper().CreateWave(items, PrepareKey(pref, "Scale U"), &M->scaleU); + PHelper().CreateWave(items, PrepareKey(pref, "Scale V"), &M->scaleV); + PHelper().CreateFlag32(items, PrepareKey(pref, "Rotate enabled"), &M->tcm_flags, CMatrix::tcmRotate); + PHelper().CreateWave(items, PrepareKey(pref, "Rotate"), &M->rotate); + PHelper().CreateFlag32(items, PrepareKey(pref, "Scroll enabled"), &M->tcm_flags, CMatrix::tcmScroll); + PHelper().CreateWave(items, PrepareKey(pref, "Scroll U"), &M->scrollU); + PHelper().CreateWave(items, PrepareKey(pref, "Scroll V"), &M->scrollV); + } +} +//--------------------------------------------------------------------------- + +void CSHEngineTools::MCOnDraw(PropValue *sender, xr_string &draw_val) +{ + if (draw_val[0] != '$') + draw_val = "Custom"; +} +//--------------------------------------------------------------------------- + +bool CSHEngineTools::MatrixOnAfterEdit(PropValue *sender, xr_string &nm) +{ + CListValue *V = dynamic_cast(sender); + R_ASSERT(V); + VERIFY(nm.size()); + LPCSTR src_val = V->GetValue(); + + if (nm[0] != '$') + { + if (src_val[0] == '$') + { + nm = AppendMatrix(); + } + else + { + nm = src_val; + } + } + else + { + if (src_val[0] != '$') + { + RemoveMatrix(src_val); + V->ApplyValue(src_val); + } + } + return true; +} +//------------------------------------------------------------------------------ + +void CSHEngineTools::FillConstProps(PropItemVec &items, LPCSTR pref, LPSTR name) +{ + CConstant *C = AppendConstant(name); + R_ASSERT(C); + PHelper().CreateWave(items, PrepareKey(pref, "R"), &C->_R); + PHelper().CreateWave(items, PrepareKey(pref, "G"), &C->_G); + PHelper().CreateWave(items, PrepareKey(pref, "B"), &C->_B); + PHelper().CreateWave(items, PrepareKey(pref, "A"), &C->_A); +} +//--------------------------------------------------------------------------- + +bool CSHEngineTools::ConstOnAfterEdit(PropValue *sender, xr_string &nm) +{ + CListValue *V = dynamic_cast(sender); + R_ASSERT(V); + VERIFY(nm.size()); + LPCSTR src_val = V->GetValue(); + + if (nm[0] != '$') + { + if (src_val[0] == '$') + { + nm = AppendConstant(); + } + else + { + nm = src_val; + } + } + else + { + if (src_val[0] != '$') + { + RemoveConstant(src_val); + V->ApplyValue(src_val); + } + } + return true; +} +//------------------------------------------------------------------------------ +bool CSHEngineTools::NameOnAfterEdit(PropValue *sender, xr_string &new_name) +{ + /* not_implemented(); + CTextValue* V = dynamic_cast(sender); R_ASSERT(V); + xr_string nn = new_name.c_str(); + if (FHelper.NameAfterEdit((TElTreeItem*)m_CurrentItem->Item(),V->GetValue(),nn)) + { + new_name = nn.c_str(); + RemoteRenameBlender(V->GetValue(),new_name.c_str()); + }*/ + R_ASSERT(0); + return true; +} +//------------------------------------------------------------------------------ + +void CSHEngineTools::RealUpdateList() +{ + if (m_bFreezeUpdate) + return; + FillItemList(); +} +//------------------------------------------------------------------------------ + +void CSHEngineTools::RealUpdateProperties() +{ + if (m_bFreezeUpdate) + return; + + PropItemVec items; + if (m_CurrentBlender) + { // fill Tree + xr_string marker_text = ""; + + IReader data(m_BlenderStream.pointer(), m_BlenderStream.size()); + CBlender_DESC *desc = (CBlender_DESC *)data.pointer(); + data.advance(sizeof(CBlender_DESC)); + DWORD type; + string256 key; + + PHelper().CreateCaption(items, "Type", m_CurrentBlender->getComment()); + PHelper().CreateCaption(items, "Owner", desc->cComputer); + /*CTextValue* V = PHelper().CreateCText(items,"Name",desc->cName,sizeof(desc->cName)); + V->OnAfterEditEvent.bind (this,&CSHEngineTools::NameOnAfterEdit); + V->OnBeforeEditEvent.bind (&PHelper(),&IPropHelper::CNameBeforeEdit); + V->Owner()->OnDrawTextEvent.bind(&PHelper(),&IPropHelper::CNameDraw);*/ + + while (!data.eof()) + { + int sz = 0; + type = data.r_u32(); + data.r_stringZ(key, sizeof(key)); + switch (type) + { + case xrPID_MARKER: + marker_text = key; + break; + case xrPID_TOKEN: + { + xrP_TOKEN *V = (xrP_TOKEN *)data.pointer(); + sz = sizeof(xrP_TOKEN) + sizeof(xrP_TOKEN::Item) * V->Count; + PHelper().CreateTokenSH(items, PrepareKey(marker_text.c_str(), key), &V->IDselected, (TokenValueSH::Item *)(LPBYTE(data.pointer()) + sizeof(xrP_TOKEN)), V->Count); + } + break; + case xrPID_MATRIX: + { + sz = sizeof(string64); + /* LPSTR V = (LPSTR)data.pointer(); + CListValue* P = PHelper().CreateCList(items,PrepareKey(marker_text.c_str(),key),V,sz,&*MCString.begin(),MCString.size()); + xr_string pref = xr_string(PrepareKey(marker_text.c_str(),"Custom ").c_str())+key; + if (V&&V[0]&&(*V!='$')) FillMatrixProps(items,pref.c_str(),V); + P->OnAfterEditEvent.bind(this,&CSHEngineTools::MatrixOnAfterEdit); + P->Owner()->OnDrawTextEvent.bind(this,&CSHEngineTools::MCOnDraw);*/ + } + break; + case xrPID_CONSTANT: + { + sz = sizeof(string64); + /* LPSTR V = (LPSTR)data.pointer(); + CListValue* P = PHelper().CreateCList(items,PrepareKey(marker_text.c_str(),key),V,sz,&*MCString.begin(),MCString.size()); + xr_string pref = xr_string(PrepareKey(marker_text.c_str(),"Custom ").c_str())+key; + if (V&&V[0]&&(*V!='$')) FillConstProps(items,pref.c_str(),V); + P->OnAfterEditEvent.bind(this,&CSHEngineTools::ConstOnAfterEdit); + P->Owner()->OnDrawTextEvent.bind(this,&CSHEngineTools::MCOnDraw);*/ + } + break; + case xrPID_TEXTURE: + sz = sizeof(string64); + PHelper().CreateTexture(items, PrepareKey(marker_text.c_str(), key), (LPSTR)data.pointer(), sz); + break; + case xrPID_INTEGER: + { + sz = sizeof(xrP_Integer); + xrP_Integer *V = (xrP_Integer *)data.pointer(); + PHelper().CreateS32(items, PrepareKey(marker_text.c_str(), key), &V->value, V->min, V->max, 1); + } + break; + case xrPID_FLOAT: + { + sz = sizeof(xrP_Float); + xrP_Float *V = (xrP_Float *)data.pointer(); + PHelper().CreateFloat(items, PrepareKey(marker_text.c_str(), key), &V->value, V->min, V->max, 0.01f, 2); + } + break; + case xrPID_BOOL: + { + sz = sizeof(xrP_BOOL); + xrP_BOOL *V = (xrP_BOOL *)data.pointer(); + PHelper().CreateBOOL(items, PrepareKey(marker_text.c_str(), key), &V->value); + } + break; + default: + THROW2("UNKNOWN xrPID_????"); + } + data.advance(sz); + } + // ApplyChanges(true); + UpdateObjectFromStream(); + // Ext.m_ItemProps->ResetModified(); + //--------------------------- + } + Ext.m_ItemProps->AssignItems(items); + Ext.m_ItemProps->SetModifiedEvent(TOnModifiedEvent(this, &CSHEngineTools::Modified)); +} +//------------------------------------------------------------------------------ diff --git a/src/editors/ShaderEditor/SHGameMtlPairTools.cpp b/src/editors/ShaderEditor/SHGameMtlPairTools.cpp new file mode 100644 index 00000000000..87223c1f686 --- /dev/null +++ b/src/editors/ShaderEditor/SHGameMtlPairTools.cpp @@ -0,0 +1,163 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "SHGameMtlPairTools.h" +#include "UI_ShaderTools.h" +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +CSHGameMtlPairTools::CSHGameMtlPairTools(const ISHInit &init) : ISHTools(init) +{ + m_MtlPair = 0; + m_GameMtlTools = 0; +} + +CSHGameMtlPairTools::~CSHGameMtlPairTools() +{ +} +//--------------------------------------------------------------------------- + +void CSHGameMtlPairTools::OnFrame() +{ + inherited::OnFrame(); +} +void CSHGameMtlPairTools::OnDrawUI() +{ + if (m_MtlPair) + m_MtlPair->OnDrawUI(); +} +//--------------------------------------------------------------------------- + +bool CSHGameMtlPairTools::OnCreate() +{ + m_GameMtlTools = STools->FindTools(aeMtl); + R_ASSERT(m_GameMtlTools); + Load(); + return true; +} +//--------------------------------------------------------------------------- + +void CSHGameMtlPairTools::OnDestroy() +{ + m_bModified = FALSE; +} +//--------------------------------------------------------------------------- + +void CSHGameMtlPairTools::Reload() +{ + // mtl + ResetCurrentItem(); + // mtl pair + m_GameMtlTools->ResetCurrentItem(); + // load + Load(); + // mtl pair + m_GameMtlTools->FillItemList(); + FillItemList(); +} +//--------------------------------------------------------------------------- + +void CSHGameMtlPairTools::FillItemList() +{ + ListItemsVec items; + for (GameMtlIt m0_it = GMLib.FirstMaterial(); m0_it != GMLib.LastMaterial(); m0_it++) + { + SGameMtl *M0 = *m0_it; + for (GameMtlIt m1_it = GMLib.FirstMaterial(); m1_it != GMLib.LastMaterial(); m1_it++) + { + SGameMtl *M1 = *m1_it; + GameMtlPairIt p_it = GMLib.GetMaterialPairIt(M0->GetID(), M1->GetID()); + if (p_it != GMLib.LastMaterialPair()) + LHelper().CreateItem(items, GMLib.MtlPairToName(M0->GetID(), M1->GetID()), 0); + } + } + Ext.m_Items->AssignItems(items); + m_MtlPair = 0; +} +//--------------------------------------------------------------------------- + +void CSHGameMtlPairTools::Load() +{ + m_bLockUpdate = TRUE; + + GMLib.Unload(); + GMLib.Load(); + ResetCurrentItem(); + + m_bLockUpdate = FALSE; +} +//--------------------------------------------------------------------------- + +bool CSHGameMtlPairTools::Save() +{ + m_bLockUpdate = TRUE; + + // save + string_path fn; + FS.update_path(fn, _game_data_, GAMEMTL_FILENAME); + EFS.MarkFile(fn, false); + bool bRes = GMLib.Save(); + m_bLockUpdate = FALSE; + if (bRes) + m_bModified = FALSE; + return bRes; +} +//--------------------------------------------------------------------------- + +void CSHGameMtlPairTools::RealUpdateList() +{ + FillItemList(); +} +//------------------------------------------------------------------------------ + +void CSHGameMtlPairTools::RealUpdateProperties() +{ + PropItemVec items; + if (m_MtlPair) + m_MtlPair->FillProp(items); + Ext.m_ItemProps->AssignItems(items); +} +//--------------------------------------------------------------------------- + +void CSHGameMtlPairTools::ApplyChanges(bool bForced) +{ +} +//--------------------------------------------------------------------------- + +void CSHGameMtlPairTools::OnActivate() +{ + FillItemList(); + inherited::OnActivate(); + m_StoreFlags = Ext.m_Items->m_Flags.get(); + Ext.m_Items->m_Flags.assign(0); +} +//--------------------------------------------------------------------------- + +void CSHGameMtlPairTools::OnDeactivate() +{ + inherited::OnDeactivate(); + Ext.m_Items->m_Flags.assign(m_StoreFlags); +} + +void CSHGameMtlPairTools::SetCurrentItem(LPCSTR name, bool bView) +{ + if (m_bLockUpdate) + return; + SGameMtlPair *S = GMLib.GetMaterialPair(name); + // set material + if (m_MtlPair != S) + { + m_MtlPair = S; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + if (bView) + ViewSetCurrentItem(name); + } +} +//--------------------------------------------------------------------------- + +void CSHGameMtlPairTools::ResetCurrentItem() +{ + m_MtlPair = 0; +} +//--------------------------------------------------------------------------- diff --git a/src/editors/ShaderEditor/SHGameMtlPairTools.h b/src/editors/ShaderEditor/SHGameMtlPairTools.h new file mode 100644 index 00000000000..46fa07c189e --- /dev/null +++ b/src/editors/ShaderEditor/SHGameMtlPairTools.h @@ -0,0 +1,48 @@ +#pragma once +#include "SHToolsInterface.h" +#include "xrEngine/GameMtlLib.h" + +// refs +class PropValue; + +class CSHGameMtlPairTools : public ISHTools +{ + ISHTools *m_GameMtlTools; + u32 m_StoreFlags; + +public: + SGameMtlPair *m_MtlPair; + virtual void AppendItem(LPCSTR folder_name, LPCSTR parent_name = 0) {} + virtual void FillItemList(); + +public: + CSHGameMtlPairTools(const ISHInit &init); + virtual ~CSHGameMtlPairTools(); + + virtual LPCSTR ToolsName() { return "Game Material Pairs"; } + + virtual void Reload(); + virtual void Load(); + virtual bool Save(); + virtual void ApplyChanges(bool bForced = false); + + virtual bool OnCreate(); + virtual void OnDestroy(); + virtual void OnActivate(); + virtual void OnDeactivate(); + + // misc + virtual void ResetCurrentItem(); + virtual void SetCurrentItem(LPCSTR name, bool bView); + + virtual void RealUpdateProperties(); + virtual void RealUpdateList(); + + virtual void OnFrame(); + virtual void OnRender() { ; } + + virtual void OnDeviceCreate() { ; } + virtual void OnDeviceDestroy() { ; } + virtual void OnDrawUI(); +}; + diff --git a/src/editors/ShaderEditor/SHGameMtlTools.cpp b/src/editors/ShaderEditor/SHGameMtlTools.cpp new file mode 100644 index 00000000000..911d7ae6921 --- /dev/null +++ b/src/editors/ShaderEditor/SHGameMtlTools.cpp @@ -0,0 +1,245 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" + +#include "SHGameMtlTools.h" +#include "ui_shadermain.h" +#include "UI_ShaderTools.h" +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +CSHGameMtlTools::CSHGameMtlTools(const ISHInit &init) : ISHTools(init) +{ + m_CreatingMtl = FALSE; + m_Mtl = 0; + m_GameMtlPairTools = 0; +} + +CSHGameMtlTools::~CSHGameMtlTools() +{ +} +//--------------------------------------------------------------------------- + +void CSHGameMtlTools::OnActivate() +{ + // fill items + FillItemList(); + + /* Ext.m_Items->SetOnModifiedEvent (fastdelegate::bind(this,&CSHGameMtlTools::Modified));*/ + Ext.m_Items->SetOnItemCloneEvent(TOnItemClone(this, &CSHGameMtlTools::OnCloneItem)); + Ext.m_Items->SetOnItemCreaetEvent(TOnItemCreate(this, &CSHGameMtlTools::OnCreateItem)); + Ext.m_Items->SetOnItemRenameEvent(TOnItemRename(this, &CSHGameMtlTools::OnRenameItem)); + Ext.m_Items->SetOnItemRemoveEvent(TOnItemRemove(this, &CSHGameMtlTools::OnRemoveItem)); + inherited::OnActivate(); +} + +void CSHGameMtlTools::OnDeactivate() +{ + inherited::OnDeactivate(); +} + +void CSHGameMtlTools::OnFrame() +{ + inherited::OnFrame(); + if (m_CreatingMtl) + { + bool change = true; + shared_str result; + if (UIChooseForm::GetResult(change, result)) + { + if (change) + { + AppendItem(m_CreatingMtlPath.c_str(), stricmp(result.c_str(), "dynamic") == 0); + } + m_CreatingMtl = FALSE; + } + } +} +void CSHGameMtlTools::OnDrawUI() +{ + if (m_CreatingMtl) + { + UIChooseForm::Update(); + } +} +//--------------------------------------------------------------------------- + +bool CSHGameMtlTools::OnCreate() +{ + m_GameMtlPairTools = STools->FindTools(aeMtlPair); + R_ASSERT(m_GameMtlPairTools); + Load(); + return true; +} + +void CSHGameMtlTools::OnDestroy() +{ + m_bModified = FALSE; +} + +void CSHGameMtlTools::Reload() +{ + // mtl + ResetCurrentItem(); + // mtl pair + m_GameMtlPairTools->ResetCurrentItem(); + // load + Load(); + FillItemList(); +} + +void CSHGameMtlTools::FillItemList() +{ + + ListItemsVec items; + for (GameMtlIt m_it = GMLib.FirstMaterial(); m_it != GMLib.LastMaterial(); m_it++) + LHelper().CreateItem(items, *(*m_it)->m_Name, 0); + // assign items + Ext.m_Items->AssignItems(items, 0, false); +} + +void CSHGameMtlTools::Load() +{ + m_bLockUpdate = TRUE; + + GMLib.Unload(); + GMLib.Load(); + ResetCurrentItem(); + + m_bLockUpdate = FALSE; +} + +bool CSHGameMtlTools::Save() +{ + ResetCurrentItem(); + m_bLockUpdate = TRUE; + + // save + string_path fn; + FS.update_path(fn, _game_data_, GAMEMTL_FILENAME); + EFS.MarkFile(fn, false); + bool bRes = GMLib.Save(); + + m_bLockUpdate = FALSE; + + if (bRes) + m_bModified = FALSE; + return bRes; +} + +SGameMtl *CSHGameMtlTools::FindItem(LPCSTR name) +{ + if (name && name[0]) + { + return GMLib.GetMaterial(name); + } + else + return 0; +} + +void CSHGameMtlTools::FillChooseMtlType(ChooseItemVec &items, void *param) +{ + items.push_back(SChooseItem("Dynamic", "Dynamic material")); + items.push_back(SChooseItem("Static", "Static material")); +} + +void CSHGameMtlTools::AppendItem(LPCSTR path, LPCSTR parent_name) +{ + SGameMtl *parent = FindItem(parent_name); + if (!parent) + { + UIChooseForm::SelectItem(smCustom, 1, 0, TOnChooseFillItems(this, &CSHGameMtlTools::FillChooseMtlType), 0, 0, 0, 0); + m_CreatingMtl = TRUE; + m_CreatingMtlPath = path; + } + else + { + AppendItem(path, false, parent); + } +} + +void CSHGameMtlTools::AppendItem(LPCSTR path, bool dynamic, SGameMtl *parent) +{ + SGameMtl *S = GMLib.AppendMaterial(parent); + m_LastSelection = path; + S->m_Name = m_LastSelection.c_str(); + if (!parent) + S->Flags.set(SGameMtl::flDynamic, dynamic); + ExecCommand(COMMAND_UPDATE_LIST); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + Modified(); +} + +void CSHGameMtlTools::OnRenameItem(LPCSTR old_full_name, LPCSTR new_full_name, EItemType type) +{ + if (type == TYPE_OBJECT) + { + SGameMtl *S = FindItem(old_full_name); + R_ASSERT(S); + S->m_Name = new_full_name; + if (S == m_Mtl) + { + ExecCommand(COMMAND_UPDATE_PROPERTIES); + ExecCommand(COMMAND_UPDATE_LIST); + m_LastSelection = m_Mtl->m_Name.c_str(); + + m_Mtl = 0; + } + } +} + +void CSHGameMtlTools::OnRemoveItem(LPCSTR name, EItemType type) +{ + if (type == TYPE_OBJECT) + { + R_ASSERT(name && name[0]); + if (m_Mtl && m_Mtl->m_Name == name) + { + m_Mtl = 0; + Tools->UpdateProperties(true); + } + GMLib.RemoveMaterial(name); + } +} + +void CSHGameMtlTools::SetCurrentItem(LPCSTR name, bool bView) +{ + if (m_bLockUpdate) + return; + + SGameMtl *S = FindItem(name); + // load material + if (m_Mtl != S) + { + m_Mtl = S; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + if (bView) + ViewSetCurrentItem(name); + } +} + +void CSHGameMtlTools::ResetCurrentItem() +{ + m_Mtl = 0; +} +//--------------------------------------------------------------------------- + +void CSHGameMtlTools::RealUpdateList() +{ + FillItemList(); +} +//------------------------------------------------------------------------------ + +void CSHGameMtlTools::RealUpdateProperties() +{ + PropItemVec items; + if (m_Mtl) + m_Mtl->FillProp(items, m_CurrentItem); + Ext.m_ItemProps->AssignItems(items); + Ext.m_ItemProps->SetModifiedEvent(TOnModifiedEvent(this, &CSHGameMtlTools::Modified)); +} +//--------------------------------------------------------------------------- + +void CSHGameMtlTools::ApplyChanges(bool bForced) +{ +} +//--------------------------------------------------------------------------- diff --git a/src/editors/ShaderEditor/SHGameMtlTools.h b/src/editors/ShaderEditor/SHGameMtlTools.h new file mode 100644 index 00000000000..83e066175f2 --- /dev/null +++ b/src/editors/ShaderEditor/SHGameMtlTools.h @@ -0,0 +1,56 @@ +#pragma once +#include "SHToolsInterface.h" +#include "xrEngine/GameMtlLib.h" + +// refs +class PropValue; + +class CSHGameMtlTools : public ISHTools +{ + BOOL m_CreatingMtl; + xr_string m_CreatingMtlPath; + ISHTools *m_GameMtlPairTools; + void ItemExist(LPCSTR name, bool &res) { res = !!FindItem(name); } + SGameMtl *FindItem(LPCSTR name); + +public: + SGameMtl *m_Mtl; + virtual void AppendItem(LPCSTR path, LPCSTR parent_name = 0); + virtual void AppendItem(LPCSTR path, bool dynamic = false, SGameMtl *parent = 0); + virtual void OnRemoveItem(LPCSTR name, EItemType type); + virtual void OnRenameItem(LPCSTR old_full_name, LPCSTR new_full_name, EItemType type); + void FillChooseMtlType(ChooseItemVec &items, void *param); + + virtual void FillItemList(); + +public: + CSHGameMtlTools(const ISHInit &init); + virtual ~CSHGameMtlTools(); + + virtual LPCSTR ToolsName() { return "Game Materials"; } + + virtual void Reload(); + virtual void Load(); + virtual bool Save(); + virtual void ApplyChanges(bool bForced = false); + + virtual bool OnCreate(); + virtual void OnDestroy(); + virtual void OnActivate(); + virtual void OnDeactivate(); + + // misc + virtual void ResetCurrentItem(); + virtual void SetCurrentItem(LPCSTR name, bool bView); + + virtual void RealUpdateProperties(); + virtual void RealUpdateList(); + + virtual void OnFrame(); + virtual void OnRender() { ; } + + virtual void OnDeviceCreate() { ; } + virtual void OnDeviceDestroy() { ; } + + virtual void OnDrawUI(); +}; diff --git a/src/editors/ShaderEditor/SHSoundEnvTools.cpp b/src/editors/ShaderEditor/SHSoundEnvTools.cpp new file mode 100644 index 00000000000..420445ef6ce --- /dev/null +++ b/src/editors/ShaderEditor/SHSoundEnvTools.cpp @@ -0,0 +1,370 @@ +//--------------------------------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +#include "ui_shadermain.h" +#include "../../xrSound/stdafx.h" +#include "eax/eax.h" +#include "../../xrSound/SoundRender_Source.h" +#include "../xrECore/Editor/D3DUtils.h" + +#include "SHSoundEnvTools.h" +//------------------------------------------------------------------------------ +xr_token eax_environment[] = { + {"Alley", EAX_ENVIRONMENT_ALLEY}, + {"Arena", EAX_ENVIRONMENT_ARENA}, + {"Auditorium", EAX_ENVIRONMENT_AUDITORIUM}, + {"Bathroom", EAX_ENVIRONMENT_BATHROOM}, + {"Carpeted Hallway", EAX_ENVIRONMENT_CARPETEDHALLWAY}, + {"Cave", EAX_ENVIRONMENT_CAVE}, + {"City", EAX_ENVIRONMENT_CITY}, + {"Concert Hall", EAX_ENVIRONMENT_CONCERTHALL}, + {"Dizzy", EAX_ENVIRONMENT_DIZZY}, + {"Drugged", EAX_ENVIRONMENT_DRUGGED}, + {"Forest", EAX_ENVIRONMENT_FOREST}, + {"Generic", EAX_ENVIRONMENT_GENERIC}, + {"Hallway", EAX_ENVIRONMENT_HALLWAY}, + {"Hangar", EAX_ENVIRONMENT_HANGAR}, + {"Livingroom", EAX_ENVIRONMENT_LIVINGROOM}, + {"Mountains", EAX_ENVIRONMENT_MOUNTAINS}, + {"Padded Cell", EAX_ENVIRONMENT_PADDEDCELL}, + {"Parkinglot", EAX_ENVIRONMENT_PARKINGLOT}, + {"Plain", EAX_ENVIRONMENT_PLAIN}, + {"Psychotic", EAX_ENVIRONMENT_PSYCHOTIC}, + {"Quarry", EAX_ENVIRONMENT_QUARRY}, + {"Room", EAX_ENVIRONMENT_ROOM}, + {"Sewer Pipe", EAX_ENVIRONMENT_SEWERPIPE}, + {"Stone Corridor", EAX_ENVIRONMENT_STONECORRIDOR}, + {"Stone Room", EAX_ENVIRONMENT_STONEROOM}, + {"Under Water", EAX_ENVIRONMENT_UNDERWATER}, + {0, 0}}; +//------------------------------------------------------------------------------ +CSHSoundEnvTools::CSHSoundEnvTools(const ISHInit &init) : ISHTools(init) +{ + m_Env = 0; + m_SoundName = "alexmx\\beep"; + OnChangeWAV(0); +} + +CSHSoundEnvTools::~CSHSoundEnvTools() +{ +} +//--------------------------------------------------------------------------- + +void CSHSoundEnvTools::OnChangeWAV(PropValue *prop) +{ + + BOOL bPlay = !!m_PreviewSnd._feedback(); + m_PreviewSnd.destroy(); + if (m_SoundName.size()) + { + m_PreviewSnd.create(*m_SoundName, st_Effect, sg_Undefined); + CSoundRender_Source *src = (CSoundRender_Source *)m_PreviewSnd._handle(); + m_Params.min_distance = src->m_fMinDist; + m_Params.max_distance = src->m_fMaxDist; + } + if (bPlay) + m_PreviewSnd.play(0, sm_Looped); +} + +void CSHSoundEnvTools::OnControlClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + + switch (V->btn_num) + { + case 0: + m_PreviewSnd.play(0, sm_Looped); + break; + case 1: + m_PreviewSnd.stop(); + break; + } + + bModif = false; +} + +void CSHSoundEnvTools::OnActivate() +{ + if (!psSoundFlags.is(ss_Hardware | ss_EFX)) + { + Log("#!HARDWARE or FX flags are not set. Preview is disabled."); + } + else + { + m_PreviewSnd.play(0, sm_Looped); + PropItemVec items; + + PropValue *V; + V = PHelper().CreateChoose(items, "Source\\WAVE name", &m_SoundName, smSoundSource); + V->OnChangeEvent.bind(this, &CSHSoundEnvTools::OnChangeWAV); + ButtonValue *B = PHelper().CreateButton(items, "Source\\Controls", "Play,Stop", 0); + B->OnBtnClickEvent.bind(this, &CSHSoundEnvTools::OnControlClick); + + Ext.m_PreviewProps->AssignItems(items); + // Ext.m_PreviewProps->ShowProperties(); + } + // fill items + FillItemList(); + // Ext.m_Items->SetOnModifiedEvent (fastdelegate::bind(this,&CSHSoundEnvTools::Modified)); + Ext.m_Items->SetOnItemCloneEvent(TOnItemClone(this, &CSHSoundEnvTools::OnCloneItem)); + Ext.m_Items->SetOnItemCreaetEvent(TOnItemCreate(this, &CSHSoundEnvTools::OnCreateItem)); + + Ext.m_Items->SetOnItemRenameEvent(TOnItemRename(this, &CSHSoundEnvTools::OnRenameItem)); + Ext.m_Items->SetOnItemRemoveEvent(TOnItemRemove(this, &CSHSoundEnvTools::OnRemoveItem)); + inherited::OnActivate(); +} +//--------------------------------------------------------------------------- + +void CSHSoundEnvTools::OnDeactivate() +{ + m_PreviewSnd.stop(); + inherited::OnDeactivate(); +} +//--------------------------------------------------------------------------- + +void CSHSoundEnvTools::OnFrame() +{ + inherited::OnFrame(); +} +//--------------------------------------------------------------------------- + +#define SOUND_SEL0_COLOR 0x00A0A0F0 +#define SOUND_SEL1_COLOR 0x00FFFFFF + +void CSHSoundEnvTools::OnRender() +{ + if (m_PreviewSnd._handle()) + { + RCache.set_xform_world(Fidentity); + EDevice.SetShader(EDevice.m_WireShader); + u32 clr0 = SOUND_SEL0_COLOR; + u32 clr1 = SOUND_SEL1_COLOR; + DU_impl.DrawLineSphere(Fvector().set(0, 0, 0), m_Params.max_distance, clr1, true); + DU_impl.DrawLineSphere(Fvector().set(0, 0, 0), m_Params.min_distance, clr0, false); + } +} +//--------------------------------------------------------------------------- + +bool CSHSoundEnvTools::OnCreate() +{ + Load(); + return true; +} + +void CSHSoundEnvTools::OnDestroy() +{ + m_Library.Unload(); + m_bModified = FALSE; +} +//--------------------------------------------------------------------------- + +void CSHSoundEnvTools::ApplyChanges(bool bForced) +{ + UseEnvironment(); +} + +void CSHSoundEnvTools::Reload() +{ + ResetCurrentItem(); + Load(); + FillItemList(); +} + +void CSHSoundEnvTools::FillItemList() +{ + // store folders + // fill items + ListItemsVec items; + SoundEnvironment_LIB::SE_VEC &lst = m_Library.Library(); + for (auto it = lst.begin(); it != lst.end(); it++) + LHelper().CreateItem(items, (*it)->name.c_str(), 0); + // assign items + Ext.m_Items->AssignItems(items, 0, false); +} + +void CSHSoundEnvTools::Load() +{ + string_path fn; + FS.update_path(fn, _game_data_, SNDENV_FILENAME); + + m_bLockUpdate = TRUE; + + if (FS.exist(fn)) + { + m_Library.Unload(); + m_Library.Load(fn); + } + else + { + ELog.DlgMsg(mtInformation, "Can't find file '%s'", fn); + } + + m_bLockUpdate = FALSE; +} + +bool CSHSoundEnvTools::Save() +{ + ApplyChanges(); + m_bLockUpdate = TRUE; + + // save + string_path fn; + FS.update_path(fn, _game_data_, SNDENV_FILENAME); + + // save new file + EFS.MarkFile(fn, false); + bool bRes = m_Library.Save(fn); + m_bLockUpdate = FALSE; + + if (bRes) + m_bModified = FALSE; + return bRes; +} + +CSoundRender_Environment *CSHSoundEnvTools::FindItem(LPCSTR name) +{ + if (name && name[0]) + { + return m_Library.Get(name); + } + else + return 0; +} + +void CSHSoundEnvTools::AppendItem(LPCSTR folder_name, LPCSTR parent_name) +{ + CSoundRender_Environment *parent = FindItem(parent_name); + m_LastSelection = folder_name; + CSoundRender_Environment *S = m_Library.Append(parent); + if (!parent) + S->set_default(); + S->name = m_LastSelection.c_str(); + ExecCommand(COMMAND_UPDATE_LIST); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + Modified(); +} + +void CSHSoundEnvTools::OnRenameItem(LPCSTR old_full_name, LPCSTR new_full_name, EItemType type) +{ + if (type == TYPE_OBJECT) + { + ApplyChanges(); + CSoundRender_Environment *S = m_Library.Get(old_full_name); + R_ASSERT(S); + S->name = new_full_name; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + ExecCommand(COMMAND_UPDATE_LIST); + } +} + +void CSHSoundEnvTools::OnRemoveItem(LPCSTR name, EItemType type) +{ + if (type == TYPE_OBJECT) + { + R_ASSERT(name && name[0]); + if (m_Env && m_Env->name == name) + { + m_Env = 0; + Tools->UpdateProperties(true); + } + m_Library.Remove(name); + } +} + +void CSHSoundEnvTools::SetCurrentItem(LPCSTR name, bool bView) +{ + if (m_bLockUpdate) + return; + CSoundRender_Environment *S = FindItem(name); + if (m_Env != S) + { + m_Env = S; + if (m_Env) + m_EnvSrc = *m_Env; + ExecCommand(COMMAND_UPDATE_PROPERTIES); + if (bView) + ViewSetCurrentItem(name); + } + UseEnvironment(); +} + +void CSHSoundEnvTools::ResetCurrentItem() +{ + m_Env = 0; + UseEnvironment(); +} + +void CSHSoundEnvTools::OnRevResetClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + switch (V->btn_num) + { + case 0: + m_Env->set_identity(); + break; + case 1: + OnEnvChange(V); + break; + } + Modified(); +} + +void CSHSoundEnvTools::OnEnvSizeChange(PropValue *sender) +{ + CSoundRender_Environment test_env = *m_Env; + test_env.EnvironmentSize = m_EnvSrc.EnvironmentSize; + test_env.DecayTime = m_EnvSrc.DecayTime; + test_env.Reflections = m_EnvSrc.Reflections; + test_env.ReflectionsDelay = m_EnvSrc.ReflectionsDelay; + test_env.Reverb = m_EnvSrc.Reverb; + test_env.ReverbDelay = m_EnvSrc.ReverbDelay; + CSound_environment *E = m_Env; + GEnv.Sound->set_environment_size(&test_env, &E); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CSHSoundEnvTools::OnEnvChange(PropValue *sender) +{ + CSound_environment *E = m_Env; + GEnv.Sound->set_environment(m_Env->Environment, &E); + m_EnvSrc = *m_Env; + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void CSHSoundEnvTools::RealUpdateList() +{ + FillItemList(); +} +//------------------------------------------------------------------------------ + +void CSHSoundEnvTools::RealUpdateProperties() +{ + PropItemVec items; + if (m_Env) + { + // fill environment + CSoundRender_Environment &S = *m_Env; + ButtonValue *B = 0; + B = PHelper().CreateButton(items, "Environment\\Set", "Identity,Reset", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &CSHSoundEnvTools::OnRevResetClick); + PropValue *V = 0; + V = PHelper().CreateToken32(items, "Environment\\Preset", &S.Environment, eax_environment); + V->OnChangeEvent.bind(this, &CSHSoundEnvTools::OnEnvChange); + V = PHelper().CreateFloat(items, "Environment\\Size", &S.EnvironmentSize, EAXLISTENER_MINENVIRONMENTSIZE, EAXLISTENER_MAXENVIRONMENTSIZE, 0.01f, 3); + V->OnChangeEvent.bind(this, &CSHSoundEnvTools::OnEnvSizeChange); + PHelper().CreateFloat(items, "Environment\\Diffusion", &S.EnvironmentDiffusion, EAXLISTENER_MINENVIRONMENTDIFFUSION, EAXLISTENER_MAXENVIRONMENTDIFFUSION, 0.01f, 3); + PHelper().CreateFloat(items, "Room\\Room", &S.Room, (float)EAXLISTENER_MINROOM, (float)EAXLISTENER_MAXROOM, 1.f, 0); + PHelper().CreateFloat(items, "Room\\RoomHF", &S.RoomHF, (float)EAXLISTENER_MINROOMHF, (float)EAXLISTENER_MAXROOMHF, 1.f, 0); + PHelper().CreateFloat(items, "Distance Effects\\RoomRolloffFactor", &S.RoomRolloffFactor, EAXLISTENER_MINROOMROLLOFFFACTOR, EAXLISTENER_MAXROOMROLLOFFFACTOR, 0.01f, 3); + PHelper().CreateFloat(items, "Distance Effects\\AirAbsorptionHF", &S.AirAbsorptionHF, EAXLISTENER_MINAIRABSORPTIONHF, EAXLISTENER_MAXAIRABSORPTIONHF, 0.01f, 3); + PHelper().CreateFloat(items, "Reflections\\Reflections", &S.Reflections, (float)EAXLISTENER_MINREFLECTIONS, (float)EAXLISTENER_MAXREFLECTIONS, 1.f, 0); + PHelper().CreateFloat(items, "Reflections\\ReflectionsDelay", &S.ReflectionsDelay, EAXLISTENER_MINREFLECTIONSDELAY, EAXLISTENER_MAXREFLECTIONSDELAY, 0.01f, 3); + PHelper().CreateFloat(items, "Reverb\\Reverb", &S.Reverb, (float)EAXLISTENER_MINREVERB, (float)EAXLISTENER_MAXREVERB, 1.f, 0); + PHelper().CreateFloat(items, "Reverb\\ReverbDelay", &S.ReverbDelay, EAXLISTENER_MINREVERBDELAY, EAXLISTENER_MAXREVERBDELAY, 0.01f, 3); + PHelper().CreateFloat(items, "Decay\\DecayTime", &S.DecayTime, EAXLISTENER_MINDECAYTIME, EAXLISTENER_MAXDECAYTIME, 0.01f, 3); + PHelper().CreateFloat(items, "Decay\\DecayHFRatio", &S.DecayHFRatio, EAXLISTENER_MINDECAYHFRATIO, EAXLISTENER_MAXDECAYHFRATIO, 0.01f, 3); + } + Ext.m_ItemProps->AssignItems(items); + Ext.m_ItemProps->SetModifiedEvent(TOnModifiedEvent(this, &CSHSoundEnvTools::Modified)); +} +//--------------------------------------------------------------------------- diff --git a/src/editors/ShaderEditor/SHSoundEnvTools.h b/src/editors/ShaderEditor/SHSoundEnvTools.h new file mode 100644 index 00000000000..4c6c313935e --- /dev/null +++ b/src/editors/ShaderEditor/SHSoundEnvTools.h @@ -0,0 +1,69 @@ +//--------------------------------------------------------------------------- +#ifndef SHSoundEnvToolsH +#define SHSoundEnvToolsH +#include "SHToolsInterface.h" +#include "../../xrSound/soundrender_environment.h" + +// refs +class PropValue; + +class CSHSoundEnvTools : public ISHTools +{ + void ItemExist(LPCSTR name, bool &res) { res = !!FindItem(name); } + CSoundRender_Environment *FindItem(LPCSTR name); + void SetCurrentEnv(CSoundRender_Environment *B); + + SoundEnvironment_LIB m_Library; + + shared_str m_SoundName; + CSound_params m_Params; + ref_sound m_PreviewSnd; + void OnControlClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnChangeWAV(PropValue *prop); + + void OnRevResetClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnEnvSizeChange(PropValue *sender); + void OnEnvChange(PropValue *sender); + +public: + CSoundRender_Environment m_EnvSrc; + CSoundRender_Environment *m_Env; + virtual void AppendItem(LPCSTR folder_name, LPCSTR parent = 0); + virtual void OnRemoveItem(LPCSTR name, EItemType type); + virtual void OnRenameItem(LPCSTR old_full_name, LPCSTR new_full_name, EItemType type); + virtual void FillItemList(); + + void UseEnvironment() { GEnv.Sound->set_user_env(m_Env); } + +public: + CSHSoundEnvTools(const ISHInit &init); + virtual ~CSHSoundEnvTools(); + + virtual LPCSTR ToolsName() { return "Sound Environment"; } + + virtual void Reload(); + virtual void Load(); + virtual bool Save(); + + virtual bool OnCreate(); + virtual void OnDestroy(); + virtual void OnActivate(); + virtual void OnDeactivate(); + + // misc + virtual void ResetCurrentItem(); + virtual void SetCurrentItem(LPCSTR name, bool bView); + virtual void ApplyChanges(bool bForced = false); + + virtual void RealUpdateProperties(); + virtual void RealUpdateList(); + + virtual void OnFrame(); + virtual void OnRender(); + + virtual void OnDeviceCreate() { ; } + virtual void OnDeviceDestroy() { ; } +}; +//--------------------------------------------------------------------------- + +#endif diff --git a/src/editors/ShaderEditor/SHToolsInterface.cpp b/src/editors/ShaderEditor/SHToolsInterface.cpp new file mode 100644 index 00000000000..0094455b4ea --- /dev/null +++ b/src/editors/ShaderEditor/SHToolsInterface.cpp @@ -0,0 +1,128 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "SHToolsInterface.h" +#include "../xrECore/Editor/ui_main.h" + +ISHTools::ISHTools(const ISHInit &init) +{ + m_bModified = FALSE; + m_bLockUpdate = FALSE; + Ext = init; +} +//--------------------------------------------------------------------------- + +void ISHTools::ViewSetCurrentItem(LPCSTR full_name) +{ + if (m_bLockUpdate) + return; + + m_bLockUpdate = TRUE; + Ext.m_Items->SelectItem(full_name); + m_bLockUpdate = FALSE; +} +//--------------------------------------------------------------------------- + +void ISHTools::Modified() +{ + m_bModified = TRUE; + + ExecCommand(COMMAND_UPDATE_CAPTION); + ApplyChanges(); +} +//--------------------------------------------------------------------------- + +bool ISHTools::IfModified() +{ + if (m_bModified) + { + int mr = ELog.DlgMsg(mtConfirmation, "The '%s' has been modified.\nDo you want to save your changes?", ToolsName()); + switch (mr) + { + case mrYes: + Save(); + m_bModified = FALSE; + break; + case mrNo: + m_bModified = FALSE; + break; + case mrCancel: + return false; + } + } + return true; +} +//--------------------------------------------------------------------------- + +void ISHTools::ZoomObject(bool bOnlySel) +{ + Fbox BB; + BB.set(-5, -5, -5, 5, 5, 5); + EDevice.m_Camera.ZoomExtents(BB); +} +//--------------------------------------------------------------------------- + +xr_string ISHTools::ViewGetCurrentItem(bool bFolderOnly) +{ + xr_string name; + RStringVec lst; + Ext.m_Items->GetSelected(lst); + if (lst.size() == 1) + { + name = lst[0].c_str(); + } + return name; +} +//--------------------------------------------------------------------------- +/* +TElTreeItem* ISHTools::ViewGetCurrentItem() +{ + return Ext.m_Items->GetSelected(); +}*/ +//--------------------------------------------------------------------------- + +void ISHTools::RemoveCurrent() +{ + R_ASSERT(0); + // Ext.m_Items->RemoveSelItems(); +} +//--------------------------------------------------------------------------- + +void ISHTools::RenameCurrent() +{ + R_ASSERT(0); + // Ext.m_Items->RenameSelItem(); +} +//--------------------------------------------------------------------------- + +void ISHTools::OnFrame() +{ + if (m_LastSelection.size()) + { + SetCurrentItem(m_LastSelection.c_str(), true); + m_LastSelection = ""; + } +} +void ISHTools::OnActivate() +{ + SetCurrentItem(m_LastSelection.c_str(), true); + UI->RedrawScene(); +} +void ISHTools::OnDeactivate() +{ + Ext.m_PreviewProps->ClearProperties(); + m_LastSelection = ViewGetCurrentItem(false); + ResetCurrentItem(); + Ext.m_Items->ClearList(); +} +//--------------------------------------------------------------------------- +void ISHTools::OnCloneItem(LPCSTR parent_path, LPCSTR new_full_name) +{ + AppendItem(new_full_name, parent_path); +} + +void ISHTools::OnCreateItem(LPCSTR path) +{ + AppendItem(path); +} \ No newline at end of file diff --git a/src/editors/ShaderEditor/SHToolsInterface.h b/src/editors/ShaderEditor/SHToolsInterface.h new file mode 100644 index 00000000000..9100081c99b --- /dev/null +++ b/src/editors/ShaderEditor/SHToolsInterface.h @@ -0,0 +1,102 @@ +//--------------------------------------------------------------------------- +#ifndef SHToolsInterfaceH +#define SHToolsInterfaceH + +// refs + +enum EToolsID +{ + aeFirstTool = 0, + aeEngine = 0, + aeCompiler, + aeMtl, + aeMtlPair, + aeSoundEnv, + aeMaxTools +}; + +struct ISHInit +{ + EToolsID tools_id; + UIItemListForm *m_Items; + UIPropertiesForm *m_ItemProps; + UIPropertiesForm *m_PreviewProps; + ISHInit() { ZeroMemory(this, sizeof(ISHInit)); } + ISHInit(EToolsID id, UIItemListForm *il, UIPropertiesForm *ip, UIPropertiesForm *pp) + { + tools_id = id; + m_Items = il; + m_ItemProps = ip; + m_PreviewProps = pp; + } +}; +class ISHTools +{ +protected: + typedef ISHTools inherited; + + ISHInit Ext; + + BOOL m_bModified; + + BOOL m_bLockUpdate; // ���� ������� ������ ��������������� Update____From___() + + xr_string m_LastSelection; + +public: + ListItem *m_CurrentItem; + +public: + void ViewSetCurrentItem(LPCSTR full_name); + xr_string ViewGetCurrentItem(bool bFolderOnly); + // UIItemListForm::Node ViewGetCurrentItem(); +public: + virtual void AppendItem(LPCSTR folder_name, LPCSTR parent = 0) = 0; + virtual void FillItemList() = 0; + +public: + ISHTools(const ISHInit &init); + virtual ~ISHTools() { ; } + + EToolsID ID() { return Ext.tools_id; } + xr_string SelectedName(); + void RemoveCurrent(); + void RenameCurrent(); + + virtual LPCSTR ToolsName() = 0; + + virtual void Reload() = 0; + virtual void Load() = 0; + virtual bool Save() = 0; + + bool IsModified() { return m_bModified; } + virtual bool IfModified(); + virtual void Modified(); + + virtual bool OnCreate() = 0; + virtual void OnDestroy() = 0; + virtual void OnActivate() = 0; + virtual void OnDeactivate() = 0; + + // misc + virtual void ResetCurrentItem() = 0; + virtual void SetCurrentItem(LPCSTR name, bool bView) = 0; + virtual void ApplyChanges(bool bForced = false) = 0; + + virtual void RealUpdateProperties() = 0; + virtual void RealUpdateList() = 0; + + virtual void OnFrame() = 0; + virtual void OnRender() = 0; + + virtual void OnDeviceCreate() = 0; + virtual void OnDeviceDestroy() = 0; + + virtual void ZoomObject(bool bOnlySel); + virtual void OnShowHint(AStringVec &ss) { ; } + virtual void OnDrawUI() {} + virtual void OnCloneItem(LPCSTR parent_path, LPCSTR new_full_name); + virtual void OnCreateItem(LPCSTR path); +}; +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/ShaderEditor/ShaderEditor.cpp b/src/editors/ShaderEditor/ShaderEditor.cpp new file mode 100644 index 00000000000..c11c728bf1d --- /dev/null +++ b/src/editors/ShaderEditor/ShaderEditor.cpp @@ -0,0 +1,29 @@ +// ShaderEditor.cpp : Определяет точку входа для приложения. + +#include "stdafx.h" + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow) +{ + if (!IsDebuggerPresent()) + xrDebug::Initialize(pCmdLine); + + GEnv.Render = &RImplementation; + Core.Initialize("shader", pCmdLine, LogCallback(ELogCallback, nullptr), true, "fs.ltx", false, true); + STools = xr_new(); + Tools = STools; + + UI = xr_new(); + UI->RegisterCommands(); + + UIMainForm *MainForm = xr_new(); + ::MainForm = MainForm; + UI->Push(MainForm, false); + + while (MainForm->Frame()) + { + } + + xr_delete(MainForm); + Core._destroy(); + return EXIT_SUCCESS; +} diff --git a/src/editors/ShaderEditor/ShaderEditor.vcxproj b/src/editors/ShaderEditor/ShaderEditor.vcxproj new file mode 100644 index 00000000000..e3dec197fbb --- /dev/null +++ b/src/editors/ShaderEditor/ShaderEditor.vcxproj @@ -0,0 +1,108 @@ + + + + + + + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A} + ShaderEditor + + + + + + + Application + + + + + + + + + + + + + + + + + + _EDITOR;_WINDOWS;%(PreprocessorDefinitions) + $(xrExternals)libtheora\include;$(xrExternals)libogg\include;$(xrExternals)libvorbis\include;%(AdditionalIncludeDirectories) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {1daec516-e52c-4a3c-a4da-ae3553e6e0f8} + + + {7885cf3c-ee04-4c67-9467-1fbf9a36b037} + + + {a0f7d1fb-59a7-4717-a7e4-96f37e91998e} + + + {ccca7859-eb86-493e-9b53-c4235f45b3c5} + + + {9187be98-531a-4276-b78e-dba3c8ab8447} + + + {6d47afc7-0557-4bbf-8902-b248f3621419} + + + {7e28883c-db86-4ee8-813a-991ba20c68c9} + + + + + + + + + + + + + + + + diff --git a/src/editors/ShaderEditor/ShaderEditor.vcxproj.filters b/src/editors/ShaderEditor/ShaderEditor.vcxproj.filters new file mode 100644 index 00000000000..d092b65025a --- /dev/null +++ b/src/editors/ShaderEditor/ShaderEditor.vcxproj.filters @@ -0,0 +1,130 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы ресурсов + + + + + Файлы ресурсов + + + Файлы ресурсов + + + + + Файлы ресурсов + + + + + + \ No newline at end of file diff --git a/src/editors/ShaderEditor/UILeftBarForm.cpp b/src/editors/ShaderEditor/UILeftBarForm.cpp new file mode 100644 index 00000000000..57008fadcc1 --- /dev/null +++ b/src/editors/ShaderEditor/UILeftBarForm.cpp @@ -0,0 +1,63 @@ +#include "stdafx.h" + +UILeftBarForm::UILeftBarForm() +{ +} + +UILeftBarForm::~UILeftBarForm() +{ +} + +void UILeftBarForm::Draw() +{ + ImGui::Begin("LeftBar", 0); + + if (ImGui::BeginTabBar("##tabs", ImGuiTabBarFlags_TabListPopupButton | ImGuiTabBarFlags_FittingPolicyScroll)) + { + for (auto &tool : STools->m_Tools) + { + const char *name = tool.second->ToolsName(); + if (ImGui::BeginTabItem(name)) + { + + if (STools->m_Current != tool.second) + { + STools->OnChangeEditor(tool.second); + } + ImGui::BeginChild("main", ImVec2(0, 0), false, 0); + + if (!STools->m_PreviewProps->Empty()) + { + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Preview")) + { + STools->m_PreviewProps->Draw(); + ImGui::TreePop(); + } + } + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Items")) + { + ImGui::BeginGroup(); + STools->m_Items->Draw(); + ImGui::EndGroup(); + ImGui::TreePop(); + } + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Item Properties")) + { + ImGui::BeginGroup(); + STools->m_ItemProps->Draw(); + ImGui::EndGroup(); + ImGui::TreePop(); + } + ImGui::EndChild(); + ImGui::EndTabItem(); + } + } + + ImGui::EndTabBar(); + } + + ImGui::End(); +} diff --git a/src/editors/ShaderEditor/UILeftBarForm.h b/src/editors/ShaderEditor/UILeftBarForm.h new file mode 100644 index 00000000000..359df04371b --- /dev/null +++ b/src/editors/ShaderEditor/UILeftBarForm.h @@ -0,0 +1,10 @@ +#pragma once +class UILeftBarForm : public xrUI +{ +public: + UILeftBarForm(); + virtual ~UILeftBarForm(); + virtual void Draw(); + +private: +}; diff --git a/src/editors/ShaderEditor/UIMainForm.cpp b/src/editors/ShaderEditor/UIMainForm.cpp new file mode 100644 index 00000000000..7563edf3a58 --- /dev/null +++ b/src/editors/ShaderEditor/UIMainForm.cpp @@ -0,0 +1,48 @@ +#include "stdafx.h" +#include "../xrECore/Editor/EditorChooseEvents.h" + +void resptrcode_texture::create(LPCSTR _name) { _set(RImplementation.Resources->_CreateTexture(_name)); } + +UIMainForm *MainForm = nullptr; + +UIMainForm::UIMainForm() +{ + EnableReceiveCommands(); + if (!ExecCommand(COMMAND_INITIALIZE, (u32)0, (u32)0)) + { + FlushLog(); + exit(-1); + } + ExecCommand(COMMAND_UPDATE_GRID); + ExecCommand(COMMAND_RENDER_FOCUS); + FillChooseEvents(); + m_TopBar = xr_new(); + m_Render = xr_new(); + m_MainMenu = xr_new(); + m_LeftBar = xr_new(); +} + +UIMainForm::~UIMainForm() +{ + ClearChooseEvents(); + xr_delete(m_LeftBar); + xr_delete(m_MainMenu); + xr_delete(m_Render); + xr_delete(m_TopBar); + ExecCommand(COMMAND_DESTROY, (u32)0, (u32)0); +} + +void UIMainForm::Draw() +{ + m_MainMenu->Draw(); + m_TopBar->Draw(); + m_LeftBar->Draw(); + m_Render->Draw(); +} + +bool UIMainForm::Frame() +{ + if (UI) + return UI->Idle(); + return false; +} diff --git a/src/editors/ShaderEditor/UIMainForm.h b/src/editors/ShaderEditor/UIMainForm.h new file mode 100644 index 00000000000..cf2561dbdb3 --- /dev/null +++ b/src/editors/ShaderEditor/UIMainForm.h @@ -0,0 +1,18 @@ +#pragma once +class UIMainForm : public xrUI +{ +public: + UIMainForm(); + virtual ~UIMainForm(); + virtual void Draw(); + bool Frame(); + IC UILeftBarForm *GetLeftBarForm() { return m_LeftBar; } + IC UITopBarForm *GetTopBarForm() { return m_TopBar; } + +private: + UITopBarForm *m_TopBar; + UIRenderForm *m_Render; + UIMainMenuForm *m_MainMenu; + UILeftBarForm *m_LeftBar; +}; +extern UIMainForm *MainForm; diff --git a/src/editors/ShaderEditor/UIMainMenuForm.cpp b/src/editors/ShaderEditor/UIMainMenuForm.cpp new file mode 100644 index 00000000000..6fe8988e6e5 --- /dev/null +++ b/src/editors/ShaderEditor/UIMainMenuForm.cpp @@ -0,0 +1,253 @@ +#include "stdafx.h" + +UIMainMenuForm::UIMainMenuForm() +{ +} + +UIMainMenuForm::~UIMainMenuForm() +{ +} + +void UIMainMenuForm::Draw() +{ + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Save")) + { + ExecCommand(COMMAND_SAVE); + } + if (ImGui::MenuItem("Reload")) + { + ExecCommand(COMMAND_LOAD); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Editors")) + { + if (ImGui::BeginMenu("Image")) + { + if (ImGui::MenuItem("Image Editor", "")) + { + ExecCommand(COMMAND_IMAGE_EDITOR); + } + ImGui::Separator(); + if (ImGui::MenuItem("Synchronize Textures", "")) + { + ExecCommand(COMMAND_REFRESH_TEXTURES); + } + if (ImGui::MenuItem("Check New Textures", "")) + { + ExecCommand(COMMAND_CHECK_TEXTURES); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Sounds")) + { + if (ImGui::MenuItem("Sound Editor", "")) + { + ExecCommand(COMMAND_SOUND_EDITOR); + } + ImGui::Separator(); + if (ImGui::MenuItem("Synchronize Sounds", "")) + { + ExecCommand(COMMAND_SYNC_SOUNDS); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Light Anim Editor", "")) + { + ExecCommand(COMMAND_LIGHTANIM_EDITOR); + } + if (ImGui::MenuItem("Minimap Editor", "")) + { + ExecCommand(COMMAND_MINIMAP_EDITOR); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Options")) + { + if (ImGui::BeginMenu("Render")) + { + if (ImGui::BeginMenu("Quality")) + { + static bool selected[4] = {false, false, true, false}; + if (ImGui::MenuItem("25%", "", &selected[0])) + { + selected[1] = selected[2] = selected[3] = false; + UI->SetRenderQuality(1 / 4.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("50%", "", &selected[1])) + { + selected[0] = selected[2] = selected[3] = false; + UI->SetRenderQuality(1 / 2.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("100%", "", &selected[2])) + { + selected[1] = selected[0] = selected[3] = false; + UI->SetRenderQuality(1.f); + UI->RedrawScene(); + } + if (ImGui::MenuItem("200%", "", &selected[3])) + { + selected[1] = selected[2] = selected[0] = false; + UI->SetRenderQuality(2.f); + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Fill Mode")) + { + bool selected[3] = {EDevice.dwFillMode == D3DFILL_POINT, EDevice.dwFillMode == D3DFILL_WIREFRAME, EDevice.dwFillMode == D3DFILL_SOLID}; + if (ImGui::MenuItem("Point", "", &selected[0])) + { + EDevice.dwFillMode = D3DFILL_POINT; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Wireframe", "", &selected[1])) + { + EDevice.dwFillMode = D3DFILL_WIREFRAME; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Solid", "", &selected[2])) + { + EDevice.dwFillMode = D3DFILL_SOLID; + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Shader Mode")) + { + bool selected[2] = {EDevice.dwShadeMode == D3DSHADE_FLAT, EDevice.dwShadeMode == D3DSHADE_GOURAUD}; + if (ImGui::MenuItem("Flat", "", &selected[0])) + { + EDevice.dwShadeMode = D3DSHADE_FLAT; + UI->RedrawScene(); + } + if (ImGui::MenuItem("Gouraud", "", &selected[1])) + { + EDevice.dwShadeMode = D3DSHADE_GOURAUD; + UI->RedrawScene(); + } + ImGui::EndMenu(); + } + { + bool selected = psDeviceFlags.test(rsEdgedFaces); + if (ImGui::MenuItem("Edged Faces", "", &selected)) + { + psDeviceFlags.set(rsEdgedFaces, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = !HW.Caps.bForceGPU_SW; + if (ImGui::MenuItem("RenderHW", "", &selected)) + { + HW.Caps.bForceGPU_SW = !selected; + UI->Resize(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsFilterLinear); + if (ImGui::MenuItem("Filter Linear", "", &selected)) + { + psDeviceFlags.set(rsFilterLinear, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsRenderTextures); + if (ImGui::MenuItem("Textures", "", &selected)) + { + psDeviceFlags.set(rsRenderTextures, selected); + UI->RedrawScene(); + } + } + ImGui::EndMenu(); + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsDrawSafeRect); + if (ImGui::MenuItem("Draw Safe Rect", "", &selected)) + { + psDeviceFlags.set(rsDrawSafeRect, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsDrawGrid); + if (ImGui::MenuItem("Draw Grid", "", &selected)) + { + psDeviceFlags.set(rsDrawGrid, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsFog); + if (ImGui::MenuItem("Fog", "", &selected)) + { + psDeviceFlags.set(rsFog, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsLighting); + ; + if (ImGui::MenuItem("Lighting", "", &selected)) + { + psDeviceFlags.set(rsLighting, selected); + UI->RedrawScene(); + } + } + { + bool selected = psDeviceFlags.test(rsMuteSounds); + if (ImGui::MenuItem("Mute Sounds", "", &selected)) + { + psDeviceFlags.set(rsMuteSounds, selected); + } + } + { + bool selected = psDeviceFlags.test(rsRenderRealTime); + if (ImGui::MenuItem("Real Time", "", &selected)) + { + psDeviceFlags.set(rsRenderRealTime, selected); + } + } + ImGui::Separator(); + { + bool selected = psDeviceFlags.test(rsStatistic); + if (ImGui::MenuItem("Stats", "", &selected)) + { + psDeviceFlags.set(rsStatistic, selected); + UI->RedrawScene(); + } + } + ImGui::Separator(); + if (ImGui::MenuItem("Preferences", "")) + { + ExecCommand(COMMAND_EDITOR_PREF); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Windows")) + { + { + bool selected = AllowLogCommands(); + + if (ImGui::MenuItem("Log", "", &selected)) + { + ExecCommand(COMMAND_LOG_COMMANDS); + } + } + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } +} diff --git a/src/editors/ShaderEditor/UIMainMenuForm.h b/src/editors/ShaderEditor/UIMainMenuForm.h new file mode 100644 index 00000000000..a44b6606609 --- /dev/null +++ b/src/editors/ShaderEditor/UIMainMenuForm.h @@ -0,0 +1,8 @@ +#pragma once +class UIMainMenuForm : public xrUI +{ +public: + UIMainMenuForm(); + virtual ~UIMainMenuForm(); + virtual void Draw(); +}; diff --git a/src/editors/ShaderEditor/UITopBarForm.cpp b/src/editors/ShaderEditor/UITopBarForm.cpp new file mode 100644 index 00000000000..e27b96b7831 --- /dev/null +++ b/src/editors/ShaderEditor/UITopBarForm.cpp @@ -0,0 +1,312 @@ +#include "stdafx.h" + +UITopBarForm::UITopBarForm() +{ + +#define ADD_BUTTON_IMAGE_T1(Class, Name) +#define ADD_BUTTON_IMAGE_T2(Class, Name) +#define ADD_BUTTON_IMAGE_S(Name) \ + m_t##Name = EDevice.Resources->_CreateTexture("ed\\bar\\" #Name); \ + m_t##Name->Load(); \ + m_time##Name = 0; +#define ADD_BUTTON_IMAGE_D(Name) \ + m_t##Name = EDevice.Resources->_CreateTexture("ed\\bar\\" #Name); \ + m_t##Name->Load(); \ + m_b##Name = false; +#include "UITopBarForm_ButtonList.h" + RefreshBar(); +} + +UITopBarForm::~UITopBarForm() +{ +} + +void UITopBarForm::Draw() +{ + ImGuiViewport *viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + UI->GetMenuBarHeight())); + ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, UIToolBarSize)); + ImGui::SetNextWindowViewport(viewport->ID); + + ImGuiWindowFlags window_flags = 0 | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings; + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(2, 2)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(2, 2)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 2)); + ImGui::Begin("TOOLBAR", NULL, window_flags); + { +#define ADD_BUTTON_IMAGE_S(Name) \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_time##Name > EDevice.TimerAsync() ? 0.5 : 0, 0), ImVec2(m_time##Name > EDevice.TimerAsync() ? 1 : 0.5, 1), 0)) \ + { \ + m_time##Name = EDevice.TimerAsync() + 130; \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_D(Name) \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_b##Name ? 0.5 : 0, 0), ImVec2(m_b##Name ? 1 : 0.5, 1), 0)) \ + { \ + m_b##Name = !m_b##Name; \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_P(Name) \ + if (ImGui::ImageButton(m_t##Name->surface_get(), ImVec2(20, 20), ImVec2(m_b##Name ? 0.5 : 0, 0), ImVec2(m_b##Name ? 1 : 0.5, 1), 0)) \ + { \ + Click##Name(); \ + } \ + ImGui::SameLine(); +#define ADD_BUTTON_IMAGE_T1(Class, Name) \ + ImGui::PushID("" #Class); \ + ImGui::PushStyleColor(ImGuiCol_Text, (ImVec4)ImColor::HSV(0, 0, 0)); \ + if (ImGui::Button("" #Name, ImVec2(20, 20))) \ + { \ + Click##Class##Name(); \ + } \ + ImGui::SameLine(); \ + ImGui::PopStyleColor(1); \ + ImGui::PopID(); +#define ADD_BUTTON_IMAGE_T2(Class, Name) \ + ImGui::PushID("" #Class); \ + if (ImGui::Button("" #Name, ImVec2(20, 20))) \ + { \ + Click##Class##Name(); \ + } \ + ImGui::SameLine(); \ + ImGui::PopID(); +//#define ADD_BUTTON_IMAGE_T1_1(Class, Name, T) \ +// ImGui::PushStyleColor(ImGuiCol_Text, (ImVec4)ImColor::HSV(0, 0, 0)); \ +// if (ImGui::Button("" #T, ImVec2(20, 20))) \ +// { \ +// Click##Class##Name(); \ +// } \ +// ImGui::SameLine(); \ +// ImGui::PopStyleColor(1); +#include "UITopBarForm_ButtonList.h" + } + ImGui::End(); + ImGui::PopStyleVar(5); +} +void UITopBarForm::RefreshBar() +{ + { + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = false; + + switch (Tools->GetAction()) + { + case etaSelect: + m_bSelect = true; + break; + case etaAdd: + m_bAdd = true; + break; + case etaMove: + m_bMove = true; + break; + case etaRotate: + m_bRotate = true; + break; + case etaScale: + m_bScale = true; + break; + default: + THROW; + } + } + { + m_bX = false; + m_bY = false; + m_bZ = false; + m_bZX = false; + // axis + switch (Tools->GetAxis()) + { + case etAxisX: + m_bX = true; + break; + case etAxisY: + m_bY = true; + break; + case etAxisZ: + m_bZ = true; + break; + case etAxisZX: + m_bZX = true; + break; + default: + THROW; + } + } + // settings + m_bCsLocal = Tools->GetSettings(etfCSParent); + m_bNuScale = Tools->GetSettings(etfNUScale); + m_bNSnap = Tools->GetSettings(etfNormalAlign); + m_bGSnap = Tools->GetSettings(etfGSnap); + m_bOSnap = Tools->GetSettings(etfOSnap); + m_bMoveToSnap = Tools->GetSettings(etfMTSnap); + m_bVSnap = Tools->GetSettings(etfVSnap); + m_bASnap = Tools->GetSettings(etfASnap); + m_bMSnap = Tools->GetSettings(etfMSnap); +} + +void UITopBarForm::ClickUndo() +{ + ExecCommand(COMMAND_UNDO); +} + +void UITopBarForm::ClickRedo() +{ + ExecCommand(COMMAND_REDO); +} +void UITopBarForm::ClickZoom() +{ + ExecCommand(COMMAND_ZOOM_EXTENTS, FALSE); +} + +void UITopBarForm::ClickZoomSel() +{ + ExecCommand(COMMAND_ZOOM_EXTENTS, TRUE); +} +void UITopBarForm::ClickSelect() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + m_bSelect = true; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickAdd() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaAdd); + m_bSelect = false; + m_bAdd = true; + m_bMove = false; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickMove() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaMove); + m_bSelect = false; + m_bAdd = false; + m_bMove = true; + m_bRotate = false; + m_bScale = false; +} +void UITopBarForm::ClickRotate() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaRotate); + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = true; + m_bScale = false; +} +void UITopBarForm::ClickScale() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaScale); + m_bSelect = false; + m_bAdd = false; + m_bMove = false; + m_bRotate = false; + m_bScale = true; +} +void UITopBarForm::ClickX() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisX); + m_bX = true; + m_bY = false; + m_bZ = false; + m_bZX = false; +} +void UITopBarForm::ClickY() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisY); + m_bX = false; + m_bY = true; + m_bZ = false; + m_bZX = false; +} +void UITopBarForm::ClickZ() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisZ); + m_bX = false; + m_bY = false; + m_bZ = true; + m_bZX = false; +} +void UITopBarForm::ClickZX() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etAxisZX); + m_bX = false; + m_bY = false; + m_bZ = false; + m_bZX = true; +} + +void UITopBarForm::ClickCsLocal() { ExecCommand(COMMAND_SET_SETTINGS, etfCSParent, m_bCsLocal); } +void UITopBarForm::ClickNuScale() { ExecCommand(COMMAND_SET_SETTINGS, etfNUScale, m_bNuScale); } +void UITopBarForm::ClickGSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfGSnap, m_bGSnap); } +void UITopBarForm::ClickOSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfOSnap, m_bOSnap); } +void UITopBarForm::ClickMoveToSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfMTSnap, m_bMoveToSnap); } +void UITopBarForm::ClickNSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfNormalAlign, m_bNSnap); } +void UITopBarForm::ClickVSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfVSnap, m_bVSnap); } +void UITopBarForm::ClickASnap() { ExecCommand(COMMAND_SET_SETTINGS, etfASnap, m_bASnap); } +void UITopBarForm::ClickMSnap() { ExecCommand(COMMAND_SET_SETTINGS, etfMSnap, m_bMSnap); } + +void UITopBarForm::ClickCameraP() +{ + EDevice.m_Camera.SetStyle(csPlaneMove); + UI->RedrawScene(); +} +void UITopBarForm::ClickCameraA() +{ + EDevice.m_Camera.SetStyle(cs3DArcBall); + UI->RedrawScene(); +} +void UITopBarForm::ClickCameraF() +{ + EDevice.m_Camera.SetStyle(csFreeFly); + UI->RedrawScene(); +} + +void UITopBarForm::ClickViewB1() +{ + EDevice.m_Camera.ViewBack(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewB2() +{ + EDevice.m_Camera.ViewBottom(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewF() +{ + EDevice.m_Camera.ViewFront(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewL() +{ + EDevice.m_Camera.ViewLeft(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewR() +{ + EDevice.m_Camera.ViewRight(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewT() +{ + EDevice.m_Camera.ViewTop(); + UI->RedrawScene(); +} +void UITopBarForm::ClickViewX() +{ + EDevice.m_Camera.ViewReset(); + UI->RedrawScene(); +} diff --git a/src/editors/ShaderEditor/UITopBarForm.h b/src/editors/ShaderEditor/UITopBarForm.h new file mode 100644 index 00000000000..d03033bf987 --- /dev/null +++ b/src/editors/ShaderEditor/UITopBarForm.h @@ -0,0 +1,26 @@ +#pragma once +class UITopBarForm : public xrUI +{ +public: + UITopBarForm(); + virtual ~UITopBarForm(); + virtual void Draw(); + void RefreshBar(); + +private: +#define ADD_BUTTON_IMAGE_T1(Class, Name) void Click##Class##Name(); +#define ADD_BUTTON_IMAGE_T2(Class, Name) void Click##Class##Name(); +#define ADD_BUTTON_IMAGE_S(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + u32 m_time##Name; +#define ADD_BUTTON_IMAGE_D(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + bool m_b##Name; +#define ADD_BUTTON_IMAGE_P(Name) \ + void Click##Name(); \ + ref_texture m_t##Name; \ + bool m_b##Name; +#include "UITopBarForm_ButtonList.h" +}; \ No newline at end of file diff --git a/src/editors/ShaderEditor/UITopBarForm_ButtonList.h b/src/editors/ShaderEditor/UITopBarForm_ButtonList.h new file mode 100644 index 00000000000..526ba68bbf2 --- /dev/null +++ b/src/editors/ShaderEditor/UITopBarForm_ButtonList.h @@ -0,0 +1,50 @@ +#ifndef ADD_BUTTON_IMAGE_P +#define ADD_BUTTON_IMAGE_P(Name) ADD_BUTTON_IMAGE_D(Name) +#endif +#ifndef ADD_BUTTON_IMAGE_T1_1 +#define ADD_BUTTON_IMAGE_T1_1(Class, Name, T) ADD_BUTTON_IMAGE_T1(Class, Name) +#endif +ADD_BUTTON_IMAGE_S(Undo) +ADD_BUTTON_IMAGE_S(Redo) + +ADD_BUTTON_IMAGE_P(Select) +ADD_BUTTON_IMAGE_P(Add) +ADD_BUTTON_IMAGE_P(Move) +ADD_BUTTON_IMAGE_P(Rotate) +ADD_BUTTON_IMAGE_P(Scale) + +ADD_BUTTON_IMAGE_P(X) +ADD_BUTTON_IMAGE_P(Y) +ADD_BUTTON_IMAGE_P(Z) +ADD_BUTTON_IMAGE_P(ZX) + +ADD_BUTTON_IMAGE_D(CsLocal) +ADD_BUTTON_IMAGE_D(NuScale) +ADD_BUTTON_IMAGE_D(GSnap) +ADD_BUTTON_IMAGE_D(OSnap) +ADD_BUTTON_IMAGE_D(MoveToSnap) +ADD_BUTTON_IMAGE_D(NSnap) +ADD_BUTTON_IMAGE_D(VSnap) +ADD_BUTTON_IMAGE_D(ASnap) +ADD_BUTTON_IMAGE_D(MSnap) + +ADD_BUTTON_IMAGE_S(Zoom) +ADD_BUTTON_IMAGE_S(ZoomSel) + +ADD_BUTTON_IMAGE_T1(View, F) +ADD_BUTTON_IMAGE_T1_1(View, B1, B) +ADD_BUTTON_IMAGE_T1(View, L) +ADD_BUTTON_IMAGE_T1(View, R) +ADD_BUTTON_IMAGE_T1(View, T) +ADD_BUTTON_IMAGE_T1_1(View, B2, B) +ADD_BUTTON_IMAGE_T1(View, X) + +ADD_BUTTON_IMAGE_T2(Camera, P) +ADD_BUTTON_IMAGE_T2(Camera, A) +ADD_BUTTON_IMAGE_T2(Camera, F) + +#undef ADD_BUTTON_IMAGE_D +#undef ADD_BUTTON_IMAGE_S +#undef ADD_BUTTON_IMAGE_P +#undef ADD_BUTTON_IMAGE_T1 +#undef ADD_BUTTON_IMAGE_T2 diff --git a/src/editors/ShaderEditor/UI_shadertools.cpp b/src/editors/ShaderEditor/UI_shadertools.cpp new file mode 100644 index 00000000000..427951b0d49 --- /dev/null +++ b/src/editors/ShaderEditor/UI_shadertools.cpp @@ -0,0 +1,348 @@ +//--------------------------------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +#include "UI_ShaderTools.h" + +//------------------------------------------------------------------------------ +CShaderTool *STools = (CShaderTool *)Tools; +//------------------------------------------------------------------------------ + +CShaderTool::CShaderTool() +{ + m_Current = 0; + m_Items = 0; + m_ItemProps = 0; + m_PreviewProps = 0; + fFogness = 0.9f; + dwFogColor = 0xffffffff; + m_Flags.zero(); +} +//--------------------------------------------------------------------------- + +CShaderTool::~CShaderTool() +{ +} +//--------------------------------------------------------------------------- + +void CShaderTool::OnChangeEditor(ISHTools *tools) +{ + if (m_Current) + m_Current->OnDeactivate(); + m_Current = tools; + R_ASSERT(m_Current); + m_Current->OnActivate(); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + ExecCommand(COMMAND_UPDATE_CAPTION); +} +//--------------------------------------------------------------------------- + +bool CShaderTool::IfModified() +{ + for (ToolsPairIt it = m_Tools.begin(); it != m_Tools.end(); it++) + if (!it->second->IfModified()) + return false; + return true; +} + +bool CShaderTool::IsModified() +{ + for (ToolsPairIt it = m_Tools.begin(); it != m_Tools.end(); it++) + if (it->second->IsModified()) + return true; + return false; +} + +void CShaderTool::Modified() +{ + Current()->Modified(); +} +//--------------------------------------------------------------------------- + +bool CShaderTool::OnCreate() +{ + + // create props + m_Items = xr_new(); /*TItemList::CreateForm ("Items", fraLeftBar->paItemList, alClient,TItemList::ilEditMenu|TItemList::ilDragAllowed|TItemList::ilFolderStore);*/ + m_Items->SetOnItemFocusedEvent(TOnILItemFocused(this, &CShaderTool::OnItemFocused)); + m_Items->m_Flags.set(UIItemListForm::fMenuEdit, true); + m_ItemProps = xr_new(); // TProperties::CreateForm ("Item Properties", fraLeftBar->paShaderProps, alClient); + m_PreviewProps = xr_new(); // = TProperties::CreateForm ("Preview Properties", fraLeftBar->paPreviewProps, alClient); + + // create tools + RegisterTools(); + + for (ToolsPairIt it = m_Tools.begin(); it != m_Tools.end(); it++) + if (!it->second->OnCreate()) + return false; + + OnChangeEditor(m_Current); + return true; +} + +void CShaderTool::OnDestroy() +{ + // destroy props + xr_delete(m_PreviewProps); + xr_delete(m_ItemProps); + xr_delete(m_Items); + + // + for (ToolsPairIt it = m_Tools.begin(); it != m_Tools.end(); it++) + it->second->OnDestroy(); + + UnregisterTools(); +} + +#include "xrEngine/igame_persistent.h" + +void CShaderTool::RenderEnvironment() +{ + /* if (psDeviceFlags.is(rsEnvironment)){ + g_pGamePersistent->Environment().RenderSky (); + g_pGamePersistent->Environment().RenderClouds (); + } + */ +} + +void CShaderTool::Render() +{ + PrepareLighting(); + Current()->OnRender(); + // if (psDeviceFlags.is(rsEnvironment)) g_pGamePersistent->Environment().RenderLast (); + inherited::Render(); +} + +void CShaderTool::OnFrame() +{ + if (m_Flags.is(flRefreshList)) + RealUpdateList(); + if (m_Flags.is(flRefreshProps)) + RealUpdateProperties(); + Current()->OnFrame(); +} + +void CShaderTool::ZoomObject(BOOL bOnlySel) +{ + Current()->ZoomObject(bOnlySel); +} + +void CShaderTool::PrepareLighting() +{ + // add directional light + Flight L; + ZeroMemory(&L, sizeof(Flight)); + L.type = Flight::Type::Directional; + L.diffuse.set(1, 1, 1, 1); + L.direction.set(1, -1, 1); + L.direction.normalize(); + EDevice.SetLight(0, L); + EDevice.LightEnable(0, true); + + L.diffuse.set(0.3, 0.3, 0.3, 1); + L.direction.set(-1, -1, -1); + L.direction.normalize(); + EDevice.SetLight(1, L); + EDevice.LightEnable(1, true); + + L.diffuse.set(0.3, 0.3, 0.3, 1); + L.direction.set(1, -1, -1); + L.direction.normalize(); + EDevice.SetLight(2, L); + EDevice.LightEnable(2, true); + + L.diffuse.set(0.3, 0.3, 0.3, 1); + L.direction.set(-1, -1, 1); + L.direction.normalize(); + EDevice.SetLight(3, L); + EDevice.LightEnable(3, true); + + L.diffuse.set(1.0, 0.8, 0.7, 1); + L.direction.set(0, 1, 0); + L.direction.normalize(); + EDevice.SetLight(4, L); + EDevice.LightEnable(4, true); +} + +void CShaderTool::OnDeviceCreate() +{ + for (ToolsPairIt it = m_Tools.begin(); it != m_Tools.end(); it++) + if (it->second) + it->second->OnDeviceCreate(); +} + +void CShaderTool::OnDeviceDestroy() +{ + for (ToolsPairIt it = m_Tools.begin(); it != m_Tools.end(); it++) + if (it->second) + it->second->OnDeviceDestroy(); +} + +void CShaderTool::OnShowHint(AStringVec &ss) +{ + Current()->OnShowHint(ss); +} + +void CShaderTool::ApplyChanges() +{ + Current()->ApplyChanges(); +} + +void CShaderTool::ShowProperties(LPCSTR focused_item) +{ + // m_ItemProps->ShowProperties(); +} + +LPCSTR CShaderTool::CurrentToolsName() +{ + return Current() ? Current()->ToolsName() : ""; +} + +LPCSTR CShaderTool::GetInfo() +{ + return 0; +} + +ISHTools *CShaderTool::FindTools(EToolsID id) +{ + ToolsPairIt it = m_Tools.find(id); + R_ASSERT(it != m_Tools.end()); + return it->second; +} +/* +ISHTools* CShaderTool::FindTools(TElTabSheet* sheet) +{ + for (ToolsPairIt it=m_Tools.begin(); it!=m_Tools.end(); it++) + if (it->second->Sheet()==sheet) return it->second; + return 0; +}*/ + +bool CShaderTool::Load(LPCSTR name) +{ + return true; +} + +bool CShaderTool::Save(LPCSTR name, bool bInternal) +{ + bool bRes = true; + for (ToolsPairIt it = m_Tools.begin(); it != m_Tools.end(); it++) + if (!it->second->Save()) + bRes = false; + return bRes; +} + +void CShaderTool::Reload() +{ + if (!Current()->IfModified()) + return; + if (ELog.DlgMsg(mtConfirmation, "Reload current items?") == mrYes) + Current()->Reload(); +} + +#include "SHEngineTools.h" +#include "SHGameMtlTools.h" +#include "SHGameMtlPairTools.h" +#include "SHCompilerTools.h" +#include "SHSoundEnvTools.h" + +void CShaderTool::RegisterTools() +{ + for (int k = aeFirstTool; k < aeMaxTools; k++) + { + ISHTools *tools = 0; + switch (k) + { + case aeEngine: + tools = xr_new(ISHInit(EToolsID(k), m_Items, m_ItemProps, m_PreviewProps)); + break; + case aeCompiler: + tools = xr_new(ISHInit(EToolsID(k), m_Items, m_ItemProps, m_PreviewProps)); + break; + case aeMtl: + tools = xr_new(ISHInit(EToolsID(k), m_Items, m_ItemProps, m_PreviewProps)); + break; + case aeMtlPair: + tools = xr_new(ISHInit(EToolsID(k), m_Items, m_ItemProps, m_PreviewProps)); + break; + case aeSoundEnv: + tools = xr_new(ISHInit(EToolsID(k), m_Items, m_ItemProps, m_PreviewProps)); + break; + } + R_ASSERT(tools); + m_Tools.insert(std::make_pair(static_cast(k), tools)); + } + m_Current = m_Tools[aeCompiler]; +} + +void CShaderTool::UnregisterTools() +{ + for (ToolsPairIt it = m_Tools.begin(); it != m_Tools.end(); it++) + xr_delete(it->second); +} + +bool CShaderTool::RayPick(const Fvector &start, const Fvector &dir, float &dist, Fvector *pt, Fvector *n) +{ + /* + if (m_EditObject) + { + SRayPickInfo pinf; + if (m_EditObject->RayPick(dist,start,dir,Fidentity,&pinf)){ + if (pt) pt->set(pinf.pt); + if (n){ + const Fvector* PT[3]; + pinf.e_mesh->GetFacePT(pinf.inf.id, PT); + n->mknormal(*PT[0],*PT[1],*PT[2]); + } + return true; + }else return false; + }else + */ + { + Fvector np; + np.mad(start, dir, dist); + if ((start.y > 0) && (np.y < 0.f)) + { + if (pt) + pt->set(start); + if (n) + n->set(0.f, 1.f, 0.f); + return true; + } + else + return false; + } +} + +void CShaderTool::RealUpdateProperties() +{ + Current()->RealUpdateProperties(); + m_Flags.set(flRefreshProps, FALSE); +} + +void CShaderTool::RealUpdateList() +{ + Current()->RealUpdateList(); + m_Flags.set(flRefreshList, FALSE); +} + +void CShaderTool::OnItemFocused(ListItem *items) +{ + if (!items) + return; + LPCSTR name = 0; + Current()->m_CurrentItem = 0; + + Current()->m_CurrentItem = items; + name = Current()->m_CurrentItem->Key(); + Current()->SetCurrentItem(name, false); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +bool CShaderTool::GetSelectionPosition(Fmatrix &result) +{ + result = Fidentity; + return true; +} + +//------------------------------------------------------------------------------ diff --git a/src/editors/ShaderEditor/UI_shadertools.h b/src/editors/ShaderEditor/UI_shadertools.h new file mode 100644 index 00000000000..51b8f61d2f8 --- /dev/null +++ b/src/editors/ShaderEditor/UI_shadertools.h @@ -0,0 +1,121 @@ +//--------------------------------------------------------------------------- +#ifndef UI_ShaderToolsH +#define UI_ShaderToolsH + +#include "SHToolsInterface.h" +// refs +class CEditableObject; +class CLibObject; +class IBlender; + +class CShaderTool : public CToolCustom +{ + typedef CToolCustom inherited; + + void RegisterTools(); + void UnregisterTools(); + void RealUpdateProperties(); + void RealUpdateList(); + + enum + { + flRefreshProps = (1ul << 0ul), + flRefreshList = (1ul << 1ul), + }; + Flags32 m_Flags; + + void PrepareLighting(); + +public: + UIItemListForm *m_Items; + UIPropertiesForm *m_ItemProps; + UIPropertiesForm *m_PreviewProps; + + DEFINE_MAP(EToolsID, ISHTools *, ToolsMap, ToolsPairIt); + ToolsMap m_Tools; + ISHTools *m_Current; + ISHTools *Current() { return m_Current; } + + void OnItemFocused(ListItem *items); + +public: + CShaderTool(); + virtual ~CShaderTool(); + + virtual void Render(); + virtual void RenderEnvironment(); + virtual void OnFrame(); + + virtual bool OnCreate(); + virtual void OnDestroy(); + + virtual bool IfModified(); + virtual bool IsModified(); + virtual void Modified(); + + virtual LPCSTR GetInfo(); + + virtual void ZoomObject(BOOL bSelOnly); + + virtual bool Load(LPCSTR name); + virtual bool Save(LPCSTR name, bool bInternal = false); + virtual void Reload(); + + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); + + virtual void Clear() { inherited::Clear(); } + + virtual void OnShowHint(AStringVec &SS); + + virtual bool MouseStart(TShiftState Shift) + { + return inherited::MouseStart(Shift); + return false; + } + virtual bool MouseEnd(TShiftState Shift) + { + inherited::MouseEnd(Shift); + return false; + } + virtual void MouseMove(TShiftState Shift) { inherited::MouseMove(Shift); } + + virtual bool Pick(TShiftState Shift) { return false; } + virtual bool RayPick(const Fvector &start, const Fvector &dir, float &dist, Fvector *pt, Fvector *n); + + virtual void ShowProperties(LPCSTR focused_item); + virtual void UpdateProperties(BOOL bForced = false) + { + m_Flags.set(flRefreshProps, TRUE); + if (bForced) + RealUpdateProperties(); + } + virtual void RefreshProperties() { ; } + virtual void UpdateList(bool bForced = false) + { + m_Flags.set(flRefreshList, TRUE); + if (bForced) + RealUpdateList(); + } + virtual bool GetSelectionPosition(Fmatrix &result); + + LPCSTR CurrentToolsName(); + + void OnChangeEditor(ISHTools *tools); + + void ApplyChanges(); + + ISHTools *FindTools(EToolsID id); + // ISHTools* FindTools (TElTabSheet* sheet); + + // commands + CCommandVar CommandSave(CCommandVar p1, CCommandVar p2); + CCommandVar CommandSaveBackup(CCommandVar p1, CCommandVar p2); + CCommandVar CommandReload(CCommandVar p1, CCommandVar p2); + CCommandVar CommandClear(CCommandVar p1, CCommandVar p2); + + CCommandVar CommandUpdateList(CCommandVar p1, CCommandVar p2); +}; +extern CShaderTool *STools; +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/ShaderEditor/resources/ShaderEditor.rc b/src/editors/ShaderEditor/resources/ShaderEditor.rc new file mode 100644 index 00000000000..e47d8e68ea9 --- /dev/null +++ b/src/editors/ShaderEditor/resources/ShaderEditor.rc @@ -0,0 +1,71 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// () resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_RUS) +LANGUAGE LANG_RUSSIAN, SUBLANG_DEFAULT +#pragma code_page(1251) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +MAINICON ICON "se.ico" + +#endif // () resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/editors/ShaderEditor/resources/resource.h b/src/editors/ShaderEditor/resources/resource.h new file mode 100644 index 00000000000..9ad2b305313 --- /dev/null +++ b/src/editors/ShaderEditor/resources/resource.h @@ -0,0 +1,17 @@ +//{{NO_DEPENDENCIES}} +// , Microsoft Visual C++. +// ShaderEditor.rc +// +#define IDI_ICON1 101 +#define MAINICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/editors/ShaderEditor/resources/se.ico b/src/editors/ShaderEditor/resources/se.ico new file mode 100644 index 00000000000..fccf63bc335 Binary files /dev/null and b/src/editors/ShaderEditor/resources/se.ico differ diff --git a/src/editors/ShaderEditor/stdafx.cpp b/src/editors/ShaderEditor/stdafx.cpp new file mode 100644 index 00000000000..706541d62fd --- /dev/null +++ b/src/editors/ShaderEditor/stdafx.cpp @@ -0,0 +1,2 @@ +#include "stdafx.h" +#pragma hdrstop \ No newline at end of file diff --git a/src/editors/ShaderEditor/stdafx.h b/src/editors/ShaderEditor/stdafx.h new file mode 100644 index 00000000000..4f9f449bd22 --- /dev/null +++ b/src/editors/ShaderEditor/stdafx.h @@ -0,0 +1,21 @@ +//---------------------------------------------------- +// file: stdafx.h +//---------------------------------------------------- +#pragma once +#include "..\xrECore\stdafx.h" +#include "..\xrECore\Editor\device.h" +#include "..\xrECore\Editor\UI_MainCommand.h" +#include "..\xrECore\Editor\UI_ToolsCustom.h" +#include "..\xrECore\Editor\ui_main.h" +#include "..\xrECore\Editor\EditorPreferences.h" +#include "..\xrECore\Editor\render.h" +#include "..\xrECore\Editor\UIRenderForm.h" +#include "..\xrECore\Editor\ELog.h" +#include "..\xrECore\Editor\Library.h" + +#include "UI_shadertools.h" +#include "ui_shadermain.h" +#include "UIMainMenuForm.h" +#include "UILeftBarForm.h" +#include "UITopBarForm.h" +#include "UIMainForm.h" diff --git a/src/editors/ShaderEditor/ui_shadermain.cpp b/src/editors/ShaderEditor/ui_shadermain.cpp new file mode 100644 index 00000000000..1add8432f60 --- /dev/null +++ b/src/editors/ShaderEditor/ui_shadermain.cpp @@ -0,0 +1,191 @@ +#include "stdafx.h" +#include "UI_ShaderMain.h" +#include "UI_ShaderTools.h" +#include "xrEngine/xr_input.h" + +CShaderMain::CShaderMain() +{ + EPrefs = xr_new(); +} + +CShaderMain::~CShaderMain() +{ + xr_delete(EPrefs); +} + +CCommandVar CShaderTool::CommandSave(CCommandVar p1, CCommandVar p2) +{ + Save(0, 0); + ExecCommand(COMMAND_UPDATE_CAPTION); + return TRUE; +} +CCommandVar CShaderTool::CommandSaveBackup(CCommandVar p1, CCommandVar p2) +{ + ExecCommand(COMMAND_SAVE); + return TRUE; +} +CCommandVar CShaderTool::CommandReload(CCommandVar p1, CCommandVar p2) +{ + Reload(); + ExecCommand(COMMAND_UPDATE_CAPTION); + return TRUE; +} +CCommandVar CShaderTool::CommandClear(CCommandVar p1, CCommandVar p2) +{ + EDevice.m_Camera.Reset(); + ExecCommand(COMMAND_UPDATE_CAPTION); + return TRUE; +} +CCommandVar CShaderTool::CommandUpdateList(CCommandVar p1, CCommandVar p2) +{ + UpdateList(); + return TRUE; +} +CCommandVar CommandRefreshUIBar(CCommandVar p1, CCommandVar p2) +{ + /* fraTopBar->RefreshBar (); + fraLeftBar->RefreshBar (); + fraBottomBar->RefreshBar();*/ + return TRUE; +} +CCommandVar CommandRestoreUIBar(CCommandVar p1, CCommandVar p2) +{ + /*fraTopBar->fsStorage->RestoreFormPlacement(); + fraLeftBar->fsStorage->RestoreFormPlacement(); + fraBottomBar->fsStorage->RestoreFormPlacement();*/ + return TRUE; +} +CCommandVar CommandSaveUIBar(CCommandVar p1, CCommandVar p2) +{ + /* fraTopBar->fsStorage->SaveFormPlacement(); + fraLeftBar->fsStorage->SaveFormPlacement(); + fraBottomBar->fsStorage->SaveFormPlacement();*/ + return TRUE; +} +CCommandVar CommandUpdateToolBar(CCommandVar p1, CCommandVar p2) +{ + // fraLeftBar->UpdateBar(); + return TRUE; +} +CCommandVar CommandUpdateCaption(CCommandVar p1, CCommandVar p2) +{ + // frmMain->UpdateCaption(); + return TRUE; +} + +void CShaderMain::RegisterCommands() +{ + inherited::RegisterCommands(); + // tools + REGISTER_CMD_CE(COMMAND_SAVE, "File\\Save", STools, CShaderTool::CommandSave, true); + REGISTER_CMD_C(COMMAND_SAVE_BACKUP, STools, CShaderTool::CommandSaveBackup); + REGISTER_CMD_CE(COMMAND_LOAD, "File\\Reload", STools, CShaderTool::CommandReload, true); + REGISTER_CMD_CE(COMMAND_CLEAR, "File\\Clear", STools, CShaderTool::CommandClear, true); + REGISTER_CMD_CE(COMMAND_UPDATE_LIST, "Update List", STools, CShaderTool::CommandUpdateList, true); + REGISTER_CMD_S(COMMAND_REFRESH_UI_BAR, CommandRefreshUIBar); + REGISTER_CMD_S(COMMAND_RESTORE_UI_BAR, CommandRestoreUIBar); + REGISTER_CMD_S(COMMAND_SAVE_UI_BAR, CommandSaveUIBar); + REGISTER_CMD_S(COMMAND_UPDATE_TOOLBAR, CommandUpdateToolBar); + REGISTER_CMD_S(COMMAND_UPDATE_CAPTION, CommandUpdateCaption); +} + +void CShaderMain::OnDrawUI() +{ + TUI::OnDrawUI(); + for (auto &tool : STools->m_Tools) + { + tool.second->OnDrawUI(); + } +} + +const char *CShaderMain::GetCaption() +{ + return STools->CurrentToolsName(); // "shaders&materials"; +} + +bool CShaderMain::ApplyShortCut(DWORD Key, TShiftState Shift) +{ + return inherited::ApplyShortCut(Key, Shift); +} +//--------------------------------------------------------------------------- + +bool CShaderMain::ApplyGlobalShortCut(DWORD Key, TShiftState Shift) +{ + return inherited::ApplyGlobalShortCut(Key, Shift); +} +//--------------------------------------------------------------------------- + +void CShaderMain::RealUpdateScene() +{ + inherited::RealUpdateScene(); +} +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// Common +//--------------------------------------------------------------------------- +void CShaderMain::ResetStatus() +{ + /*VERIFY(m_bReady); + if (fraBottomBar->paStatus->Caption!=""){ + fraBottomBar->paStatus->Caption=""; fraBottomBar->paStatus->Repaint(); + }*/ +} +void CShaderMain::SetStatus(LPCSTR s, bool bOutLog) +{ + /* VERIFY(m_bReady); + if (fraBottomBar->paStatus->Caption!=s){ + fraBottomBar->paStatus->Caption=s; fraBottomBar->paStatus->Repaint(); + if (bOutLog&&s&&s[0]) ELog.Msg(mtInformation,s); + }*/ +} +void CShaderMain::ProgressDraw() +{ + inherited::ProgressDraw(); + // fraBottomBar->RedrawBar(); +} +//--------------------------------------------------------------------------- +void CShaderMain::OutCameraPos() +{ + /* VERIFY(m_bReady); + xr_string s; + const Fvector& c = EDevice.m_Camera.GetPosition(); + s.sprintf("C: %3.1f, %3.1f, %3.1f",c.x,c.y,c.z); + // const Fvector& hpb = EDevice.m_Camera.GetHPB(); + // s.sprintf(" Cam: %3.1f�, %3.1f�, %3.1f�",rad2deg(hpb.y),rad2deg(hpb.x),rad2deg(hpb.z)); + fraBottomBar->paCamera->Caption=s; fraBottomBar->paCamera->Repaint();*/ +} +//--------------------------------------------------------------------------- +void CShaderMain::OutUICursorPos() +{ + /* VERIFY(fraBottomBar); + xr_string s; POINT pt; + GetCursorPos(&pt); + s.sprintf("Cur: %d, %d",pt.x,pt.y); + fraBottomBar->paUICursor->Caption=s; fraBottomBar->paUICursor->Repaint();*/ +} + +void CShaderMain::OutGridSize() +{ + /*VERIFY(fraBottomBar); + xr_string s; + s.sprintf("Grid: %1.1f",EPrefs->grid_cell_size); + fraBottomBar->paGridSquareSize->Caption=s; fraBottomBar->paGridSquareSize->Repaint();*/ +} + +void CShaderMain::OutInfo() +{ + // fraBottomBar->paSel->Caption = Tools->GetInfo(); +} + +void CShaderMain::RealQuit() +{ + UI->Quit(); +} + +#include "Resources\resource.h" + +HICON CShaderMain::EditorIcon() +{ + return LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(MAINICON)); +} diff --git a/src/editors/ShaderEditor/ui_shadermain.h b/src/editors/ShaderEditor/ui_shadermain.h new file mode 100644 index 00000000000..bf271514f3a --- /dev/null +++ b/src/editors/ShaderEditor/ui_shadermain.h @@ -0,0 +1,45 @@ +#ifndef UI_ShaderMainH +#define UI_ShaderMainH + +enum +{ + COMMAND_EXTFIRST_EXT = COMMAND_MAIN_LAST - 1, + COMMAND_UPDATE_LIST, +}; +//------------------------------------------------------------------------------ +class CShaderMain : public TUI +{ + typedef TUI inherited; + + virtual void RealUpdateScene(); + virtual void RealQuit(); + +public: + CShaderMain(); + virtual ~CShaderMain(); + + virtual const char* GetCaption(); + + virtual void ResetStatus(); + virtual void SetStatus(LPCSTR s, bool bOutLog); + virtual void ProgressDraw(); + virtual void OutCameraPos(); + virtual void OutUICursorPos(); + virtual void OutGridSize(); + virtual void OutInfo(); + + virtual LPCSTR EditorName() { return "shader"; } + virtual LPCSTR EditorDesc() { return "Shader Editor"; } + HICON EditorIcon() override; + + virtual bool ApplyShortCut(DWORD Key, TShiftState Shift); + virtual bool ApplyGlobalShortCut(DWORD Key, TShiftState Shift); + + // commands + virtual void RegisterCommands(); + +protected: + virtual void OnDrawUI(); +}; + +#endif // UI_MainCommandH diff --git a/src/editors/xrECore/EditObjectExportLWO.cpp b/src/editors/xrECore/EditObjectExportLWO.cpp new file mode 100644 index 00000000000..36d98152477 --- /dev/null +++ b/src/editors/xrECore/EditObjectExportLWO.cpp @@ -0,0 +1,104 @@ +#include "stdafx.h" +#include "FS2.h" +#include "Editor/EditObject.h" +#include "Editor/EditMesh.h" + +int FindLPCSTR(LPCSTRVec &vec, LPCSTR key) +{ + for (LPCSTRIt it = vec.begin(); it != vec.end(); it++) + if (0 == strcmp(*it, key)) + return it - vec.begin(); + return -1; +} + +bool CEditableObject::ExportLWO(LPCSTR fname) +{ + CLWMemoryStream *F = xr_new(); + + LPCSTRVec images; + + F->begin_save(); + // tags + F->open_chunk(ID_TAGS); + for (SurfaceIt s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + { + CSurface *S = *s_it; + F->w_stringZ(S->_Name()); + S->tag = s_it - m_Surfaces.begin(); + if (FindLPCSTR(images, S->_Texture()) < 0) + images.push_back(S->_Texture()); + } + F->close_chunk(); + // images + for (LPCSTRIt im_it = images.begin(); im_it != images.end(); im_it++) + { + F->open_chunk(ID_CLIP); + F->w_u32(im_it - images.begin()); + F->open_subchunk(ID_STIL); + F->w_stringZ(*im_it); + F->close_subchunk(); + F->close_chunk(); + } + // surfaces + for (auto s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + { + CSurface *S = *s_it; + int im_idx = FindLPCSTR(images, S->_Texture()); + R_ASSERT(im_idx >= 0); + LPCSTR vm_name = S->_VMap(); + F->Wsurface(S->_Name(), S->m_Flags.is(CSurface::sf2Sided), (u16)im_idx, (vm_name && vm_name[0]) ? vm_name : "Texture", S->_ShaderName(), S->_ShaderXRLCName()); + } + // meshes/layers + for (EditMeshIt mesh_it = FirstMesh(); mesh_it != LastMesh(); mesh_it++) + { + CEditableMesh *MESH = *mesh_it; + F->w_layer(u16(mesh_it - FirstMesh()), MESH->Name().c_str()); + // bounding box + F->open_chunk(ID_BBOX); + F->w_vector(MESH->m_Box.vMin); + F->w_vector(MESH->m_Box.vMax); + F->close_chunk(); + // points + F->open_chunk(ID_PNTS); + for (u32 point_id = 0; point_id < MESH->GetVCount(); point_id++) + F->w_vector(MESH->GetVertices()[point_id]); + F->close_chunk(); + // polygons + F->open_chunk(ID_POLS); + F->w_u32(ID_FACE); + for (u32 f_id = 0; f_id < MESH->GetFCount(); f_id++) + F->w_face3(MESH->GetFaces()[f_id].pv[0].pindex, MESH->GetFaces()[f_id].pv[1].pindex, MESH->GetFaces()[f_id].pv[2].pindex); + F->close_chunk(); + // surf<->face + F->open_chunk(ID_PTAG); + F->w_u32(ID_SURF); + for (SurfFacesPairIt sf_it = MESH->m_SurfFaces.begin(); sf_it != MESH->m_SurfFaces.end(); sf_it++) + { + IntVec &lst = sf_it->second; + for (IntIt i_it = lst.begin(); i_it != lst.end(); i_it++) + { + F->w_vx(*i_it); + F->w_u16(WORD(sf_it->first->tag)); + } + } + F->close_chunk(); + // vmap&vmad + for (VMapIt vm_it = MESH->m_VMaps.begin(); vm_it != MESH->m_VMaps.end(); vm_it++) + { + st_VMap *vmap = *vm_it; + F->begin_vmap(vmap->polymap, (vmap->type == vmtUV) ? ID_TXUV : ID_WGHT, vmap->dim, vmap->name.c_str()); + if (vmap->polymap) + for (int k = 0; k < vmap->size(); k++) + F->w_vmad(vmap->vindices[k], vmap->pindices[k], vmap->dim, vmap->getVMdata(k)); + else + for (int k = 0; k < vmap->size(); k++) + F->w_vmap(vmap->vindices[k], vmap->dim, vmap->getVMdata(k)); + F->end_vmap(); + } + } + F->end_save(fname); + + xr_delete(F); + + return true; +} diff --git a/src/editors/xrECore/Editor/ArbitraryList.h b/src/editors/xrECore/Editor/ArbitraryList.h new file mode 100644 index 00000000000..1a2da995a5d --- /dev/null +++ b/src/editors/xrECore/Editor/ArbitraryList.h @@ -0,0 +1,169 @@ +/* Copyright (C) Tom Forsyth, 2001. + * All rights reserved worldwide. + * + * This software is provided "as is" without express or implied + * warranties. You may freely copy and compile this source into + * applications you distribute provided that the copyright text + * below is included in the resulting source code, for example: + * "Portions Copyright (C) Tom Forsyth, 2001" + */ +// Some standard useful classes, templates, etc. + +#ifndef ArbitraryListH +#define ArbitraryListH + +// An arbitrary-sized list template class. +// Designed to hold _unsorted_ data, but only RemoveItem() +// actually disturbs the order, so you can use it for general arrays +// if you don't use that function. +template +class ArbitraryList +{ + T *pT; // The list. + u32 iSize; // The current size of the list. + u32 iReservedSize; // The current reserved size of the list. +public: + // Constructor, with optional initial size setting. + ArbitraryList(u32 iInitialSize = 0) + { + pT = NULL; + iSize = 0; + iReservedSize = 0; + if (iInitialSize > 0) + resize(iInitialSize); + } + // Destructor. + ~ArbitraryList(void) + { + if (pT == NULL) + { + VERIFY(iReservedSize == 0); + VERIFY(iSize == 0); + } + else + { + VERIFY(iReservedSize > 0); + VERIFY(iSize > 0); + delete[] pT; + pT = NULL; + } + } + // Returns the pointer to the given item. + IC T *item(u32 iItem) + { + VERIFY(iItem < iSize); + return (&pT[iItem]); + } + // Returns the pointer to the first item. + IC T *ptr() { return (pT); } + // Returns the size of the list + IC u32 size() const { return iSize; } + // Grows or shrinks the list to this number of items. + // Preserves existing items. + // Items that fall off the end of a shrink may vanish. + // Returns the pointer to the first item. + IC T *resize(u32 iNum) + { + VERIFY(iNum >= 0); + iSize = iNum; + if (iNum <= iReservedSize) + { + if (iNum == 0) + { + // Shrunk to 0 - bin the memory. + delete[] pT; + pT = NULL; + iReservedSize = 0; + } + else + { + VERIFY(pT != NULL); + } + return (pT); + } + else + { + // Need to grow. Grow by 50% more than + // needed to avoid constant regrows. + u32 iNewSize = (iNum * 3) >> 1; + if (pT == NULL) + { + VERIFY(iReservedSize == 0); + pT = new T[iNewSize]; + } + else + { + VERIFY(iReservedSize != 0); + + T *pOldT = pT; + pT = new T[iNewSize]; + for (u32 i = 0; i < iReservedSize; i++) + { + pT[i] = pOldT[i]; + } + delete[] pOldT; + } + VERIFY(pT != NULL); + iReservedSize = iNewSize; + return (pT); + } + } + // Adds one item to the list and returns a pointer to that new item. + IC T *append() + { + resize(iSize + 1); + return (&pT[iSize - 1]); + } + // Adds one item to the list and returns a pointer to that new item. + IC void push_back(T &val) + { + resize(iSize + 1); + pT[iSize - 1] = val; + } + // Removes the given item number by copying the last item + // to that position and shrinking the list. + IC void erase_fast(u32 iItemNumber) + { + VERIFY(iItemNumber < iSize); + pT[iItemNumber] = pT[iSize - 1]; + resize(iSize - 1); + } + // Copy the specified data into the list. + IC void insert(u32 iFirstItem, T *p, u32 iNumItems) + { + for (u32 i = 0; i < iNumItems; i++) + *(item(i + iFirstItem)) = p[i]; + } + // A copy from another arbitrary list of the same type. + IC void insert(u32 iFirstItem, ArbitraryList &other, u32 iFirstOtherItem, u32 iNumItems) + { + for (u32 i = 0; i < iNumItems; i++) + *(item(i + iFirstItem)) = *(other.item(i + iFirstOtherItem)); + } + IC T &operator[](u32 id) + { + VERIFY(id < iSize); + return pT[id]; + } + IC const T &operator[](u32 id) const + { + VERIFY(id < iSize); + return pT[id]; + } + + // Copy constructor. + ArbitraryList(const ArbitraryList &other) + { + u32 iNumItems = other.size(); + + pT = NULL; + iSize = 0; + iReservedSize = 0; + if (iNumItems > 0) + resize(iNumItems); + for (u32 i = 0; i < iNumItems; i++) + *(item(i)) = other[i]; + } +}; + +#endif //#ifndef ArbitraryListH diff --git a/src/editors/xrECore/Editor/BoneEditor.cpp b/src/editors/xrECore/Editor/BoneEditor.cpp new file mode 100644 index 00000000000..745d7812205 --- /dev/null +++ b/src/editors/xrECore/Editor/BoneEditor.cpp @@ -0,0 +1,264 @@ +#include "stdafx.h" +#pragma hdrstop +// +//#include "xrCore/Animation/Bone.hpp" +//#include "ui_toolscustom.h" +// +//void SJointIKData::clamp_by_limits(Fvector &dest_xyz) +//{ +// switch (type) +// { +// case jtRigid: +// dest_xyz.set(0.f, 0.f, 0.f); +// break; +// case jtJoint: +// clamp(dest_xyz.x, limits[0].limit.x, limits[0].limit.y); +// clamp(dest_xyz.y, limits[1].limit.x, limits[1].limit.y); +// clamp(dest_xyz.z, limits[2].limit.x, limits[2].limit.y); +// break; +// case jtWheel: +// clamp(dest_xyz.x, limits[0].limit.x, limits[0].limit.y); +// dest_xyz.y = 0; +// break; +// case jtSlider: +// dest_xyz.x = 0.f; +// dest_xyz.y = 0.f; +// clamp(dest_xyz.z, limits[1].limit.x, limits[1].limit.y); +// break; +// /* +// case jtWheelXZ: +// clamp(dest_xyz.x,limits[0].limit.x,limits[0].limit.y); dest_xyz.y=0; +// break; +// case jtWheelXY: +// clamp(dest_xyz.x,limits[0].limit.x,limits[0].limit.y); dest_xyz.z=0; +// break; +// case jtWheelYX: +// clamp(dest_xyz.y,limits[1].limit.x,limits[1].limit.y); dest_xyz.z=0; +// break; +// case jtWheelYZ: +// clamp(dest_xyz.y,limits[1].limit.x,limits[1].limit.y); dest_xyz.x=0; +// break; +// case jtWheelZX: +// clamp(dest_xyz.z,limits[2].limit.x,limits[2].limit.y); dest_xyz.y=0; +// break; +// case jtWheelZY: +// clamp(dest_xyz.z,limits[2].limit.x,limits[2].limit.y); dest_xyz.x=0; +// break; +// */ +// } +//} +// +//void CBone::ShapeScale(const Fvector &_amount) +//{ +// switch (shape.type) +// { +// case SBoneShape::stBox: +// { +// Fvector amount = _amount; +// // Fmatrix _IT;_IT.invert(LTransform()); +// // _IT.transform_dir(amount,_amount); +// // if (Tools->GetSettings(etfCSParent)) _IT.transform_dir(amount); +// shape.box.m_halfsize.add(amount); +// if (shape.box.m_halfsize.x < EPS) +// shape.box.m_halfsize.x = EPS; +// if (shape.box.m_halfsize.y < EPS) +// shape.box.m_halfsize.y = EPS; +// if (shape.box.m_halfsize.z < EPS) +// shape.box.m_halfsize.z = EPS; +// } +// break; +// case SBoneShape::stSphere: +// shape.sphere.R += _amount.x; +// if (shape.sphere.R < EPS) +// shape.sphere.R = EPS; +// break; +// case SBoneShape::stCylinder: +// shape.cylinder.m_height += _amount.z; +// if (shape.cylinder.m_height < EPS) +// shape.cylinder.m_height = EPS; +// shape.cylinder.m_radius += _amount.x; +// if (shape.cylinder.m_radius < EPS) +// shape.cylinder.m_radius = EPS; +// break; +// } +//} +// +//void CBone::ShapeRotate(const Fvector &_amount) +//{ +// Fvector amount = _amount; +// Fmatrix _IT; +// _IT.invert(LTransform()); +// if (Tools->GetSettings(etfCSParent)) +// _IT.transform_dir(amount); +// switch (shape.type) +// { +// case SBoneShape::stBox: +// { +// Fmatrix R; +// R.setXYZi(amount.x, amount.y, amount.z); +// shape.box.transform(shape.box, R); +// } +// break; +// case SBoneShape::stSphere: +// break; +// case SBoneShape::stCylinder: +// { +// Fmatrix R; +// R.setXYZi(amount.x, amount.y, amount.z); +// R.transform_dir(shape.cylinder.m_direction); +// } +// break; +// } +//} +// +//void CBone::ShapeMove(const Fvector &_amount) +//{ +// Fvector amount = _amount; +// Fmatrix _IT; +// _IT.invert(LTransform()); +// if (Tools->GetSettings(etfCSParent)) +// _IT.transform_dir(amount); +// switch (shape.type) +// { +// case SBoneShape::stBox: +// shape.box.m_translate.add(amount); +// break; +// case SBoneShape::stSphere: +// shape.sphere.P.add(amount); +// break; +// case SBoneShape::stCylinder: +// { +// shape.cylinder.m_center.add(amount); +// } +// break; +// } +//} +// +//void CBone::BindRotate(const Fvector &_amount) +//{ +// rest_rotate.add(_amount); +//} +// +//void CBone::BindMove(const Fvector &_amount) +//{ +// rest_offset.add(_amount); +//} +// +//bool CBone::Pick(float &dist, const Fvector &S, const Fvector &D, const Fmatrix &parent) +//{ +// Fvector start, dir; +// Fmatrix M; +// M.mul_43(parent, LTransform()); +// M.invert(); +// M.transform_tiny(start, S); +// M.transform_dir(dir, D); +// switch (shape.type) +// { +// case SBoneShape::stBox: +// return shape.box.intersect(start, dir, dist); +// case SBoneShape::stSphere: +// return shape.sphere.intersect(start, dir, dist); +// case SBoneShape::stCylinder: +// return shape.cylinder.intersect(start, dir, dist); +// default: +// Fsphere S; +// S.P.set(0, 0, 0); +// S.R = 0.025f; +// return S.intersect(start, dir, dist); +// } +//} +// +//void CBone::BoneRotate(const Fvector &_axis, float angle) +//{ +// if (!fis_zero(angle)) +// { +// if (Tools->GetSettings(etfCSParent)) +// { +// // bind pose CS +// mot_rotate.x += _axis.x * angle; +// mot_rotate.y += _axis.y * angle; +// mot_rotate.z += _axis.z * angle; +// +// ClampByLimits(); +// /* +// Fmatrix mBind,mBindI,mLocal,mRotate,mLocalBP; +// mBind.setXYZi (rest_rotate); +// mBindI.invert (mBind); +// mLocal.setXYZi (mot_rotate); +// Fvector axis; +// mBind.transform (axis,_axis); +// mRotate.rotation (axis,angle); +// mLocal.mulA (mRotate); +// +// mLocalBP.mul (mBindI,mLocal); +// Fvector mot; +// mLocalBP.getXYZi (mot); +// +// IK_data.clamp_by_limits(mot); +// +// mLocalBP.setXYZi (mot); +// mLocal.mul (mBind,mLocalBP); +// mLocal.getXYZi (mot_rotate); +// */ +// } +// else +// { +// // local CS +// Fmatrix mBind, mBindI, mRotate, mLocal, mLocalBP; +// mBind.setXYZi(rest_rotate); +// mBindI.invert(mBind); +// +// Fvector axis; +// MTransform().transform_dir(axis, _axis); +// +// // rotation +// mRotate.rotation(axis, angle); +// mLocal.mul(mRotate, MTransform()); +// mLocal.getXYZi(mot_rotate); +// +// // local clamp +// Fvector mot; +// mLocalBP.mul(mBindI, mLocal); +// mLocalBP.getXYZi(mot); +// +// IK_data.clamp_by_limits(mot); +// +// mLocalBP.setXYZi(mot); +// mLocal.mul(mBind, mLocalBP); +// mLocal.getXYZi(mot_rotate); +// } +// } +//} +//void CBone::BoneMove(const Fvector &_amount) +//{ +// Fvector amount = _amount; +// switch (IK_data.type) +// { +// case jtSlider: +// amount.x = 0.f; +// amount.y = 0.f; +// rest_i_transform.transform(mot_offset); +// mot_offset.add(amount); +// clamp(mot_offset.z, rest_offset.z + IK_data.limits[0].limit.x, rest_offset.z + IK_data.limits[0].limit.y); +// rest_transform.transform(mot_offset); +// break; +// } +//} +// +//void CBone::ClampByLimits() +//{ +// Fmatrix mBind, mBindI, mLocal, mLocalBP; +// mBind.setXYZi(rest_rotate); +// mBindI.invert(mBind); +// +// mLocal.setXYZi(mot_rotate); +// mLocalBP.mul(mBindI, mLocal); +// Fvector mot; +// mLocalBP.getXYZi(mot); +// +// IK_data.clamp_by_limits(mot); +// +// mLocalBP.setXYZi(mot); +// mLocal.mul(mBind, mLocalBP); +// mLocal.getXYZi(mot_rotate); +//} diff --git a/src/editors/xrECore/Editor/ColorPicker.cpp b/src/editors/xrECore/Editor/ColorPicker.cpp new file mode 100644 index 00000000000..0849a5bdcb1 --- /dev/null +++ b/src/editors/xrECore/Editor/ColorPicker.cpp @@ -0,0 +1,62 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "ColorPicker.h" +/* +class CTCD{ +public: + TColorDialog* cdColor; +public: + CTCD(){ + cdColor = xr_new((TComponent*)0); + cdColor->Options = TColorDialogOptions()<Color = TColor(rgb2bgr(*currentcolor)); + if (TCD.cdColor->Execute()){ + *currentcolor = bgr2rgb(TCD.cdColor->Color); + return true; + } + return false; + }else{ + u32 clr=*currentcolor; + if (FSColorPickerExecute(&clr, 0, 0)){ + *currentcolor = clr; + return true; + } + return false; + }*/ + return false; +} + +bool SelectColorWin(u32 *currentcolor, bool bDefaultPicker) +{ + /* VERIFY(currentcolor); + if (bDefaultPicker){ + TCD.cdColor->Color = TColor(*currentcolor); + if (TCD.cdColor->Execute()){ + *currentcolor = TCD.cdColor->Color; + return true; + } + return false; + }else{ + u32 cur = bgr2rgb(*currentcolor); + if (FSColorPickerExecute(&cur, 0, 0)){ + *currentcolor = rgb2bgr(cur); + return true; + } + return false; + }*/ + return false; +} diff --git a/src/editors/xrECore/Editor/ColorPicker.h b/src/editors/xrECore/Editor/ColorPicker.h new file mode 100644 index 00000000000..492c288a0b0 --- /dev/null +++ b/src/editors/xrECore/Editor/ColorPicker.h @@ -0,0 +1,8 @@ +//--------------------------------------------------------------------------- +#ifndef ColorPickerH +#define ColorPickerH + +bool ECORE_API SelectColor(u32 *currentcolor, bool bDefaultPicker = false); +bool ECORE_API SelectColorWin(u32 *currentcolor, bool bDefaultPicker = false); + +#endif // ColorPicker diff --git a/src/editors/xrECore/Editor/D3DUtils.cpp b/src/editors/xrECore/Editor/D3DUtils.cpp new file mode 100644 index 00000000000..c384e6c6006 --- /dev/null +++ b/src/editors/xrECore/Editor/D3DUtils.cpp @@ -0,0 +1,1542 @@ +#include "stdafx.h" +#include "xrEngine/GameFont.h" +#include "d3dutils.h" +#include "Layers/xrRender/du_box.h" +#include "du_sphere.h" +#include "du_sphere_part.h" +#include "du_cone.h" +#include "du_cylinder.h" +#include "Library.h" +#include "EditObject.h" +#include "ui_main.h" + +#pragma warning(push) +#pragma warning(disable : 4995) +#include "d3dx9.h" +#pragma warning(pop) + +CDrawUtilities DU_impl; + +#define LINE_DIVISION 32 // не меньше 6!!!!! +// for drawing sphere +static Fvector circledef1[LINE_DIVISION]; +static Fvector circledef2[LINE_DIVISION]; +static Fvector circledef3[LINE_DIVISION]; + +const u32 boxcolor = D3DCOLOR_RGBA(255, 255, 255, 0); +static const int boxvertcount = 48; +static Fvector boxvert[boxvertcount]; + +#ifdef _EDITOR +#define DU_DRAW_RS EDevice.SetRS +#define DU_DRAW_SH_C(a, c) \ + { \ + EDevice.SetShader(a); \ + EDevice.SetRS(D3DRS_TEXTUREFACTOR, c); \ + } +#define DU_DRAW_SH(a) \ + { \ + EDevice.SetShader(a); \ + EDevice.SetRS(D3DRS_TEXTUREFACTOR, 0xFFFFFFFF); \ + } +#else +#define DU_DRAW_RS RCache.dbg_SetRS +#define DU_DRAW_SH_C(sh, c) \ + { \ + RCache.set_Shader(sh); \ + RCache.set_c("tfactor", float(color_get_R(c)) / 255.f, float(color_get_G(c)) / 255.f, float(color_get_B(c)) / 255.f, float(color_get_A(c)) / 255.f); \ + } +#define DU_DRAW_SH(sh) \ + { \ + RCache.set_Shader(sh); \ + RCache.set_c("tfactor", 1, 1, 1, 1); \ + } +#endif + +#ifdef _EDITOR +#define FILL_MODE EDevice.dwFillMode +#define SHADE_MODE EDevice.dwShadeMode +#define SCREEN_QUALITY EDevice.m_ScreenQuality +#else +#define FILL_MODE D3DFILL_SOLID +#define SHADE_MODE D3DSHADE_GOURAUD +#define SCREEN_QUALITY 1.f +#endif + +// identity box +const u32 identboxcolor = D3DCOLOR_RGBA(255, 255, 255, 0); +static const int identboxwirecount = 24; +static Fvector identboxwire[identboxwirecount] = { + {-0.5f, -0.5f, -0.5f}, {-0.5f, +0.5f, -0.5f}, {-0.5f, +0.5f, -0.5f}, {+0.5f, +0.5f, -0.5f}, {+0.5f, +0.5f, -0.5f}, {+0.5f, -0.5f, -0.5f}, {+0.5f, -0.5f, -0.5f}, {-0.5f, -0.5f, -0.5f}, {-0.5f, +0.5f, +0.5f}, {+0.5f, +0.5f, +0.5f}, {+0.5f, +0.5f, +0.5f}, {+0.5f, -0.5f, +0.5f}, {+0.5f, -0.5f, +0.5f}, {-0.5f, -0.5f, +0.5f}, {-0.5f, -0.5f, +0.5f}, {-0.5f, +0.5f, +0.5f}, {-0.5f, +0.5f, -0.5f}, {-0.5f, +0.5f, +0.5f}, {+0.5f, +0.5f, -0.5f}, {+0.5f, +0.5f, +0.5f}, {+0.5f, -0.5f, -0.5f}, {+0.5f, -0.5f, +0.5f}, {-0.5f, -0.5f, -0.5f}, {-0.5f, -0.5f, +0.5f}}; + +/* +static const int identboxindexcount = 36; +static const WORD identboxindices[identboxindexcount] = { + 0, 1, 2, 2, 3, 0, + 3, 2, 6, 6, 7, 3, + 6, 4, 5, 6, 5, 7, + 4, 1, 5, 1, 0, 5, + 3, 5, 0, 3, 7, 5, + 1, 4, 6, 1, 6, 2}; +static const int identboxindexwirecount = 24; +static const WORD identboxindiceswire[identboxindexwirecount] = { + 0, 1, 1, 2, + 2, 3, 3, 0, + 4, 6, 6, 7, + 7, 5, 5, 4, + 1, 4, 2, 6, + 3, 7, 0, 5}; +*/ + +#define SIGN(x) ((x < 0) ? -1 : 1) + +DEFINE_VECTOR(FVF::L, FLvertexVec, FLvertexIt) + +static FLvertexVec m_GridPoints; + +u32 m_ColorAxis = 0xff000000; +u32 m_ColorGrid = 0xff909090; +u32 m_ColorGridTh = 0xffb4b4b4; +u32 m_SelectionRect = D3DCOLOR_RGBA(127, 255, 127, 64); + +u32 m_ColorSafeRect = 0xffB040B0; + +void SPrimitiveBuffer::CreateFromData(D3DPRIMITIVETYPE _pt, u32 _p_cnt, u32 FVF, LPVOID vertices, u32 _v_cnt, u16 *indices, u32 _i_cnt) +{ + IDirect3DVertexBuffer9 *pVB = 0; + IDirect3DIndexBuffer9 *pIB = 0; + p_cnt = _p_cnt; + p_type = _pt; + v_cnt = _v_cnt; + i_cnt = _i_cnt; + u32 stride = D3DXGetFVFVertexSize(FVF); + R_CHK(HW.pDevice->CreateVertexBuffer(v_cnt * stride, D3DUSAGE_WRITEONLY, 0, D3DPOOL_MANAGED, &pVB, 0)); + u8 *bytes; + R_CHK(pVB->Lock(0, 0, (LPVOID *)&bytes, 0)); + FLvertexVec verts(v_cnt); + for (u32 k = 0; k < v_cnt; ++k) + verts[k].set(((Fvector *)vertices)[k], 0xFFFFFFFF); + memcpy(bytes, &*verts.begin(), v_cnt * stride); + R_CHK(pVB->Unlock()); + if (i_cnt) + { + R_CHK(HW.pDevice->CreateIndexBuffer(i_cnt * sizeof(u16), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &pIB, NULL)); + R_CHK(pIB->Lock(0, 0, (LPVOID *)&bytes, 0)); + memcpy(bytes, indices, i_cnt * sizeof(u16)); + R_CHK(pIB->Unlock()); + OnRender.bind(this, &SPrimitiveBuffer::RenderDIP); + } + else + { + OnRender.bind(this, &SPrimitiveBuffer::RenderDP); + } + pGeom.create(FVF, pVB, pIB); +} +void SPrimitiveBuffer::Destroy() +{ + if (pGeom) + { + _RELEASE(pGeom->vb); + _RELEASE(pGeom->ib); + pGeom.destroy(); + } +} + +void CDrawUtilities::UpdateGrid(int number_of_cell, float square_size, int subdiv) +{ + m_GridPoints.clear(); + // grid + int m_GridSubDiv[2]; + int m_GridCounts[2]; + Fvector2 m_GridStep; + + m_GridStep.set(square_size, square_size); + m_GridSubDiv[0] = subdiv; + m_GridSubDiv[1] = subdiv; + m_GridCounts[0] = number_of_cell; // iFloor(size/step)*subdiv; + m_GridCounts[1] = number_of_cell; // iFloor(size/step)*subdiv; + + FVF::L left, right; + left.p.y = right.p.y = 0; + + for (int thin = 0; thin < 2; thin++) + { + for (int i = -m_GridCounts[0]; i <= m_GridCounts[0]; i++) + { + if ((!!thin) != !!(i % m_GridSubDiv[0])) + { + left.p.z = -m_GridCounts[1] * m_GridStep.y; + right.p.z = m_GridCounts[1] * m_GridStep.y; + left.p.x = i * m_GridStep.x; + right.p.x = left.p.x; + left.color = (i % m_GridSubDiv[0]) ? m_ColorGrid : m_ColorGridTh; + right.color = left.color; + m_GridPoints.push_back(left); + m_GridPoints.push_back(right); + } + } + for (int i = -m_GridCounts[1]; i <= m_GridCounts[1]; i++) + { + if ((!!thin) != !!(i % m_GridSubDiv[1])) + { + left.p.x = -m_GridCounts[0] * m_GridStep.x; + right.p.x = m_GridCounts[0] * m_GridStep.x; + left.p.z = i * m_GridStep.y; + right.p.z = left.p.z; + left.color = (i % m_GridSubDiv[1]) ? m_ColorGrid : m_ColorGridTh; + right.color = left.color; + m_GridPoints.push_back(left); + m_GridPoints.push_back(right); + } + } + } +} + +void CDrawUtilities::OnDeviceCreate() +{ + EDevice.seqRender.Add(this, REG_PRIORITY_LOW - 1000); + + m_SolidBox.CreateFromData(D3DPT_TRIANGLELIST, DU_BOX_NUMFACES, D3DFVF_XYZ | D3DFVF_DIFFUSE, du_box_vertices, DU_BOX_NUMVERTEX, du_box_faces, DU_BOX_NUMFACES * 3); + m_SolidCone.CreateFromData(D3DPT_TRIANGLELIST, DU_CONE_NUMFACES, D3DFVF_XYZ | D3DFVF_DIFFUSE, du_cone_vertices, DU_CONE_NUMVERTEX, du_cone_faces, DU_CONE_NUMFACES * 3); + m_SolidSphere.CreateFromData(D3DPT_TRIANGLELIST, DU_SPHERE_NUMFACES, D3DFVF_XYZ | D3DFVF_DIFFUSE, du_sphere_vertices, DU_SPHERE_NUMVERTEX, du_sphere_faces, DU_SPHERE_NUMFACES * 3); + m_SolidSpherePart.CreateFromData(D3DPT_TRIANGLELIST, DU_SPHERE_PART_NUMFACES, D3DFVF_XYZ | D3DFVF_DIFFUSE, du_sphere_part_vertices, DU_SPHERE_PART_NUMVERTEX, du_sphere_part_faces, DU_SPHERE_PART_NUMFACES * 3); + m_SolidCylinder.CreateFromData(D3DPT_TRIANGLELIST, DU_CYLINDER_NUMFACES, D3DFVF_XYZ | D3DFVF_DIFFUSE, du_cylinder_vertices, DU_CYLINDER_NUMVERTEX, du_cylinder_faces, DU_CYLINDER_NUMFACES * 3); + m_WireBox.CreateFromData(D3DPT_LINELIST, DU_BOX_NUMLINES, D3DFVF_XYZ | D3DFVF_DIFFUSE, du_box_vertices, DU_BOX_NUMVERTEX, du_box_lines, DU_BOX_NUMLINES * 2); + m_WireCone.CreateFromData(D3DPT_LINELIST, DU_CONE_NUMLINES, D3DFVF_XYZ | D3DFVF_DIFFUSE, du_cone_vertices, DU_CONE_NUMVERTEX, du_cone_lines, DU_CONE_NUMLINES * 2); + m_WireSphere.CreateFromData(D3DPT_LINELIST, DU_SPHERE_NUMLINES, D3DFVF_XYZ | D3DFVF_DIFFUSE, du_sphere_verticesl, DU_SPHERE_NUMVERTEXL, du_sphere_lines, DU_SPHERE_NUMLINES * 2); + m_WireSpherePart.CreateFromData(D3DPT_LINELIST, DU_SPHERE_PART_NUMLINES, D3DFVF_XYZ | D3DFVF_DIFFUSE, du_sphere_part_vertices, DU_SPHERE_PART_NUMVERTEX, du_sphere_part_lines, DU_SPHERE_PART_NUMLINES * 2); + m_WireCylinder.CreateFromData(D3DPT_LINELIST, DU_CYLINDER_NUMLINES, D3DFVF_XYZ | D3DFVF_DIFFUSE, du_cylinder_vertices, DU_CYLINDER_NUMVERTEX, du_cylinder_lines, DU_CYLINDER_NUMLINES * 2); + + for (int i = 0; i < LINE_DIVISION; i++) + { + float angle = M_PI * 2.f * (i / (float)LINE_DIVISION); + float _sa = _sin(angle), _ca = _cos(angle); + circledef1[i].x = _ca; + circledef1[i].y = _sa; + circledef1[i].z = 0; + circledef2[i].x = 0; + circledef2[i].y = _ca; + circledef2[i].z = _sa; + circledef3[i].x = _sa; + circledef3[i].y = 0; + circledef3[i].z = _ca; + } + // initialize identity box + Fbox bb; + bb.set(-0.505f, -0.505f, -0.505f, 0.505f, 0.505f, 0.505f); + for (int i = 0; i < 8; i++) + { + Fvector S; + Fvector p; + bb.getpoint(i, p); + S.set((float)SIGN(p.x), (float)SIGN(p.y), (float)SIGN(p.z)); + boxvert[i * 6 + 0].set(p); + boxvert[i * 6 + 1].set(p.x - S.x * 0.25f, p.y, p.z); + boxvert[i * 6 + 2].set(p); + boxvert[i * 6 + 3].set(p.x, p.y - S.y * 0.25f, p.z); + boxvert[i * 6 + 4].set(p); + boxvert[i * 6 + 5].set(p.x, p.y, p.z - S.z * 0.25f); + } + // create render stream + vs_L.create(FVF::F_L, RImplementation.Vertex.Buffer(), RImplementation.Index.Buffer()); + vs_TL.create(FVF::F_TL, RImplementation.Vertex.Buffer(), RImplementation.Index.Buffer()); + vs_LIT.create(FVF::F_LIT, RImplementation.Vertex.Buffer(), RImplementation.Index.Buffer()); + + m_Font = xr_new("hud_font_small"); + + m_axis_object = NULL; +} + +void CDrawUtilities::DestroyObjects() +{ + Lib.RemoveEditObject(m_axis_object); +} + +void CDrawUtilities::OnDeviceDestroy() +{ + EDevice.seqRender.Remove(this); + xr_delete(m_Font); + m_SolidBox.Destroy(); + m_SolidCone.Destroy(); + m_SolidSphere.Destroy(); + m_SolidSpherePart.Destroy(); + m_SolidCylinder.Destroy(); + m_WireBox.Destroy(); + m_WireCone.Destroy(); + m_WireSphere.Destroy(); + m_WireSpherePart.Destroy(); + m_WireCylinder.Destroy(); + + vs_L.destroy(); + vs_TL.destroy(); + vs_LIT.destroy(); +} +//---------------- + +void CDrawUtilities::DrawSpotLight(const Fvector &p, const Fvector &d, float range, float phi, u32 clr) +{ + Fmatrix T; + Fvector p1; + float H, P; + float da = PI_MUL_2 / LINE_DIVISION; + float b = range * _cos(PI_DIV_2 - phi / 2); + float a = range * _sin(PI_DIV_2 - phi / 2); + d.getHP(H, P); + T.setHPB(H, P, 0); + T.translate_over(p); + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + FVF::L *pv = (FVF::L *)Stream->Lock(LINE_DIVISION * 2 + 2, vs_L->vb_stride, vBase); + for (float angle = 0; angle < PI_MUL_2; angle += da) + { + float _sa = _sin(angle); + float _ca = _cos(angle); + p1.x = b * _ca; + p1.y = b * _sa; + p1.z = a; + T.transform_tiny(p1); + // fill VB + pv->set(p, clr); + pv++; + pv->set(p1, clr); + pv++; + } + p1.mad(p, d, range); + pv->set(p, clr); + pv++; + pv->set(p1, clr); + pv++; + Stream->Unlock(LINE_DIVISION * 2 + 2, vs_L->vb_stride); + // and Render it as triangle list + DU_DRAW_DP(D3DPT_LINELIST, vs_L, vBase, LINE_DIVISION + 1); +} + +void CDrawUtilities::DrawDirectionalLight(const Fvector &p, const Fvector &d, float radius, float range, u32 c) +{ + float r = radius * 0.71f; + Fvector R, N, D; + D.normalize(d); + Fmatrix rot; + + N.set(0, 1, 0); + if (_abs(D.y) > 0.99f) + N.set(1, 0, 0); + R.crossproduct(N, D); + R.normalize(); + N.crossproduct(D, R); + N.normalize(); + rot.set(R, N, D, p); + float sz = radius + range; + + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + FVF::L *pv = (FVF::L *)Stream->Lock(6, vs_L->vb_stride, vBase); + pv->set(0, 0, r, c); + rot.transform_tiny(pv->p); + pv++; + pv->set(0, 0, sz, c); + rot.transform_tiny(pv->p); + pv++; + pv->set(-r, 0, r, c); + rot.transform_tiny(pv->p); + pv++; + pv->set(-r, 0, sz, c); + rot.transform_tiny(pv->p); + pv++; + pv->set(r, 0, r, c); + rot.transform_tiny(pv->p); + pv++; + pv->set(r, 0, sz, c); + rot.transform_tiny(pv->p); + pv++; + Stream->Unlock(6, vs_L->vb_stride); + + // and Render it as triangle list + DU_DRAW_DP(D3DPT_LINELIST, vs_L, vBase, 3); + + Fbox b; + b.vMin.set(-r, -r, -r); + b.vMax.set(r, r, r); + + DrawLineSphere(p, radius, c, true); +} + +void CDrawUtilities::DrawPointLight(const Fvector &p, float radius, u32 c) +{ + RCache.set_xform_world(Fidentity); + DrawCross(p, radius, radius, radius, radius, radius, radius, c, true); +} + +void CDrawUtilities::DrawEntity(u32 clr, ref_shader s) +{ + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + FVF::L *pv = (FVF::L *)Stream->Lock(5, vs_L->vb_stride, vBase); + pv->set(0.f, 0.f, 0.f, clr); + pv++; + pv->set(0.f, 1.f, 0.f, clr); + pv++; + pv->set(0.f, 1.f, .5f, clr); + pv++; + pv->set(0.f, .5f, .5f, clr); + pv++; + pv->set(0.f, .5f, 0.f, clr); + pv++; + Stream->Unlock(5, vs_L->vb_stride); + // render flagshtok + DU_DRAW_SH(EDevice.m_WireShader); + DU_DRAW_DP(D3DPT_LINESTRIP, vs_L, vBase, 4); + + if (s) + DU_DRAW_SH(s); + { + // fill VB + FVF::LIT *pv = (FVF::LIT *)Stream->Lock(6, vs_LIT->vb_stride, vBase); + pv->set(0.f, 1.f, 0.f, clr, 0.f, 0.f); + pv++; + pv->set(0.f, 1.f, .5f, clr, 1.f, 0.f); + pv++; + pv->set(0.f, .5f, .5f, clr, 1.f, 1.f); + pv++; + pv->set(0.f, .5f, 0.f, clr, 0.f, 1.f); + pv++; + pv->set(0.f, .5f, .5f, clr, 1.f, 1.f); + pv++; + pv->set(0.f, 1.f, .5f, clr, 1.f, 0.f); + pv++; + Stream->Unlock(6, vs_LIT->vb_stride); + // and Render it as line list + DU_DRAW_DP(D3DPT_TRIANGLEFAN, vs_LIT, vBase, 4); + } +} + +void CDrawUtilities::DrawFlag(const Fvector &p, float heading, float height, float sz, float sz_fl, u32 clr, BOOL bDrawEntity) +{ + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + FVF::L *pv = (FVF::L *)Stream->Lock(2, vs_L->vb_stride, vBase); + pv->set(p, clr); + pv++; + pv->set(p.x, p.y + height, p.z, clr); + pv++; + Stream->Unlock(2, vs_L->vb_stride); + // and Render it as triangle list + DU_DRAW_DP(D3DPT_LINELIST, vs_L, vBase, 1); + + if (bDrawEntity) + { + // fill VB + float rx = _sin(heading); + float rz = _cos(heading); + FVF::L *pv = (FVF::L *)Stream->Lock(6, vs_L->vb_stride, vBase); + sz *= 0.8f; + pv->set(p.x, p.y + height, p.z, clr); + pv++; + pv->set(p.x + rx * sz, p.y + height, p.z + rz * sz, clr); + pv++; + sz *= 0.5f; + pv->set(p.x, p.y + height * (1.f - sz_fl * .5f), p.z, clr); + pv++; + pv->set(p.x + rx * sz * 0.6f, p.y + height * (1.f - sz_fl * .5f), p.z + rz * sz * 0.75f, clr); + pv++; + pv->set(p.x, p.y + height * (1.f - sz_fl), p.z, clr); + pv++; + pv->set(p.x + rx * sz, p.y + height * (1.f - sz_fl), p.z + rz * sz, clr); + pv++; + Stream->Unlock(6, vs_L->vb_stride); + // and Render it as line list + DU_DRAW_DP(D3DPT_LINELIST, vs_L, vBase, 3); + } + else + { + // fill VB + FVF::L *pv = (FVF::L *)Stream->Lock(6, vs_L->vb_stride, vBase); + pv->set(p.x, p.y + height * (1.f - sz_fl), p.z, clr); + pv++; + pv->set(p.x, p.y + height, p.z, clr); + pv++; + pv->set(p.x + _sin(heading) * sz, ((pv - 2)->p.y + (pv - 1)->p.y) / 2, p.z + _cos(heading) * sz, clr); + pv++; + pv->set(*(pv - 3)); + pv++; + pv->set(*(pv - 2)); + pv++; + pv->set(*(pv - 4)); + pv++; + Stream->Unlock(6, vs_L->vb_stride); + // and Render it as triangle list + DU_DRAW_DP(D3DPT_TRIANGLELIST, vs_L, vBase, 2); + } +} + +//------------------------------------------------------------------------------ + +void CDrawUtilities::DrawRomboid(const Fvector &p, float r, u32 c) +{ + static const u32 IL[24] = {0, 2, 2, 5, 0, 5, 3, 5, 3, 0, 4, 3, 4, 0, 4, 2, 1, 2, 1, 5, 1, 3, 1, 4}; + static const u32 IT[24] = {2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 0, 4, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1}; + static Fvector PT[6] = { + {0.0f, 1.0f, 0.0f}, + {0.0f, -1.0f, 0.0f}, + {0.0f, 0.0f, -1.0f}, + {0.0f, 0.0f, 1.0f}, + {-1.0f, 0.0f, 0.0f}, + {1.0f, 0.0f, 0.0f}, + }; + Fcolor C; + C.set(c); + C.mul_rgb(0.75); + u32 c1 = C.get(); + + DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 8, p, PT, 6, IT, 24, c1, r); + DrawIndexedPrimitive(D3DPT_LINELIST, 12, p, PT, 6, IL, 24, c, r); + return; + + u32 vBase, iBase; + int k; + FVF::L *pv; + WORD *i; + _VertexStream *Stream = &RImplementation.Vertex; + _IndexStream *StreamI = &RImplementation.Index; + + // fill VB + pv = (FVF::L *)Stream->Lock(6, vs_L->vb_stride, vBase); + pv->set(p.x, p.y + r, p.z, c1); + pv++; + pv->set(p.x, p.y - r, p.z, c1); + pv++; + pv->set(p.x, p.y, p.z - r, c1); + pv++; + pv->set(p.x, p.y, p.z + r, c1); + pv++; + pv->set(p.x - r, p.y, p.z, c1); + pv++; + pv->set(p.x + r, p.y, p.z, c1); + pv++; + Stream->Unlock(6, vs_L->vb_stride); + + i = StreamI->Lock(24, iBase); + for (k = 0; k < 24; k++, i++) + *i = IT[k]; + StreamI->Unlock(24); + + // and Render it as triangle list + DU_DRAW_DIP(D3DPT_TRIANGLELIST, vs_L, vBase, 0, 6, iBase, 12); + + // draw lines + pv = (FVF::L *)Stream->Lock(6, vs_L->vb_stride, vBase); + pv->set(p.x, p.y + r, p.z, c); + pv++; + pv->set(p.x, p.y - r, p.z, c); + pv++; + pv->set(p.x, p.y, p.z - r, c); + pv++; + pv->set(p.x, p.y, p.z + r, c); + pv++; + pv->set(p.x - r, p.y, p.z, c); + pv++; + pv->set(p.x + r, p.y, p.z, c); + pv++; + Stream->Unlock(6, vs_L->vb_stride); + + i = StreamI->Lock(24, iBase); + for (k = 0; k < 24; k++, i++) + *i = IL[k]; + StreamI->Unlock(24); + + DU_DRAW_DIP(D3DPT_LINELIST, vs_L, vBase, 0, 6, iBase, 12); +} +//------------------------------------------------------------------------------ + +void CDrawUtilities::DrawSound(const Fvector &p, float r, u32 c) +{ + DrawCross(p, r, r, r, r, r, r, c, true); +} +//------------------------------------------------------------------------------ +void CDrawUtilities::DrawIdentCone(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w) +{ + if (bWire) + { + DU_DRAW_SH_C(EDevice.m_WireShader, clr_w); + m_WireCone.Render(); + } + if (bSolid) + { + DU_DRAW_SH_C(color_get_A(clr_s) >= 254 ? EDevice.m_WireShader : EDevice.m_SelectionShader, clr_s); + m_SolidCone.Render(); + } + DU_DRAW_RS(D3DRS_TEXTUREFACTOR, 0xffffffff); +} + +void CDrawUtilities::DrawIdentSphere(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w) +{ + if (bWire) + { + DU_DRAW_SH_C(EDevice.m_WireShader, clr_w); + m_WireSphere.Render(); + } + if (bSolid) + { + DU_DRAW_SH_C(color_get_A(clr_s) >= 254 ? EDevice.m_WireShader : EDevice.m_SelectionShader, clr_s); + m_SolidSphere.Render(); + } + DU_DRAW_RS(D3DRS_TEXTUREFACTOR, 0xffffffff); +} + +void CDrawUtilities::DrawIdentSpherePart(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w) +{ + if (bWire) + { + DU_DRAW_SH_C(EDevice.m_WireShader, clr_w); + m_WireSpherePart.Render(); + } + if (bSolid) + { + DU_DRAW_SH_C(color_get_A(clr_s) >= 254 ? EDevice.m_WireShader : EDevice.m_SelectionShader, clr_s); + m_SolidSpherePart.Render(); + } + DU_DRAW_RS(D3DRS_TEXTUREFACTOR, 0xffffffff); +} + +void CDrawUtilities::DrawIdentCylinder(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w) +{ + if (bWire) + { + DU_DRAW_SH_C(EDevice.m_WireShader, clr_w); + m_WireCylinder.Render(); + } + if (bSolid) + { + DU_DRAW_SH_C(color_get_A(clr_s) >= 254 ? EDevice.m_WireShader : EDevice.m_SelectionShader, clr_s); + m_SolidCylinder.Render(); + } + DU_DRAW_RS(D3DRS_TEXTUREFACTOR, 0xffffffff); +} + +void CDrawUtilities::DrawIdentBox(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w) +{ + if (bWire) + { + DU_DRAW_SH_C(EDevice.m_WireShader, clr_w); + m_WireBox.Render(); + } + if (bSolid) + { + DU_DRAW_SH_C(color_get_A(clr_s) >= 254 ? EDevice.m_WireShader : EDevice.m_SelectionShader, clr_s); + m_SolidBox.Render(); + } + DU_DRAW_RS(D3DRS_TEXTUREFACTOR, 0xffffffff); +} + +void CDrawUtilities::DrawLineSphere(const Fvector &p, float radius, u32 c, BOOL bCross) +{ + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + int i; + FVF::L *pv; + // seg 0 + pv = (FVF::L *)Stream->Lock(LINE_DIVISION + 1, vs_L->vb_stride, vBase); + for (i = 0; i < LINE_DIVISION; i++, pv++) + { + pv->p.mad(p, circledef1[i], radius); + pv->color = c; + } + pv->set(*(pv - LINE_DIVISION)); + Stream->Unlock(LINE_DIVISION + 1, vs_L->vb_stride); + DU_DRAW_DP(D3DPT_LINESTRIP, vs_L, vBase, LINE_DIVISION); + // seg 1 + pv = (FVF::L *)Stream->Lock(LINE_DIVISION + 1, vs_L->vb_stride, vBase); + for (i = 0; i < LINE_DIVISION; i++) + { + pv->p.mad(p, circledef2[i], radius); + pv->color = c; + pv++; + } + pv->set(*(pv - LINE_DIVISION)); + pv++; + Stream->Unlock(LINE_DIVISION + 1, vs_L->vb_stride); + DU_DRAW_DP(D3DPT_LINESTRIP, vs_L, vBase, LINE_DIVISION); + // seg 2 + pv = (FVF::L *)Stream->Lock(LINE_DIVISION + 1, vs_L->vb_stride, vBase); + for (i = 0; i < LINE_DIVISION; i++) + { + pv->p.mad(p, circledef3[i], radius); + pv->color = c; + pv++; + } + pv->set(*(pv - LINE_DIVISION)); + pv++; + Stream->Unlock(LINE_DIVISION + 1, vs_L->vb_stride); + DU_DRAW_DP(D3DPT_LINESTRIP, vs_L, vBase, LINE_DIVISION); + + if (bCross) + DrawCross(p, radius, radius, radius, radius, radius, radius, c); +} + +//---------------------------------------------------- +#ifdef _EDITOR +IC float _x2real(float x) +{ + return (x + 1) * EDevice.m_RenderWidth * 0.5; +} +IC float _y2real(float y) +{ + return (y + 1) * EDevice.m_RenderHeight * 0.5; +} +#else +IC float _x2real(float x) +{ + return (x + 1) * EDevice.dwWidth * 0.5f; +} +IC float _y2real(float y) +{ + return (y + 1) * EDevice.dwHeight * 0.5f; +} +#endif + +void CDrawUtilities::dbgDrawPlacement(const Fvector &p, int sz, u32 clr, LPCSTR caption, u32 clr_font) +{ + VERIFY(EDevice.b_is_Ready); + Fvector c; + float w = p.x * EDevice.mFullTransform._14 + p.y * EDevice.mFullTransform._24 + p.z * EDevice.mFullTransform._34 + EDevice.mFullTransform._44; + if (w < 0) + return; // culling + + float s = (float)sz; + EDevice.mFullTransform.transform(c, p); + c.x = (float)iFloor(_x2real(c.x)); + c.y = (float)iFloor(_y2real(-c.y)); + + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + FVF::TL *pv = (FVF::TL *)Stream->Lock(5, vs_TL->vb_stride, vBase); + pv->p.set(c.x - s, c.y - s, 0, 1); + pv->color = clr; + pv++; + pv->p.set(c.x + s, c.y - s, 0, 1); + pv->color = clr; + pv++; + pv->p.set(c.x + s, c.y + s, 0, 1); + pv->color = clr; + pv++; + pv->p.set(c.x - s, c.y + s, 0, 1); + pv->color = clr; + pv++; + pv->p.set(c.x - s, c.y - s, 0, 1); + pv->color = clr; + pv++; + Stream->Unlock(5, vs_TL->vb_stride); + + // Render it as line strip + DU_DRAW_DP(D3DPT_LINESTRIP, vs_TL, vBase, 4); + if (caption) + { + m_Font->SetColor(clr_font); + m_Font->Out(c.x, c.y + s, "%s", caption); + } +} + +void CDrawUtilities::dbgDrawVert(const Fvector &p0, u32 clr, LPCSTR caption) +{ + dbgDrawPlacement(p0, 1, clr, caption); + DrawCross(p0, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, clr, false); +} + +void CDrawUtilities::dbgDrawEdge(const Fvector &p0, const Fvector &p1, u32 clr, LPCSTR caption) +{ + dbgDrawPlacement(p0, 1, clr, caption); + DrawCross(p0, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, clr, false); + DrawCross(p1, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, clr, false); + DrawLine(p0, p1, clr); +} + +void CDrawUtilities::dbgDrawFace(const Fvector &p0, const Fvector &p1, const Fvector &p2, u32 clr, LPCSTR caption) +{ + dbgDrawPlacement(p0, 1, clr, caption); + DrawCross(p0, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, clr, false); + DrawCross(p1, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, clr, false); + DrawCross(p2, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, 0.01f, clr, false); + DrawLine(p0, p1, clr); + DrawLine(p1, p2, clr); + DrawLine(p2, p0, clr); +} +//---------------------------------------------------- + +void CDrawUtilities::DrawLine(const Fvector &p0, const Fvector &p1, u32 c) +{ + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + FVF::L *pv = (FVF::L *)Stream->Lock(2, vs_L->vb_stride, vBase); + pv->set(p0, c); + pv++; + pv->set(p1, c); + pv++; + Stream->Unlock(2, vs_L->vb_stride); + // and Render it as triangle list + DU_DRAW_DP(D3DPT_LINELIST, vs_L, vBase, 1); +} + +void CDrawUtilities::DrawSelectionBoxB(const Fbox &box, u32 *c) +{ + Fvector S, C; + box.getsize(S); + box.getcenter(C); + DrawSelectionBox(C, S, c); +} + +//---------------------------------------------------- +void CDrawUtilities::DrawSelectionBox(const Fvector &C, const Fvector &S, u32 *clr) +{ + u32 cc = (clr) ? *clr : boxcolor; + + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + FVF::L *pv = (FVF::L *)Stream->Lock(boxvertcount, vs_L->vb_stride, vBase); + for (int i = 0; i < boxvertcount; i++, pv++) + { + pv->p.mul(boxvert[i], S); + pv->p.add(C); + pv->color = cc; + } + Stream->Unlock(boxvertcount, vs_L->vb_stride); + + // and Render it as triangle list + DU_DRAW_RS(D3DRS_FILLMODE, D3DFILL_SOLID); + DU_DRAW_DP(D3DPT_LINELIST, vs_L, vBase, boxvertcount / 2); + DU_DRAW_RS(D3DRS_FILLMODE, FILL_MODE); +} + +void CDrawUtilities::DrawBox(const Fvector &offs, const Fvector &Size, BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w) +{ + _VertexStream *Stream = &RImplementation.Vertex; + if (bWire) + { + u32 vBase; + FVF::L *pv = (FVF::L *)Stream->Lock(identboxwirecount, vs_L->vb_stride, vBase); + for (int i = 0; i < identboxwirecount; i++, pv++) + { + pv->p.mul(identboxwire[i], Size); + pv->p.mul(2); + pv->p.add(offs); + pv->color = clr_w; + } + Stream->Unlock(identboxwirecount, vs_L->vb_stride); + + DU_DRAW_DP(D3DPT_LINELIST, vs_L, vBase, identboxwirecount / 2); + } + if (bSolid) + { + u32 vBase; + FVF::L *pv = (FVF::L *)Stream->Lock(DU_BOX_NUMVERTEX2, vs_L->vb_stride, vBase); + for (int i = 0; i < DU_BOX_NUMVERTEX2; i++, pv++) + { + pv->p.mul(du_box_vertices2[i], Size); + pv->p.mul(2); + pv->p.add(offs); + pv->color = clr_s; + } + Stream->Unlock(DU_BOX_NUMVERTEX2, vs_L->vb_stride); + + DU_DRAW_DP(D3DPT_TRIANGLELIST, vs_L, vBase, DU_BOX_NUMFACES); + } +} +//---------------------------------------------------- + +void CDrawUtilities::DrawOBB(const Fmatrix &parent, const Fobb &box, u32 clr_s, u32 clr_w) +{ + Fmatrix R, S, X; + box.xform_get(R); + S.scale(box.m_halfsize.x * 2.f, box.m_halfsize.y * 2.f, box.m_halfsize.z * 2.f); + X.mul_43(R, S); + R.mul_43(parent, X); + RCache.set_xform_world(R); + DrawIdentBox(true, true, clr_s, clr_w); +} +//---------------------------------------------------- + +void CDrawUtilities::DrawAABB(const Fmatrix &parent, const Fvector ¢er, const Fvector &size, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire) +{ + Fmatrix R, S; + S.scale(size.x * 2.f, size.y * 2.f, size.z * 2.f); + S.translate_over(center); + R.mul_43(parent, S); + RCache.set_xform_world(R); + DrawIdentBox(bSolid, bWire, clr_s, clr_w); +} + +void CDrawUtilities::DrawAABB(const Fvector &p0, const Fvector &p1, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire) +{ + Fmatrix R; + Fvector C; + C.set((p1.x + p0.x) * 0.5f, (p1.y + p0.y) * 0.5f, (p1.z + p0.z) * 0.5f); + R.scale(_abs(p1.x - p0.x), _abs(p1.y - p0.y), _abs(p1.z - p0.z)); + R.translate_over(C); + RCache.set_xform_world(R); + DrawIdentBox(bSolid, bWire, clr_s, clr_w); +} + +void CDrawUtilities::DrawSphere(const Fmatrix &parent, const Fvector ¢er, float radius, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire) +{ + Fmatrix B; + B.scale(radius, radius, radius); + B.translate_over(center); + B.mulA_43(parent); + RCache.set_xform_world(B); + DrawIdentSphere(bSolid, bWire, clr_s, clr_w); +} +//---------------------------------------------------- + +void CDrawUtilities::DrawFace(const Fvector &p0, const Fvector &p1, const Fvector &p2, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire) +{ + _VertexStream *Stream = &RImplementation.Vertex; + + u32 vBase; + if (bSolid) + { + FVF::L *pv = (FVF::L *)Stream->Lock(3, vs_L->vb_stride, vBase); + pv->set(p0, clr_s); + pv++; + pv->set(p1, clr_s); + pv++; + pv->set(p2, clr_s); + pv++; + Stream->Unlock(3, vs_L->vb_stride); + DU_DRAW_DP(D3DPT_TRIANGLELIST, vs_L, vBase, 1); + } + if (bWire) + { + FVF::L *pv = (FVF::L *)Stream->Lock(4, vs_L->vb_stride, vBase); + pv->set(p0, clr_w); + pv++; + pv->set(p1, clr_w); + pv++; + pv->set(p2, clr_w); + pv++; + pv->set(p0, clr_w); + pv++; + Stream->Unlock(4, vs_L->vb_stride); + DU_DRAW_DP(D3DPT_LINESTRIP, vs_L, vBase, 3); + } +} +//---------------------------------------------------- + +static const u32 MAX_VERT_COUNT = 0xFFFF; +void CDrawUtilities::DD_DrawFace_begin(BOOL bWire) +{ + VERIFY(m_DD_pv_start == 0); + m_DD_wire = bWire; + m_DD_pv_start = (FVF::L *)RImplementation.Vertex.Lock(MAX_VERT_COUNT, vs_L->vb_stride, m_DD_base); + m_DD_pv = m_DD_pv_start; +} +void CDrawUtilities::DD_DrawFace_flush(BOOL try_again) +{ + RImplementation.Vertex.Unlock((u32)(m_DD_pv - m_DD_pv_start), vs_L->vb_stride); + if (m_DD_wire) + DU_DRAW_RS(D3DRS_FILLMODE, D3DFILL_WIREFRAME); + DU_DRAW_DP(D3DPT_TRIANGLELIST, vs_L, m_DD_base, u32(m_DD_pv - m_DD_pv_start) / 3); + if (m_DD_wire) + DU_DRAW_RS(D3DRS_FILLMODE, FILL_MODE); + if (try_again) + { + m_DD_pv_start = (FVF::L *)RImplementation.Vertex.Lock(MAX_VERT_COUNT, vs_L->vb_stride, m_DD_base); + m_DD_pv = m_DD_pv_start; + } +} +void CDrawUtilities::DD_DrawFace_push(const Fvector &p0, const Fvector &p1, const Fvector &p2, u32 clr) +{ + m_DD_pv->set(p0, clr); + m_DD_pv++; + m_DD_pv->set(p1, clr); + m_DD_pv++; + m_DD_pv->set(p2, clr); + m_DD_pv++; + if (m_DD_pv - m_DD_pv_start == MAX_VERT_COUNT) + DD_DrawFace_flush(TRUE); +} +void CDrawUtilities::DD_DrawFace_end() +{ + DD_DrawFace_flush(FALSE); + m_DD_pv_start = 0; +} +//---------------------------------------------------- + +void CDrawUtilities::DrawCylinder(const Fmatrix &parent, const Fvector ¢er, const Fvector &dir, float height, float radius, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire) +{ + Fmatrix mScale; + mScale.scale(2.f * radius, 2.f * radius, height); + + // build final rotation / translation + Fvector L_dir, L_up, L_right; + L_dir.set(dir); + L_dir.normalize(); + L_up.set(0, 1, 0); + if (_abs(L_up.dotproduct(L_dir)) > .99f) + L_up.set(0, 0, 1); + L_right.crossproduct(L_up, L_dir); + L_right.normalize(); + L_up.crossproduct(L_dir, L_right); + L_up.normalize(); + + Fmatrix mR; + mR.i = L_right; + mR._14 = 0; + mR.j = L_up; + mR._24 = 0; + mR.k = L_dir; + mR._34 = 0; + mR.c = center; + mR._44 = 1; + + // final xform + Fmatrix xf; + xf.mul(mR, mScale); + xf.mulA_43(parent); + RCache.set_xform_world(xf); + DrawIdentCylinder(bSolid, bWire, clr_s, clr_w); +} +//---------------------------------------------------- + +void CDrawUtilities::DrawCone(const Fmatrix &parent, const Fvector &apex, const Fvector &dir, float height, float radius, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire) +{ + Fmatrix mScale; + mScale.scale(2.f * radius, 2.f * radius, height); + + // build final rotation / translation + Fvector L_dir, L_up, L_right; + L_dir.set(dir); + L_dir.normalize(); + L_up.set(0, 1, 0); + if (_abs(L_up.dotproduct(L_dir)) > .99f) + L_up.set(0, 0, 1); + L_right.crossproduct(L_up, L_dir); + L_right.normalize(); + L_up.crossproduct(L_dir, L_right); + L_up.normalize(); + + Fmatrix mR; + mR.i = L_right; + mR._14 = 0; + mR.j = L_up; + mR._24 = 0; + mR.k = L_dir; + mR._34 = 0; + mR.c = apex; + mR._44 = 1; + + // final xform + Fmatrix xf; + xf.mul(mR, mScale); + xf.mulA_43(parent); + RCache.set_xform_world(xf); + DrawIdentCone(bSolid, bWire, clr_s, clr_w); +} +//---------------------------------------------------- + +void CDrawUtilities::DrawPlane(const Fvector &p, const Fvector &n, const Fvector2 &scale, u32 clr_s, u32 clr_w, BOOL bCull, BOOL bSolid, BOOL bWire) +{ + if (n.square_magnitude() < EPS_S) + return; + // build final rotation / translation + Fvector L_dir, L_up = n, L_right; + L_dir.set(0, 0, 1); + if (_abs(L_up.dotproduct(L_dir)) > .99f) + L_dir.set(1, 0, 0); + L_right.crossproduct(L_up, L_dir); + L_right.normalize(); + L_dir.crossproduct(L_right, L_up); + L_dir.normalize(); + + Fmatrix mR; + mR.i = L_right; + mR._14 = 0; + mR.j = L_up; + mR._24 = 0; + mR.k = L_dir; + mR._34 = 0; + mR.c = p; + mR._44 = 1; + + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + + if (bSolid) + { + DU_DRAW_SH(EDevice.m_SelectionShader); + FVF::L *pv = (FVF::L *)Stream->Lock(5, vs_L->vb_stride, vBase); + pv->set(-scale.x, 0, -scale.y, clr_s); + mR.transform_tiny(pv->p); + pv++; + pv->set(-scale.x, 0, +scale.y, clr_s); + mR.transform_tiny(pv->p); + pv++; + pv->set(+scale.x, 0, +scale.y, clr_s); + mR.transform_tiny(pv->p); + pv++; + pv->set(+scale.x, 0, -scale.y, clr_s); + mR.transform_tiny(pv->p); + pv++; + pv->set(*(pv - 4)); + Stream->Unlock(5, vs_L->vb_stride); + if (!bCull) + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_NONE); + DU_DRAW_DP(D3DPT_TRIANGLEFAN, vs_L, vBase, 2); + if (!bCull) + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_CCW); + } + + if (bWire) + { + DU_DRAW_SH(EDevice.m_WireShader); + FVF::L *pv = (FVF::L *)Stream->Lock(5, vs_L->vb_stride, vBase); + pv->set(-scale.x, 0, -scale.y, clr_w); + mR.transform_tiny(pv->p); + pv++; + pv->set(+scale.x, 0, -scale.y, clr_w); + mR.transform_tiny(pv->p); + pv++; + pv->set(+scale.x, 0, +scale.y, clr_w); + mR.transform_tiny(pv->p); + pv++; + pv->set(-scale.x, 0, +scale.y, clr_w); + mR.transform_tiny(pv->p); + pv++; + pv->set(*(pv - 4)); + Stream->Unlock(5, vs_L->vb_stride); + DU_DRAW_DP(D3DPT_LINESTRIP, vs_L, vBase, 4); + } +} +//---------------------------------------------------- + +void CDrawUtilities::DrawPlane(const Fvector ¢er, const Fvector2 &scale, const Fvector &rotate, u32 clr_s, u32 clr_w, BOOL bCull, BOOL bSolid, BOOL bWire) +{ + Fmatrix M; + M.setHPB(rotate.y, rotate.x, rotate.z); + M.translate_over(center); + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + + if (bSolid) + { + DU_DRAW_SH(EDevice.m_SelectionShader); + FVF::L *pv = (FVF::L *)Stream->Lock(5, vs_L->vb_stride, vBase); + pv->set(-scale.x, 0, -scale.y, clr_s); + M.transform_tiny(pv->p); + pv++; + pv->set(-scale.x, 0, +scale.y, clr_s); + M.transform_tiny(pv->p); + pv++; + pv->set(+scale.x, 0, +scale.y, clr_s); + M.transform_tiny(pv->p); + pv++; + pv->set(+scale.x, 0, -scale.y, clr_s); + M.transform_tiny(pv->p); + pv++; + pv->set(*(pv - 4)); + Stream->Unlock(5, vs_L->vb_stride); + if (!bCull) + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_NONE); + DU_DRAW_DP(D3DPT_TRIANGLEFAN, vs_L, vBase, 2); + if (!bCull) + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_CCW); + } + + if (bWire) + { + DU_DRAW_SH(EDevice.m_WireShader); + FVF::L *pv = (FVF::L *)Stream->Lock(5, vs_L->vb_stride, vBase); + pv->set(-scale.x, 0, -scale.y, clr_w); + M.transform_tiny(pv->p); + pv++; + pv->set(+scale.x, 0, -scale.y, clr_w); + M.transform_tiny(pv->p); + pv++; + pv->set(+scale.x, 0, +scale.y, clr_w); + M.transform_tiny(pv->p); + pv++; + pv->set(-scale.x, 0, +scale.y, clr_w); + M.transform_tiny(pv->p); + pv++; + pv->set(*(pv - 4)); + Stream->Unlock(5, vs_L->vb_stride); + DU_DRAW_DP(D3DPT_LINESTRIP, vs_L, vBase, 4); + } +} +//---------------------------------------------------- + +void CDrawUtilities::DrawRectangle(const Fvector &o, const Fvector &u, const Fvector &v, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire) +{ + _VertexStream *Stream = &RImplementation.Vertex; + + u32 vBase; + if (bSolid) + { + DU_DRAW_SH(EDevice.m_SelectionShader); + FVF::L *pv = (FVF::L *)Stream->Lock(6, vs_L->vb_stride, vBase); + pv->set(o.x, o.y, o.z, clr_s); + pv++; + pv->set(o.x + u.x + v.x, o.y + u.y + v.y, o.z + u.z + v.z, clr_s); + pv++; + pv->set(o.x + v.x, o.y + v.y, o.z + v.z, clr_s); + pv++; + pv->set(o.x, o.y, o.z, clr_s); + pv++; + pv->set(o.x + u.x, o.y + u.y, o.z + u.z, clr_s); + pv++; + pv->set(o.x + u.x + v.x, o.y + u.y + v.y, o.z + u.z + v.z, clr_s); + pv++; + Stream->Unlock(6, vs_L->vb_stride); + DU_DRAW_DP(D3DPT_TRIANGLELIST, vs_L, vBase, 2); + } + if (bWire) + { + DU_DRAW_SH(EDevice.m_WireShader); + FVF::L *pv = (FVF::L *)Stream->Lock(5, vs_L->vb_stride, vBase); + pv->set(o.x, o.y, o.z, clr_w); + pv++; + pv->set(o.x + u.x, o.y + u.y, o.z + u.z, clr_w); + pv++; + pv->set(o.x + u.x + v.x, o.y + u.y + v.y, o.z + u.z + v.z, clr_w); + pv++; + pv->set(o.x + v.x, o.y + v.y, o.z + v.z, clr_w); + pv++; + pv->set(o.x, o.y, o.z, clr_w); + pv++; + Stream->Unlock(5, vs_L->vb_stride); + DU_DRAW_DP(D3DPT_LINESTRIP, vs_L, vBase, 4); + } +} +//---------------------------------------------------- + +void CDrawUtilities::DrawCross(const Fvector &p, float szx1, float szy1, float szz1, float szx2, float szy2, float szz2, u32 clr, BOOL bRot45) +{ + _VertexStream *Stream = &RImplementation.Vertex; + // actual rendering + u32 vBase; + FVF::L *pv = (FVF::L *)Stream->Lock(bRot45 ? 12 : 6, vs_L->vb_stride, vBase); + pv->set(p.x + szx2, p.y, p.z, clr); + pv++; + pv->set(p.x - szx1, p.y, p.z, clr); + pv++; + pv->set(p.x, p.y + szy2, p.z, clr); + pv++; + pv->set(p.x, p.y - szy1, p.z, clr); + pv++; + pv->set(p.x, p.y, p.z + szz2, clr); + pv++; + pv->set(p.x, p.y, p.z - szz1, clr); + pv++; + if (bRot45) + { + Fmatrix M; + M.setHPB(PI_DIV_4, PI_DIV_4, PI_DIV_4); + for (int i = 0; i < 6; i++, pv++) + { + pv->p.sub((pv - 6)->p, p); + M.transform_dir(pv->p); + pv->p.add(p); + pv->color = clr; + } + } + // unlock VB and Render it as triangle list + Stream->Unlock(bRot45 ? 12 : 6, vs_L->vb_stride); + DU_DRAW_DP(D3DPT_LINELIST, vs_L, vBase, bRot45 ? 6 : 3); +} + +void CDrawUtilities::DrawPivot(const Fvector &pos, float sz) +{ + DU_DRAW_SH(EDevice.m_WireShader); + DrawCross(pos, sz, sz, sz, sz, sz, sz, 0xFF7FFF7F); +} + +void CDrawUtilities::DrawAxis(const Fmatrix &T) +{ + if (!m_axis_object) + m_axis_object = Lib.CreateEditObject("editor\\axis"); + + R_ASSERT(m_axis_object); + + Fmatrix M = Fidentity; + Fmatrix S; + S.scale(0.04f, 0.04f, 0.04f); + M.mulB_44(S); + + Fvector start, dir; + Ivector2 pt; + + static int _wh = 50; + static float _kl = 1.0f; + + pt.x = _wh; + pt.y = UI->GetRenderHeight() - _wh; + + EDevice.m_Camera.MouseRayFromPoint(M.c, dir, pt); + M.c.mad(dir, _kl); + m_axis_object->Render(M, 2, false); +} + +void CDrawUtilities::DrawObjectAxis(const Fmatrix &T, float sz, BOOL sel) +{ + VERIFY(EDevice.b_is_Ready); + + _VertexStream *Stream = &RImplementation.Vertex; + Fvector c, r, n, d; + float w = T.c.x * EDevice.mFullTransform._14 + T.c.y * EDevice.mFullTransform._24 + T.c.z * EDevice.mFullTransform._34 + EDevice.mFullTransform._44; + + if (w < 0) + return; // culling + + float s = w * sz; + + EDevice.mFullTransform.transform(c, T.c); + r.mul(T.i, s); + r.add(T.c); + EDevice.mFullTransform.transform(r); + n.mul(T.j, s); + n.add(T.c); + EDevice.mFullTransform.transform(n); + d.mul(T.k, s); + d.add(T.c); + EDevice.mFullTransform.transform(d); + c.x = (float)iFloor(_x2real(c.x)); + c.y = (float)iFloor(_y2real(-c.y)); + r.x = (float)iFloor(_x2real(r.x)); + r.y = (float)iFloor(_y2real(-r.y)); + n.x = (float)iFloor(_x2real(n.x)); + n.y = (float)iFloor(_y2real(-n.y)); + d.x = (float)iFloor(_x2real(d.x)); + d.y = (float)iFloor(_y2real(-d.y)); + + u32 vBase; + FVF::TL *pv = (FVF::TL *)Stream->Lock(6, vs_TL->vb_stride, vBase); + + pv->set(c.x, c.y, 0, 1, 0xFF222222, 0, 0); + pv++; + pv->set(d.x, d.y, 0, 1, sel ? 0xFF0000FF : 0xFF000080, 0, 0); + pv++; + pv->set(c.x, c.y, 0, 1, 0xFF222222, 0, 0); + pv++; + pv->set(r.x, r.y, 0, 1, sel ? 0xFFFF0000 : 0xFF800000, 0, 0); + pv++; + pv->set(c.x, c.y, 0, 1, 0xFF222222, 0, 0); + pv++; + pv->set(n.x, n.y, 0, 1, sel ? 0xFF00FF00 : 0xFF008000, 0, 0); + + Stream->Unlock(6, vs_TL->vb_stride); + + // Render it as line list + DU_DRAW_RS(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); + DU_DRAW_SH(EDevice.m_WireShader); + DU_DRAW_DP(D3DPT_LINELIST, vs_TL, vBase, 3); + DU_DRAW_RS(D3DRS_SHADEMODE, SHADE_MODE); + + m_Font->SetColor(sel ? 0xFF000000 : 0xFF909090); + m_Font->Out(r.x, r.y, "x"); + m_Font->Out(n.x, n.y, "y"); + m_Font->Out(d.x, d.y, "z"); + m_Font->SetColor(sel ? 0xFFFFFFFF : 0xFF000000); + m_Font->Out(r.x - 1, r.y - 1, "x"); + m_Font->Out(n.x - 1, n.y - 1, "y"); + m_Font->Out(d.x - 1, d.y - 1, "z"); +} + +void CDrawUtilities::DrawGrid() +{ + VERIFY(EDevice.b_is_Ready); + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + // fill VB + FVF::L *pv = (FVF::L *)Stream->Lock(m_GridPoints.size(), vs_L->vb_stride, vBase); + for (FLvertexIt v_it = m_GridPoints.begin(); v_it != m_GridPoints.end(); v_it++, pv++) + pv->set(*v_it); + Stream->Unlock(m_GridPoints.size(), vs_L->vb_stride); + // Render it as triangle list + Fmatrix ddd; + ddd.identity(); + RCache.set_xform_world(ddd); + DU_DRAW_SH(EDevice.m_WireShader); + DU_DRAW_DP(D3DPT_LINELIST, vs_L, vBase, m_GridPoints.size() / 2); +} + +void CDrawUtilities::DrawSelectionRect(const Ivector2 &m_SelStart, const Ivector2 &m_SelEnd) +{ + VERIFY(EDevice.b_is_Ready); + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + FVF::TL *pv = (FVF::TL *)Stream->Lock(4, vs_TL->vb_stride, vBase); + pv->set(m_SelStart.x * SCREEN_QUALITY, m_SelStart.y * SCREEN_QUALITY, m_SelectionRect, 0.f, 0.f); + pv++; + pv->set(m_SelStart.x * SCREEN_QUALITY, m_SelEnd.y * SCREEN_QUALITY, m_SelectionRect, 0.f, 0.f); + pv++; + pv->set(m_SelEnd.x * SCREEN_QUALITY, m_SelEnd.y * SCREEN_QUALITY, m_SelectionRect, 0.f, 0.f); + pv++; + pv->set(m_SelEnd.x * SCREEN_QUALITY, m_SelStart.y * SCREEN_QUALITY, m_SelectionRect, 0.f, 0.f); + pv++; + Stream->Unlock(4, vs_TL->vb_stride); + // Render it as triangle list + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_NONE); + DU_DRAW_SH(EDevice.m_SelectionShader); + DU_DRAW_DP(D3DPT_TRIANGLEFAN, vs_TL, vBase, 2); + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_CCW); +} + +void CDrawUtilities::DrawPrimitiveL(D3DPRIMITIVETYPE pt, u32 pc, Fvector *vertices, int vc, u32 color, BOOL bCull, BOOL bCycle) +{ + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase, dwNeed = (bCycle) ? vc + 1 : vc; + FVF::L *pv = (FVF::L *)Stream->Lock(dwNeed, vs_L->vb_stride, vBase); + for (int k = 0; k < vc; k++, pv++) + pv->set(vertices[k], color); + if (bCycle) + pv->set(*(pv - vc)); + Stream->Unlock(dwNeed, vs_L->vb_stride); + + if (!bCull) + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_NONE); + DU_DRAW_DP(pt, vs_L, vBase, pc); + if (!bCull) + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_CCW); +} + +void CDrawUtilities::DrawIndexedPrimitive(int pt, + u32 pc, + const Fvector &pos, + const Fvector *vb, + const u32 &vb_size, + const u32 *ib, + const u32 &ib_size, + const u32 &clr_argb, + float scale) +{ + _VertexStream *Stream = &RImplementation.Vertex; + _IndexStream *StreamI = &RImplementation.Index; + + u32 vBase, iBase; + WORD *i; + + FVF::L *pv = (FVF::L *)Stream->Lock(vb_size, vs_L->vb_stride, vBase); + for (int k = 0; k < vb_size; ++k, ++pv) + pv->set(Fvector().add(pos, Fvector().mul(vb[k], scale)), clr_argb); + + Stream->Unlock(vb_size, vs_L->vb_stride); + + i = StreamI->Lock(ib_size, iBase); + for (int k = 0; k < ib_size; ++k, ++i) + *i = ib[k]; + + StreamI->Unlock(ib_size); + + EDevice.SetShader(EDevice.m_SelectionShader); + // and Render it as triangle list + DU_DRAW_DIP((D3DPRIMITIVETYPE)pt, vs_L, vBase, 0, vb_size, iBase, pc); +} + +void CDrawUtilities::DrawPrimitiveTL(D3DPRIMITIVETYPE pt, u32 pc, FVF::TL *vertices, int vc, BOOL bCull, BOOL bCycle) +{ + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase, dwNeed = (bCycle) ? vc + 1 : vc; + FVF::TL *pv = (FVF::TL *)Stream->Lock(dwNeed, vs_TL->vb_stride, vBase); + for (int k = 0; k < vc; k++, pv++) + pv->set(vertices[k]); + if (bCycle) + pv->set(*(pv - vc)); + Stream->Unlock(dwNeed, vs_TL->vb_stride); + + if (!bCull) + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_NONE); + DU_DRAW_DP(pt, vs_TL, vBase, pc); + if (!bCull) + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_CCW); +} + +void CDrawUtilities::DrawPrimitiveLIT(D3DPRIMITIVETYPE pt, u32 pc, FVF::LIT *vertices, int vc, BOOL bCull, BOOL bCycle) +{ + // fill VB + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase, dwNeed = (bCycle) ? vc + 1 : vc; + FVF::LIT *pv = (FVF::LIT *)Stream->Lock(dwNeed, vs_LIT->vb_stride, vBase); + for (int k = 0; k < vc; k++, pv++) + pv->set(vertices[k]); + if (bCycle) + pv->set(*(pv - vc)); + Stream->Unlock(dwNeed, vs_LIT->vb_stride); + + if (!bCull) + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_NONE); + DU_DRAW_DP(pt, vs_LIT, vBase, pc); + if (!bCull) + DU_DRAW_RS(D3DRS_CULLMODE, D3DCULL_CCW); +} + +void CDrawUtilities::DrawLink(const Fvector &p0, const Fvector &p1, float sz, u32 clr) +{ + if (p0.similar(p1)) + return; + + DrawLine(p1, p0, clr); + Fvector pp[2], D, R, N = {0, 1, 0}; + D.sub(p1, p0); + D.normalize(); + R.crossproduct(N, D); + R.mul(0.5f); + D.mul(2.0f); + N.mul(0.5f); + // LR + pp[0].add(R, D); + pp[0].mul(sz * -0.5f); + pp[0].add(p1); + R.invert(); + pp[1].add(R, D); + pp[1].mul(sz * -0.5f); + pp[1].add(p1); + DrawLine(p1, pp[0], clr); + DrawLine(p1, pp[1], clr); + // UB + pp[0].add(N, D); + pp[0].mul(sz * -0.5f); + pp[0].add(p1); + N.invert(); + pp[1].add(N, D); + pp[1].mul(sz * -0.5f); + pp[1].add(p1); + DrawLine(p1, pp[0], clr); + DrawLine(p1, pp[1], clr); +} + +void CDrawUtilities::DrawJoint(const Fvector &p, float radius, u32 clr) +{ + // RCache.set_xform_world (Fidentity); + DrawLineSphere(p, radius, clr, false); +} + +void CDrawUtilities::OnRender() +{ + m_Font->OnRender(); +} + +void CDrawUtilities::OutText(const Fvector &pos, LPCSTR text, u32 color, u32 shadow_color) +{ + Fvector p; + float w = pos.x * EDevice.mFullTransform._14 + pos.y * EDevice.mFullTransform._24 + pos.z * EDevice.mFullTransform._34 + EDevice.mFullTransform._44; + if (w >= 0) + { + EDevice.mFullTransform.transform(p, pos); + p.x = (float)iFloor(_x2real(p.x)); + p.y = (float)iFloor(_y2real(-p.y)); + + m_Font->SetColor(shadow_color); + m_Font->Out(p.x, p.y, (LPSTR)text); + m_Font->SetColor(color); + m_Font->Out(p.x - 1, p.y - 1, (LPSTR)text); + } +} diff --git a/src/editors/xrECore/Editor/D3DUtils.h b/src/editors/xrECore/Editor/D3DUtils.h new file mode 100644 index 00000000000..492094ae2f1 --- /dev/null +++ b/src/editors/xrECore/Editor/D3DUtils.h @@ -0,0 +1,172 @@ +//---------------------------------------------------- +// file: D3DUtils.h +//---------------------------------------------------- + +#ifndef D3DUtilsH_included +#define D3DUtilsH_included + +#include "Include/xrRender/DrawUtils.h" +//---------------------------------------------------- + +#ifdef _EDITOR +#define DU_DRAW_DIP EDevice.DIP +#define DU_DRAW_DP EDevice.DP +#else +#define DU_DRAW_DIP RCache.dbg_DIP +#define DU_DRAW_DP RCache.dbg_DP +#endif + +class CEditableObject; + +struct SPrimitiveBuffer +{ + ref_geom pGeom; + u32 v_cnt; + u32 i_cnt; + D3DPRIMITIVETYPE p_type; + u32 p_cnt; + typedef fastdelegate::FastDelegate0<> TOnRender; + TOnRender OnRender; + void RenderDIP() { DU_DRAW_DIP(p_type, pGeom, 0, 0, v_cnt, 0, p_cnt); } + void RenderDP() { DU_DRAW_DP(p_type, pGeom, 0, p_cnt); } + +public: + SPrimitiveBuffer() : OnRender(0), pGeom(0) { ; } + void CreateFromData(D3DPRIMITIVETYPE _pt, u32 _p_cnt, u32 FVF, LPVOID vertices, u32 _v_cnt, u16 *indices = 0, u32 _i_cnt = 0); + void Destroy(); + void Render() { OnRender(); } +}; + +//---------------------------------------------------- +// Utilities +//---------------------------------------------------- +class ECORE_API CDrawUtilities : public CDUInterface, public pureRender +{ + SPrimitiveBuffer m_SolidCone; + SPrimitiveBuffer m_WireCone; + SPrimitiveBuffer m_SolidSphere; + SPrimitiveBuffer m_WireSphere; + SPrimitiveBuffer m_SolidSpherePart; + SPrimitiveBuffer m_WireSpherePart; + SPrimitiveBuffer m_SolidCylinder; + SPrimitiveBuffer m_WireCylinder; + SPrimitiveBuffer m_SolidBox; + SPrimitiveBuffer m_WireBox; + CGameFont *m_Font; + CEditableObject *m_axis_object; + +public: + ref_geom vs_L; + ref_geom vs_TL; + ref_geom vs_LIT; + +protected: + FVF::L *m_DD_pv; + FVF::L *m_DD_pv_start; + u32 m_DD_base; + BOOL m_DD_wire; + void DD_DrawFace_flush(BOOL try_again); + +public: + void DD_DrawFace_begin(BOOL bWire); + void DD_DrawFace_push(const Fvector &p0, const Fvector &p1, const Fvector &p2, u32 clr); + void DD_DrawFace_end(); + +public: + CDrawUtilities() + { + vs_L = 0; + vs_TL = 0; + vs_LIT = 0; + m_DD_pv = 0; + m_DD_pv_start = 0; + m_DD_base = 0; + m_Font = 0; + } + + void OnDeviceCreate(); + void DestroyObjects(); + void OnDeviceDestroy(); + + void UpdateGrid(int number_of_cell, float square_size, int subdiv = 10); + + //---------------------------------------------------- + virtual void DrawCross(const Fvector &p, float szx1, float szy1, float szz1, float szx2, float szy2, float szz2, u32 clr, BOOL bRot45 = false); + virtual void DrawCross(const Fvector &p, float sz, u32 clr, BOOL bRot45 = false) { DrawCross(p, sz, sz, sz, sz, sz, sz, clr, bRot45); } + virtual void DrawEntity(u32 clr, ref_shader s); + virtual void DrawFlag(const Fvector &p, float heading, float height, float sz, float sz_fl, u32 clr, BOOL bDrawEntity); + virtual void DrawRomboid(const Fvector &p, float radius, u32 clr); + virtual void DrawJoint(const Fvector &p, float radius, u32 clr); + + virtual void DrawSpotLight(const Fvector &p, const Fvector &d, float range, float phi, u32 clr); + virtual void DrawDirectionalLight(const Fvector &p, const Fvector &d, float radius, float range, u32 clr); + virtual void DrawPointLight(const Fvector &p, float radius, u32 clr); + + virtual void DrawSound(const Fvector &p, float radius, u32 clr); + virtual void DrawLineSphere(const Fvector &p, float radius, u32 clr, BOOL bCross); + + virtual void dbgDrawPlacement(const Fvector &p, int sz, u32 clr, LPCSTR caption = 0, u32 clr_font = 0xffffffff); + virtual void dbgDrawVert(const Fvector &p0, u32 clr, LPCSTR caption = 0); + virtual void dbgDrawEdge(const Fvector &p0, const Fvector &p1, u32 clr, LPCSTR caption = 0); + virtual void dbgDrawFace(const Fvector &p0, const Fvector &p1, const Fvector &p2, u32 clr, LPCSTR caption = 0); + + virtual void DrawFace(const Fvector &p0, const Fvector &p1, const Fvector &p2, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); + virtual void DrawLine(const Fvector &p0, const Fvector &p1, u32 clr); + virtual void DrawLink(const Fvector &p0, const Fvector &p1, float sz, u32 clr); + IC virtual void DrawFaceNormal(const Fvector &p0, const Fvector &p1, const Fvector &p2, float size, u32 clr) + { + Fvector N, C, P; + N.mknormal(p0, p1, p2); + C.set(p0); + C.add(p1); + C.add(p2); + C.div(3); + P.mad(C, N, size); + DrawLine(C, P, clr); + } + IC virtual void DrawFaceNormal(const Fvector *p, float size, u32 clr) { DrawFaceNormal(p[0], p[1], p[2], size, clr); } + IC virtual void DrawFaceNormal(const Fvector &C, const Fvector &N, float size, u32 clr) + { + Fvector P; + P.mad(C, N, size); + DrawLine(C, P, clr); + } + virtual void DrawSelectionBox(const Fvector ¢er, const Fvector &size, u32 *c = 0); + virtual void DrawSelectionBoxB(const Fbox &box, u32 *c = 0); + + virtual void DrawIdentSphere(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); + virtual void DrawIdentSpherePart(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); + virtual void DrawIdentCone(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); + virtual void DrawIdentCylinder(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); + virtual void DrawIdentBox(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); + + virtual void DrawBox(const Fvector &offs, const Fvector &Size, BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); + virtual void DrawAABB(const Fvector &p0, const Fvector &p1, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); + virtual void DrawAABB(const Fmatrix &parent, const Fvector ¢er, const Fvector &size, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); + virtual void DrawOBB(const Fmatrix &parent, const Fobb &box, u32 clr_s, u32 clr_w); + virtual void DrawSphere(const Fmatrix &parent, const Fvector ¢er, float radius, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); + virtual void DrawSphere(const Fmatrix &parent, const Fsphere &S, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire) { DrawSphere(parent, S.P, S.R, clr_s, clr_w, bSolid, bWire); } + virtual void DrawCylinder(const Fmatrix &parent, const Fvector ¢er, const Fvector &dir, float height, float radius, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); + virtual void DrawCone(const Fmatrix &parent, const Fvector &apex, const Fvector &dir, float height, float radius, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); + virtual void DrawPlane(const Fvector ¢er, const Fvector2 &scale, const Fvector &rotate, u32 clr_s, u32 clr_w, BOOL bCull, BOOL bSolid, BOOL bWire); + virtual void DrawPlane(const Fvector &p, const Fvector &n, const Fvector2 &scale, u32 clr_s, u32 clr_w, BOOL bCull, BOOL bSolid, BOOL bWire); + virtual void DrawRectangle(const Fvector &o, const Fvector &u, const Fvector &v, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); + + virtual void DrawGrid(); + virtual void DrawPivot(const Fvector &pos, float sz = 5.f); + virtual void DrawAxis(const Fmatrix &T); + virtual void DrawObjectAxis(const Fmatrix &T, float sz, BOOL sel); + virtual void DrawSelectionRect(const Ivector2 &m_SelStart, const Ivector2 &m_SelEnd); + virtual void DrawIndexedPrimitive(int pt, u32 pc, const Fvector &pos, const Fvector *vb, const u32 &vb_size, const u32 *ib, const u32 &ib_size, const u32 &clr_argb, float scale = 1.0f); + + virtual void DrawPrimitiveL(D3DPRIMITIVETYPE pt, u32 pc, Fvector *vertices, int vc, u32 color, BOOL bCull, BOOL bCycle); + virtual void DrawPrimitiveTL(D3DPRIMITIVETYPE pt, u32 pc, FVF::TL *vertices, int vc, BOOL bCull, BOOL bCycle); + virtual void DrawPrimitiveLIT(D3DPRIMITIVETYPE pt, u32 pc, FVF::LIT *vertices, int vc, BOOL bCull, BOOL bCycle); + + virtual void OutText(const Fvector &pos, LPCSTR text, u32 color = 0xFF000000, u32 shadow_color = 0xFF909090); + + virtual void OnRender(); +}; +extern ECORE_API CDrawUtilities DU_impl; +//---------------------------------------------------- +#endif /*_INCDEF_D3DUtils_H_*/ diff --git a/src/editors/xrECore/Editor/D3DX_Wrapper.h b/src/editors/xrECore/Editor/D3DX_Wrapper.h new file mode 100644 index 00000000000..46a01c06285 --- /dev/null +++ b/src/editors/xrECore/Editor/D3DX_Wrapper.h @@ -0,0 +1,208 @@ +#ifndef D3DX_WraperH +#define D3DX_WraperH +#pragma once + +#ifdef ETOOLS_EXPORTS +#define ETOOLS_API __declspec(dllexport) +#else +#define ETOOLS_API __declspec(dllimport) +#endif +// +//extern "C" +//{ +// ETOOLS_API UINT WINAPI +// D3DX_GetDriverLevel( +// LPDIRECT3DDEVICE9 pDevice); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_GetImageInfoFromFileInMemory( +// LPCVOID pSrcData, +// UINT SrcDataSize, +// D3DXIMAGE_INFO *pSrcInfo); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_CreateCubeTextureFromFileInMemoryEx( +// LPDIRECT3DDEVICE9 pDevice, +// LPCVOID pSrcData, +// UINT SrcDataSize, +// UINT Size, +// UINT MipLevels, +// DWORD Usage, +// D3DFORMAT Format, +// D3DPOOL Pool, +// DWORD Filter, +// DWORD MipFilter, +// D3DCOLOR ColorKey, +// D3DXIMAGE_INFO *pSrcInfo, +// PALETTEENTRY *pPalette, +// LPDIRECT3DCUBETEXTURE9 *ppCubeTexture); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_CreateTextureFromFileInMemoryEx( +// LPDIRECT3DDEVICE9 pDevice, +// LPCVOID pSrcData, +// UINT SrcDataSize, +// UINT Width, +// UINT Height, +// UINT MipLevels, +// DWORD Usage, +// D3DFORMAT Format, +// D3DPOOL Pool, +// DWORD Filter, +// DWORD MipFilter, +// D3DCOLOR ColorKey, +// D3DXIMAGE_INFO *pSrcInfo, +// PALETTEENTRY *pPalette, +// LPDIRECT3DTEXTURE9 *ppTexture); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_CreateTexture( +// LPDIRECT3DDEVICE9 pDevice, +// UINT Width, +// UINT Height, +// UINT MipLevels, +// DWORD Usage, +// D3DFORMAT Format, +// D3DPOOL Pool, +// LPDIRECT3DTEXTURE9 *ppTexture); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_ComputeNormalMap( +// LPDIRECT3DTEXTURE9 pTexture, +// LPDIRECT3DTEXTURE9 pSrcTexture, +// const PALETTEENTRY *pSrcPalette, +// DWORD Flags, +// DWORD Channel, +// FLOAT Amplitude); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_LoadSurfaceFromSurface( +// LPDIRECT3DSURFACE9 pDestSurface, +// CONST PALETTEENTRY *pDestPalette, +// CONST RECT *pDestRect, +// LPDIRECT3DSURFACE9 pSrcSurface, +// CONST PALETTEENTRY *pSrcPalette, +// CONST RECT *pSrcRect, +// DWORD Filter, +// D3DCOLOR ColorKey); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_CompileShader( +// LPCSTR pSrcData, +// UINT SrcDataLen, +// CONST D3DXMACRO *pDefines, +// LPD3DXINCLUDE pInclude, +// LPCSTR pFunctionName, +// LPCSTR pTarget, +// DWORD Flags, +// LPD3DXBUFFER *ppShader, +// LPD3DXBUFFER *ppErrorMsgs, +// LPD3DXCONSTANTTABLE *ppConstantTable); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_CompileShaderFromFile( +// LPCSTR pSrcFile, +// CONST D3DXMACRO *pDefines, +// LPD3DXINCLUDE pInclude, +// LPCSTR pFunctionName, +// LPCSTR pTarget, +// DWORD Flags, +// LPD3DXBUFFER *ppShader, +// LPD3DXBUFFER *ppErrorMsgs, +// LPD3DXCONSTANTTABLE *ppConstantTable); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_FindShaderComment( +// CONST DWORD *pFunction, +// DWORD FourCC, +// LPCVOID *ppData, +// UINT *pSizeInBytes); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_DeclaratorFromFVF( +// DWORD FVF, +// D3DVERTEXELEMENT9 pDeclarator[MAX_FVF_DECL_SIZE]); +// +// ETOOLS_API UINT WINAPI +// D3DX_GetDeclVertexSize( +// CONST D3DVERTEXELEMENT9 *pDecl, +// DWORD Stream); +// +// ETOOLS_API UINT WINAPI +// D3DX_GetDeclLength( +// CONST D3DVERTEXELEMENT9 *pDecl); +// +// ETOOLS_API UINT WINAPI +// D3DX_GetFVFVertexSize( +// DWORD FVF); +// +// ETOOLS_API const char *WINAPI +// DX_GetErrorDescription9( +// HRESULT hr); +// +// ETOOLS_API D3DXMATRIX *WINAPI +// D3DX_MatrixInverse( +// D3DXMATRIX *pOut, +// FLOAT *pDeterminant, +// CONST D3DXMATRIX *pM); +// +// ETOOLS_API D3DXMATRIX *WINAPI +// D3DX_MatrixTranspose( +// D3DXMATRIX *pOut, +// CONST D3DXMATRIX *pM); +// +// ETOOLS_API D3DXPLANE *WINAPI +// D3DX_PlaneNormalize( +// D3DXPLANE *pOut, +// CONST D3DXPLANE *pP); +// +// ETOOLS_API D3DXPLANE *WINAPI +// D3DX_PlaneTransform( +// D3DXPLANE *pOut, +// CONST D3DXPLANE *pP, +// CONST D3DXMATRIX *pM); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_OptimizeFaces( +// LPCVOID pIndices, +// UINT NumFaces, +// UINT NumVertices, +// BOOL Indices32Bit, +// DWORD *pFaceRemap); +// +// ETOOLS_API HRESULT WINAPI +// D3DX_OptimizeVertices( +// LPCVOID pIndices, +// UINT NumFaces, +// UINT NumVertices, +// BOOL Indices32Bit, +// DWORD *pVertexRemap); +//} + +#ifndef ETOOLS_EXPORTS +#undef D3DXCompileShaderFromFile +#undef DXGetErrorDescription9 +#define D3DXGetDriverLevel D3DX_GetDriverLevel +#define D3DXGetImageInfoFromFileInMemory D3DX_GetImageInfoFromFileInMemory +#define D3DXCreateCubeTextureFromFileInMemoryEx D3DX_CreateCubeTextureFromFileInMemoryEx +#define D3DXCreateTextureFromFileInMemoryEx D3DX_CreateTextureFromFileInMemoryEx +#define D3DXCreateTexture D3DX_CreateTexture +#define D3DXComputeNormalMap D3DX_ComputeNormalMap +#define D3DXLoadSurfaceFromSurface D3DX_LoadSurfaceFromSurface +#define D3DXCompileShaderFromFile D3DX_CompileShaderFromFile +#define D3DXCompileShader D3DX_CompileShader +#define D3DXFindShaderComment D3DX_FindShaderComment +#define D3DXDeclaratorFromFVF D3DX_DeclaratorFromFVF +#define D3DXGetDeclVertexSize D3DX_GetDeclVertexSize +#define D3DXGetDeclLength D3DX_GetDeclLength +#define D3DXGetFVFVertexSize D3DX_GetFVFVertexSize +#define DXGetErrorDescription9 DX_GetErrorDescription9 +#define D3DXMatrixInverse D3DX_MatrixInverse +#define D3DXMatrixTranspose D3DX_MatrixTranspose +#define D3DXPlaneNormalize D3DX_PlaneNormalize +#define D3DXPlaneTransform D3DX_PlaneTransform +#define D3DXOptimizeFaces D3DX_OptimizeFaces +#define D3DXOptimizeVertices D3DX_OptimizeVertices +#endif + +#endif diff --git a/src/editors/xrECore/Editor/DeviceScreenshot.cpp b/src/editors/xrECore/Editor/DeviceScreenshot.cpp new file mode 100644 index 00000000000..6c688de9211 --- /dev/null +++ b/src/editors/xrECore/Editor/DeviceScreenshot.cpp @@ -0,0 +1,66 @@ +#include "stdafx.h" +#include "ui_toolscustom.h" +#include "ui_main.h" +#include "Layers/xrRender/ResourceManager.h" + +bool CEditorRenderDevice::MakeScreenshot(U32Vec &pixels, u32 width, u32 height) +{ + if (!b_is_Ready) + return false; + + // free managed resource + Resources->Evict(); + + IDirect3DSurface9 *poldZB = 0; + IDirect3DSurface9 *pZB = 0; + IDirect3DSurface9 *pRT = 0; + IDirect3DSurface9 *poldRT = 0; + D3DVIEWPORT9 oldViewport; + SetRS(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED); + CHK_DX(HW.pDevice->GetRenderTarget(0, &poldRT)); + CHK_DX(HW.pDevice->GetDepthStencilSurface(&poldZB)); + CHK_DX(HW.pDevice->GetViewport(&oldViewport)); + + CHK_DX(HW.pDevice->CreateRenderTarget(width, height, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, FALSE, &pRT, 0)); + CHK_DX(HW.pDevice->CreateDepthStencilSurface(width, height, HW.Caps.bStencil ? D3DFMT_D24S8 : D3DFMT_D24X8, D3DMULTISAMPLE_NONE, 0, FALSE, &pZB, 0)); + CHK_DX(HW.pDevice->SetRenderTarget(0, pRT)); + CHK_DX(HW.pDevice->SetDepthStencilSurface(pZB)); + + UI->PrepareRedraw(); + EDevice.Begin(); + Tools->Render(); + EDevice.End(); + + // Create temp-surface + IDirect3DSurface9 *pFB; + R_CHK(HW.pDevice->CreateOffscreenPlainSurface( + width, height, D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM, &pFB, NULL)); + R_CHK(HW.pDevice->GetRenderTargetData(pRT, pFB)); + + D3DLOCKED_RECT D; + R_CHK(pFB->LockRect(&D, 0, D3DLOCK_NOSYSLOCK)); + pixels.resize(width * height); + // Image processing + u32 *pPixel = (u32 *)D.pBits; + + u32 *it = pixels.data(); + for (int h = height - 1; h >= 0; h--, it += width) + { + LPDWORD dt = LPDWORD(size_t(pPixel) + size_t(D.Pitch * h)); + CopyMemory(it, dt, sizeof(u32) * width); + } + + R_CHK(pFB->UnlockRect()); + + CHK_DX(HW.pDevice->SetDepthStencilSurface(poldZB)); + CHK_DX(HW.pDevice->SetRenderTarget(0, poldRT)); + CHK_DX(HW.pDevice->SetViewport(&oldViewport)); + + _RELEASE(pZB); + _RELEASE(poldZB); + _RELEASE(pFB); + _RELEASE(pRT); + _RELEASE(poldRT); + + return true; +} diff --git a/src/editors/xrECore/Editor/EDetailModel.cpp b/src/editors/xrECore/Editor/EDetailModel.cpp new file mode 100644 index 00000000000..50e8f08bb43 --- /dev/null +++ b/src/editors/xrECore/Editor/EDetailModel.cpp @@ -0,0 +1,294 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "EDetailModel.h" +#include "Library.h" +#include "EditObject.h" +#include "EditMesh.h" +#include "ImageManager.h" + +//------------------------------------------------------------------------------ +#define DETOBJ_CHUNK_VERSION 0x1000 +#define DETOBJ_CHUNK_REFERENCE 0x0101 +#define DETOBJ_CHUNK_SCALE_LIMITS 0x0102 +#define DETOBJ_CHUNK_DENSITY_FACTOR 0x0103 +#define DETOBJ_CHUNK_FLAGS 0x0104 + +#define DETOBJ_VERSION 0x0001 +//------------------------------------------------------------------------------ +void EDetail::EVertexIn::remapUV(const fvfVertexIn &src, const Fvector2 &offs, const Fvector2 &scale, bool bRotate) +{ + P.set(src.P); + ImageLib.MergedTextureRemapUV(u, v, src.u, src.v, offs, scale, bRotate); +} + +EDetail::EDetail() +{ + shader = 0; + m_Flags.zero(); + m_pRefs = 0; + m_fMinScale = 0.5f; + m_fMaxScale = 2.f; + m_fDensityFactor = 1.f; + m_sRefs = ""; + vertices = 0; + number_vertices = 0; + indices = 0; + number_indices = 0; +} + +EDetail::~EDetail() +{ + Unload(); +} + +void EDetail::Unload() +{ + CDetail::Unload(); + Lib.RemoveEditObject(m_pRefs); + OnDeviceDestroy(); +} + +LPCSTR EDetail::GetName() +{ + return m_pRefs ? m_pRefs->GetName() : m_sRefs.c_str(); +} + +LPCSTR EDetail::GetTextureName() +{ + VERIFY(m_pRefs); + CSurface *surf = *m_pRefs->FirstSurface(); + VERIFY(surf); + return surf->_Texture(); +} + +void EDetail::DefferedLoad() +{ +} + +void EDetail::OnDeviceCreate() +{ + if (!m_pRefs) + return; + CSurface *surf = *m_pRefs->FirstSurface(); + VERIFY(surf); + xr_string s_name = surf->_ShaderName(); + xr_string t_name = surf->_Texture(); + shader.create(s_name.c_str(), t_name.c_str()); +} + +void EDetail::OnDeviceDestroy() +{ + shader.destroy(); +} + +u16 EDetail::_AddVert(const Fvector &p, float u, float v) +{ + EVertexIn V(p, u, v); + for (u16 k = 0; k < (u16)number_vertices; k++) + if (V.similar((EVertexIn &)vertices[k])) + return k; + number_vertices++; + vertices = (fvfVertexIn *)xr_realloc(vertices, number_vertices * sizeof(fvfVertexIn)); + vertices[number_vertices - 1] = V; + return u16(number_vertices - 1); +} + +IC BOOL isDegenerated(u16 v[3]) +{ + return (v[0] == v[1] || v[0] == v[2] || v[1] == v[2]); +}; +IC BOOL isEqual(U16Vec &ind, u16 v[3]) +{ + for (U16It it = ind.begin(); it != ind.end(); it += 3) + { + // Test for 6 variations + if ((*(it + 0) == v[0]) && (*(it + 1) == v[1]) && (*(it + 2) == v[2])) + return true; + if ((*(it + 0) == v[0]) && (*(it + 2) == v[1]) && (*(it + 1) == v[2])) + return true; + if ((*(it + 2) == v[0]) && (*(it + 0) == v[1]) && (*(it + 1) == v[2])) + return true; + if ((*(it + 2) == v[0]) && (*(it + 1) == v[1]) && (*(it + 0) == v[2])) + return true; + if ((*(it + 1) == v[0]) && (*(it + 0) == v[1]) && (*(it + 2) == v[2])) + return true; + if ((*(it + 1) == v[0]) && (*(it + 2) == v[1]) && (*(it + 0) == v[2])) + return true; + } + return false; +} + +bool EDetail::Update(LPCSTR name) +{ + m_sRefs = name; + // update link + CEditableObject *R = Lib.CreateEditObject(name); + if (!R) + { + ELog.Msg(mtError, "Can't load detail object '%s'.", name); + return false; + } + if (R->SurfaceCount() != 1) + { + ELog.Msg(mtError, "Object must contain 1 material."); + Lib.RemoveEditObject(R); + return false; + } + if (R->MeshCount() == 0) + { + ELog.Msg(mtError, "Object must contain 1 mesh."); + Lib.RemoveEditObject(R); + return false; + } + + Lib.RemoveEditObject(m_pRefs); + m_pRefs = R; + + // fill geometry + CEditableMesh *M = *m_pRefs->FirstMesh(); + U16Vec inds; + + // fill vertices + bv_bb.invalidate(); + u32 idx = 0; + for (u32 f_id = 0; f_id < M->GetFCount(); f_id++) + { + const st_Face &F = M->GetFaces()[f_id]; + u16 ind[3]; + for (int k = 0; k < 3; k++, idx++) + { + const Fvector &P = M->GetVertices()[F.pv[k].pindex]; + st_VMapPt &vm = M->GetVMRefs()[F.pv[k].vmref].pts[0]; + Fvector2 &uv = M->GetVMaps()[vm.vmap_index]->getUV(vm.index); + ind[k] = _AddVert(P, uv.x, uv.y); + bv_bb.modify(vertices[ind[k]].P); + } + if (isDegenerated(ind)) + continue; + if (isEqual(inds, ind)) + continue; + inds.push_back(ind[0]); + inds.push_back(ind[1]); + inds.push_back(ind[2]); + } + number_indices = inds.size(); + indices = (u16 *)xr_malloc(number_indices * sizeof(u16)); + memcpy(indices, inds.data(), number_indices * sizeof(u16)); + + bv_bb.getsphere(bv_sphere.P, bv_sphere.R); + + OnDeviceCreate(); + + return true; +} + +bool EDetail::Load(IReader &F) +{ + // check version + R_ASSERT(F.find_chunk(DETOBJ_CHUNK_VERSION)); + u32 version = F.r_u32(); + if (version != DETOBJ_VERSION) + { + ELog.Msg(mtError, "EDetail: unsupported version."); + return false; + } + + // references + string256 buf; + R_ASSERT(F.find_chunk(DETOBJ_CHUNK_REFERENCE)); + F.r_stringZ(buf, sizeof(buf)); + + // scale + R_ASSERT(F.find_chunk(DETOBJ_CHUNK_SCALE_LIMITS)); + m_fMinScale = F.r_float(); + if (fis_zero(m_fMinScale)) + m_fMinScale = 0.1f; + m_fMaxScale = F.r_float(); + if (m_fMaxScale < m_fMinScale) + m_fMaxScale = m_fMinScale; + + // density factor + if (F.find_chunk(DETOBJ_CHUNK_DENSITY_FACTOR)) + m_fDensityFactor = F.r_float(); + + if (F.find_chunk(DETOBJ_CHUNK_FLAGS)) + m_Flags.assign(F.r_u32()); + + // update object + return Update(buf); +} + +void EDetail::Save(IWriter &F) +{ + // version + F.open_chunk(DETOBJ_CHUNK_VERSION); + F.w_u32(DETOBJ_VERSION); + F.close_chunk(); + + // reference + F.open_chunk(DETOBJ_CHUNK_REFERENCE); + F.w_stringZ(m_sRefs.c_str()); + F.close_chunk(); + + // scale + F.open_chunk(DETOBJ_CHUNK_SCALE_LIMITS); + F.w_float(m_fMinScale); + F.w_float(m_fMaxScale); + F.close_chunk(); + + // density factor + F.open_chunk(DETOBJ_CHUNK_DENSITY_FACTOR); + F.w_float(m_fDensityFactor); + F.close_chunk(); + + // flags + F.open_chunk(DETOBJ_CHUNK_FLAGS); + F.w_u32(m_Flags.get()); + F.close_chunk(); +} + +void EDetail::Export(IWriter &F, LPCSTR tex_name, const Fvector2 &offs, const Fvector2 &scale, bool rot) +{ + R_ASSERT(m_pRefs); + CSurface *surf = *m_pRefs->FirstSurface(); + R_ASSERT(surf); + // write data + F.w_stringZ(surf->_ShaderName()); + F.w_stringZ(tex_name); // surf->_Texture()); + + F.w_u32(m_Flags.get()); + F.w_float(m_fMinScale); + F.w_float(m_fMaxScale); + + F.w_u32(number_vertices); + F.w_u32(number_indices); + + // remap UV + EVertexIn *rm_vertices = xr_alloc(number_vertices); + for (u32 k = 0; k < number_vertices; k++) + rm_vertices[k].remapUV(vertices[k], offs, scale, rot); + + F.w(rm_vertices, number_vertices * sizeof(fvfVertexIn)); + F.w(indices, number_indices * sizeof(WORD)); + + xr_free(rm_vertices); +} + +void EDetail::Export(LPCSTR name) +{ + CSurface *surf = *m_pRefs->FirstSurface(); + R_ASSERT(surf); + IWriter *F = FS.w_open(name); + if (F) + { + Fvector2 offs = {0, 0}; + Fvector2 scale = {1, 1}; + Export(*F, surf->_Texture(), offs, scale, false); + FS.w_close(F); + } + else + { + Log("!Can't export detail:", name); + } +} diff --git a/src/editors/xrECore/Editor/EDetailModel.h b/src/editors/xrECore/Editor/EDetailModel.h new file mode 100644 index 00000000000..5e52630c69a --- /dev/null +++ b/src/editors/xrECore/Editor/EDetailModel.h @@ -0,0 +1,109 @@ +#pragma once + +#include "Layers/xrRender/DetailModel.h" + +// refs +class CEditableObject; + +class ECORE_API EDetail : public CDetail +{ + friend class EDetailManager; + friend class CDetailManager; + friend class UIDOShuffle; + + struct EVertexIn : public fvfVertexIn + { + EVertexIn(const Fvector &_P, float _u, float _v) + { + P.set(_P); + u = _u; + v = _v; + }; + IC void set(EVertexIn &src) + { + P.set(src.P); + u = src.u; + v = src.v; + }; + IC void set(const Fvector &_P, float _u, float _v) + { + P.set(_P); + u = _u; + v = _v; + }; + IC BOOL similar(EVertexIn &V) + { + if (!fsimilar(u, V.u, EPS_L)) + return FALSE; + if (!fsimilar(v, V.v, EPS_L)) + return FALSE; + if (!P.similar(V.P, EPS_L)) + return FALSE; + return TRUE; + } + void remapUV(const fvfVertexIn &src, const Fvector2 &offs, const Fvector2 &scale, bool bRotate); + }; + /* + struct fvfVertexIn{ + Fvector P; + float u,v; + fvfVertexIn (const Fvector& _P, float _u, float _v){P.set(_P); u=_u; v=_v;}; + void set (fvfVertexIn& src){P.set(src.P); u=src.u; v=src.v;}; + void set (const Fvector& _P, float _u, float _v){P.set(_P); u=_u; v=_v;}; + BOOL similar (fvfVertexIn& V) + { + if (!fsimilar (u,V.u,EPS_L)) return FALSE; + if (!fsimilar (v,V.v,EPS_L)) return FALSE; + if (!P.similar (V.P,EPS_L)) return FALSE; + return TRUE; + } + }; + struct fvfVertexOut + { + Fvector P; + DWORD C; + float u,v; + }; + + float m_fMinScale; + float m_fMaxScale; + + // render + fvfVertexIn *vertices; + DWORD number_vertices; + WORD *indices; + DWORD number_indices; + ref_shader shader; + Flags32 m_Flags; + Fsphere bv_sphere; + Fbox bv_bb; + */ + float m_fDensityFactor; + + // references + xr_string m_sRefs; + CEditableObject *m_pRefs; + + u16 _AddVert(const Fvector &p, float u, float v); + +public: + // bool m_bMarkDel; +public: + EDetail(); + virtual ~EDetail(); + + bool Load(IReader &); + void Save(IWriter &); + void Export(IWriter &, LPCSTR tex_name, const Fvector2 &offs, const Fvector2 &scale, bool rot); + void Export(LPCSTR name); + + bool Update(LPCSTR name); + virtual void Unload(); + + LPCSTR GetName(); + LPCSTR GetTextureName(); + void OnDeviceCreate(); + void OnDeviceDestroy(); + void DefferedLoad(); +}; +DEFINE_VECTOR(EDetail *, DOVec, DOIt); diff --git a/src/editors/xrECore/Editor/ELog.cpp b/src/editors/xrECore/Editor/ELog.cpp new file mode 100644 index 00000000000..316733fdcb6 --- /dev/null +++ b/src/editors/xrECore/Editor/ELog.cpp @@ -0,0 +1,323 @@ +//---------------------------------------------------- +// file: NetDeviceELog.cpp +//---------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +#include "ELog.h" +#ifdef _EDITOR +#include "UILogForm.h" +#include "ui_main.h" +void ELogCallback(void* context, const char* txt) +{ + if (0 == txt[0]) + return; + bool bDlg = ('#' == txt[0]) || ((0 != txt[1]) && ('#' == txt[1])); + TMsgDlgType mt = ('!' == txt[0]) || ((0 != txt[1]) && ('!' == txt[1])) ? mtError : mtInformation; + if (('!' == txt[0]) || ('#' == txt[0])) + txt++; + if (('!' == txt[0]) || ('#' == txt[0])) + txt++; + if (bDlg) + UILogForm::AddDlgMessage(mt, txt); + else + UILogForm::AddMessage(mt, txt); +} +#endif +#ifdef _LW_EXPORT +#include +extern "C" LWMessageFuncs *g_msg; +void ELogCallback(LPCSTR txt) +{ + if (0 == txt[0]) + return; + bool bDlg = ('#' == txt[0]) || ((0 != txt[1]) && ('#' == txt[1])); + if (bDlg) + { + int mt = ('!' == txt[0]) || ((0 != txt[1]) && ('!' == txt[1])) ? 1 : 0; + if (('!' == txt[0]) || ('#' == txt[0])) + txt++; + if (('!' == txt[0]) || ('#' == txt[0])) + txt++; + if (mt == 1) + g_msg->error(txt, 0); + else + g_msg->info(txt, 0); + } +} +#endif +#ifdef _MAX_EXPORT +#include "NetDeviceLog.h" +void ELogCallback(LPCSTR txt) +{ + if (0 != txt[0]) + { + if (txt[0] == '!') + EConsole.print(mtError, txt + 1); + else + EConsole.print(mtInformation, txt); + } +} +#endif +#ifdef _MAYA_PLUGIN +void ELogCallback(LPCSTR txt) +{ + if (0 != txt[0]) + { + if (txt[0] == '!') + std::cerr << "XR-Error: " << txt + 1 << "\n"; + else + std::cerr << "XR-Info: " << txt << "\n"; + } + //. MStringArray res; + // MGlobal::executeCommand("confirmDialog -title \"Error\" -message \"Mesh have non-triangulated polygon.\" -button \"Ok\" -defaultButton \"Ok\"",res); +} +#endif + +//---------------------------------------------------- +CLog ELog; +//---------------------------------------------------- +inline TMsgDlgButtons MessageDlg(const char *text, TMsgDlgType mt, int btn) +{ + UINT Flags = 0; + const char *Title = ""; + switch (mt) + { + case mtCustom: + break; + case mtError: + Title = "Error"; + Flags = MB_ICONERROR; + break; + case mtInformation: + Title = "Info"; + Flags = MB_ICONINFORMATION; + break; + case mtConfirmation: + Title = "Warning"; + Flags = MB_ICONWARNING; + break; + default: + R_ASSERT(0); + break; + } + if (btn == mbYes) + { + Flags |= MB_OK; + } + if (btn == mbOK) + { + Flags |= MB_OK; + } + else if (btn == (mbYes | mbNo)) + { + Flags |= MB_YESNO; + } + else if (btn == (mbYes | mbNo | mbCancel)) + { + Flags |= MB_YESNOCANCEL; + } + else + { + R_ASSERT(0); + } + int msgboxID = MessageBox( + NULL, + text, + Title, + Flags); + switch (msgboxID) + { + case IDCANCEL: + return mrCancel; // TODO: add code + break; + case IDYES: + return mrYes; + break; + case IDNO: + return mrNo; + break; + case IDOK: + return mrOK; + break; + } + if (btn | mbCancel) + return mrCancel; + if (btn | mbNo) + return mrNo; + if (btn == mbOK) + return mrOK; + return mrYes; +} +int CLog::DlgMsg(TMsgDlgType mt, int btn, LPCSTR _Format, ...) +{ + in_use = true; + char buf[4096]; + va_list l; + va_start(l, _Format); + vsprintf(buf, _Format, l); + + int res = 0; +#ifdef _EDITOR + ExecCommand(COMMAND_RENDER_FOCUS); + + res = MessageDlg(buf, mt, btn); + if (mtConfirmation == mt) + { + switch (res) + { + case mrYes: + strcat(buf, " - Yes."); + break; + case mrNo: + strcat(buf, " - No."); + break; + case mrCancel: + strcat(buf, " - Cancel."); + break; + default: + strcat(buf, " - Something."); + } + } +#endif +#ifdef _LW_EXPORT + switch (mt) + { + case mtError: + g_msg->error(buf, 0); + break; + case mtInformation: + g_msg->info(buf, 0); + break; + default: + g_msg->info(buf, 0); + break; + } +#endif +#ifdef _MAX_PLUGIN + switch (mt) + { + case mtError: + MessageBox(0, buf, "Error", MB_OK | MB_ICONERROR); + break; + case mtInformation: + MessageBox(0, buf, "Information", MB_OK | MB_ICONINFORMATION); + break; + default: + MessageBox(0, buf, "Information", MB_OK | MB_ICONINFORMATION); + break; + } +#endif + + Msg(mt, buf); + + in_use = false; + + return res; +} + +void CLog::Close() +{ + SetLogCB(0); + UILogForm::Destroy(); +} + +int CLog::DlgMsg(TMsgDlgType mt, LPCSTR _Format, ...) +{ + in_use = true; + char buf[4096]; + va_list l; + va_start(l, _Format); + vsprintf(buf, _Format, l); + + int res = 0; +#ifdef _EDITOR + ExecCommand(COMMAND_RENDER_FOCUS); + + if (mtConfirmation == mt) + res = MessageDlg(buf, mt, mbYes | mbNo | mbCancel); + else + res = MessageDlg(buf, mt, mbOK); + + if (mtConfirmation == mt) + { + switch (res) + { + case mrYes: + strcat(buf, " - Yes."); + break; + case mrNo: + strcat(buf, " - No."); + break; + case mrCancel: + strcat(buf, " - Cancel."); + break; + default: + strcat(buf, " - Something."); + } + } +#endif +#ifdef _LW_EXPORT + switch (mt) + { + case mtError: + g_msg->error(buf, 0); + break; + case mtInformation: + g_msg->info(buf, 0); + break; + default: + g_msg->info(buf, 0); + break; + } +#endif +#ifdef _MAX_PLUGIN + switch (mt) + { + case mtError: + MessageBox(0, buf, "Error", MB_OK | MB_ICONERROR); + break; + case mtInformation: + MessageBox(0, buf, "Information", MB_OK | MB_ICONINFORMATION); + break; + default: + MessageBox(0, buf, "Information", MB_OK | MB_ICONINFORMATION); + break; + } +#endif + + Msg(mt, buf); + + in_use = false; + + return res; +} + +void CLog::Msg(TMsgDlgType mt, LPCSTR _Format, ...) +{ + char buf[4096]; + va_list l; + va_start(l, _Format); + vsprintf(buf, _Format, l); + +#ifdef _EDITOR + UILogForm::AddMessage(mt, xr_string(buf)); +#endif +#ifdef _MAX_EXPORT + EConsole.print(mt, buf); +#endif +#ifdef _LW_EXPORT + switch (mt) + { + case mtError: + g_msg->error(buf, 0); + break; + } +#endif + + ::LogExecCB = FALSE; + ::Msg(buf); + ::LogExecCB = TRUE; +} +//---------------------------------------------------- diff --git a/src/editors/xrECore/Editor/ELog.h b/src/editors/xrECore/Editor/ELog.h new file mode 100644 index 00000000000..b9bd783dc6b --- /dev/null +++ b/src/editors/xrECore/Editor/ELog.h @@ -0,0 +1,44 @@ +//---------------------------------------------------- +// file: Log.h +//---------------------------------------------------- + +#ifndef ELogH +#define ELogH +enum TMsgDlgType +{ + mtCustom = 0, + mtError = 1, + mtInformation = 2, + mtConfirmation = 4, + +}; +enum TMsgDlgButtons +{ + mbYes = 1, + mbNo = 2, + mbCancel = 4, + mbOK = 8, + mrNone = 0, + mrYes, + mrNo, + mrCancel, + mrOK, +}; +class ECORE_API CLog +{ +public: + bool in_use; + +public: + CLog() { in_use = false; } + void Msg(TMsgDlgType mt, LPCSTR _Format, ...); + int DlgMsg(TMsgDlgType mt, LPCSTR _Format, ...); + int DlgMsg(TMsgDlgType mt, int btn, LPCSTR _Format, ...); + void Close(); +}; + +void ECORE_API ELogCallback(void* contect, const char* txt); + +extern ECORE_API CLog ELog; + +#endif /*_INCDEF_NETDEVICELOG_H_*/ diff --git a/src/editors/xrECore/Editor/EStats.cpp b/src/editors/xrECore/Editor/EStats.cpp new file mode 100644 index 00000000000..1058de2cdeb --- /dev/null +++ b/src/editors/xrECore/Editor/EStats.cpp @@ -0,0 +1,139 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "EStats.h" +#include "xrEngine/GameFont.h" + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +CEStats::CEStats() +{ + fFPS = 30.f; + fRFPS = 30.f; + fTPS = 0; + dwLevelSelFaceCount = 0; + dwLevelSelVertexCount = 0; +} + +CEStats::~CEStats() +{ +} + +void CEStats::Show(CGameFont *font) +{ + // Stop timers + { + RenderTOTAL.FrameEnd(); + RenderCALC.FrameEnd(); + + RenderDUMP_SKIN.FrameEnd(); + + Animation.FrameEnd(); + Input.FrameEnd(); + clRAY.FrameEnd(); + clBOX.FrameEnd(); + clFRUSTUM.FrameEnd(); + + RenderDUMP_RT.FrameEnd(); + + RenderDUMP_DT_VIS.FrameEnd(); + RenderDUMP_DT_Render.FrameEnd(); + RenderDUMP_DT_Cache.FrameEnd(); + TEST0.FrameEnd(); + TEST1.FrameEnd(); + TEST2.FrameEnd(); + TEST3.FrameEnd(); + } + + // calc FPS & TPS + CBackend::_stats &DPS = RCache.stat; + if (EDevice.fTimeDelta > EPS_S) + { + float fps = 1.f / EDevice.fTimeDelta; + float fOne = 0.3f; + float fInv = 1.f - fOne; + fFPS = fInv * fFPS + fOne * fps; + + if (RenderTOTAL.result > EPS_S) + { + fTPS = fInv * fTPS + fOne * float(DPS.render.polys) / (RenderTOTAL.result * 1000.f); + fRFPS = fInv * fRFPS + fOne * 1000.f / RenderTOTAL.result; + } + } + + // Show them + if (psDeviceFlags.is(rsStatistic)) + { + CGameFont &F = *font; + F.SetColor(0xFFFFFFFF); + F.OutSet(5, 5); + F.OutNext("FPS/RFPS: %3.1f/%3.1f", fFPS, fRFPS); + F.OutNext("TPS: %2.2f M", fTPS); + F.OutNext("VERT: %d", DPS.render.verts); + F.OutNext("POLY: %d", DPS.render.polys); + F.OutNext("DIP/DP: %d", DPS.render.calls); + F.OutNext("SH/T/M/C: %d/%d/%d/%d", dwShader_Codes, dwShader_Textures, dwShader_Matrices, dwShader_Constants); + F.OutNext("LIGHT S/T: %d/%d", dwLightInScene, dwTotalLight); + F.OutNext("Skeletons: %2.2fms, %d", Animation.result, Animation.count); + F.OutNext("Skinning: %2.2fms", RenderDUMP_SKIN.result); + F.OutSkip(); + F.OutNext("Input: %2.2fms", Input.result); + F.OutNext("clRAY: %2.2fms, %d", clRAY.result, clRAY.count); + F.OutNext("clBOX: %2.2fms, %d", clBOX.result, clBOX.count); + F.OutNext("clFRUSTUM: %2.2fms, %d", clFRUSTUM.result, clFRUSTUM.count); + F.OutSkip(); + // F.OutNext ("Render: %2.2fms", RenderDUMP.result); + F.OutNext(" RT: %2.2fms, %d", RenderDUMP_RT.result, RenderDUMP_RT.count); + F.OutNext(" DT_Vis: %2.2fms", RenderDUMP_DT_VIS.result); + F.OutNext(" DT_Render: %2.2fms", RenderDUMP_DT_Render.result); + F.OutNext(" DT_Cache: %2.2fms", RenderDUMP_DT_Cache.result); + F.OutSkip(); + F.OutNext("TEST 0: %2.2fms, %d", TEST0.result, TEST0.count); + F.OutNext("TEST 1: %2.2fms, %d", TEST1.result, TEST1.count); + F.OutNext("TEST 2: %2.2fms, %d", TEST2.result, TEST2.count); + F.OutNext("TEST 3: %2.2fms, %d", TEST3.result, TEST3.count); + F.OutSkip(); + // F.OutNext ("GAME TIME: %s", FloatTimeToStrTime(g_pGamePersistent->Environment().GetGameTime()).c_str()); + // F.OutSkip (2.f); + // F.OutNext ("Level summary:"); + // F.OutNext (" Sel Faces: %d", dwLevelSelFaceCount); + // F.OutNext (" Sel Verts: %d", dwLevelSelVertexCount); + } + + { + Animation.FrameStart(); + RenderTOTAL.FrameStart(); + + Input.FrameStart(); + clRAY.FrameStart(); + clBOX.FrameStart(); + clFRUSTUM.FrameStart(); + + RenderDUMP_SKIN.FrameStart(); + RenderDUMP_RT.FrameStart(); + + RenderDUMP_DT_VIS.FrameStart(); + RenderDUMP_DT_Render.FrameStart(); + RenderDUMP_DT_Cache.FrameStart(); + + TEST0.FrameStart(); + TEST1.FrameStart(); + TEST2.FrameStart(); + TEST3.FrameStart(); + } + dwShader_Codes = dwShader_Textures = dwShader_Matrices = dwShader_Constants = 0; + dwSND_Played = dwSND_Allocated = 0; + dwTotalLight = dwLightInScene = 0; + + DPS.render.polys = 0; + DPS.render.verts = 0; + DPS.render.calls = 0; + DPS.vs = 0; + // DPS.vb = 0; + // DPS.ib = 0; + + dwLevelSelFaceCount = 0; + dwLevelSelVertexCount = 0; +} diff --git a/src/editors/xrECore/Editor/EStats.h b/src/editors/xrECore/Editor/EStats.h new file mode 100644 index 00000000000..2c8071674b1 --- /dev/null +++ b/src/editors/xrECore/Editor/EStats.h @@ -0,0 +1,60 @@ +// Stats.h: interface for the CStats class. +// +////////////////////////////////////////////////////////////////////// + +#ifndef EStatsH +#define EStatsH +#pragma once +//#include "../../../xrengine/stats.h" +// refs +class CGameFont; + +class ENGINE_API CEStats +{ +public: + float fFPS, fRFPS, fTPS; // FPS, RenderFPS, TPS + u32 dwShader_Codes; // Number of times the shader-code changes + u32 dwShader_Textures; // Number of times the shader-tex changes + u32 dwShader_Matrices; // Number of times the shader-xform changes + u32 dwShader_Constants; // Number of times the shader-consts changes + u32 dwSND_Played, dwSND_Allocated; // Play/Alloc + u32 dwTotalLight, dwLightInScene; + u32 dwLevelSelFaceCount; // Number of faces in scene + u32 dwLevelSelVertexCount; // Number of vertices in scene + + CStatTimer RenderDUMP_RT; + CStatTimer RenderTOTAL; // + CStatTimer RenderTOTAL_Real; + CStatTimer RenderCALC; // portal traversal, frustum culling, entities "OnVisible" + CStatTimer RenderDUMP_SKIN; + CStatTimer Animation; // skeleton calculation + CStatTimer RenderDUMP_DT_VIS; // ...details visibility detection + CStatTimer RenderDUMP_DT_Render; // ...details rendering + CStatTimer RenderDUMP_DT_Cache; // ...details slot cache access + + u32 RenderDUMP_DT_Count; + + CStatTimer Input; // total time taken by input subsystem (accurate only in single-threaded mode) + CStatTimer clRAY; // total: ray-testing + CStatTimer clBOX; // total: box query + CStatTimer clFRUSTUM; // total: frustum query + + CStatTimer TEST0; // debug counter + CStatTimer TEST1; // debug counter + CStatTimer TEST2; // debug counter + CStatTimer TEST3; // debug counter + + void Show(CGameFont *font); + + CEStats(); + ~CEStats(); +}; + +#define UPDATEC(vert, poly, pass) \ + { \ + EDevice.Statistic->dwVert += (vert) * (pass); \ + EDevice.Statistic->dwPoly += (poly)*pass; \ + EDevice.Statistic->dwCalls += pass; \ + } + +#endif // !defined(AFX_STATS_H__4C8D1860_0EE2_11D4_B4E3_4854E82A090D__INCLUDED_) diff --git a/src/editors/xrECore/Editor/EThumbnail.cpp b/src/editors/xrECore/Editor/EThumbnail.cpp new file mode 100644 index 00000000000..ee5663634e5 --- /dev/null +++ b/src/editors/xrECore/Editor/EThumbnail.cpp @@ -0,0 +1,131 @@ +#include "stdafx.h" +#include "EThumbnail.h" +#include "xrEngine/xrImage_Resampler.h" + +// Custom Thumbnail +ECustomThumbnail::ECustomThumbnail(LPCSTR src_name, THMType type) +{ + m_Type = type; + m_SrcName = src_name; + m_Name = ChangeFileExt(xr_string(src_name), ".thm"); + m_Age = 0; +} + +ECustomThumbnail::~ECustomThumbnail() +{ +} +/* +void DrawThumbnail(TCanvas* pCanvas, TRect& r, U32Vec& data, bool bDrawWithAlpha, int _w = THUMB_WIDTH, int _h = THUMB_HEIGHT) +{ + pCanvas->CopyMode = cmSrcCopy; + Graphics::TBitmap *pBitmap = xr_new(); + + pBitmap->PixelFormat = pf32bit; + pBitmap->Height = _h; + pBitmap->Width = _w; + + if (bDrawWithAlpha){ + Fcolor back; + back.set (bgr2rgb(pCanvas->Brush->Color)); back.mul_rgb(255.f); + for (int y = 0; y < pBitmap->Height; y++) + { + u32* ptr = (u32*)pBitmap->ScanLine[y]; + for (int x = 0; x < pBitmap->Width; x++){ + u32 src = data[(_h-1-y)*_w+x]; + float a = float(color_get_A(src))/255.f; + float inv_a = 1.f-a;; + u32 r = iFloor(float(color_get_R(src))*a+back.r*inv_a); + u32 g = iFloor(float(color_get_G(src))*a+back.g*inv_a); + u32 b = iFloor(float(color_get_B(src))*a+back.b*inv_a); + ptr[x] = color_rgba(r,g,b,0); + } + } + }else{ + for (int y = 0; y < pBitmap->Height; y++) + { + u32* ptr = (u32*)pBitmap->ScanLine[y]; + memcpy (ptr,&data[(_h-1-y)*_w],_w*4); + } + } + pCanvas->StretchDraw(r,pBitmap); + xr_delete(pBitmap); +} +*/ +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +// Image Thumbnail +//------------------------------------------------------------------------------ +EImageThumbnail::~EImageThumbnail() +{ + m_Pixels.clear(); +} + +void EImageThumbnail::VFlip() +{ + R_ASSERT(!m_Pixels.empty()); + u32 line[THUMB_WIDTH]; + u32 sz_ln = sizeof(u32) * THUMB_WIDTH; + u32 y2 = THUMB_WIDTH - 1; + for (int y = 0; y < THUMB_HEIGHT / 2; y++, y2--) + { + CopyMemory(line, m_Pixels.data() + y2 * THUMB_WIDTH, sz_ln); + CopyMemory(m_Pixels.data() + y2 * THUMB_WIDTH, m_Pixels.data() + y * THUMB_WIDTH, sz_ln); + CopyMemory(m_Pixels.data() + y * THUMB_WIDTH, line, sz_ln); + } +} + +void EImageThumbnail::CreatePixels(u32 *p, u32 w, u32 h) +{ + // imf_filter imf_box imf_triangle imf_bell imf_b_spline imf_lanczos3 imf_mitchell + R_ASSERT(p && (w > 0) && (h > 0)); + m_Pixels.resize(THUMB_SIZE); + imf_Process(m_Pixels.data(), THUMB_WIDTH, THUMB_HEIGHT, p, w, h, imf_box); +} +void EImageThumbnail::Update(ImTextureID &Texture) +{ + if (m_Pixels.size() == 0) + { + if (Texture) + Texture->Release(); + Texture = nullptr; + return; + } + ID3DTexture2D *pTexture = nullptr; + if (Texture != nullptr) + { + R_CHK(Texture->QueryInterface(__uuidof(ID3DTexture2D), (void **)&pTexture)); + } + else + { + R_CHK(HW.pDevice->CreateTexture(THUMB_WIDTH, THUMB_HEIGHT, 1, 0, D3DFMT_X8R8G8B8, D3DPOOL_MANAGED, &pTexture, 0)); + Texture = pTexture; + } + { + D3DLOCKED_RECT rect; + R_CHK(pTexture->LockRect(0, &rect, 0, D3DLOCK_DISCARD)); + for (int i = 0; i < THUMB_HEIGHT; i++) + { + + unsigned char *dest = static_cast(rect.pBits) + (rect.Pitch * i); + memcpy(dest, Pixels() + (THUMB_WIDTH * (THUMB_HEIGHT - i - 1)), sizeof(unsigned char) * THUMB_WIDTH * 4); + } + R_CHK(pTexture->UnlockRect(0)); + } +} + +EImageThumbnail *CreateThumbnail(LPCSTR src_name, ECustomThumbnail::THMType type, bool bLoad) +{ + switch (type) + { + case ECustomThumbnail::ETObject: + return xr_new(src_name, bLoad); + case ECustomThumbnail::ETTexture: + return xr_new(src_name, bLoad); + case ECustomThumbnail::ETGroup: + return xr_new(src_name, bLoad); + default: + NODEFAULT; + } + return 0; +} diff --git a/src/editors/xrECore/Editor/EThumbnail.h b/src/editors/xrECore/Editor/EThumbnail.h new file mode 100644 index 00000000000..67ca49d87c8 --- /dev/null +++ b/src/editors/xrECore/Editor/EThumbnail.h @@ -0,0 +1,187 @@ +#ifndef EThumbnailH +#define EThumbnailH + +#include "Layers/xrRender/ETextureParams.h" + +//------------------------------------------------------------------------------ +// Custom class +//------------------------------------------------------------------------------ +class ECORE_API ECustomThumbnail +{ +public: + enum THMType + { + ETUndef = -1, + ETObject = 0, + ETTexture = 1, + ETSound = 2, + ETGroup = 3, + force_dword = (-1) + }; + +protected: + xr_string m_SrcName; + xr_string m_Name; + int m_Age; + THMType m_Type; + +public: + ECustomThumbnail(LPCSTR src_name, THMType type); + virtual ~ECustomThumbnail(); + + LPCSTR Name() { return m_Name.c_str(); } + LPCSTR SrcName() { return m_SrcName.c_str(); } + + IC bool IsClass(THMType type) { return m_Type == type; } + + // thumbnail public routines + virtual bool Load(LPCSTR src_name = 0, LPCSTR path = 0) = 0; + virtual void Save(int age = 0, LPCSTR path = 0) = 0; + virtual bool Valid() = 0; + // virtual void FillProp (PropItemVec& values)=0; + virtual void FillInfo(PropItemVec &values) = 0; +}; +//------------------------------------------------------------------------------ + +class ECORE_API EImageThumbnail : public ECustomThumbnail +{ + friend class CImageManager; + +protected: + U32Vec m_Pixels; + +protected: + void CreatePixels(u32 *p, u32 w, u32 h); + void VFlip(); + +public: + EImageThumbnail(LPCSTR src_name, THMType type) : ECustomThumbnail(src_name, type){}; + virtual ~EImageThumbnail(); + virtual void Update(ImTextureID &Texture); + // virtual void Draw (TMxPanel* panel){Irect r; r.set(1,1,1+panel->Width,1+panel->Height); Draw(panel->Canvas->Handle,r);} + u32 *Pixels() { return &*m_Pixels.begin(); } + virtual int MemoryUsage() { return 0; }; +}; + +class ECORE_API ETextureThumbnail : public EImageThumbnail +{ + friend class CImageManager; + typedef EImageThumbnail inherited; + +private: + STextureParams m_TexParams; + bool m_bValid; + +public: + ETextureThumbnail(LPCSTR src_name, bool bLoad = true); + virtual ~ETextureThumbnail(); + + // Texture routines + void CreateFromData(u32 *p, u32 w, u32 h); + IC u32 _Width() { return m_TexParams.width; } + IC u32 _Height() { return m_TexParams.height; } + IC u32 _Alpha() { return m_TexParams.HasAlphaChannel(); } + // thumbnail public routines + IC STextureParams &_Format() { return m_TexParams; } + virtual bool Load(LPCSTR src_name = 0, LPCSTR path = 0); + virtual void Save(int age = 0, LPCSTR path = 0); + virtual bool Valid() { return m_bValid; /*return !m_Pixels.empty();*/ } + void SetValid() { m_bValid = true; } + virtual void FillProp(PropItemVec &values, PropValue::TOnChange on_type_change); + virtual void FillInfo(PropItemVec &values); + virtual void Update(ImTextureID &Texture); + // virtual void Draw (TMxPanel* panel){inherited::Draw(panel);} + + virtual int MemoryUsage(); + LPCSTR FormatString(); + BOOL similar(ETextureThumbnail *thm1, xr_vector &sel_params); +}; +//------------------------------------------------------------------------------ + +class ECORE_API EObjectThumbnail : public EImageThumbnail +{ + friend class CImageManager; + typedef EImageThumbnail inherited; + +private: + u32 face_count; + u32 vertex_count; + +public: + EObjectThumbnail(LPCSTR src_name, bool bLoad = true); + virtual ~EObjectThumbnail(); + + // Object routines + void CreateFromData(u32 *p, u32 w, u32 h, int fc, int vc); + IC int _VertexCount() { return vertex_count; } + IC int _FaceCount() { return face_count; } + + // thumbnail public routines + virtual bool Load(LPCSTR src_name = 0, LPCSTR path = 0); + virtual void Save(int age = 0, LPCSTR path = 0); + virtual bool Valid() { return !m_Pixels.empty(); } + virtual void FillProp(PropItemVec &values); + virtual void FillInfo(PropItemVec &values); +}; +//------------------------------------------------------------------------------ + +class ECORE_API EGroupThumbnail : public EImageThumbnail +{ + friend class CImageManager; + typedef EImageThumbnail inherited; + +private: + SStringVec objects; + +public: + EGroupThumbnail(LPCSTR src_name, bool bLoad = true); + virtual ~EGroupThumbnail(); + + // Object routines + void CreateFromData(u32 *p, u32 w, u32 h, const SStringVec &lst); + + // thumbnail public routines + virtual bool Load(LPCSTR src_name = 0, LPCSTR path = 0); + virtual void Save(int age = 0, LPCSTR path = 0); + virtual bool Valid() { return !m_Pixels.empty(); } + virtual void FillProp(PropItemVec &values); + virtual void FillInfo(PropItemVec &values); +}; +//------------------------------------------------------------------------------ + +class ECORE_API ESoundThumbnail : public ECustomThumbnail +{ + friend class CSoundManager; + typedef ECustomThumbnail inherited; + +private: + float m_fQuality; + float m_fMinDist; + float m_fMaxDist; + float m_fMaxAIDist; + float m_fBaseVolume; + u32 m_uGameType; + bool OnMaxAIDistAfterEdit(PropValue *sender, float &edit_val); + void OnMaxDistChange(PropValue *sender); + +public: + ESoundThumbnail(LPCSTR src_name, bool bLoad = true); + virtual ~ESoundThumbnail(); + + // thumbnail public routines + virtual bool Load(LPCSTR src_name = 0, LPCSTR path = 0); + virtual void Save(int age = 0, LPCSTR path = 0); + virtual bool Valid() { return true; } + virtual void FillProp(PropItemVec &values); + virtual void FillInfo(PropItemVec &values); + float MinDist() { return m_fMinDist; } + float MaxDist() { return m_fMaxDist; }; + float BaseVolume() { return m_fBaseVolume; }; + void SetMinDist(float d) { m_fMinDist = d; } + void SetMaxDist(float d) { m_fMaxDist = d; }; +}; +//------------------------------------------------------------------------------ + +EImageThumbnail *CreateThumbnail(LPCSTR src_name, ECustomThumbnail::THMType type, bool bLoad = true); + +#endif diff --git a/src/editors/xrECore/Editor/EThumbnailGroup.cpp b/src/editors/xrECore/Editor/EThumbnailGroup.cpp new file mode 100644 index 00000000000..c18c019742b --- /dev/null +++ b/src/editors/xrECore/Editor/EThumbnailGroup.cpp @@ -0,0 +1,118 @@ +#include "stdafx.h" +#include "EThumbnail.h" + +#define THM_GROUP_VERSION 0x0001 +#define THM_CHUNK_GROUPPARAM 0x0001 + +EGroupThumbnail::EGroupThumbnail(LPCSTR src_name, bool bLoad) : EImageThumbnail(src_name, ETObject) +{ + if (bLoad) + Load(); +} + +EGroupThumbnail::~EGroupThumbnail() +{ + m_Pixels.clear(); +} + +void EGroupThumbnail::CreateFromData(u32 *p, u32 w, u32 h, const SStringVec &lst) +{ + EImageThumbnail::CreatePixels(p, w, h); + objects = lst; +} + +bool EGroupThumbnail::Load(LPCSTR src_name, LPCSTR path) +{ + string_path fn; + strcpy(fn, EFS.ChangeFileExt(src_name ? src_name : m_Name.c_str(), ".thm").c_str()); + if (path) + FS.update_path(fn, path, fn); + else + FS.update_path(fn, _objects_, fn); + if (!FS.exist(fn)) + return false; + + IReader *F = FS.r_open(fn); + u16 version = 0; + + R_ASSERT(F->r_chunk(THM_CHUNK_VERSION, &version)); + if (version != THM_GROUP_VERSION) + { + Msg("!Thumbnail: Unsupported version."); + return false; + } + + IReader *D = F->open_chunk(THM_CHUNK_DATA); + R_ASSERT(D); + m_Pixels.resize(THUMB_SIZE); + D->r(m_Pixels.data(), THUMB_SIZE * sizeof(u32)); + D->close(); + + R_ASSERT(F->find_chunk(THM_CHUNK_TYPE)); + m_Type = THMType(F->r_u32()); + R_ASSERT(m_Type == ETObject); + + R_ASSERT(F->find_chunk(THM_CHUNK_GROUPPARAM)); + objects.resize(F->r_u32()); + for (SStringVecIt it = objects.begin(); it != objects.end(); it++) + F->r_stringZ(*it); + + m_Age = FS.get_file_age(fn); + + FS.r_close(F); + + return true; +} +//------------------------------------------------------------------------------ + +void EGroupThumbnail::Save(int age, LPCSTR path) +{ + if (!Valid()) + return; + + CMemoryWriter F; + F.open_chunk(THM_CHUNK_VERSION); + F.w_u16(THM_GROUP_VERSION); + F.close_chunk(); + + F.w_chunk(THM_CHUNK_DATA | CFS_CompressMark, m_Pixels.data(), m_Pixels.size() * sizeof(u32)); + + F.open_chunk(THM_CHUNK_TYPE); + F.w_u32(m_Type); + F.close_chunk(); + + F.open_chunk(THM_CHUNK_GROUPPARAM); + F.w_u32(objects.size()); + for (SStringVecIt it = objects.begin(); it != objects.end(); it++) + F.w_stringZ(*it); + F.close_chunk(); + + string_path fn; + if (path) + FS.update_path(fn, path, m_Name.c_str()); + else + FS.update_path(fn, _objects_, m_Name.c_str()); + if (F.save_to(fn)) + { + FS.set_file_age(fn, age ? age : m_Age); + } + else + { + Log("!Can't save thumbnail:", fn); + } +} +//------------------------------------------------------------------------------ + +void EGroupThumbnail::FillProp(PropItemVec &items) +{ + PHelper().CreateCaption(items, "Objects\\Count", std::to_string(objects.size()).c_str()); + for (SStringVecIt it = objects.begin(); it != objects.end(); it++) + PHelper().CreateCaption(items, make_string("Objects\\#%d", it - objects.begin()).c_str(), it->c_str()); +} +//------------------------------------------------------------------------------ + +void EGroupThumbnail::FillInfo(PropItemVec &items) +{ + FillProp(items); +} +//------------------------------------------------------------------------------ diff --git a/src/editors/xrECore/Editor/EThumbnailObject.cpp b/src/editors/xrECore/Editor/EThumbnailObject.cpp new file mode 100644 index 00000000000..293af879895 --- /dev/null +++ b/src/editors/xrECore/Editor/EThumbnailObject.cpp @@ -0,0 +1,119 @@ +#include "stdafx.h" +#include "EThumbnail.h" + +#define THM_OBJECT_VERSION 0x0012 +#define THM_CHUNK_OBJECTPARAM 0x0816 + +EObjectThumbnail::EObjectThumbnail(LPCSTR src_name, bool bLoad) : EImageThumbnail(src_name, ETObject) +{ + face_count = 0; + vertex_count = 0; + if (bLoad) + Load(); +} + +EObjectThumbnail::~EObjectThumbnail() +{ + m_Pixels.clear(); +} + +void EObjectThumbnail::CreateFromData(u32 *p, u32 w, u32 h, int fc, int vc) +{ + EImageThumbnail::CreatePixels(p, w, h); + face_count = fc; + vertex_count = vc; +} +//------------------------------------------------------------------------------ + +bool EObjectThumbnail::Load(LPCSTR src_name, LPCSTR path) +{ + string_path fn; + strcpy(fn, EFS.ChangeFileExt(src_name ? src_name : m_Name.c_str(), ".thm").c_str()); + if (path) + FS.update_path(fn, path, fn); + else + FS.update_path(fn, _objects_, fn); + if (!FS.exist(fn)) + return false; + + IReader *F = FS.r_open(fn); + u16 version = 0; + + R_ASSERT(F->r_chunk(THM_CHUNK_VERSION, &version)); + if (version != THM_OBJECT_VERSION) + { + Msg("!Thumbnail: Unsupported version."); + return false; + } + + IReader *D = F->open_chunk(THM_CHUNK_DATA); + R_ASSERT(D); + m_Pixels.resize(THUMB_SIZE); + D->r(m_Pixels.data(), THUMB_SIZE * sizeof(u32)); + D->close(); + + R_ASSERT(F->find_chunk(THM_CHUNK_TYPE)); + m_Type = THMType(F->r_u32()); + R_ASSERT(m_Type == ETObject); + + R_ASSERT(F->find_chunk(THM_CHUNK_OBJECTPARAM)); + face_count = F->r_u32(); + vertex_count = F->r_u32(); + + m_Age = FS.get_file_age(fn); + + FS.r_close(F); + + return true; +} +//------------------------------------------------------------------------------ + +void EObjectThumbnail::Save(int age, LPCSTR path) +{ + if (!Valid()) + return; + + CMemoryWriter F; + F.open_chunk(THM_CHUNK_VERSION); + F.w_u16(THM_OBJECT_VERSION); + F.close_chunk(); + + F.w_chunk(THM_CHUNK_DATA | CFS_CompressMark, m_Pixels.data(), m_Pixels.size() * sizeof(u32)); + + F.open_chunk(THM_CHUNK_TYPE); + F.w_u32(m_Type); + F.close_chunk(); + + F.open_chunk(THM_CHUNK_OBJECTPARAM); + F.w_u32(face_count); + F.w_u32(vertex_count); + F.close_chunk(); + + string_path fn; + //. if (path) FS.update_path(fn,path,m_Name.c_str()); + //. else FS.update_path(fn,_objects_,m_Name.c_str()); + + strcpy(fn, m_Name.c_str()); + if (F.save_to(fn)) + { + FS.set_file_age(fn, age ? age : m_Age); + } + else + { + Log("!Can't save thumbnail:", fn); + } +} +//------------------------------------------------------------------------------ + +void EObjectThumbnail::FillProp(PropItemVec &items) +{ + PHelper().CreateCaption(items, "Face Count", std::to_string(face_count).c_str()); + PHelper().CreateCaption(items, "Vertex Count", std::to_string(vertex_count).c_str()); +} +//------------------------------------------------------------------------------ + +void EObjectThumbnail::FillInfo(PropItemVec &items) +{ + PHelper().CreateCaption(items, "Face Count", face_count ? std::to_string(face_count).c_str() : "?"); + PHelper().CreateCaption(items, "Vertex Count", vertex_count ? std::to_string(vertex_count).c_str() : "?"); +} diff --git a/src/editors/xrECore/Editor/EThumbnailSound.cpp b/src/editors/xrECore/Editor/EThumbnailSound.cpp new file mode 100644 index 00000000000..64fd5894add --- /dev/null +++ b/src/editors/xrECore/Editor/EThumbnailSound.cpp @@ -0,0 +1,186 @@ +#include "stdafx.h" +#include "EThumbnail.h" + +#define THM_SOUND_VERSION 0x0014 +#define THM_CHUNK_SOUNDPARAM 0x1000 +#define THM_CHUNK_SOUNDPARAM2 0x1001 +#define THM_CHUNK_SOUND_AI_DIST 0x1002 + +ESoundThumbnail::ESoundThumbnail(LPCSTR src_name, bool bLoad) : ECustomThumbnail(src_name, ETSound) +{ + m_fQuality = 0.f; + m_fMinDist = 1.f; + m_fMaxDist = 300.f; + m_fMaxAIDist = 300.f; + m_fBaseVolume = 1.f; + m_uGameType = 0; + if (bLoad) + Load(); +} + +ESoundThumbnail::~ESoundThumbnail() +{ +} + +bool ESoundThumbnail::Load(LPCSTR src_name, LPCSTR path) +{ + string_path fn; + strcpy(fn, EFS.ChangeFileExt(src_name ? src_name : m_Name.c_str(), ".thm").c_str()); + if (path) + FS.update_path(fn, path, fn); + else + FS.update_path(fn, _sounds_, fn); + if (!FS.exist(fn)) + return false; + + IReader *F = FS.r_open(fn); + u16 version = 0; + + R_ASSERT(F->r_chunk(THM_CHUNK_VERSION, &version)); + if (version != THM_SOUND_VERSION) + { + Msg("!Thumbnail: Unsupported version."); + return false; + } + + R_ASSERT(F->find_chunk(THM_CHUNK_TYPE)); + m_Type = THMType(F->r_u32()); + R_ASSERT(m_Type == ETSound); + + R_ASSERT(F->find_chunk(THM_CHUNK_SOUNDPARAM)); + m_fQuality = F->r_float(); + m_fMinDist = F->r_float(); + m_fMaxDist = F->r_float(); + m_uGameType = F->r_u32(); + + if (F->find_chunk(THM_CHUNK_SOUNDPARAM2)) + m_fBaseVolume = F->r_float(); + + if (F->find_chunk(THM_CHUNK_SOUND_AI_DIST)) + m_fMaxAIDist = F->r_float(); + else + m_fMaxAIDist = m_fMaxDist; + + m_Age = FS.get_file_age(fn); + + FS.r_close(F); + + return true; +} +//------------------------------------------------------------------------------ + +void ESoundThumbnail::Save(int age, LPCSTR path) +{ + if (!Valid()) + return; + + CMemoryWriter F; + F.open_chunk(THM_CHUNK_VERSION); + F.w_u16(THM_SOUND_VERSION); + F.close_chunk(); + + F.open_chunk(THM_CHUNK_TYPE); + F.w_u32(m_Type); + F.close_chunk(); + + F.open_chunk(THM_CHUNK_SOUNDPARAM); + F.w_float(m_fQuality); + F.w_float(m_fMinDist); + F.w_float(m_fMaxDist); + F.w_u32(m_uGameType); + F.close_chunk(); + + F.open_chunk(THM_CHUNK_SOUNDPARAM2); + F.w_float(m_fBaseVolume); + F.close_chunk(); + + F.open_chunk(THM_CHUNK_SOUND_AI_DIST); + F.w_float(m_fMaxAIDist); + F.close_chunk(); + + string_path fn; + if (path) + FS.update_path(fn, path, m_Name.c_str()); + else + FS.update_path(fn, _sounds_, m_Name.c_str()); + + if (F.save_to(fn)) + { + FS.set_file_age(fn, age ? age : m_Age); + } + else + { + Log("!Can't save thumbnail:", fn); + } +} +//------------------------------------------------------------------------------ + +#include "..\Engine\ai_sounds.h" + +bool ESoundThumbnail::OnMaxAIDistAfterEdit(PropValue *sender, float &edit_val) +{ + UIPropertiesForm *P = sender->Owner()->Owner(); + VERIFY(P); + PropItem *S = P->FindItemOfName("Max Dist"); + VERIFY(S); + FloatValue *V = dynamic_cast(S->GetFrontValue()); + VERIFY(V); + float max_val = V->GetValue(); + return edit_val < max_val; + return false; +} +void ESoundThumbnail::OnMaxDistChange(PropValue *sender) +{ + FloatValue *SV = dynamic_cast(sender); + VERIFY(SV); + UIPropertiesForm *P = sender->Owner()->Owner(); + VERIFY(P); + PropItem *S = P->FindItemOfName("Max AI Dist"); + VERIFY(S); + bool bChanged = false; + for (PropItem::PropValueIt it = S->Values().begin(); S->Values().end() != it; ++it) + { + FloatValue *CV = dynamic_cast(*it); + VERIFY(CV); + CV->lim_mx = *SV->value; + if (*CV->value > CV->lim_mx) + { + ELog.DlgMsg(mtInformation, "'Max AI Dist' <= 'Max Dist'. 'Max AI Dist' will be clamped."); + bChanged = true; + *CV->value = CV->lim_mx; + } + if (!CV->Equal(S->Values().front())) + S->m_Flags.set(PropItem::flMixed, TRUE); + } + if (bChanged) + { + /*P->Modified (); + P->RefreshForm ();*/ + /*TODO:Это теперь не нужно*/ + } +} + +void ESoundThumbnail::FillProp(PropItemVec &items) +{ + FloatValue *V = 0; + PHelper().CreateFloat(items, "Quality", &m_fQuality); + PHelper().CreateFloat(items, "Min Dist", &m_fMinDist, 0.01f, 1000.f); + V = PHelper().CreateFloat(items, "Max Dist", &m_fMaxDist, 0.1f, 1000.f); + V->OnChangeEvent.bind(this, &ESoundThumbnail::OnMaxDistChange); + V = PHelper().CreateFloat(items, "Max AI Dist", &m_fMaxAIDist, 0.1f, 1000.f); + V->OnAfterEditEvent.bind(this, &ESoundThumbnail::OnMaxAIDistAfterEdit); + PHelper().CreateFloat(items, "Base Volume", &m_fBaseVolume, 0.f, 2.f); + PHelper().CreateToken32(items, "Game Type", &m_uGameType, anomaly_type_token); +} +//------------------------------------------------------------------------------ + +void ESoundThumbnail::FillInfo(PropItemVec &items) +{ + PHelper().CreateCaption(items, "Quality", make_string("%3.2f", m_fQuality).c_str()); + PHelper().CreateCaption(items, "Min Dist", make_string("%3.2f", m_fMinDist).c_str()); + PHelper().CreateCaption(items, "Max Dist", make_string("%3.2f", m_fMaxDist).c_str()); + PHelper().CreateCaption(items, "Max AI Dist", make_string("%3.2f", m_fMaxAIDist).c_str()); + PHelper().CreateCaption(items, "Base Volume", make_string("%3.2f", m_fBaseVolume).c_str()); + PHelper().CreateCaption(items, "Game Type", get_token_name(anomaly_type_token, m_uGameType)); +} +//------------------------------------------------------------------------------ diff --git a/src/editors/xrECore/Editor/EThumbnailTexture.cpp b/src/editors/xrECore/Editor/EThumbnailTexture.cpp new file mode 100644 index 00000000000..e478da789af --- /dev/null +++ b/src/editors/xrECore/Editor/EThumbnailTexture.cpp @@ -0,0 +1,277 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "EThumbnail.h" +#ifndef XR_EPROPS_EXPORTS +#include "ImageManager.h" +#endif + +#define THM_TEXTURE_VERSION 0x0012 + +ETextureThumbnail::ETextureThumbnail(LPCSTR src_name, bool bLoad) : EImageThumbnail(src_name, ETTexture) +{ + if (!strchr(src_name, '\\')) + { + xr_string _name = src_name; + ImageLib.UpdateFileName(_name); + m_Name = _name.c_str(); + m_Name = ChangeFileExt(m_Name, ".thm"); + } + m_bValid = false; + if (bLoad) +#ifdef XR_EPROPS_EXPORTS + Load(); +#else + if (!Load()) + { + ImageLib.CreateTextureThumbnail(this, src_name); + } +#endif +} +//------------------------------------------------------------------------------ + +ETextureThumbnail::~ETextureThumbnail() +{ + m_Pixels.clear(); +} +//------------------------------------------------------------------------------ + +int ETextureThumbnail::MemoryUsage() +{ + int mem_usage = _Width() * _Height() * 4; + switch (m_TexParams.fmt) + { + case STextureParams::tfDXT1: + case STextureParams::tfADXT1: + mem_usage /= 6; + break; + case STextureParams::tfDXT3: + case STextureParams::tfDXT5: + mem_usage /= 4; + break; + case STextureParams::tf4444: + case STextureParams::tf1555: + case STextureParams::tf565: + mem_usage /= 2; + break; + case STextureParams::tfRGBA: + break; + } + string_path fn; + FS.update_path(fn, _game_textures_, EFS.ChangeFileExt(m_Name.c_str(), ".seq").c_str()); + if (FS.exist(fn)) + { + string128 buffer; + IReader *F = FS.r_open(0, fn); + F->r_string(buffer, sizeof(buffer)); + int cnt = 0; + while (!F->eof()) + { + F->r_string(buffer, sizeof(buffer)); + cnt++; + } + FS.r_close(F); + mem_usage *= cnt ? cnt : 1; + } + return mem_usage; +} +//------------------------------------------------------------------------------ + +void ETextureThumbnail::CreateFromData(u32 *p, u32 w, u32 h) +{ + EImageThumbnail::CreatePixels(p, w, h); + m_TexParams.width = w; + m_TexParams.height = h; + m_TexParams.flags.set(STextureParams::flHasAlpha, FALSE); +} +//------------------------------------------------------------------------------ + +bool Stbi_Load(LPCSTR full_name, U32Vec &data, u32 &w, u32 &h, u32 &a); + +bool ETextureThumbnail::Load(LPCSTR src_name, LPCSTR path) +{ + string_path fn; + strcpy(fn, EFS.ChangeFileExt(src_name ? src_name : m_Name.c_str(), ".thm").c_str()); + if (path) + FS.update_path(fn, path, fn); + else + { + FS.update_path(fn, _game_textures_, fn); + } + + if (!FS.exist(fn)) + return false; + + IReader *F = FS.r_open(fn); + u16 version = 0; + + R_ASSERT(F->r_chunk(THM_CHUNK_VERSION, &version)); + if (version != THM_TEXTURE_VERSION) + { + Msg("!Thumbnail: Unsupported version."); + return false; + } + + /* + IReader* D = F->open_chunk(THM_CHUNK_DATA); R_ASSERT(D); + m_Pixels.resize (THUMB_SIZE); + D->r (m_Pixels.begin(),THUMB_SIZE*sizeof(u32)); + D->close (); + */ + + R_ASSERT(F->find_chunk(THM_CHUNK_TYPE)); + m_Type = THMType(F->r_u32()); + R_ASSERT(m_Type == ETTexture); + + m_TexParams.Load(*F); + m_Age = FS.get_file_age(fn); + + FS.r_close(F); + SetValid(); + return true; +} +//------------------------------------------------------------------------------ + +void ETextureThumbnail::Save(int age, LPCSTR path) +{ + if (!Valid()) + return; + + CMemoryWriter F; + F.open_chunk(THM_CHUNK_VERSION); + F.w_u16(THM_TEXTURE_VERSION); + F.close_chunk(); + + /* + F.w_chunk (THM_CHUNK_DATA | CFS_CompressMark,m_Pixels.begin(),m_Pixels.size()*sizeof(u32)); + */ + + F.open_chunk(THM_CHUNK_TYPE); + F.w_u32(m_Type); + F.close_chunk(); + + m_TexParams.Save(F); + + string_path fn; + if (path) + FS.update_path(fn, path, m_Name.c_str()); + else + FS.update_path(fn, _game_textures_, m_Name.c_str()); + + if (F.save_to(fn)) + { + FS.set_file_age(fn, age ? age : m_Age); + } + else + { + Log("!Can't save thumbnail:", fn); + } +} +//------------------------------------------------------------------------------ + +void ETextureThumbnail::FillProp(PropItemVec &items, PropValue::TOnChange on_type_change) +{ + m_TexParams.FillProp(m_SrcName.c_str(), items, on_type_change); +} +//------------------------------------------------------------------------------ + +void ETextureThumbnail::FillInfo(PropItemVec &items) +{ + STextureParams &F = m_TexParams; + PHelper().CreateCaption(items, "Format", get_token_name(tfmt_token, F.fmt)); + PHelper().CreateCaption(items, "Type", get_token_name(ttype_token, F.type)); + PHelper().CreateCaption(items, "Width", shared_str().printf("%d", _Width())); + PHelper().CreateCaption(items, "Height", shared_str().printf("%d", _Height())); + PHelper().CreateCaption(items, "Alpha", _Alpha() ? "on" : "off"); +} + +void ETextureThumbnail::Update(ImTextureID &Texture) +{ + VERIFY(!Texture); + if (0 == m_Pixels.size()) + { + u32 image_w, image_h, image_a; + xr_string fn_img = EFS.ChangeFileExt(m_Name.c_str(), ".tga"); + string_path fn; + FS.update_path(fn, _textures_, fn_img.c_str()); + + if (!FS.exist(fn)) + { + fn_img = EFS.ChangeFileExt(m_Name.c_str(), ".dds"); + FS.update_path(fn, _game_textures_, fn_img.c_str()); + + if (!FS.exist(fn)) + { + ELog.Msg(mtError, "Can't make preview for texture '%s'.", m_Name.c_str()); + return; + } + } + + U32Vec data; + u32 w, h, a; + if (!Stbi_Load(fn, data, image_w, image_h, image_a)) + { + + fn_img = EFS.ChangeFileExt(m_Name.c_str(), ".dds"); + u32 mem = 0; + Texture = ::RImplementation.texture_load(fn_img.c_str(), mem); + if (!Texture) + ELog.Msg(mtError, "Can't make preview for texture '%s'.", m_Name.c_str()); + + return; + } + ImageLib.MakeThumbnailImage(this, data.data(), image_w, image_h, image_a); + } + + if (Valid()) + { + + inherited::Update(Texture); + } +} + +BOOL ETextureThumbnail::similar(ETextureThumbnail *thm1, xr_vector &sel_params) +{ + BOOL res = m_TexParams.similar(thm1->m_TexParams, sel_params); + /* + if(res) + { + xr_vector::iterator it = sel_params.begin(); + xr_vector::iterator it_e = sel_params.end(); + + for(;it!=it_e;++it) + { + const xr_string& par_name = *it; + if(par_name=="Format") + { + res = (m_TexParams.fmt == thm1->m_TexParams.fmt); + }else + if(par_name=="Type") + { + res = (m_TexParams.type == thm1->m_TexParams.type); + }else + if(par_name=="Width") + { + res = (_Width()==thm1->_Width()); + }else + if(par_name=="Height") + { + res = (_Height()==thm1->_Height()); + }else + if(par_name=="Alpha") + { + res = (_Alpha()==thm1->_Alpha()); + } + if(!res) + break; + } + } + */ + return res; +} + +LPCSTR ETextureThumbnail::FormatString() +{ + return m_TexParams.FormatString(); +} +//------------------------------------------------------------------------------ diff --git a/src/editors/xrECore/Editor/EditMesh.cpp b/src/editors/xrECore/Editor/EditMesh.cpp new file mode 100644 index 00000000000..958f37b9db2 --- /dev/null +++ b/src/editors/xrECore/Editor/EditMesh.cpp @@ -0,0 +1,553 @@ +#include "stdafx.h" +#include "EditMesh.h" +#include "EditObject.h" +#include "xrCore/Animation/Bone.hpp" + +#include "face_smoth_flags.h" +#include "itterate_adjacents.h" +#include "itterate_adjacents_dynamic.h" + +#ifdef _EDITOR +#include "UI_ToolsCustom.h" +#endif + +#include "utils/ETools/ETools.h" + +CEditableMesh::~CEditableMesh() +{ + Clear(); +#ifdef _EDITOR + R_ASSERT2(0 == m_RenderBuffers, "Render buffer still referenced."); +#endif +} + +void CEditableMesh::Construct() +{ + m_Box.set(0, 0, 0, 0, 0, 0); + m_Flags.assign(flVisible); + m_Name = ""; +#ifdef _EDITOR + m_CFModel = 0; +#endif + m_Vertices = 0; + m_SmoothGroups = 0; + m_Adjs = 0; + m_Faces = 0; + m_FaceNormals = 0; + m_VertexNormals = 0; + m_SVertices = 0; + m_SVertInfl = 0; +#ifdef _EDITOR + m_RenderBuffers = 0; +#endif + m_FNormalsRefs = 0; + m_VNormalsRefs = 0; + m_AdjsRefs = 0; + m_SVertRefs = 0; +} + +void CEditableMesh::Clear() +{ +#ifdef _EDITOR + UnloadRenderBuffers(); +#endif + UnloadAdjacency(); + UnloadCForm(); + UnloadFNormals(); + UnloadVNormals(); + UnloadSVertices(); + if (m_SmoothGroups) + xr_free(m_SmoothGroups); + m_SmoothGroups = 0; + VERIFY(m_FNormalsRefs == 0 && m_VNormalsRefs == 0 && m_AdjsRefs == 0 && m_SVertRefs == 0); + + xr_free(m_Vertices); + xr_free(m_Faces); + for (VMapIt vm_it = m_VMaps.begin(); vm_it != m_VMaps.end(); vm_it++) + xr_delete(*vm_it); + m_VMaps.clear(); + m_SurfFaces.clear(); + for (VMRefsIt ref_it = m_VMRefs.begin(); ref_it != m_VMRefs.end(); ref_it++) + xr_free(ref_it->pts); + m_VMRefs.clear(); +} + +void CEditableMesh::UnloadCForm() +{ +#ifdef _EDITOR + ETOOLS::destroy_model(m_CFModel); +#endif +} + +void CEditableMesh::UnloadFNormals(bool force) +{ + m_FNormalsRefs--; + if (force || m_FNormalsRefs <= 0) + { + xr_free(m_FaceNormals); + m_FNormalsRefs = 0; + } +} +void CEditableMesh::UnloadVNormals(bool force) +{ + m_VNormalsRefs--; + if (force || m_VNormalsRefs <= 0) + { + xr_free(m_VertexNormals); + m_VNormalsRefs = 0; + } +} +void CEditableMesh::UnloadSVertices(bool force) +{ + m_SVertRefs--; + if (force || m_SVertRefs <= 0) + { + xr_free(m_SVertices); + m_SVertRefs = 0; + } +} +void CEditableMesh::UnloadAdjacency(bool force) +{ + m_AdjsRefs--; + if (force || m_AdjsRefs <= 0) + { + xr_delete(m_Adjs); + m_AdjsRefs = 0; + } +} + +void CEditableMesh::RecomputeBBox() +{ + if (0 == m_VertCount) + { + m_Box.set(0, 0, 0, 0, 0, 0); + return; + } + m_Box.set(m_Vertices[0], m_Vertices[0]); + for (u32 k = 1; k < m_VertCount; k++) + m_Box.modify(m_Vertices[k]); +} + +void CEditableMesh::GenerateFNormals() +{ + m_FNormalsRefs++; + if (m_FaceNormals) + return; + m_FaceNormals = xr_alloc(m_FaceCount); + + // face normals + for (u32 k = 0; k < m_FaceCount; k++) + m_FaceNormals[k].mknormal(m_Vertices[m_Faces[k].pv[0].pindex], + m_Vertices[m_Faces[k].pv[1].pindex], + m_Vertices[m_Faces[k].pv[2].pindex]); +} +BOOL CEditableMesh::m_bDraftMeshMode = FALSE; + +void CEditableMesh::GenerateVNormals(const Fmatrix *parent_xform) +{ + m_VNormalsRefs++; + if (m_VertexNormals) + return; + m_VertexNormals = xr_alloc(m_FaceCount * 3); + + // gen req + GenerateFNormals(); + GenerateAdjacency(); + + for (u32 f_i = 0; f_i < m_FaceCount; f_i++) + { + + for (int k = 0; k < 3; k++) + { + Fvector &N = m_VertexNormals[f_i * 3 + k]; + IntVec &a_lst = (*m_Adjs)[m_Faces[f_i].pv[k].pindex]; + + IntIt face_adj_it = std::find(a_lst.begin(), a_lst.end(), f_i); + VERIFY(face_adj_it != a_lst.end()); + // + N.set(m_FaceNormals[a_lst.front()]); + if (m_bDraftMeshMode) + continue; + + using iterate_adj = itterate_adjacents>; + iterate_adj::recurse_tri_params p(N, m_SmoothGroups, m_FaceNormals, a_lst, m_Faces, m_FaceCount); + iterate_adj::RecurseTri(face_adj_it - a_lst.begin(), p); + float len = N.magnitude(); + if (len > EPS_S) + { + N.div(len); + } + else + { + //. Msg ("!Invalid smooth group found (Maya type). Object: '%s'. Vertex: [%3.2f, %3.2f, %3.2f]",m_Parent->GetName(),VPUSH(m_Vertices[m_Faces[f_i].pv[k].pindex])); + +#ifdef _EDITOR + if (parent_xform) + { + Fvector p0; + parent_xform->transform_tiny(p0, m_Vertices[m_Faces[f_i].pv[k].pindex]); + Tools->m_DebugDraw.AppendPoint(p0, 0xffff0000, true, true, "invalid vNORMAL"); + } +#endif + + N.set(m_FaceNormals[a_lst.front()]); + } + } + } + + UnloadFNormals(); + UnloadAdjacency(); +} +/* +void CEditableMesh::GenerateVNormals(const Fmatrix* parent_xform) +{ + m_VNormalsRefs++; + if (m_VertexNormals) return; + m_VertexNormals = xr_alloc(m_FaceCount*3); + + // gen req + GenerateFNormals (); + GenerateAdjacency (); + + // vertex normals + if (m_Flags.is(flSGMask)) + { + for (u32 f_i=0; f_i > iterate_adj ; + iterate_adj::recurse_tri_params p( N, m_SmoothGroups, m_FaceNormals, a_lst, m_Faces, m_FaceCount ); + iterate_adj::RecurseTri( 0, p ); +// + if (sg) + { + N.set (0,0,0); + + VERIFY(a_lst.size()); + for (IntIt i_it=a_lst.begin(); i_it!=a_lst.end(); i_it++) + if (sg&m_SmoothGroups[*i_it]) + N.add (m_FaceNormals[*i_it]); + + float len = N.magnitude(); + if (len>EPS_S) + { + N.div (len); + }else + { +//. Msg ("!Invalid smooth group found (MAX type). Object: '%s'. Vertex: [%3.2f, %3.2f, %3.2f]",m_Parent->GetName(),VPUSH(m_Vertices[m_Faces[f_i].pv[k].pindex])); +#ifdef _EDITOR + Fvector p0; + p0 = m_Vertices[m_Faces[f_i].pv[k].pindex]; + Tools->m_DebugDraw.AppendPoint(p0, 0xffff0000, true, true, "invalid vNORMAL"); +#endif + N.set (m_FaceNormals[a_lst.front()]); + } + }else + { + N.set (FN); + } + } + } + }else{ + for (u32 f_i=0; f_i > iterate_adj ; + iterate_adj::recurse_tri_params p( N, m_SmoothGroups, m_FaceNormals, a_lst, m_Faces, m_FaceCount ); + iterate_adj::RecurseTri( 0, p ); +// + VERIFY (a_lst.size()); + for (IntIt i_it=a_lst.begin(); i_it!=a_lst.end(); i_it++) + { + if (sg != m_SmoothGroups[*i_it]) + continue; + N.add (m_FaceNormals[*i_it]); + } + float len = N.magnitude(); + if (len>EPS_S) + { + N.div (len); + }else + { +//. Msg ("!Invalid smooth group found (Maya type). Object: '%s'. Vertex: [%3.2f, %3.2f, %3.2f]",m_Parent->GetName(),VPUSH(m_Vertices[m_Faces[f_i].pv[k].pindex])); + +#ifdef _EDITOR + if(parent_xform) + { + Fvector p0; + parent_xform->transform_tiny(p0, m_Vertices[m_Faces[f_i].pv[k].pindex]); + Tools->m_DebugDraw.AppendPoint(p0, 0xffff0000, true, true, "invalid vNORMAL"); + } +#endif + + N.set (m_FaceNormals[a_lst.front()]); + } + } + else + { + N.set (FN); + + //IntVec& a_lst=(*m_Adjs)[m_Faces[f_i].pv[k].pindex]; + //VERIFY(a_lst.size()); + //for (IntIt i_it=a_lst.begin(); i_it!=a_lst.end(); i_it++) + // N.add (m_FNormals[*i_it]); + // float len = N.magnitude(); + // if (len>EPS_S){ + // N.div (len); + // }else{ + // Msg ("!Invalid smooth group found (No smooth). Object: '%s'. Vertex: [%3.2f, %3.2f, %3.2f]",m_Parent->GetName(),VPUSH(m_Verts[m_Faces[f_i].pv[k].pindex])); + // N.set (m_FNormals[a_lst.front()]); + // } + + } + } + } + } + UnloadFNormals (); + UnloadAdjacency (); +} +*/ +void CEditableMesh::GenerateSVertices(u32 influence) +{ + if (!m_Parent->IsSkeleton()) + return; + + m_SVertRefs++; + if (m_SVertInfl != influence) + UnloadSVertices(true); + if (m_SVertices) + return; + m_SVertices = xr_alloc(m_FaceCount * 3); + m_SVertInfl = influence; + + // CSMotion* active_motion=m_Parent->ResetSAnimation(); + m_Parent->CalculateAnimation(0); + + // generate normals + GenerateFNormals(); + GenerateVNormals(0); + + for (u32 f_id = 0; f_id < m_FaceCount; f_id++) + { + st_Face &F = m_Faces[f_id]; + + for (int k = 0; k < 3; ++k) + { + st_SVert &SV = m_SVertices[f_id * 3 + k]; + const Fvector &N = m_VertexNormals[f_id * 3 + k]; + const st_FaceVert &fv = F.pv[k]; + const Fvector &P = m_Vertices[fv.pindex]; + + const st_VMapPtLst &vmpt_lst = m_VMRefs[fv.vmref]; + + st_VertexWB wb; + for (u8 vmpt_id = 0; vmpt_id != vmpt_lst.count; ++vmpt_id) + { + const st_VMap &VM = *m_VMaps[vmpt_lst.pts[vmpt_id].vmap_index]; + if (VM.type == vmtWeight) + { + wb.push_back(st_WB(m_Parent->GetBoneIndexByWMap(VM.name.c_str()), VM.getW(vmpt_lst.pts[vmpt_id].index))); + + if (wb.back().bone == BI_NONE) + { + ELog.DlgMsg(mtError, "Can't find bone assigned to weight map %s", *VM.name); + FATAL("Editor crashed."); + return; + } + } + else if (VM.type == vmtUV) + SV.uv.set(VM.getUV(vmpt_lst.pts[vmpt_id].index)); + } + + VERIFY(m_SVertInfl <= 4); + + wb.prepare_weights(m_SVertInfl); + + SV.offs = P; + SV.norm = N; + SV.bones.resize(wb.size()); + for (u8 k = 0; k < (u8)SV.bones.size(); k++) + { + SV.bones[k].id = wb[k].bone; + SV.bones[k].w = wb[k].weight; + } + } + } + + // restore active motion + UnloadFNormals(); + UnloadVNormals(); +} + +void CEditableMesh::GenerateAdjacency() +{ + m_AdjsRefs++; + if (m_Adjs) + return; + m_Adjs = xr_new(); + VERIFY(m_Faces); + m_Adjs->resize(m_VertCount); + //. Log (".. Update adjacency"); + for (u32 f_id = 0; f_id < m_FaceCount; f_id++) + for (int k = 0; k < 3; k++) + (*m_Adjs)[m_Faces[f_id].pv[k].pindex].push_back(f_id); +} + +CSurface *CEditableMesh::GetSurfaceByFaceID(u32 fid) +{ + R_ASSERT(fid < m_FaceCount); + for (SurfFacesPairIt sp_it = m_SurfFaces.begin(); sp_it != m_SurfFaces.end(); sp_it++) + { + IntVec &face_lst = sp_it->second; + IntIt f_it = std::lower_bound(face_lst.begin(), face_lst.end(), (int)fid); + if ((f_it != face_lst.end()) && (*f_it == (int)fid)) + return sp_it->first; + //. if (std::find(face_lst.begin(),face_lst.end(),fid)!=face_lst.end()) return sp_it->first; + } + return 0; +} + +void CEditableMesh::GetFaceTC(u32 fid, const Fvector2 *tc[3]) +{ + R_ASSERT(fid < m_FaceCount); + st_Face &F = m_Faces[fid]; + for (int k = 0; k < 3; k++) + { + st_VMapPt &vmr = m_VMRefs[F.pv[k].vmref].pts[0]; + tc[k] = &(m_VMaps[vmr.vmap_index]->getUV(vmr.index)); + } +} + +void CEditableMesh::GetFacePT(u32 fid, const Fvector *pt[3]) +{ + R_ASSERT(fid < m_FaceCount); + st_Face &F = m_Faces[fid]; + + for (int k = 0; k < 3; ++k) + pt[k] = &m_Vertices[F.pv[k].pindex]; +} + +int CEditableMesh::GetFaceCount(bool bMatch2Sided, bool bIgnoreOCC) +{ + static shared_str occ_name = "materials\\occ"; + int f_cnt = 0; + for (SurfFacesPairIt sp_it = m_SurfFaces.begin(); sp_it != m_SurfFaces.end(); sp_it++) + { + CSurface *S = sp_it->first; + if (S->m_GameMtlName == occ_name && bIgnoreOCC) + continue; + + if (bMatch2Sided) + { + if (S->m_Flags.is(CSurface::sf2Sided)) + f_cnt += sp_it->second.size() * 2; + else + f_cnt += sp_it->second.size(); + } + else + { + f_cnt += sp_it->second.size(); + } + } + return f_cnt; +} + +float CEditableMesh::CalculateSurfaceArea(CSurface *surf, bool bMatch2Sided) +{ + SurfFacesPairIt sp_it = m_SurfFaces.find(surf); + if (sp_it == m_SurfFaces.end()) + return 0; + float area = 0; + IntVec &pol_lst = sp_it->second; + for (int k = 0; k < int(pol_lst.size()); k++) + { + st_Face &F = m_Faces[pol_lst[k]]; + Fvector c, e01, e02; + e01.sub(m_Vertices[F.pv[1].pindex], m_Vertices[F.pv[0].pindex]); + e02.sub(m_Vertices[F.pv[2].pindex], m_Vertices[F.pv[0].pindex]); + area += c.crossproduct(e01, e02).magnitude() / 2.f; + } + if (bMatch2Sided && sp_it->first->m_Flags.is(CSurface::sf2Sided)) + area *= 2; + return area; +} + +float CEditableMesh::CalculateSurfacePixelArea(CSurface *surf, bool bMatch2Sided) +{ + SurfFacesPairIt sp_it = m_SurfFaces.find(surf); + if (sp_it == m_SurfFaces.end()) + return 0; + float area = 0; + IntVec &pol_lst = sp_it->second; + for (int k = 0; k < int(pol_lst.size()); k++) + { + // st_Face& F = m_Faces[pol_lst[k]]; + Fvector c, e01, e02; + const Fvector2 *tc[3]; + GetFaceTC(pol_lst[k], tc); + e01.sub(Fvector().set(tc[1]->x, tc[1]->y, 0), Fvector().set(tc[0]->x, tc[0]->y, 0)); + e02.sub(Fvector().set(tc[2]->x, tc[2]->y, 0), Fvector().set(tc[0]->x, tc[0]->y, 0)); + area += c.crossproduct(e01, e02).magnitude() / 2.f; + } + if (bMatch2Sided && sp_it->first->m_Flags.is(CSurface::sf2Sided)) + area *= 2; + return area; +} + +int CEditableMesh::GetSurfFaceCount(CSurface *surf, bool bMatch2Sided) +{ + SurfFacesPairIt sp_it = m_SurfFaces.find(surf); + if (sp_it == m_SurfFaces.end()) + return 0; + int f_cnt = sp_it->second.size(); + if (bMatch2Sided && sp_it->first->m_Flags.is(CSurface::sf2Sided)) + f_cnt *= 2; + return f_cnt; +} + +void CEditableMesh::DumpAdjacency() +{ + Log("Adjacency dump."); + Log("------------------------------------------------------------------------"); + /* for (u32 i=0; itype == t) && (stricmp((*vm_it)->name.c_str(), name) == 0) && (polymap == (*vm_it)->polymap)) + return vm_it - vmaps.begin(); + } + return -1; +} +//---------------------------------------------------------------------------- + +bool CEditableMesh::Validate() +{ + return true; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/Editor/EditMesh.h b/src/editors/xrECore/Editor/EditMesh.h new file mode 100644 index 00000000000..4f8ad3b10b5 --- /dev/null +++ b/src/editors/xrECore/Editor/EditMesh.h @@ -0,0 +1,454 @@ +//---------------------------------------------------- +// file: StaticMesh.h +//---------------------------------------------------- +#ifndef EditMeshH +#define EditMeshH + +//---------------------------------------------------- +// refs +class CSurface; +struct SRayPickInfo; +// struct CFrustum; +struct FSChunkDef; +class CExporter; +class CCustomObject; + +#ifdef _EDITOR +#include "pick_defs.h" +#endif + +#include "xrCore/Animation/Bone.hpp" + +#pragma pack(push, 1) +const u8 vmtUV = 0; +const u8 vmtWeight = 1; + +struct ECORE_API st_WB +{ + u16 bone; + float weight; + st_WB() : bone(BI_NONE), weight(0.f) { ; } + st_WB(u16 b, float w) : bone(b), weight(w) { ; } + void set(u16 b, float w) + { + bone = b; + weight = w; + } +}; +DEFINE_VECTOR(st_WB, WBVec, WBIt); +struct ECORE_API st_VertexWB : public WBVec +{ +protected: + static bool compare_by_weight(const st_WB &a, const st_WB &b) + { + return a.weight > b.weight; // отсортировать по убыванию + } + static bool compare_by_bone(const st_WB &a, const st_WB &b) + { + return a.bone < b.bone; // отсортировать по возрастанию + } + +public: + void sort_by_bone() + { + std::sort(begin(), end(), compare_by_bone); + } + void sort_by_weight() + { + std::sort(begin(), end(), compare_by_weight); + } + void prepare_weights(u32 max_influence) + { + sort_by_weight(); + // delete >max_influence weights + if (size() > max_influence) + erase(begin() + max_influence, end()); + // accumulate weights + float sum_weight = 0; + WBIt it; + for (it = begin(); it != end(); it++) + sum_weight += it->weight; + // normalize weights + for (it = begin(); it != end(); it++) + it->weight /= sum_weight; + // sort_by_bone (); // need only for export (before add vertex sort_by_bone) + } +}; +DEFINE_VECTOR(st_VertexWB, VWBVec, VWBIt); + +struct ECORE_API st_VMapPt +{ + int vmap_index; // ссылка на мапу + int index; // индекс в V-мапе на uv/w + st_VMapPt() + { + vmap_index = -1; + index = -1; + } +}; +// uv's +class ECORE_API st_VMap +{ + FloatVec vm; // u,v - координаты или weight +public: + shared_str name; // vertex uv map name + struct + { + u8 type : 2; + u8 polymap : 1; + u8 dim : 2; + u8 reserved : 3; + }; + IntVec vindices; + IntVec pindices; + +public: + st_VMap(LPCSTR nm = 0, u8 t = vmtUV, bool pm = false) + { + type = t; + polymap = pm; + name = nm; + if (t == vmtUV) + dim = 2; + else + dim = 1; + } + IC const Fvector2 &getUV(int idx) const + { + VERIFY(type == vmtUV); + return (Fvector2 &)vm[idx * dim]; + } + IC Fvector2 &getUV(int idx) + { + VERIFY(type == vmtUV); + return (Fvector2 &)vm[idx * dim]; + } + IC const float &getW(int idx) const + { + VERIFY(type == vmtWeight); + return vm[idx]; + } + IC const FloatVec &getVM() const { return vm; } + IC float *getVMdata() { return &*vm.begin(); } + IC float *getVMdata(int start) { return &*(vm.begin() + start * dim); } + IC int VMdatasize() { return vm.size() * sizeof(float); } + IC int *getVIdata() { return &*vindices.begin(); } + IC int VIdatasize() { return vindices.size() * sizeof(int); } + IC int *getPIdata() { return &*pindices.begin(); } + IC int PIdatasize() { return pindices.size() * sizeof(int); } + IC int size() { return vm.size() / dim; } + IC void resize(int cnt) + { + vm.resize(cnt * dim); + vindices.resize(cnt); + if (polymap) + pindices.resize(cnt); + } + IC void appendUV(const float u, const float v) + { + vm.push_back(u); + vm.push_back(v); + } + IC void appendUV(const Fvector2 &uv) { appendUV(uv.x, uv.y); } + IC void appendW(const float w) { vm.push_back(w); } + IC void appendVI(const int vi) { vindices.push_back(vi); } + IC void appendPI(const int pi) + { + VERIFY(polymap); + pindices.push_back(pi); + } + IC void copyfrom(float *src, int cnt) + { + resize(cnt); + CopyMemory(&*vm.begin(), src, cnt * dim * 4); + } +}; + +struct st_VMapPtLst +{ + u8 count; + st_VMapPt *pts; +}; +DEFINE_VECTOR(st_VMapPtLst, VMRefsVec, VMRefsIt); + +struct ECORE_API st_SVert +{ + Fvector offs; + Fvector norm; + Fvector2 uv; + struct bone + { + public: + float w; + u16 id; + bone() + { + w = 0.f; + id = BI_NONE; + } + bool similar(const bone &b) { return (id == b.id) && fsimilar(w, b.w, EPS_L); } + }; + svector bones; + +protected: + static bool compare_by_weight(const bone &a, const bone &b) + { + return a.w > b.w; // отсортировать по убыванию + } + static bool compare_by_bone(const bone &a, const bone &b) + { + return a.id < b.id; // отсортировать по возрастанию + } + +public: + void sort_by_weight() { std::sort(bones.begin(), bones.end(), compare_by_weight); } + void sort_by_bone() { std::sort(bones.begin(), bones.end(), compare_by_bone); } +}; +// faces +struct st_Face; +struct ECORE_API st_FaceVert +{ + typedef st_Face type_face; + int pindex; // point index in PointList + int vmref; // vm-ref index + bool gt(const st_FaceVert &v) const { return pindex > v.pindex; } + bool eq(const st_FaceVert &v) const { return pindex == v.pindex; } +}; +struct ECORE_API st_Face +{ + st_FaceVert pv[3]; // face vertices (P->P...) + void EdgeVerts(u8 e, st_FaceVert &v0, st_FaceVert &v1) const + { + VERIFY(e < 3); + v0 = pv[e]; + v1 = pv[(e + 1) % 3]; + } +}; + +// mesh options +struct ECORE_API st_MeshOptions +{ + int m_Reserved0; + int m_Reserved1; + st_MeshOptions() + { + m_Reserved0 = 0; + m_Reserved1 = 0; + } +}; +#pragma pack(pop) + +DEFINE_VECTOR(IntVec, AdjVec, AdjIt); +DEFINE_VECTOR(st_VMap *, VMapVec, VMapIt); +DEFINE_MAP(CSurface *, IntVec, SurfFaces, SurfFacesPairIt); + +// refs +struct st_RenderBuffer; +class CSurface; +class CSector; + +#ifdef _EDITOR +struct ECORE_API st_RenderBuffer +{ + u32 dwStartVertex; + u32 dwNumVertex; + ref_geom pGeom; + st_RenderBuffer(u32 sv, u32 nv) : dwStartVertex(sv), dwNumVertex(nv), pGeom(0) { ; } +}; +DEFINE_VECTOR(st_RenderBuffer, RBVector, RBVecIt); +DEFINE_MAP(CSurface *, RBVector, RBMap, RBMapPairIt); +#endif + +class ECORE_API CEditableMesh +{ + friend class MeshExpUtility; + friend class CEditableObject; + friend class CSectorItem; + friend class CSector; + friend class CPortalUtils; + friend class SceneBuilder; + friend class CExportSkeleton; + friend class CExportObjectOGF; + friend class TfrmEditLibrary; + friend class CExporter; + friend class CXRayObjectExport; + friend class CXRaySkinExport; + + shared_str m_Name; + + CEditableObject *m_Parent; + + void GenerateCFModel(); + void GenerateRenderBuffers(); + void UnloadCForm(); +#ifdef _EDITOR + void UnloadRenderBuffers(); +#endif +public: + static BOOL m_bDraftMeshMode; + void GenerateFNormals(); + void GenerateVNormals(const Fmatrix *parent_xform); + void GenerateSVertices(u32 influence); + void GenerateAdjacency(); + + bool IsGeneratedSVertices(u32 influence) { return (m_SVertices && (m_SVertInfl == influence)); } + + void UnloadFNormals(bool force = false); + void UnloadVNormals(bool force = false); + void UnloadSVertices(bool force = false); + void UnloadAdjacency(bool force = false); + IC Fvector *Vertices() { return m_Vertices; } // + IC st_Face *Faces() { return m_Faces; } // + some array size!!! + IC SurfFaces &Surfaces() { return m_SurfFaces; } + +private: + // internal variables + enum + { + flVisible = (1 << 0), + flLocked = (1 << 1), + flSGMask = (1 << 2), + }; + Flags8 m_Flags; + +public: + st_MeshOptions m_Ops; + +protected: + Fbox m_Box; + + int m_FNormalsRefs; + int m_VNormalsRefs; + int m_AdjsRefs; + int m_SVertRefs; + + u32 m_SVertInfl; + + u32 m_VertCount; + u32 m_FaceCount; + + Fvector *m_Vertices; // | + AdjVec *m_Adjs; // + some array size!!! + u32 *m_SmoothGroups; // | + Fvector *m_FaceNormals; // | + Fvector *m_VertexNormals; // | *3 + st_SVert *m_SVertices; // | *3 + st_Face *m_Faces; // + some array size!!! + SurfFaces m_SurfFaces; + VMapVec m_VMaps; + VMRefsVec m_VMRefs; + +#ifdef _EDITOR + CDB::MODEL *m_CFModel; + RBMap *m_RenderBuffers; +#endif + + void FillRenderBuffer(IntVec &face_lst, int start_face, int num_face, const CSurface *surf, LPBYTE &data); + + void RecurseTri(int id); + + // mesh optimize routine + bool OptimizeFace(st_Face &face); + +public: + void RecomputeBBox(); + void OptimizeMesh(BOOL NoOpt); + +public: + CEditableMesh(CEditableObject *parent) + { + m_Parent = parent; + Construct(); + } + virtual ~CEditableMesh(); + void Construct(); + void Clear(); + + IC void SetName(LPCSTR name) { m_Name = name; } + IC shared_str Name() { return m_Name; } + void GetBox(Fbox &box) { box.set(m_Box); } + CSurface *GetSurfaceByFaceID(u32 fid); + void GetFaceTC(u32 fid, const Fvector2 *tc[3]); + void GetFacePT(u32 fid, const Fvector *pt[3]); + IC BOOL Visible() { return m_Flags.is(flVisible); } + IC void Show(BOOL bVisible) { m_Flags.set(flVisible, bVisible); } + + // mesh modify routine + void Transform(const Fmatrix &parent); + + IC CEditableObject *Parent() { return m_Parent; } + IC u32 GetFCount() { return m_FaceCount; } + IC const st_Face *GetFaces() { return m_Faces; } + IC const u32 *GetSmoothGroups() { return m_SmoothGroups; } + IC const Fvector *GetVertices() { return m_Vertices; } + IC u32 GetVCount() { return m_VertCount; } + IC const VMapVec &GetVMaps() { return m_VMaps; } + IC const VMRefsVec &GetVMRefs() { return m_VMRefs; } + IC const SurfFaces &GetSurfFaces() { return m_SurfFaces; } + IC const Fvector *GetFNormals() + { + VERIFY(0 != m_FaceNormals); + return m_FaceNormals; + } + IC const Fvector *GetVNormals() + { + VERIFY(0 != m_VertexNormals); + return m_VertexNormals; + } + IC const st_SVert *GetSVertices() + { + VERIFY(0 != m_SVertices); + return m_SVertices; + } + + // pick routine + bool RayPick(float &dist, const Fvector &start, const Fvector &dir, const Fmatrix &inv_parent, SRayPickInfo *pinf = NULL); +#ifdef _EDITOR + void RayQuery(SPickQuery &pinf); + void RayQuery(const Fmatrix &parent, const Fmatrix &inv_parent, SPickQuery &pinf); + void BoxQuery(const Fmatrix &parent, const Fmatrix &inv_parent, SPickQuery &pinf); + bool BoxPick(const Fbox &box, const Fmatrix &inv_parent, SBoxPickInfoVec &pinf); + bool FrustumPick(const CFrustum &frustum, const Fmatrix &parent); + void FrustumPickFaces(const CFrustum &frustum, const Fmatrix &parent, U32Vec &fl); + bool CHullPickMesh(PlaneVec &pl, const Fmatrix &parent); + void GetTiesFaces(int start_id, U32Vec &fl, float fSoftAngle, bool bRecursive); +#endif + + // render routine + void Render(const Fmatrix &parent, CSurface *S); + void RenderSkeleton(const Fmatrix &parent, CSurface *S); + void RenderList(const Fmatrix &parent, u32 color, bool bEdge, IntVec &fl); + void RenderSelection(const Fmatrix &parent, CSurface *s, u32 color); + void RenderEdge(const Fmatrix &parent, CSurface *s, u32 color); + + // statistics methods + int GetFaceCount(bool bMatch2Sided = true, bool bIgnoreOCC = true); + int GetVertexCount() { return m_VertCount; } + int GetSurfFaceCount(CSurface *surf, bool bMatch2Sided = true); + float CalculateSurfaceArea(CSurface *surf, bool bMatch2Sided); + float CalculateSurfacePixelArea(CSurface *surf, bool bMatch2Sided); + + // IO - routine + void SaveMesh(IWriter &); + bool LoadMesh(IReader &); + + // debug + void DumpAdjacency(); + + // convert +#ifdef _MAX_EXPORT + void FlipFaces(); + TriObject *ExtractTriObject(INode *node, int &deleteIt); + bool Convert(INode *node); + bool Convert(CExporter *exporter); +#endif + + int FindSimilarUV(st_VMap *vmap, Fvector2 &_uv); + int FindSimilarWeight(st_VMap *vmap, float _w); + int FindVMapByName(VMapVec &vmaps, const char *name, u8 t, bool polymap); + void RebuildVMaps(); + + bool Validate(); +}; +//---------------------------------------------------- +#endif /*_INCDEF_EditableMesh_H_*/ diff --git a/src/editors/xrECore/Editor/EditMeshIO.cpp b/src/editors/xrECore/Editor/EditMeshIO.cpp new file mode 100644 index 00000000000..b8aa8fe4ee1 --- /dev/null +++ b/src/editors/xrECore/Editor/EditMeshIO.cpp @@ -0,0 +1,246 @@ +//---------------------------------------------------- +// file: StaticMesh.cpp +//---------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +#include "EditMesh.h" +#include "EditObject.h" + +#define EMESH_CURRENT_VERSION 0x0011 +//---------------------------------------------------- +#define EMESH_CHUNK_VERSION 0x1000 +#define EMESH_CHUNK_MESHNAME 0x1001 +#define EMESH_CHUNK_FLAGS 0x1002 +#define EMESH_CHUNK_NOT_USED_0 0x1003 +#define EMESH_CHUNK_BBOX 0x1004 +#define EMESH_CHUNK_VERTS 0x1005 +#define EMESH_CHUNK_FACES 0x1006 +#define EMESH_CHUNK_VMAPS_0 0x1007 +#define EMESH_CHUNK_VMREFS 0x1008 +#define EMESH_CHUNK_SFACE 0x1009 +#define EMESH_CHUNK_BOP 0x1010 +#define EMESH_CHUNK_VMAPS_1 0x1011 +#define EMESH_CHUNK_VMAPS_2 0x1012 +#define EMESH_CHUNK_SG 0x1013 + +void CEditableMesh::SaveMesh(IWriter &F) +{ + F.open_chunk(EMESH_CHUNK_VERSION); + F.w_u16(EMESH_CURRENT_VERSION); + F.close_chunk(); + + F.open_chunk(EMESH_CHUNK_MESHNAME); + F.w_stringZ(m_Name); + F.close_chunk(); + + F.w_chunk(EMESH_CHUNK_BBOX, &m_Box, sizeof(m_Box)); + F.w_chunk(EMESH_CHUNK_FLAGS, &m_Flags, 1); + F.w_chunk(EMESH_CHUNK_BOP, &m_Ops, sizeof(m_Ops)); + + F.open_chunk(EMESH_CHUNK_VERTS); + F.w_u32(m_VertCount); + F.w(m_Vertices, m_VertCount * sizeof(Fvector)); + + F.close_chunk(); + + F.open_chunk(EMESH_CHUNK_FACES); + F.w_u32(m_FaceCount); + F.w(m_Faces, m_FaceCount * sizeof(st_Face)); + F.close_chunk(); + + if (GetSmoothGroups()) + { + F.open_chunk(EMESH_CHUNK_SG); + F.w(GetSmoothGroups(), m_FaceCount * sizeof(u32)); + F.close_chunk(); + } + + F.open_chunk(EMESH_CHUNK_VMREFS); + F.w_u32(m_VMRefs.size()); + for (VMRefsIt r_it = m_VMRefs.begin(); r_it != m_VMRefs.end(); r_it++) + { + int sz = r_it->count; + VERIFY(sz <= 255); + F.w_u8((u8)sz); + F.w(r_it->pts, sizeof(st_VMapPt) * sz); + } + F.close_chunk(); + + F.open_chunk(EMESH_CHUNK_SFACE); + F.w_u16((u16)m_SurfFaces.size()); /* surface polygon count*/ + for (SurfFacesPairIt plp_it = m_SurfFaces.begin(); plp_it != m_SurfFaces.end(); plp_it++) + { + F.w_stringZ(plp_it->first->_Name()); /* surface name*/ + IntVec &pol_lst = plp_it->second; + F.w_u32(pol_lst.size()); /* surface-polygon indices*/ + F.w(&*pol_lst.begin(), sizeof(int) * pol_lst.size()); + } + F.close_chunk(); + + F.open_chunk(EMESH_CHUNK_VMAPS_2); + F.w_u32(m_VMaps.size()); + for (VMapIt vm_it = m_VMaps.begin(); vm_it != m_VMaps.end(); vm_it++) + { + F.w_stringZ((*vm_it)->name); + F.w_u8((*vm_it)->dim); + F.w_u8((u8)(*vm_it)->polymap); + F.w_u8((*vm_it)->type); + F.w_u32((*vm_it)->size()); + F.w((*vm_it)->getVMdata(), (*vm_it)->VMdatasize()); + F.w((*vm_it)->getVIdata(), (*vm_it)->VIdatasize()); + if ((*vm_it)->polymap) + F.w((*vm_it)->getPIdata(), (*vm_it)->PIdatasize()); + } + F.close_chunk(); +} + +bool CEditableMesh::LoadMesh(IReader &F) +{ + u32 version = 0; + + R_ASSERT(F.r_chunk(EMESH_CHUNK_VERSION, &version)); + if (version != EMESH_CURRENT_VERSION) + { + ELog.DlgMsg(mtError, "CEditableMesh: unsuported file version. Mesh can't load."); + return false; + } + + R_ASSERT(F.find_chunk(EMESH_CHUNK_MESHNAME)); + F.r_stringZ(m_Name); + + R_ASSERT(F.r_chunk(EMESH_CHUNK_BBOX, &m_Box)); + R_ASSERT(F.r_chunk(EMESH_CHUNK_FLAGS, &m_Flags)); + F.r_chunk(EMESH_CHUNK_BOP, &m_Ops); + + R_ASSERT(F.find_chunk(EMESH_CHUNK_VERTS)); + m_VertCount = F.r_u32(); + if (m_VertCount < 3) + { + Log("!CEditableMesh: Vertices<3."); + return false; + } + m_Vertices = xr_alloc(m_VertCount); + F.r(m_Vertices, m_VertCount * sizeof(Fvector)); + + R_ASSERT(F.find_chunk(EMESH_CHUNK_FACES)); + m_FaceCount = F.r_u32(); + m_Faces = xr_alloc(m_FaceCount); + if (m_FaceCount == 0) + { + Log("!CEditableMesh: Faces==0."); + return false; + } + F.r(m_Faces, m_FaceCount * sizeof(st_Face)); + + m_SmoothGroups = xr_alloc(m_FaceCount); + MemFill32(m_SmoothGroups, m_Flags.is(flSGMask) ? 0 : u32(-1), m_FaceCount); + u32 sg_chunk_size = F.find_chunk(EMESH_CHUNK_SG); + if (sg_chunk_size) + { + VERIFY(m_FaceCount * sizeof(u32) == sg_chunk_size); + F.r(m_SmoothGroups, m_FaceCount * sizeof(u32)); + } + + R_ASSERT(F.find_chunk(EMESH_CHUNK_VMREFS)); + m_VMRefs.resize(F.r_u32()); + int sz_vmpt = sizeof(st_VMapPt); + for (VMRefsIt r_it = m_VMRefs.begin(); r_it != m_VMRefs.end(); r_it++) + { + r_it->count = F.r_u8(); + r_it->pts = xr_alloc(r_it->count); + F.r(r_it->pts, sz_vmpt * r_it->count); + } + + R_ASSERT(F.find_chunk(EMESH_CHUNK_SFACE)); + string128 surf_name; + u32 sface_cnt = F.r_u16(); // surface-face count + for (u32 sp_i = 0; sp_i < sface_cnt; sp_i++) + { + F.r_stringZ(surf_name, sizeof(surf_name)); + int surf_id; + CSurface *surf = m_Parent->FindSurfaceByName(surf_name, &surf_id); + VERIFY(surf); + IntVec &face_lst = m_SurfFaces[surf]; + face_lst.resize(F.r_u32()); + if (face_lst.empty()) + { + Log("!Empty surface found: %s", surf->_Name()); + return false; + } + F.r(&*face_lst.begin(), face_lst.size() * sizeof(int)); + std::sort(face_lst.begin(), face_lst.end()); + } + + if (F.find_chunk(EMESH_CHUNK_VMAPS_2)) + { + m_VMaps.resize(F.r_u32()); + for (VMapIt vm_it = m_VMaps.begin(); vm_it != m_VMaps.end(); vm_it++) + { + *vm_it = xr_new(); + F.r_stringZ((*vm_it)->name); + (*vm_it)->dim = F.r_u8(); + (*vm_it)->polymap = F.r_u8(); + (*vm_it)->type = F.r_u8(); + (*vm_it)->resize(F.r_u32()); + F.r((*vm_it)->getVMdata(), (*vm_it)->VMdatasize()); + F.r((*vm_it)->getVIdata(), (*vm_it)->VIdatasize()); + if ((*vm_it)->polymap) + F.r((*vm_it)->getPIdata(), (*vm_it)->PIdatasize()); + } + } + else + { + if (F.find_chunk(EMESH_CHUNK_VMAPS_1)) + { + m_VMaps.resize(F.r_u32()); + for (VMapIt vm_it = m_VMaps.begin(); vm_it != m_VMaps.end(); vm_it++) + { + *vm_it = xr_new(); + F.r_stringZ((*vm_it)->name); + (*vm_it)->dim = F.r_u8(); + (*vm_it)->type = F.r_u8(); + (*vm_it)->resize(F.r_u32()); + F.r((*vm_it)->getVMdata(), (*vm_it)->VMdatasize()); + } + } + else + { + R_ASSERT(F.find_chunk(EMESH_CHUNK_VMAPS_0)); + m_VMaps.resize(F.r_u32()); + for (VMapIt vm_it = m_VMaps.begin(); vm_it != m_VMaps.end(); vm_it++) + { + *vm_it = xr_new(); + F.r_stringZ((*vm_it)->name); + (*vm_it)->dim = 2; + (*vm_it)->type = vmtUV; + (*vm_it)->resize(F.r_u32()); + F.r((*vm_it)->getVMdata(), (*vm_it)->VMdatasize()); + } + } + // update vmaps + RebuildVMaps(); + } + +#ifdef _EDITOR + if (!EPrefs->object_flags.is(epoDeffLoadRB)) + { + GenerateFNormals(); + GenerateAdjacency(); + GenerateVNormals(0); + GenerateRenderBuffers(); + UnloadFNormals(); + UnloadAdjacency(); + UnloadVNormals(); + } + + if (!EPrefs->object_flags.is(epoDeffLoadCF)) + GenerateCFModel(); +#endif + // OptimizeMesh (false); + RebuildVMaps(); + + return true; +} +//---------------------------------------------------- diff --git a/src/editors/xrECore/Editor/EditMeshModify.cpp b/src/editors/xrECore/Editor/EditMeshModify.cpp new file mode 100644 index 00000000000..5df6a8cd576 --- /dev/null +++ b/src/editors/xrECore/Editor/EditMeshModify.cpp @@ -0,0 +1,347 @@ +//---------------------------------------------------- +// file: EditMeshModify.cpp +//---------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +#include "EditMesh.h" + +//---------------------------------------------------- +void CEditableMesh::Transform(const Fmatrix &parent) +{ + // transform position + for (u32 k = 0; k < m_VertCount; ++k) + parent.transform_tiny(m_Vertices[k]); + + // RecomputeBBox + RecomputeBBox(); + // update normals & cform +#ifdef _EDITOR + UnloadRenderBuffers(); + UnloadCForm(); +#endif + UnloadFNormals(true); + UnloadVNormals(true); + UnloadSVertices(true); +} +//---------------------------------------------------- + +int CEditableMesh::FindSimilarUV(st_VMap *vmap, Fvector2 &_uv) +{ + int sz = vmap->size(); + for (int k = 0; k < sz; ++k) + { + const Fvector2 &uv = vmap->getUV(k); + if (uv.similar(_uv)) + return k; + } + return -1; +} + +int CEditableMesh::FindSimilarWeight(st_VMap *vmap, float _w) +{ + int sz = vmap->size(); + for (int k = 0; k < sz; ++k) + { + float w = vmap->getW(k); + if (fsimilar(w, _w)) + return k; + } + return -1; +} + +void CEditableMesh::RebuildVMaps() +{ + //. Log ("Rebuilding VMaps..."); + IntVec m_VertVMap; + m_VertVMap.resize(m_VertCount, -1); + VMapVec nVMaps; + VMRefsVec nVMRefs; + // refs copy to new + { + nVMRefs.resize(m_VMRefs.size()); + for (VMRefsIt o_it = m_VMRefs.begin(), n_it = nVMRefs.begin(); o_it != m_VMRefs.end(); o_it++, n_it++) + { + n_it->count = o_it->count; + n_it->pts = xr_alloc(n_it->count); + } + } + + for (u32 f_id = 0; f_id < m_FaceCount; f_id++) + { + st_Face &F = m_Faces[f_id]; + for (int k = 0; k < 3; k++) + { + u32 pts_cnt = m_VMRefs[F.pv[k].vmref].count; + for (u32 pt_id = 0; pt_id < pts_cnt; pt_id++) + { + st_VMapPt *n_pt_it = &nVMRefs[F.pv[k].vmref].pts[pt_id]; + st_VMapPt *o_pt_it = &m_VMRefs[F.pv[k].vmref].pts[pt_id]; + st_VMap *vmap = m_VMaps[o_pt_it->vmap_index]; + switch (vmap->type) + { + case vmtUV: + { + int &pm = m_VertVMap[F.pv[k].pindex]; + if (-1 == pm) + { // point map + pm = F.pv[k].vmref; + int vm_idx = FindVMapByName(nVMaps, vmap->name.c_str(), vmap->type, false); + if (-1 == vm_idx) + { + nVMaps.push_back(xr_new(vmap->name.c_str(), static_cast(vmap->type), false)); + vm_idx = nVMaps.size() - 1; + } + st_VMap *nVMap = nVMaps[vm_idx]; + + // int uv_idx = FindSimilarUV(nVMap,vmap->getUV(pt_it->index)); + // if (uv_idx==-1){ + // uv_idx = nVMap->size(); + // nVMap->appendUV(vmap->getUV(pt_it->index)); + // nVMap->appendVI(F.pv[k].pindex); + // } + + nVMap->appendUV(vmap->getUV(o_pt_it->index)); + nVMap->appendVI(F.pv[k].pindex); + n_pt_it->index = nVMap->size() - 1; + n_pt_it->vmap_index = vm_idx; + } + else + { // poly map + int vm_idx = FindVMapByName(nVMaps, vmap->name.c_str(), vmap->type, true); + if (-1 == vm_idx) + { + nVMaps.push_back(xr_new(vmap->name.c_str(), static_cast(vmap->type), true)); + vm_idx = nVMaps.size() - 1; + } + st_VMap *nVMapPM = nVMaps[vm_idx]; + + // int uv_idx = FindSimilarUV(nVMapPM,vmap->getUV(pt_it->index)); + // if (uv_idx==-1){ + // uv_idx = nVMapPM->size(); + // nVMapPM->appendUV(vmap->getUV(pt_it->index)); + // nVMapPM->appendVI(F.pv[k].pindex); + // nVMapPM->appendPI(f_it-m_Faces.begin()); + // } + // n_pt_it->index = uv_idx; + + nVMapPM->appendUV(vmap->getUV(o_pt_it->index)); + nVMapPM->appendVI(F.pv[k].pindex); + nVMapPM->appendPI(f_id); + n_pt_it->index = nVMapPM->size() - 1; + n_pt_it->vmap_index = vm_idx; + } + } + break; + case vmtWeight: + { + int vm_idx = FindVMapByName(nVMaps, vmap->name.c_str(), vmap->type, false); + if (-1 == vm_idx) + { + nVMaps.push_back(xr_new(vmap->name.c_str(), static_cast(vmap->type), false)); + vm_idx = nVMaps.size() - 1; + } + st_VMap *nWMap = nVMaps[vm_idx]; + nWMap->appendW(vmap->getW(o_pt_it->index)); + nWMap->appendVI(F.pv[k].pindex); + n_pt_it->index = nWMap->size() - 1; + n_pt_it->vmap_index = vm_idx; + } + break; + } + } + } + } + for (VMapIt vm_it = m_VMaps.begin(); vm_it != m_VMaps.end(); vm_it++) + xr_delete(*vm_it); + + m_VMaps.clear(); + m_VMaps = nVMaps; + // clear refs + for (VMRefsIt ref_it = m_VMRefs.begin(); ref_it != m_VMRefs.end(); ref_it++) + xr_free(ref_it->pts); + m_VMRefs.clear(); + m_VMRefs = nVMRefs; +} + +#define MX 25 +#define MY 15 +#define MZ 25 +static Fvector VMmin, VMscale; +static U32Vec VM[MX + 1][MY + 1][MZ + 1]; +static Fvector VMeps; + +static FvectorVec m_NewPoints; +bool CEditableMesh::OptimizeFace(st_Face &face) +{ + Fvector points[3]; + int mface[3]; + int k; + + for (k = 0; k < 3; k++) + { + points[k].set(m_Vertices[face.pv[k].pindex]); + mface[k] = -1; + } + + // get similar vert idx list + for (k = 0; k < 3; k++) + { + U32Vec *vl; + int ix, iy, iz; + ix = iFloor(float(points[k].x - VMmin.x) / VMscale.x * MX); + iy = iFloor(float(points[k].y - VMmin.y) / VMscale.y * MY); + iz = iFloor(float(points[k].z - VMmin.z) / VMscale.z * MZ); + vl = &(VM[ix][iy][iz]); + for (U32It it = vl->begin(); it != vl->end(); it++) + { + FvectorIt v = m_NewPoints.begin() + (*it); + if (v->similar(points[k], EPS)) + mface[k] = *it; + } + } + for (k = 0; k < 3; k++) + { + if (mface[k] == -1) + { + mface[k] = m_NewPoints.size(); + m_NewPoints.push_back(points[k]); + int ix, iy, iz; + ix = iFloor(float(points[k].x - VMmin.x) / VMscale.x * MX); + iy = iFloor(float(points[k].y - VMmin.y) / VMscale.y * MY); + iz = iFloor(float(points[k].z - VMmin.z) / VMscale.z * MZ); + VM[ix][iy][iz].push_back(mface[k]); + int ixE, iyE, izE; + ixE = iFloor(float(points[k].x + VMeps.x - VMmin.x) / VMscale.x * MX); + iyE = iFloor(float(points[k].y + VMeps.y - VMmin.y) / VMscale.y * MY); + izE = iFloor(float(points[k].z + VMeps.z - VMmin.z) / VMscale.z * MZ); + if (ixE != ix) + VM[ixE][iy][iz].push_back(mface[k]); + if (iyE != iy) + VM[ix][iyE][iz].push_back(mface[k]); + if (izE != iz) + VM[ix][iy][izE].push_back(mface[k]); + if ((ixE != ix) && (iyE != iy)) + VM[ixE][iyE][iz].push_back(mface[k]); + if ((ixE != ix) && (izE != iz)) + VM[ixE][iy][izE].push_back(mface[k]); + if ((iyE != iy) && (izE != iz)) + VM[ix][iyE][izE].push_back(mface[k]); + if ((ixE != ix) && (iyE != iy) && (izE != iz)) + VM[ixE][iyE][izE].push_back(mface[k]); + } + } + + if ((mface[0] == mface[1]) || (mface[1] == mface[2]) || (mface[0] == mface[2])) + { + Msg("!Optimize: Invalid face found. Removed."); + return false; + } + else + { + face.pv[0].pindex = mface[0]; + face.pv[1].pindex = mface[1]; + face.pv[2].pindex = mface[2]; + return true; + } +} + +void CEditableMesh::OptimizeMesh(BOOL NoOpt) +{ + if (!NoOpt) + { +#ifdef _EDITOR + UnloadRenderBuffers(); + UnloadCForm(); +#endif + UnloadFNormals(true); + UnloadVNormals(true); + UnloadSVertices(true); + UnloadAdjacency(true); + + // clear static data + for (int x = 0; x < MX + 1; x++) + for (int y = 0; y < MY + 1; y++) + for (int z = 0; z < MZ + 1; z++) + VM[x][y][z].clear(); + VMscale.set(m_Box.vMax.x - m_Box.vMin.x + EPS_S, m_Box.vMax.y - m_Box.vMin.y + EPS_S, m_Box.vMax.z - m_Box.vMin.z + EPS_S); + VMmin.set(m_Box.vMin.x, m_Box.vMin.y, m_Box.vMin.z); + + VMeps.set(VMscale.x / MX / 2, VMscale.y / MY / 2, VMscale.z / MZ / 2); + VMeps.x = (VMeps.x < EPS_L) ? VMeps.x : EPS_L; + VMeps.y = (VMeps.y < EPS_L) ? VMeps.y : EPS_L; + VMeps.z = (VMeps.z < EPS_L) ? VMeps.z : EPS_L; + + m_NewPoints.clear(); + m_NewPoints.reserve(m_VertCount); + + boolVec faces_mark; + faces_mark.resize(m_FaceCount, false); + int i_del_face = 0; + for (u32 k = 0; k < m_FaceCount; k++) + { + if (!OptimizeFace(m_Faces[k])) + { + faces_mark[k] = true; + + //. -----in plugin + //. i_del_face = 0; + + //. -----in editor + i_del_face++; + } + } + + m_VertCount = m_NewPoints.size(); + xr_free(m_Vertices); + m_Vertices = xr_alloc(m_VertCount); + memcpy(m_Vertices, &*m_NewPoints.begin(), m_NewPoints.size() * sizeof(Fvector)); + + if (i_del_face) + { + st_Face *old_faces = m_Faces; + u32 *old_sg = m_SmoothGroups; + + m_Faces = xr_alloc(m_FaceCount - i_del_face); + m_SmoothGroups = xr_alloc(m_FaceCount - i_del_face); + + u32 new_dk = 0; + for (u32 dk = 0; dk < m_FaceCount; ++dk) + { + if (faces_mark[dk]) + { + for (SurfFacesPairIt plp_it = m_SurfFaces.begin(); plp_it != m_SurfFaces.end(); ++plp_it) + { + IntVec &pol_lst = plp_it->second; + for (int k = 0; k < int(pol_lst.size()); ++k) + { + int &f = pol_lst[k]; + if (f > (int)dk) + { + --f; + } + else if (f == (int)dk) + { + pol_lst.erase(pol_lst.begin() + k); + --k; + } + } + } + continue; + } + //. -----in plugin + //. new_dk++; + + m_Faces[new_dk] = old_faces[dk]; + m_SmoothGroups[new_dk] = old_sg[dk]; + + //. -----in editors + ++new_dk; + } + m_FaceCount = m_FaceCount - i_del_face; + xr_free(old_faces); + xr_free(old_sg); + } + } +} diff --git a/src/editors/xrECore/Editor/EditMeshPick.cpp b/src/editors/xrECore/Editor/EditMeshPick.cpp new file mode 100644 index 00000000000..1a07d280f70 --- /dev/null +++ b/src/editors/xrECore/Editor/EditMeshPick.cpp @@ -0,0 +1,238 @@ +#include "stdafx.h" +#include "EditMesh.h" +#include "EditObject.h" +#include "pick_defs.h" +#include "utils/ETools/ETools.h" + +static IntVec sml_processed; +static Fvector sml_normal; +static float m_fSoftAngle; + +// номер face должен соответствовать списку +void CEditableMesh::GenerateCFModel() +{ + UnloadCForm(); + // Collect faces + CDB::Collector *CL = ETOOLS::create_collector(); + // double sided + for (SurfFacesPairIt sp_it = m_SurfFaces.begin(); sp_it != m_SurfFaces.end(); sp_it++) + { + IntVec &face_lst = sp_it->second; + for (IntIt it = face_lst.begin(); it != face_lst.end(); it++) + { + st_Face &F = m_Faces[*it]; + ETOOLS::collector_add_face_d(CL, m_Vertices[F.pv[0].pindex], m_Vertices[F.pv[1].pindex], m_Vertices[F.pv[2].pindex], *it); + if (sp_it->first->m_Flags.is(CSurface::sf2Sided)) + ETOOLS::collector_add_face_d(CL, m_Vertices[F.pv[2].pindex], m_Vertices[F.pv[1].pindex], m_Vertices[F.pv[0].pindex], *it); + } + } + m_CFModel = ETOOLS::create_model_cl(CL); + ETOOLS::destroy_collector(CL); +} + +void CEditableMesh::RayQuery(SPickQuery &pinf) +{ + if (!m_CFModel) + GenerateCFModel(); + + ETOOLS::ray_query(m_CFModel, pinf.m_Start, pinf.m_Direction, pinf.m_Dist); + for (int r = 0; r < ETOOLS::r_count(); r++) + pinf.append(ETOOLS::r_begin() + r, m_Parent, this); + /* + XRC.ray_query (m_CFModel, pinf.m_Start, pinf.m_Direction, pinf.m_Dist); + for (int r=0; rinf.range+EPS_L:UI->ZFar();// (bugs: не всегда выбирает) //S ???? + + ETOOLS::ray_options(CDB::OPT_ONLYNEAREST | CDB::OPT_CULL); + ETOOLS::ray_query_m(inv_parent, m_CFModel, start, direction, _sqrt_flt_max); + + if (ETOOLS::r_count()) + { + CDB::RESULT *I = ETOOLS::r_begin(); + if (I->range < distance) + { + if (pinf) + { + pinf->SetRESULT(m_CFModel, I); + pinf->e_obj = m_Parent; + pinf->e_mesh = this; + pinf->pt.mul(direction, pinf->inf.range); + pinf->pt.add(start); + } + distance = I->range; + return true; + } + } + return false; +} +//---------------------------------------------------- +#ifdef _EDITOR +bool CEditableMesh::CHullPickMesh(PlaneVec &pl, const Fmatrix &parent) +{ + Fvector p; + boolVec inside; + inside.assign(m_VertCount, true); + for (u32 v_id = 0; v_id < m_VertCount; v_id++) + { + parent.transform_tiny(p, m_Vertices[v_id]); + for (PlaneIt p_it = pl.begin(); p_it != pl.end(); p_it++) + if (p_it->classify(p) > EPS_L) + { + inside[v_id] = false; + break; + } + } + for (u32 f_id = 0; f_id < m_FaceCount; f_id++) + if (inside[m_Faces[f_id].pv[0].pindex] && inside[m_Faces[f_id].pv[1].pindex] && inside[m_Faces[f_id].pv[2].pindex]) + return true; + return false; +} +//---------------------------------------------------- + +void CEditableMesh::RecurseTri(int id) +{ + // Check if triangle already processed + if (std::find(sml_processed.begin(), sml_processed.end(), id) != sml_processed.end()) + return; + + sml_processed.push_back(id); + + // recurse + for (int k = 0; k < 3; k++) + { + IntVec &PL = (*m_Adjs)[m_Faces[id].pv[k].pindex]; + for (IntIt pl_it = PL.begin(); pl_it != PL.end(); pl_it++) + { + Fvector &test_normal = m_FaceNormals[*pl_it]; + float cosa = test_normal.dotproduct(sml_normal); + if (cosa < m_fSoftAngle) + continue; + RecurseTri(*pl_it); + } + } +} +//---------------------------------------------------- + +void CEditableMesh::GetTiesFaces(int start_id, U32Vec &fl, float fSoftAngle, bool bRecursive) +{ + R_ASSERT(start_id < int(m_FaceCount)); + m_fSoftAngle = cosf(deg2rad(fSoftAngle)); + GenerateFNormals(); + GenerateAdjacency(); + VERIFY(m_FaceNormals); + if (bRecursive) + { + sml_processed.clear(); + sml_normal.set(m_FaceNormals[start_id]); + RecurseTri(start_id); + fl.insert(fl.begin(), sml_processed.begin(), sml_processed.end()); + } + else + { + for (int k = 0; k < 3; k++) + fl.insert(fl.end(), (*m_Adjs)[m_Faces[start_id].pv[k].pindex].begin(), (*m_Adjs)[m_Faces[start_id].pv[k].pindex].end()); + std::sort(fl.begin(), fl.end()); + fl.erase(std::unique(fl.begin(), fl.end()), fl.end()); + } + UnloadFNormals(); + UnloadAdjacency(); +} +//---------------------------------------------------- + +bool CEditableMesh::BoxPick(const Fbox &box, const Fmatrix &inv_parent, SBoxPickInfoVec &pinf) +{ + if (!m_CFModel) + GenerateCFModel(); + + ETOOLS::box_query_m(inv_parent, m_CFModel, box); + if (ETOOLS::r_count()) + { + pinf.push_back(SBoxPickInfo()); + pinf.back().e_obj = m_Parent; + pinf.back().e_mesh = this; + for (CDB::RESULT *I = ETOOLS::r_begin(); I != ETOOLS::r_end(); I++) + pinf.back().AddRESULT(m_CFModel, I); + return true; + } + + return false; +} +//---------------------------------------------------- + +bool CEditableMesh::FrustumPick(const CFrustum &frustum, const Fmatrix &parent) +{ + if (!m_Flags.is(flVisible)) + return false; + + Fvector p[3]; + for (u32 i = 0; i < m_FaceCount; i++) + { + for (int k = 0; k < 3; k++) + parent.transform_tiny(p[k], m_Vertices[m_Faces[i].pv[k].pindex]); + if (frustum.testPolyInside(p, 3)) + return true; + } + return false; +} +//--------------------------------------------------------------------------- + +void CEditableMesh::FrustumPickFaces(const CFrustum &frustum, const Fmatrix &parent, U32Vec &fl) +{ + if (!m_Flags.is(flVisible)) + return; + + Fvector p[3]; + bool bCulling = EPrefs->bp_cull; + for (u32 p_id = 0; p_id < m_FaceCount; p_id++) + { + for (int k = 0; k < 3; ++k) + parent.transform_tiny(p[k], m_Vertices[m_Faces[p_id].pv[k].pindex]); + + if (bCulling) + { + Fplane P; + P.build(p[0], p[1], p[2]); + if (P.classify(EDevice.m_Camera.GetPosition()) < 0) + continue; + } + if (frustum.testPolyInside(p, 3)) + fl.push_back(p_id); + } +} +#endif // diff --git a/src/editors/xrECore/Editor/EditMeshRender.cpp b/src/editors/xrECore/Editor/EditMeshRender.cpp new file mode 100644 index 00000000000..2241b9b317e --- /dev/null +++ b/src/editors/xrECore/Editor/EditMeshRender.cpp @@ -0,0 +1,428 @@ +//---------------------------------------------------- +// file: StaticMesh.cpp +//---------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +//#include "EditMeshVLight.h" +#include "EditMesh.h" +#include "EditObject.h" +#include "d3dutils.h" +#include "render.h" +//---------------------------------------------------- +#define F_LIM (10000) +#define V_LIM (F_LIM * 3) +//---------------------------------------------------- +void CEditableMesh::GenerateRenderBuffers() +{ + // CTimer T; + // T.Start(); + /* + CMemoryWriter F; + m_Parent->PrepareOGF(F,false,this); + IReader R (F.pointer(), F.size()); + m_Visual = ::Render->Models->Create(GetName(),&R); + // Log ("Time: ",T.GetElapsed_sec()); + // string_path fn; + // strconcat (fn,"_alexmx_\\",GetName(),".ogf"); + // FS.update_path (fn,_import_,fn); + // F.save_to (fn); + return; + */ + if (m_RenderBuffers) + return; + m_RenderBuffers = xr_new(); + + GenerateVNormals(0); + + VERIFY(m_VertexNormals); + + for (SurfFacesPairIt sp_it = m_SurfFaces.begin(); sp_it != m_SurfFaces.end(); sp_it++) + { + IntVec &face_lst = sp_it->second; + CSurface *_S = sp_it->first; + int num_verts = face_lst.size() * 3; + RBVector rb_vec; + int v_cnt = num_verts; + int start_face = 0; + int num_face; + VERIFY3(v_cnt, "Empty surface arrive.", _S->_Name()); +#if 0 + do{ + rb_vec.push_back (st_RenderBuffer(0,(v_cntm_Flags.is(CSurface::sf2Sided)) rb.dwNumVertex *= 2; + num_face = (v_cnt_FVF())*rb.dwNumVertex; + R_ASSERT2 (buf_size,"Empty buffer size or bad FVF."); + u8* bytes = 0; + IDirect3DVertexBuffer9* pVB=0; +// IDirect3DIndexBuffer9* pIB=0; + R_CHK(HW.pDevice->CreateVertexBuffer(buf_size, D3DUSAGE_WRITEONLY, 0, D3DPOOL_MANAGED, &pVB, 0)); +// R_CHK(HW.pDevice->CreateIndexBuffer(i_cnt*sizeof(u16),D3DUSAGE_WRITEONLY,D3DFMT_INDEX16,D3DPOOL_MANAGED,&pIB,NULL)); + rb.pGeom.create (_S->_FVF(),pVB,0); + + R_CHK (pVB->Lock(0,0,(LPVOID*)&bytes,0)); + FillRenderBuffer (face_lst,start_face,num_face,_S,bytes); + pVB->Unlock (); + + v_cnt -= V_LIM; + start_face += (_S->m_Flags.is(CSurface::sf2Sided))?rb.dwNumVertex/6:rb.dwNumVertex/3; + }while(v_cnt>0); +#else + { + rb_vec.push_back(st_RenderBuffer(0, v_cnt)); + st_RenderBuffer &rb = rb_vec.back(); + if (_S->m_Flags.is(CSurface::sf2Sided)) + rb.dwNumVertex *= 2; + num_face = v_cnt / 3; + + int buf_size = D3DXGetFVFVertexSize(_S->_FVF()) * rb.dwNumVertex; + R_ASSERT2(buf_size, "Empty buffer size or bad FVF."); + u8 *bytes = 0; + IDirect3DVertexBuffer9 *pVB = 0; + R_CHK(HW.pDevice->CreateVertexBuffer(buf_size, D3DUSAGE_WRITEONLY, 0, D3DPOOL_MANAGED, &pVB, 0)); + rb.pGeom.create(_S->_FVF(), pVB, 0); + R_CHK(pVB->Lock(0, 0, (LPVOID *)&bytes, 0)); + FillRenderBuffer(face_lst, start_face, num_face, _S, bytes); + pVB->Unlock(); + + start_face += (_S->m_Flags.is(CSurface::sf2Sided)) ? rb.dwNumVertex / 6 : rb.dwNumVertex / 3; + } +#endif + if (num_verts > 0) + m_RenderBuffers->insert(make_pair(_S, rb_vec)); + } + UnloadVNormals(); +} +//---------------------------------------------------- + +void CEditableMesh::UnloadRenderBuffers() +{ + if (m_RenderBuffers) + { + for (RBMapPairIt rbmp_it = m_RenderBuffers->begin(); rbmp_it != m_RenderBuffers->end(); rbmp_it++) + { + for (RBVecIt rb_it = rbmp_it->second.begin(); rb_it != rbmp_it->second.end(); rb_it++) + if (rb_it->pGeom) + { + _RELEASE(rb_it->pGeom->vb); + _RELEASE(rb_it->pGeom->ib); + rb_it->pGeom.destroy(); + } + } + xr_delete(m_RenderBuffers); + } +} +//---------------------------------------------------- + +void CEditableMesh::FillRenderBuffer(IntVec &face_lst, int start_face, int num_face, const CSurface *surf, LPBYTE &src_data) +{ + LPBYTE data = src_data; + u32 dwFVF = surf->_FVF(); + u32 dwTexCnt = ((dwFVF & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT); + for (int fl_i = start_face; fl_i < start_face + num_face; fl_i++) + { + u32 f_index = face_lst[fl_i]; + VERIFY(f_index < m_FaceCount); + st_Face &face = m_Faces[f_index]; + for (int k = 0; k < 3; k++) + { + st_FaceVert &fv = face.pv[k]; + u32 norm_id = f_index * 3 + k; // fv.pindex; + VERIFY2(norm_id < m_FaceCount * 3, "Normal index out of range."); + VERIFY2(fv.pindex < (int)m_VertCount, "Point index out of range."); + Fvector &PN = m_VertexNormals[norm_id]; + Fvector &V = m_Vertices[fv.pindex]; + int sz; + if (dwFVF & D3DFVF_XYZ) + { + sz = sizeof(Fvector); + VERIFY2(fv.pindex < int(m_VertCount), "- Face index out of range."); + CopyMemory(data, &V, sz); + data += sz; + } + if (dwFVF & D3DFVF_NORMAL) + { + sz = sizeof(Fvector); + CopyMemory(data, &PN, sz); + data += sz; + } + sz = sizeof(Fvector2); + int offs = 0; + for (int t = 0; t < (int)dwTexCnt; t++) + { + VERIFY2((t + offs) < (int)m_VMRefs[fv.vmref].count, "- VMap layer index out of range"); + st_VMapPt &vm_pt = m_VMRefs[fv.vmref].pts[t + offs]; + if (m_VMaps[vm_pt.vmap_index]->type != vmtUV) + { + offs++; + t--; + continue; + } + VERIFY2(vm_pt.vmap_index < int(m_VMaps.size()), "- VMap index out of range"); + st_VMap *vmap = m_VMaps[vm_pt.vmap_index]; + VERIFY2(vm_pt.index < vmap->size(), "- VMap point index out of range"); + CopyMemory(data, &vmap->getUV(vm_pt.index), sz); + data += sz; + // Msg("%3.2f, %3.2f",vmap->getUV(vm_pt.index).x,vmap->getUV(vm_pt.index).y); + } + } + if (surf->m_Flags.is(CSurface::sf2Sided)) + { + for (int k = 2; k >= 0; k--) + { + st_FaceVert &fv = face.pv[k]; + Fvector &PN = m_VertexNormals[f_index * 3 + k]; + int sz; + if (dwFVF & D3DFVF_XYZ) + { + sz = sizeof(Fvector); + VERIFY2(fv.pindex < int(m_VertCount), "- Face index out of range."); + CopyMemory(data, &m_Vertices[fv.pindex], sz); + data += sz; + } + if (dwFVF & D3DFVF_NORMAL) + { + sz = sizeof(Fvector); + Fvector N; + N.invert(PN); + CopyMemory(data, &N, sz); + data += sz; + } + sz = sizeof(Fvector2); + int offs = 0; + for (int t = 0; t < (int)dwTexCnt; t++) + { + VERIFY2((t + offs) < (int)m_VMRefs[fv.vmref].count, "- VMap layer index out of range"); + st_VMapPt &vm_pt = m_VMRefs[fv.vmref].pts[t]; + if (m_VMaps[vm_pt.vmap_index]->type != vmtUV) + { + offs++; + t--; + continue; + } + VERIFY2(vm_pt.vmap_index < int(m_VMaps.size()), "- VMap index out of range"); + st_VMap *vmap = m_VMaps[vm_pt.vmap_index]; + VERIFY2(vm_pt.index < vmap->size(), "- VMap point index out of range"); + CopyMemory(data, &vmap->getUV(vm_pt.index), sz); + data += sz; + + // Msg("%3.2f, %3.2f",vmap->getUV(vm_pt.index).x,vmap->getUV(vm_pt.index).y); + } + } + } + } +} +//---------------------------------------------------- +void CEditableMesh::Render(const Fmatrix &parent, CSurface *S) +{ + if (0 == m_RenderBuffers) + GenerateRenderBuffers(); + // visibility test + if (!m_Flags.is(flVisible)) + return; + // frustum test + Fbox bb; + bb.set(m_Box); + bb.xform(parent); + if (!::Render->occ_visible(bb)) + return; + // render + RBMapPairIt rb_pair = m_RenderBuffers->find(S); + if (rb_pair != m_RenderBuffers->end()) + { + RBVector &rb_vec = rb_pair->second; + for (RBVecIt rb_it = rb_vec.begin(); rb_it != rb_vec.end(); rb_it++) + EDevice.DP(D3DPT_TRIANGLELIST, rb_it->pGeom, 0, rb_it->dwNumVertex / 3); + } +} +//---------------------------------------------------- +#define MAX_VERT_COUNT 0xFFFF +static Fvector RB[MAX_VERT_COUNT]; +static int RB_cnt = 0; + +void CEditableMesh::RenderList(const Fmatrix &parent, u32 color, bool bEdge, IntVec &fl) +{ + // if (!m_Visible) return; + // if (!m_LoadState.is(LS_RBUFFERS)) CreateRenderBuffers(); + + if (fl.size() == 0) + return; + RCache.set_xform_world(parent); + EDevice.RenderNearer(0.0006); + RB_cnt = 0; + if (bEdge) + { + EDevice.SetShader(EDevice.m_WireShader); + EDevice.SetRS(D3DRS_FILLMODE, D3DFILL_WIREFRAME); + } + else + EDevice.SetShader(EDevice.m_SelectionShader); + for (IntIt dw_it = fl.begin(); dw_it != fl.end(); ++dw_it) + { + st_Face &face = m_Faces[*dw_it]; + for (int k = 0; k < 3; ++k) + RB[RB_cnt++].set(m_Vertices[face.pv[k].pindex]); + + if (RB_cnt == MAX_VERT_COUNT) + { + DU_impl.DrawPrimitiveL(D3DPT_TRIANGLELIST, RB_cnt / 3, RB, RB_cnt, color, true, false); + RB_cnt = 0; + } + } + + if (RB_cnt) + DU_impl.DrawPrimitiveL(D3DPT_TRIANGLELIST, RB_cnt / 3, RB, RB_cnt, color, true, false); + + if (bEdge) + EDevice.SetRS(D3DRS_FILLMODE, EDevice.dwFillMode); + + EDevice.ResetNearer(); +} +//---------------------------------------------------- + +void CEditableMesh::RenderSelection(const Fmatrix &parent, CSurface *s, u32 color) +{ + if (0 == m_RenderBuffers) + GenerateRenderBuffers(); + // if (!m_Visible) return; + Fbox bb; + bb.set(m_Box); + bb.xform(parent); + if (!::Render->occ_visible(bb)) + return; + // render + RCache.set_xform_world(parent); + if (s) + { + SurfFacesPairIt sp_it = m_SurfFaces.find(s); + if (sp_it != m_SurfFaces.end()) + RenderList(parent, color, false, sp_it->second); + } + else + { + EDevice.SetRS(D3DRS_TEXTUREFACTOR, color); + for (RBMapPairIt p_it = m_RenderBuffers->begin(); p_it != m_RenderBuffers->end(); p_it++) + { + RBVector &rb_vec = p_it->second; + for (RBVecIt rb_it = rb_vec.begin(); rb_it != rb_vec.end(); rb_it++) + EDevice.DP(D3DPT_TRIANGLELIST, rb_it->pGeom, 0, rb_it->dwNumVertex / 3); + } + EDevice.SetRS(D3DRS_TEXTUREFACTOR, 0xffffffff); + } +} +//---------------------------------------------------- + +void CEditableMesh::RenderEdge(const Fmatrix &parent, CSurface *s, u32 color) +{ + if (0 == m_RenderBuffers) + GenerateRenderBuffers(); + // if (!m_Visible) return; + RCache.set_xform_world(parent); + EDevice.SetShader(EDevice.m_WireShader); + EDevice.RenderNearer(0.001); + + // render + EDevice.SetRS(D3DRS_FILLMODE, D3DFILL_WIREFRAME); + if (s) + { + SurfFacesPairIt sp_it = m_SurfFaces.find(s); + if (sp_it != m_SurfFaces.end()) + RenderList(parent, color, true, sp_it->second); + } + else + { + EDevice.SetRS(D3DRS_TEXTUREFACTOR, color); + for (RBMapPairIt p_it = m_RenderBuffers->begin(); p_it != m_RenderBuffers->end(); p_it++) + { + RBVector &rb_vec = p_it->second; + for (RBVecIt rb_it = rb_vec.begin(); rb_it != rb_vec.end(); rb_it++) + EDevice.DP(D3DPT_TRIANGLELIST, rb_it->pGeom, 0, rb_it->dwNumVertex / 3); + } + EDevice.SetRS(D3DRS_TEXTUREFACTOR, 0xffffffff); + } + EDevice.SetRS(D3DRS_FILLMODE, EDevice.dwFillMode); + EDevice.ResetNearer(); +} +//---------------------------------------------------- + +#define SKEL_MAX_FACE_COUNT 10000 +struct svertRender +{ + Fvector P; + Fvector N; + Fvector2 uv; +}; +void CEditableMesh::RenderSkeleton(const Fmatrix &, CSurface *S) +{ + if (false == IsGeneratedSVertices(RENDER_SKELETON_LINKS)) + GenerateSVertices(RENDER_SKELETON_LINKS); + + R_ASSERT2(m_SVertices, "SVertices empty!"); + SurfFacesPairIt sp_it = m_SurfFaces.find(S); + R_ASSERT(sp_it != m_SurfFaces.end()); + IntVec &face_lst = sp_it->second; + _VertexStream *Stream = &RImplementation.Vertex; + u32 vBase; + + svertRender *pv = (svertRender *)Stream->Lock(SKEL_MAX_FACE_COUNT * 3, m_Parent->vs_SkeletonGeom->vb_stride, vBase); + Fvector P0, N0, P1, N1; + + int f_cnt = 0; + for (IntIt i_it = face_lst.begin(); i_it != face_lst.end(); i_it++) + { + for (int k = 0; k < 3; k++, pv++) + { + st_SVert &SV = m_SVertices[*i_it * 3 + k]; + pv->uv.set(SV.uv); + float total = SV.bones[0].w; + + const Fmatrix &M = m_Parent->m_Bones[SV.bones[0].id]->RenderTransform(); + M.transform_tiny(pv->P, SV.offs); + M.transform_dir(pv->N, SV.norm); + + Fvector P, N; + + for (u8 cnt = 1; cnt < (u8)SV.bones.size(); cnt++) + { + total += SV.bones[cnt].w; + const Fmatrix &M = m_Parent->m_Bones[SV.bones[cnt].id]->RenderTransform(); + M.transform_tiny(P, SV.offs); + M.transform_dir(N, SV.norm); + pv->P.lerp(pv->P, P, SV.bones[cnt].w / total); + pv->N.lerp(pv->N, N, SV.bones[cnt].w / total); + } + } + f_cnt++; + if (S->m_Flags.is(CSurface::sf2Sided)) + { + pv->P.set((pv - 1)->P); + pv->N.invert((pv - 1)->N); + pv->uv.set((pv - 1)->uv); + pv++; + pv->P.set((pv - 3)->P); + pv->N.invert((pv - 3)->N); + pv->uv.set((pv - 3)->uv); + pv++; + pv->P.set((pv - 5)->P); + pv->N.invert((pv - 5)->N); + pv->uv.set((pv - 5)->uv); + pv++; + f_cnt++; + } + if (f_cnt >= SKEL_MAX_FACE_COUNT - 1) + { + Stream->Unlock(f_cnt * 3, m_Parent->vs_SkeletonGeom->vb_stride); + EDevice.DP(D3DPT_TRIANGLELIST, m_Parent->vs_SkeletonGeom, vBase, f_cnt); + pv = (svertRender *)Stream->Lock(SKEL_MAX_FACE_COUNT * 3, m_Parent->vs_SkeletonGeom->vb_stride, vBase); + f_cnt = 0; + } + } + Stream->Unlock(f_cnt * 3, m_Parent->vs_SkeletonGeom->vb_stride); + if (f_cnt) + EDevice.DP(D3DPT_TRIANGLELIST, m_Parent->vs_SkeletonGeom, vBase, f_cnt); +} +//---------------------------------------------------- diff --git a/src/editors/xrECore/Editor/EditObject.cpp b/src/editors/xrECore/Editor/EditObject.cpp new file mode 100644 index 00000000000..9e4bceceb24 --- /dev/null +++ b/src/editors/xrECore/Editor/EditObject.cpp @@ -0,0 +1,351 @@ +//---------------------------------------------------- +// file: EditObject.cpp +//---------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +#include "xrCore/FMesh.hpp" + +#include "EditObject.h" +#include "EditMesh.h" + +#ifdef _EDITOR +#include "xrCore/Animation/Motion.hpp" +#include "xrCore/Animation/Bone.hpp" +#include "ImageManager.h" +#endif + +// mimimal bounding box size +float g_MinBoxSize = 0.05f; + +#ifdef _EDITOR +void CSurface::CreateImageData() +{ + VERIFY(0 == m_ImageData); + m_ImageData = xr_new(); + m_ImageData->name = m_Texture; + m_ImageData->layers.push_back(U32Vec()); + ImageLib.LoadTextureData(*m_ImageData->name, m_ImageData->layers.back(), m_ImageData->w, m_ImageData->h); +} +void CSurface::RemoveImageData() +{ + xr_delete(m_ImageData); +} +#endif + +CEditableObject::CEditableObject(LPCSTR name) : m_physics_shell(0), + m_object_xform(0) +{ + m_FaceCount = -1; + m_VertexCount = -1; + m_LibName = name; + + m_objectFlags.zero(); + m_ObjectVersion = 0; + +#ifdef _EDITOR + vs_SkeletonGeom = 0; +#endif + m_BBox.invalidate(); + + m_LoadState.zero(); + + m_ActiveSMotion = 0; + + t_vPosition.set(0.f, 0.f, 0.f); + t_vScale.set(1.f, 1.f, 1.f); + t_vRotate.set(0.f, 0.f, 0.f); + + a_vPosition.set(0.f, 0.f, 0.f); + a_vRotate.set(0.f, 0.f, 0.f); + + bOnModified = false; + + m_RefCount = 0; + + m_LODShader = 0; + + m_CreateName = "unknown"; + m_CreateTime = 0; + m_ModifName = "unknown"; + m_ModifTime = 0; +} + +CEditableObject::~CEditableObject() +{ + ClearGeometry(); +} +//---------------------------------------------------- + +void CEditableObject::VerifyMeshNames() +{ + int idx = 0; + string1024 nm, pref; + for (EditMeshIt m_def = m_Meshes.begin(); m_def != m_Meshes.end(); m_def++) + { + strcpy(pref, (*m_def)->m_Name.size() ? (*m_def)->m_Name.c_str() : "mesh"); + _Trim(pref); + strcpy(nm, pref); + while (FindMeshByName(nm, *m_def)) + sprintf(nm, "%s%2d", pref, idx++); + (*m_def)->SetName(nm); + } +} + +bool CEditableObject::ContainsMesh(const CEditableMesh *m) +{ + VERIFY(m); + for (EditMeshIt m_def = m_Meshes.begin(); m_def != m_Meshes.end(); m_def++) + if (m == (*m_def)) + return true; + return false; +} + +CEditableMesh *CEditableObject::FindMeshByName(const char *name, CEditableMesh *Ignore) +{ + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + if ((Ignore != (*m)) && (stricmp((*m)->Name().c_str(), name) == 0)) + return (*m); + return 0; +} + +void CEditableObject::ClearGeometry() +{ +#ifdef _EDITOR + OnDeviceDestroy(); +#endif + if (!m_Meshes.empty()) + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + xr_delete(*m); + if (!m_Surfaces.empty()) + for (SurfaceIt s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + xr_delete(*s_it); + m_Meshes.clear(); + m_Surfaces.clear(); +#ifdef _EDITOR + // bones + for (BoneIt b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + xr_delete(*b_it); + m_Bones.clear(); + // skeletal motions + for (SMotionIt s_it = m_SMotions.begin(); s_it != m_SMotions.end(); s_it++) + xr_delete(*s_it); + m_SMotions.clear(); +#endif + m_ActiveSMotion = 0; +} + +int CEditableObject::GetFaceCount(bool bMatch2Sided, bool bIgnoreOCC) +{ + if (m_FaceCount != -1) + return m_FaceCount; + m_FaceCount = 0; + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + m_FaceCount += (*m)->GetFaceCount(bMatch2Sided, bIgnoreOCC); + return m_FaceCount; +} + +int CEditableObject::GetSurfFaceCount(const char *surf_name) +{ + int cnt = 0; + CSurface *surf = FindSurfaceByName(surf_name); + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + cnt += (*m)->GetSurfFaceCount(surf); + return cnt; +} + +int CEditableObject::GetVertexCount() +{ + if (m_VertexCount != -1) + return m_VertexCount; + m_VertexCount = 0; + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + m_VertexCount += (*m)->GetVertexCount(); + return m_VertexCount; +} + +void CEditableObject::UpdateBox() +{ + VERIFY(!m_Meshes.empty()); + EditMeshIt m = m_Meshes.begin(); + m_BBox.invalidate(); + + for (; m != m_Meshes.end(); ++m) + { + Fbox meshbox; + (*m)->GetBox(meshbox); + for (int i = 0; i < 8; ++i) + { + Fvector pt; + meshbox.getpoint(i, pt); + m_BBox.modify(pt); + } + } +} +//---------------------------------------------------- +void CEditableObject::RemoveMesh(CEditableMesh *mesh) +{ + EditMeshIt m_it = std::find(m_Meshes.begin(), m_Meshes.end(), mesh); + VERIFY(m_it != m_Meshes.end()); + m_Meshes.erase(m_it); + xr_delete(mesh); +} + +void CEditableObject::TranslateToWorld(const Fmatrix &parent) +{ + EditMeshIt m = m_Meshes.begin(); + for (; m != m_Meshes.end(); m++) + (*m)->Transform(parent); +#ifdef _EDITOR + OnDeviceDestroy(); +#endif + UpdateBox(); +} + +CSurface *CEditableObject::FindSurfaceByName(const char *surf_name, int *s_id) +{ + for (SurfaceIt s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + if (stricmp((*s_it)->_Name(), surf_name) == 0) + { + if (s_id) + *s_id = s_it - m_Surfaces.begin(); + return *s_it; + } + return 0; +} + +LPCSTR CEditableObject::GenerateSurfaceName(const char *base_name) +{ + static string1024 nm; + strcpy(nm, base_name); + if (FindSurfaceByName(nm)) + { + DWORD idx = 0; + do + { + sprintf(nm, "%s_%d", base_name, idx); + idx++; + } while (FindSurfaceByName(nm)); + } + return nm; +} + +bool CEditableObject::VerifyBoneParts() +{ + U8Vec b_use(BoneCount(), 0); + for (BPIt bp_it = m_BoneParts.begin(); bp_it != m_BoneParts.end(); bp_it++) + for (int i = 0; i < int(bp_it->bones.size()); i++) + { + int idx = FindBoneByNameIdx(bp_it->bones[i].c_str()); + if (idx == -1) + { + bp_it->bones.erase(bp_it->bones.begin() + i); + i--; + } + else + { + b_use[idx]++; + } + } + + for (U8It u_it = b_use.begin(); u_it != b_use.end(); u_it++) + if (*u_it != 1) + return false; + return true; +} + +void CEditableObject::PrepareOGFDesc(ogf_desc &desc) +{ + string512 tmp; + desc.source_file = m_LibName.c_str(); + desc.create_name = m_CreateName.c_str(); + desc.create_time = m_CreateTime; + desc.modif_name = m_ModifName.c_str(); + desc.modif_time = m_ModifTime; + desc.build_name = strconcat(sizeof(tmp), tmp, "\\\\", Core.CompName, "\\", Core.UserName); + _ctime32(&desc.build_time); +} + +void CEditableObject::SetVersionToCurrent(BOOL bCreate, BOOL bModif) +{ + string512 tmp; + if (bCreate) + { + m_CreateName = strconcat(sizeof(tmp), tmp, "\\\\", Core.CompName, "\\", Core.UserName); + m_CreateTime = time(NULL); + } + if (bModif) + { + m_ModifName = strconcat(sizeof(tmp), tmp, "\\\\", Core.CompName, "\\", Core.UserName); + m_ModifTime = time(NULL); + } +} + +void CEditableObject::GetFaceWorld(const Fmatrix &parent, CEditableMesh *M, int idx, Fvector *verts) +{ + const Fvector *PT[3]; + M->GetFacePT(idx, PT); + parent.transform_tiny(verts[0], *PT[0]); + parent.transform_tiny(verts[1], *PT[1]); + parent.transform_tiny(verts[2], *PT[2]); +} + +void CEditableObject::Optimize() +{ + for (EditMeshIt m_def = m_Meshes.begin(); m_def != m_Meshes.end(); m_def++) + { + (*m_def)->OptimizeMesh(false); + (*m_def)->RebuildVMaps(); + } +} + +bool CEditableObject::Validate() +{ + bool bRes = true; + for (SurfaceIt s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + if (false == (*s_it)->Validate()) + { + Msg("!Invalid surface found: Object [%s], Surface [%s].", GetName(), (*s_it)->_Name()); + bRes = false; + } + for (EditMeshIt m_def = m_Meshes.begin(); m_def != m_Meshes.end(); m_def++) + if (false == (*m_def)->Validate()) + { + Msg("!Invalid mesh found: Object [%s], Mesh [%s].", m_LibName.c_str(), (*m_def)->Name().c_str()); + bRes = false; + } + return bRes; +} +//---------------------------------------------------------------------------- +//#ifdef DEBUG + +LPCSTR CEditableObject::LL_BoneName_dbg(u16 ID) +{ + return GetBone(ID)->Name().c_str(); +} + +//#endif +CBoneInstance &CEditableObject::LL_GetBoneInstance(u16 bone_id) +{ + return *GetBone(bone_id); +} +CBoneData &CEditableObject::LL_GetData(u16 bone_id) +{ + VERIFY(false); + static CBoneData dummy_bone_data(0); + return dummy_bone_data; +} + +Fmatrix &CEditableObject::LL_GetTransform_R(u16 bone_id) +{ + // VERIFY(false); + // static Fmatrix dummy_matrix; + return GetBone(bone_id)->RenderTransform(); +} +Fobb &CEditableObject::LL_GetBox(u16 bone_id) +{ + VERIFY(false); + static Fobb dummy_box; + return dummy_box; +} diff --git a/src/editors/xrECore/Editor/EditObject.h b/src/editors/xrECore/Editor/EditObject.h new file mode 100644 index 00000000000..2f494766f1d --- /dev/null +++ b/src/editors/xrECore/Editor/EditObject.h @@ -0,0 +1,623 @@ +#pragma once +#include "xrCore/Animation/Bone.hpp" +#include "xrCore/Animation/Motion.hpp" + +#ifdef _EDITOR +#include "xrEngine/GameMtlLib.h" +#include "pick_defs.h" +#endif + +#include "Include/xrRender/Kinematics.h" +#include "physicsshellholdereditorbase.h" + +struct SRayPickInfo; +class CEditableMesh; +class CFrustum; +class CCustomMotion; +class CBone; +struct Shader; +class Mtl; +class CExporter; +class CMayaTranslator; +struct st_ObjectDB; +struct SXRShaderData; +struct ogf_desc; +class CCustomObject; + +#ifndef _EDITOR +class PropValue; +#define ref_shader LPVOID +#endif + +#define LOD_SHADER_NAME "details\\lod" +#define LOD_SAMPLE_COUNT 8 +#define LOD_IMAGE_SIZE 64 +#define RENDER_SKELETON_LINKS 4 + +// refs +class XRayMtl; +struct SSimpleImage; + +class ECORE_API CSurface +{ + u32 m_GameMtlID; + ref_shader m_Shader; + enum ERTFlags + { + rtValidShader = (1 << 0), + }; + +public: + enum EFlags + { + sf2Sided = (1 << 0), + }; + shared_str m_Name; + shared_str m_Texture; // + shared_str m_VMap; // + shared_str m_ShaderName; + shared_str m_ShaderXRLCName; + shared_str m_GameMtlName; + Flags32 m_Flags; + u32 m_dwFVF; + + Flags32 m_RTFlags; + u32 tag; + SSimpleImage *m_ImageData; + +public: + CSurface() + { + m_GameMtlName = "default"; + m_ImageData = 0; + m_Shader = 0; + m_RTFlags.zero(); + m_Flags.zero(); + m_dwFVF = 0; + tag = 0; + } + IC bool Validate() + { + return (0 != xr_strlen(m_Texture)) && (0 != xr_strlen(m_ShaderName)); + } +#ifdef _EDITOR + ~CSurface() + { + R_ASSERT(!m_Shader); + xr_delete(m_ImageData); + } + IC void CopyFrom(CSurface *surf) + { + *this = *surf; + m_Shader = 0; + m_RTFlags.set(rtValidShader, FALSE); + } + IC int _Priority() { return _Shader() ? _Shader()->E[0]->flags.iPriority : 1; } + IC bool _StrictB2F() { return _Shader() ? _Shader()->E[0]->flags.bStrictB2F : false; } + IC ref_shader _Shader() + { + if (!m_RTFlags.is(rtValidShader)) + OnDeviceCreate(); + return m_Shader; + } +#endif + IC LPCSTR _Name() const + { + return *m_Name; + } + IC LPCSTR _ShaderName() const { return *m_ShaderName; } + IC LPCSTR _GameMtlName() const { return *m_GameMtlName; } + IC LPCSTR _ShaderXRLCName() const { return *m_ShaderXRLCName; } + IC LPCSTR _Texture() const { return *m_Texture; } + IC LPCSTR _VMap() const { return *m_VMap; } + IC u32 _FVF() const { return m_dwFVF; } + IC void SetName(LPCSTR name) { m_Name = name; } + IC void SetShader(LPCSTR name) + { + R_ASSERT2(name && name[0], "Empty shader name."); + m_ShaderName = name; +#ifdef _EDITOR + OnDeviceDestroy(); +#endif + } + IC void SetShaderXRLC(LPCSTR name) { m_ShaderXRLCName = name; } + IC void SetGameMtl(LPCSTR name) { m_GameMtlName = name; } + IC void SetFVF(u32 fvf) { m_dwFVF = fvf; } + IC void SetTexture(LPCSTR name) + { + string512 buf; + xr_strcpy(buf, sizeof(buf), name); + if (strext(buf)) + *strext(buf) = 0; + m_Texture = buf; + } + IC void SetVMap(LPCSTR name) { m_VMap = name; } +#ifdef _EDITOR + IC u32 _GameMtl() const + { + return GMLib.GetMaterialID(*m_GameMtlName); + } + IC void OnDeviceCreate() + { + R_ASSERT(!m_RTFlags.is(rtValidShader)); + if (m_ShaderName.size() && m_Texture.size()) + m_Shader.create(*m_ShaderName, *m_Texture); + else + m_Shader.create("editor\\wire"); + m_RTFlags.set(rtValidShader, TRUE); + } + IC void OnDeviceDestroy() + { + m_Shader.destroy(); + m_RTFlags.set(rtValidShader, FALSE); + } + void CreateImageData(); + void RemoveImageData(); + IC bool IsVoid() const + { + return !m_RTFlags.is(rtValidShader); + } + +#endif +}; + +DEFINE_VECTOR(CSurface *, SurfaceVec, SurfaceIt); +DEFINE_VECTOR(CEditableMesh *, EditMeshVec, EditMeshIt); +DEFINE_VECTOR(COMotion *, OMotionVec, OMotionIt); +DEFINE_VECTOR(CSMotion *, SMotionVec, SMotionIt); + +struct ECORE_API SBonePart +{ + shared_str alias; + RStringVec bones; +}; +DEFINE_VECTOR(SBonePart, BPVec, BPIt); + +const u32 FVF_SV = D3DFVF_XYZ | D3DFVF_TEX1 | D3DFVF_NORMAL; + +class ECORE_API CEditableObject : public IKinematics, + public CPhysicsShellHolderEditorBase +{ + friend class CSceneObject; + friend class CEditableMesh; + friend class TfrmPropertiesEObject; + friend class CSector; + friend class TUI_ControlSectorAdd; + friend class ELibrary; + friend class TfrmEditLibrary; + friend class MeshExpUtility; + +#ifdef _EDITOR + ref_geom vs_SkeletonGeom; +#endif + // desc + shared_str m_CreateName; + time_t m_CreateTime; + shared_str m_ModifName; + time_t m_ModifTime; + + // general + xr_string m_ClassScript; + + EditMeshVec m_Meshes; + + ref_shader m_LODShader; + + // skeleton + BoneVec m_Bones; + SMotionVec m_SMotions; + BPVec m_BoneParts; + CSMotion *m_ActiveSMotion; + CPhysicsShell *m_physics_shell; + Fmatrix *m_object_xform; + +public: + SurfaceVec m_Surfaces; + SAnimParams m_SMParam; + xr_vector m_SMotionRefs; + shared_str m_LODs; + +public: + // options + Flags32 m_objectFlags; + enum + { + eoDynamic = (1 << 0), + eoProgressive = (1 << 1), + eoUsingLOD = (1 << 2), + eoHOM = (1 << 3), + eoMultipleUsage = (1 << 4), + eoSoundOccluder = (1 << 5), + eoHQExport = (1 << 6), + eoFORCE32 = u32(-1) + }; + IC BOOL IsDynamic() { return m_objectFlags.is(eoDynamic); } + IC BOOL IsStatic() { return !m_objectFlags.is(eoSoundOccluder) && !m_objectFlags.is(eoDynamic) && !m_objectFlags.is(eoHOM) && !m_objectFlags.is(eoMultipleUsage); } + IC BOOL IsMUStatic() { return !m_objectFlags.is(eoSoundOccluder) && !m_objectFlags.is(eoDynamic) && !m_objectFlags.is(eoHOM) && m_objectFlags.is(eoMultipleUsage); } + +private: + // bounding volume + Fbox m_BBox; + +public: + // temp variable for actor + Fvector a_vPosition; + Fvector a_vRotate; + + // temp variables for transformation + Fvector t_vPosition; + Fvector t_vScale; + Fvector t_vRotate; + + bool bOnModified; + IC bool IsModified() { return bOnModified; } + IC void Modified() { bOnModified = true; } + + xr_string m_LoadName; + int m_RefCount; + +protected: + int m_ObjectVersion; + + void ClearGeometry(); + + void PrepareBones(); + void DefferedLoadRP(); + void DefferedUnloadRP(); + + void OnChangeTransform(PropValue *prop); + void OnChangeShader(PropValue *prop); + +public: + enum + { + LS_RBUFFERS = (1 << 0), + }; + Flags32 m_LoadState; + + xr_string m_LibName; + +public: + // constructor/destructor methods + CEditableObject(LPCSTR name); + virtual ~CEditableObject(); + + LPCSTR GetName() { return m_LibName.c_str(); } + + void SetVersionToCurrent(BOOL bCreate, BOOL bModif); + + void Optimize(); + + IC EditMeshIt FirstMesh() { return m_Meshes.begin(); } + IC EditMeshIt LastMesh() { return m_Meshes.end(); } + IC EditMeshVec &Meshes() { return m_Meshes; } + IC int MeshCount() { return m_Meshes.size(); } + IC void AppendMesh(CEditableMesh *M) { m_Meshes.push_back(M); } + IC SurfaceVec &Surfaces() { return m_Surfaces; } + IC SurfaceIt FirstSurface() { return m_Surfaces.begin(); } + IC SurfaceIt LastSurface() { return m_Surfaces.end(); } + IC int SurfaceCount() { return m_Surfaces.size(); } + IC int Version() { return m_ObjectVersion; } + + IGameObject* IObject() { R_ASSERT(false); return nullptr; } + virtual bool IsCollideWithBullets() { R_ASSERT(false); return false; } + virtual bool IsCollideWithActorCamera() { R_ASSERT(false); return false; } + + // LOD + xr_string GetLODTextureName(); + LPCSTR GetLODShaderName() { return LOD_SHADER_NAME; } + void GetLODFrame(int frame, Fvector p[4], Fvector2 t[4], const Fmatrix *parent = 0); + + // skeleton + IC BPIt FirstBonePart() { return m_BoneParts.begin(); } + IC BPIt LastBonePart() { return m_BoneParts.end(); } + IC BPVec &BoneParts() { return m_BoneParts; } + IC int BonePartCount() { return m_BoneParts.size(); } + IC BPIt BonePart(CBone *B); + + IC BoneIt FirstBone() { return m_Bones.begin(); } + IC BoneIt LastBone() { return m_Bones.end(); } + IC BoneVec &Bones() { return m_Bones; } + IC int BoneCount() const { return m_Bones.size(); } + shared_str BoneNameByID(int id); + int GetRootBoneID(); + int PartIDByName(LPCSTR name); + IC CBone *GetBone(u32 idx) + { + VERIFY(idx < m_Bones.size()); + return m_Bones[idx]; + } + IC const CBone *GetBone(u32 idx) const + { + VERIFY(idx < m_Bones.size()); + return m_Bones[idx]; + } + void GetBoneWorldTransform(u32 bone_idx, float t, CSMotion *motion, Fmatrix &matrix); + IC SMotionIt FirstSMotion() { return m_SMotions.begin(); } + IC SMotionIt LastSMotion() { return m_SMotions.end(); } + SMotionVec &SMotions() { return m_SMotions; } + IC int SMotionCount() { return m_SMotions.size(); } + IC bool IsAnimated() { return SMotionCount() || m_SMotionRefs.size(); } + IC void SkeletonPlay() { m_SMParam.Play(); } + IC void SkeletonStop() { m_SMParam.Stop(); } + IC void SkeletonPause(bool val) { m_SMParam.Pause(val); } + + // get object properties methods + + IC xr_string &GetClassScript() { return m_ClassScript; } + + IC const Fbox &GetBox() const { return m_BBox; } + + IC LPCSTR GetLODs() { return m_LODs.c_str(); } + + // animation + IC bool IsSkeleton() { return !!m_Bones.size(); } + IC bool IsSMotionActive() { return IsSkeleton() && m_ActiveSMotion; } + CSMotion *GetActiveSMotion() { return m_ActiveSMotion; } + void SetActiveSMotion(CSMotion *mot); + bool CheckBoneCompliance(CSMotion *M); + bool VerifyBoneParts(); + void OptimizeSMotions(); + + bool LoadBoneData(IReader &F); + void SaveBoneData(IWriter &F); + void ResetBones(); + CSMotion *ResetSAnimation(bool bGotoBindPose = true); + void CalculateAnimation(CSMotion *motion); + void CalculateBindPose(); + void GotoBindPose(); + void OnBindTransformChange(); + + // statistics methods + void GetFaceWorld(const Fmatrix &parent, CEditableMesh *M, int idx, Fvector *verts); + int GetFaceCount(bool bMatch2Sided = true, bool bIgnoreOCC = true); + int GetVertexCount(); + int GetSurfFaceCount(LPCSTR surf_name); + + // render methods + void Render(const Fmatrix &parent, int priority, bool strictB2F, SurfaceVec *surfaces = nullptr); + void RenderSelection(const Fmatrix &parent, CEditableMesh *m = 0, CSurface *s = 0, u32 c = 0x40E64646); + void RenderEdge(const Fmatrix &parent, CEditableMesh *m = 0, CSurface *s = 0, u32 c = 0xFFC0C0C0); + void RenderBones(const Fmatrix &parent); + void RenderAnimation(const Fmatrix &parent); + void RenderSingle(const Fmatrix &parent); + void RenderSkeletonSingle(const Fmatrix &parent); + void RenderLOD(const Fmatrix &parent); + + // update methods + void OnFrame(); + void UpdateBox(); + void EvictObject(); + + // pick methods + bool RayPick(float &dist, const Fvector &S, const Fvector &D, const Fmatrix &inv_parent, SRayPickInfo *pinf = 0); +#ifdef _EDITOR + void AddBone(CBone *parent_bone); + void DeleteBone(CBone *bone); + void RenameBone(CBone *bone, LPCSTR new_name); + + void RayQuery(SPickQuery &pinf); + void RayQuery(const Fmatrix &parent, const Fmatrix &inv_parent, SPickQuery &pinf); + void BoxQuery(const Fmatrix &parent, const Fmatrix &inv_parent, SPickQuery &pinf); + bool BoxPick(CCustomObject *obj, const Fbox &box, const Fmatrix &inv_parent, SBoxPickInfoVec &pinf); + bool FrustumPick(const CFrustum &frustum, const Fmatrix &parent); + bool SpherePick(const Fvector ¢er, float radius, const Fmatrix &parent); + + // bone + CBone *PickBone(const Fvector &S, const Fvector &D, const Fmatrix &parent); + void SelectBones(bool bVal); + void SelectBone(CBone *b, bool bVal); + void ClampByLimits(bool bSelOnly); +#endif + // change position/orientation methods + void TranslateToWorld(const Fmatrix &parent); + + // clone/copy methods + void RemoveMesh(CEditableMesh *mesh); + + bool RemoveSMotion(LPCSTR name); + bool RenameSMotion(LPCSTR old_name, LPCSTR new_name); + bool AppendSMotion(LPCSTR fname, SMotionVec *inserted = 0); + void ClearSMotions(); + bool SaveSMotions(LPCSTR fname); + + // load/save methods + bool Reload(); + bool Load(LPCSTR fname); + bool Save(LPCSTR fname); + bool Load(IReader &); + void Save(IWriter &); +#ifdef _EDITOR + void FillMotionList(LPCSTR pref, ListItemsVec &items, int modeID); + void FillBoneList(LPCSTR pref, ListItemsVec &items, int modeID); + void FillSurfaceList(LPCSTR pref, ListItemsVec &items, int modeID); + void FillSurfaceProps(CSurface *surf, LPCSTR pref, PropItemVec &items); + void FillBasicProps(LPCSTR pref, PropItemVec &items); + void FillSummaryProps(LPCSTR pref, PropItemVec &items); + bool CheckShaderCompatible(); +#endif + + // contains methods + CEditableMesh *FindMeshByName(LPCSTR name, CEditableMesh *Ignore = 0); + void VerifyMeshNames(); + bool ContainsMesh(const CEditableMesh *m); + CSurface *FindSurfaceByName(LPCSTR surf_name, int *s_id = 0); + int FindBoneByNameIdx(LPCSTR name); + BoneIt FindBoneByNameIt(LPCSTR name); + CBone *FindBoneByName(LPCSTR name); + int GetSelectedBones(BoneVec &sel_bones); + u16 GetBoneIndexByWMap(LPCSTR wm_name); + CSMotion *FindSMotionByName(LPCSTR name, const CSMotion *Ignore = 0); + void GenerateSMotionName(char *buffer, LPCSTR start_name, const CSMotion *M); + bool GenerateBoneShape(bool bSelOnly); + + // device dependent routine + void OnDeviceCreate(); + void OnDeviceDestroy(); + + // utils + void PrepareOGFDesc(ogf_desc &desc); + // skeleton + bool PrepareSVGeometry(IWriter &F, u8 infl); + bool PrepareSVKeys(IWriter &F); + bool PrepareSVDefs(IWriter &F); + bool PrepareSkeletonOGF(IWriter &F, u8 infl); + // rigid + bool PrepareRigidOGF(IWriter &F, bool gen_tb, CEditableMesh *mesh); + // ogf + bool PrepareOGF(IWriter &F, u8 infl, bool gen_tb, CEditableMesh *mesh); + bool ExportOGF(LPCSTR fname, u8 skl_infl); + // omf + bool PrepareOMF(IWriter &F); + bool ExportOMF(LPCSTR fname); + // obj + bool ExportOBJ(LPCSTR name); + + LPCSTR GenerateSurfaceName(LPCSTR base_name); +#ifdef _MAYA_EXPORT + BOOL ParseMAMaterial(CSurface *dest, SXRShaderData &d); + CSurface *CreateSurface(LPCSTR m_name, SXRShaderData &d); + CSurface *CreateSurface(MObject shader); +#endif + bool ExportLWO(LPCSTR fname); + bool Validate(); + +private: + float GetBonesBottom(); + +public: + void CalculateRootObjectAnimation(const Fmatrix &anchor); + void GetAnchorForRootObjectAnimation(Fmatrix &anchor); + bool AnimateRootObject(CSMotion *motion); + +private: + virtual void Bone_Calculate(CBoneData *bd, Fmatrix *parent) { VERIFY(false); } + virtual void Bone_GetAnimPos(Fmatrix &pos, u16 id, u8 channel_mask, bool ignore_callbacks) { VERIFY(false); } + + virtual bool PickBone(const Fmatrix &parent_xform, pick_result &r, float dist, const Fvector &start, const Fvector &dir, u16 bone_id) + { + VERIFY(false); + return false; + } + virtual void EnumBoneVertices(SEnumVerticesCallback &C, u16 bone_id) { VERIFY(false); } + + // Low level interface + virtual u16 LL_BoneID(LPCSTR B) + { + int id = FindBoneByNameIdx(B); + VERIFY(id < u16(-1)); + return (u16)id; + } + virtual u16 LL_BoneID(const shared_str &B) { return LL_BoneID(B.c_str()); } + virtual LPCSTR LL_BoneName_dbg(u16 ID); + + virtual CInifile *LL_UserData() { return 0; } + virtual accel *LL_Bones() + { + VERIFY(false); + return 0; + } + + virtual CBoneInstance &LL_GetBoneInstance(u16 bone_id); + + virtual CBoneData &LL_GetData(u16 bone_id); + + virtual const IBoneData &GetBoneData(u16 bone_id) const { return *GetBone(bone_id); } + + virtual u16 LL_BoneCount() const { return (u16)BoneCount(); } + virtual u16 LL_VisibleBoneCount() + { + VERIFY(false); + return 0; + } + virtual ICF Fmatrix &LL_GetTransform(u16 bone_id) { return GetBone(bone_id)->LTransform(); } + virtual ICF const Fmatrix &LL_GetTransform(u16 bone_id) const { return GetBone(bone_id)->LTransform(); } + virtual ICF Fmatrix &LL_GetTransform_R(u16 bone_id); + virtual Fobb &LL_GetBox(u16 bone_id); + virtual void LL_GetBindTransform(xr_vector &matrices) { VERIFY(false); } + virtual int LL_GetBoneGroups(xr_vector> &groups) + { + VERIFY(false); + return 0; + } + + virtual u16 LL_GetBoneRoot() + { + u16 root_id = (u16)GetRootBoneID(); + VERIFY(root_id < u16(-1)); + return root_id; + } + virtual void LL_SetBoneRoot(u16 bone_id) { VERIFY(false); } + + virtual BOOL LL_GetBoneVisible(u16 bone_id) { return TRUE; } + virtual void LL_SetBoneVisible(u16 bone_id, BOOL val, BOOL bRecursive) { VERIFY(false); } + virtual u64 LL_GetBonesVisible() { return -1; } + virtual void LL_SetBonesVisible(u64 mask) { VERIFY(false); } + + // Main functionality + virtual void CalculateBones(BOOL bForceExact = FALSE) {} // Recalculate skeleton + virtual void CalculateBones_Invalidate() {} + virtual void Callback(UpdateCallback C, void *Param) { VERIFY(false); } + + // Callback: data manipulation + virtual void SetUpdateCallback(UpdateCallback pCallback) { VERIFY(false); } + virtual void SetUpdateCallbackParam(void *pCallbackParam) { VERIFY(false); } + + virtual UpdateCallback GetUpdateCallback() + { + VERIFY(false); + return 0; + } + virtual void *GetUpdateCallbackParam() + { + VERIFY(false); + return 0; + } + // UpdateCallback Update_Callback; + // void* Update_Callback_Param; + virtual IRenderVisual *dcast_RenderVisual() { return 0; } + virtual IKinematicsAnimated *dcast_PKinematicsAnimated() + { + VERIFY(false); + return 0; + } + + virtual void LL_AddTransformToBone(KinematicsABT::additional_bone_transform& offset) { R_ASSERT(false); } + virtual void LL_ClearAdditionalTransform(u16 bone_id) { R_ASSERT(false); } + + // debug +#ifdef DEBUG + virtual void DebugRender(Fmatrix &XFORM) + { + VERIFY(false); + } + virtual shared_str getDebugName() { return m_ModifName; } +#endif +private: + virtual IKinematics *ObjectKinematics() { return this; } + int m_FaceCount; + int m_VertexCount; +}; +//---------------------------------------------------- +#define EOBJ_CURRENT_VERSION 0x0010 +//---------------------------------------------------- +#define EOBJ_CHUNK_OBJECT_BODY 0x7777 +#define EOBJ_CHUNK_VERSION 0x0900 +#define EOBJ_CHUNK_REFERENCE 0x0902 +#define EOBJ_CHUNK_FLAGS 0x0903 +#define EOBJ_CHUNK_SURFACES 0x0905 +#define EOBJ_CHUNK_SURFACES2 0x0906 +#define EOBJ_CHUNK_SURFACES3 0x0907 +#define EOBJ_CHUNK_EDITMESHES 0x0910 +#define EOBJ_CHUNK_CLASSSCRIPT 0x0912 +#define EOBJ_CHUNK_BONES 0x0913 +#define EOBJ_CHUNK_SMOTIONS 0x0916 +#define EOBJ_CHUNK_SURFACES_XRLC 0x0918 +#define EOBJ_CHUNK_BONEPARTS 0x0919 +#define EOBJ_CHUNK_ACTORTRANSFORM 0x0920 +#define EOBJ_CHUNK_BONES2 0x0921 +#define EOBJ_CHUNK_DESC 0x0922 +#define EOBJ_CHUNK_BONEPARTS2 0x0923 +#define EOBJ_CHUNK_SMOTIONS2 0x0924 +#define EOBJ_CHUNK_LODS 0x0925 +#define EOBJ_CHUNK_SMOTIONS3 0x0926 diff --git a/src/editors/xrECore/Editor/EditObjectEditor.cpp b/src/editors/xrECore/Editor/EditObjectEditor.cpp new file mode 100644 index 00000000000..e8f3e500958 --- /dev/null +++ b/src/editors/xrECore/Editor/EditObjectEditor.cpp @@ -0,0 +1,562 @@ +#include "stdafx.h" +#include "EditObject.h" +#include "EditMesh.h" +#include "xrCore/Animation/Motion.hpp" +#include "xrCore/Animation/Bone.hpp" +#include "d3dutils.h" +#include "ui_main.h" +#include "render.h" +#include "Layers/xrRender/ResourceManager.h" +#include "ImageManager.h" + +const float tex_w = LOD_SAMPLE_COUNT * LOD_IMAGE_SIZE; +const float tex_h = 1 * LOD_IMAGE_SIZE; +const float half_p_x = 0.5f * (1.f / tex_w); +const float half_p_y = 0.5f * (1.f / tex_h); +const float offs_x = 1.f / tex_w; +const float offs_y = 1.f / tex_h; + +static Fvector LOD_pos[4] = { + {-1.0f + offs_x, 1.0f - offs_y, 0.0f}, + {1.0f - offs_x, 1.0f - offs_y, 0.0f}, + {1.0f - offs_x, -1.0f + offs_y, 0.0f}, + {-1.0f + offs_x, -1.0f + offs_y, 0.0f}}; +static FVF::LIT LOD[4] = { + {{-1.0f, 1.0f, 0.0f}, 0xFFFFFFFF, {0.0f, 0.0f}}, // F 0 + {{1.0f, 1.0f, 0.0f}, 0xFFFFFFFF, {0.0f, 0.0f}}, // F 1 + {{1.0f, -1.0f, 0.0f}, 0xFFFFFFFF, {0.0f, 0.0f}}, // F 2 + {{-1.0f, -1.0f, 0.0f}, 0xFFFFFFFF, {0.0f, 0.0f}}, // F 3 +}; + +bool CEditableObject::Reload() +{ + ClearGeometry(); + return Load(m_LoadName.c_str()); +} + +bool CEditableObject::RayPick(float &dist, const Fvector &S, const Fvector &D, const Fmatrix &inv_parent, SRayPickInfo *pinf) +{ + bool picked = false; + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + if ((*m)->RayPick(dist, S, D, inv_parent, pinf)) + picked = true; + return picked; +} + +void CEditableObject::RayQuery(SPickQuery &pinf) +{ + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + (*m)->RayQuery(pinf); +} + +void CEditableObject::RayQuery(const Fmatrix &parent, const Fmatrix &inv_parent, SPickQuery &pinf) +{ + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + (*m)->RayQuery(parent, inv_parent, pinf); +} + +void CEditableObject::BoxQuery(const Fmatrix &parent, const Fmatrix &inv_parent, SPickQuery &pinf) +{ + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + (*m)->BoxQuery(parent, inv_parent, pinf); +} + +#ifdef _EDITOR +bool CEditableObject::FrustumPick(const CFrustum &frustum, const Fmatrix &parent) +{ + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + if ((*m)->FrustumPick(frustum, parent)) + return true; + return false; +} + +bool CEditableObject::BoxPick(CCustomObject *obj, const Fbox &box, const Fmatrix &inv_parent, SBoxPickInfoVec &pinf) +{ + bool picked = false; + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); m++) + if ((*m)->BoxPick(box, inv_parent, pinf)) + { + pinf.back().s_obj = obj; + picked = true; + } + return picked; +} +#endif + +extern float ssaLIMIT; +extern float g_fSCREEN; +static const float ssaLim = 64.f * 64.f / (640 * 480); +void CEditableObject::Render(const Fmatrix &parent, int priority, bool strictB2F, SurfaceVec *surfaces) +{ + if (!(m_LoadState.is(LS_RBUFFERS))) + DefferedLoadRP(); + Fvector v; + float r; + Fbox bb; + bb.xform(m_BBox, parent); + bb.getsphere(v, r); + + if (EPrefs->object_flags.is(epoDrawLOD) && (m_objectFlags.is(eoUsingLOD) && (CalcSSA(v, r) < ssaLim))) + { + if ((1 == priority) && (true == strictB2F)) + RenderLOD(parent); + } + else + { + RCache.set_xform_world(parent); + if (m_objectFlags.is(eoHOM)) + { + if ((1 == priority) && (false == strictB2F)) + RenderEdge(parent, 0, 0, 0x40B64646); + + if ((2 == priority) && (true == strictB2F)) + RenderSelection(parent, 0, 0, 0xA0FFFFFF); + } + else if (m_objectFlags.is(eoSoundOccluder)) + { + if ((1 == priority) && (false == strictB2F)) + RenderEdge(parent, 0, 0, 0xFF000000); + + if ((2 == priority) && (true == strictB2F)) + RenderSelection(parent, 0, 0, 0xA00000FF); + } + else + { + if (psDeviceFlags.is(rsEdgedFaces) && (1 == priority) && (false == strictB2F)) + RenderEdge(parent); + size_t s_id = 0; + for (SurfaceIt s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + { + int pr = (*s_it)->_Priority(); + bool strict = (*s_it)->_StrictB2F(); + + if ((priority == pr) && (strictB2F == strict)) + { + if (surfaces) + { + EDevice.SetShader((*surfaces)[s_id]->_Shader()); + } + else + { + + EDevice.SetShader((*s_it)->_Shader()); + } + for (EditMeshIt _M = m_Meshes.begin(); _M != m_Meshes.end(); _M++) + if (IsSkeleton()) + (*_M)->RenderSkeleton(parent, *s_it); + else + (*_M)->Render(parent, *s_it); + } + s_id++; + } + } + } +} + +void CEditableObject::RenderSingle(const Fmatrix &parent) +{ + for (int i = 0; i < 4; i++) + { + Render(parent, i, false); + Render(parent, i, true); + } +} + +void CEditableObject::RenderAnimation(const Fmatrix &) +{ +} + +void CEditableObject::RenderEdge(const Fmatrix &parent, CEditableMesh *mesh, CSurface *surf, u32 color) +{ + if (!(m_LoadState.is(LS_RBUFFERS))) + DefferedLoadRP(); + + EDevice.SetShader(EDevice.m_WireShader); + if (mesh) + mesh->RenderEdge(parent, surf, color); + else + for (EditMeshIt _M = m_Meshes.begin(); _M != m_Meshes.end(); _M++) + (*_M)->RenderEdge(parent, surf, color); +} + +void CEditableObject::RenderSelection(const Fmatrix &parent, CEditableMesh *mesh, CSurface *surf, u32 color) +{ + if (!(m_LoadState.is(LS_RBUFFERS))) + DefferedLoadRP(); + + RCache.set_xform_world(parent); + EDevice.SetShader(EDevice.m_SelectionShader); + EDevice.RenderNearer(0.0005); + if (mesh) + mesh->RenderSelection(parent, surf, color); + else + for (EditMeshIt _M = m_Meshes.begin(); _M != m_Meshes.end(); _M++) + (*_M)->RenderSelection(parent, surf, color); + EDevice.ResetNearer(); +} + +IC static void CalculateLODTC(int frame, int w_cnt, int h_cnt, Fvector2 <, Fvector2 &rb) +{ + Fvector2 ts; + ts.set(1.f / (float)w_cnt, 1.f / (float)h_cnt); + lt.x = (frame % w_cnt + 0) * ts.x + half_p_x; + lt.y = (frame / w_cnt + 0) * ts.y + half_p_y; + rb.x = (frame % w_cnt + 1) * ts.x - half_p_x; + rb.y = (frame / w_cnt + 1) * ts.y - half_p_y; +} + +void CEditableObject::GetLODFrame(int frame, Fvector p[4], Fvector2 t[4], const Fmatrix *parent) +{ + R_ASSERT(m_objectFlags.is(eoUsingLOD)); + Fvector P, S; + m_BBox.get_CD(P, S); + float r = _max(S.x, S.z); // sqrtf(S.x*S.x+S.z*S.z); + Fmatrix T, matrix, rot; + T.scale(r, S.y, r); + T.translate_over(P); + if (parent) + T.mulA_43(*parent); + + float angle = frame * (PI_MUL_2 / float(LOD_SAMPLE_COUNT)); + rot.rotateY(-angle); + matrix.mul(T, rot); + Fvector2 lt, rb; + CalculateLODTC(frame, LOD_SAMPLE_COUNT, 1, lt, rb); + t[0].set(lt); + t[1].set(rb.x, lt.y); + t[2].set(rb); + t[3].set(lt.x, rb.y); + matrix.transform_tiny(p[0], LOD_pos[0]); + matrix.transform_tiny(p[1], LOD_pos[1]); + matrix.transform_tiny(p[2], LOD_pos[2]); + matrix.transform_tiny(p[3], LOD_pos[3]); +} + +void CEditableObject::RenderLOD(const Fmatrix &parent) +{ + Fvector C; + C.sub(parent.c, EDevice.m_Camera.GetPosition()); + C.y = 0; + float m = C.magnitude(); + if (m < EPS) + return; + C.div(m); + int max_frame; + float max_dot = 0; + Fvector HPB; + parent.getHPB(HPB); + + for (int frame = 0; frame < LOD_SAMPLE_COUNT; frame++) + { + float angle = angle_normalize(frame * (PI_MUL_2 / float(LOD_SAMPLE_COUNT)) + HPB.x); + + Fvector D; + D.setHP(angle, 0); + float dot = C.dotproduct(D); + if (dot < 0.7072f) + continue; + + if (dot > max_dot) + { + max_dot = dot; + max_frame = frame; + } + } + { + Fvector p[4]; + Fvector2 t[4]; + GetLODFrame(max_frame, p, t); + for (int i = 0; i < 4; i++) + { + LOD[i].p.set(p[i]); + LOD[i].t.set(t[i]); + } + RCache.set_xform_world(parent); + EDevice.SetShader(m_LODShader ? m_LODShader : EDevice.m_WireShader); + DU_impl.DrawPrimitiveLIT(D3DPT_TRIANGLEFAN, 2, LOD, 4, true, false); + } +} + +xr_string CEditableObject::GetLODTextureName() +{ + string512 nm; + strcpy(nm, m_LibName.c_str()); + _ChangeSymbol(nm, '\\', '_'); + xr_string l_name; + l_name = xr_string("lod_") + nm; + return ImageLib.UpdateFileName(l_name); +} + +void CEditableObject::OnDeviceCreate() +{ +} + +void CEditableObject::OnDeviceDestroy() +{ + DefferedUnloadRP(); +} + +void CEditableObject::DefferedLoadRP() +{ + if (m_LoadState.is(LS_RBUFFERS)) + return; + + // skeleton + if (IsSkeleton()) + vs_SkeletonGeom.create(FVF_SV, RImplementation.Vertex.Buffer(), RImplementation.Index.Buffer()); + + //*/ + // создать LOD shader + xr_string l_name = GetLODTextureName(); + xr_string fname = xr_string(l_name) + xr_string(".dds"); + m_LODShader.destroy(); + // if (FS.exist(_game_textures_,fname.c_str())) + if (m_objectFlags.is(eoUsingLOD)) + m_LODShader.create(GetLODShaderName(), l_name.c_str()); + m_LoadState.set(LS_RBUFFERS, TRUE); +} +void CEditableObject::DefferedUnloadRP() +{ + if (!(m_LoadState.is(LS_RBUFFERS))) + return; + // skeleton + vs_SkeletonGeom.destroy(); + // удалить буфера + for (EditMeshIt _M = m_Meshes.begin(); _M != m_Meshes.end(); _M++) + if (*_M) + (*_M)->GenerateRenderBuffers(); + // удалить shaders + for (SurfaceIt s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + (*s_it)->OnDeviceDestroy(); + // LOD + m_LODShader.destroy(); + m_LoadState.set(LS_RBUFFERS, FALSE); +} +void CEditableObject::EvictObject() +{ + EditMeshIt m = m_Meshes.begin(); + for (; m != m_Meshes.end(); m++) + { + (*m)->UnloadCForm(); + (*m)->UnloadVNormals(true); + (*m)->UnloadSVertices(true); + (*m)->UnloadFNormals(true); + } + DefferedUnloadRP(); +} + +// bool CEditableObject::PrepareOGF(IWriter& F, u8 infl, bool gen_tb, CEditableMesh* mesh) +//{ +// return IsSkeleton()?PrepareSkeletonOGF(F,infl):PrepareRigidOGF(F,gen_tb,mesh); +// } +// +// bool CEditableObject::PrepareRigidOGF(IWriter& F, bool gen_tb, CEditableMesh* mesh) +//{ +// CExportObjectOGF E(this); +// return E.Export(F,gen_tb,mesh); +// } +// +// bool CEditableObject::PrepareSVGeometry(IWriter& F, u8 infl) +//{ +// CExportSkeleton E(this); +// return E.ExportGeometry(F, infl); +// } +// +// bool CEditableObject::PrepareSVKeys(IWriter& F) +//{ +// CExportSkeleton E(this); +// return E.ExportMotionKeys(F); +// } +// +// bool CEditableObject::PrepareSVDefs(IWriter& F) +//{ +// CExportSkeleton E(this); +// return E.ExportMotionDefs(F); +// } +// +// bool CEditableObject::PrepareSkeletonOGF(IWriter& F, u8 infl) +//{ +// CExportSkeleton E(this); +// return E.Export(F,infl); +// } +// +// bool CEditableObject::PrepareOMF(IWriter& F) +//{ +// CExportSkeleton E(this); +// return E.ExportMotions(F); +// } +//--------------------------------------------------------------------------- + +void CEditableObject::OnChangeTransform(PropValue *) +{ + UI->RedrawScene(); +} +//--------------------------------------------------------------------------- + +//. #include "../../xrEngine/blenders/Blender.h" +IC BOOL BE(BOOL A, BOOL B) +{ + bool a = !!A; + bool b = !!B; + return a == b; +} +bool CEditableObject::CheckShaderCompatible() +{ + bool bRes = true; + for (SurfaceIt s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + { + IBlender *B = EDevice.Resources->_FindBlender(*(*s_it)->m_ShaderName); + Shader_xrLC *C = EDevice.ShaderXRLC.Get(*(*s_it)->m_ShaderXRLCName); + if (!B || !C) + { + ELog.Msg(mtError, "Object '%s': invalid or missing shader [E:'%s', C:'%s']", GetName(), (*s_it)->_ShaderName(), (*s_it)->_ShaderXRLCName()); + bRes = false; + } + else + { + if (!BE(B->canBeLMAPped(), !C->flags.bLIGHT_Vertex)) + { + ELog.Msg(mtError, "Object '%s': engine shader '%s' non compatible with compiler shader '%s'", GetName(), (*s_it)->_ShaderName(), (*s_it)->_ShaderXRLCName()); + bRes = false; + } + } + } + return bRes; +} +#ifdef _EDITOR +void CEditableObject::AddBone(CBone *parent_bone) +{ + CBone *B = xr_new(); + + string256 new_name; + u32 i = 0; + + do + { + sprintf(new_name, "bone%.3d", i++); + } while (FindBoneByName(new_name)); + + B->SetName(new_name); + B->SetWMap(""); + B->SetRestParams(0.01f, Fvector().set(0, 0, 0), Fvector().set(0, 0, 0)); + + B->ResetData(); + B->Reset(); + + if (parent_bone) + { + B->SetParentName(parent_bone->Name().c_str()); + } + else + { + int bid = GetRootBoneID(); + GetBone(bid)->SetParentName(B->Name().c_str()); + B->SetParentName(""); + } + + m_BoneParts[0].bones.push_back(B->Name()); + m_Bones.push_back(B); + PrepareBones(); + + for (EditMeshIt _M = m_Meshes.begin(); _M != m_Meshes.end(); _M++) + { + (*_M)->UnloadSVertices(); + } +} + +CBone *bone_to_delete = NULL; +u32 bone_to_delete_frame = 0; + +void CEditableObject::DeleteBone(CBone *bone) +{ + CBone *PB = bone->Parent(); + + for (BoneIt b_it = m_Bones.begin(); b_it != m_Bones.end(); ++b_it) + { + CBone *B = *b_it; + if (B->Parent() == bone) + B->SetParentName(PB ? PB->Name().c_str() : ""); + } + BoneIt bit = std::find(m_Bones.begin(), m_Bones.end(), bone); + if (bit == m_Bones.end()) + Msg("! bone not found -(("); + else + m_Bones.erase(bit); + + BPIt bpit = BonePart(bone); + RStringVec::iterator iit = (*bpit).bones.begin(); + RStringVec::iterator iit_e = (*bpit).bones.end(); + for (; iit != iit_e; ++iit) + { + if (*iit == bone->Name()) + { + (*bpit).bones.erase(iit); + break; + } + } + + bone_to_delete = bone; + bone_to_delete_frame = EDevice.dwFrame; + PrepareBones(); + + for (EditMeshIt _M = m_Meshes.begin(); _M != m_Meshes.end(); _M++) + { + (*_M)->UnloadSVertices(); + } +} +#endif +//--------------------------------------------------------------------------- + +BPIt CEditableObject::BonePart(CBone *B) +{ + BPIt it = FirstBonePart(); + BPIt it_e = LastBonePart(); + for (; it != it_e; ++it) + { + RStringVec::iterator iit = (*it).bones.begin(); + RStringVec::iterator iit_e = (*it).bones.end(); + for (; iit != iit_e; ++iit) + { + if (*iit == B->Name()) + return it; + } + } + return it_e; +} + +void CEditableObject::RenameBone(CBone *bone, LPCSTR new_name) +{ + BPIt bpit = BonePart(bone); + RStringVec::iterator iit = (*bpit).bones.begin(); + RStringVec::iterator iit_e = (*bpit).bones.end(); + + for (; iit != iit_e; ++iit) + { + if (*iit == bone->Name()) + { + *iit = new_name; + break; + } + } + + for (BoneIt b_it = m_Bones.begin(); b_it != m_Bones.end(); ++b_it) + { + CBone *B = *b_it; + if (B->ParentName() == bone->Name()) + B->SetParentName(new_name); + } + + for (SMotionIt s_it = m_SMotions.begin(); s_it != m_SMotions.end(); ++s_it) + { + CSMotion *M = *s_it; + for (auto bm_it = M->BoneMotions().begin(); bm_it != M->BoneMotions().end(); ++bm_it) + { + if (bm_it->name == bone->Name()) + bm_it->name = new_name; + } + } + + // bone->SetName(new_name); + + Modified(); +} diff --git a/src/editors/xrECore/Editor/EditObjectIO.cpp b/src/editors/xrECore/Editor/EditObjectIO.cpp new file mode 100644 index 00000000000..4bd7adaa924 --- /dev/null +++ b/src/editors/xrECore/Editor/EditObjectIO.cpp @@ -0,0 +1,519 @@ +#include "stdafx.h" +#include "EditObject.h" +#include "EditMesh.h" +#include "xrCore/Animation/Bone.hpp" +#include "xrCore/Animation/Motion.hpp" +#include "exportobjectOGF.h" + +#ifdef _EDITOR + +bool CEditableObject::Load(const char *fname) +{ + if (FS.exist(fname)) + { + int age = FS.get_file_age(fname); + VERIFY3(age > 0, "Invalid file age:", fname); + IReader *F = FS.r_open(fname); + R_ASSERT(F); + IReader *OBJ = F->open_chunk(EOBJ_CHUNK_OBJECT_BODY); + R_ASSERT2(OBJ, "Corrupted file."); + bool bRes = Load(*OBJ); + OBJ->close(); + FS.r_close(F); + if (bRes) + { + m_LoadName = fname; + m_ObjectVersion = age; + } + return bRes; + } + return false; +} +#endif + +bool CEditableObject::Save(const char *fname) +{ + if (IsModified()) + { + // update transform matrix + Fmatrix mTransform, mScale, mTranslate, mRotate; + if (!fsimilar(t_vRotate.magnitude(), 0) || + !fsimilar(t_vScale.magnitude(), 1.73205f) || + !fsimilar(t_vPosition.magnitude(), 0)) + { + mRotate.setHPB(t_vRotate.y, t_vRotate.x, t_vRotate.z); + mScale.scale(t_vScale); + mTranslate.translate(t_vPosition); + mTransform.mul(mTranslate, mRotate); + mTransform.mulB_43(mScale); + TranslateToWorld(mTransform); + t_vRotate.set(0, 0, 0); + t_vPosition.set(0, 0, 0); + t_vScale.set(1, 1, 1); + } + } + + // save object + IWriter *F = FS.w_open(fname); + if (F) + { + F->open_chunk(EOBJ_CHUNK_OBJECT_BODY); + Save(*F); + F->close_chunk(); + + FS.w_close(F); + + m_LoadName = fname; + m_ObjectVersion = (int)FS.get_file_age(fname); + VERIFY3(m_ObjectVersion > 0, "Invalid file age:", fname); + return true; + } + else + { + return false; + } +} + +void CEditableObject::Save(IWriter &F) +{ + F.open_chunk(EOBJ_CHUNK_VERSION); + F.w_u16(EOBJ_CURRENT_VERSION); + F.close_chunk(); + + F.open_chunk(EOBJ_CHUNK_CLASSSCRIPT); + F.w_stringZ(m_ClassScript); + F.close_chunk(); + + F.open_chunk(EOBJ_CHUNK_LODS); + F.w_stringZ(m_LODs); + F.close_chunk(); + + F.w_chunk(EOBJ_CHUNK_FLAGS, &m_objectFlags.flags, sizeof(m_objectFlags.flags)); + + // meshes + F.open_chunk(EOBJ_CHUNK_EDITMESHES); + int count = 0; + + for (EditMeshIt m = m_Meshes.begin(); m != m_Meshes.end(); ++m) + { + F.open_chunk(count); + ++count; + (*m)->SaveMesh(F); + F.close_chunk(); + } + F.close_chunk(); + + // surfaces + F.open_chunk(EOBJ_CHUNK_SURFACES3); + F.w_u32(m_Surfaces.size()); + + for (SurfaceIt sf_it = m_Surfaces.begin(); sf_it != m_Surfaces.end(); ++sf_it) + { + F.w_stringZ((*sf_it)->_Name()); + F.w_stringZ((*sf_it)->_ShaderName()); + F.w_stringZ((*sf_it)->_ShaderXRLCName()); + F.w_stringZ((*sf_it)->_GameMtlName()); + F.w_stringZ((*sf_it)->_Texture()); + F.w_stringZ((*sf_it)->_VMap()); + F.w_u32((*sf_it)->m_Flags.get()); + F.w_u32((*sf_it)->_FVF()); + F.w_u32(1); + } + F.close_chunk(); + + // bones + if (!m_Bones.empty()) + { + F.open_chunk(EOBJ_CHUNK_BONES2); + for (BoneIt b_it = m_Bones.begin(); b_it != m_Bones.end(); ++b_it) + { + F.open_chunk(b_it - m_Bones.begin()); + (*b_it)->Save(F); + F.close_chunk(); + } + F.close_chunk(); + } + + // skeleton motions + if (!m_SMotions.empty()) + { + F.open_chunk(EOBJ_CHUNK_SMOTIONS); + F.w_u32(m_SMotions.size()); + + for (SMotionIt s_it = m_SMotions.begin(); s_it != m_SMotions.end(); ++s_it) + (*s_it)->Save(F); + + F.close_chunk(); + } + // skeleton motions refs + if (m_SMotionRefs.size()) + { + F.open_chunk(EOBJ_CHUNK_SMOTIONS3); + F.w_u32(m_SMotionRefs.size()); + + for (u32 i = 0; i < m_SMotionRefs.size(); ++i) + F.w_stringZ(m_SMotionRefs[i].c_str()); + + F.close_chunk(); + } + + // bone parts + if (!m_BoneParts.empty()) + { + F.open_chunk(EOBJ_CHUNK_BONEPARTS2); + F.w_u32(m_BoneParts.size()); + for (BPIt bp_it = m_BoneParts.begin(); bp_it != m_BoneParts.end(); ++bp_it) + { + F.w_stringZ(bp_it->alias); + F.w_u32(bp_it->bones.size()); + + for (RStringVecIt s_it = bp_it->bones.begin(); s_it != bp_it->bones.end(); ++s_it) + F.w_stringZ(s_it->c_str()); + } + F.close_chunk(); + } + + if (IsDynamic()) + { + F.open_chunk(EOBJ_CHUNK_ACTORTRANSFORM); + F.w_fvector3(a_vPosition); + F.w_fvector3(a_vRotate); + F.close_chunk(); + } + + F.open_chunk(EOBJ_CHUNK_DESC); + F.w_stringZ(m_CreateName.c_str()); + F.w(&m_CreateTime, sizeof(m_CreateTime)); + F.w_stringZ(m_ModifName.c_str()); + F.w(&m_ModifTime, sizeof(m_ModifTime)); + F.close_chunk(); + + // set modif desc + SetVersionToCurrent(FALSE, TRUE); + + bOnModified = false; +} + +#if 1 //#ifdef _EDITOR + +bool CEditableObject::Load(IReader &F) +{ + bool bRes = true; + do + { + u32 version = 0; + shared_str buf; + shared_str sh_name; + R_ASSERT(F.r_chunk(EOBJ_CHUNK_VERSION, &version)); + if (version != EOBJ_CURRENT_VERSION) + { + ELog.DlgMsg(mtError, "CEditableObject: unsupported file version. Object can't load."); + bRes = false; + break; + } + + R_ASSERT(F.r_chunk(EOBJ_CHUNK_FLAGS, &m_objectFlags.flags)); + + if (F.find_chunk(EOBJ_CHUNK_CLASSSCRIPT)) + F.r_stringZ(m_ClassScript); + + if (F.find_chunk(EOBJ_CHUNK_LODS)) + F.r_stringZ(m_LODs); + + // surfaces + if (F.find_chunk(EOBJ_CHUNK_SURFACES3)) + { + u32 cnt = F.r_u32(); + m_Surfaces.resize(cnt); + for (SurfaceIt s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + { + *s_it = xr_new(); + F.r_stringZ(buf); + (*s_it)->SetName(buf.c_str()); + F.r_stringZ(buf); + (*s_it)->SetShader(buf.c_str()); + F.r_stringZ(buf); + (*s_it)->SetShaderXRLC(buf.c_str()); + F.r_stringZ(buf); + (*s_it)->SetGameMtl(buf.c_str()); + F.r_stringZ(buf); + (*s_it)->SetTexture(buf.c_str()); + F.r_stringZ(buf); + (*s_it)->SetVMap(buf.c_str()); + (*s_it)->m_Flags.assign(F.r_u32()); + (*s_it)->SetFVF(F.r_u32()); + cnt = F.r_u32(); + if (cnt > 1) + ELog.DlgMsg(mtError, "Object surface '%s' has more than one TC's.", buf.c_str()); + R_ASSERT(1 <= cnt); + } + } + else if (F.find_chunk(EOBJ_CHUNK_SURFACES2)) + { + u32 cnt = F.r_u32(); + m_Surfaces.resize(cnt); + for (SurfaceIt s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + { + *s_it = xr_new(); + F.r_stringZ(buf); + (*s_it)->SetName(buf.c_str()); + F.r_stringZ(buf); + (*s_it)->SetShader(buf.c_str()); + F.r_stringZ(buf); + (*s_it)->SetShaderXRLC(buf.c_str()); + F.r_stringZ(buf); + (*s_it)->SetTexture(buf.c_str()); + F.r_stringZ(buf); + (*s_it)->SetVMap(buf.c_str()); + (*s_it)->m_Flags.assign(F.r_u32()); + (*s_it)->SetFVF(F.r_u32()); + cnt = F.r_u32(); + if (cnt > 1) + ELog.DlgMsg(mtError, "Object surface '%s' has more than one TC's.", buf.c_str()); + R_ASSERT(1 <= cnt); + } + } + else + { + R_ASSERT(F.find_chunk(EOBJ_CHUNK_SURFACES)); + u32 cnt = F.r_u32(); + m_Surfaces.resize(cnt); + for (SurfaceIt s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + { + *s_it = xr_new(); + F.r_stringZ(buf); + (*s_it)->SetName(buf.c_str()); + F.r_stringZ(sh_name); + (*s_it)->m_Flags.set(CSurface::sf2Sided, !!F.r_u8()); + (*s_it)->SetFVF(F.r_u32()); + cnt = F.r_u32(); + if (cnt > 1) + ELog.DlgMsg(mtError, "Object surface '%s' has more than one TC's.", buf.c_str()); + R_ASSERT(1 <= cnt); + F.r_stringZ(buf); + (*s_it)->SetTexture(buf.c_str()); + F.r_stringZ(buf); + (*s_it)->SetVMap(buf.c_str()); + (*s_it)->SetShader(sh_name.c_str()); + (*s_it)->SetShaderXRLC("default"); + } + + // surfaces xrlc part + if (F.find_chunk(EOBJ_CHUNK_SURFACES_XRLC)) + for (auto s_it = m_Surfaces.begin(); s_it != m_Surfaces.end(); s_it++) + { + F.r_stringZ(buf); + (*s_it)->SetShaderXRLC(buf.c_str()); + } + } + + // Load meshes + IReader *OBJ = F.open_chunk(EOBJ_CHUNK_EDITMESHES); + if (OBJ) + { + IReader *M = OBJ->open_chunk(0); + for (int count = 1; M; count++) + { + CEditableMesh *mesh = xr_new(this); + if (mesh->LoadMesh(*M)) + m_Meshes.push_back(mesh); + else + { + ELog.DlgMsg(mtError, "CEditableObject: Can't load mesh '%s'!", *mesh->m_Name); + xr_delete(mesh); + bRes = false; + } + M->close(); + if (!bRes) + break; + M = OBJ->open_chunk(count); + } + OBJ->close(); + } + + // bones + if (bRes) + { + IReader *B_CHUNK = F.open_chunk(EOBJ_CHUNK_BONES2); + if (B_CHUNK) + { + int chunk = 0; + IReader *O; + while (0 != (O = B_CHUNK->open_chunk(chunk++))) + { + m_Bones.push_back(xr_new()); + m_Bones.back()->Load_1(*O); + O->close(); + } + B_CHUNK->close(); + PrepareBones(); + } + else if (F.find_chunk(EOBJ_CHUNK_BONES)) + { + m_Bones.resize(F.r_u32()); + for (BoneIt b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + { + *b_it = xr_new(); + (*b_it)->Load_0(F); + } + PrepareBones(); + } + + // skeleton motions + if (F.find_chunk(EOBJ_CHUNK_SMOTIONS)) + { + m_SMotions.resize(F.r_u32()); + for (SMotionIt s_it = m_SMotions.begin(); s_it != m_SMotions.end(); s_it++) + { + *s_it = xr_new(); + if (!(*s_it)->Load(F)) + { + Log("!Motions has different version. Load failed."); + xr_delete(*s_it); + m_SMotions.clear(); + break; + } + // resort bone_mots + (*s_it)->SortBonesBySkeleton(m_Bones); + } + } + if (F.find_chunk(EOBJ_CHUNK_SMOTIONS2)) + { + shared_str tmp; + F.r_stringZ(tmp); + u32 set_cnt = _GetItemCount(tmp.c_str()); + + string_path nm; + for (u32 k = 0; k < set_cnt; ++k) + { + _GetItem(tmp.c_str(), k, nm); + m_SMotionRefs.push_back(nm); + } + } + else if (F.find_chunk(EOBJ_CHUNK_SMOTIONS3)) + { + u32 set_cnt = F.r_u32(); + + shared_str nm; + for (u32 k = 0; k < set_cnt; ++k) + { + F.r_stringZ(nm); + m_SMotionRefs.push_back(nm); + } + } + } + + // bone parts + if (bRes) + { + if (F.find_chunk(EOBJ_CHUNK_BONEPARTS)) + { + m_BoneParts.resize(F.r_u32()); + bool bBPok = true; + for (BPIt bp_it = m_BoneParts.begin(); bp_it != m_BoneParts.end(); bp_it++) + { + F.r_stringZ(buf); + bp_it->alias = buf; + bp_it->bones.resize(F.r_u32()); + for (RStringVecIt s_it = bp_it->bones.begin(); s_it != bp_it->bones.end(); s_it++) + { + int idx = F.r_u32(); + if ((idx >= 0) && (idx < (int)m_Bones.size())) + { + *s_it = m_Bones[idx]->Name(); + } + else + { + Log("!Invalid bone parts.", GetName()); + bBPok = false; + break; + } + } + if (!bBPok) + break; + } + if (!bBPok) + m_BoneParts.clear(); + if (!m_BoneParts.empty() && !VerifyBoneParts()) + Log("!Invalid bone parts. Found duplicate bones in object '%s'.", GetName()); + } + else if (F.find_chunk(EOBJ_CHUNK_BONEPARTS2)) + { + m_BoneParts.resize(F.r_u32()); + for (BPIt bp_it = m_BoneParts.begin(); bp_it != m_BoneParts.end(); bp_it++) + { + F.r_stringZ(buf); + bp_it->alias = buf; + bp_it->bones.resize(F.r_u32()); + for (RStringVecIt s_it = bp_it->bones.begin(); s_it != bp_it->bones.end(); s_it++) + F.r_stringZ(*s_it); + } + if (!m_BoneParts.empty() && !VerifyBoneParts()) + Log("!Invalid bone parts. Found duplicate bones in object '%s'.", GetName()); + } + } + + if (bRes) + { + if (F.find_chunk(EOBJ_CHUNK_ACTORTRANSFORM)) + { + F.r_fvector3(a_vPosition); + F.r_fvector3(a_vRotate); + } + + if (F.find_chunk(EOBJ_CHUNK_DESC)) + { + F.r_stringZ(m_CreateName); + F.r(&m_CreateTime, sizeof(m_CreateTime)); + F.r_stringZ(m_ModifName); + F.r(&m_ModifTime, sizeof(m_ModifTime)); + } + + ResetSAnimation(); + } + + if (!bRes) + break; + UpdateBox(); + VerifyMeshNames(); + } while (0); + + return bRes; +} + +bool CEditableObject::ExportOGF(LPCSTR fn, u8 infl) +{ + UpdateBox(); + CMemoryWriter F; + + if (PrepareOGF(F, infl, true, NULL)) + { + return F.save_to(fn); + } + return false; +} +//------------------------------------------------------------------------------ +bool CEditableObject::ExportOMF(LPCSTR fn) +{ + UpdateBox(); + CMemoryWriter F; + if (PrepareOMF(F)) + { + return F.save_to(fn); + } + return false; +} +//------------------------------------------------------------------------------ +bool CEditableObject::ExportOBJ(LPCSTR fn) +{ + UpdateBox(); + CExportObjectOGF E(this); + CMemoryWriter F; + if (E.ExportAsWavefrontOBJ(F, fn)) + { + return F.save_to(fn); + } + return false; +} +//------------------------------------------------------------------------------ +#endif diff --git a/src/editors/xrECore/Editor/EditObjectImport.cpp b/src/editors/xrECore/Editor/EditObjectImport.cpp new file mode 100644 index 00000000000..da5c24d29dd --- /dev/null +++ b/src/editors/xrECore/Editor/EditObjectImport.cpp @@ -0,0 +1,27 @@ +//---------------------------------------------------- +// file: CEditableObjectImport.cpp +//---------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +//#include "lwo2.h" +#include "EditMesh.h" + +extern "C" +{ +#include "lwo2.h" +}; + +#ifdef _EDITOR + +extern "C" __declspec(dllimport) lwObject *LWO_ImportObject(char *filename, lwObject *new_obj); +extern "C" __declspec(dllimport) void LWO_CloseFile(lwObject *new_obj); +#endif + +DEFINE_MAP(void *, int, VMIndexLink, VMIndexLinkIt); + +bool CompareFunc(const st_VMapPt &vm0, const st_VMapPt &vm1) +{ + return vm0.vmap_index < vm1.vmap_index; +}; diff --git a/src/editors/xrECore/Editor/EditObjectMotions.cpp b/src/editors/xrECore/Editor/EditObjectMotions.cpp new file mode 100644 index 00000000000..7e3bd0ec01a --- /dev/null +++ b/src/editors/xrECore/Editor/EditObjectMotions.cpp @@ -0,0 +1,662 @@ +//---------------------------------------------------- +// file: CEditableObject.cpp +//---------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "EditObject.h" + +#ifdef _EDITOR +#include "ui_main.h" +#endif + +#include "xrCore/Animation/Motion.hpp" +#include "xrCore/Animation/Bone.hpp" +#include "EditMesh.h" + +#ifdef _EDITOR +#include "Layers/xrRender/SkeletonAnimated.h" +#include "Layers/xrRender/AnimationKeyCalculate.h" +#endif + +#ifndef _EDITOR +bool check_scale(Fmatrix F) { return true; } +#endif + +//---------------------------------------------------- +class fBoneNameEQ +{ + shared_str name; + +public: + fBoneNameEQ(shared_str N) : name(N){}; + IC bool operator()(CBone *B) { return (xr_strcmp(B->Name(), name) == 0); } +}; +class fBoneWMNameEQ +{ + shared_str wm_name; + +public: + fBoneWMNameEQ(shared_str N) : wm_name(N){}; + IC bool operator()(CBone *B) { return (xr_strcmp(B->WMap(), wm_name) == 0); } +}; +//---------------------------------------------------- +#ifdef _EDITOR +extern CBone *bone_to_delete; +extern u32 bone_to_delete_frame; + +void CEditableObject::OnFrame() +{ + if (IsSkeleton()) + { + BoneVec &lst = m_Bones; + if (IsSMotionActive()) + { + Fvector R, T; + int i = 0; + for (BoneIt b_it = lst.begin(); b_it != lst.end(); b_it++, i++) + { + m_ActiveSMotion->_Evaluate(i, m_SMParam.Frame(), T, R); + (*b_it)->Update(T, R); + } + m_SMParam.Update(EDevice.fTimeDelta, m_ActiveSMotion->fSpeed, !m_ActiveSMotion->m_Flags.is(esmStopAtEnd)); + } + else + { + // for (BoneIt b_it=lst.begin(); b_it!=lst.end(); b_it++) (*b_it)->Reset(); + } + CalculateAnimation(m_ActiveSMotion); + } + if (bone_to_delete) + { + if (EDevice.dwFrame > bone_to_delete_frame + 3) + xr_delete(bone_to_delete); + } +} +#endif + +void CEditableObject::OnBindTransformChange() +{ + for (EditMeshIt mesh_it = FirstMesh(); mesh_it != LastMesh(); mesh_it++) + { + CEditableMesh *MESH = *mesh_it; + MESH->UnloadSVertices(true); + } + GotoBindPose(); +} + +void CEditableObject::GotoBindPose() +{ + BoneVec &lst = m_Bones; + for (BoneIt b_it = lst.begin(); b_it != lst.end(); b_it++) + (*b_it)->Reset(); + CalculateAnimation(0); +#ifdef _EDITOR + UI->RedrawScene(); +#endif +} + +CSMotion *CEditableObject::ResetSAnimation(bool bGotoBindPose) +{ + CSMotion *M = m_ActiveSMotion; + SetActiveSMotion(0); + if (bGotoBindPose) + GotoBindPose(); + return M; +} + +//---------------------------------------------------- +// Skeletal motion +//---------------------------------------------------- +static void CalculateAnimBone(CBone *bone, CSMotion *motion, Fmatrix &parent) +{ + Flags8 flags; + flags.zero(); + if (motion) + flags = motion->GetMotionFlags(bone->SelfID); + + Fmatrix &M = bone->MTransform(); + Fmatrix &L = bone->LTransform(); + + const Fvector &r = bone->Rotate(); + if (!bone->callback_overwrite()) + { + if (flags.is(st_BoneMotion::flWorldOrient)) + { + M.setXYZi(r.x, r.y, r.z); + M.c.set(bone->Offset()); + L.mul(parent, M); + L.i.set(M.i); + L.j.set(M.j); + L.k.set(M.k); + + Fmatrix LI; + LI.invert(parent); + M.mulA_43(LI); + } + else + { + M.setXYZi(r.x, r.y, r.z); + M.c.set(bone->Offset()); + L.mul(parent, M); + } + } + if (bone->callback()) + { + bone->callback()(bone); + M.mul_43(Fmatrix().invert(parent), L); + // bone->Offset().set( M.c ); + } + + bone->RenderTransform().mul_43(bone->LTransform(), bone->RITransform()); +} +static void CalculateAnim(CBone *bone, CSMotion *motion, Fmatrix &parent) +{ + + CalculateAnimBone(bone, motion, parent); + // Calculate children + for (BoneIt b_it = bone->children.begin(); b_it != bone->children.end(); b_it++) + CalculateAnim(*b_it, motion, bone->LTransform()); +} + +static void CalculateRest(CBone *bone, Fmatrix &parent) +{ + Fmatrix &R = bone->RTransform(); + R.setXYZi(bone->RestRotate()); + R.c.set(bone->RestOffset()); + bone->LRTransform() = R; + R.mulA_43(parent); + bone->RITransform().invert(bone->RTransform()); + + // Calculate children + for (BoneIt b_it = bone->children.begin(); b_it != bone->children.end(); b_it++) + CalculateRest(*b_it, bone->RTransform()); +} + +void CEditableObject::CalculateAnimation(CSMotion *motion) +{ + if (!m_Bones.empty()) + CalculateAnim(m_Bones.front(), motion, Fidentity); +} +float CEditableObject::GetBonesBottom() +{ + float bottom = FLT_MAX; + VERIFY(!m_Bones.empty()); + for (BoneIt b_it = m_Bones.begin() + 1; b_it != m_Bones.end(); b_it++) + if (!(*b_it)->IsRoot() && (*b_it)->LTransform().c.y < bottom) + bottom = (*b_it)->LTransform().c.y; + return bottom; +} + +static void SetBoneTransform(CBone &bone, const Fmatrix &T, const Fmatrix &parent) +{ + + bone.LTransform() = T; + Fmatrix LI; + LI.invert(parent); + bone.MTransform().mul_43(LI, T); + bone.RenderTransform().mul_43(bone.LTransform(), bone.RITransform()); +} +bool CEditableObject::AnimateRootObject(CSMotion *motion) +{ + VERIFY(motion); + if (!motion->m_Flags.test(esmRootMover)) + return false; + CBone &root_bone = *m_Bones[GetRootBoneID()]; + if (root_bone.children.size() != 1) + return false; + return true; +} +void CEditableObject::GetAnchorForRootObjectAnimation(Fmatrix &anchor) +{ + CBone &root_bone = *m_Bones[GetRootBoneID()]; + VERIFY(root_bone.children.size() == 1); + CBone &anchor_bone = *root_bone.children[0]; + anchor = anchor_bone.LTransform(); + anchor.invert(); +} +static void AlineYtoGlobalFrame(Fmatrix &in_out_m) +{ + Fmatrix &m = in_out_m; + + m.i.y = 0; + m.k.y = 0; + + m.j.x = 0; + m.j.y = 1; + m.j.z = 0; + + float smi = m.i.x * m.i.x + m.i.z * m.i.z; + float smk = m.k.x * m.k.x + m.k.z * m.k.z; + bool bi = smi > EPS_S; + bool bk = smk > EPS_S; + if (smk > smi && bk) + { + m.k.mul(1.f / _sqrt(smk)); + m.i.crossproduct(m.j, m.k); + } + else if (bi) + { + m.i.mul(1.f / _sqrt(smi)); + m.k.crossproduct(m.i, m.j); + } + else // if( !bi && !bk ) + { + // unreal indeed + m = Fidentity; + } + + // if ( bi && bk ) + // { + // m.i.mul( 1.f/_sqrt( smi ) ); + // m.k.mul( 1.f/_sqrt( smk ) ); + // } + + if (!check_scale(in_out_m)) + VERIFY(check_scale(in_out_m)); +} +void CEditableObject::CalculateRootObjectAnimation(const Fmatrix &anchor) +{ + float bottom = GetBonesBottom(); + CBone &root_bone = *m_Bones[GetRootBoneID()]; + VERIFY(root_bone.children.size() == 1); + CBone &anchor_bone = *root_bone.children[0]; + const Fmatrix gl_anchor = Fmatrix().mul_43(anchor_bone.LTransform(), anchor); + + Fmatrix root_transform = gl_anchor; // gl_anchor; + AlineYtoGlobalFrame(root_transform); + + root_transform.c = gl_anchor.c; + root_transform.c.y = bottom; + SetBoneTransform(root_bone, root_transform, Fidentity); + + SetBoneTransform(anchor_bone, anchor_bone.LTransform(), root_transform); + + // for (BoneIt b_it=root_bone .children.begin(); b_it!=root_bone .children.end(); b_it++) + // SetBoneTransform( *(*b_it), (*(*b_it)).LTransform(), root_transform ); +} +void CEditableObject::CalculateBindPose() +{ + if (!m_Bones.empty()) + CalculateRest(m_Bones.front(), Fidentity); +} + +void CEditableObject::SetActiveSMotion(CSMotion *mot) +{ + m_ActiveSMotion = mot; + if (m_ActiveSMotion) + m_SMParam.Set(m_ActiveSMotion); +} + +bool CEditableObject::RemoveSMotion(const char *name) +{ + SMotionVec &lst = m_SMotions; + for (SMotionIt m = lst.begin(); m != lst.end(); m++) + if ((stricmp((*m)->Name(), name) == 0)) + { + if (m_ActiveSMotion == *m) + SetActiveSMotion(0); + xr_delete(*m); + lst.erase(m); + return true; + } + return false; +} + +//--------------------------------------------------------------------------- +/* +bool CEditableObject::LoadSMotions(const char* fname) +{ + IReader* F = FS.r_open(fname); + ClearSMotions(); + // object motions + m_SMotions.resize(F->r_u32()); + SetActiveSMotion(0); + for (SMotionIt m_it=m_SMotions.begin(); m_it!=m_SMotions.end(); m_it++){ + *m_it = xr_new(); + if (!(*m_it)->Load(*F)){ + ELog.DlgMsg(mtError,"Motions has different version. Load failed."); + xr_delete(*m_it); + m_SMotions.clear(); + FS.r_close(F); + return false; + } + if (!CheckBoneCompliance(*m_it)){ + ClearSMotions(); + ELog.DlgMsg(mtError,"Load failed.",fname); + xr_delete(&*m_it); + FS.r_close(F); + return false; + } + } + FS.r_close(F); + return true; +} +*/ +bool CEditableObject::AppendSMotion(LPCSTR fname, SMotionVec *inserted) +{ + VERIFY(IsSkeleton()); + + bool bRes = true; + + LPCSTR ext = strext(fname); + if (0 == stricmp(ext, ".skl")) + { + CSMotion *M = xr_new(); + if (!M->LoadMotion(fname)) + { + ELog.Msg(mtError, "Motion '%s' can't load. Append failed.", fname); + xr_delete(M); + bRes = false; + } + else + { + string256 name; + _splitpath(fname, 0, 0, name, 0); + if (CheckBoneCompliance(M)) + { + M->SortBonesBySkeleton(m_Bones); + string256 m_name; + GenerateSMotionName(m_name, name, M); + M->SetName(m_name); + m_SMotions.push_back(M); + if (inserted) + inserted->push_back(M); + // optimize + M->Optimize(); + } + else + { + ELog.Msg(mtError, "Append failed.", fname); + xr_delete(M); + bRes = false; + } + } + } + else if (0 == stricmp(ext, ".skls")) + { + IReader *F = FS.r_open(fname); + if (!F) + { + ELog.Msg(mtError, "Can't open file '%s'.", fname); + bRes = false; + } + if (bRes) + { + // object motions + int cnt = F->r_u32(); + for (int k = 0; k < cnt; k++) + { + CSMotion *M = xr_new(); + if (!M->Load(*F)) + { + ELog.Msg(mtError, "Motion '%s' has different version. Load failed.", M->Name()); + xr_delete(M); + bRes = false; + break; + } + if (!CheckBoneCompliance(M)) + { + xr_delete(M); + bRes = false; + break; + } + if (bRes) + { + M->SortBonesBySkeleton(m_Bones); + string256 m_name; + GenerateSMotionName(m_name, M->Name(), M); + M->SetName(m_name); + m_SMotions.push_back(M); + if (inserted) + inserted->push_back(M); + // optimize + M->Optimize(); + } + } + } + FS.r_close(F); + } + return bRes; +} + +void CEditableObject::ClearSMotions() +{ + SetActiveSMotion(0); + for (SMotionIt m_it = m_SMotions.begin(); m_it != m_SMotions.end(); m_it++) + xr_delete(*m_it); + m_SMotions.clear(); +} + +bool CEditableObject::SaveSMotions(const char *fname) +{ + CMemoryWriter F; + F.w_u32(m_SMotions.size()); + for (SMotionIt m_it = m_SMotions.begin(); m_it != m_SMotions.end(); m_it++) + (*m_it)->Save(F); + return F.save_to(fname); +} + +bool CEditableObject::RenameSMotion(const char *old_name, const char *new_name) +{ + if (stricmp(old_name, new_name) == 0) + return true; + if (FindSMotionByName(new_name)) + return false; + CSMotion *M = FindSMotionByName(old_name); + VERIFY(M); + M->SetName(new_name); + return true; +} + +CSMotion *CEditableObject::FindSMotionByName(const char *name, const CSMotion *Ignore) +{ + if (name && name[0]) + { + SMotionVec &lst = m_SMotions; + for (SMotionIt m = lst.begin(); m != lst.end(); m++) + if ((Ignore != (*m)) && (stricmp((*m)->Name(), name) == 0)) + return (*m); + } + return 0; +} + +void CEditableObject::GenerateSMotionName(char *buffer, const char *start_name, const CSMotion *M) +{ + strcpy(buffer, start_name); + int idx = 0; + while (FindSMotionByName(buffer, M)) + { + sprintf(buffer, "%s_%2d", start_name, idx); + idx++; + } + strlwr(buffer); +} + +ICF bool pred_sort_B(CBone *A, CBone *B) +{ + return (xr_strcmp(A->Name().c_str(), B->Name().c_str()) < 0); +} +ICF void fill_bones_by_parent(BoneVec &bones, CBone *start) +{ + bones.push_back(start); + for (BoneIt b_it = start->children.begin(); b_it != start->children.end(); b_it++) + fill_bones_by_parent(bones, *b_it); +} +void CEditableObject::PrepareBones() +{ + if (m_Bones.empty()) + return; + CBone *PARENT = 0; + // clear empty parent + BoneIt b_it; + for (b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + { + (*b_it)->children.clear(); + (*b_it)->parent = NULL; + BoneIt parent = std::find_if(m_Bones.begin(), m_Bones.end(), fBoneNameEQ((*b_it)->ParentName())); + if (parent == m_Bones.end()) + { + (*b_it)->SetParentName(""); + VERIFY2(0 == PARENT, "Invalid object. Have more than 1 parent."); + PARENT = *b_it; + } + else + { + BoneIt parent = std::find_if(m_Bones.begin(), m_Bones.end(), fBoneNameEQ((*b_it)->ParentName())); + CBone *tmp = (parent == m_Bones.end()) ? 0 : *parent; + (*b_it)->parent = tmp; + } + } + // sort by name + std::sort(m_Bones.begin(), m_Bones.end(), pred_sort_B); + // fill children + for (b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + { + BoneIt parent = std::find_if(m_Bones.begin(), m_Bones.end(), fBoneNameEQ((*b_it)->ParentName())); + if (parent != m_Bones.end()) + (*parent)->children.push_back(*b_it); + } + // manual sort + u32 b_cnt = m_Bones.size(); + m_Bones.clear(); + fill_bones_by_parent(m_Bones, PARENT); + + u32 cnt_new = m_Bones.size(); + VERIFY(b_cnt == cnt_new); + // update SelfID + for (b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + (*b_it)->SelfID = b_it - m_Bones.begin(); + VERIFY(0 == m_Bones.front()->parent); + /* + for (b_it=m_Bones.begin(); b_it!=m_Bones.end(); b_it++) + Msg("%20s - %20s",(*b_it)->Name().c_str(),(*b_it)->ParentName().c_str()); + */ + CalculateBindPose(); +} + +BoneIt CEditableObject::FindBoneByNameIt(const char *name) +{ + return std::find_if(m_Bones.begin(), m_Bones.end(), fBoneNameEQ(name)); +} + +int CEditableObject::FindBoneByNameIdx(LPCSTR name) +{ + BoneIt b_it = FindBoneByNameIt(name); + return (b_it == m_Bones.end()) ? -1 : b_it - m_Bones.begin(); +} + +CBone *CEditableObject::FindBoneByName(const char *name) +{ + BoneIt b_it = FindBoneByNameIt(name); + return (b_it == m_Bones.end()) ? 0 : *b_it; +} + +int CEditableObject::GetRootBoneID() +{ + for (BoneIt b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + if ((*b_it)->IsRoot()) + return b_it - m_Bones.begin(); + THROW; + return -1; +} + +int CEditableObject::PartIDByName(LPCSTR name) +{ + for (BPIt it = m_BoneParts.begin(); it != m_BoneParts.end(); it++) + if (it->alias == name) + return it - m_BoneParts.begin(); + return -1; +} + +shared_str CEditableObject::BoneNameByID(int id) +{ + VERIFY((id >= 0) && (id < (int)m_Bones.size())); + return m_Bones[id]->Name(); +} + +u16 CEditableObject::GetBoneIndexByWMap(const char *wm_name) +{ + BoneIt bone = std::find_if(m_Bones.begin(), m_Bones.end(), fBoneWMNameEQ(wm_name)); + return (bone == m_Bones.end()) ? BI_NONE : (u16)(bone - m_Bones.begin()); +} + +void CEditableObject::GetBoneWorldTransform(u32 bone_idx, float t, CSMotion *motion, Fmatrix &matrix) +{ + VERIFY(bone_idx < m_Bones.size()); + int idx = bone_idx; + matrix.identity(); + IntVec lst; + do + { + lst.push_back(idx); + } while ((idx = m_Bones[idx]->Parent() ? m_Bones[idx]->Parent()->SelfID : -1) > -1); + for (int i = lst.size() - 1; i >= 0; i--) + { + idx = lst[i]; + Flags8 flags = motion->GetMotionFlags(idx); + Fvector T, R; + Fmatrix rot, mat; + motion->_Evaluate(idx, t, T, R); + if (flags.is(st_BoneMotion::flWorldOrient)) + { + rot.setXYZi(R.x, R.y, R.z); + mat.identity(); + mat.c.set(T); + mat.mulA_43(matrix); + mat.i.set(rot.i); + mat.j.set(rot.j); + mat.k.set(rot.k); + } + else + { + mat.setXYZi(R.x, R.y, R.z); + mat.c.set(T); + mat.mulA_43(matrix); + } + matrix.set(mat); + } +} + +bool CEditableObject::CheckBoneCompliance(CSMotion *M) +{ + VERIFY(M); + /* + BoneMotionVec& lst = M->BoneMotions(); + if (m_Bones.size()!=lst.size()){ + Log ("!Different bone count.\nObject has '%d' bones. Motion has '%d' bones.",m_Bones.size(),lst.size()); + return false; + } + for(BoneMotionIt bm_it=lst.begin(); bm_it!=lst.end(); bm_it++) + if (!FindBoneByName(*bm_it->name)){ + Msg ("!Can't find bone '%s' in object.",bm_it->name); + return false; + } + */ + for (BoneIt b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + if (!M->FindBoneMotion((*b_it)->Name())) + { + // Msg ("!Can't find bone '%s' in motion.",*(*b_it)->Name()); + // return false; + M->add_empty_motion((*b_it)->Name()); + continue; + } + return true; +} + +void CEditableObject::OptimizeSMotions() +{ +#ifdef _EDITOR + SPBItem *pb = UI->ProgressStart(static_cast(m_SMotions.size()), "Motions optimizing..."); +#endif + for (SMotionIt s_it = m_SMotions.begin(); s_it != m_SMotions.end(); s_it++) + { + (*s_it)->Optimize(); +#ifdef _EDITOR + pb->Inc(); +#endif + } +#ifdef _EDITOR + UI->ProgressEnd(pb); +#endif +} diff --git a/src/editors/xrECore/Editor/EditObjectProps.cpp b/src/editors/xrECore/Editor/EditObjectProps.cpp new file mode 100644 index 00000000000..238828b64fc --- /dev/null +++ b/src/editors/xrECore/Editor/EditObjectProps.cpp @@ -0,0 +1,134 @@ +#include "stdafx.h" +#include "EditObject.h" +#include "EditMesh.h" +#include "ui_main.h" +#include "xrCore/Animation/Motion.hpp" +#include "xrCore/Animation/Bone.hpp" + +void CEditableObject::OnChangeShader(PropValue *) +{ + OnDeviceDestroy(); + UI->RedrawScene(); +} + +void CEditableObject::FillSurfaceProps(CSurface *SURF, LPCSTR pref, PropItemVec &items) +{ + PropValue *V; + V = PHelper().CreateChoose(items, PrepareKey(pref, "Texture"), &SURF->m_Texture, smTexture); + V->OnChangeEvent.bind(this, &CEditableObject::OnChangeShader); + V = PHelper().CreateChoose(items, PrepareKey(pref, "Shader"), &SURF->m_ShaderName, smEShader); + V->OnChangeEvent.bind(this, &CEditableObject::OnChangeShader); + V = PHelper().CreateChoose(items, PrepareKey(pref, "Compile"), &SURF->m_ShaderXRLCName, smCShader); + PHelper().CreateChoose(items, PrepareKey(pref, "Game Mtl"), &SURF->m_GameMtlName, smGameMaterial); + V = PHelper().CreateFlag32(items, PrepareKey(pref, "2 Sided"), &SURF->m_Flags, CSurface::sf2Sided); + V->OnChangeEvent.bind(this, &CEditableObject::OnChangeShader); + PHelper().CreateCaption(items, PrepareKey(pref, "Face Count"), shared_str().printf("%d", GetSurfFaceCount(SURF->_Name()))); +} +//--------------------------------------------------------------------------- + +xr_token ECORE_API eo_type_token[] = { + {"Static", 0}, + {"Dynamic", CEditableObject::eoDynamic}, + {"Progressive Dynamic", CEditableObject::eoDynamic | CEditableObject::eoProgressive}, + {"HOM", CEditableObject::eoHOM}, + {"Multiple Usage", CEditableObject::eoMultipleUsage | CEditableObject::eoUsingLOD}, + {"Sound Occluder", CEditableObject::eoSoundOccluder}, + {0, 0}}; + +void CEditableObject::FillBasicProps(LPCSTR pref, PropItemVec &items) +{ + xr_string ct(_ctime32(&m_CreateTime)); + _Trim(ct); + xr_string mt(_ctime32(&m_ModifTime)); + _Trim(mt); + PropValue *V = 0; + PHelper().CreateCaption(items, PrepareKey(pref, "Reference Name"), m_LibName.c_str()); + PHelper().CreateToken32(items, PrepareKey(pref, "Object Type"), &m_objectFlags.flags, eo_type_token); + PHelper().CreateCaption(items, PrepareKey(pref, "Version\\Owner Name"), m_CreateName.c_str()); + PHelper().CreateCaption(items, PrepareKey(pref, "Version\\Modif Name"), m_ModifName.c_str()); + PHelper().CreateCaption(items, PrepareKey(pref, "Version\\Creation Time"), ct.c_str()); + PHelper().CreateCaption(items, PrepareKey(pref, "Version\\Modified Time"), mt.c_str()); + V = PHelper().CreateVector(items, PrepareKey(pref, "Transform\\Position"), &t_vPosition, -10000, 10000, 0.01, 2); + V->OnChangeEvent.bind(this, &CEditableObject::OnChangeTransform); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Transform\\Rotation"), &t_vRotate, -10000, 10000, 0.1, 1); + V->OnChangeEvent.bind(this, &CEditableObject::OnChangeTransform); + V = PHelper().CreateVector(items, PrepareKey(pref, "Transform\\Scale"), &t_vScale, 0.01, 10000, 0.01, 2); + V->OnChangeEvent.bind(this, &CEditableObject::OnChangeTransform); + V = PHelper().CreateCaption(items, PrepareKey(pref, "Transform\\BBox Min"), shared_str().printf("{%3.2f, %3.2f, %3.2f}", VPUSH(GetBox().vMin))); + V = PHelper().CreateCaption(items, PrepareKey(pref, "Transform\\BBox Max"), shared_str().printf("{%3.2f, %3.2f, %3.2f}", VPUSH(GetBox().vMax))); + //. PHelper().CreateChoose (items, PrepareKey(pref,"LOD\\Reference"), &m_LODs, smObject); + PHelper().CreateChoose(items, PrepareKey(pref, "LOD\\Reference"), &m_LODs, smVisual); + + FillSummaryProps(pref, items); +} +//--------------------------------------------------------------------------- + +void CEditableObject::FillSummaryProps(LPCSTR pref, PropItemVec &items) +{ + auto t = make_string("V: %d, F: %d", GetVertexCount(), GetFaceCount()); + PHelper().CreateCaption(items, PrepareKey(pref, "Geometry\\Object"), t.c_str()); + for (EditMeshIt m_it = FirstMesh(); m_it != LastMesh(); m_it++) + { + CEditableMesh *MESH = *m_it; + t = make_string("V: %d, F: %d", MESH->GetVertexCount(), MESH->GetFaceCount()); + PHelper().CreateCaption(items, PrepareKey(pref, xr_string(xr_string("Geometry\\Meshes\\") + MESH->Name().c_str()).c_str()), t.c_str()); + } + PHelper().CreateSText(items, PrepareKey(pref, "Game options\\User Data"), &m_ClassScript); +} +//--------------------------------------------------------------------------- + +ECORE_API xr_string MakeFullBoneName(CBone *bone) +{ + if (bone->Parent()) + { + return MakeFullBoneName(bone->Parent()) + "\\" + bone->Name().c_str(); + } + else + { + return bone->Name().c_str(); + } +} + +xr_string MakeFullBonePath(CBone *bone) +{ + if (bone->Parent()) + { + return MakeFullBoneName(bone->Parent()); + } + else + { + return ""; + } +} + +void CEditableObject::FillSurfaceList(LPCSTR pref, ListItemsVec &items, int modeID) +{ + SurfaceVec &s_lst = Surfaces(); + if (pref) + LHelper().CreateItem(items, pref, modeID, ListItem::flSorted); + for (SurfaceIt s_it = s_lst.begin(); s_it != s_lst.end(); s_it++) + LHelper().CreateItem(items, PrepareKey(pref, (*s_it)->_Name()).c_str(), modeID, 0, *s_it); +} +//--------------------------------------------------------------------------- + +void CEditableObject::FillBoneList(LPCSTR pref, ListItemsVec &items, int modeID) +{ + BoneVec &b_lst = Bones(); + if (pref) + LHelper().CreateItem(items, pref, modeID, ListItem::flSorted); + for (BoneIt b_it = b_lst.begin(); b_it != b_lst.end(); b_it++) + { + xr_string pt = MakeFullBonePath(*b_it); + xr_string path = (!pt.size()) ? pref : PrepareKey(pref, pt.c_str()).c_str(); + LHelper().CreateItem(items, PrepareKey(path.c_str(), (*b_it)->Name().c_str()).c_str(), modeID, 0, *b_it); + } +} + +void CEditableObject::FillMotionList(LPCSTR pref, ListItemsVec &items, int modeID) +{ + SMotionVec &m_lst = SMotions(); + if (pref) + LHelper().CreateItem(items, pref, modeID, ListItem::flSorted); + for (SMotionIt m_it = m_lst.begin(); m_it != m_lst.end(); m_it++) + LHelper().CreateItem(items, PrepareKey(pref, (*m_it)->Name()).c_str(), modeID, 0, *m_it); +} diff --git a/src/editors/xrECore/Editor/EditObjectSkin.cpp b/src/editors/xrECore/Editor/EditObjectSkin.cpp new file mode 100644 index 00000000000..4a60a37a752 --- /dev/null +++ b/src/editors/xrECore/Editor/EditObjectSkin.cpp @@ -0,0 +1,492 @@ +#include "stdafx.h" +#include "EditObject.h" +#include "EditMesh.h" +#include "d3dutils.h" + +#include "editors/FreeMagic/MgcCont3DCylinder.h" + +const u32 color_bone_sel_color = 0xFFFFFFFF; +const u32 color_bone_norm_color = 0xFFFFFF00; +const u32 color_bone_link_color = 0xFFA0A000; +const u32 color_bone_sel_cm = 0xFFFF0000; +const u32 color_bone_norm_cm = 0xFF700000; +const float joint_size = 0.025f; + +void CEditableObject::ResetBones() +{ + BoneVec &lst = m_Bones; + for (BoneIt b_it = lst.begin(); b_it != lst.end(); b_it++) + (*b_it)->ResetData(); +} + +class fBoneNameEQ +{ + shared_str name; + +public: + fBoneNameEQ(shared_str N) : name(N){}; + IC bool operator()(CBone *B) { return (xr_strcmp(B->Name(), name) == 0); } +}; + +bool CEditableObject::LoadBoneData(IReader &F) +{ + BoneVec load_bones; + int count = 0; + IReader *R; + while (0 != (R = F.open_chunk(count++))) + { + CBone *nBone = xr_new(); + load_bones.push_back(nBone); + nBone->LoadData(*R); + Msg("loaded bone [%s]", nBone->Name().c_str()); + } + bool bRes = true; + // load bones + if (!load_bones.empty()) + { + for (BoneIt b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + { + CBone *B = *b_it; + BoneIt n_it = std::find_if(load_bones.begin(), load_bones.end(), fBoneNameEQ(B->Name())); + if (n_it != load_bones.end()) + { + B->CopyData(*n_it); + } + else + { + ELog.Msg(mtError, "Can't find bone: '%s'.", *(*b_it)->Name()); + bRes = false; + // break; + } + } + + for (BoneIt n_it = load_bones.begin(); n_it != load_bones.end(); n_it++) + xr_delete(*n_it); + + load_bones.clear(); + } + else + { + ELog.Msg(mtError, "Empty bone list."); + bRes = false; + } + // load bone part + if (F.find_chunk(EOBJ_CHUNK_BONEPARTS2)) + { + shared_str buf; + m_BoneParts.resize(F.r_u32()); + for (BPIt bp_it = m_BoneParts.begin(); bp_it != m_BoneParts.end(); bp_it++) + { + F.r_stringZ(buf); + bp_it->alias = buf; + bp_it->bones.resize(F.r_u32()); + for (RStringVecIt s_it = bp_it->bones.begin(); s_it != bp_it->bones.end(); s_it++) + F.r_stringZ(*s_it); + } + if (!m_BoneParts.empty() && !VerifyBoneParts()) + ELog.Msg(mtError, "Invalid bone parts. Found missing or duplicate bone."); + } + else + { + ELog.Msg(mtError, "Can't load bone parts. Invalid version."); + } + return bRes; +} + +void CEditableObject::SaveBoneData(IWriter &F) +{ + for (BoneIt b_it = m_Bones.begin(); b_it != m_Bones.end(); b_it++) + { + F.open_chunk(b_it - m_Bones.begin()); + (*b_it)->SaveData(F); + F.close_chunk(); + } + // save bone part + F.open_chunk(EOBJ_CHUNK_BONEPARTS2); + F.w_u32(m_BoneParts.size()); + for (BPIt bp_it = m_BoneParts.begin(); bp_it != m_BoneParts.end(); bp_it++) + { + F.w_stringZ(bp_it->alias.c_str()); + F.w_u32(bp_it->bones.size()); + for (RStringVecIt s_it = bp_it->bones.begin(); s_it != bp_it->bones.end(); s_it++) + F.w_stringZ(*s_it); + } + F.close_chunk(); +} + +void CEditableObject::RenderSkeletonSingle(const Fmatrix &parent) +{ + RenderSingle(parent); + RenderBones(parent); +} + +void CEditableObject::RenderBones(const Fmatrix &parent) +{ + if (IsSkeleton()) + { + // render + BoneVec &lst = m_Bones; + for (BoneIt b_it = lst.begin(); b_it != lst.end(); b_it++) + { + EDevice.SetShader(EDevice.m_WireShader); + RCache.set_xform_world(parent); + Fmatrix &M = (*b_it)->LTransform(); + Fvector p1 = M.c; + u32 c_joint = (*b_it)->flags.is(CBone::flSelected) ? color_bone_sel_color : color_bone_norm_color; + if (EPrefs->object_flags.is(epoDrawJoints)) + DU_impl.DrawJoint(p1, joint_size, c_joint); + // center of mass + if ((*b_it)->shape.type != SBoneShape::stNone) + { + Fvector cm; + M.transform_tiny(cm, (*b_it)->center_of_mass); + if ((*b_it)->flags.is(CBone::flSelected)) + { + float sz = joint_size * 2.f; + DU_impl.DrawCross(cm, sz, sz, sz, sz, sz, sz, 0xFFFFFFFF, false); + DU_impl.DrawRomboid(cm, joint_size * 0.7f, color_bone_sel_cm); + } + else + { + DU_impl.DrawRomboid(cm, joint_size * 0.7f, color_bone_norm_cm); + } + } + /* + if (0){ + M.transform_dir (d); + p2.mad (p1,d,(*b_it)->_Length()); + DU.DrawLine (p1,p2,c_joint); + } + */ + if ((*b_it)->Parent()) + { + EDevice.SetShader(EDevice.m_SelectionShader); + Fvector &p2 = (*b_it)->Parent()->LTransform().c; + DU_impl.DrawLine(p1, p2, color_bone_link_color); + } + if (EPrefs->object_flags.is(epoDrawBoneAxis)) + { + Fmatrix mat; + mat.mul(parent, M); + DU_impl.DrawObjectAxis(mat, 0.03f, (*b_it)->flags.is(CBone::flSelected)); + } + if (EPrefs->object_flags.is(epoDrawBoneNames)) + { + parent.transform_tiny(p1); + u32 c = (*b_it)->flags.is(CBone::flSelected) ? 0xFFFFFFFF : 0xFF000000; + u32 s = (*b_it)->flags.is(CBone::flSelected) ? 0xFF000000 : 0xFF909090; + DU_impl.OutText(p1, (*b_it)->Name().c_str(), c, s); + } + if (EPrefs->object_flags.is(epoDrawBoneShapes)) + { + EDevice.SetShader(EDevice.m_SelectionShader); + Fmatrix mat = M; + mat.mulA_43(parent); + u32 c = (*b_it)->flags.is(CBone::flSelected) ? 0x80ffffff : 0x300000ff; + if ((*b_it)->shape.Valid()) + { + switch ((*b_it)->shape.type) + { + case SBoneShape::stBox: + DU_impl.DrawOBB(mat, (*b_it)->shape.box, c, c); + break; + case SBoneShape::stSphere: + DU_impl.DrawSphere(mat, (*b_it)->shape.sphere, c, c, TRUE, TRUE); + break; + case SBoneShape::stCylinder: + DU_impl.DrawCylinder(mat, (*b_it)->shape.cylinder.m_center, (*b_it)->shape.cylinder.m_direction, (*b_it)->shape.cylinder.m_height, (*b_it)->shape.cylinder.m_radius, c, c, TRUE, TRUE); + break; + } + } + } + } + } +} + +CBone *CEditableObject::PickBone(const Fvector &S, const Fvector &D, const Fmatrix &parent) +{ + BoneVec &lst = m_Bones; + float dist = 10000.f; + CBone *sel = 0; + for (BoneIt b_it = lst.begin(); b_it != lst.end(); b_it++) + { + if ((*b_it)->Pick(dist, S, D, parent)) + sel = *b_it; + } + return sel; +} + +void CEditableObject::SelectBones(bool bVal) +{ + BoneVec &lst = m_Bones; + for (BoneIt b_it = lst.begin(); b_it != lst.end(); b_it++) + (*b_it)->Select(bVal); +} + +void CEditableObject::SelectBone(CBone *b, bool bVal) +{ + if (b) + b->Select(bVal); +} + +int CEditableObject::GetSelectedBones(BoneVec &sel_bones) +{ + BoneVec &lst = m_Bones; + for (BoneIt b_it = lst.begin(); b_it != lst.end(); b_it++) + if ((*b_it)->flags.is(CBone::flSelected)) + sel_bones.push_back(*b_it); + return sel_bones.size(); +} + +#include "editors/FreeMagic/MgcCont3DMinSphere.h" +#include "ExportSkeleton.h" + +BOOL f_valid(float f) +{ + return _finite(f) && !_isnan(f); +} +BOOL SphereValid(FvectorVec &geom, Fsphere &test) +{ + if (!f_valid(test.P.x) || !f_valid(test.R)) + { + Msg("*** Attention ***: invalid sphere: %f,%f,%f - %f", test.P.x, test.P.y, test.P.z, test.R); + } + + Fsphere S = test; + S.R += EPS_L; + for (FvectorIt I = geom.begin(); I != geom.end(); I++) + if (!S.contains(*I)) + return FALSE; + return TRUE; +} + +void ComputeSphere(Fsphere &B, FvectorVec &V) +{ + if (V.size() < 3) + { + B.P.set(0, 0, 0); + B.R = 0.f; + return; + } + + // 1: calc first variation + Fsphere S1; + Fsphere_compute(S1, V.data(), V.size()); + BOOL B1 = SphereValid(V, S1); + + // 2: calc ordinary algorithm (2nd) + Fsphere S2; + Fbox bbox; + bbox.invalidate(); + for (FvectorIt I = V.begin(); I != V.end(); I++) + bbox.modify(*I); + bbox.grow(EPS_L); + bbox.getsphere(S2.P, S2.R); + S2.R = -1; + for (auto I = V.begin(); I != V.end(); I++) + { + float d = S2.P.distance_to_sqr(*I); + if (d > S2.R) + S2.R = d; + } + S2.R = _sqrt(_abs(S2.R)); + BOOL B2 = SphereValid(V, S2); + + // 3: calc magic-fm + Mgc::Sphere _S3 = Mgc::MinSphere(V.size(), (const Mgc::Vector3 *)V.data()); + Fsphere S3; + S3.P.set(_S3.Center().x, _S3.Center().y, _S3.Center().z); + S3.R = _S3.Radius(); + BOOL B3 = SphereValid(V, S3); + + // select best one + if (B1 && (S1.R < S2.R)) + { // miniball or FM + if (B3 && (S3.R < S1.R)) + { // FM wins + B.set(S3); + } + else + { // MiniBall wins + B.set(S1); + } + } + else + { // base or FM + if (B3 && (S3.R < S2.R)) + { // FM wins + B.set(S3); + } + else + { // Base wins :) + R_ASSERT(B2); + B.set(S2); + } + } +} + +void ComputeCylinder(Fcylinder &C, Fobb &B, FvectorVec &V) +{ + if (V.size() < 3) + { + C.invalidate(); + return; + } + // pow(area,(3/2))/volume + // 2*Pi*R*H+2*Pi*R*R + + // Fvector axis; + float max_hI = flt_min; + float min_hI = flt_max; + float max_rI = flt_min; + float max_hJ = flt_min; + float min_hJ = flt_max; + float max_rJ = flt_min; + float max_hK = flt_min; + float min_hK = flt_max; + float max_rK = flt_min; + Fvector axisJ = B.m_rotate.j; + Fvector axisI = B.m_rotate.i; + Fvector axisK = B.m_rotate.k; + Fvector &c = B.m_translate; + for (FvectorIt I = V.begin(); I != V.end(); I++) + { + Fvector tmp; + Fvector pt = *I; + Fvector pt_c; + pt_c.sub(pt, c); + + float pI = axisI.dotproduct(pt); + min_hI = _min(min_hI, pI); + max_hI = _max(max_hI, pI); + tmp.mad(c, axisI, axisI.dotproduct(pt_c)); + max_rI = _max(max_rI, tmp.distance_to(pt)); + + float pJ = axisJ.dotproduct(pt); + min_hJ = _min(min_hJ, pJ); + max_hJ = _max(max_hJ, pJ); + tmp.mad(c, axisJ, axisJ.dotproduct(pt_c)); + max_rJ = _max(max_rJ, tmp.distance_to(pt)); + + float pK = axisK.dotproduct(pt); + min_hK = _min(min_hK, pK); + max_hK = _max(max_hK, pK); + tmp.mad(c, axisK, axisK.dotproduct(pt_c)); + max_rK = _max(max_rK, tmp.distance_to(pt)); + } + + float hI = (max_hI - min_hI); + float hJ = (max_hJ - min_hJ); + float hK = (max_hK - min_hK); + float vI = hI * M_PI * _sqr(max_rI); + float vJ = hJ * M_PI * _sqr(max_rJ); + float vK = hK * M_PI * _sqr(max_rK); + // vI = pow(2*M_PI*max_rI*hI+2*M_PI*_sqr(max_rI),3/2)/vI; + // vJ = pow(2*M_PI*max_rJ*hJ+2*M_PI*_sqr(max_rJ),3/2)/vJ; + // vK = pow(2*M_PI*max_rK*hK+2*M_PI*_sqr(max_rK),3/2)/vK; + // pow(area,(3/2))/volume + // 2*Pi*R*H+2*Pi*R*R + + if (vI < vJ) + { + if (vI < vK) + { + // vI; + C.m_direction.set(axisI); + C.m_height = hI; + C.m_radius = max_rI; + } + else + { + // vK + C.m_direction.set(axisK); + C.m_height = hK; + C.m_radius = max_rK; + } + } + else + { + // vJ < vI + if (vJ < vK) + { + // vJ + C.m_direction.set(axisJ); + C.m_height = hJ; + C.m_radius = max_rJ; + } + else + { + // vK + C.m_direction.set(axisK); + C.m_height = hK; + C.m_radius = max_rK; + } + } + + C.m_center.set(B.m_translate); + /* + if (V.size()<3) { B.invalidate(); return; } + Mgc::Cylinder CYL = Mgc::ContCylinder(V.size(), (const Mgc::Vector3*) V.begin()); + B.m_center.set (CYL.Center()); + B.m_direction.set (CYL.Direction()); + B.m_height = CYL.Height(); + B.m_radius = CYL.Radius(); + */ +} + +bool CEditableObject::GenerateBoneShape(bool bSelOnly) +{ + R_ASSERT(IsSkeleton()); + xr_vector bone_points; + bone_points.resize(m_Bones.size()); + for (EditMeshIt mesh_it = FirstMesh(); mesh_it != LastMesh(); mesh_it++) + { + CEditableMesh *MESH = *mesh_it; + // generate vertex offset + MESH->GenerateSVertices(1); + for (u32 f_id = 0; f_id != MESH->GetFCount(); f_id++) + { + for (int k = 0; k < 3; k++) + { + st_SVert &sv = MESH->m_SVertices[f_id * 3 + k]; + VERIFY(sv.bones.size() == 1); + u16 b_id = sv.bones[0].id; //(sv.bones.size()>1)?(sv.bones[0].w>sv.bones[1].w?sv.bones[0].id:sv.bones[1].id):sv.bones[0].id; + FvectorVec &P = bone_points[b_id]; + bool bFound = false; + Fvector p; + m_Bones[b_id]->RITransform().transform_tiny(p, sv.offs); + for (FvectorIt p_it = P.begin(); p_it != P.end(); p_it++) + if (p_it->similar(p)) + { + bFound = true; + break; + } + if (!bFound) + P.push_back(p); + // if (sv.bone1!=BI_NONE) bone_points[sv.bone1].push_back(sv.offs1); + } + } + MESH->UnloadSVertices(); + } + + BoneVec &lst = m_Bones; + for (BoneIt b_it = lst.begin(); b_it != lst.end(); b_it++) + { + if (bSelOnly && !(*b_it)->flags.is(CBone::flSelected)) + continue; + FvectorVec &positions = bone_points[b_it - lst.begin()]; + ComputeOBB_WML((*b_it)->shape.box, positions); + ComputeSphere((*b_it)->shape.sphere, positions); + ComputeCylinder((*b_it)->shape.cylinder, (*b_it)->shape.box, positions); + (*b_it)->center_of_mass.set((*b_it)->shape.sphere.P); + } + return true; +} + +void CEditableObject::ClampByLimits(bool bSelOnly) +{ + BoneVec &lst = m_Bones; + for (BoneIt b_it = lst.begin(); b_it != lst.end(); b_it++) + if (!bSelOnly || (bSelOnly && (*b_it)->Selected())) + (*b_it)->ClampByLimits(); +} diff --git a/src/editors/xrECore/Editor/EditorChooseEvents.h b/src/editors/xrECore/Editor/EditorChooseEvents.h new file mode 100644 index 00000000000..7a3ce910d19 --- /dev/null +++ b/src/editors/xrECore/Editor/EditorChooseEvents.h @@ -0,0 +1,481 @@ +#pragma once +#include "SoundManager.h" +#include "Library.h" +#include "xrEngine/GameMtlLib.h" +#include "xrEngine/LightAnimLibrary.h" +#include "Layers/xrRender/SkeletonAnimated.h" +#include "Layers/xrRender/ResourceManager.h" +#include "Layers/xrRender/ParticleEffect.h" +#include "Layers/xrRender/ParticleGroup.h" +#include "xrEngine/defines.h" +#include "EditObject.h" +ref_sound *choose_snd; + +namespace ChoseEvents +{ + void FillEntity(ChooseItemVec &items, void *param) + { + CInifile::Root const &data = pSettings->sections(); + for (auto it = data.begin(); it != data.end(); it++) + { + LPCSTR val; + if ((*it)->line_exist("$spawn", &val)) + items.push_back(SChooseItem(*(*it)->Name, "")); + } + } + //--------------------------------------------------------------------------- + void SelectSoundSource(SChooseItem *item, PropItemVec &info_items) + { + choose_snd->stop(); + choose_snd->create(item->name.c_str(), st_Effect, sg_Undefined); + choose_snd->play(0, sm_2D); + // snd.pla + /* + //. + ECustomThumbnail*& thm, ref_sound& snd, + thm = xr_new(item->name.c_str()); + */ + } + void CloseSoundSource() + { + choose_snd->destroy(); + } + void FillSoundSource(ChooseItemVec &items, void *param) + { + FS_FileSet lst; + if (SndLib->GetGameSounds(lst)) + { + auto it = lst.begin(); + auto _E = lst.end(); + for (; it != _E; it++) + items.push_back(SChooseItem(it->name.c_str(), "")); + } + } + //--------------------------------------------------------------------------- + void FillSoundEnv(ChooseItemVec &items, void *param) + { + AStringVec lst; + if (SndLib->GetSoundEnvs(lst)) + { + AStringIt it = lst.begin(); + AStringIt _E = lst.end(); + for (; it != _E; it++) + items.push_back(SChooseItem(it->c_str(), "")); + } + } + //--------------------------------------------------------------------------- + void FillObject(ChooseItemVec &items, void *param) + { + FS_FileSet lst; + if (Lib.GetObjects(lst)) + { + auto it = lst.begin(); + auto _E = lst.end(); + for (; it != _E; it++) + items.push_back(SChooseItem(it->name.c_str(), "")); + } + } + void SelectObject(SChooseItem *item, PropItemVec &info_items) + { + EObjectThumbnail *thm = xr_new(*item->name); + if (thm->Valid()) + thm->FillInfo(info_items); + xr_delete(thm); + } + void UpdateObjectTHM(LPCSTR name, ImTextureID &ID) + { + EObjectThumbnail *thm = xr_new(name); + if (thm->Valid()) + { + thm->Update(ID); + } + else if (ID) + { + ID->Release(); + ID = 0; + } + xr_delete(thm); + } + //--------------------------------------------------------------------------- + void FillGroup(ChooseItemVec &items, void *param) + { + FS_FileSet lst; + if (FS.file_list(lst, _groups_, FS_ListFiles | FS_ClampExt, "*.group")) + { + auto it = lst.begin(); + auto _E = lst.end(); + for (; it != _E; it++) + items.push_back(SChooseItem(it->name.c_str(), "")); + } + } + void SelectGroup(SChooseItem *item, PropItemVec &info_items) + { + EGroupThumbnail *thm = xr_new(*item->name); + if (thm->Valid()) + thm->FillInfo(info_items); + xr_delete(thm); + } + void UpdateGroupTHM(LPCSTR name, ImTextureID &ID) + { + EGroupThumbnail *thm = xr_new(name); + if (thm->Valid()) + { + thm->Update(ID); + } + else if (ID) + { + ID->Release(); + ID = 0; + } + xr_delete(thm); + } + //--------------------------------------------------------------------------- + void FillVisual(ChooseItemVec &items, void *param) + { + FS_FileSet lst; + if (FS.file_list(lst, _game_meshes_, FS_ListFiles | FS_ClampExt, "*.ogf")) + { + auto it = lst.begin(); + auto _E = lst.end(); + for (; it != _E; it++) + items.push_back(SChooseItem(it->name.c_str(), "")); + } + } + void SelectVisual(SChooseItem *item, PropItemVec &info_items) + { + /* + //. + AnsiString fn = ChangeFileExt(item->name.c_str(),".ogf"); + IRender_Visual* visual = ::Render->model_Create(fn.c_str()); + if (visual){ + PHelper().CreateCaption (info_items, "Source", *visual->desc.source_file?*visual->desc.source_file:"unknown"); + PHelper().CreateCaption (info_items, "Creator N",*visual->desc.create_name?*visual->desc.create_name:"unknown"); + PHelper().CreateCaption (info_items, "Creator T",Trim(AnsiString(ctime(&visual->desc.create_time))).c_str()); + PHelper().CreateCaption (info_items, "Modif N", *visual->desc.modif_name ?*visual->desc.modif_name :"unknown"); + PHelper().CreateCaption (info_items, "Modif T", Trim(AnsiString(ctime(&visual->desc.modif_time))).c_str()); + PHelper().CreateCaption (info_items, "Build N", *visual->desc.build_name ?*visual->desc.build_name :"unknown"); + PHelper().CreateCaption (info_items, "Build T", Trim(AnsiString(ctime(&visual->desc.build_time))).c_str()); + } + ::Render->model_Delete(visual); + */ + } + //--------------------------------------------------------------------------- + void FillGameObjectMots(ChooseItemVec &items, void *param) + { + FS_FileSet lst; + if (FS.file_list(lst, _game_meshes_, FS_ListFiles | FS_ClampExt, "*.omf")) + { + auto it = lst.begin(); + auto _E = lst.end(); + for (; it != _E; it++) + items.push_back(SChooseItem(it->name.c_str(), "")); + } + } + void SelectGameObjectMots(SChooseItem *item, PropItemVec &info_items) + { + } + //--------------------------------------------------------------------------- + void FillGameAnim(ChooseItemVec &items, void *param) + { + FS_FileSet lst; + if (FS.file_list(lst, "$game_anims$", FS_ListFiles, "*.anm,*.anms")) + { + auto it = lst.begin(); + auto _E = lst.end(); + for (; it != _E; it++) + items.push_back(SChooseItem(it->name.c_str(), "")); + } + } + //--------------------------------------------------------------------------- + void FillLAnim(ChooseItemVec &items, void *param) + { + LAItemVec &lst = LALib.Objects(); + LAItemIt it = lst.begin(); + LAItemIt _E = lst.end(); + for (; it != _E; it++) + items.push_back(SChooseItem((*it)->cName.c_str(), "")); + } + void UpdateLAnim(LPCSTR name, ImTextureID &Texture) + { + int frame; + CLAItem *item = LALib.FindItem(name); + if (item) + { + + ID3DTexture2D *pTexture = nullptr; + if (Texture != nullptr) + { + R_CHK(Texture->QueryInterface(__uuidof(ID3DTexture2D), (void **)&pTexture)); + } + else + { + R_CHK(HW.pDevice->CreateTexture(THUMB_WIDTH, THUMB_HEIGHT, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &pTexture, 0)); + Texture = pTexture; + } + { + D3DLOCKED_RECT rect; + R_CHK(pTexture->LockRect(0, &rect, 0, 0)); + u32 *dest = nullptr; + + for (u32 y = 0; y < THUMB_HEIGHT; y++) + { + dest = reinterpret_cast(reinterpret_cast(rect.pBits) + (rect.Pitch * y)); + for (u32 i = 0; i < THUMB_WIDTH; i++) + { + dest[i] = item->CalculateBGR(EDevice.fTimeGlobal, frame); + dest[i] = subst_alpha(dest[i], 0xFF); + } + } + R_CHK(pTexture->UnlockRect(0)); + } + } + } + //--------------------------------------------------------------------------- + void FillEShader(ChooseItemVec &items, void *param) + { + CResourceManager::map_Blender &blenders = EDevice.Resources->_GetBlenders(); + auto _S = blenders.begin(); + auto _E = blenders.end(); + for (; _S != _E; _S++) + items.push_back(SChooseItem(_S->first, "")); + } + //--------------------------------------------------------------------------- + void FillCShader(ChooseItemVec &items, void *param) + { + Shader_xrLCVec &shaders = EDevice.ShaderXRLC.Library(); + auto _F = shaders.begin(); + auto _E = shaders.end(); + for (; _F != _E; _F++) + items.push_back(SChooseItem(_F->Name, "")); + } + //--------------------------------------------------------------------------- + void FillPE(ChooseItemVec &items, void *param) + { + for (PS::PEDIt E = ::Render->PSLibrary.FirstPED(); E != ::Render->PSLibrary.LastPED(); E++) + items.push_back(SChooseItem(*(*E)->m_Name, "EFFECT")); + } + //--------------------------------------------------------------------------- + void FillParticles(ChooseItemVec &items, void *param) + { + for (PS::PEDIt E = ::Render->PSLibrary.FirstPED(); E != ::Render->PSLibrary.LastPED(); E++) + items.push_back(SChooseItem(*(*E)->m_Name, "EFFECT")); + for (PS::PGDIt G = ::Render->PSLibrary.FirstPGD(); G != ::Render->PSLibrary.LastPGD(); G++) + items.push_back(SChooseItem(*(*G)->m_Name, "GROUP")); + } + + void SelectPE(SChooseItem *item, PropItemVec &info_items) + { + string64 str; + u32 i = 0; + PHelper().CreateCaption(info_items, "", "used in groups"); + for (PS::PGDIt G = ::Render->PSLibrary.FirstPGD(); G != ::Render->PSLibrary.LastPGD(); ++G) + { + PS::CPGDef *def = (*G); + auto pe_it = def->m_Effects.begin(); + auto pe_it_e = def->m_Effects.end(); + + for (; pe_it != pe_it_e; ++pe_it) + { + if ((*pe_it)->m_EffectName == item->name) + { + xr_sprintf(str, sizeof(str), "%d", ++i); + PHelper().CreateCaption(info_items, str, def->m_Name); + } + } + } + } + + void SelectPG(SChooseItem *item, PropItemVec &info_items) + { + string64 str; + u32 i = 0; + PHelper().CreateCaption(info_items, "", "using effects"); + for (PS::PGDIt G = ::Render->PSLibrary.FirstPGD(); G != ::Render->PSLibrary.LastPGD(); G++) + { + PS::CPGDef *def = (*G); + if (def->m_Name == item->name) + { + auto pe_it = def->m_Effects.begin(); + auto pe_it_e = def->m_Effects.end(); + for (; pe_it != pe_it_e; ++pe_it) + { + xr_sprintf(str, sizeof(str), "%d", ++i); + PHelper().CreateCaption(info_items, (LPCSTR)str, (*pe_it)->m_EffectName); + } + break; + } + } + } + + //--------------------------------------------------------------------------- + void FillTexture(ChooseItemVec &items, void *param) + { + FS_FileSet lst; + if (ImageLib.GetTextures(lst)) + { + auto it = lst.begin(); + auto _E = lst.end(); + for (; it != _E; it++) + items.push_back(SChooseItem(it->name.c_str(), "")); + } + } + + void UpdateTextureTHM(LPCSTR name, ImTextureID &Texture) + { + if (name && name[0]) + { + ETextureThumbnail *thm = xr_new(name); + if (thm->Valid()) + thm->Update(Texture); + xr_delete(thm); + } + } + + //--------------------------------------------------------------------------- + void FillTextureRaw(ChooseItemVec &items, void *param) + { + FS_FileSet lst; + if (ImageLib.GetTexturesRaw(lst)) + { + auto it = lst.begin(); + auto _E = lst.end(); + for (; it != _E; it++) + items.push_back(SChooseItem(it->name.c_str(), "")); + } + } + + void UpdateTextureTHMRaw(LPCSTR name, ImTextureID &ID) + { + if (name && name[0]) + { + ETextureThumbnail *thm = xr_new(name); + if (thm->Valid()) + thm->Update(ID); + xr_delete(thm); + } + } + + void SelectTexture(SChooseItem *item, PropItemVec &info_items) + { + if (item->name.size()) + { + ETextureThumbnail *thm = xr_new(*item->name); + if (thm->Valid()) + thm->FillInfo(info_items); + xr_delete(thm); + } + } + void SelectTextureRaw(SChooseItem *item, PropItemVec &info_items) + { + if (item->name.size()) + { + ETextureThumbnail *thm = xr_new(*item->name); + if (thm->Valid()) + thm->FillInfo(info_items); + xr_delete(thm); + } + } + //--------------------------------------------------------------------------- + void FillGameMaterial(ChooseItemVec &items, void *param) + { + GameMtlIt _F = GMLib.FirstMaterial(); + GameMtlIt _E = GMLib.LastMaterial(); + for (; _F != _E; _F++) + items.push_back(SChooseItem(*(*_F)->m_Name, "")); + } + //--------------------------------------------------------------------------- + + void FillSkeletonAnims(ChooseItemVec &items, void *param) + { + IRenderVisual *V = ::Render->model_Create((LPCSTR)param); + if (PKinematicsAnimated(V)) + { + u32 cnt = PKinematicsAnimated(V)->LL_MotionsSlotCount(); + for (u32 k = 0; k < cnt; k++) + { + accel_map *ll_motions = PKinematicsAnimated(V)->LL_Motions(k); + accel_map::iterator _I, _E; + _I = ll_motions->begin(); + _E = ll_motions->end(); + for (; _I != _E; ++_I) + { + bool bFound = false; + for (ChooseItemVecIt it = items.begin(); it != items.end(); it++) + if (it->name == _I->first) + { + bFound = true; + break; + } + if (!bFound) + items.push_back(SChooseItem(*_I->first, "")); + } + } + } + ::Render->model_Delete(V); + } + + void FillSkeletonBones(ChooseItemVec &items, void *param) + { + IRenderVisual *V = ::Render->model_Create((LPCSTR)param); + if (PKinematics(V)) + { + CKinematicsAnimated::accel *ll_bones = PKinematics(V)->LL_Bones(); + CKinematicsAnimated::accel::iterator _I, _E; + _I = ll_bones->begin(); + _E = ll_bones->end(); + for (; _I != _E; ++_I) + items.push_back(SChooseItem(*_I->first, "")); + } + ::Render->model_Delete(V); + } + + void FillSkeletonBonesObject(ChooseItemVec &items, void *param) + { + CEditableObject *eo = (CEditableObject *)param; + + BoneIt _I = eo->FirstBone(); + BoneIt _E = eo->LastBone(); + for (; _I != _E; ++_I) + { + items.push_back(SChooseItem((*_I)->Name().c_str(), "")); + } + } + +} // namespace + +void FillChooseEvents() +{ + { + ref_texture texture_null; + texture_null.create("ed\\ed_nodata"); + texture_null->Load(); + VERIFY(texture_null->surface_get()); + texture_null->surface_get()->AddRef(); + UIChooseForm::SetNullTexture(texture_null->surface_get()); + } + UIChooseForm::AppendEvents(smSoundSource, "Select Sound Source", ChoseEvents::FillSoundSource, ChoseEvents::SelectSoundSource, 0, ChoseEvents::CloseSoundSource, 0); + UIChooseForm::AppendEvents(smSoundEnv, "Select Sound Environment", ChoseEvents::FillSoundEnv, 0, 0, 0, 0); + UIChooseForm::AppendEvents(smObject, "Select Library Object", ChoseEvents::FillObject, ChoseEvents::SelectObject, ChoseEvents::UpdateObjectTHM, 0, 0); + UIChooseForm::AppendEvents(smGroup, "Select Group", ChoseEvents::FillGroup, ChoseEvents::SelectGroup, ChoseEvents::UpdateGroupTHM, 0, 0); + UIChooseForm::AppendEvents(smEShader, "Select Engine Shader", ChoseEvents::FillEShader, 0, 0, 0, 0); + UIChooseForm::AppendEvents(smCShader, "Select Compiler Shader", ChoseEvents::FillCShader, 0, 0, 0, 0); + UIChooseForm::AppendEvents(smPE, "Select Particle Effect", ChoseEvents::FillPE, 0 /*ChoseEvents::SelectPE*/, 0, 0, 0); + UIChooseForm::AppendEvents(smParticles, "Select Particle System", ChoseEvents::FillParticles, 0 /*ChoseEvents::SelectPG*/, 0, 0, 0); + UIChooseForm::AppendEvents(smTextureRaw, "Select Source Texture", ChoseEvents::FillTextureRaw, ChoseEvents::SelectTextureRaw, ChoseEvents::UpdateTextureTHMRaw, 0, SChooseEvents::flClearTexture); + UIChooseForm::AppendEvents(smTexture, "Select Texture", ChoseEvents::FillTexture, ChoseEvents::SelectTexture, ChoseEvents::UpdateTextureTHM, 0, SChooseEvents::flClearTexture); + UIChooseForm::AppendEvents(smEntityType, "Select Entity", ChoseEvents::FillEntity, 0, 0, 0, 0); + UIChooseForm::AppendEvents(smLAnim, "Select Light Animation", ChoseEvents::FillLAnim, 0, ChoseEvents::UpdateLAnim, 0, SChooseEvents::flAnimated); + UIChooseForm::AppendEvents(smVisual, "Select Visual", ChoseEvents::FillVisual, ChoseEvents::SelectVisual, 0, 0, 0); + UIChooseForm::AppendEvents(smSkeletonAnims, "Select Skeleton Animation", ChoseEvents::FillSkeletonAnims, 0, 0, 0, 0); + UIChooseForm::AppendEvents(smSkeletonBones, "Select Skeleton Bones", ChoseEvents::FillSkeletonBones, 0, 0, 0, 0); + UIChooseForm::AppendEvents(smSkeletonBonesInObject, "Select Skeleton Bones", ChoseEvents::FillSkeletonBonesObject, 0, 0, 0, 0); + UIChooseForm::AppendEvents(smGameMaterial, "Select Game Material", ChoseEvents::FillGameMaterial, 0, 0, 0, 0); + UIChooseForm::AppendEvents(smGameAnim, "Select Animation", ChoseEvents::FillGameAnim, 0, 0, 0, 0); + UIChooseForm::AppendEvents(smGameSMotions, "Select Game Object Motions", ChoseEvents::FillGameObjectMots, ChoseEvents::SelectGameObjectMots, 0, 0, 0); + choose_snd = xr_new(); +} +void ClearChooseEvents() +{ + UIChooseForm::ClearEvents(); + xr_delete(choose_snd); +} diff --git a/src/editors/xrECore/Editor/EditorPreferences.cpp b/src/editors/xrECore/Editor/EditorPreferences.cpp new file mode 100644 index 00000000000..b4dc18a096f --- /dev/null +++ b/src/editors/xrECore/Editor/EditorPreferences.cpp @@ -0,0 +1,415 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "ui_main.h" +#include "ui_toolscustom.h" +//--------------------------------------------------------------------------- +CCustomPreferences *EPrefs = 0; +//--------------------------------------------------------------------------- + +CCustomPreferences::CCustomPreferences() +{ + bOpen = false; + // view + view_np = 0.1f; + view_fp = 1500.f; + view_fov = deg2rad(60.f); + // fog + fog_color = 0x00555555; + fog_fogness = 0.9; + // camera + cam_fly_speed = 5.0f; + cam_fly_alt = 1.8f; + cam_sens_rot = 0.6f; + cam_sens_move = 0.6f; + // tools mouse + tools_sens_move = 0.3f; + tools_sens_rot = 0.3f; + tools_sens_scale = 0.3f; + tools_show_move_axis = false; + // box pick + bp_lim_depth = TRUE; + bp_cull = TRUE; + bp_depth_tolerance = 0.1f; + // snap + snap_angle = deg2rad(5.f); + snap_move = 0.1f; + snap_moveto = 0.5f; + // grid + grid_cell_size = 1.f; + grid_cell_count = 100; + // scene + scene_undo_level = 125; + scene_recent_count = 10; + scene_clear_color = DEFAULT_CLEARCOLOR; + // objects + object_flags.zero(); +} +//--------------------------------------------------------------------------- + +CCustomPreferences::~CCustomPreferences() +{ +} + +void CCustomPreferences::ApplyValues() +{ + Tools->m_MoveSnap = snap_move; + Tools->m_MoveSnapTo = snap_moveto; + Tools->m_RotateSnapAngle = snap_angle; + + EDevice.m_Camera.SetViewport(view_np, view_fp, rad2deg(view_fov)); + Tools->SetFog(fog_color, fog_fogness); + + UI->m_MouseSM = 0.2f * tools_sens_move * tools_sens_move; + UI->m_MouseSR = 0.02f * tools_sens_rot * tools_sens_rot; + UI->m_MouseSS = 0.02f * tools_sens_scale * tools_sens_scale; + + EDevice.m_Camera.SetSensitivity(cam_sens_move, cam_sens_rot); + EDevice.m_Camera.SetFlyParams(cam_fly_speed, cam_fly_alt); + + ExecCommand(COMMAND_UPDATE_GRID); +} +//--------------------------------------------------------------------------- + +void CCustomPreferences::OnClose() +{ + ApplyValues(); +} +//--------------------------------------------------------------------------- + +void CheckValidate(ShortcutValue *, const xr_shortcut &new_val, bool &result) +{ + { + xr_shortcut null; + if (null.similar(new_val)) + { + return; + } + } + result = true; + ECommandVec &cmds = GetEditorCommands(); + for (u32 cmd_idx = 0; cmd_idx < cmds.size(); cmd_idx++) + { + SECommand *&CMD = cmds[cmd_idx]; + if (CMD && CMD->editable) + { + VERIFY(!CMD->sub_commands.empty()); + for (u32 sub_cmd_idx = 0; sub_cmd_idx < CMD->sub_commands.size(); sub_cmd_idx++) + { + SESubCommand *&SUB_CMD = CMD->sub_commands[sub_cmd_idx]; + if (SUB_CMD->shortcut.similar(new_val)) + { + result = false; + return; + } + } + } + } +} + +void CCustomPreferences::OnKeyboardCommonFileClick(ButtonValue *B, bool &bModif, bool &) +{ + bModif = false; + xr_string fn; + switch (B->btn_num) + { + case 0: + if (EFS.GetOpenName(EDevice.m_hWnd, "$import$", fn, false, NULL, 6)) + { + CInifile *I = xr_new(fn.c_str(), TRUE, TRUE, TRUE); + LoadShortcuts(I); + xr_delete(I); + // m_ItemProps->RefreshForm(); + } + break; + case 1: + if (EFS.GetSaveName("$import$", fn, NULL, 6)) + { + CInifile *I = xr_new(fn.c_str(), FALSE, TRUE, TRUE); + SaveShortcuts(I); + xr_delete(I); + } + break; + } +} + +void CCustomPreferences::FillProp(PropItemVec &props) +{ + PHelper().CreateFlag32(props, "Objects\\Library\\Discard Instance", &object_flags, epoDiscardInstance); + PHelper().CreateFlag32(props, "Objects\\Skeleton\\Draw Joints", &object_flags, epoDrawJoints); + PHelper().CreateFlag32(props, "Objects\\Skeleton\\Draw Bone Axis", &object_flags, epoDrawBoneAxis); + PHelper().CreateFlag32(props, "Objects\\Skeleton\\Draw Bone Names", &object_flags, epoDrawBoneNames); + PHelper().CreateFlag32(props, "Objects\\Skeleton\\Draw Bone Shapes", &object_flags, epoDrawBoneShapes); + PHelper().CreateFlag32(props, "Objects\\Show\\Hint", &object_flags, epoShowHint); + PHelper().CreateFlag32(props, "Objects\\Show\\Pivot", &object_flags, epoDrawPivot); + PHelper().CreateFlag32(props, "Objects\\Show\\Animation Path", &object_flags, epoDrawAnimPath); + PHelper().CreateFlag32(props, "Objects\\Show\\LOD", &object_flags, epoDrawLOD); + PHelper().CreateFlag32(props, "Objects\\Loading\\Deffered Loading RB", &object_flags, epoDeffLoadRB); + PHelper().CreateFlag32(props, "Objects\\Loading\\Deffered Loading CF", &object_flags, epoDeffLoadCF); + PHelper().CreateFlag32(props, "Objects\\GroupObject\\Select ingroup", &object_flags, epoSelectInGroup); + + PHelper().CreateU32(props, "Scene\\Common\\Recent Count", &scene_recent_count, 0, 25); + PHelper().CreateU32(props, "Scene\\Common\\Undo Level", &scene_undo_level, 0, 125); + PHelper().CreateFloat(props, "Scene\\Grid\\Cell Size", &grid_cell_size, 0.1f, 10.f); + PHelper().CreateU32(props, "Scene\\Grid\\Cell Count", &grid_cell_count, 10, 1000); + PHelper().CreateFloat(props, "Scene\\RadiusRender", &EDevice.RadiusRender, 10.f, 100000.f); + + PHelper().CreateBOOL(props, "Tools\\Box Pick\\Limited Depth", &bp_lim_depth); + PHelper().CreateBOOL(props, "Tools\\Box Pick\\Back Face Culling", &bp_cull); + PHelper().CreateFloat(props, "Tools\\Box Pick\\Depth Tolerance", &bp_depth_tolerance, 0.f, 10000.f); + PHelper().CreateFloat(props, "Tools\\Sens\\Move", &tools_sens_move); + PHelper().CreateBOOL(props, "Tools\\Sens\\ShowMoveAxis", &tools_show_move_axis); + + PHelper().CreateFloat(props, "Tools\\Sens\\Rotate", &tools_sens_rot); + PHelper().CreateFloat(props, "Tools\\Sens\\Scale", &tools_sens_scale); + PHelper().CreateAngle(props, "Tools\\Snap\\Angle", &snap_angle, 0, PI_MUL_2); + PHelper().CreateFloat(props, "Tools\\Snap\\Move", &snap_move, 0.01f, 1000.f); + PHelper().CreateFloat(props, "Tools\\Snap\\Move To", &snap_moveto, 0.01f, 1000.f); + + PHelper().CreateFloat(props, "Viewport\\Camera\\Move Sens", &cam_sens_move); + PHelper().CreateFloat(props, "Viewport\\Camera\\Rotate Sens", &cam_sens_rot); + PHelper().CreateFloat(props, "Viewport\\Camera\\Fly Speed", &cam_fly_speed, 0.01f, 100.f); + PHelper().CreateFloat(props, "Viewport\\Camera\\Fly Altitude", &cam_fly_alt, 0.f, 1000.f); + PHelper().CreateColor(props, "Viewport\\Fog\\Color", &fog_color); + PHelper().CreateFloat(props, "Viewport\\Fog\\Fogness", &fog_fogness, 0.f, 100.f); + PHelper().CreateFloat(props, "Viewport\\Near Plane", &view_np, 0.01f, 10.f); + PHelper().CreateFloat(props, "Viewport\\Far Plane", &view_fp, 10.f, 10000.f); + PHelper().CreateAngle(props, "Viewport\\FOV", &view_fov, deg2rad(0.1f), deg2rad(170.f)); + PHelper().CreateColor(props, "Viewport\\Clear Color", &scene_clear_color); + + ButtonValue *B = PHelper().CreateButton(props, "Keyboard\\Common\\File", "Load,Save", 0); + B->OnBtnClickEvent.bind(this, &CCustomPreferences::OnKeyboardCommonFileClick); + ECommandVec &cmds = GetEditorCommands(); + for (u32 cmd_idx = 0; cmd_idx < cmds.size(); cmd_idx++) + { + SECommand *&CMD = cmds[cmd_idx]; + if (CMD && CMD->editable) + { + VERIFY(!CMD->sub_commands.empty()); + for (u32 sub_cmd_idx = 0; sub_cmd_idx < CMD->sub_commands.size(); sub_cmd_idx++) + { + SESubCommand *&SUB_CMD = CMD->sub_commands[sub_cmd_idx]; + string128 nm; + sprintf(nm, "%s%s%s", CMD->Desc(), !SUB_CMD->desc.empty() ? "\\" : "", SUB_CMD->desc.c_str()); + ShortcutValue *V = PHelper().CreateShortcut(props, PrepareKey("Keyboard\\Shortcuts", nm), &SUB_CMD->shortcut); + V->OnValidateResultEvent.bind(CheckValidate); + } + } + } +} + +void CCustomPreferences::Edit() +{ + if (bOpen) + return; + bOpen = true; + // fill prop + PropItemVec props; + + FillProp(props); + + m_ItemProps->AssignItems(props); + UI->Push(this, false); + // m_ItemProps->ShowPropertiesModal(); + + // save changed options +} +//--------------------------------------------------------------------------- +extern bool bAllowLogCommands; +void CCustomPreferences::Load(CInifile *I) +{ + psDeviceFlags.flags = R_U32_SAFE("editor_prefs", "device_flags", psDeviceFlags.flags); + psSoundFlags.flags = R_U32_SAFE("editor_prefs", "sound_flags", psSoundFlags.flags) + + Tools->m_Settings.flags = R_U32_SAFE("editor_prefs", "tools_settings", Tools->m_Settings.flags); + + view_np = R_FLOAT_SAFE("editor_prefs", "view_np", view_np); + view_fp = R_FLOAT_SAFE("editor_prefs", "view_fp", view_fp); + view_fov = R_FLOAT_SAFE("editor_prefs", "view_fov", view_fov); + + fog_color = R_U32_SAFE("editor_prefs", "fog_color", fog_color); + fog_fogness = R_FLOAT_SAFE("editor_prefs", "fog_fogness", fog_fogness); + + cam_fly_speed = R_FLOAT_SAFE("editor_prefs", "cam_fly_speed", cam_fly_speed); + cam_fly_alt = R_FLOAT_SAFE("editor_prefs", "cam_fly_alt", cam_fly_alt); + cam_sens_rot = R_FLOAT_SAFE("editor_prefs", "cam_sens_rot", cam_sens_rot); + cam_sens_move = R_FLOAT_SAFE("editor_prefs", "cam_sens_move", cam_sens_move); + + tools_sens_move = R_FLOAT_SAFE("editor_prefs", "tools_sens_move", tools_sens_move); + tools_sens_rot = R_FLOAT_SAFE("editor_prefs", "tools_sens_rot", tools_sens_rot); + tools_sens_scale = R_FLOAT_SAFE("editor_prefs", "tools_sens_scale", tools_sens_scale); + tools_show_move_axis = R_BOOL_SAFE("editor_prefs", "tools_show_move_axis", tools_show_move_axis); + + bp_lim_depth = R_BOOL_SAFE("editor_prefs", "bp_lim_depth", bp_lim_depth); + bp_cull = R_BOOL_SAFE("editor_prefs", "bp_lim_depth", bp_cull); + bp_depth_tolerance = R_FLOAT_SAFE("editor_prefs", "tools_sens_rot", bp_depth_tolerance); + + snap_angle = R_FLOAT_SAFE("editor_prefs", "snap_angle", snap_angle); + snap_move = R_FLOAT_SAFE("editor_prefs", "snap_move", snap_move); + snap_moveto = R_FLOAT_SAFE("editor_prefs", "snap_moveto", snap_moveto); + + grid_cell_size = R_FLOAT_SAFE("editor_prefs", "grid_cell_size", grid_cell_size); + grid_cell_count = R_U32_SAFE("editor_prefs", "grid_cell_count", grid_cell_count); + + scene_undo_level = R_U32_SAFE("editor_prefs", "scene_undo_level", scene_undo_level); + scene_recent_count = R_U32_SAFE("editor_prefs", "scene_recent_count", scene_recent_count); + scene_clear_color = R_U32_SAFE("editor_prefs", "scene_clear_color", scene_clear_color); + + object_flags.flags = R_U32_SAFE("editor_prefs", "object_flags", object_flags.flags); + EDevice.RadiusRender = R_FLOAT_SAFE("render", "render_radius", EDevice.RadiusRender); + + start_w = R_U32_SAFE("render", "w", 1280); + start_h = R_U32_SAFE("render", "h", 800); + start_maximized = R_BOOL_SAFE("render", "maximized", false); + + bAllowLogCommands = R_BOOL_SAFE("windows", "log", false); + // read recent list + for (u32 i = 0; i < scene_recent_count; i++) + { + shared_str fn = R_STRING_SAFE("editor_prefs", make_string("recent_files_%d", i).c_str(), shared_str("")); + if (fn.size()) + { + AStringIt it = std::find(scene_recent_list.begin(), scene_recent_list.end(), fn.c_str()); + if (it == scene_recent_list.end()) + scene_recent_list.push_back(*fn); + } + } + sWeather = R_STRING_SAFE("editor_prefs", "weather", shared_str("")); + // load shortcuts + + LoadShortcuts(I); + + UI->LoadSettings(I); +} + +void CCustomPreferences::Save(CInifile *I) +{ + I->w_u32("editor_prefs", "device_flags", psDeviceFlags.flags); + I->w_u32("editor_prefs", "sound_flags", psSoundFlags.flags); + + I->w_u32("editor_prefs", "tools_settings", Tools->m_Settings.flags); + + I->w_float("editor_prefs", "view_np", view_np); + I->w_float("editor_prefs", "view_fp", view_fp); + I->w_float("editor_prefs", "view_fov", view_fov); + + I->w_u32("editor_prefs", "fog_color", fog_color); + I->w_float("editor_prefs", "fog_fogness", fog_fogness); + + I->w_float("editor_prefs", "cam_fly_speed", cam_fly_speed); + I->w_float("editor_prefs", "cam_fly_alt", cam_fly_alt); + I->w_float("editor_prefs", "cam_sens_rot", cam_sens_rot); + I->w_float("editor_prefs", "cam_sens_move", cam_sens_move); + + I->w_float("editor_prefs", "tools_sens_rot", tools_sens_rot); + I->w_float("editor_prefs", "tools_sens_move", tools_sens_move); + I->w_float("editor_prefs", "tools_sens_scale", tools_sens_scale); + I->w_bool("editor_prefs", "tools_show_move_axis", tools_show_move_axis); + + I->w_bool("editor_prefs", "bp_lim_depth", bp_lim_depth); + I->w_bool("editor_prefs", "bp_lim_depth", bp_cull); + I->w_float("editor_prefs", "bp_depth_tolerance", bp_depth_tolerance); + + I->w_float("editor_prefs", "snap_angle", snap_angle); + I->w_float("editor_prefs", "snap_move", snap_move); + I->w_float("editor_prefs", "snap_moveto", snap_moveto); + + I->w_float("editor_prefs", "grid_cell_size", grid_cell_size); + I->w_u32("editor_prefs", "grid_cell_count", grid_cell_count); + + I->w_u32("editor_prefs", "scene_undo_level", scene_undo_level); + I->w_u32("editor_prefs", "scene_recent_count", scene_recent_count); + I->w_u32("editor_prefs", "scene_clear_color", scene_clear_color); + + I->w_u32("editor_prefs", "object_flags", object_flags.flags); + for (AStringIt it = scene_recent_list.begin(); it != scene_recent_list.end(); it++) + { + auto L = make_string("recent_files_%d", it - scene_recent_list.begin()); + auto V = make_string("\"%s\"", it->c_str()); + I->w_string("editor_prefs", L.c_str(), V.c_str()); + } + I->w_string("editor_prefs", "weather", sWeather.c_str()); + I->w_bool("render", "maximized", EDevice.dwMaximized); + I->w_u32("render", "w", EDevice.dwWidth); + I->w_u32("render", "h", EDevice.dwHeight); + I->w_bool("windows", "log", bAllowLogCommands); + I->w_float("render", "render_radius", EDevice.RadiusRender); + + // load shortcuts + SaveShortcuts(I); + UI->SaveSettings(I); +} + +void CCustomPreferences::Draw() +{ + if (!bOpen) + return; + ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(300, 400)); + if (!ImGui::Begin("Editor Preferences", &bOpen)) + { + OnClose(); + Save(); + ImGui::PopStyleVar(); + ImGui::End(); + return; + } + ImGui::PopStyleVar(); + { + m_ItemProps->Draw(); + } + ImGui::End(); +} + +void CCustomPreferences::Load() +{ + string_path fn; + INI_NAME(fn); + CInifile *I = xr_new(fn, TRUE, TRUE, TRUE); + Load(I); + xr_delete(I); + ApplyValues(); +} +void CCustomPreferences::Save() +{ + string_path fn; + INI_NAME(fn); + CInifile *I = xr_new(fn, FALSE, TRUE, TRUE); + I->set_override_names(TRUE); + Save(I); + xr_delete(I); +} + +void CCustomPreferences::AppendRecentFile(LPCSTR name) +{ + for (AStringIt it = scene_recent_list.begin(); it != scene_recent_list.end(); it++) + { + if (*it == name) + { + scene_recent_list.erase(it); + break; + } + } + scene_recent_list.insert(scene_recent_list.begin(), name); + while (scene_recent_list.size() >= EPrefs->scene_recent_count) + scene_recent_list.pop_back(); + + ExecCommand(COMMAND_REFRESH_UI_BAR); +} +//--------------------------------------------------------------------------- + +void CCustomPreferences::OnCreate() +{ + Load(); + m_ItemProps = xr_new(); + // m_ItemProps = TProperties::CreateModalForm("Editor Preferences",false,0,0,TOnCloseEvent(this,&CCustomPreferences::OnClose),TProperties::plItemFolders|TProperties::plFullSort); //TProperties::plFullExpand TProperties::plFullSort TProperties::plNoClearStore|TProperties::plFolderStore| +} +//--------------------------------------------------------------------------- + +void CCustomPreferences::OnDestroy() +{ + + xr_delete(m_ItemProps); + Save(); +} +//--------------------------------------------------------------------------- diff --git a/src/editors/xrECore/Editor/EditorPreferences.h b/src/editors/xrECore/Editor/EditorPreferences.h new file mode 100644 index 00000000000..3d482232434 --- /dev/null +++ b/src/editors/xrECore/Editor/EditorPreferences.h @@ -0,0 +1,106 @@ +//--------------------------------------------------------------------------- + +#ifndef EditorPreferencesH +#define EditorPreferencesH +//--------------------------------------------------------------------------- +// refs +class UIPropertiesForm; + +//--------------------------------------------------------------------------- +enum +{ + epoDrawPivot = (1 << 0), + epoDrawAnimPath = (1 << 1), + epoDrawJoints = (1 << 2), + epoDrawBoneAxis = (1 << 3), + epoDrawBoneNames = (1 << 4), + epoDrawBoneShapes = (1 << 5), + epoShowHint = (1 << 6), + epoDrawLOD = (1 << 7), + epoDiscardInstance = (1 << 8), + epoDeffLoadRB = (1 << 9), + epoDeffLoadCF = (1 << 10), + epoSelectInGroup = (1 << 11), +}; +class ECORE_API CCustomPreferences : protected xrUI +{ +private: // User declarations + UIPropertiesForm *m_ItemProps; + +public: + u32 start_w; + u32 start_h; + u32 start_maximized; + // view + float view_np; + float view_fp; + float view_fov; + // fog + u32 fog_color; + float fog_fogness; + // camera + float cam_fly_speed; + float cam_fly_alt; + float cam_sens_rot; + float cam_sens_move; + // tools mouse + float tools_sens_rot; + float tools_sens_move; + float tools_sens_scale; + BOOL tools_show_move_axis; + // box pick + BOOL bp_lim_depth; + BOOL bp_cull; + float bp_depth_tolerance; + // snap + float snap_angle; + float snap_move; + float snap_moveto; + // grid + float grid_cell_size; + u32 grid_cell_count; + // scene + u32 scene_undo_level; + u32 scene_recent_count; + u32 scene_clear_color; + AStringVec scene_recent_list; + // objects + Flags32 object_flags; + shared_str sWeather; + +protected: + void OnKeyboardCommonFileClick(ButtonValue *value, bool &bModif, bool &bSafe); + void OnClose(); + void ApplyValues(); + + virtual void Load(CInifile *); + virtual void Save(CInifile *); + virtual void Draw(); + +public: // User declarations + CCustomPreferences(); + virtual ~CCustomPreferences(); + + void OnCreate(); + void OnDestroy(); + + virtual void FillProp(PropItemVec &items); + + void Edit(); + + void Load(); + void Save(); + + void AppendRecentFile(LPCSTR name); + LPCSTR FirstRecentFile() { return scene_recent_list.empty() ? "" : scene_recent_list.front().c_str(); } +}; +//--------------------------------------------------------------------------- +#define R_FLOAT_SAFE(S, L, D) I->line_exist(S, L) ? I->r_float(S, L) : D; +#define R_U32_SAFE(S, L, D) I->line_exist(S, L) ? I->r_u32(S, L) : D; +#define R_BOOL_SAFE(S, L, D) I->line_exist(S, L) ? I->r_bool(S, L) : D; +#define R_STRING_SAFE(S, L, D) I->line_exist(S, L) ? I->r_string_wb(S, L) : D; +//--------------------------------------------------------------------------- +extern ECORE_API CCustomPreferences *EPrefs; +//--------------------------------------------------------------------------- + +#endif diff --git a/src/editors/xrECore/Editor/Engine.cpp b/src/editors/xrECore/Editor/Engine.cpp new file mode 100644 index 00000000000..aea6844dd99 --- /dev/null +++ b/src/editors/xrECore/Editor/Engine.cpp @@ -0,0 +1,85 @@ +// Engine.cpp: implementation of the CEngine class. +// +////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#pragma hdrstop + +#include "Engine.h" +#include "ui_main.h" + +//xrDispatchTable PSGP; +CEngine Engine; + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +CEngine::CEngine() +{ + pSettings = 0; +} + +CEngine::~CEngine() +{ +} + +LPCSTR CEngine::LastWindowsError() +{ + static string1024 errmsg_buf; + LPCSTR err = 0; + + u32 hr = GetLastError(); + if (hr != 0) + { + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, hr, 0, errmsg_buf, 1024, 0); + err = errmsg_buf; + } + return err; +} + +//extern void xrSkin1W_x86(vertRender *D, vertBoned1W *S, u32 vCount, CBoneInstance *Bones); +//extern void xrSkin2W_x86(vertRender *D, vertBoned2W *S, u32 vCount, CBoneInstance *Bones); + +void CEngine::Initialize(void) +{ + // Other stuff + string_path fn; + strconcat(sizeof(fn), fn, UI->EditorName(), ".log"); + FS.update_path(fn, _local_root_, fn); + +#ifdef _EDITOR + // Bind PSGP + //ZeroMemory(&PSGP, sizeof(PSGP)); + //hPSGP = LoadLibrary("xrCPU_Pipe.dll"); + //R_ASSERT2(hPSGP, "Can't find 'xrCPU_Pipe.dll'"); + + //xrBinder *bindCPU = (xrBinder *)GetProcAddress(hPSGP, "xrBind_PSGP"); + //R_ASSERT(bindCPU); + //bindCPU(&PSGP, CPU::ID.feature /*& CPU::ID.os_support*/); + //// for compliance with editor + //PSGP.skin1W = xrSkin1W_x86; + //PSGP.skin2W = xrSkin2W_x86; +#endif + + ReloadSettings(); +} + +void CEngine::ReloadSettings() +{ + xr_delete(const_cast(pSettings)); + // game configure + string_path si_name; + FS.update_path(si_name, "$game_config$", "system.ltx"); + pSettings = xr_new(si_name, TRUE); // FALSE,TRUE,TRUE); +} + +void CEngine::Destroy() +{ + xr_delete(const_cast(pSettings)); + if (hPSGP) + { + FreeLibrary(hPSGP); + hPSGP = 0; + } +} diff --git a/src/editors/xrECore/Editor/ExportObjectOGF.cpp b/src/editors/xrECore/Editor/ExportObjectOGF.cpp new file mode 100644 index 00000000000..5520b5368a9 --- /dev/null +++ b/src/editors/xrECore/Editor/ExportObjectOGF.cpp @@ -0,0 +1,692 @@ +#include "stdafx.h" +#include "ExportObjectOGF.h" +#include "EditObject.h" +#include "EditMesh.h" +#include "xrCore/FMesh.hpp" +#include "xrCore/Animation/Motion.hpp" + +CObjectOGFCollectorPacked::CObjectOGFCollectorPacked(const Fbox &bb, int apx_vertices, int apx_faces) +{ + // Params + m_VMscale.set(bb.vMax.x - bb.vMin.x + EPS, bb.vMax.y - bb.vMin.y + EPS, bb.vMax.z - bb.vMin.z + EPS); + m_VMmin.set(bb.vMin).sub(EPS); + m_VMeps.set(m_VMscale.x / clpOGFMX / 2, m_VMscale.y / clpOGFMY / 2, m_VMscale.z / clpOGFMZ / 2); + m_VMeps.x = (m_VMeps.x < EPS_L) ? m_VMeps.x : EPS_L; + m_VMeps.y = (m_VMeps.y < EPS_L) ? m_VMeps.y : EPS_L; + m_VMeps.z = (m_VMeps.z < EPS_L) ? m_VMeps.z : EPS_L; + + // Preallocate memory + m_Verts.reserve(apx_vertices); + m_Faces.reserve(apx_faces); + + int _size = (clpOGFMX + 1) * (clpOGFMY + 1) * (clpOGFMZ + 1); + int _average = (apx_vertices / _size) / 2; + for (int ix = 0; ix < clpOGFMX + 1; ++ix) + for (int iy = 0; iy < clpOGFMY + 1; ++iy) + for (int iz = 0; iz < clpOGFMZ + 1; ++iz) + m_VM[ix][iy][iz].reserve(_average); +} + +u16 CObjectOGFCollectorPacked::VPack(SOGFVert &V) +{ + u32 P = 0xffffffff; + + u32 ix, iy, iz; + ix = iFloor(float(V.P.x - m_VMmin.x) / m_VMscale.x * clpOGFMX); + iy = iFloor(float(V.P.y - m_VMmin.y) / m_VMscale.y * clpOGFMY); + iz = iFloor(float(V.P.z - m_VMmin.z) / m_VMscale.z * clpOGFMZ); + R_ASSERT(ix <= clpOGFMX && iy <= clpOGFMY && iz <= clpOGFMZ); + + int similar_pos = -1; + { + U32Vec &vl = m_VM[ix][iy][iz]; + for (U32It it = vl.begin(); it != vl.end(); it++) + { + SOGFVert &src = m_Verts[*it]; + if (src.similar_pos(V)) + { + if (src.similar(V)) + { + P = *it; + break; + } + similar_pos = *it; + } + } + } + if (0xffffffff == P) + { + if (similar_pos >= 0) + V.P.set(m_Verts[similar_pos].P); + P = m_Verts.size(); + if (P >= 0xFFFF) + return 0xffff; + m_Verts.push_back(V); + + m_VM[ix][iy][iz].push_back(P); + + u32 ixE, iyE, izE; + ixE = iFloor(float(V.P.x + m_VMeps.x - m_VMmin.x) / m_VMscale.x * clpOGFMX); + iyE = iFloor(float(V.P.y + m_VMeps.y - m_VMmin.y) / m_VMscale.y * clpOGFMY); + izE = iFloor(float(V.P.z + m_VMeps.z - m_VMmin.z) / m_VMscale.z * clpOGFMZ); + + R_ASSERT(ixE <= clpOGFMX && iyE <= clpOGFMY && izE <= clpOGFMZ); + + if (ixE != ix) + m_VM[ixE][iy][iz].push_back(P); + if (iyE != iy) + m_VM[ix][iyE][iz].push_back(P); + if (izE != iz) + m_VM[ix][iy][izE].push_back(P); + if ((ixE != ix) && (iyE != iy)) + m_VM[ixE][iyE][iz].push_back(P); + if ((ixE != ix) && (izE != iz)) + m_VM[ixE][iy][izE].push_back(P); + if ((iyE != iy) && (izE != iz)) + m_VM[ix][iyE][izE].push_back(P); + if ((ixE != ix) && (iyE != iy) && (izE != iz)) + m_VM[ixE][iyE][izE].push_back(P); + } + VERIFY(P < u16(-1)); + return (u16)P; +} + +void CObjectOGFCollectorPacked::ComputeBounding() +{ + m_Box.invalidate(); + for (OGFVertIt v_it = m_Verts.begin(); v_it != m_Verts.end(); ++v_it) + m_Box.modify(v_it->P); +} + +CExportObjectOGF::SSplit::SSplit(CSurface *surf, const Fbox &bb) +{ + apx_box = bb; + m_Surf = surf; + m_CurrentPart = NULL; +} + +CExportObjectOGF::SSplit::~SSplit() +{ + for (COGFCPIt it = m_Parts.begin(); it != m_Parts.end(); ++it) + xr_delete(*it); +} + +void CExportObjectOGF::SSplit::AppendPart(int apx_vertices, int apx_faces) +{ + m_Parts.push_back(xr_new(apx_box, apx_vertices, apx_faces)); + m_CurrentPart = m_Parts.back(); +} + +void CExportObjectOGF::SSplit::SavePart(IWriter &F, CObjectOGFCollectorPacked *part) +{ + // Header + F.open_chunk(OGF_HEADER); + ogf_header H; + H.format_version = xrOGF_FormatVersion; + H.type = (part->m_SWR.size()) ? MT_PROGRESSIVE : MT_NORMAL; + H.shader_id = 0; + H.bb.min = part->m_Box.vMin; + H.bb.max = part->m_Box.vMax; + part->m_Box.getsphere(H.bs.c, H.bs.r); + F.w(&H, sizeof(H)); + F.close_chunk(); + + // Texture + F.open_chunk(OGF_TEXTURE); + F.w_stringZ(m_Surf->_Texture()); + F.w_stringZ(m_Surf->_ShaderName()); + F.close_chunk(); + + // Vertices + u32 dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL | (1 << D3DFVF_TEXCOUNT_SHIFT); + F.open_chunk(OGF_VERTICES); + F.w_u32(dwFVF); + F.w_u32(part->m_Verts.size()); + for (OGFVertIt v_it = part->m_Verts.begin(); v_it != part->m_Verts.end(); ++v_it) + { + SOGFVert const &pV = *v_it; + F.w(&(pV.P), sizeof(float) * 3); // position (offset) + F.w(&(pV.N), sizeof(float) * 3); // normal + F.w_float(pV.UV.x); + F.w_float(pV.UV.y); // tu,tv + } + F.close_chunk(); + + // Faces + F.open_chunk(OGF_INDICES); + F.w_u32(part->m_Faces.size() * 3); + F.w(&part->m_Faces.front(), part->m_Faces.size() * 3 * sizeof(u16)); + F.close_chunk(); + + // PMap + if (part->m_SWR.size()) + { + F.open_chunk(OGF_SWIDATA); + F.w_u32(0); // reserved space 16 bytes + F.w_u32(0); + F.w_u32(0); + F.w_u32(0); + F.w_u32(part->m_SWR.size()); // num collapses + for (u32 swr_idx = 0; swr_idx < part->m_SWR.size(); ++swr_idx) + F.w(&part->m_SWR[swr_idx], sizeof(VIPM_SWR)); + + F.close_chunk(); + } +} + +void CExportObjectOGF::SSplit::Save(IWriter &F, int &chunk_id) +{ + for (COGFCPIt it = m_Parts.begin(); it != m_Parts.end(); ++it) + { + CObjectOGFCollectorPacked *part = *it; + F.open_chunk(chunk_id); + SavePart(F, part); + F.close_chunk(); + ++chunk_id; + } +} + +void CObjectOGFCollectorPacked::MakeProgressive() +{ + VIPM_Init(); + + for (OGFVertIt vert_it = m_Verts.begin(); vert_it != m_Verts.end(); ++vert_it) + VIPM_AppendVertex(vert_it->P, vert_it->UV); + + for (OGFFaceIt f_it = m_Faces.begin(); f_it != m_Faces.end(); ++f_it) + VIPM_AppendFace(f_it->v[0], f_it->v[1], f_it->v[2]); + + VIPM_Result *R = VIPM_Convert(u32(-1), 1.f, 1); + + if (R) + { + // Permute vertices + OGFVertVec const temp_list = m_Verts; + for (u32 i = 0; i < temp_list.size(); ++i) + m_Verts[R->permute_verts[i]] = temp_list[i]; + + // Fill indices + m_Faces.resize(R->indices.size() / 3); + for (u32 f_idx = 0; f_idx < m_Faces.size(); ++f_idx) + { + SOGFFace &F = m_Faces[f_idx]; + F.v[0] = R->indices[f_idx * 3 + 0]; + F.v[1] = R->indices[f_idx * 3 + 1]; + F.v[2] = R->indices[f_idx * 3 + 2]; + } + + // Fill SWR + m_SWR.resize(R->swr_records.size()); + for (u32 swr_idx = 0; swr_idx != m_SWR.size(); ++swr_idx) + m_SWR[swr_idx] = R->swr_records[swr_idx]; + } + else + { + Log("!..Can't make progressive."); + } + + // cleanup + VIPM_Destroy(); +} + +void CObjectOGFCollectorPacked::OptimizeTextureCoordinates() +{ + // Optimize texture coordinates + // 1. Calc bounds + Fvector2 Tdelta; + Fvector2 Tmin, Tmax; + Tmin.set(flt_max, flt_max); + Tmax.set(flt_min, flt_min); + const u32 v_cnt = m_Verts.size(); + { + for (u32 v_idx = 0; v_idx != v_cnt; v_idx++) + { + SOGFVert const &iV = m_Verts[v_idx]; + Tmin.min(iV.UV); + Tmax.max(iV.UV); + } + } + Tdelta.x = floorf((Tmax.x - Tmin.x) / 2 + Tmin.x); + Tdelta.y = floorf((Tmax.y - Tmin.y) / 2 + Tmin.y); + + Fvector2 Tsize; + Tsize.sub(Tmax, Tmin); + { + // 2. Recalc UV mapping + for (u32 v_idx = 0; v_idx != v_cnt; ++v_idx) + { + SOGFVert &iV = m_Verts[v_idx]; + iV.UV.sub(Tdelta); + } + } +} + +void CExportObjectOGF::SSplit::MakeProgressive() +{ + for (COGFCPIt it = m_Parts.begin(); it != m_Parts.end(); ++it) + (*it)->MakeProgressive(); +} + +CExportObjectOGF::CExportObjectOGF(CEditableObject *object) +{ + m_Source = object; +} + +CExportObjectOGF::~CExportObjectOGF() +{ + for (SplitIt it = m_Splits.begin(); it != m_Splits.end(); ++it) + xr_delete(*it); +} + +CExportObjectOGF::SSplit *CExportObjectOGF::FindSplit(CSurface *surf) +{ + for (SplitIt it = m_Splits.begin(); it != m_Splits.end(); ++it) + if ((*it)->m_Surf == surf) + return *it; + + return 0; +} + +bool CExportObjectOGF::PrepareMESH(CEditableMesh *MESH) +{ + // // generate normals + bool bResult = true; + MESH->GenerateVNormals(0); + // fill faces + for (SurfFacesPairIt sp_it = MESH->m_SurfFaces.begin(); sp_it != MESH->m_SurfFaces.end(); ++sp_it) + { + IntVec &face_lst = sp_it->second; + CSurface *surf = sp_it->first; + u32 dwTexCnt = ((surf->_FVF() & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT); + R_ASSERT(dwTexCnt == 1); + SSplit *split = FindSplit(surf); + if (0 == split) + { +#ifdef _EDITOR + SGameMtl *M = GMLib.GetMaterialByID(surf->_GameMtl()); + if (0 == M) + { + ELog.DlgMsg(mtError, "Surface: '%s' contains undefined game material.", surf->_Name()); + bResult = false; + break; + } +#endif + m_Splits.push_back(xr_new(surf, m_Source->GetBox())); + split = m_Splits.back(); + } + int elapsed_faces = surf->m_Flags.is(CSurface::sf2Sided) ? face_lst.size() * 2 : face_lst.size(); + const bool b2sided = !!surf->m_Flags.is(CSurface::sf2Sided); + + if (0 == split->m_CurrentPart) + split->AppendPart((elapsed_faces > 0xffff) ? 0xffff : elapsed_faces, + (elapsed_faces > 0xffff) ? 0xffff : elapsed_faces); + + do + { + for (IntIt f_it = face_lst.begin(); f_it != face_lst.end(); ++f_it) + { + bool bNewPart = false; + st_Face &face = MESH->m_Faces[*f_it]; + { + SOGFVert v[3]; + for (int k = 0; k < 3; ++k) + { + st_FaceVert &fv = face.pv[k]; + int offs = 0; + const Fvector2 *uv = 0; + for (u32 t = 0; t < dwTexCnt; ++t) + { + st_VMapPt &vm_pt = MESH->m_VMRefs[fv.vmref].pts[t + offs]; + st_VMap &vmap = *MESH->m_VMaps[vm_pt.vmap_index]; + if (vmap.type != vmtUV) + { + ++offs; + --t; + continue; + } + uv = &vmap.getUV(vm_pt.index); + } + R_ASSERT2(uv, "uv empty"); + u32 norm_id = (*f_it) * 3 + k; + R_ASSERT2(norm_id < MESH->GetFCount() * 3, "Normal index out of range."); + v[k].set(MESH->m_Vertices[fv.pindex], MESH->m_VertexNormals[norm_id], *uv); + } + --elapsed_faces; + if (!split->m_CurrentPart->add_face(v[0], v[1], v[2])) + bNewPart = true; + + if (b2sided) + { + v[0].N.invert(); + v[1].N.invert(); + v[2].N.invert(); + if (!split->m_CurrentPart->add_face(v[2], v[1], v[0])) + bNewPart = true; + } + } + if (bNewPart && (elapsed_faces > 0)) + split->AppendPart((elapsed_faces > 0xffff) ? 0xffff : elapsed_faces, + (elapsed_faces > 0xffff) ? 0xffff : elapsed_faces); + } + } while (elapsed_faces > 0); + } + // mesh fin + MESH->UnloadVNormals(); + return bResult; +} + +bool CExportObjectOGF::Prepare(bool gen_tb, CEditableMesh *mesh) +{ + if ((m_Source->MeshCount() == 0)) + return false; + + bool bResult = true; + if (mesh) + bResult = PrepareMESH(mesh); + else + { + for (EditMeshIt mesh_it = m_Source->FirstMesh(); mesh_it != m_Source->LastMesh(); ++mesh_it) + if (!PrepareMESH(*mesh_it)) + { + bResult = false; + break; + } + } + + if (!bResult) + return false; + + // calculate TB + if (gen_tb) + { + for (SplitIt split_it = m_Splits.begin(); split_it != m_Splits.end(); ++split_it) + (*split_it)->CalculateTB(); + // Log ("Time B: ",T.GetElapsed_sec()); + } + + // fill per bone vertices + if (m_Source->m_objectFlags.is(CEditableObject::eoProgressive)) + { + for (SplitIt split_it = m_Splits.begin(); split_it != m_Splits.end(); ++split_it) + (*split_it)->MakeProgressive(); + } + + // Compute bounding... + ComputeBounding(); + // Log ("Time C: ",T.GetElapsed_sec()); + return bResult; +} + +bool CExportObjectOGF::Export(IWriter &F, bool gen_tb, CEditableMesh *mesh) +{ + if (!Prepare(gen_tb, mesh)) + return false; + + // Saving geometry... + if ((m_Splits.size() == 1) && (m_Splits[0]->m_Parts.size() == 1)) + { + // export as single mesh + m_Splits[0]->SavePart(F, m_Splits[0]->m_Parts[0]); + } + else + { + // export as hierrarhy mesh + // Header + ogf_header H; + H.format_version = xrOGF_FormatVersion; + H.type = MT_HIERRARHY; + H.shader_id = 0; + H.bb.min = m_Box.vMin; + H.bb.max = m_Box.vMax; + m_Box.getsphere(H.bs.c, H.bs.r); + F.w_chunk(OGF_HEADER, &H, sizeof(H)); + + // Desc + ogf_desc desc; + m_Source->PrepareOGFDesc(desc); + F.open_chunk(OGF_S_DESC); + desc.Save(F); + F.close_chunk(); + + // OGF_CHILDREN + F.open_chunk(OGF_CHILDREN); + int chunk = 0; + for (SplitIt split_it = m_Splits.begin(); split_it != m_Splits.end(); ++split_it) + (*split_it)->Save(F, chunk); + + F.close_chunk(); + } + SplitIt split_it; + F.open_chunk(OGF_COLLISION_VERTICES); + for (split_it = m_Splits.begin(); split_it != m_Splits.end(); ++split_it) + { + SSplit *split = *split_it; + COGFCPIt it = split->m_Parts.begin(); + for (; it != split->m_Parts.end(); ++it) + { + CObjectOGFCollectorPacked *part = *it; + // vertices + OGFVertVec &VERTS = part->getV_Verts(); + OGFVertIt v_it = VERTS.begin(); + for (; v_it != VERTS.end(); ++v_it) + { + SOGFVert &V = *v_it; + F.w(&V.P, sizeof(V.P)); + } + } // parts + } // splits + F.close_chunk(); + + F.open_chunk(OGF_COLLISION_INDICES); + u32 v_offs = 0; + for (split_it = m_Splits.begin(); split_it != m_Splits.end(); ++split_it) + { + SSplit *split = *split_it; + COGFCPIt it = split->m_Parts.begin(); + + for (; it != split->m_Parts.end(); ++it) + { + CObjectOGFCollectorPacked *part = *it; + OGFFaceVec &FACES = part->getV_Faces(); + OGFFaceIt f_it = FACES.begin(); + for (; f_it != FACES.end(); ++f_it) + { + SOGFFace &Face = *f_it; + F.w_u32(v_offs + Face.v[0]); + F.w_u32(v_offs + Face.v[1]); + F.w_u32(v_offs + Face.v[2]); + } + v_offs += part->getV_Verts().size(); + } // parts + } // splits + F.close_chunk(); + + return true; +} + +bool CExportObjectOGF::ExportAsSimple(IWriter &F) +{ + if (Prepare(true, NULL)) + { + // Saving geometry... + if ((m_Splits.size() == 1) && (m_Splits[0]->m_Parts.size() == 1)) + { + // export as single mesh + m_Splits[0]->SavePart(F, m_Splits[0]->m_Parts[0]); + return true; + } + } + return false; +} + +bool CExportObjectOGF::ExportAsWavefrontOBJ(IWriter &F, LPCSTR fn) +{ + if (!Prepare(false, NULL)) + return false; + + string_path tmp, tex_path, tex_name; + string_path name, ext; + _splitpath(fn, 0, 0, name, ext); + strcat(name, ext); + + xr_string fn_material = EFS.ChangeFileExt(fn, ".mtl"); + IWriter *Fm = FS.w_open(fn_material.c_str()); + + // write material file + for (SplitIt split_it = m_Splits.begin(); split_it != m_Splits.end(); ++split_it) + { + _splitpath((*split_it)->m_Surf->_Texture(), 0, tex_path, tex_name, 0); + + sprintf(tmp, "newmtl %s", tex_name); + Fm->w_string(tmp); + Fm->w_string("Ka 0 0 0"); + Fm->w_string("Kd 1 1 1"); + Fm->w_string("Ks 0 0 0"); + + sprintf(tmp, "map_Kd %s\\\\%s\\%s%s\n", + "T:", + tex_path, + tex_name, + ".tga"); + Fm->w_string(tmp); + } + + FS.w_close(Fm); + + // writ comment + F.w_string("# This file uses meters as units for non-parametric coordinates."); + + _splitpath(fn, 0, 0, tex_name, 0); + sprintf(tmp, "mtllib %s.mtl", tex_name); + F.w_string(tmp); + + u32 v_offs = 0; + for (auto split_it = m_Splits.begin(); split_it != m_Splits.end(); ++split_it) + { + _splitpath((*split_it)->m_Surf->_Texture(), 0, 0, tex_name, 0); + sprintf(tmp, "g %u", static_cast(split_it - m_Splits.begin())); + F.w_string(tmp); + sprintf(tmp, "usemtl %s", tex_name); + F.w_string(tmp); + Fvector mV; + Fmatrix mZ; + mZ.mirrorZ(); + for (COGFCPIt it = (*split_it)->m_Parts.begin(); it != (*split_it)->m_Parts.end(); ++it) + { + CObjectOGFCollectorPacked *part = *it; + // vertices + OGFVertVec &VERTS = part->getV_Verts(); + OGFVertIt v_it; + for (v_it = VERTS.begin(); v_it != VERTS.end(); v_it++) + { + mZ.transform_tiny(mV, v_it->P); + sprintf(tmp, "v %f %f %f", mV.x, mV.y, mV.z); + F.w_string(tmp); + } + for (v_it = VERTS.begin(); v_it != VERTS.end(); ++v_it) + { + sprintf(tmp, "vt %f %f", v_it->UV.x, _abs(1.f - v_it->UV.y)); + F.w_string(tmp); + } + for (v_it = VERTS.begin(); v_it != VERTS.end(); ++v_it) + { + mZ.transform_dir(mV, v_it->N); + sprintf(tmp, "vn %f %f %f", mV.x, mV.y, mV.z); + F.w_string(tmp); + } + + for (v_it = VERTS.begin(); v_it != VERTS.end(); ++v_it) + { + mZ.transform_dir(mV, v_it->T); + sprintf(tmp, "vg %f %f %f", mV.x, mV.y, mV.z); + F.w_string(tmp); + } + + for (v_it = VERTS.begin(); v_it != VERTS.end(); ++v_it) + { + mZ.transform_dir(mV, v_it->B); + sprintf(tmp, "vb %f %f %f", mV.x, mV.y, mV.z); + F.w_string(tmp); + } + + // faces + OGFFaceVec &FACES = part->getV_Faces(); + OGFFaceIt f_it; + for (f_it = FACES.begin(); f_it != FACES.end(); ++f_it) + { + sprintf(tmp, "f %d/%d/%d %d/%d/%d %d/%d/%d", v_offs + f_it->v[2] + 1, v_offs + f_it->v[2] + 1, v_offs + f_it->v[2] + 1, + v_offs + f_it->v[1] + 1, v_offs + f_it->v[1] + 1, v_offs + f_it->v[1] + 1, + v_offs + f_it->v[0] + 1, v_offs + f_it->v[0] + 1, v_offs + f_it->v[0] + 1); + F.w_string(tmp); + } + v_offs += VERTS.size(); + } + } + return true; +} + +bool CEditableObject::PrepareOGF(IWriter &F, u8 infl, bool gen_tb, CEditableMesh *mesh) +{ + return IsSkeleton() ? PrepareSkeletonOGF(F, infl) : PrepareRigidOGF(F, gen_tb, mesh); +} + +#include "ExportSkeleton.h" + +bool CEditableObject::PrepareSkeletonOGF(IWriter &F, u8 infl) +{ + CExportSkeleton E(this); + float prev = g_EpsSkelPositionDelta; + if (m_objectFlags.test(eoHQExport)) + g_EpsSkelPositionDelta = EPS; + + bool res = E.Export(F, infl); + g_EpsSkelPositionDelta = prev; + + return res; +} + +bool CEditableObject::PrepareRigidOGF(IWriter &F, bool gen_tb, CEditableMesh *mesh) +{ + CExportObjectOGF E(this); + float prev = g_EpsSkelPositionDelta; + if (m_objectFlags.test(eoHQExport)) + g_EpsSkelPositionDelta = EPS; + + g_EpsSkelPositionDelta = prev; + + bool res = E.Export(F, gen_tb, mesh); + return res; +} + +bool CEditableObject::PrepareSVGeometry(IWriter &F, u8 infl) +{ + CExportSkeleton E(this); + + float prev = g_EpsSkelPositionDelta; + if (m_objectFlags.test(eoHQExport)) + g_EpsSkelPositionDelta = EPS; + + bool res = E.ExportGeometry(F, infl); + + g_EpsSkelPositionDelta = prev; + + return res; +} + +bool CEditableObject::PrepareSVKeys(IWriter &F) +{ + CExportSkeleton E(this); + return E.ExportMotionKeys(F); +} + +bool CEditableObject::PrepareSVDefs(IWriter &F) +{ + CExportSkeleton E(this); + return E.ExportMotionDefs(F); +} + +bool CEditableObject::PrepareOMF(IWriter &F) +{ + CExportSkeleton E(this); + return E.ExportMotions(F); +} diff --git a/src/editors/xrECore/Editor/ExportObjectOGF.h b/src/editors/xrECore/Editor/ExportObjectOGF.h new file mode 100644 index 00000000000..dabf61c97bd --- /dev/null +++ b/src/editors/xrECore/Editor/ExportObjectOGF.h @@ -0,0 +1,196 @@ +//--------------------------------------------------------------------------- + +#ifndef ExportObjectOGFH +#define ExportObjectOGFH + +#include "PropSlimTools.h" +//--------------------------------------------------------------------------- +const int clpOGFMX = 48, clpOGFMY = 16, clpOGFMZ = 48; +//--------------------------------------------------------------------------- +// refs +class CEditableObject; +class CEditableMesh; +class CSurface; +class CInifile; + +struct SOGFVert +{ + Fvector P; + Fvector N; + Fvector2 UV; + Fvector T; + Fvector B; + SOGFVert() + { + P.set(0, 0, 0); + N.set(0, 1, 0); + UV.set(0.f, 0.f); + T.set(0, 0, 0); + B.set(0, 0, 0); + } + void set(Fvector const &p, Fvector const &n, Fvector2 const &uv) + { + P.set(p); + N.set(n); + UV.set(uv); + } + BOOL similar_pos(SOGFVert &V) + { + return P.similar(V.P, EPS_L); + } + BOOL similar(SOGFVert &V) + { + if (!P.similar(V.P, EPS_L)) + return FALSE; + if (!UV.similar(V.UV, EPS_S)) + return FALSE; + if (!N.similar(V.N, EPS_L)) + return FALSE; + return TRUE; + } +}; + +struct SOGFFace +{ + WORD v[3]; +}; + +DEFINE_VECTOR(SOGFVert, OGFVertVec, OGFVertIt); +DEFINE_VECTOR(SOGFFace, OGFFaceVec, OGFFaceIt); + +class CObjectOGFCollectorPacked +{ +public: + // Fobb m_OBB; + Fbox m_Box; + + OGFVertVec m_Verts; + OGFFaceVec m_Faces; + + // Progressive + ArbitraryList m_SWR; // The records of the collapses. + + Fvector m_VMmin, m_VMscale; + U32Vec m_VM[clpOGFMX + 1][clpOGFMY + 1][clpOGFMZ + 1]; + Fvector m_VMeps; + + u16 VPack(SOGFVert &V); + void ComputeBounding(); + void OptimizeTextureCoordinates(); + +public: + CObjectOGFCollectorPacked(const Fbox &bb, int apx_vertices, int apx_faces); + void CalculateTB(); + void MakeProgressive(); + IC bool check(SOGFFace &F) + { + if ((F.v[0] == F.v[1]) || (F.v[0] == F.v[2]) || (F.v[1] == F.v[2])) + return false; + else + return true; + } + IC bool add_face(SOGFVert &v0, SOGFVert &v1, SOGFVert &v2) + { + if (v0.P.similar(v1.P, EPS) || v0.P.similar(v2.P, EPS) || v1.P.similar(v2.P, EPS)) + { + ELog.Msg(mtError, "Degenerate face found. Removed."); + return true; + } + SOGFFace F; + u16 v; + v = VPack(v0); + if (0xffff == v) + return false; + F.v[0] = v; + v = VPack(v1); + if (0xffff == v) + return false; + F.v[1] = v; + v = VPack(v2); + if (0xffff == v) + return false; + F.v[2] = v; + + if (check(F)) + m_Faces.push_back(F); + else + { + ELog.Msg(mtError, "Duplicate(degenerate) face found. Removed."); + return true; + } + return true; + } + IC OGFVertVec &getV_Verts() { return m_Verts; } + IC OGFFaceVec &getV_Faces() { return m_Faces; } + IC SOGFVert *getVert() { return &m_Verts.front(); } + IC u32 getVS() { return m_Verts.size(); } + IC u32 getTS() { return m_Faces.size(); } +}; +//---------------------------------------------------- +DEFINE_VECTOR(CObjectOGFCollectorPacked *, COGFCPVec, COGFCPIt) + +class ECORE_API CExportObjectOGF +{ + struct SSplit + { + Fbox apx_box; + + COGFCPVec m_Parts; + CObjectOGFCollectorPacked *m_CurrentPart; + + Fbox m_Box; + CSurface *m_Surf; + + // Progressive + void AppendPart(int apx_vertices, int apx_faces); + void SavePart(IWriter &F, CObjectOGFCollectorPacked *part); + void Save(IWriter &F, int &chunk_id); + + void CalculateTB() + { + for (COGFCPIt it = m_Parts.begin(); it != m_Parts.end(); it++) + (*it)->CalculateTB(); + } + + void MakeProgressive(); + SSplit(CSurface *surf, const Fbox &bb); + ~SSplit(); + void ComputeBounding() + { + m_Box.invalidate(); + for (COGFCPIt it = m_Parts.begin(); it != m_Parts.end(); it++) + { + CObjectOGFCollectorPacked *part = *it; + part->ComputeBounding(); + m_Box.merge(part->m_Box); + } + } + }; + DEFINE_VECTOR(SSplit *, SplitVec, SplitIt); + SplitVec m_Splits; + CEditableObject *m_Source; + Fbox m_Box; + //---------------------------------------------------- + // void ComputeOBB (Fobb &B, FvectorVec& V); + SSplit *FindSplit(CSurface *surf); + void ComputeBounding() + { + m_Box.invalidate(); + for (SplitIt it = m_Splits.begin(); it != m_Splits.end(); it++) + { + (*it)->ComputeBounding(); + m_Box.merge((*it)->m_Box); + } + } + bool PrepareMESH(CEditableMesh *mesh); + bool Prepare(bool gen_tb, CEditableMesh *mesh); + +public: + CExportObjectOGF(CEditableObject *object); + ~CExportObjectOGF(); + bool Export(IWriter &F, bool gen_tb = true, CEditableMesh *mesh = NULL); + bool ExportAsSimple(IWriter &F); + bool ExportAsWavefrontOBJ(IWriter &F, LPCSTR fn); +}; + +#endif diff --git a/src/editors/xrECore/Editor/ExportObjectOGFCalculateTB.cpp b/src/editors/xrECore/Editor/ExportObjectOGFCalculateTB.cpp new file mode 100644 index 00000000000..b263a586be0 --- /dev/null +++ b/src/editors/xrECore/Editor/ExportObjectOGFCalculateTB.cpp @@ -0,0 +1,194 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "ExportObjectOGF.h" + +//-------------------------------------------------------------------------------- + +//-------------------------------------------------------------------------------- +/*IC void set_vertex( MeshMender::Vertex &out_vertex, const SOGFVert& in_vertex ) +{ + cv_vector( out_vertex.pos, in_vertex.P ); + cv_vector( out_vertex.normal, in_vertex.N ); + out_vertex.s = in_vertex.UV.x; + out_vertex.t = in_vertex.UV.y; + //out_vertex.tangent; + //out_vertex.binormal; +} + +IC void set_vertex( SOGFVert& out_vertex, const SOGFVert& in_old_vertex, const MeshMender::Vertex &in_vertex ) +{ + out_vertex = in_old_vertex; + + cv_vector( out_vertex.P, in_vertex.pos );//? + cv_vector( out_vertex.N, in_vertex.normal );//? + + out_vertex.UV.x = in_vertex.s; + out_vertex.UV.y = in_vertex.t; + Fvector tangent; Fvector binormal; + out_vertex.T.set( cv_vector( tangent, in_vertex.tangent ) ); + out_vertex.B.set( cv_vector( binormal, in_vertex.binormal ) ); +} + + +IC WORD &face_vertex( SOGFFace &F, u32 vertex_index ) +{ + VERIFY( vertex_index < 3 ); + return F.v[vertex_index]; +} + +IC const WORD &face_vertex( const SOGFFace &F, u32 vertex_index ) +{ + VERIFY( vertex_index < 3 ); + return F.v[vertex_index]; +} +*/ +//-------------------------------------------------------------------------------------------- +void CObjectOGFCollectorPacked::CalculateTB() +{ + /* + u32 v_count_reserve = 3*iFloor(float(m_Verts.size())*1.33f); + u32 i_count_reserve = 3*m_Faces.size(); + + // Declare inputs + xr_vector input; + input.push_back (NVMeshMender::VertexAttribute()); // pos + input.push_back (NVMeshMender::VertexAttribute()); // norm + input.push_back (NVMeshMender::VertexAttribute()); // tex0 + input.push_back (NVMeshMender::VertexAttribute()); // *** faces + + input[0].Name_= "position"; xr_vector& i_position = input[0].floatVector_; i_position.reserve (v_count_reserve); + input[1].Name_= "normal"; xr_vector& i_normal = input[1].floatVector_; i_normal.reserve (v_count_reserve); + input[2].Name_= "tex0"; xr_vector& i_tc = input[2].floatVector_; i_tc.reserve (v_count_reserve); + input[3].Name_= "indices"; xr_vector& i_indices = input[3].intVector_; i_indices.reserve (i_count_reserve); + + // Declare outputs + xr_vector output; + output.push_back(NVMeshMender::VertexAttribute()); // position, needed for mender + output.push_back(NVMeshMender::VertexAttribute()); // normal + output.push_back(NVMeshMender::VertexAttribute()); // tangent + output.push_back(NVMeshMender::VertexAttribute()); // binormal + output.push_back(NVMeshMender::VertexAttribute()); // tex0 + output.push_back(NVMeshMender::VertexAttribute()); // *** faces + + output[0].Name_= "position"; + output[1].Name_= "normal"; + output[2].Name_= "tangent"; + output[3].Name_= "binormal"; + output[4].Name_= "tex0"; + output[5].Name_= "indices"; + + // fill inputs (verts&indices) + for (OGFVertIt vert_it=m_Verts.begin(); vert_it!=m_Verts.end(); vert_it++){ + SOGFVert &iV = *vert_it; + i_position.push_back(iV.P.x); i_position.push_back(iV.P.y); i_position.push_back(iV.P.z); + i_normal.push_back (iV.N.x); i_normal.push_back (iV.N.y); i_normal.push_back (iV.N.z); + i_tc.push_back (iV.UV.x); i_tc.push_back (iV.UV.y); i_tc.push_back (0); + } + for (OGFFaceIt face_it=m_Faces.begin(); face_it!=m_Faces.end(); face_it++){ + SOGFFace &iF = *face_it; + i_indices.push_back (iF.v[0]); + i_indices.push_back (iF.v[1]); + i_indices.push_back (iF.v[2]); + } + + // Perform munge + NVMeshMender mender; + if (!mender.Munge( + input, // input attributes + output, // outputs attributes + deg2rad(75.f), // tangent space smooth angle + 0, // no texture matrix applied to my texture coordinates + NVMeshMender::FixTangents, // fix degenerate bases & texture mirroring + NVMeshMender::DontFixCylindricalTexGen, // handle cylindrically mapped textures via vertex duplication + NVMeshMender::DontWeightNormalsByFaceSize // weigh vertex normals by the triangle's size + )) + { + Debug.fatal (DEBUG_INFO,"NVMeshMender failed (%s)",mender.GetLastError().c_str()); + } + + // Bind declarators + // bind + output[0].Name_= "position"; + output[1].Name_= "normal"; + output[2].Name_= "tangent"; + output[3].Name_= "binormal"; + output[4].Name_= "tex0"; + output[5].Name_= "indices"; + + xr_vector& o_position = output[0].floatVector_; R_ASSERT(output[0].Name_=="position"); + xr_vector& o_normal = output[1].floatVector_; R_ASSERT(output[1].Name_=="normal"); + xr_vector& o_tangent = output[2].floatVector_; R_ASSERT(output[2].Name_=="tangent"); + xr_vector& o_binormal = output[3].floatVector_; R_ASSERT(output[3].Name_=="binormal"); + xr_vector& o_tc = output[4].floatVector_; R_ASSERT(output[4].Name_=="tex0"); + xr_vector& o_indices = output[5].intVector_; R_ASSERT(output[5].Name_=="indices"); + + // verify + R_ASSERT (3*m_Faces.size() == o_indices.size()); + u32 v_cnt = o_position.size(); + R_ASSERT (0==v_cnt%3); + R_ASSERT (v_cnt == o_normal.size()); + R_ASSERT (v_cnt == o_tangent.size()); + R_ASSERT (v_cnt == o_binormal.size()); + R_ASSERT (v_cnt == o_tc.size()); + v_cnt /= 3; + + // retriving data + u32 o_idx = 0; + for (face_it=m_Faces.begin(); face_it!=m_Faces.end(); face_it++){ + SOGFFace &iF = *face_it; + iF.v[0] = (u16)o_indices[o_idx++]; + iF.v[1] = (u16)o_indices[o_idx++]; + iF.v[2] = (u16)o_indices[o_idx++]; + } + m_Verts.clear (); m_Verts.resize(v_cnt); + for (u32 v_idx=0; v_idx!=v_cnt; v_idx++){ + SOGFVert &iV = m_Verts[v_idx]; + iV.P.set (o_position[v_idx*3+0], o_position[v_idx*3+1], o_position[v_idx*3+2]); + iV.N.set (o_normal[v_idx*3+0], o_normal[v_idx*3+1], o_normal[v_idx*3+2]); + iV.T.set (o_tangent[v_idx*3+0], o_tangent[v_idx*3+1], o_tangent[v_idx*3+2]); + iV.B.set (o_binormal[v_idx*3+0], o_binormal[v_idx*3+1], o_binormal[v_idx*3+2]); + iV.UV.set (o_tc[v_idx*3+0], o_tc[v_idx*3+1]); + } + + + + xr_vector mender_in_out_verts; + xr_vector< unsigned int > mender_in_out_indices; + xr_vector< unsigned int > mender_mapping_out_to_in_vert; + + fill_mender_input( m_Verts, m_Faces, mender_in_out_verts, mender_in_out_indices ); + + MeshMender mender ; + if + ( + !mender.Mend + ( + mender_in_out_verts, + mender_in_out_indices, + mender_mapping_out_to_in_vert, + 1, + 0.5, + 0.5, + 0.0f, + MeshMender::DONT_CALCULATE_NORMALS, + MeshMender::RESPECT_SPLITS, + MeshMender::DONT_FIX_CYLINDRICAL + ) + ) + { + Debug.fatal ( DEBUG_INFO, "NVMeshMender failed " ); + //Debug.fatal (DEBUG_INFO,"NVMeshMender failed (%s)",mender.GetLastError().c_str()); + } + + retrive_data_from_mender_otput( m_Verts, m_Faces, mender_in_out_verts, mender_in_out_indices, mender_mapping_out_to_in_vert ); + t_remove_isolated_verts( m_Verts, m_Faces ); + + mender_in_out_verts .clear( ); + mender_in_out_indices .clear( ); + mender_mapping_out_to_in_vert .clear( ); + + OptimizeTextureCoordinates(); + + */ +} diff --git a/src/editors/xrECore/Editor/ExportSkeleton.cpp b/src/editors/xrECore/Editor/ExportSkeleton.cpp new file mode 100644 index 00000000000..876b21e7bdf --- /dev/null +++ b/src/editors/xrECore/Editor/ExportSkeleton.cpp @@ -0,0 +1,1414 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "ExportSkeleton.h" +#include "ExportObjectOGF.h" +#include "EditObject.h" +#include "EditMesh.h" + +#include "xrCore/FMesh.hpp" +#include "xrCore/Animation/Bone.hpp" +#include "xrCore/Animation/Motion.hpp" +#include "xrCore/Animation/SkeletonMotions.hpp" + +#define MAX_BONE 64 + +#ifdef _EDITOR +#include "ui_main.h" +#endif + +ECORE_API BOOL g_force16BitTransformQuant = FALSE; +ECORE_API float g_EpsSkelPositionDelta = EPS_L; + +u16 CSkeletonCollectorPacked::VPack(SSkelVert &V) +{ + u32 P = 0xffffffff; + + u32 ix, iy, iz; + ix = iFloor(float(V.offs.x - m_VMmin.x) / m_VMscale.x * clpSMX); + iy = iFloor(float(V.offs.y - m_VMmin.y) / m_VMscale.y * clpSMY); + iz = iFloor(float(V.offs.z - m_VMmin.z) / m_VMscale.z * clpSMZ); + R_ASSERT(ix <= clpSMX && iy <= clpSMY && iz <= clpSMZ); + + int similar_pos = -1; + { + U32Vec &vl = m_VM[ix][iy][iz]; + for (U32It it = vl.begin(); it != vl.end(); it++) + { + SSkelVert &src = m_Verts[*it]; + if (src.similar_pos(V)) + { + if (src.similar(V)) + { + P = *it; + break; + } + similar_pos = *it; + } + } + } + if (0xffffffff == P) + { + if (similar_pos >= 0) + V.offs.set(m_Verts[similar_pos].offs); + P = m_Verts.size(); + m_Verts.push_back(V); + + m_VM[ix][iy][iz].push_back(P); + + u32 ixE, iyE, izE; + ixE = iFloor(float(V.offs.x + m_VMeps.x - m_VMmin.x) / m_VMscale.x * clpSMX); + iyE = iFloor(float(V.offs.y + m_VMeps.y - m_VMmin.y) / m_VMscale.y * clpSMY); + izE = iFloor(float(V.offs.z + m_VMeps.z - m_VMmin.z) / m_VMscale.z * clpSMZ); + + R_ASSERT(ixE <= clpSMX && iyE <= clpSMY && izE <= clpSMZ); + + if (ixE != ix) + m_VM[ixE][iy][iz].push_back(P); + if (iyE != iy) + m_VM[ix][iyE][iz].push_back(P); + if (izE != iz) + m_VM[ix][iy][izE].push_back(P); + if ((ixE != ix) && (iyE != iy)) + m_VM[ixE][iyE][iz].push_back(P); + if ((ixE != ix) && (izE != iz)) + m_VM[ixE][iy][izE].push_back(P); + if ((iyE != iy) && (izE != iz)) + m_VM[ix][iyE][izE].push_back(P); + if ((ixE != ix) && (iyE != iy) && (izE != iz)) + m_VM[ixE][iyE][izE].push_back(P); + } + VERIFY(P < u16(-1)); + return (u16)P; +} + +CSkeletonCollectorPacked::CSkeletonCollectorPacked(const Fbox &_bb, int apx_vertices, int apx_faces) +{ + Fbox bb; + bb.set(_bb); + bb.grow(EPS_L); + // Params + m_VMscale.set(bb.vMax.x - bb.vMin.x + EPS, bb.vMax.y - bb.vMin.y + EPS, bb.vMax.z - bb.vMin.z + EPS); + m_VMmin.set(bb.vMin).sub(EPS); + m_VMeps.set(m_VMscale.x / clpSMX / 2, m_VMscale.y / clpSMY / 2, m_VMscale.z / clpSMZ / 2); + m_VMeps.x = (m_VMeps.x < EPS_L) ? m_VMeps.x : EPS_L; + m_VMeps.y = (m_VMeps.y < EPS_L) ? m_VMeps.y : EPS_L; + m_VMeps.z = (m_VMeps.z < EPS_L) ? m_VMeps.z : EPS_L; + + invalid_faces = 0; + + // Preallocate memory + m_Verts.reserve(apx_vertices); + m_Faces.reserve(apx_faces); + + int _size = (clpSMX + 1) * (clpSMY + 1) * (clpSMZ + 1); + int _average = (apx_vertices / _size) / 2; + for (int ix = 0; ix < clpSMX + 1; ix++) + for (int iy = 0; iy < clpSMY + 1; iy++) + for (int iz = 0; iz < clpSMZ + 1; iz++) + m_VM[ix][iy][iz].reserve(_average); +} +//---------------------------------------------------- + +CExportSkeleton::SSplit::SSplit(CSurface *surf, const Fbox &bb, u16 part) : CSkeletonCollectorPacked(bb) +{ + //. m_b2Link = FALSE; + m_SkeletonLinkType = 1; + m_Shader = surf->m_ShaderName; + m_Texture = surf->m_Texture; + m_PartID = part; +} +//---------------------------------------------------- + +class VertexCache +{ + +public: + VertexCache(int size); + VertexCache(); + ~VertexCache(); + + bool InCache(int entry); + int AddEntry(int entry); + void Clear(); + + void Copy(VertexCache *inVcache); + int At(int index); + void Set(int index, int value); + +private: + xr_vector entries; +}; + +IC bool VertexCache::InCache(int entry) +{ + bool returnVal = false; + + for (u32 i = 0; i < entries.size(); i++) + { + if (entries[i] == entry) + { + returnVal = true; + break; + } + } + + return returnVal; +} + +IC int VertexCache::AddEntry(int entry) +{ + int removed; + + removed = entries[entries.size() - 1]; + + // push everything right one + for (int i = (u32)entries.size() - 2; i >= 0; i--) + { + entries[i + 1] = entries[i]; + } + + entries[0] = entry; + + return removed; +} + +VertexCache::VertexCache() +{ + VertexCache(24); +} + +VertexCache::VertexCache(int size) +{ + entries.assign(size, -1); +} + +VertexCache::~VertexCache() +{ + entries.clear(); +} + +int VertexCache::At(int index) +{ + return entries[index]; +} + +void VertexCache::Set(int index, int value) +{ + entries[index] = value; +} + +void VertexCache::Clear() +{ + for (u32 i = 0; i < entries.size(); i++) + entries[i] = -1; +} + +void VertexCache::Copy(VertexCache *inVcache) +{ + for (u32 i = 0; i < entries.size(); i++) + { + inVcache->Set(i, entries[i]); + } +} + +int xrSimulate(u16 *indices, u32 i_cnt, int iCacheSize) +{ + VertexCache C(iCacheSize); + + int count = 0; + for (u32 i = 0; i < i_cnt; i++) + { + int id = indices[i]; + if (C.InCache(id)) + continue; + count++; + C.AddEntry(id); + } + return count; +} + +void CExportSkeleton::SSplit::Save(IWriter &F) +{ + // Header + F.open_chunk(OGF_HEADER); + ogf_header H; + H.format_version = xrOGF_FormatVersion; + H.type = (m_SWR.size()) ? MT_SKELETON_GEOMDEF_PM : MT_SKELETON_GEOMDEF_ST; + H.shader_id = 0; + H.bb.min = m_Box.vMin; + H.bb.max = m_Box.vMax; + m_Box.getsphere(H.bs.c, H.bs.r); + F.w(&H, sizeof(H)); + F.close_chunk(); + + // Texture + F.open_chunk(OGF_TEXTURE); + F.w_stringZ(m_Texture); + F.w_stringZ(m_Shader); + F.close_chunk(); + + // Vertices + F.open_chunk(OGF_VERTICES); + + if (Core.SocSdk) + { + switch (m_SkeletonLinkType) + { + case 1: + F.w_u32(OGF_VERTEXFORMAT_FVF_1L); + break; + + case 2: + F.w_u32(OGF_VERTEXFORMAT_FVF_2L); + break; + + default: + std::string message = "��� ����� �������: " + std::to_string(m_SkeletonLinkType) + ", ������������ �� �� ������ ��������� ������� ��� ogf."; + MessageBoxA(0, message.c_str(), "��������!", 0); + F.w_u32(m_SkeletonLinkType); + break; + } + } + else + F.w_u32(m_SkeletonLinkType); + + F.w_u32(m_Verts.size()); + + if (m_SkeletonLinkType == 1) + { + for (SkelVertIt v_it = m_Verts.begin(); v_it != m_Verts.end(); ++v_it) + { + SSkelVert &pV = *v_it; + pV.sort_by_weight(); + F.w(&pV.offs, sizeof(Fvector)); // position (offset) + F.w(&pV.norm, sizeof(Fvector)); // normal + F.w(&pV.tang, sizeof(Fvector)); // T + F.w(&pV.binorm, sizeof(Fvector)); // B + F.w(&pV.uv, sizeof(Fvector2)); // tu,tv + F.w_u32(pV.bones[0].id); + } + } + else if (m_SkeletonLinkType == 2) + { + for (SkelVertIt v_it = m_Verts.begin(); v_it != m_Verts.end(); v_it++) + { + SSkelVert &pV = *v_it; + pV.sort_by_weight(); + float _weight_b0 = 0.0f; + + // write vertex + F.w_u16(pV.bones[0].id); + + if (pV.bones.size() == 2) + { + F.w_u16(pV.bones[1].id); + _weight_b0 = pV.bones[1].w / (pV.bones[0].w + pV.bones[1].w); + } + else + { + F.w_u16(pV.bones[0].id); + //. Log ("filling up foo-bone"); + _weight_b0 = 1.0f; + } + + F.w(&pV.offs, sizeof(Fvector)); // position (offset) + F.w(&pV.norm, sizeof(Fvector)); // normal + F.w(&pV.tang, sizeof(Fvector)); // T + F.w(&pV.binorm, sizeof(Fvector)); // B + F.w_float(_weight_b0); + F.w(&pV.uv, sizeof(Fvector2)); // tu,tv + } + } + else if (m_SkeletonLinkType == 3 || m_SkeletonLinkType == 4) + { + + for (SkelVertIt v_it = m_Verts.begin(); v_it != m_Verts.end(); v_it++) + { + SSkelVert &pV = *v_it; + pV.sort_by_weight(); + u32 i = 0; + + u32 _bones = pV.bones.size(); + R_ASSERT(m_SkeletonLinkType >= pV.bones.size()); + for (i = 0; i < m_SkeletonLinkType; ++i) + { + if (i < _bones) + { + F.w_u16(pV.bones[i].id); + } + else + { + F.w_u16(pV.bones[0].id); + // Log ("filling up foo-bone"); + } + } + + // write vertex + F.w(&pV.offs, sizeof(Fvector)); // position (offset) + F.w(&pV.norm, sizeof(Fvector)); // normal + F.w(&pV.tang, sizeof(Fvector)); // T + F.w(&pV.binorm, sizeof(Fvector)); // B + + for (i = 0; i < m_SkeletonLinkType - 1; ++i) + { + if (i < _bones) + { + F.w_float(pV.bones[i].w); + } + else + { + F.w_float(0.0f); + } + } + F.w(&pV.uv, sizeof(Fvector2)); // tu,tv + } + } + + F.close_chunk(); + + // Faces + F.open_chunk(OGF_INDICES); + F.w_u32(m_Faces.size() * 3); + F.w(&m_Faces.front(), m_Faces.size() * 3 * sizeof(WORD)); + F.close_chunk(); + + // PMap + if (m_SWR.size()) + { + F.open_chunk(OGF_SWIDATA); + F.w_u32(0); // reserved space 16 bytes + F.w_u32(0); + F.w_u32(0); + F.w_u32(0); + F.w_u32(m_SWR.size()); // num collapses + for (u32 swr_idx = 0; swr_idx < m_SWR.size(); swr_idx++) + F.w(&m_SWR[swr_idx], sizeof(VIPM_SWR)); + F.close_chunk(); + } + // SMF + /* + if (0){ + static u32 chunk_id = 0; chunk_id++; + xr_string r=xr_string("x:\\import\\test")+chunk_id+".smf"; + IWriter* W = FS._w_open(r.c_str()); + for (SkelVertIt v_it=m_Verts.begin(); v_it!=m_Verts.end(); v_it++){ + SSkelVert& pV = *v_it; + // vertices + xr_string tmp; + tmp.sprintf ("v %f %f %f",pV.O.x,pV.O.y,-pV.O.z); + W->w_string (tmp.c_str()); + } + // face + for (SkelFaceIt f_it=m_Faces.begin(); f_it!=m_Faces.end(); f_it++){ + SSkelFace& pF = *f_it; + xr_string tmp; + tmp.sprintf ("f %d %d %d",pF.v[0]+1,pF.v[2]+1,pF.v[1]+1); + W->w_string (tmp.c_str()); + } + // normals + W->w_string ("bind n vertex"); + for (v_it=m_Verts.begin(); v_it!=m_Verts.end(); v_it++){ + SSkelVert& pV = *v_it; + xr_string tmp; + tmp.sprintf ("n %f %f %f",pV.N.x,pV.N.y,-pV.N.z); + W->w_string (tmp.c_str()); + } + FS.w_close (W); + } + */ +} + +void CExportSkeleton::SSplit::MakeProgressive() +{ + VIPM_Init(); + for (SkelVertIt vert_it = m_Verts.begin(); vert_it != m_Verts.end(); vert_it++) + VIPM_AppendVertex(vert_it->offs, vert_it->uv); + for (SkelFaceIt f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + VIPM_AppendFace(f_it->v[0], f_it->v[1], f_it->v[2]); + + VIPM_Result *R = VIPM_Convert(u32(-1), 1.f, 1); + + if (R) + { + // Permute vertices + SkelVertVec temp_list = m_Verts; + for (u32 i = 0; i < temp_list.size(); i++) + m_Verts[R->permute_verts[i]] = temp_list[i]; + + // Fill indices + m_Faces.resize(R->indices.size() / 3); + for (u32 f_idx = 0; f_idx < m_Faces.size(); f_idx++) + { + SSkelFace &F = m_Faces[f_idx]; + F.v[0] = R->indices[f_idx * 3 + 0]; + F.v[1] = R->indices[f_idx * 3 + 1]; + F.v[2] = R->indices[f_idx * 3 + 2]; + } + + // Fill SWR + m_SWR.resize(R->swr_records.size()); + for (u32 swr_idx = 0; swr_idx != m_SWR.size(); swr_idx++) + m_SWR[swr_idx] = R->swr_records[swr_idx]; + } + else + { + Log("!..Can't make progressive."); + } + + // cleanup + VIPM_Destroy(); +} + +void CExportSkeleton::SSplit::MakeStripify() +{ + // int ccc = xrSimulate ((u16*)&m_Faces.front(),m_Faces.size()*3,24); + // Log("SRC:",ccc); + // alternative stripification - faces + { + DWORD *remap = xr_alloc(m_Faces.size()); + HRESULT rhr = D3DXOptimizeFaces(&m_Faces.front(), m_Faces.size(), m_Verts.size(), FALSE, remap); + R_CHK(rhr); + SkelFaceVec _source = m_Faces; + for (u32 it = 0; it < _source.size(); it++) + m_Faces[it] = _source[remap[it]]; + + xr_free(remap); + + // int ccc = xrSimulate ((u16*)&m_Faces.front(),m_Faces.size()*3,24); + // Log("X:",ccc); + } + // alternative stripification - vertices + { + DWORD *remap = xr_alloc(m_Verts.size()); + HRESULT rhr = D3DXOptimizeVertices(&m_Faces.front(), m_Faces.size(), m_Verts.size(), FALSE, remap); + R_CHK(rhr); + SkelVertVec _source = m_Verts; + + for (u32 vit = 0; vit < _source.size(); vit++) + m_Verts[remap[vit]] = _source[vit]; + + for (u32 fit = 0; fit < (u32)m_Faces.size(); ++fit) + for (u32 j = 0; j < 3; j++) + m_Faces[fit].v[j] = remap[m_Faces[fit].v[j]]; + + xr_free(remap); + + // int ccc = xrSimulate ((u16*)&m_Faces.front(),m_Faces.size()*3,24); + // Log("Y:",ccc); + } +} + +CExportSkeleton::CExportSkeleton(CEditableObject *object) +{ + m_Source = object; +} +//---------------------------------------------------- +#include "../WildMagic/WmlContMinBox3.h" +#include "../WildMagic/WmlContBox3.h" + +extern BOOL RAPIDMinBox(Fobb &B, Fvector *vertices, u32 v_count); +void ComputeOBB_RAPID(Fobb &B, FvectorVec &V, u32 t_cnt) +{ + VERIFY(t_cnt == (V.size() / 3)); + if ((t_cnt < 1) || (V.size() < 3)) + { + B.invalidate(); + return; + } + RAPIDMinBox(B, &V.front(), V.size()); + + // Normalize rotation matrix (???? ???????? ContOrientedBox - ?????? ????? ???????) + B.m_rotate.i.crossproduct(B.m_rotate.j, B.m_rotate.k); + B.m_rotate.j.crossproduct(B.m_rotate.k, B.m_rotate.i); + + VERIFY(_valid(B.m_rotate) && _valid(B.m_translate) && _valid(B.m_halfsize)); +} + +void ComputeOBB_WML(Fobb &B, FvectorVec &V) +{ + if (V.size() < 3) + { + B.invalidate(); + return; + } + float HV = flt_max; + { + Wml::Box3 BOX; + Wml::MinBox3 mb(V.size(), (const Wml::Vector3 *)&V.front(), BOX); + float hv = BOX.Extents()[0] * BOX.Extents()[1] * BOX.Extents()[2]; + if (hv < HV) + { + HV = hv; + B.m_rotate.i.set(BOX.Axis(0)); + B.m_rotate.j.set(BOX.Axis(1)); + B.m_rotate.k.set(BOX.Axis(2)); + + B.m_translate.set(BOX.Center()); + B.m_halfsize.set(BOX.Extents()[0], BOX.Extents()[1], BOX.Extents()[2]); + } + } + + B.m_rotate.i.crossproduct(B.m_rotate.j, B.m_rotate.k); + B.m_rotate.j.crossproduct(B.m_rotate.k, B.m_rotate.i); + + VERIFY(_valid(B.m_rotate) && _valid(B.m_translate) && _valid(B.m_halfsize)); +} +//---------------------------------------------------- + +int CExportSkeletonCustom::FindSplit(shared_str shader, shared_str texture, u16 part_id) +{ + for (SplitIt it = m_Splits.begin(); it != m_Splits.end(); it++) + if (it->m_Shader.equal(shader) && + it->m_Texture.equal(texture) && + (it->m_PartID == part_id)) + + return it - m_Splits.begin(); + return -1; +} + +IC void BuildGroups(CBone *B, U16Vec &tgt, u16 id, u16 &last_id) +{ + if (B->IK_data.ik_flags.is(SJointIKData::flBreakable)) + id = ++last_id; + tgt[B->SelfID] = id; + for (BoneIt bone_it = B->children.begin(); bone_it != B->children.end(); bone_it++) + BuildGroups(*bone_it, tgt, id, last_id); +} +#define TO_STRING(x) #x +bool CExportSkeleton::PrepareGeometry(u8 influence) +{ + if (m_Source->MeshCount() == 0) + return false; + + if (m_Source->BoneCount() < 1) + { + ELog.Msg(mtError, "There are no bones in the object."); + return false; + } + + if (m_Source->BoneCount() > MAX_BONE) + { + ELog.Msg(mtError, "Object cannot handle more than" TO_STRING(MAX_BONE) " bones."); + return false; + } + + // mem active motion + CSMotion *active_motion = m_Source->ResetSAnimation(); + + R_ASSERT(m_Source->IsDynamic() && m_Source->IsSkeleton()); + +#ifdef _EDITOR + SPBItem *pb = UI->ProgressStart(static_cast(5 + m_Source->MeshCount() * 2 + m_Source->SurfaceCount()), "..Prepare skeleton geometry"); + pb->Inc(); +#endif + + bool bBreakable = false; + U16Vec bone_brk_parts(m_Source->BoneCount()); + CBone *root = 0; + for (BoneIt bone_it = m_Source->FirstBone(); bone_it != m_Source->LastBone(); bone_it++) + { + CBone *B = *bone_it; + if (B->IK_data.ik_flags.is(SJointIKData::flBreakable)) + bBreakable = true; + if (B->IsRoot()) + root = B; + } + if (bBreakable) + { + VERIFY(root); + u16 last_id = 0; + BuildGroups(root, bone_brk_parts, 0, last_id); + } + + for (U16It uit = bone_brk_parts.begin(); uit != bone_brk_parts.end(); uit++) + { + Msg("Bone: %s - Part: %d", *m_Source->GetBone(uit - bone_brk_parts.begin())->Name(), *uit); + } + + bool bRes = true; + +#ifdef _EDITOR + UI->SetStatus("..Split meshes"); +#endif + + U16Vec tmp_bone_lst; + + for (EditMeshIt mesh_it = m_Source->FirstMesh(); mesh_it != m_Source->LastMesh(); mesh_it++) + { + if (!bRes) + break; + + CEditableMesh *MESH = *mesh_it; + // generate vertex offset + MESH->GenerateVNormals(0); + MESH->GenerateFNormals(); + MESH->GenerateSVertices(influence); +#ifdef _EDITOR + pb->Inc(); +#endif + // fill faces + for (SurfFacesPairIt sp_it = MESH->m_SurfFaces.begin(); sp_it != MESH->m_SurfFaces.end(); sp_it++) + { + if (!bRes) + break; + IntVec &face_lst = sp_it->second; + CSurface *surf = sp_it->first; + u32 dwTexCnt = ((surf->_FVF() & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT); + R_ASSERT(dwTexCnt == 1); + + for (IntIt f_it = face_lst.begin(); f_it != face_lst.end(); f_it++) + { + if (!bRes) + break; + int f_idx = *f_it; + + { + SSkelVert v[3]; + tmp_bone_lst.clear(); + u32 link_type = _max(MESH->m_SVertices[f_idx * 3 + 0].bones.size(), MESH->m_SVertices[f_idx * 3 + 1].bones.size()); + link_type = _max(link_type, MESH->m_SVertices[f_idx * 3 + 2].bones.size()); + VERIFY(link_type > 0 && link_type <= (u32)influence); + + for (int k = 0; k < 3; k++) + { + st_SVert &sv = MESH->m_SVertices[f_idx * 3 + k]; + VERIFY(sv.bones.size() > 0 && (u8)sv.bones.size() <= influence); + + if (link_type == 1) + { + st_SVert::bone b[2]; + b[0].id = sv.bones[0].id; + b[1].id = sv.bones[0].id; + b[0].w = 1.f; + b[1].w = 0.f; + v[k].set(sv.offs, sv.norm, sv.uv, 2, b); + tmp_bone_lst.push_back(sv.bones[0].id); + } + else if (link_type == 2) + { + { + v[k].set(sv.offs, sv.norm, sv.uv, (u8)sv.bones.size(), sv.bones.begin()); + + for (u32 i = 0; i < sv.bones.size(); ++i) + { + tmp_bone_lst.push_back(sv.bones[i].id); + } + } + } + else if (link_type == 4 || link_type == 3) + { + v[k].set(sv.offs, sv.norm, sv.uv, (u8)sv.bones.size(), sv.bones.begin()); + + for (u32 i = 0; i < sv.bones.size(); ++i) + tmp_bone_lst.push_back(sv.bones[i].id); + } + } + u16 bone_brk_part = 0; + if (bBreakable) + { + std::sort(tmp_bone_lst.begin(), tmp_bone_lst.end()); + U16It ne = std::unique(tmp_bone_lst.begin(), tmp_bone_lst.end()); + tmp_bone_lst.erase(ne, tmp_bone_lst.end()); + U16It tit = tmp_bone_lst.begin(); + bone_brk_part = bone_brk_parts[*tit]; + tit++; + + for (; tit != tmp_bone_lst.end(); tit++) + if (bone_brk_part != bone_brk_parts[*tit]) + { + ELog.Msg(mtError, "Can't export object as breakable. Object have N-Link face(s)."); + bRes = false; + } + } + // find split + int mtl_idx = FindSplit(surf->m_ShaderName, surf->m_Texture, bone_brk_part); + if (mtl_idx < 0) + { + m_Splits.push_back(SSplit(surf, m_Source->GetBox(), bone_brk_part)); + mtl_idx = m_Splits.size() - 1; + m_Splits[mtl_idx].m_SkeletonLinkType = 0; + } + + SSplit &cur_split = m_Splits[mtl_idx]; + cur_split.m_SkeletonLinkType = _max(link_type, cur_split.m_SkeletonLinkType); + + cur_split.m_UsedBones.insert(cur_split.m_UsedBones.end(), tmp_bone_lst.begin(), tmp_bone_lst.end()); + + // append face + cur_split.add_face(v[0], v[1], v[2]); + + if (surf->m_Flags.is(CSurface::sf2Sided)) + { + v[0].norm.invert(); + v[1].norm.invert(); + v[2].norm.invert(); + cur_split.add_face(v[0], v[2], v[1]); + } + } + } + } + // mesh fin + MESH->UnloadSVertices(); + MESH->UnloadVNormals(); + MESH->UnloadFNormals(); +#ifdef _EDITOR + pb->Inc(); +#endif + } +#ifdef _EDITOR + UI->SetStatus("..Calculate TB"); +#endif + Msg("Split statistic:"); + for (int k = 0; k < (int)m_Splits.size(); k++) + { + // check splits + if (bRes) + { + if (!m_Splits[k].valid()) + { + ELog.Msg(mtError, "Empty split found (Shader/Texture: %s/%s). Removed.", *m_Splits[k].m_Shader, *m_Splits[k].m_Texture); + m_Splits.erase(m_Splits.begin() + k); + k--; + } + else + { + SSplit &split = m_Splits[k]; + std::sort(split.m_UsedBones.begin(), split.m_UsedBones.end()); + U16It ne = std::unique(split.m_UsedBones.begin(), split.m_UsedBones.end()); + split.m_UsedBones.erase(ne, split.m_UsedBones.end()); + Msg(" - Split %d: [Bones: %d, Links: %d, Faces: %d, Verts: %d, BrPart: %d, Shader/Texture: '%s'/'%s']", k, split.m_UsedBones.size(), split.m_SkeletonLinkType, split.getTS(), split.getVS(), split.m_PartID, *m_Splits[k].m_Shader, *m_Splits[k].m_Texture); + } + } + } + // calculate TB + for (SplitIt split_it = m_Splits.begin(); split_it != m_Splits.end(); split_it++) + { + split_it->CalculateTB(); + +#ifdef _EDITOR + pb->Inc(); +#endif + } + +#ifdef _EDITOR + pb->Inc(); +#endif + // compute bounding + ComputeBounding(); + +#ifdef _EDITOR + UI->ProgressEnd(pb); +#endif + // restore active motion 6 + m_Source->SetActiveSMotion(active_motion); + + return bRes; +} + +bool CExportSkeleton::ExportAsSimple(IWriter &F) +{ + if (!PrepareGeometry(2)) + return false; + { + // Saving geometry... + if (m_Splits.size() == 1) + { + // export as single mesh + m_Splits[0].Save(F); + return true; + } + else + return false; + } +} + +#define _string_lod + +bool CExportSkeleton::ExportGeometry(IWriter &F, u8 infl) +{ + if (!PrepareGeometry(infl)) + return false; + +#ifdef _EDITOR + SPBItem *pb = UI->ProgressStart(static_cast(3 + m_Splits.size()), "..Export skeleton geometry"); + pb->Inc("Make Progressive..."); +#endif + // fill per bone vertices + BoneVec &bones = m_Source->Bones(); + xr_vector bone_points; + bone_points.resize(m_Source->BoneCount()); + + for (SplitIt split_it = m_Splits.begin(); split_it != m_Splits.end(); ++split_it) + { + if (m_Source->m_objectFlags.is(CEditableObject::eoProgressive)) + split_it->MakeProgressive(); + else + split_it->MakeStripify(); + + SkelVertVec &lst = split_it->getV_Verts(); + for (SkelVertIt sv_it = lst.begin(); sv_it != lst.end(); sv_it++) + { + bone_points[sv_it->bones[0].id].push_back(sv_it->offs); + bones[sv_it->bones[0].id]->RITransform().transform_tiny(bone_points[sv_it->bones[0].id].back()); + } +#ifdef _EDITOR + pb->Inc(); +#endif + } + + // create OGF + // Header + ogf_header H; + H.format_version = xrOGF_FormatVersion; + H.type = m_Source->IsAnimated() ? MT_SKELETON_ANIM : MT_SKELETON_RIGID; + H.shader_id = 0; + H.bb.min = m_Box.vMin; + H.bb.max = m_Box.vMax; + m_Box.getsphere(H.bs.c, H.bs.r); + F.w_chunk(OGF_HEADER, &H, sizeof(H)); + + // Desc + ogf_desc desc; + m_Source->PrepareOGFDesc(desc); + F.open_chunk(OGF_S_DESC); + desc.Save(F); + F.close_chunk(); + + // OGF_CHILDREN + F.open_chunk(OGF_CHILDREN); + int chield = 0; + for (auto split_it = m_Splits.begin(); split_it != m_Splits.end(); split_it++) + { + F.open_chunk(chield++); + split_it->Save(F); + F.close_chunk(); + } + F.close_chunk(); + +#ifdef _EDITOR + pb->Inc("Compute bone bounding volume..."); +#endif + + // BoneNames + F.open_chunk(OGF_S_BONE_NAMES); + F.w_u32(m_Source->BoneCount()); + int bone_idx = 0; + for (BoneIt bone_it = m_Source->FirstBone(); bone_it != m_Source->LastBone(); bone_it++, bone_idx++) + { + F.w_stringZ((*bone_it)->Name()); + F.w_stringZ((*bone_it)->Parent() ? (*bone_it)->ParentName().c_str() : ""); + Fobb obb; + ComputeOBB_WML(obb, bone_points[bone_idx]); + F.w(&obb, sizeof(Fobb)); + } + F.close_chunk(); + + bool bRes = true; + + F.open_chunk(OGF_S_IKDATA); + for (auto bone_it = m_Source->FirstBone(); bone_it != m_Source->LastBone(); ++bone_it, ++bone_idx) + if (!BoneExportOGF(*bone_it, F)) + bRes = false; + + F.close_chunk(); + + if (m_Source->GetClassScript().size()) + { + F.open_chunk(OGF_S_USERDATA); + F.w_stringZ(m_Source->GetClassScript()); + F.close_chunk(); + } + +#ifdef _EDITOR + pb->Inc(); +#endif + if (m_Source->GetLODs() && xr_strlen(m_Source->GetLODs()) > 0 && bRes) + { + F.open_chunk(OGF_S_LODS); +#ifndef _string_lod + CEditableObject *lod_src = Lib.CreateEditObject(m_Source->GetLODs()); + if (0 == lod_src) + { + Log("! Invalid LOD name:", m_Source->GetLODs()); + bRes = false; + } + else + { + CExportSkeleton E(lod_src); +#else + + F.w_string(m_Source->GetLODs()); +#endif + +#ifndef _string_lod + if (!E.ExportAsSimple(F)) + { + Log("! Invalid LOD object:", m_Source->GetLODs()); + bRes = false; + } + + Lib.RemoveEditObject(lod_src); + } +#endif + F.close_chunk(); + } + +#ifdef _EDITOR + UI->ProgressEnd(pb); +#endif + return bRes; +} +//---------------------------------------------------- +struct bm_item +{ + CKeyQR *_keysQR; + CKeyQT8 *_keysQT8; + CKeyQT16 *_keysQT16; + Fvector *_keysT; + void create(u32 len) + { + _keysQR = xr_alloc(len); + _keysQT8 = xr_alloc(len); + _keysQT16 = xr_alloc(len); + _keysT = xr_alloc(len); + } + void destroy() + { + xr_free(_keysQR); + xr_free(_keysQT8); + xr_free(_keysQT16); + xr_free(_keysT); + } +}; + +bool CExportSkeleton::ExportMotionKeys(IWriter &F) +{ + if (!!m_Source->m_SMotionRefs.size() || (m_Source->SMotionCount() < 1)) + { + Msg("!..Object doesn't have own motion"); + return !!m_Source->m_SMotionRefs.size(); + } + +#ifdef _EDITOR + SPBItem *pb = UI->ProgressStart(static_cast(1 + m_Source->SMotionCount()), "..Export skeleton motions keys"); + pb->Inc(); +#endif + // mem active motion + CSMotion *active_motion = m_Source->ResetSAnimation(); + + // Motions + F.open_chunk(OGF_S_MOTIONS); + F.open_chunk(0); + F.w_u32(m_Source->SMotionCount()); + F.close_chunk(); + int smot = 1; + + // use global transform + Fmatrix mGT, mTranslate, mRotate; + mRotate.setHPB(m_Source->a_vRotate.y, m_Source->a_vRotate.x, m_Source->a_vRotate.z); + mTranslate.translate(m_Source->a_vPosition); + mGT.mul(mTranslate, mRotate); + + for (SMotionIt motion_it = m_Source->FirstSMotion(); motion_it != m_Source->LastSMotion(); motion_it++, smot++) + { + CSMotion *cur_motion = *motion_it; + + if (cur_motion->m_Flags.test(esmRootMover) && !m_Source->AnimateRootObject(cur_motion)) + { + Msg("! %s has moveXform flag - but skeleton root has more than one child or has mesh! add special root bone please!", cur_motion->Name()); + return false; + } + // if (motion->m_Flags.is(esmStopAtEnd)) Msg("%s - %d",motion->Name(),motion->m_Flags.is(esmStopAtEnd)); + + F.open_chunk(smot); + F.w_stringZ(cur_motion->Name()); + F.w_u32(cur_motion->Length()); + + u32 dwLen = cur_motion->Length(); + BoneVec &b_lst = m_Source->Bones(); + + bm_item *items = xr_alloc(b_lst.size()); + for (u32 itm_idx = 0; itm_idx < b_lst.size(); itm_idx++) + items[itm_idx].create(dwLen); + Fmatrix ro_anchor = Fidentity; + for (int frame = cur_motion->FrameStart(); frame <= cur_motion->FrameEnd(); ++frame) + { + + float t = (float)frame / cur_motion->FPS(); + int bone_id = 0; + + for (BoneIt b_it = b_lst.begin(); b_it != b_lst.end(); ++b_it, ++bone_id) + { + Fvector T, R; + if (cur_motion->BoneMotions().size() > bone_id) + cur_motion->_Evaluate(bone_id, t, T, R); + else + { + T = (*b_it)->Offset(); + R = (*b_it)->Rotate(); + } + (*b_it)->Update(T, R); + + if (bone_id == 0 && frame == (cur_motion->FrameEnd())) + { + Msg("motion [%s] end frame %f,%f,%f", cur_motion->Name(), T.x, T.y, T.z); + } + } + + m_Source->CalculateAnimation(cur_motion); + if (cur_motion->m_Flags.test(esmRootMover)) + { + if (frame == cur_motion->FrameStart()) + m_Source->GetAnchorForRootObjectAnimation(ro_anchor); + + m_Source->CalculateRootObjectAnimation(ro_anchor); + } + bone_id = 0; + for (auto b_it = b_lst.begin(); b_it != b_lst.end(); b_it++, bone_id++) + { + CBone *B = *b_it; + Fmatrix mat = B->MTransform(); + if (B->IsRoot()) + mat.mulA_43(mGT); + Fquaternion q; + q.set(mat); + CKeyQR &Kr = items[bone_id]._keysQR[frame - cur_motion->FrameStart()]; + Fvector &Kt = items[bone_id]._keysT[frame - cur_motion->FrameStart()]; + // Quantize quaternion + int _x = int(q.x * KEY_Quant); + clamp(_x, -32767, 32767); + Kr.x = (s16)_x; + int _y = int(q.y * KEY_Quant); + clamp(_y, -32767, 32767); + Kr.y = (s16)_y; + int _z = int(q.z * KEY_Quant); + clamp(_z, -32767, 32767); + Kr.z = (s16)_z; + int _w = int(q.w * KEY_Quant); + clamp(_w, -32767, 32767); + Kr.w = (s16)_w; + Kt.set(mat.c); // B->_Offset()); + } + } + // free temp storage + for (int itm_idx = 0; itm_idx < b_lst.size(); ++itm_idx) + { + bm_item &BM = items[itm_idx]; + // check T + R_ASSERT(dwLen); + Fvector Mt = {0, 0, 0}; + Fvector Ct = {0, 0, 0}; + Fvector St = {0, 0, 0}; + BOOL t_present = FALSE; + BOOL r_present = FALSE; + Fvector At = BM._keysT[0]; + Fvector Bt = BM._keysT[0]; + for (u32 t_idx = 0; t_idx < dwLen; ++t_idx) + { + Fvector &t = BM._keysT[t_idx]; + Mt.add(t); + At.x = _min(At.x, t.x); + At.y = _min(At.y, t.y); + At.z = _min(At.z, t.z); + Bt.x = _max(Bt.x, t.x); + Bt.y = _max(Bt.y, t.y); + Bt.z = _max(Bt.z, t.z); + } + Mt.div(static_cast(dwLen)); + Ct.add(Bt, At); + Ct.mul(0.5f); + St.sub(Bt, At); + St.mul(0.5f); + CKeyQR &R = BM._keysQR[0]; + + bool bTransform16Bit = false; + if (g_force16BitTransformQuant || St.magnitude() > 1.5f) + { + bTransform16Bit = true; + Msg("animation [%s] is 16bit-transform (%f)m", cur_motion->Name(), St.magnitude()); + } + + for (int t_idx = 0; t_idx < dwLen; ++t_idx) + { + Fvector &t = BM._keysT[t_idx]; + CKeyQR &r = BM._keysQR[t_idx]; + if (!Mt.similar(t, EPS_L)) + t_present = TRUE; + if ((R.x != r.x) || (R.y != r.y) || (R.z != r.z) || (R.w != r.w)) + r_present = TRUE; + + if (bTransform16Bit) + { + CKeyQT16 &Kt = BM._keysQT16[t_idx]; + int _x = int(32767.f * (t.x - Ct.x) / St.x); + clamp(_x, -32767, 32767); + Kt.x1 = (s16)_x; + + int _y = int(32767.f * (t.y - Ct.y) / St.y); + clamp(_y, -32767, 32767); + + Kt.y1 = (s16)_y; + + int _z = int(32767.f * (t.z - Ct.z) / St.z); + clamp(_z, -32767, 32767); + Kt.z1 = (s16)_z; + } + else + { + CKeyQT8 &Kt = BM._keysQT8[t_idx]; + int _x = int(127.f * (t.x - Ct.x) / St.x); + clamp(_x, -128, 127); + Kt.x1 = (s16)_x; + + int _y = int(127.f * (t.y - Ct.y) / St.y); + clamp(_y, -128, 127); + + Kt.y1 = (s16)_y; + + int _z = int(127.f * (t.z - Ct.z) / St.z); + clamp(_z, -128, 127); + Kt.z1 = (s16)_z; + } + } + if (bTransform16Bit) + St.div(32767.f); + else + St.div(127.f); + + // save + F.w_u8(u8((t_present ? flTKeyPresent : 0) | (r_present ? 0 : flRKeyAbsent) | (bTransform16Bit ? flTKey16IsBit : 0))); + if (r_present) + { + F.w_u32(crc32(BM._keysQR, dwLen * sizeof(CKeyQR))); + F.w(BM._keysQR, dwLen * sizeof(CKeyQR)); + } + else + { + F.w(&BM._keysQR[0], sizeof(BM._keysQR[0])); + } + if (t_present) + { + if (bTransform16Bit) + { + F.w_u32(crc32(BM._keysQT16, u32(dwLen * sizeof(CKeyQT16)))); + F.w(BM._keysQT16, dwLen * sizeof(CKeyQT16)); + } + else + { + F.w_u32(crc32(BM._keysQT8, u32(dwLen * sizeof(CKeyQT8)))); + F.w(BM._keysQT8, dwLen * sizeof(CKeyQT8)); + } + F.w_fvector3(St); + F.w_fvector3(Ct); + } + else + { + F.w_fvector3(Mt); + } + BM.destroy(); + } + xr_free(items); + + F.close_chunk(); +#ifdef _EDITOR + pb->Inc(); +#endif + } + F.close_chunk(); +#ifdef _EDITOR + UI->ProgressEnd(pb); +#endif + // restore active motion + m_Source->SetActiveSMotion(active_motion); + return true; +} + +bool CExportSkeleton::ExportMotionDefs(IWriter &F) +{ + if (!m_Source->IsAnimated()) + { + ELog.Msg(mtError, "Object doesn't have any motion or motion refs."); + return false; + } + + bool bRes = true; + +#ifdef _EDITOR + SPBItem *pb = UI->ProgressStart(3, "..Export skeleton motions defs"); + pb->Inc(); +#endif + + if (m_Source->m_SMotionRefs.size()) + { + F.open_chunk(OGF_S_MOTION_REFS2); + F.w_u32(m_Source->m_SMotionRefs.size()); + for (u32 i = 0; i < m_Source->m_SMotionRefs.size(); ++i) + F.w_stringZ(m_Source->m_SMotionRefs[i].c_str()); + + F.close_chunk(); +#ifdef _EDITOR + pb->Inc(); +#endif + } + else + { + // save smparams + F.open_chunk(OGF_S_SMPARAMS); + F.w_u16(xrOGF_SMParamsVersion); + // bone parts + BPVec &bp_lst = m_Source->BoneParts(); + if (bp_lst.size()) + { + if (m_Source->VerifyBoneParts()) + { + F.w_u16((u16)bp_lst.size()); + for (BPIt bp_it = bp_lst.begin(); bp_it != bp_lst.end(); ++bp_it) + { + string512 buff; + strcpy(buff, bp_it->alias.c_str()); + strlwr(buff); + F.w_stringZ(buff); + F.w_u16((u16)bp_it->bones.size()); + for (int i = 0; i < int(bp_it->bones.size()); ++i) + { + F.w_stringZ(bp_it->bones[i].c_str()); + int idx = m_Source->FindBoneByNameIdx(bp_it->bones[i].c_str()); + VERIFY(idx >= 0); + F.w_u32(idx); + } + } + } + else + { + ELog.Msg(mtError, "Invalid bone parts (missing or duplicate bones)."); + bRes = false; + } + } + else + { + F.w_u16(1); + F.w_stringZ("default"); + F.w_u16((u16)m_Source->BoneCount()); + for (int i = 0; i < m_Source->BoneCount(); i++) + F.w_u32(i); + } +#ifdef _EDITOR + pb->Inc(); +#endif + // motion defs + SMotionVec &sm_lst = m_Source->SMotions(); + F.w_u16((u16)sm_lst.size()); + for (SMotionIt motion_it = m_Source->FirstSMotion(); motion_it != m_Source->LastSMotion(); ++motion_it) + { + CSMotion *motion = *motion_it; + // verify + if (!motion->m_Flags.is(esmFX)) + { + if (!((motion->m_BoneOrPart == BI_NONE) || (motion->m_BoneOrPart < (int)bp_lst.size()))) + { + ELog.Msg(mtError, "Invalid Bone Part of motion: '%s'.", motion->Name()); + bRes = false; + continue; + } + } + if (bRes) + { + // export + F.w_stringZ(motion->Name()); + F.w_u32(motion->m_Flags.get()); + F.w_u16(motion->m_BoneOrPart); + F.w_u16(u16(motion_it - sm_lst.begin())); + F.w_float(motion->fSpeed); + F.w_float(motion->fPower); + F.w_float(motion->fAccrue); + F.w_float(motion->fFalloff); + +#ifdef _EDITOR + u32 sz = motion->marks.size(); + F.w_u32(sz); + for (u32 i = 0; i < sz; ++i) + { + motion->marks[i].Save(&F); + } +#else + F.w_u32(0); +#endif + } + } +#ifdef _EDITOR + pb->Inc(); +#endif + F.close_chunk(); + } + +#ifdef _EDITOR + UI->ProgressEnd(pb); +#endif + return bRes; +} + +bool CExportSkeleton::ExportMotions(IWriter &F) +{ + if (!ExportMotionKeys(F)) + return false; + if (!ExportMotionDefs(F)) + return false; + return true; +} +//---------------------------------------------------- + +bool CExportSkeleton::Export(IWriter &F, u8 infl) +{ + if (!ExportGeometry(F, infl)) + return false; + if (m_Source->IsAnimated() && !ExportMotions(F)) + return false; + return true; +}; + //---------------------------------------------------- + +#if defined _EDITOR || defined _MAYA_EXPORT + +bool BoneExportOGF(CBone *bone, IWriter &F) +{ + // check valid + if (!bone->shape.Valid()) + { + ELog.Msg(mtError, "Bone '%s' has invalid shape.", *bone->Name()); + return false; + } + +#ifdef _EDITOR + SGameMtl *M = GMLib.GetMaterial(bone->game_mtl.c_str()); + if (!M) + { + ELog.Msg(mtError, "Bone '%s' has invalid game material.", *bone->Name()); + return false; + } + if (!M->Flags.is(SGameMtl::flDynamic)) + { + ELog.Msg(mtError, "Bone '%s' has non-dynamic game material.", *bone->Name()); + return false; + } +#endif + + F.w_u32(OGF_IKDATA_VERSION); + + F.w_stringZ(bone->game_mtl); + F.w(&bone->shape, sizeof(SBoneShape)); + + bone->IK_data.Export(F); + + // Fvector xyz; + // Fmatrix& R = RTransform(); + // R.getXYZi (xyz); + + F.w_fvector3(bone->rest_rotate); + F.w_fvector3(bone->rest_offset); + F.w_float(bone->mass); + F.w_fvector3(bone->center_of_mass); + return true; +} + +#endif diff --git a/src/editors/xrECore/Editor/ExportSkeleton.h b/src/editors/xrECore/Editor/ExportSkeleton.h new file mode 100644 index 00000000000..17e61dbdcd2 --- /dev/null +++ b/src/editors/xrECore/Editor/ExportSkeleton.h @@ -0,0 +1,231 @@ +#ifndef ExportSkeletonH +#define ExportSkeletonH + +#include "PropSlimTools.h" +//#include "../../../xrRender/Private/SkeletonCustom.h" +#include "EditMesh.h" +//--------------------------------------------------------------------------- +const int clpSMX = 28, clpSMY = 16, clpSMZ = 28; +//--------------------------------------------------------------------------- +// refs +class CEditableObject; +class CSurface; +class CInifile; +extern ECORE_API BOOL g_force16BitTransformQuant; +extern ECORE_API float g_EpsSkelPositionDelta; + +struct ECORE_API SSkelVert : public st_SVert +{ + Fvector tang; + Fvector binorm; + SSkelVert() + { + uv.set(0.f, 0.f); + offs.set(0, 0, 0); + norm.set(0, 1, 0); + tang.set(1, 0, 0); + binorm.set(0, 0, 1); + } + void set(const Fvector &_o, const Fvector &_n, const Fvector2 &_uv, u8 _w_cnt, const st_SVert::bone *b) + { + offs.set(_o); + norm.set(_n); + uv.set(_uv); + VERIFY(_w_cnt > 0 && _w_cnt <= 4); + bones.resize(_w_cnt); + + for (u8 k = 0; k < _w_cnt; k++) + { + bones[k] = b[k]; + } + sort_by_bone(); // need to similar + } + BOOL similar_pos(SSkelVert &V) + { + return offs.similar(V.offs, g_EpsSkelPositionDelta); + } + BOOL similar(SSkelVert &V) + { + if (bones.size() != V.bones.size()) + return FALSE; + for (u8 k = 0; k < (u8)bones.size(); k++) + { + if (!bones[k].similar(V.bones[k])) + return FALSE; + } + if (!uv.similar(V.uv, EPS_S)) + return FALSE; + + if (!offs.similar(V.offs, g_EpsSkelPositionDelta)) + return FALSE; + + if (!norm.similar(V.norm, g_EpsSkelPositionDelta)) + return FALSE; + + return TRUE; + } +}; + +struct ECORE_API SSkelFace +{ + WORD v[3]; +}; + +DEFINE_VECTOR(SSkelVert, SkelVertVec, SkelVertIt); +DEFINE_VECTOR(SSkelFace, SkelFaceVec, SkelFaceIt); + +class ECORE_API CSkeletonCollectorPacked +{ +protected: + SkelVertVec m_Verts; + SkelFaceVec m_Faces; + + Fvector m_VMmin, m_VMscale; + U32Vec m_VM[clpSMX + 1][clpSMY + 1][clpSMZ + 1]; + Fvector m_VMeps; + + u16 VPack(SSkelVert &V); + +public: + u32 invalid_faces; + +public: + CSkeletonCollectorPacked(const Fbox &bb, int apx_vertices = 5000, int apx_faces = 5000); + bool check(SSkelFace &F) + { + if ((F.v[0] == F.v[1]) || (F.v[0] == F.v[2]) || (F.v[1] == F.v[2])) + return false; + for (SkelFaceIt f_it = m_Faces.begin(); f_it != m_Faces.end(); f_it++) + { + // Test for 6 variations + if ((f_it->v[0] == F.v[0]) && (f_it->v[1] == F.v[1]) && (f_it->v[2] == F.v[2])) + return false; + if ((f_it->v[0] == F.v[0]) && (f_it->v[2] == F.v[1]) && (f_it->v[1] == F.v[2])) + return false; + if ((f_it->v[2] == F.v[0]) && (f_it->v[0] == F.v[1]) && (f_it->v[1] == F.v[2])) + return false; + if ((f_it->v[2] == F.v[0]) && (f_it->v[1] == F.v[1]) && (f_it->v[0] == F.v[2])) + return false; + if ((f_it->v[1] == F.v[0]) && (f_it->v[0] == F.v[1]) && (f_it->v[2] == F.v[2])) + return false; + if ((f_it->v[1] == F.v[0]) && (f_it->v[2] == F.v[1]) && (f_it->v[0] == F.v[2])) + return false; + } + return true; + } + bool add_face(SSkelVert &v0, SSkelVert &v1, SSkelVert &v2) + { + if (v0.offs.similar(v1.offs, EPS) || v0.offs.similar(v2.offs, EPS) || v1.offs.similar(v2.offs, EPS)) + { + ELog.Msg(mtError, "Degenerate face found. Removed."); + invalid_faces++; + return false; + } + SSkelFace F; + F.v[0] = VPack(v0); + F.v[1] = VPack(v1); + F.v[2] = VPack(v2); + if (check(F)) + { + m_Faces.push_back(F); + return true; + } + else + { + ELog.Msg(mtError, "Duplicate face found. Removed."); + invalid_faces++; + return false; + } + } + SkelVertVec &getV_Verts() { return m_Verts; } + SkelFaceVec &getV_Faces() { return m_Faces; } + SSkelVert *getVert() { return &m_Verts[0]; /*.begin();*/ } + int getVS() { return m_Verts.size(); } + // SSkelFace& getFace(int id) { return VERIFY(id m_SWR; // The records of the collapses. + u32 m_SkeletonLinkType; + + public: + SSplit(CSurface *surf, const Fbox &bb, u16 part); + + bool valid() + { + if (m_Verts.empty()) + return false; + if (m_Faces.empty()) + return false; + return true; + } + void MakeProgressive(); + void MakeStripify(); + void CalculateTB(); + void OptimizeTextureCoordinates(); + + void Save(IWriter &F); + + void ComputeBounding() + { + // calculate BBox + m_Box.invalidate(); + for (SkelVertIt v_it = m_Verts.begin(); v_it != m_Verts.end(); v_it++) + { + SSkelVert &pV = *v_it; + m_Box.modify(pV.offs); + } + } + }; + DEFINE_VECTOR(SSplit, SplitVec, SplitIt); + SplitVec m_Splits; + Fbox m_Box; + //---------------------------------------------------- + int FindSplit(shared_str shader, shared_str texture, u16 part_id); + void ComputeBounding() + { + m_Box.invalidate(); + for (SplitIt it = m_Splits.begin(); it != m_Splits.end(); it++) + { + it->ComputeBounding(); + m_Box.merge(it->m_Box); + } + } + +public: + virtual bool Export(IWriter &F, u8 infl) = 0; +}; + +class ECORE_API CExportSkeleton : public CExportSkeletonCustom +{ + CEditableObject *m_Source; + bool PrepareGeometry(u8 influence); + +public: + CExportSkeleton(CEditableObject *object); + virtual bool Export(IWriter &F, u8 infl); + virtual bool ExportGeometry(IWriter &F, u8 infl); + virtual bool ExportMotions(IWriter &F); + + virtual bool ExportMotionKeys(IWriter &F); + virtual bool ExportMotionDefs(IWriter &F); + bool ExportAsSimple(IWriter &F); +}; + +void ECORE_API ComputeOBB_RAPID(Fobb &B, FvectorVec &V, u32 t_cnt); +void ECORE_API ComputeOBB_WML(Fobb &B, FvectorVec &V); + +#endif diff --git a/src/editors/xrECore/Editor/ExportSkeletonCalculateTB.cpp b/src/editors/xrECore/Editor/ExportSkeletonCalculateTB.cpp new file mode 100644 index 00000000000..9148e60f607 --- /dev/null +++ b/src/editors/xrECore/Editor/ExportSkeletonCalculateTB.cpp @@ -0,0 +1,304 @@ + +//---------------------------------------------------- +// file: ExportSkeleton.cpp +//---------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#ifndef _EDITOR +// +#include "../../xrEngine/defines.h" +// +#include "../../xrCore/xrCore.h" + +#include "../../../xrRender/Private/hwcaps.h" +#include "../../../xrRender/Private/hw.h" +#include "../../../xrEngine/pure.h" +class CGameFont; +#include "..\..\include\xrRender\drawutils.h" +#include "../../../xrRender/Public/xrD3dDefs.h" +#include "../../../xrRender/Public/shader.h" +#include "../../../xrRender/Public/R_Backend.h" + +#include "..\..\xrEngine\fmesh.h" +#include "..\..\xrEngine\_d3d_extensions.h" +#include "..\..\xrEngine\properties.h" + +// + +DEFINE_VECTOR(FVF::L, FLvertexVec, FLvertexIt); +DEFINE_VECTOR(FVF::TL, FTLvertexVec, FTLvertexIt); +DEFINE_VECTOR(FVF::LIT, FLITvertexVec, FLITvertexIt); +DEFINE_VECTOR(shared_str, RStrVec, RStrVecIt); + +#endif + +#include "ExportSkeleton.h" + +/* +void CExportSkeleton::SSplit::CalculateTB() +{ + u32 v_count_reserve = 3*iFloor(float(m_Verts.size())*1.33f); + u32 i_count_reserve = 3*m_Faces.size(); + + // Declare inputs + xr_vector input; + input.push_back (NVMeshMender::VertexAttribute()); // pos + input.push_back (NVMeshMender::VertexAttribute()); // norm + input.push_back (NVMeshMender::VertexAttribute()); // tex0 + input.push_back (NVMeshMender::VertexAttribute()); // c_w0_b0 + input.push_back (NVMeshMender::VertexAttribute()); // w1_w2_w3 + input.push_back (NVMeshMender::VertexAttribute()); // b1_b2_b3 + input.push_back (NVMeshMender::VertexAttribute()); // *** faces + + int i_id=-1; + input[++i_id].Name_= "position"; xr_vector& i_position = input[i_id].floatVector_; i_position.reserve (v_count_reserve); + input[++i_id].Name_= "normal"; xr_vector& i_normal = input[i_id].floatVector_; i_normal.reserve (v_count_reserve); + input[++i_id].Name_= "tex0"; xr_vector& i_tc = input[i_id].floatVector_; i_tc.reserve (v_count_reserve); + input[++i_id].Name_= "c_w0_b0"; xr_vector& i_c_w0_b0 = input[i_id].floatVector_; i_c_w0_b0.reserve (v_count_reserve); + input[++i_id].Name_= "w1_w2_w3"; xr_vector& i_w1_w2_w3 = input[i_id].floatVector_; i_w1_w2_w3.reserve (v_count_reserve); + input[++i_id].Name_= "b1_b2_b3"; xr_vector& i_b1_b2_b3 = input[i_id].floatVector_; i_b1_b2_b3.reserve (v_count_reserve); + input[++i_id].Name_= "indices"; xr_vector& i_indices = input[i_id].intVector_; i_indices.reserve (i_count_reserve); + + // Declare outputs + xr_vector output; + output.push_back(NVMeshMender::VertexAttribute()); // position, needed for mender + output.push_back(NVMeshMender::VertexAttribute()); // normal + output.push_back(NVMeshMender::VertexAttribute()); // tangent + output.push_back(NVMeshMender::VertexAttribute()); // binormal + output.push_back(NVMeshMender::VertexAttribute()); // tex0 + output.push_back(NVMeshMender::VertexAttribute()); // w0_w1_w2 + output.push_back(NVMeshMender::VertexAttribute()); // b0_b1_b2 + output.push_back(NVMeshMender::VertexAttribute()); // w3_b3 + output.push_back(NVMeshMender::VertexAttribute()); // *** faces + + int o_id=-1; + output[++o_id].Name_= "position"; xr_vector& o_position = output[o_id].floatVector_; + output[++o_id].Name_= "normal"; xr_vector& o_normal = output[o_id].floatVector_; + output[++o_id].Name_= "tangent"; xr_vector& o_tangent = output[o_id].floatVector_; + output[++o_id].Name_= "binormal"; xr_vector& o_binormal = output[o_id].floatVector_; + output[++o_id].Name_= "tex0"; xr_vector& o_tc = output[o_id].floatVector_; + output[++o_id].Name_= "c_w0_b0"; xr_vector& o_c_w0_b0 = output[o_id].floatVector_; + output[++o_id].Name_= "w1_w2_w3"; xr_vector& o_w1_w2_w3 = output[o_id].floatVector_; + output[++o_id].Name_= "b1_b2_b3"; xr_vector& o_b1_b2_b3 = output[o_id].floatVector_; + output[++o_id].Name_= "indices"; xr_vector& o_indices = output[o_id].intVector_; + + // fill inputs (verts&indices) + for (SkelVertIt vert_it=m_Verts.begin(); vert_it!=m_Verts.end(); vert_it++){ + SSkelVert &iV = *vert_it; + i_position.push_back(iV.offs.x); i_position.push_back(iV.offs.y); i_position.push_back(iV.offs.z); + i_normal.push_back (iV.norm.x); i_normal.push_back (iV.norm.y); i_normal.push_back (iV.norm.z); + i_tc.push_back (iV.uv.x); i_tc.push_back (iV.uv.y); i_tc.push_back (0); + u32 sz = iV.bones.size(); + i_c_w0_b0.push_back (*(float*)&sz); i_c_w0_b0.push_back(iV.bones[0].w); i_c_w0_b0.push_back (*(float*)&iV.bones[0].id); + u32 pt_w = i_w1_w2_w3.size(); + u32 pt_b = i_b1_b2_b3.size(); + i_w1_w2_w3.push_back(0.f); i_w1_w2_w3.push_back(0.f); i_w1_w2_w3.push_back(0.f); + i_b1_b2_b3.push_back(0.f); i_b1_b2_b3.push_back(0.f); i_b1_b2_b3.push_back(0.f); + if (iV.bones.size()>1){ + i_w1_w2_w3[pt_w+0] = iV.bones[1].w; + i_b1_b2_b3[pt_b+0] = (*(float*)&iV.bones[1].id); + if (iV.bones.size()>2){ + i_w1_w2_w3[pt_w+1] = iV.bones[2].w; + i_b1_b2_b3[pt_b+1] = (*(float*)&iV.bones[2].id); + if (iV.bones.size()>3){ + i_w1_w2_w3[pt_w+2] = iV.bones[3].w; + i_b1_b2_b3[pt_b+2] = (*(float*)&iV.bones[3].id); + } + } + } + } + for (SkelFaceIt face_it=m_Faces.begin(); face_it!=m_Faces.end(); face_it++){ + SSkelFace &iF = *face_it; + i_indices.push_back (iF.v[0]); + i_indices.push_back (iF.v[1]); + i_indices.push_back (iF.v[2]); + } + + // Perform munge + NVMeshMender mender; + if (!mender.Munge( + input, // input attributes + output, // outputs attributes + deg2rad(75.f), // tangent space smooth angle + 0, // no texture matrix applied to my texture coordinates + NVMeshMender::FixTangents, // fix degenerate bases & texture mirroring + NVMeshMender::DontFixCylindricalTexGen, // handle cylindrically mapped textures via vertex duplication + NVMeshMender::DontWeightNormalsByFaceSize // weigh vertex normals by the triangle's size + )) + { + Debug.fatal (DEBUG_INFO,"NVMeshMender failed (%s)",mender.GetLastError().c_str()); + } + + // verify + R_ASSERT (3*m_Faces.size() == o_indices.size()); + u32 v_cnt = o_position.size(); + R_ASSERT (0==v_cnt%3); + R_ASSERT (v_cnt == o_normal.size()); + R_ASSERT (v_cnt == o_tangent.size()); + R_ASSERT (v_cnt == o_binormal.size()); + R_ASSERT (v_cnt == o_tc.size()); + R_ASSERT (v_cnt == o_w1_w2_w3.size()); + R_ASSERT (v_cnt == o_b1_b2_b3.size()); + R_ASSERT (v_cnt == o_c_w0_b0.size()); + v_cnt /= 3; + + // retriving data + u32 o_idx = 0; + for (face_it=m_Faces.begin(); face_it!=m_Faces.end(); face_it++){ + SSkelFace &iF = *face_it; + iF.v[0] = (u16)o_indices[o_idx++]; + iF.v[1] = (u16)o_indices[o_idx++]; + iF.v[2] = (u16)o_indices[o_idx++]; + } + m_Verts.clear (); m_Verts.resize(v_cnt); + for (u32 v_idx=0; v_idx!=v_cnt; v_idx++){ + SSkelVert &oV = m_Verts[v_idx]; + oV.offs.set (o_position[v_idx*3+0], o_position[v_idx*3+1], o_position[v_idx*3+2]); + oV.norm.set (o_normal[v_idx*3+0], o_normal[v_idx*3+1], o_normal[v_idx*3+2]); + oV.tang.set (o_tangent[v_idx*3+0], o_tangent[v_idx*3+1], o_tangent[v_idx*3+2]); + oV.binorm.set(o_binormal[v_idx*3+0],o_binormal[v_idx*3+1], o_binormal[v_idx*3+2]); + oV.uv.set (o_tc[v_idx*3+0], o_tc[v_idx*3+1]); + oV.bones.resize (*(u32*)&o_c_w0_b0 [v_idx*3+0]); + + oV.bones[0].w = o_c_w0_b0 [v_idx*3+1];oV.bones[0].id = (u16)(*(u32*)&o_c_w0_b0 [v_idx*3+2]); + if (oV.bones.size()>1){ + oV.bones[1].w = o_w1_w2_w3[v_idx*3+0]; + oV.bones[1].id = (u16)(*(u32*)&o_b1_b2_b3 [v_idx*3+0]); + if (oV.bones.size()>2){ + oV.bones[2].w = o_w1_w2_w3[v_idx*3+1]; + oV.bones[2].id = (u16)(*(u32*)&o_b1_b2_b3 [v_idx*3+1]); + if (oV.bones.size()>3){ + oV.bones[3].w = o_w1_w2_w3[v_idx*3+2]; + oV.bones[3].id = (u16)(*(u32*)&o_b1_b2_b3 [v_idx*3+2]); + } + } + } + } + + +} +*/ +///////////////////////////////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////////////////////////////// +/*#include "../WildMagic/nvmeshmender.h" +#include "../../common/NvMender2003/nvMeshMender.h" +#include "../../common/NvMender2003/mender_input_output.h" +#include "../../common/NvMender2003/remove_isolated_verts.h"*/ + +void CExportSkeleton::SSplit::OptimizeTextureCoordinates() +{ + // Optimize texture coordinates + // 1. Calc bounds + Fvector2 Tdelta; + Fvector2 Tmin, Tmax; + Tmin.set(flt_max, flt_max); + Tmax.set(flt_min, flt_min); + + u32 v_cnt = m_Verts.size(); + + for (u32 v_idx = 0; v_idx != v_cnt; v_idx++) + { + SSkelVert &iV = m_Verts[v_idx]; + Tmin.min(iV.uv); + Tmax.max(iV.uv); + } + Tdelta.x = floorf((Tmax.x - Tmin.x) / 2 + Tmin.x); + Tdelta.y = floorf((Tmax.y - Tmin.y) / 2 + Tmin.y); + + Fvector2 Tsize; + Tsize.sub(Tmax, Tmin); + if ((Tsize.x > 32) || (Tsize.y > 32)) + Msg("#!Surface [T:'%s', S:'%s'] has UV tiled more than 32 times.", *m_Texture, *m_Shader); + { + // 2. Recalc UV mapping + for (u32 v_idx = 0; v_idx != v_cnt; v_idx++) + { + SSkelVert &iV = m_Verts[v_idx]; + iV.uv.sub(Tdelta); + } + } +} +/* +IC void set_vertex( MeshMender::Vertex &out_vertex, const SSkelVert& in_vertex ) +{ + cv_vector( out_vertex.pos, in_vertex.offs ); + cv_vector( out_vertex.normal, in_vertex.norm ); + out_vertex.s = in_vertex.uv.x; + out_vertex.t = in_vertex.uv.y; + //out_vertex.tangent; + //out_vertex.binormal; +} + +IC void set_vertex( SSkelVert& out_vertex, const SSkelVert& in_old_vertex, const MeshMender::Vertex &in_vertex ) +{ + out_vertex = in_old_vertex; + + cv_vector( out_vertex.offs, in_vertex.pos );//? + cv_vector( out_vertex.norm, in_vertex.normal );//? + + out_vertex.uv.x = in_vertex.s; + out_vertex.uv.y = in_vertex.t; + Fvector tangent; Fvector binormal; + out_vertex.tang.set( cv_vector( tangent, in_vertex.tangent ) ); + out_vertex.binorm.set( cv_vector( binormal, in_vertex.binormal ) ); +} + + +IC u16 &face_vertex( SSkelFace &F, u32 vertex_index ) +{ + VERIFY( vertex_index < 3 ); + return F.v[vertex_index]; +} + +IC const u16 &face_vertex( const SSkelFace &F, u32 vertex_index ) +{ + VERIFY( vertex_index < 3 ); + return F.v[vertex_index]; +} + + + +*/ + +void CExportSkeleton::SSplit::CalculateTB() +{ + /*xr_vector mender_in_out_verts; + xr_vector< unsigned int > mender_in_out_indices; + xr_vector< unsigned int > mender_mapping_out_to_in_vert; + + fill_mender_input( m_Verts, m_Faces, mender_in_out_verts, mender_in_out_indices ); + + MeshMender mender ; + if + ( + !mender.Mend + ( + mender_in_out_verts, + mender_in_out_indices, + mender_mapping_out_to_in_vert, + 1, + 0.5, + 0.5, + 0.0f, + MeshMender::DONT_CALCULATE_NORMALS, + MeshMender::RESPECT_SPLITS, + MeshMender::DONT_FIX_CYLINDRICAL + ) + ) + { + Debug.fatal ( DEBUG_INFO, "NVMeshMender failed " ); + //Debug.fatal (DEBUG_INFO,"NVMeshMender failed (%s)",mender.GetLastError().c_str()); + } + + retrive_data_from_mender_otput( m_Verts, m_Faces, mender_in_out_verts, mender_in_out_indices, mender_mapping_out_to_in_vert ); + + t_remove_isolated_verts( m_Verts, m_Faces ); + + mender_in_out_verts .clear( ); + mender_in_out_indices .clear( ); + mender_mapping_out_to_in_vert .clear( ); + + OptimizeTextureCoordinates();*/ +} \ No newline at end of file diff --git a/src/editors/xrECore/Editor/GeometryCollector.cpp b/src/editors/xrECore/Editor/GeometryCollector.cpp new file mode 100644 index 00000000000..90623d0368c --- /dev/null +++ b/src/editors/xrECore/Editor/GeometryCollector.cpp @@ -0,0 +1,155 @@ +#include "stdafx.h" +#include "GeometryCollector.h" + +// VCPacked + +VCPacked::VCPacked(const Fbox &bb, float _eps, u32 _sx, u32 _sy, u32 _sz, int apx_vertices) +{ + eps = _eps; + sx = _max(_sx, 1); + sy = _max(_sy, 1); + sz = _max(_sz, 1); + // prepare hash table + VM.resize(sx * sy * sz); + + // Params + VMscale.set(bb.vMax.x - bb.vMin.x, bb.vMax.y - bb.vMin.y, bb.vMax.z - bb.vMin.z); + VMmin.set(bb.vMin); + VMeps.set(VMscale.x / (sx - 1) / 2, VMscale.y / (sy - 1) / 2, VMscale.z / (sz - 1) / 2); + VMeps.x = (VMeps.x < EPS_L) ? VMeps.x : EPS_L; + VMeps.y = (VMeps.y < EPS_L) ? VMeps.y : EPS_L; + VMeps.z = (VMeps.z < EPS_L) ? VMeps.z : EPS_L; + + // Preallocate memory + verts.reserve(apx_vertices); + + int _size = VM.size(); + int _average = (apx_vertices / _size) / 2; + for (GCHashIt it = VM.begin(); it != VM.end(); it++) + it->reserve(_average); +} + +u32 VCPacked::add_vert(const Fvector &V) +{ + u32 P = 0xffffffff; + + u32 clpX = sx - 1, clpY = sy - 1, clpZ = sz - 1; + + u32 ix, iy, iz; + ix = iFloor(float(V.x - VMmin.x) / VMscale.x * clpX); + iy = iFloor(float(V.y - VMmin.y) / VMscale.y * clpY); + iz = iFloor(float(V.z - VMmin.z) / VMscale.z * clpZ); + + clamp(ix, (u32)0, clpX); + clamp(iy, (u32)0, clpY); + clamp(iz, (u32)0, clpZ); + + { + U32Vec &vl = get_element(ix, iy, iz); + for (U32It it = vl.begin(); it != vl.end(); it++) + if (verts[*it].similar(V, eps)) + { + P = *it; + verts[*it].refs++; + break; + } + } + if (0xffffffff == P) + { + P = verts.size(); + verts.push_back(GCVertex(V)); + + get_element(ix, iy, iz).push_back(P); + + u32 ixE, iyE, izE; + ixE = iFloor(float(V.x + VMeps.x - VMmin.x) / VMscale.x * clpX); + iyE = iFloor(float(V.y + VMeps.y - VMmin.y) / VMscale.y * clpY); + izE = iFloor(float(V.z + VMeps.z - VMmin.z) / VMscale.z * clpZ); + + // R_ASSERT(ixE<=clpMX && iyE<=clpMY && izE<=clpMZ); + clamp(ixE, (u32)0, clpX); + clamp(iyE, (u32)0, clpY); + clamp(izE, (u32)0, clpZ); + + if (ixE != ix) + get_element(ixE, iy, iz).push_back(P); + if (iyE != iy) + get_element(ix, iyE, iz).push_back(P); + if (izE != iz) + get_element(ix, iy, izE).push_back(P); + if ((ixE != ix) && (iyE != iy)) + get_element(ixE, iyE, iz).push_back(P); + if ((ixE != ix) && (izE != iz)) + get_element(ixE, iy, izE).push_back(P); + if ((iyE != iy) && (izE != iz)) + get_element(ix, iyE, izE).push_back(P); + if ((ixE != ix) && (iyE != iy) && (izE != iz)) + get_element(ixE, iyE, izE).push_back(P); + } + return P; +} + +void VCPacked::clear() +{ + verts.clear(); + for (GCHashIt it = VM.begin(); it != VM.end(); it++) + it->clear(); +} + +//------------------------------------------------------------------------------ +// GCPacked +//------------------------------------------------------------------------------ +void GCPacked::add_face(const Fvector &v0, const Fvector &v1, const Fvector &v2, u32 dummy) +{ + GCFace T; + T.verts[0] = add_vert(v0); + T.verts[1] = add_vert(v1); + T.verts[2] = add_vert(v2); + T.dummy = dummy; + faces.push_back(T); + validate(T); +} + +void GCPacked::clear() +{ + // ?? + //GCPacked::clear(); + faces.clear(); +} + +void GCPacked::calc_adjacency(U32Vec &dest) +{ + dest.assign(faces.size() * 3, 0xffffffff); + // Dumb algorithm O(N^2) :) + for (u32 f = 0; f < faces.size(); f++) + { + for (u32 t = 0; t < faces.size(); t++) + { + if (t == f) + continue; + + for (u32 f_e = 0; f_e < 3; f_e++) + { + u32 f1 = faces[f].verts[(f_e + 0) % 3]; + u32 f2 = faces[f].verts[(f_e + 1) % 3]; + if (f1 > f2) + std::swap(f1, f2); + + for (u32 t_e = 0; t_e < 3; t_e++) + { + u32 t1 = faces[t].verts[(t_e + 0) % 3]; + u32 t2 = faces[t].verts[(t_e + 1) % 3]; + if (t1 > t2) + std::swap(t1, t2); + + if (f1 == t1 && f2 == t2) + { + // f.edge[f_e] linked to t.edge[t_e] + dest[f * 3 + f_e] = t; + break; + } + } + } + } + } +} diff --git a/src/editors/xrECore/Editor/GeometryCollector.h b/src/editors/xrECore/Editor/GeometryCollector.h new file mode 100644 index 00000000000..3ecf7b096cc --- /dev/null +++ b/src/editors/xrECore/Editor/GeometryCollector.h @@ -0,0 +1,89 @@ +#ifndef GeometryCollectorH +#define GeometryCollectorH +//--------------------------------------------------------------------------- + +struct ECORE_API GCVertex +{ + Fvector pos; + u32 refs; + GCVertex(const Fvector &p) + { + pos = p; + refs = 1; + } + bool similar(const GCVertex &v, float eps = EPS) { return pos.similar(v.pos); } +}; + +struct ECORE_API GCFace +{ + u32 verts[3]; + bool valid; + u32 dummy; +}; + +class ECORE_API VCPacked +{ +protected: + DEFINE_VECTOR(U32Vec, GCHash, GCHashIt); + + xr_vector verts; + + GCHash VM; + Fvector VMmin, VMscale; + Fvector VMeps; + float eps; + u32 sx, sy, sz; + + IC U32Vec &get_element(u32 ix, u32 iy, u32 iz) + { + VERIFY((ix < sx) && (iy < sy) && (iz < sz)); + return VM[iz * sy * sx + iy * sx + ix]; + } + +public: + VCPacked(const Fbox &bb, float eps = EPS, u32 clpSX = 24, u32 clpSY = 16, u32 clpSZ = 24, int apx_vertices = 5000); + virtual ~VCPacked() { clear(); } + virtual void clear(); + + u32 add_vert(const Fvector &V); + + GCVertex *getV() { return &*verts.begin(); } + size_t getVS() { return verts.size(); } + xr_vector &Vertices() { return verts; } + + void getHASH_size(u32 &x, u32 &y, u32 &z) + { + x = sx; + y = sy; + z = sz; + } + U32Vec &getHASH_elem(u32 ix, u32 iy, u32 iz) { return get_element(ix, iy, iz); } +}; + +class ECORE_API GCPacked : public VCPacked +{ + xr_vector faces; + void validate(GCFace &F) + { + if ((F.verts[0] == F.verts[1]) || (F.verts[0] == F.verts[2]) || (F.verts[1] == F.verts[2])) + F.valid = false; + else + F.valid = true; + } + +public: + GCPacked(const Fbox &bb, float eps = EPS, u32 clpMX = 24, u32 clpMY = 16, u32 clpMZ = 24, int apx_vertices = 5000, int apx_faces = 5000) : VCPacked(bb, eps, clpMX, clpMY, clpMZ, apx_vertices) { faces.reserve(apx_faces); } + virtual ~GCPacked() { clear(); } + virtual void clear(); + + xr_vector &Faces() { return faces; } + + void add_face(const Fvector &v0, const Fvector &v1, const Fvector &v2, u32 dummy = 0); + + GCFace *getF() { return &*faces.begin(); } + size_t getFS() { return faces.size(); } + + void calc_adjacency(U32Vec &dest); +}; + +#endif diff --git a/src/editors/xrECore/Editor/ImageEditor.ddp b/src/editors/xrECore/Editor/ImageEditor.ddp new file mode 100644 index 00000000000..cdc0ee8c2b5 Binary files /dev/null and b/src/editors/xrECore/Editor/ImageEditor.ddp differ diff --git a/src/editors/xrECore/Editor/ImageEditor.dfm b/src/editors/xrECore/Editor/ImageEditor.dfm new file mode 100644 index 00000000000..cb8ab75c52e --- /dev/null +++ b/src/editors/xrECore/Editor/ImageEditor.dfm @@ -0,0 +1,412 @@ +object frmImageLib: TfrmImageLib + Left = 482 + Top = 150 + Width = 469 + Height = 596 + BorderIcons = [biSystemMenu, biMinimize] + Caption = 'Image Editor' + Color = 10528425 + Constraints.MinHeight = 400 + Constraints.MinWidth = 390 + Font.Charset = DEFAULT_CHARSET + Font.Color = clWindowText + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + FormStyle = fsStayOnTop + KeyPreview = True + OldCreateOrder = False + Scaled = False + OnClose = FormClose + OnCreate = FormCreate + OnDestroy = FormDestroy + OnKeyDown = FormKeyDown + OnShow = FormShow + PixelsPerInch = 96 + TextHeight = 13 + object Splitter1: TSplitter + Left = 194 + Top = 0 + Width = 2 + Height = 562 + Cursor = crHSplit + Color = 3026478 + ParentColor = False + end + object paRight: TPanel + Left = 196 + Top = 0 + Width = 265 + Height = 562 + Align = alClient + BevelOuter = bvLowered + Color = 10528425 + Constraints.MinWidth = 172 + TabOrder = 0 + object Bevel2: TBevel + Left = 1 + Top = 456 + Width = 263 + Height = 2 + Align = alBottom + Shape = bsBottomLine + end + object paCommand: TPanel + Left = 1 + Top = 458 + Width = 263 + Height = 103 + Align = alBottom + BevelInner = bvLowered + BevelOuter = bvNone + Color = 10528425 + TabOrder = 0 + object ebOk: TExtBtn + Left = 1 + Top = 68 + Width = 261 + Height = 17 + Align = alBottom + BevelShow = False + Caption = 'Ok' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + FlatAlwaysEdge = True + OnClick = ebOkClick + end + object Bevel1: TBevel + Left = 1 + Top = 1 + Width = 261 + Height = 2 + Align = alTop + Shape = bsLeftLine + Style = bsRaised + end + object ebCancel: TExtBtn + Left = 1 + Top = 85 + Width = 261 + Height = 17 + Align = alBottom + BevelShow = False + Caption = 'Cancel' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + FlatAlwaysEdge = True + OnClick = ebCancelClick + end + object ebRemoveTexture: TExtBtn + Left = 1 + Top = 26 + Width = 261 + Height = 17 + Align = alTop + BevelShow = False + Caption = 'Remove Texture' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + FlatAlwaysEdge = True + OnClick = ebRemoveTextureClick + end + object Bevel5: TBevel + Left = 1 + Top = 3 + Width = 261 + Height = 2 + Align = alTop + Shape = bsLeftLine + Style = bsRaised + end + object Panel2: TPanel + Left = 1 + Top = 5 + Width = 261 + Height = 21 + Align = alTop + BorderWidth = 1 + Color = 10528425 + TabOrder = 0 + object btFilter: TExtBtn + Left = 2 + Top = 2 + Width = 194 + Height = 17 + Align = alClient + BevelShow = False + Caption = 'Filter by selected' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + FlatAlwaysEdge = True + OnClick = btFilterClick + end + object ExtBtn1: TExtBtn + Left = 196 + Top = 2 + Width = 63 + Height = 17 + Align = alRight + BevelShow = False + Caption = 'Reset Filter' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + FlatAlwaysEdge = True + OnClick = ExtBtn1Click + end + end + end + object paProperties: TPanel + Left = 1 + Top = 133 + Width = 263 + Height = 323 + Align = alClient + BevelOuter = bvNone + Color = 10528425 + TabOrder = 1 + end + object Panel1: TPanel + Left = 1 + Top = 1 + Width = 263 + Height = 132 + Align = alTop + BevelOuter = bvNone + ParentColor = True + TabOrder = 2 + object paImage: TMxPanel + Left = 1 + Top = 1 + Width = 130 + Height = 130 + BevelOuter = bvLowered + Caption = '' + ParentColor = True + TabOrder = 0 + OnPaint = paImagePaint + end + end + end + object paItems: TPanel + Left = 0 + Top = 0 + Width = 194 + Height = 562 + Align = alLeft + BevelOuter = bvNone + Constraints.MinWidth = 194 + ParentColor = True + TabOrder = 1 + object paFilter: TPanel + Left = 0 + Top = 0 + Width = 194 + Height = 21 + Align = alTop + BevelInner = bvLowered + Constraints.MinWidth = 168 + ParentColor = True + TabOrder = 0 + object ttImage: TExtBtn + Left = 2 + Top = 2 + Width = 38 + Height = 17 + Align = alNone + AllowAllUp = True + BevelShow = False + GroupIndex = 1 + Down = True + Caption = 'Image' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + FlatAlwaysEdge = True + OnClick = ttImageClick + end + object ttBumpMap: TExtBtn + Left = 78 + Top = 2 + Width = 38 + Height = 17 + Align = alNone + AllowAllUp = True + BevelShow = False + GroupIndex = 3 + Down = True + Caption = 'Bump' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + FlatAlwaysEdge = True + OnClick = ttImageClick + end + object ttNormalMap: TExtBtn + Left = 116 + Top = 2 + Width = 38 + Height = 17 + Align = alNone + AllowAllUp = True + BevelShow = False + GroupIndex = 4 + Down = True + Caption = 'Normal' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + FlatAlwaysEdge = True + OnClick = ttImageClick + end + object ttCubeMap: TExtBtn + Left = 40 + Top = 2 + Width = 38 + Height = 17 + Align = alNone + AllowAllUp = True + BevelShow = False + GroupIndex = 2 + Down = True + Caption = 'Cube' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + FlatAlwaysEdge = True + OnClick = ttImageClick + end + object ttTerrain: TExtBtn + Left = 154 + Top = 2 + Width = 38 + Height = 17 + Align = alNone + AllowAllUp = True + BevelShow = False + GroupIndex = 5 + Down = True + Caption = 'Terrain' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + FlatAlwaysEdge = True + OnClick = ttImageClick + end + end + end + object fsStorage: TFormStorage + Version = 1 + OnSavePlacement = fsStorageSavePlacement + OnRestorePlacement = fsStorageRestorePlacement + StoredProps.Strings = ( + 'paRight.Width' + 'paItems.Width') + StoredValues = <> + Top = 40 + end + object ImageList: TImageList + Height = 10 + Width = 11 + Left = 32 + Top = 40 + Bitmap = { + 494C01010200040004000B000A00FFFFFFFFFF10FFFFFFFFFFFFFFFF424D3600 + 00000000000036000000280000002C0000000A0000000100200000000000E006 + 0000000000000000000000000000000000000000000000000000000000000000 + 00000C0C57000C0C570000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000C0C57000C0C5700000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 00000C0C57000C0C570000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000002A2A57000C0C57000C0C57002A2A57000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000002A2A + 57000C0C57000C0C57002A2A5700000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000002A2A57000C0C57000C0C57002A2A57000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000002A2A + 57000C0C57000C0C57002A2A5700000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000C0C57000C0C5700000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000 + 000000000000000000000000000000000000424D3E000000000000003E000000 + 280000002C0000000A0000000100010000000000500000000000000000000000 + 000000000000000000000000FFFFFF00F3FFFC0000000000F3FDFC0000000000 + FFF8FC0000000000FFF07C0000000000F3E33C0000000000E1E79C0000000000 + E1FFCC0000000000E1FFE40000000000E1FFF40000000000F3FFFC0000000000 + 00000000000000000000000000000000000000000000} + end +end diff --git a/src/editors/xrECore/Editor/ImageManager.cpp b/src/editors/xrECore/Editor/ImageManager.cpp new file mode 100644 index 00000000000..be8f70c54ef --- /dev/null +++ b/src/editors/xrECore/Editor/ImageManager.cpp @@ -0,0 +1,897 @@ +#include "stdafx.h" +#include "ImageManager.h" +#include "xrEngine/xrImage_Resampler.h" +#include "..\Engine\Image.h" +#include "ui_main.h" +#include "EditObject.h" +#include "Layers/xrRender/ResourceManager.h" +#include "utils/ETools/ETools.h" + +#include "FreeImage.h" +#pragma comment(lib, "FreeImage.lib") + +CImageManager ImageLib; + +extern "C" __declspec(dllimport) int DXTCompress(LPCSTR out_name, u8 *raw_data, u8 *ext_data, u32 w, u32 h, u32 pitch, STextureParams *options, u32 depth); + +bool IsValidSize(u32 w, u32 h) +{ + if (!btwIsPow2(h)) + return false; + + if (h * 6 == w) + return true; + + if (!btwIsPow2(w)) + return false; + + return true; +} + +FIBITMAP *Surface_Load(char *full_name) +{ + // load + FREE_IMAGE_FORMAT fif = FreeImage_GetFIFFromFilename(full_name); + FIBITMAP *map = FreeImage_Load(fif, full_name); + + if (!map) + return nullptr; + + // check if already 32bpp + if (32 == FreeImage_GetBPP(map)) + return map; + + // convert + FIBITMAP *map32 = FreeImage_ConvertTo32Bits(map); + + if (!map32) + map32 = map; + else + FreeImage_Unload(map); + + return map32; +} + +bool Stbi_Load(LPCSTR full_name, U32Vec &data, u32 &w, u32 &h, u32 &a) +{ + if (!FS.exist(full_name)) + { + ELog.Msg(mtError, "Can't find file: '%s'", full_name); + return false; + } + + if (strstr(full_name, ".tga")) + { + CImage img; + + if (!img.LoadTGA(full_name)) + return false; + + w = img.dwWidth; + h = img.dwHeight; + a = img.bAlpha; + data.resize(w * h); + + for (int y = 0; y < h; y++) + CopyMemory(data.data() + y * w, img.pData + (y * w), sizeof(u32) * w); + + if (!IsValidSize(w, h)) + ELog.Msg(mtError, "Texture (%s) - invalid size: [%d, %d]", full_name, w, h); + + return true; + } + + if (FIBITMAP *bm = Surface_Load((LPSTR)full_name)) + { + w = FreeImage_GetWidth(bm); + h = FreeImage_GetHeight(bm); + u32 w4 = w * 4; + data.resize(w * h); + + for (int y = h - 1; y >= 0; y--) + CopyMemory(&data[0] + (h - y - 1) * w, FreeImage_GetScanLine(bm, y), w4); + + a = FIC_RGBALPHA == FreeImage_GetColorType(bm); + FreeImage_Unload(bm); + + if (!IsValidSize(w, h)) + ELog.Msg(mtError, "Texture (%s) - invalid size: [%d, %d]", full_name, w, h); + + return true; + } + + return false; +} + +u32 *Stbi_Load(LPCSTR full_name, u32 &w, u32 &h) +{ + u32 a; + xr_vector data; + + if (Stbi_Load(full_name, data, w, h, a)) + { + u32 *raw_data = xr_alloc(w * h); + memcpy(raw_data, data.data(), w * h * 4); + return raw_data; + } + + return nullptr; +} + +xr_string CImageManager::UpdateFileName(xr_string &fn) +{ + return EFS.AppendFolderToName(fn, 1, TRUE); +} + +//------------------------------------------------------------------------------ +// создает тхм +//------------------------------------------------------------------------------ +void CImageManager::MakeThumbnailImage(ETextureThumbnail *THM, u32 *data, u32 w, u32 h, u32 a) +{ + R_ASSERT(THM); + // create thumbnail + + if (THM->m_Pixels.empty()) + THM->m_Pixels.resize(THUMB_SIZE); + + THM->m_TexParams.width = w; + THM->m_TexParams.height = h; + THM->m_TexParams.flags.set(STextureParams::flHasAlpha, a); + + imf_Process(THM->m_Pixels.data(), THUMB_WIDTH, THUMB_HEIGHT, data, THM->_Width(), THM->_Height(), imf_box); + THM->VFlip(); +} + +//------------------------------------------------------------------------------ +// создает тхм +//------------------------------------------------------------------------------ +void CImageManager::CreateTextureThumbnail(ETextureThumbnail *THM, const xr_string &src_name, LPCSTR initial, bool bSetDefParam) +{ + R_ASSERT(src_name.size()); + string_path base_name; + + if (initial) + FS.update_path(base_name, initial, src_name.c_str()); + else + FS.update_path(base_name, _textures_, src_name.c_str()); + + U32Vec data; + u32 w, h, a; + xr_string fn = EFS.ChangeFileExt(base_name, ".tga"); + + if (!Stbi_Load(fn.c_str(), data, w, h, a)) + { + if (!Stbi_Load(base_name, data, w, h, a)) + { + ELog.Msg(mtError, "Can't load texture '%s'.\nCheck file existence", fn.c_str()); + return; + } + } + + MakeThumbnailImage(THM, data.data(), w, h, a); + + // выставить начальные параметры + if (bSetDefParam) + { + THM->m_Age = FS.get_file_age(fn.c_str()); + THM->m_TexParams.fmt = (a) ? STextureParams::tfDXT3 : STextureParams::tfDXT1; + + if ((h * 6) == w) + { + THM->m_TexParams.type = STextureParams::ttCubeMap; + THM->m_TexParams.flags.set(STextureParams::flGenerateMipMaps, FALSE); + } + } + + THM->SetValid(); +} + +//------------------------------------------------------------------------------ +// создает новую текстуру +//------------------------------------------------------------------------------ +void CImageManager::CreateGameTexture(LPCSTR src_name, ETextureThumbnail *thumb) +{ + R_ASSERT(src_name && src_name[0]); + ETextureThumbnail *THM = thumb ? thumb : xr_new(src_name); + string_path base_name; + strcpy(base_name, src_name); + + string_path game_name; + strcpy(game_name, EFS.ChangeFileExt(src_name, ".dds").c_str()); + FS.update_path(base_name, _textures_, base_name); + FS.update_path(game_name, _game_textures_, game_name); + int base_age = FS.get_file_age(base_name); + + U32Vec data; + u32 w, h, a; + if (!Stbi_Load(base_name, data, w, h, a)) + return; + MakeGameTexture(THM, game_name, data.data()); + + FS.set_file_age(game_name, base_age); + if (!thumb) + xr_delete(THM); +} + +//------------------------------------------------------------------------------ +// создает игровую текстуру +//------------------------------------------------------------------------------ +bool CImageManager::MakeGameTexture(LPCSTR game_name, u32 *data, const STextureParams &tp) +{ + VerifyPath(game_name); + // fill texture params + // compress + u32 w4 = tp.width * 4; + int res = DXTCompress(game_name, (u8 *)data, 0, tp.width, tp.height, w4, (STextureParams *)&tp, 4); + if (1 != res) + { + FS.file_delete(game_name); + + switch (res) + { + case 0: + ELog.DlgMsg(mtError, "Can't make game texture '%s'.", game_name); + break; + + case -1000: + ELog.Msg(mtError, "Invalid gloss mask '%s'.", game_name); + return true; + } + + return false; + } + + R_ASSERT((res == 1) && FS.file_length(game_name)); + return res == 1; +} + +bool CImageManager::MakeGameTexture(ETextureThumbnail *THM, LPCSTR game_name, u32 *load_data) +{ + VerifyPath(game_name); + // flip + u32 w = THM->_Width(); + u32 h = THM->_Height(); + u32 w4 = w * 4; + // remove old + FS.file_delete(game_name); + xr_string game_name2 = ChangeFileExt(game_name, "#.dds"); + FS.file_delete(game_name2.c_str()); + + U32Vec ext_data; + if ((THM->m_TexParams.type == STextureParams::ttBumpMap) && (THM->m_TexParams.ext_normal_map_name.size())) + { + bool e_res = true; + LPCSTR e_name = THM->m_TexParams.ext_normal_map_name.c_str(); + ETextureThumbnail *NM_THM = xr_new(e_name); + + if (NM_THM->_Format().type == STextureParams::ttNormalMap) + { + if (NM_THM->_Format().fmt == STextureParams::tfRGBA) + { + u32 _w, _h; + + if (!LoadTextureData(e_name, ext_data, _w, _h)) + { + ELog.DlgMsg(mtError, "Can't load special normal map texture '%s'.", e_name); + e_res = false; + } + else if ((_w != w) || (_h != h)) + { + ELog.DlgMsg(mtError, "Invalid load special normal map size '%s'. It should be [%dx%d]", e_name, w, h); + e_res = false; + } + } + else + { + ELog.DlgMsg(mtError, "Invalid special normal map format '%s'. It should be '32 bit (8:8:8:8)'", e_name); + e_res = false; + } + } + else + { + ELog.DlgMsg(mtError, "Invalid special normal map type '%s'. It should be 'NormalMap'", e_name); + e_res = false; + } + + xr_delete(NM_THM); + if (false == e_res) + return false; + } + // compress + int res = DXTCompress(game_name, (u8 *)load_data, (u8 *)(ext_data.empty() ? 0 : ext_data.data()), w, h, w4, &THM->m_TexParams, 4); + if (1 != res) + { + if (-1000 != res) + { //. Special for Oles (glos<10%) + FS.file_delete(game_name); + FS.file_delete(game_name2.c_str()); + } + switch (res) + { + case 0: + ELog.DlgMsg(mtError, "Can't make game texture '%s'.", THM->m_SrcName.c_str()); + break; + + case -1000: + ELog.Msg(mtError, "Invalid gloss mask '%s'.", THM->m_SrcName.c_str()); + return true; + } + return false; + } + R_ASSERT((res == 1) && FS.file_length(game_name)); + return res == 1; +} + +//------------------------------------------------------------------------------ +// загружает 32-bit данные +//------------------------------------------------------------------------------ +bool CImageManager::LoadTextureData(LPCSTR src_name, U32Vec &data, u32 &w, u32 &h, int *age) +{ + string_path fn; + FS.update_path(fn, _game_textures_, ChangeFileExt(src_name, ".dds").c_str()); + u32 a; + + if (!Stbi_Load(fn, data, w, h, a)) + return false; + + if (age) + *age = FS.get_file_age(fn); + + return true; +} + +//------------------------------------------------------------------------------ +// копирует обновленные текстуры с Import'a в Textures +// files - список файлов для копирование +//------------------------------------------------------------------------------ +void CImageManager::SafeCopyLocalToServer(FS_FileSet &files) +{ + string_path p_import, p_textures; + string_path src_name, dest_name; + FS.update_path(p_import, _import_, ""); + FS.update_path(p_textures, _textures_, ""); + + auto it = files.begin(); + auto _E = files.end(); + + for (; it != _E; it++) + { + xr_string fn; + + // copy sources + fn = it->name; + strconcat(sizeof(src_name), src_name, p_import, fn.c_str()); + UpdateFileName(fn); + + strconcat(sizeof(dest_name), dest_name, p_textures, EFS.ChangeFileExt(fn, ".tga").c_str()); + + if (0 == strcmp(strext(src_name), ".tga")) + { + FS.file_copy(src_name, dest_name); + } + else + { + // convert to TGA + U32Vec data; + u32 w, h, a; + R_ASSERT(Stbi_Load(src_name, data, w, h, a)); + CImage *I = xr_new(); + I->Create(w, h, data.data()); + I->Vflip(); + I->SaveTGA(dest_name); + xr_delete(I); + } + + FS.set_file_age(dest_name, FS.get_file_age(src_name)); + EFS.MarkFile(src_name, true); + } +} + +//------------------------------------------------------------------------------ +// возвращает список не синхронизированных (модифицированных) текстур +// source_list - содержит список текстур с расширениями +// sync_list - реально сохраненные файлы (после использования освободить) +//------------------------------------------------------------------------------ +void CImageManager::SynchronizeTextures(bool sync_thm, bool sync_game, bool bForceGame, FS_FileSet *source_list, AStringVec *sync_list, FS_FileSet *modif_map, bool bForceBaseAge) +{ + FS_FileSet M_BASE; + FS_FileSet M_THUM; + FS_FileSet M_GAME; + + if (source_list) + M_BASE = *source_list; + else + FS.file_list(M_BASE, _textures_, FS_ListFiles | FS_ClampExt, "*.tga"); + if (M_BASE.empty()) + return; + if (sync_thm) + FS.file_list(M_THUM, _textures_, FS_ListFiles | FS_ClampExt, "*.thm"); + if (sync_game) + FS.file_list(M_GAME, _game_textures_, FS_ListFiles | FS_ClampExt, "*.dds"); + + bool bProgress = M_BASE.size() > 1; + + // lock rescanning + int m_age = time(NULL); + + // sync assoc + SPBItem *pb = 0; + if (bProgress) + pb = UI->ProgressStart(static_cast(M_BASE.size()), "Synchronize textures..."); + auto it = M_BASE.begin(); + auto _E = M_BASE.end(); + for (; it != _E; it++) + { + U32Vec data; + u32 w, h, a; + + xr_string base_name = EFS.ChangeFileExt(it->name, ""); + xr_strlwr(base_name); + string_path fn; + FS.update_path(fn, _textures_, EFS.ChangeFileExt(base_name, ".tga").c_str()); + if (!FS.exist(fn)) + continue; + + auto th = M_THUM.find(base_name); + bool bThm = ((th == M_THUM.end()) || ((th != M_THUM.end()) && (th->time_write != it->time_write))); + auto gm = M_GAME.find(base_name); + bool bGame = bThm || ((gm == M_GAME.end()) || ((gm != M_GAME.end()) && (gm->time_write != it->time_write))); + + ETextureThumbnail *THM = 0; + + BOOL bUpdated = FALSE; + BOOL bFailed = FALSE; + // check thumbnail + if (sync_thm && bThm) + { + THM = xr_new(it->name.c_str()); + bool bRes = Stbi_Load(fn, data, w, h, a); + R_ASSERT(bRes); + //. MakeThumbnailImage(THM,data.begin(),w,h,a); + THM->Save(it->time_write); + bUpdated = TRUE; + } + // check game textures + if (bForceGame || (sync_game && bGame)) + { + if (!THM) + THM = xr_new(it->name.c_str()); + R_ASSERT(THM); + if (data.empty()) + { + bool bRes = Stbi_Load(fn, data, w, h, a); + R_ASSERT(bRes); + } + if (IsValidSize(w, h)) + { + string_path game_name; + strconcat(sizeof(game_name), game_name, base_name.c_str(), ".dds"); + + FS.update_path(game_name, _game_textures_, game_name); + if (MakeGameTexture(THM, game_name, data.data())) + { + if (sync_list) + sync_list->push_back(base_name.c_str()); + if (modif_map) + modif_map->insert(*it); + } + else + { + bFailed = TRUE; + } + bUpdated = TRUE; + } + else + { + ELog.DlgMsg(mtError, "Can't make game texture '%s'.\nInvalid size (%dx%d).", base_name.c_str(), w, h); + } + } + if (THM) + xr_delete(THM); + if (UI->NeedAbort()) + break; + + if (bProgress) + pb->Inc(bUpdated ? xr_string(base_name + (bFailed ? " - FAILED" : " - UPDATED.")).c_str() : base_name.c_str(), bUpdated); + + if (bUpdated) + { + string_path tga_fn, thm_fn, dds_fn; + FS.update_path(tga_fn, _textures_, EFS.ChangeFileExt(base_name, ".tga").c_str()); + FS.update_path(thm_fn, _game_textures_, EFS.ChangeFileExt(base_name, ".thm").c_str()); + FS.update_path(dds_fn, _game_textures_, EFS.ChangeFileExt(base_name, ".dds").c_str()); + if (bForceBaseAge) + { + int age = it->time_write; + FS.set_file_age(tga_fn, age); + FS.set_file_age(thm_fn, age); + FS.set_file_age(dds_fn, age); + } + else + { + FS.set_file_age(tga_fn, m_age); + FS.set_file_age(thm_fn, m_age); + FS.set_file_age(dds_fn, m_age); + } + } + } + if (bProgress) + UI->ProgressEnd(pb); +} +/* +void CImageManager::ChangeFileAgeTo(FS_FileSet* tgt_map, int age) +{ + VERIFY(tgt_map); + FS_FileSet* M_BASE = tgt_map; + + // lock rescanning + FS.lock_rescan (); + // change + SPBItem* pb=0; + if (M_BASE->size()>1) pb = UI->ProgressStart(M_BASE->size(),"Change textures age..."); + auto it = M_BASE->begin(); + auto _E = M_BASE->end(); + for (; it!=_E; it++){ + xr_string base_name = EFS.ChangeFileExt(it->name,""); xr_strlwr(base_name); + xr_string tga_fn,thm_fn,dds_fn; + FS.update_path (tga_fn,_textures_, EFS.ChangeFileExt(base_name,".tga").c_str()); + FS.update_path (thm_fn,_textures_, EFS.ChangeFileExt(base_name,".thm").c_str()); + FS.update_path (dds_fn,_game_textures_,EFS.ChangeFileExt(base_name,".dds").c_str()); + FS.set_file_age (tga_fn.c_str(),age); + FS.set_file_age (thm_fn.c_str(),age); + FS.set_file_age (dds_fn.c_str(),age); + if (pb) pb->Inc(); + } + if (pb) UI->ProgressEnd(pb); + // lock rescanning + FS.unlock_rescan (); +} +*/ +void CImageManager::WriteAssociation(CInifile *ltx_ini, LPCSTR base_name, const STextureParams &fmt) +{ + ltx_ini->w_u32("types", base_name, fmt.type); +} + +void CImageManager::SynchronizeTexture(LPCSTR tex_name, int age) +{ + AStringVec modif; + FS_FileSet t_map; + FS_File F(tex_name); + F.time_write = age; + t_map.insert(F); + SynchronizeTextures(true, true, true, &t_map, &modif, 0, age); + RefreshTextures(&modif); +} +//------------------------------------------------------------------------------ +// возвращает список всех текстур +//------------------------------------------------------------------------------ +int CImageManager::GetTextures(FS_FileSet &files, BOOL bFolders) +{ + return FS.file_list(files, _game_textures_, (bFolders ? FS_ListFolders : 0) | FS_ListFiles | FS_ClampExt, "*.dds"); +} + +int CImageManager::GetTexturesRaw(FS_FileSet &files, BOOL bFolders) +{ + return FS.file_list(files, _textures_, (bFolders ? FS_ListFolders : 0) | FS_ListFiles | FS_ClampExt, "*.tga"); +} +//------------------------------------------------------------------------------ +// возвращает список текстур, которые нужно обновить +//------------------------------------------------------------------------------ +int CImageManager::GetLocalNewTextures(FS_FileSet &files) +{ + return FS.file_list(files, _import_, FS_ListFiles | FS_RootOnly, "*.tga,*.bmp,*.dds,*.png,*.jpg"); +} +//------------------------------------------------------------------------------ +// проверяет соответствие размера текстур +// input: список файлов для тестирования +// output: соответствие +//------------------------------------------------------------------------------ +#define SQR(a) ((a) * (a)) +BOOL CImageManager::CheckCompliance(LPCSTR fname, int & completed ) +{ + completed = 0; + U32Vec data; + u32 w, h, a; + if (!Stbi_Load(fname, data, w, h, a)) + return FALSE; + if ((1 == w) || (1 == h)) + return TRUE; + + u32 w_2 = (1 == w) ? w : w / 2; + u32 h_2 = (1 == h) ? h : h / 2; + // scale down(lanczos3) and up (bilinear, as video board) + u32 *pScaled = (u32 *)(xr_malloc((w_2) * (h_2)*4)); + u32 *pRestored = (u32 *)(xr_malloc(w * h * 4)); + try + { + imf_Process(pScaled, w_2, h_2, data.data(), w, h, imf_lanczos3); + imf_Process(pRestored, w, h, pScaled, w_2, h_2, imf_filter); + } + catch (...) + { + Msg("* ERROR: imf_Process"); + xr_free(pScaled); + xr_free(pRestored); + return FALSE; + } + // Analyze + float difference = 0; + float maximal = 0; + for (u32 p = 0; p < data.size(); p++) + { + Fcolor c1, c2; + c1.set(data[p]); + c2.set(pRestored[p]); + float E = 0; + if (a) + E = sqrtf(SQR(c1.r - c2.r) + SQR(c1.g - c2.g) + SQR(c1.b - c2.b) + SQR(c1.a - c2.a)) * c1.a; // q(4) + else + E = sqrtf(SQR(c1.r - c2.r) + SQR(c1.g - c2.g) + SQR(c1.b - c2.b)); // q(3) + difference += E; + maximal = _max(maximal, E); + } + difference /= float(data.size()); + difference = difference / (a ? 2.f : sqrtf(3.f)); + difference = difference * 100.f; + clamp(difference, 0.f, 100.f); + completed = iFloor(difference) * 1000; + maximal = maximal / (a ? 2.f : sqrtf(3.f)); + maximal = maximal * 100.f; + clamp(maximal, 0.f, 100.f); + completed += iFloor(maximal); + + // free + xr_free(pScaled); + xr_free(pRestored); + return TRUE; +} +void CImageManager::CheckCompliance(FS_FileSet &files, FS_FileSet & completed ) +{ + SPBItem *pb = UI->ProgressStart(static_cast(files.size()), "Check texture compliance: "); + auto it = files.begin(); + auto _E = files.end(); + for (; it != _E; it++) + { + int val = 0; + string_path fname; + FS.update_path(fname, _textures_, it->name.c_str()); + if (!CheckCompliance(fname, val)) + ELog.Msg(mtError, "Bad texture: '%s'", it->name.c_str()); + FS_File F(*it); + F.attrib = val; + completed .insert(F); + pb->Inc(); + if (UI->NeedAbort()) + break; + } + UI->ProgressEnd(pb); +} + +IC void GET(U32Vec &pixels, u32 w, u32 h, u32 x, u32 y, u32 ref, u32 &count, u32 &r, u32 &g, u32 &b) +{ + // wrap pixels + if (x >= w) + return; + if (y >= h) + return; + + // summarize + u32 pixel = pixels[y * w + x]; + if (color_get_A(pixel) <= ref) + return; + + r += color_get_R(pixel); + g += color_get_G(pixel); + b += color_get_B(pixel); + count++; +} + +BOOL _ApplyBorders(U32Vec &pixels, u32 w, u32 h, u32 ref) +{ + BOOL bNeedContinue = FALSE; + + try + { + U32Vec result; + result.resize(w * h); + + CopyMemory(result.data(), pixels.data(), w * h * 4); + for (u32 y = 0; y < h; y++) + { + for (u32 x = 0; x < w; x++) + { + if (color_get_A(pixels[y * w + x]) == 0) + { + u32 C = 0, r = 0, g = 0, b = 0; + GET(pixels, w, h, x - 1, y - 1, ref, C, r, g, b); + GET(pixels, w, h, x, y - 1, ref, C, r, g, b); + GET(pixels, w, h, x + 1, y - 1, ref, C, r, g, b); + + GET(pixels, w, h, x - 1, y, ref, C, r, g, b); + GET(pixels, w, h, x + 1, y, ref, C, r, g, b); + + GET(pixels, w, h, x - 1, y + 1, ref, C, r, g, b); + GET(pixels, w, h, x, y + 1, ref, C, r, g, b); + GET(pixels, w, h, x + 1, y + 1, ref, C, r, g, b); + + if (C) + { + result[y * w + x] = color_rgba(r / C, g / C, b / C, ref); + bNeedContinue = TRUE; + } + } + } + } + CopyMemory(pixels.data(), result.data(), h * w * 4); + } + catch (...) + { + Msg("* ERROR: ApplyBorders"); + } + return bNeedContinue; +} + +void CImageManager::ApplyBorders(U32Vec &tgt_data, u32 w, u32 h) +{ + U32Vec border_pixels = tgt_data; + for (U32It it = tgt_data.begin(); it != tgt_data.end(); it++) + *it = (color_get_A(*it) > 200) ? subst_alpha(*it, 0xFF) : subst_alpha(*it, 0x00); + for (u32 ref = 254; ref > 0; ref--) + _ApplyBorders(tgt_data, w, h, ref); + for (int t = 0; t < int(tgt_data.size()); t++) + tgt_data[t] = subst_alpha(tgt_data[t], color_get_A(border_pixels[t])); +} + +BOOL CImageManager::CreateOBJThumbnail(LPCSTR tex_name, CEditableObject *obj, int age) +{ + BOOL bResult = TRUE; + // save render params + Flags32 old_flag = psDeviceFlags; + // set render params + psDeviceFlags.set(rsStatistic | rsDrawGrid, FALSE); + // u32 cc = EPrefs.scene_clear_color; + // EPrefs.scene_clear_color = 0x00333333; + + U32Vec pixels; + u32 w = 512, h = 512; + if (EDevice.MakeScreenshot(pixels, w, h)) + { + EObjectThumbnail tex(tex_name, false); + tex.CreateFromData(pixels.data(), w, h, obj->GetFaceCount(), obj->GetVertexCount()); + tex.Save(age); + } + else + { + bResult = FALSE; + ELog.DlgMsg(mtError, "Can't make screenshot."); + } + + // restore render params + psDeviceFlags = old_flag; + // EPrefs.scene_clear_color = cc; + return bResult; +} + +void CImageManager::RemoveTexture(LPCSTR fname, EItemType type) +{ + if (TYPE_FOLDER == type) + { + FS.dir_delete(_textures_, fname, FALSE); + FS.dir_delete(_game_textures_, fname, FALSE); + return; + } + else if (TYPE_OBJECT == type) + { + xr_string src_name; + src_name = EFS.ChangeFileExt(fname, ".tga"); + if (FS.exist(_textures_, src_name.c_str())) + { + xr_string base_name = EFS.ChangeFileExt(fname, ""); + xr_string thm_name = EFS.ChangeFileExt(fname, ".thm"); + xr_string game_name = EFS.ChangeFileExt(fname, ".dds"); + xr_string game_name2 = EFS.ChangeFileExt(fname, "#.dds"); + // source + FS.file_delete(_textures_, src_name.c_str()); + // thumbnail + FS.file_delete(_textures_, thm_name.c_str()); + // game + FS.file_delete(_game_textures_, game_name.c_str()); + // game 2 + FS.file_delete(_game_textures_, game_name2.c_str()); + return; + } + } +} + +EImageThumbnail *CImageManager::CreateThumbnail(LPCSTR src_name, ECustomThumbnail::THMType type, bool bLoad) +{ + switch (type) + { + case ECustomThumbnail::ETObject: + return xr_new(src_name, bLoad); + case ECustomThumbnail::ETTexture: + return xr_new(src_name, bLoad); + default: + NODEFAULT; + } + return 0; +} + +//------------------------------------------------------------------------------ +// если передан параметр modif - обновляем DX-Surface only и только из списка +// иначе полная синхронизация +//------------------------------------------------------------------------------ +void CImageManager::RefreshTextures(AStringVec *modif) +{ + if (FS.can_write_to_alias(_textures_)) + { + if (modif) + EDevice.Resources->ED_UpdateTextures(modif); + else + { + UI->SetStatus("Refresh textures..."); + AStringVec modif_files; + ImageLib.SynchronizeTextures(true, true, false, 0, &modif_files); + EDevice.Resources->ED_UpdateTextures(&modif_files); + UI->SetStatus(""); + } + } + else + { + Log("#!You don't have permisions to modify textures."); + } +} + +void pb_callback(void *data, float &v) +{ + SPBItem *PB = (SPBItem *)(data); + PB->Update(v); +} + +BOOL CImageManager::CreateSmallerCubeMap(LPCSTR src_name, LPCSTR dst_name) +{ + U32Vec data; + u32 w, wf, h, a; + string_path full_name; + FS.update_path(full_name, _textures_, src_name); + strcat(full_name, ".tga"); + + if (Stbi_Load(full_name, data, wf, h, a)) + { + w = wf / 6; + u32 sm_w = 32, sm_wf = 6 * sm_w, sm_h = 32; + if (!btwIsPow2(h) || (h * 6 != wf) || (wf < sm_wf) || (h < sm_h)) + { + ELog.Msg(mtError, "Texture '%s' - invalid size: [%d, %d]", src_name, wf, h); + return FALSE; + } + // generate smaller + U32Vec sm_data(sm_wf * sm_h, 0); + SPBItem *PB = UI->ProgressStart(1.f, "Cube Map: scale image..."); + CTimer T; + T.Start(); + ETOOLS::SimplifyCubeMap(data.data(), w, h, sm_data.data(), sm_w, sm_h, 16.f, pb_callback, PB); + float tm_scm = T.GetElapsed_sec(); + UI->ProgressEnd(PB); + // write texture + string_path out_name; + FS.update_path(out_name, _game_textures_, dst_name); + strcat(out_name, ".dds"); + + STextureParams tp; + tp.width = sm_wf; + tp.height = sm_h; + tp.fmt = STextureParams::tfRGBA; + tp.type = STextureParams::ttCubeMap; + tp.flags.zero(); + if (!MakeGameTexture(out_name, &*sm_data.begin(), tp)) + return FALSE; + ELog.DlgMsg(mtInformation, "Smaller cubemap successfylly created [%3.2f sec].", tm_scm); + return TRUE; + } + else + { + ELog.Msg(mtError, "Can't load texture '%s'.", src_name); + } + return FALSE; +} diff --git a/src/editors/xrECore/Editor/ImageManager.h b/src/editors/xrECore/Editor/ImageManager.h new file mode 100644 index 00000000000..51f3965f43d --- /dev/null +++ b/src/editors/xrECore/Editor/ImageManager.h @@ -0,0 +1,74 @@ +//--------------------------------------------------------------------------- +#ifndef ImageManagerH +#define ImageManagerH + +class CEditableObject; +#include "EThumbnail.h" +struct SSimpleImage +{ + shared_str name; + DEFINE_VECTOR(U32Vec, DATAVec, DATAIt); + DATAVec layers; + u32 w, h, a; + u32 tag; + int LongestEdge() const { return (w > h) ? w : h; } + int Area() const { return w * h; } +}; +IC bool operator==(const SSimpleImage &a, shared_str nm) { return a.name == nm; } +IC bool operator<(const SSimpleImage &a, const SSimpleImage &b) { return a.name < b.name; } +DEFINE_VECTOR(SSimpleImage, SSimpleImageVec, SSimpleImageVecIt); + +class ECORE_API CImageManager +{ + +public: + bool MakeGameTexture(ETextureThumbnail *THM, LPCSTR game_name, u32 *data); + static void MakeThumbnailImage(ETextureThumbnail *THM, u32 *data, u32 w, u32 h, u32 a); + +public: + CImageManager() { ; } + ~CImageManager() { ; } + // texture routines + void RemoveTexture(LPCSTR fname, EItemType type); + BOOL CheckCompliance(LPCSTR fname, int & completed); + void CheckCompliance(FS_FileSet &files, FS_FileSet & completed); + int GetTextures(FS_FileSet &files, BOOL bFolder = FALSE); + int GetTexturesRaw(FS_FileSet &files, BOOL bFolder = FALSE); + // int GetServerModifiedTextures(CLocatorAPI::files_query& files); + int GetLocalNewTextures(FS_FileSet &files); + void SafeCopyLocalToServer(FS_FileSet &files); + + void SynchronizeTextures(bool sync_thm, bool sync_game, bool bForceGame, FS_FileSet *source_map, AStringVec *sync_list_without_extention, FS_FileSet *modif_map = 0, bool bForceBaseAge = false); + void SynchronizeTexture(LPCSTR tex_name, int age); + // void ChangeFileAgeTo (FS_FileSet* source_map, int age); + // make/update routines + bool MakeGameTexture(LPCSTR game_name, u32 *data, const STextureParams &tp); + void CreateTextureThumbnail(ETextureThumbnail *THM, const xr_string &src_name, LPCSTR path = 0, bool bSetDefParam = true); + BOOL CreateOBJThumbnail(LPCSTR tex_name, CEditableObject *obj, int age); + void CreateLODTexture(CEditableObject *object, U32Vec &lod_pixels, U32Vec &nm_pixels, u32 tgt_w, u32 tgt_h, int samples, int quality); + void CreateLODTexture(CEditableObject *object, LPCSTR tex_name, u32 tgt_w, u32 tgt_h, int samples, int age, int quality); + void CreateGameTexture(LPCSTR src_name, ETextureThumbnail *thumb = 0); + bool LoadTextureData(LPCSTR src_name, U32Vec &data, u32 &w, u32 &h, int *age = 0); + + // result 0-can't fit images, 1-ok, -1 can't load image + void MergedTextureRemapUV(float &dest_u, float &dest_v, float src_u, float src_v, const Fvector2 &offs, const Fvector2 &scale, bool bRotate); + int CreateMergedTexture(const RStringVec &src_names, LPCSTR dest_name, STextureParams::ETFormat fmt, int dest_width, int dest_height, Fvector2Vec &dest_offset, Fvector2Vec &dest_scale, boolVec &dest_rotate, U32Vec &remap); + int CreateMergedTexture(const RStringVec &src_names, LPCSTR dest_name, STextureParams::ETFormat fmt, int dest_width_min, int dest_width_max, int dest_height_min, int dest_height_max, Fvector2Vec &dest_offset, Fvector2Vec &dest_scale, boolVec &dest_rotate, U32Vec &remap); + int CreateMergedTexture(u32 layer_cnt, SSimpleImageVec &src_images, SSimpleImage &dst_image, int dest_width, int dest_height, Fvector2Vec &dest_offset, Fvector2Vec &dest_scale, boolVec &dest_rotate, U32Vec &remap); + int CreateMergedTexture(u32 layer_cnt, SSimpleImageVec &src_images, SSimpleImage &dst_image, int dest_width_min, int dest_width_max, int dest_height_min, int dest_height_max, Fvector2Vec &dest_offset, Fvector2Vec &dest_scale, boolVec &dest_rotate, U32Vec &remap); + void ApplyBorders(U32Vec &tgt_data, u32 w, u32 h); + + EImageThumbnail *CreateThumbnail(LPCSTR src_name, ECustomThumbnail::THMType type, bool bLoad = true); + + void RefreshTextures(AStringVec *modif); + + xr_string UpdateFileName(xr_string &fn); + + void WriteAssociation(CInifile *ltx_ini, LPCSTR base_name, const STextureParams &fmt); + + BOOL CreateSmallerCubeMap(LPCSTR src_name, LPCSTR dst_name); +}; + +extern ECORE_API CImageManager ImageLib; +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/xrECore/Editor/ImageManagerDO.cpp b/src/editors/xrECore/Editor/ImageManagerDO.cpp new file mode 100644 index 00000000000..92e9cbd22e0 --- /dev/null +++ b/src/editors/xrECore/Editor/ImageManagerDO.cpp @@ -0,0 +1,328 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "ImageManager.h" + +IC void blit(u32 *dest, u32 ds_x, u32 ds_y, u32 *src, u32 ss_x, u32 ss_y, u32 px, u32 py) +{ + R_ASSERT(ds_x >= (ss_x + px)); + R_ASSERT(ds_y >= (ss_y + py)); + for (u32 y = 0; y < ss_y; y++) + for (u32 x = 0; x < ss_x; x++) + { + u32 dx = px + x; + u32 dy = py + y; + dest[dy * ds_x + dx] = src[y * ss_x + x]; + } +} + +IC void blit_r(u32 *dest, u32 ds_x, u32 ds_y, u32 *src, u32 ss_x, u32 ss_y, u32 px, u32 py) +{ + R_ASSERT(ds_x >= (ss_y + px)); + R_ASSERT(ds_y >= (ss_x + py)); + for (u32 y = 0; y < ss_y; y++) + for (u32 x = 0; x < ss_x; x++) + { + u32 dx = px + y; + u32 dy = py + x; + dest[dy * ds_x + dx] = src[y * ss_x + x]; + } +} +// Rendering of rect +IC void _rect_register(U8Vec &mask, int dest_width, int dest_height, Irect &R) +{ + u32 s_x = R.width() + 1; + u32 s_y = R.height() + 1; + + // Normal (and fastest way) + for (u32 y = 0; y < s_y; y++) + { + u8 *P = mask.data() + (y + R.lt.y) * dest_width + R.lt.x; // destination scan-line + for (u32 x = 0; x < s_x; x++, P++) + *P = 0xff; + } +} + +// Test of per-pixel intersection (surface test) +IC bool _rect_test(U8Vec &mask, int dest_width, int dest_height, Irect &R) +{ + u32 s_x = R.width() + 1; + u32 s_y = R.height() + 1; + + if (R.rb.x >= dest_width) + return false; + if (R.rb.y >= dest_height) + return false; + // Normal (and fastest way) + for (u32 y = 0; y < s_y; y++) + { + u8 *P = mask.data() + (y + R.lt.y) * dest_width + R.lt.x; // destination scan-line + for (u32 x = 0; x < s_x; x++, P++) + if (*P) + return false; + } + // It's OK to place it + return true; +} + +// Check for intersection +IC bool _rect_place(U8Vec &mask, int dest_width, int dest_height, Irect &r, BOOL &bRotated) +{ + Irect R; + + // Normal + if ((r.rb.x < dest_width) && (r.rb.y < dest_height)) + { + u32 x_max = dest_width - r.rb.x; + u32 y_max = dest_height - r.rb.y; + bRotated = FALSE; + for (u32 _Y = 0; _Y < y_max; _Y++) + { + for (u32 _X = 0; _X < x_max; _X++) + { + if (mask[_Y * dest_width + _X]) + continue; + R.set(_X, _Y, _X + r.rb.x, _Y + r.rb.y); + if (_rect_test(mask, dest_width, dest_height, R)) + { + _rect_register(mask, dest_width, dest_height, R); + r.set(R); + return true; + } + } + } + } + + // Rotated + if ((r.rb.y < dest_width) && (r.rb.x < dest_height)) + { + u32 x_max = dest_width - r.rb.y; + u32 y_max = dest_height - r.rb.x; + bRotated = TRUE; + for (u32 _Y = 0; _Y < y_max; _Y++) + { + for (u32 _X = 0; _X < x_max; _X++) + { + if (mask[_Y * dest_width + _X]) + continue; + R.set(_X, _Y, _X + r.rb.y, _Y + r.rb.x); + if (_rect_test(mask, dest_width, dest_height, R)) + { + _rect_register(mask, dest_width, dest_height, R); + r.set(R); + return true; + } + } + } + } + + return false; +}; + +bool item_area_sort_pred(const SSimpleImage &item0, const SSimpleImage &item1) { return ((item0.Area() > item1.Area()) || (item0.LongestEdge() > item1.LongestEdge())); } +extern bool Stbi_Load(LPCSTR full_name, U32Vec &data, u32 &w, u32 &h, u32 &a); + +int CImageManager::CreateMergedTexture(u32 layer_cnt, SSimpleImageVec &src_images, SSimpleImage &dst_image, int dest_width, int dest_height, Fvector2Vec &dest_offset, Fvector2Vec &dest_scale, boolVec &dest_rotate, U32Vec &dest_remap) +{ + if (src_images.empty()) + return -1; + + dest_offset.clear(); + dest_scale.clear(); + dest_rotate.clear(); + dest_remap.resize(src_images.size()); + + SSimpleImage::DATAVec dest_layers(layer_cnt); + for (SSimpleImage::DATAIt layer_it = dest_layers.begin(); layer_it != dest_layers.end(); layer_it++) + layer_it->resize(dest_width * dest_height, 0); + U8Vec dest_mask(dest_width * dest_height, 0); + + int max_area = dest_width * dest_height; + int calc_area = 0; + + for (SSimpleImageVecIt s_it = src_images.begin(); s_it != src_images.end(); s_it++) + { + s_it->tag = s_it - src_images.begin(); + calc_area += (s_it->w * s_it->h); + if (calc_area > max_area) + return 0; + } + + std::sort(src_images.begin(), src_images.end(), item_area_sort_pred); + + for (auto s_it = src_images.begin(); s_it != src_images.end(); s_it++) + dest_remap[s_it->tag] = s_it - src_images.begin(); + + for (auto s_it = src_images.begin(); s_it != src_images.end(); s_it++) + { + Irect R; + R.set(0, 0, s_it->w - 1, s_it->h - 1); + BOOL bRotated; + if (!_rect_place(dest_mask, dest_width, dest_height, R, bRotated)) + return 0; + Fvector2 offs, scale; + offs.x = float(R.lt.x) / float(dest_width); + offs.y = float(R.lt.y) / float(dest_height); + scale.x = float(R.width() + 1) / float(dest_width); + scale.y = float(R.height() + 1) / float(dest_height); + dest_offset.push_back(offs); + dest_scale.push_back(scale); + dest_rotate.push_back(bRotated); + // Perform BLIT + VERIFY(s_it->layers.size() == layer_cnt); + for (u32 k = 0; k < layer_cnt; k++) + { + if (!bRotated) + blit(dest_layers[k].data(), dest_width, dest_height, s_it->layers[k].data(), s_it->w, s_it->h, R.lt.x, R.lt.y); + else + blit_r(dest_layers[k].data(), dest_width, dest_height, s_it->layers[k].data(), s_it->w, s_it->h, R.lt.x, R.lt.y); + } + } + + dst_image.w = dest_width; + dst_image.h = dest_height; + dst_image.a = TRUE; + dst_image.layers = dest_layers; + + return 1; +} + +int CImageManager::CreateMergedTexture(u32 layer_cnt, SSimpleImageVec &src_images, SSimpleImage &dst_image, int dest_width_min, int dest_width_max, int dest_height_min, int dest_height_max, Fvector2Vec &dest_offset, Fvector2Vec &dest_scale, boolVec &dest_rotate, U32Vec &dest_remap) +{ + int res = 0; + int w = dest_width_min; + int h = dest_height_min; + do + { + res = ImageLib.CreateMergedTexture(layer_cnt, src_images, dst_image, w, h, dest_offset, dest_scale, dest_rotate, dest_remap); + if (0 == res) + { + if ((w <= h) && (w < dest_width_max)) + w *= 2; + else if ((h < w) && (h < dest_height_max)) + h *= 2; + else + break; + } + } while ((0 == res) && (w <= dest_width_max) && (h <= dest_height_max)); + return res; +} + +int CImageManager::CreateMergedTexture(const RStringVec &_names, LPCSTR dest_name, STextureParams::ETFormat fmt, int dest_width, int dest_height, Fvector2Vec &dest_offset, Fvector2Vec &dest_scale, boolVec &dest_rotate, U32Vec &dest_remap) +{ + if (_names.empty()) + return -1; + + dest_offset.clear(); + dest_scale.clear(); + dest_rotate.clear(); + + RStringVec src_names = _names; + dest_remap.resize(src_names.size()); + std::sort(src_names.begin(), src_names.end()); + src_names.erase(std::unique(src_names.begin(), src_names.end()), src_names.end()); + + U32Vec dest_pixels(dest_width * dest_height, 0); + U8Vec dest_mask(dest_width * dest_height, 0); + + int max_area = dest_width * dest_height; + int calc_area = 0; + + SSimpleImageVec src_items(src_names.size()); + SSimpleImageVecIt s_it = src_items.begin(); + for (RStringVecIt n_it = src_names.begin(); n_it != src_names.end(); n_it++, s_it++) + { + s_it->layers.resize(1); + string_path t_name; + //. FS.update_path (t_name,_textures_,**n_it); + FS.update_path(t_name, _game_textures_, **n_it); + if (!Stbi_Load(EFS.ChangeFileExt(t_name, ".dds" /*".tga"*/).c_str(), s_it->layers.back(), s_it->w, s_it->h, s_it->a)) + { + ELog.DlgMsg(mtError, "Can't load texture '%s'. Check file existence.", **n_it); + return -1; + } + calc_area += (s_it->w * s_it->h); + if (calc_area > max_area) + return 0; + s_it->name = *n_it; + } + + std::sort(src_items.begin(), src_items.end(), item_area_sort_pred); + + for (u32 k = 0; k < _names.size(); k++) + { + shared_str nm = _names[k]; + s_it = std::find(src_items.begin(), src_items.end(), nm); + VERIFY(s_it != src_items.end()); + dest_remap[k] = s_it - src_items.begin(); + } + + for (s_it = src_items.begin(); s_it != src_items.end(); s_it++) + { + Irect R; + R.set(0, 0, s_it->w - 1, s_it->h - 1); + BOOL bRotated; + if (!_rect_place(dest_mask, dest_width, dest_height, R, bRotated)) + return 0; + Fvector2 offs, scale; + offs.x = float(R.lt.x) / float(dest_width); + offs.y = float(R.lt.y) / float(dest_height); + scale.x = float(R.width() + 1) / float(dest_width); + scale.y = float(R.height() + 1) / float(dest_height); + dest_offset.push_back(offs); + dest_scale.push_back(scale); + dest_rotate.push_back(bRotated); + // Perform BLIT + if (!bRotated) + blit(dest_pixels.data(), dest_width, dest_height, s_it->layers.back().data(), s_it->w, s_it->h, R.lt.x, R.lt.y); + else + blit_r(dest_pixels.data(), dest_width, dest_height, s_it->layers.back().data(), s_it->w, s_it->h, R.lt.x, R.lt.y); + } + + // all right. make texture. + xr_string fn = ChangeFileExt(dest_name, ".dds"); + STextureParams tp; + tp.width = dest_width; + tp.height = dest_height; + tp.fmt = fmt; + tp.type = STextureParams::ttImage; + tp.mip_filter = STextureParams::kMIPFilterAdvanced; + tp.flags.assign(STextureParams::flDitherColor); + MakeGameTexture(fn.c_str(), dest_pixels.data(), tp); + return 1; +} + +int CImageManager::CreateMergedTexture(const RStringVec &src_names, LPCSTR dest_name, STextureParams::ETFormat fmt, int dest_width_min, int dest_width_max, int dest_height_min, int dest_height_max, Fvector2Vec &dest_offset, Fvector2Vec &dest_scale, boolVec &dest_rotate, U32Vec &remap) +{ + int res = 0; + int w = dest_width_min; + int h = dest_height_min; + do + { + res = ImageLib.CreateMergedTexture(src_names, dest_name, fmt, w, h, dest_offset, dest_scale, dest_rotate, remap); + if (0 == res) + { + if ((w <= h) && (w < dest_width_max)) + w *= 2; + else if ((h < w) && (h < dest_height_max)) + h *= 2; + else + break; + } + } while ((0 == res) && (w <= dest_width_max) && (h <= dest_height_max)); + return res; +} + +void CImageManager::MergedTextureRemapUV(float &dest_u, float &dest_v, float src_u, float src_v, const Fvector2 &offs, const Fvector2 &scale, bool bRotate) +{ + if (bRotate) + { + dest_u = scale.x * src_v + offs.x; + dest_v = scale.y * src_u + offs.y; + } + else + { + dest_u = scale.x * src_u + offs.x; + dest_v = scale.y * src_v + offs.y; + } +} diff --git a/src/editors/xrECore/Editor/ImageManagerLOD.cpp b/src/editors/xrECore/Editor/ImageManagerLOD.cpp new file mode 100644 index 00000000000..d3947fc57fd --- /dev/null +++ b/src/editors/xrECore/Editor/ImageManagerLOD.cpp @@ -0,0 +1,495 @@ +#include "stdafx.h" +#include "ImageManager.h" +#include "editobject.h" +#include "editmesh.h" +#include "ui_main.h" + +#include "xrEngine/xrHemisphere.h" +#include "xrEngine/xrImage_Resampler.h" +#include "..\Engine\Image.h" + +/* +IC void SetCamera(float angle, const Fvector& C, float height, float radius, float dist) +{ + Fvector D; + Fvector hpb; + Fmatrix P; + + hpb.set (angle,0,0); + D.setHP (hpb.x,hpb.y); + D.mul (-dist); + D.add (C); + + float ta = height/dist; + float asp = height/radius; + float fp = dist+4.f*radius; + float np = dist-4.f*radius; clamp(np,0.1f,fp); + EDevice.m_Camera.Set (hpb,D); + P.build_projection_HAT (ta,asp,np,fp); + RCache.set_xform_project(P); +} + +IC void CopyLODImage(U32Vec& src, U32Vec& dest, u32 src_w, u32 src_h, int id, int pitch) +{ + for (u32 y=0; yscene_clear_color; + EPrefs.scene_clear_color = 0x0000000; + psDeviceFlags.zero (); + psDeviceFlags.set (rsFilterLinear,TRUE); + EDevice.dwFillMode = D3DFILL_SOLID; + EDevice.dwShadeMode = D3DSHADE_GOURAUD; + + SetCamera(0,C,S.y,R,D); + + for (int frame=0; framee_mesh->GetSurfaceByFaceID(R->tag); + VERIFY(surf); + Shader_xrLC *c_sh = EDevice.ShaderXRLC.Get(surf->_ShaderXRLCName()); + if (!c_sh->flags.bRendering) + return FALSE; + const Fvector2 *cuv[3]; + R->e_mesh->GetFaceTC(R->tag, cuv); + + // barycentric coords + // note: W,U,V order + Fvector B; + B.set(1.0f - R->u - R->v, R->u, R->v); + + // calc UV + Fvector2 uv; + uv.x = cuv[0]->x * B.x + cuv[1]->x * B.y + cuv[2]->x * B.z; + uv.y = cuv[0]->y * B.x + cuv[1]->y * B.y + cuv[2]->y * B.z; + + int U = iFloor(uv.x * float(surf->m_ImageData->w) + .5f); + int V = iFloor(uv.y * float(surf->m_ImageData->h) + .5f); + U %= surf->m_ImageData->w; + if (U < 0) + U += surf->m_ImageData->w; + V %= surf->m_ImageData->h; + if (V < 0) + V += surf->m_ImageData->h; + + /* + // float filter_core[3][3]={{0.0125,0.0125,0.0125},{0.0125,0.9,0.0125},{0.0125,0.0125,0.0125}}; + // float filter_core[3][3]={{0.0625,0.0625,0.0625},{0.0625,0.5,0.0625},{0.0625,0.0625,0.0625}}; + // float filter_core[3][3]={{0,0,0},{0,1,0},{0,0,0}}; + Fvector4 C={0,0,0,0}; + u32 cnt=0; + for (int y=-1; y<=1; y++){ + int v = V+y; + if (v<0||v>=(int)surf->m_ImageData->h) continue; + for (int x=-1; x<=1; x++){ + int u = U+x; + if (u<0||u>=(int)surf->m_ImageData->w) continue; + Fvector4 c; + color = surf->m_ImageData->layers.back()[v*surf->m_ImageData->w+u]; + float f = filter_core[x+1][y+1]; + c.set (f*color_get_R(color),f*color_get_G(color),f*color_get_B(color),f*color_get_A(color)); + C.add (c); + cnt++; + } + } + // if (0!=cnt) C.div(cnt); + color = color_rgba(C.x,C.y,C.z,C.w); + */ + color = surf->m_ImageData->layers.back()[V * surf->m_ImageData->w + U]; + alpha = color_get_A(color); + return TRUE; +} + +struct SBuildLight +{ + Flight light; + float energy; +}; +DEFINE_VECTOR(SBuildLight, BLVec, BLIt); +ICF static void simple_hemi_callback(float x, float y, float z, float E, LPVOID P) +{ + BLVec *dst = (BLVec *)P; + SBuildLight T; + T.energy = E; + T.light.direction.set(x, y, z); + dst->push_back(T); +} + +const u32 lod_ss_quality = 8; + +void CreateLODSamples(const Fbox &bbox, U32Vec &tgt_data, u32 tgt_w, u32 tgt_h) +{ + U32Vec s_pixels, d_pixels; + Fmatrix save_projection = EDevice.mProject; + Fmatrix save_view = EDevice.mView; + + // save render params + Flags32 old_flag = psDeviceFlags; + u32 old_dwFillMode = EDevice.dwFillMode; + u32 old_dwShadeMode = EDevice.dwShadeMode; + // set render params + + u32 cc = EPrefs->scene_clear_color; + EPrefs->scene_clear_color = 0x0000000; + psDeviceFlags.zero(); + psDeviceFlags.set(rsFilterLinear, TRUE); + EDevice.dwFillMode = D3DFILL_SOLID; + EDevice.dwShadeMode = D3DSHADE_GOURAUD; + + Fvector vP, vD, vN, vR; + Fmatrix mV, mP; + + Fvector S; + bbox.getradius(S); + float R = 2.f * _max(S.x, S.z); + + u32 pitch = tgt_w * LOD_SAMPLE_COUNT; + tgt_data.resize(pitch * tgt_h); + for (int frame = 0; frame < LOD_SAMPLE_COUNT; frame++) + { + float angle = frame * (PI_MUL_2 / LOD_SAMPLE_COUNT); + + Fbox bb = bbox; + // build camera matrix + bb.getcenter(vP); + vN.set(0.f, 1.f, 0.f); + vD.setHP(angle, 0); + vR.crossproduct(vN, vD); + mV.build_camera_dir(vP, vD, vN); + bb.xform(mV); + // build project matrix + mP.build_projection_ortho(R, bb.vMax.y - bb.vMin.y, bb.vMin.z, bb.vMax.z); + RCache.set_xform_project(mP); + RCache.set_xform_view(mV); + EDevice.mFullTransform.mul(mP, mV); + EDevice.MakeScreenshot(s_pixels, tgt_w * lod_ss_quality, tgt_h * lod_ss_quality); + d_pixels.resize(tgt_w * tgt_h); + imf_Process(d_pixels.data(), tgt_w, tgt_h, s_pixels.data(), tgt_w * lod_ss_quality, tgt_h * lod_ss_quality, imf_box); + // copy LOD to final + for (u32 y = 0; y < tgt_h; y++) + CopyMemory(tgt_data.data() + y * pitch + frame * tgt_w, d_pixels.data() + y * tgt_w, tgt_w * sizeof(u32)); + } + + // flip data + for (u32 y = 0; y < tgt_h / 2; y++) + { + u32 y2 = tgt_h - y - 1; + for (u32 x = 0; x < pitch; x++) + { + std::swap(tgt_data[y * pitch + x], tgt_data[y2 * pitch + x]); + } + } + + // restore render params + EDevice.dwFillMode = old_dwFillMode; + EDevice.dwShadeMode = old_dwShadeMode; + psDeviceFlags = old_flag; + EPrefs->scene_clear_color = cc; + + RCache.set_xform_view(save_view); + RCache.set_xform_project(save_projection); +} + +void CImageManager::CreateLODTexture(CEditableObject *OBJECT, U32Vec &lod_pixels, U32Vec &nm_pixels, u32 tgt_w, u32 tgt_h, int _samples, int quality) +{ + // build hemi light + BLVec simple_hemi; + // fill simple hemi + simple_hemi.clear(); + xrHemisphereBuild(1, 2.f, simple_hemi_callback, &simple_hemi); + + Fbox bb = OBJECT->GetBox(); + + // build lod normals + lod_pixels.resize(LOD_IMAGE_SIZE * LOD_IMAGE_SIZE * LOD_SAMPLE_COUNT, 0); + nm_pixels.resize(LOD_IMAGE_SIZE * LOD_IMAGE_SIZE * LOD_SAMPLE_COUNT, 0); + U32Vec hemi_tmp(LOD_IMAGE_SIZE * LOD_IMAGE_SIZE * LOD_SAMPLE_COUNT, 0); + Fvector o_center, o_size; + Fmatrix M, Mi; + bb.getradius(o_size); + bb.getcenter(o_center); + SPBItem *PB = UI->ProgressStart(LOD_SAMPLE_COUNT * LOD_IMAGE_SIZE, OBJECT->GetName()); + float dW = _max(o_size.x, o_size.z) / (LOD_IMAGE_SIZE / 2); + float dH = o_size.y / (LOD_IMAGE_SIZE / 2); + float dR = bb.getradius(); + float d2R = dR * 2.f; + CreateLODSamples(bb, lod_pixels, LOD_IMAGE_SIZE, LOD_IMAGE_SIZE); + + float tN = 0.f, tH = 0.f, tT = 0.f, tR = 0.f; + + float LOD_CALC_SAMPLES = static_cast(quality); + s32 LOD_CALC_SAMPLES_LIM = quality / 2; + + xr_vector loadedSurfaces; + + // preload textures + for (CSurface* surf: OBJECT->Surfaces()) + { + Shader_xrLC *c_sh = EDevice.ShaderXRLC.Get(surf->_ShaderXRLCName()); + if (!c_sh->flags.bRendering) + continue; + + if (!surf->m_ImageData) + { + surf->CreateImageData(); + loadedSurfaces.push_back(surf); + } + } + + // calculate + for (u32 sample_idx = 0; sample_idx < LOD_SAMPLE_COUNT; sample_idx++) + { + float angle = sample_idx * (PI_MUL_2 / LOD_SAMPLE_COUNT); + M.setXYZ(0, angle, 0); + M.translate_over(o_center); + Mi.invert(M); + + for (s32 iH = 0; iH < LOD_IMAGE_SIZE; iH++) + { + PB->Inc(); + float Y = (iH - (LOD_IMAGE_SIZE - 1) / 2) * dH; + + for (s32 iW = 0; iW < LOD_IMAGE_SIZE; iW++) + { + float X = (iW - (LOD_IMAGE_SIZE) / 2) * dW; + + u32 pixel = (LOD_IMAGE_SIZE - iH - 1) * LOD_SAMPLE_COUNT * LOD_IMAGE_SIZE + LOD_IMAGE_SIZE * sample_idx + iW; + u32 &tgt_c = lod_pixels[pixel]; + u32 &tgt_n = nm_pixels[pixel]; + u32 &tgt_h = hemi_tmp[pixel]; + + FvectorVec n_vec; + Fvector4Vec sample_pt_vec; + Fvector start; + CTimer TT, TT1; + TT.Start(); + SPickQuery PQ; + + for (s32 iiH = -LOD_CALC_SAMPLES_LIM; iiH <= LOD_CALC_SAMPLES_LIM; iiH++) + { + float dY = iiH * (dH / LOD_CALC_SAMPLES); + + for (s32 iiW = -LOD_CALC_SAMPLES_LIM; iiW <= LOD_CALC_SAMPLES_LIM; iiW++) + { + float dX = iiW * (dW / LOD_CALC_SAMPLES); + start.set(X + dX, Y + dY, 0); + M.transform_tiny(start); + start.mad(M.k, -dR); + PQ.prepare_rq(start, M.k, d2R, CDB::OPT_CULL); + OBJECT->RayQuery(PQ); + + if (PQ.r_count()) + { + PQ.r_sort(); + Fvector N = {0, 0, 0}; + + for (s32 k = PQ.r_count() - 1; k >= 0; k--) + { + SPickQuery::SResult *R = PQ.r_begin() + k; + u32 uA, uC; + if (!GetPointColor(R, uA, uC)) + continue; + float fA = float(uA) / 255.f; + + if (uA) + { + Fvector pt; + pt.mad(PQ.m_Start, PQ.m_Direction, R->range - EPS_L); + Fvector4 ptt; + ptt.set(pt.x, pt.y, pt.z, fA); + sample_pt_vec.push_back(ptt); + } + + // normal + Fvector Nn; + Nn.mknormal(R->verts[0], R->verts[1], R->verts[2]); + Nn.mul(fA); + + N.mul(1.f - fA); + N.add(Nn); + } + + float n_mag = N.magnitude(); + + if (!fis_zero(n_mag, EPS)) + n_vec.push_back(N.div(n_mag)); + } + } + } + + tN += TT.GetElapsed_sec(); + Fvector N = {0, 0, 0}; + + if (!n_vec.empty()) + { + for (FvectorIt it = n_vec.begin(); it != n_vec.end(); it++) + N.add(*it); + + N.div(static_cast(n_vec.size())); + N.normalize_safe(); + Mi.transform_dir(N); + } + N.mul(0.5f); + N.add(0.5f); + N.mul(255.f); + tgt_n = color_rgba(iFloor(N.x), iFloor(N.y), iFloor(N.z), color_get_A(tgt_c)); + + if (0 == color_get_A(tgt_c)) + continue; + TT.Start(); + // light points + float res_transp = 0.f; + + for (Fvector4It pt_it = sample_pt_vec.begin(); pt_it != sample_pt_vec.end(); pt_it++) + { + float avg_transp = 0.f; + for (BLIt it = simple_hemi.begin(); it != simple_hemi.end(); it++) + { + TT1.Start(); + Fvector start; + start.mad(Fvector().set(pt_it->x, pt_it->y, pt_it->z), it->light.direction, -dR); + PQ.prepare_rq(start, it->light.direction, dR, CDB::OPT_CULL); + OBJECT->RayQuery(PQ); + tR += TT1.GetElapsed_sec(); + float ray_transp = 1.f; + if (PQ.r_count()) + { + for (s32 k = 0; k < PQ.r_count(); k++) + { + u32 a, uC; + TT1.Start(); + if (!GetPointColor(PQ.r_begin() + k, a, uC)) + continue; + tT += TT1.GetElapsed_sec(); + ray_transp *= (1.f - float(a) / 255.f); + if (fis_zero(ray_transp, EPS_L)) + break; + } + } + avg_transp += ray_transp; + } + avg_transp /= simple_hemi.size(); + res_transp = res_transp * (1.f - pt_it->w) + avg_transp * pt_it->w; + } + tH += TT.GetElapsed_sec(); + u8 h = (u8)iFloor(res_transp * 255.f); + tgt_h = color_rgba(h, h, h, color_get_A(tgt_c)); + } + } + } + + Msg("Normal: %3.2fsec, Hemi: %3.2f, PC: %3.2f, RP: %3.2f", tN, tH, tT, tR); + ImageLib.ApplyBorders(lod_pixels, LOD_IMAGE_SIZE * LOD_SAMPLE_COUNT, LOD_IMAGE_SIZE); + ImageLib.ApplyBorders(nm_pixels, LOD_IMAGE_SIZE * LOD_SAMPLE_COUNT, LOD_IMAGE_SIZE); + ImageLib.ApplyBorders(hemi_tmp, LOD_IMAGE_SIZE * LOD_SAMPLE_COUNT, LOD_IMAGE_SIZE); + // fill alpha to N-channel (HEMI) + for (int px_idx = 0; px_idx < int(nm_pixels.size()); px_idx++) + nm_pixels[px_idx] = subst_alpha(nm_pixels[px_idx], color_get_R(hemi_tmp[px_idx])); + + for (CSurface* surf : loadedSurfaces) + surf->RemoveImageData(); + + UI->ProgressEnd(PB); +} + +void CImageManager::CreateLODTexture(CEditableObject *OBJECT, LPCSTR tex_name, u32 tgt_w, u32 tgt_h, int samples, int age, int quality) +{ + U32Vec lod_pixels, nm_pixels; + + CreateLODTexture(OBJECT, lod_pixels, nm_pixels, tgt_w, tgt_h, samples, quality); + + string_path out_name, src_name; + CImage *I = xr_new(); + // save lod + strcpy(src_name, tex_name); + + strcpy(src_name, EFS.ChangeFileExt(src_name, ".thm").c_str()); + FS.file_delete(_textures_, src_name); + + strcpy(src_name, EFS.ChangeFileExt(src_name, ".tga").c_str()); + FS.update_path(out_name, _textures_, src_name); + I->Create(tgt_w * samples, tgt_h, lod_pixels.data()); + // I->Vflip (); + I->SaveTGA(out_name); + FS.set_file_age(out_name, age); + SynchronizeTexture(src_name, age); + + // save normal map + strconcat(sizeof(src_name), src_name, tex_name, "_nm"); + strcpy(src_name, EFS.ChangeFileExt(src_name, ".thm").c_str()); + FS.file_delete(_textures_, src_name); + + strcpy(src_name, EFS.ChangeFileExt(src_name, ".tga").c_str()); + FS.update_path(out_name, _textures_, src_name); + I->Create(tgt_w * samples, tgt_h, nm_pixels.data()); + // I->Vflip (); + I->SaveTGA(out_name); + FS.set_file_age(out_name, age); + SynchronizeTexture(src_name, age); + + xr_delete(I); +} diff --git a/src/editors/xrECore/Editor/LW_ShaderDef.h b/src/editors/xrECore/Editor/LW_ShaderDef.h new file mode 100644 index 00000000000..dc14b0f03ac --- /dev/null +++ b/src/editors/xrECore/Editor/LW_ShaderDef.h @@ -0,0 +1,21 @@ +#ifndef _LW_SHADERDEF_H_ +#define _LW_SHADERDEF_H_ +#pragma once + +/* our instance data */ +#pragma pack(push, 1) +typedef struct st_XRShader +{ + char en_name[64]; + int en_idx; + char lc_name[64]; + int lc_idx; + char gm_name[64]; + int gm_idx; + char *desc; +} XRShader; +#pragma pack(pop) + +#define SH_PLUGIN_NAME "!XRayShader" + +#endif diff --git a/src/editors/xrECore/Editor/Library.cpp b/src/editors/xrECore/Editor/Library.cpp new file mode 100644 index 00000000000..224fded7468 --- /dev/null +++ b/src/editors/xrECore/Editor/Library.cpp @@ -0,0 +1,300 @@ +//---------------------------------------------------- +// file: Library.cpp +//---------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +#include "Library.h" +#include "EditObject.h" + +//---------------------------------------------------- +ELibrary Lib; +//---------------------------------------------------- +ELibrary::ELibrary() +{ + m_bReady = false; +} +//---------------------------------------------------- + +ELibrary::~ELibrary() +{ +} +//---------------------------------------------------- + +void ELibrary::OnCreate() +{ + // EDevice.seqDevCreate.Add (this,REG_PRIORITY_NORMAL); + // EDevice.seqDevDestroy.Add(this,REG_PRIORITY_NORMAL); + m_bReady = true; +} +//---------------------------------------------------- + +void ELibrary::OnDestroy() +{ + VERIFY(m_bReady); + m_bReady = false; + // EDevice.seqDevCreate.Remove(this); + // EDevice.seqDevDestroy.Remove(this); + + // remove all instance CEditableObject + EditObjPairIt O = m_EditObjects.begin(); + EditObjPairIt E = m_EditObjects.end(); + for (; O != E; O++) + { + if (0 != O->second->m_RefCount) + { + //. ELog.DlgMsg(mtError,"Object '%s' still referenced.",O->first.c_str()); + //. R_ASSERT(0==O->second->m_RefCount); + } + xr_delete(O->second); + } + m_EditObjects.clear(); +} +//---------------------------------------------------- + +void ELibrary::CleanLibrary() +{ + VERIFY(m_bReady); + // remove all unused instance CEditableObject + for (EditObjPairIt O = m_EditObjects.begin(); O != m_EditObjects.end();) + { + if (0 == O->second->m_RefCount) + { + EditObjPairIt D = O; + O++; + xr_delete(D->second); + m_EditObjects.erase(D); + } + else + O++; + } +} +//---------------------------------------------------- +void ELibrary::ReloadObject(LPCSTR nm) +{ + VERIFY(m_bReady); + R_ASSERT(nm && nm[0]); + string512 name; + strcpy(name, nm); + strlwr(name); + EditObjPairIt it = m_EditObjects.find(name); + if (it != m_EditObjects.end()) + it->second->Reload(); +} +//--------------------------------------------------------------------------- +void ELibrary::ReloadObjects() +{ + VERIFY(m_bReady); + EditObjPairIt O = m_EditObjects.begin(); + EditObjPairIt E = m_EditObjects.end(); + for (; O != E; O++) + O->second->Reload(); +} +//---------------------------------------------------- + +void ELibrary::OnDeviceCreate() +{ + VERIFY(m_bReady); + EditObjPairIt O = m_EditObjects.begin(); + EditObjPairIt E = m_EditObjects.end(); + for (; O != E; O++) + O->second->OnDeviceCreate(); +} +//--------------------------------------------------------------------------- + +void ELibrary::OnDeviceDestroy() +{ + VERIFY(m_bReady); + EditObjPairIt O = m_EditObjects.begin(); + EditObjPairIt E = m_EditObjects.end(); + for (; O != E; O++) + O->second->OnDeviceDestroy(); +} +//--------------------------------------------------------------------------- + +void ELibrary::EvictObjects() +{ + EditObjPairIt O = m_EditObjects.begin(); + EditObjPairIt E = m_EditObjects.end(); + for (; O != E; O++) + O->second->EvictObject(); +} +//---------------------------------------------------- + +CEditableObject *ELibrary::LoadEditObject(LPCSTR name) +{ + VERIFY(m_bReady); + CEditableObject *m_EditObject = xr_new(name); + string_path fn; + FS.update_path(fn, _objects_, EFS.ChangeFileExt(name, ".object").c_str()); + if (FS.exist(fn)) + { + if (m_EditObject->Load(fn)) + return m_EditObject; + } + else + { + ELog.Msg(mtError, "Can't find file '%s'", fn); + } + xr_delete(m_EditObject); + return 0; +} +//--------------------------------------------------------------------------- + +CEditableObject *ELibrary::CreateEditObject(LPCSTR nm) +{ + VERIFY(m_bReady); + R_ASSERT(nm && nm[0]); + //. UI->ProgressInfo (nm); + xr_string name = xr_string(nm); + xr_strlwr(name); + // file exist - find in already loaded + CEditableObject *m_EditObject = 0; + EditObjPairIt it = m_EditObjects.find(name); + if (it != m_EditObjects.end()) + m_EditObject = it->second; + else if (0 != (m_EditObject = LoadEditObject(name.c_str()))) + m_EditObjects[name] = m_EditObject; + if (m_EditObject) + m_EditObject->m_RefCount++; + return m_EditObject; +} +//--------------------------------------------------------------------------- + +void ELibrary::RemoveEditObject(CEditableObject *&object) +{ + if (object) + { + object->m_RefCount--; + R_ASSERT(object->m_RefCount >= 0); + if ((object->m_RefCount == 0) && EPrefs->object_flags.is(epoDiscardInstance)) + if (!object->IsModified()) + UnloadEditObject(object->GetName()); + object = 0; + } +} +//--------------------------------------------------------------------------- + +void ELibrary::Save(FS_FileSet *modif_map) +{ + VERIFY(m_bReady); + EditObjPairIt O = m_EditObjects.begin(); + EditObjPairIt E = m_EditObjects.end(); + if (modif_map) + { + for (; O != E; O++) + if (modif_map->end() != modif_map->find(FS_File(O->second->GetName()))) + { + string_path nm; + FS.update_path(nm, _objects_, O->second->GetName()); + strcpy(nm, EFS.ChangeFileExt(nm, ".object").c_str()); + + if (!O->second->Save(nm)) + Log("!Can't save object:", nm); + } + } + else + { + for (; O != E; O++) + if (O->second->IsModified()) + { + string_path nm; + FS.update_path(nm, _objects_, O->second->GetName()); + strcpy(nm, EFS.ChangeFileExt(nm, ".object").c_str()); + + if (!O->second->Save(nm)) + Log("!Can't save object:", nm); + } + } +} +//--------------------------------------------------------------------------- + +int ELibrary::GetObjects(FS_FileSet &files) +{ + return FS.file_list(files, _objects_, FS_ListFiles | FS_ClampExt, "*.object"); +} +//--------------------------------------------------------------------------- + +void ELibrary::RemoveObject(LPCSTR _fname, EItemType type, bool &res) +{ + if (TYPE_FOLDER == type) + { + FS.dir_delete(_objects_, _fname, FALSE); + res = true; + return; + } + else if (TYPE_OBJECT == type) + { + string_path fname, src_name; + strcpy(fname, EFS.ChangeFileExt(_fname, ".object").c_str()); + FS.update_path(src_name, _objects_, fname); + if (FS.exist(src_name)) + { + xr_string thm_name = EFS.ChangeFileExt(fname, ".thm"); + // source + FS.file_delete(src_name); + // thumbnail + FS.file_delete(_objects_, thm_name.c_str()); + + UnloadEditObject(_fname); + + res = true; + return; + } + } + else + THROW; + res = false; +} +//--------------------------------------------------------------------------- + +void ELibrary::RenameObject(LPCSTR nm0, LPCSTR nm1, EItemType type) +{ + if (TYPE_FOLDER == type) + { + FS.dir_delete(_objects_, nm0, FALSE); + } + else if (TYPE_OBJECT == type) + { + string_path fn0, fn1, temp; + // rename base file + FS.update_path(fn0, _objects_, nm0); + strcat(fn0, ".object"); + FS.update_path(fn1, _objects_, nm1); + strcat(fn1, ".object"); + FS.file_rename(fn0, fn1, false); + + // rename thm + FS.update_path(fn0, _objects_, nm0); + strcat(fn0, ".thm"); + FS.update_path(fn1, _objects_, nm1); + strcat(fn1, ".thm"); + FS.file_rename(fn0, fn1, false); + + // rename in cache + EditObjPairIt it = m_EditObjects.find(nm0); + if (it != m_EditObjects.end()) + { + m_EditObjects[nm1] = it->second; + m_EditObjects.erase(it); + } + } +} +//--------------------------------------------------------------------------- + +void ELibrary::UnloadEditObject(LPCSTR full_name) +{ + EditObjPairIt it = m_EditObjects.find(full_name); + if (it != m_EditObjects.end()) + { + if (0 != it->second->m_RefCount) + { + ELog.DlgMsg(mtError, "Object '%s' still referenced.", it->first.c_str()); + THROW; + } + m_EditObjects.erase(it); + xr_delete(it->second); + } +} +//--------------------------------------------------------------------------- diff --git a/src/editors/xrECore/Editor/Library.h b/src/editors/xrECore/Editor/Library.h new file mode 100644 index 00000000000..28da11e2709 --- /dev/null +++ b/src/editors/xrECore/Editor/Library.h @@ -0,0 +1,51 @@ +//---------------------------------------------------- +// file: Library.h +//---------------------------------------------------- + +#ifndef LibraryH +#define LibraryH + +//---------------------------------------------------- +class CEditableObject; + +DEFINE_MAP_PRED(xr_string, CEditableObject *, EditObjMap, EditObjPairIt, astr_pred); +//---------------------------------------------------- +class ECORE_API ELibrary //: public pureDeviceCreate, public pureDeviceDestroy +{ + bool m_bReady; + friend class TfrmChoseObject; + EditObjMap m_EditObjects; + + CEditableObject *LoadEditObject(LPCSTR full_name); + void UnloadEditObject(LPCSTR full_name); + +public: + ELibrary(); + virtual ~ELibrary(); + + void RemoveObject(LPCSTR fname, EItemType type, bool &res); + void RenameObject(LPCSTR fn0, LPCSTR fn1, EItemType type); + + void OnCreate(); + void OnDestroy(); + void Save(FS_FileSet *modif_map = 0); + + void ReloadObjects(); + void CleanLibrary(); + void ReloadObject(LPCSTR name); + + CEditableObject *CreateEditObject(LPCSTR name); + void RemoveEditObject(CEditableObject *&object); + + int GetObjects(FS_FileSet &files); + int ObjectCount() { return m_EditObjects.size(); } + + void EvictObjects(); + + virtual void OnDeviceCreate(); + virtual void OnDeviceDestroy(); +}; + +extern ECORE_API ELibrary Lib; +//---------------------------------------------------- +#endif /*_INCDEF_Library_H_*/ diff --git a/src/editors/xrECore/Editor/LogForm.dfm b/src/editors/xrECore/Editor/LogForm.dfm new file mode 100644 index 00000000000..f87536451e3 --- /dev/null +++ b/src/editors/xrECore/Editor/LogForm.dfm @@ -0,0 +1,164 @@ +object frmLog: TfrmLog + Left = 560 + Top = 413 + Width = 400 + Height = 225 + BorderStyle = bsSizeToolWin + Caption = 'Log' + Color = clBtnFace + Constraints.MinHeight = 80 + Constraints.MinWidth = 400 + Font.Charset = DEFAULT_CHARSET + Font.Color = clWindowText + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + FormStyle = fsStayOnTop + KeyPreview = True + OldCreateOrder = False + Scaled = False + OnKeyDown = FormKeyDown + OnShow = FormShow + PixelsPerInch = 96 + TextHeight = 13 + object Panel1: TPanel + Left = 0 + Top = 178 + Width = 392 + Height = 20 + Align = alBottom + BevelOuter = bvNone + TabOrder = 0 + object ebClear: TExtBtn + Left = 184 + Top = 2 + Width = 82 + Height = 18 + Align = alNone + BevelShow = False + Caption = 'Clear' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + Transparent = False + FlatAlwaysEdge = True + OnClick = ebClearClick + end + object ebClearSelected: TExtBtn + Left = 266 + Top = 2 + Width = 82 + Height = 18 + Align = alNone + BevelShow = False + Caption = 'Clear Selected' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + Transparent = False + FlatAlwaysEdge = True + OnClick = ebClearSelectedClick + end + object ebClose: TExtBtn + Left = 0 + Top = 2 + Width = 82 + Height = 18 + Align = alNone + BevelShow = False + Caption = 'Close' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + Transparent = False + FlatAlwaysEdge = True + OnClick = ebCloseClick + end + object ebFlush: TExtBtn + Left = 82 + Top = 2 + Width = 82 + Height = 18 + Align = alNone + BevelShow = False + Caption = 'Flush' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + Transparent = False + FlatAlwaysEdge = True + OnClick = ebFlushClick + end + end + object Panel2: TPanel + Left = 0 + Top = 0 + Width = 392 + Height = 178 + Align = alClient + BevelOuter = bvNone + TabOrder = 1 + object lbLog: TListBox + Left = 0 + Top = 0 + Width = 392 + Height = 178 + Style = lbOwnerDrawFixed + AutoComplete = False + Align = alClient + Color = 15263976 + ItemHeight = 13 + MultiSelect = True + PopupMenu = MxPopupMenu1 + TabOrder = 0 + OnDrawItem = lbLogDrawItem + OnKeyDown = lbLogKeyDown + OnKeyPress = lbLogKeyPress + end + end + object fsStorage: TFormStorage + IniSection = 'Log Form' + Version = 1 + StoredValues = <> + Left = 8 + Top = 8 + end + object MxPopupMenu1: TMxPopupMenu + MarginEndColor = clBlack + Left = 40 + Top = 8 + object imCopy: TMenuItem + Caption = '&Copy' + ShortCut = 16451 + OnClick = imCopyClick + end + object imSelectAll: TMenuItem + Caption = 'Select &All' + ShortCut = 16449 + OnClick = imSelectAllClick + end + object N1: TMenuItem + Caption = '-' + end + object ClearAll1: TMenuItem + Caption = 'Clear All' + OnClick = ebClearClick + end + object ClearSelected1: TMenuItem + Caption = 'Clear Selected' + OnClick = ebClearSelectedClick + end + end +end diff --git a/src/editors/xrECore/Editor/MinimapEditor.ddp b/src/editors/xrECore/Editor/MinimapEditor.ddp new file mode 100644 index 00000000000..cdc0ee8c2b5 Binary files /dev/null and b/src/editors/xrECore/Editor/MinimapEditor.ddp differ diff --git a/src/editors/xrECore/Editor/MinimapEditor.dfm b/src/editors/xrECore/Editor/MinimapEditor.dfm new file mode 100644 index 00000000000..b19eba0dd29 --- /dev/null +++ b/src/editors/xrECore/Editor/MinimapEditor.dfm @@ -0,0 +1,209 @@ +object TMinimapEditor: TTMinimapEditor + Left = 360 + Top = 420 + Width = 601 + Height = 449 + Caption = 'TMinimapEditor' + Color = clBtnFace + Font.Charset = DEFAULT_CHARSET + Font.Color = clWindowText + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + OldCreateOrder = False + PixelsPerInch = 96 + TextHeight = 13 + object Panel1: TPanel + Left = 0 + Top = 334 + Width = 593 + Height = 81 + Align = alBottom + BevelOuter = bvNone + Color = 10528425 + TabOrder = 0 + object btnLoad: TExtBtn + Left = 0 + Top = 2 + Width = 57 + Height = 17 + Align = alNone + BevelShow = False + Caption = 'Load' + Font.Charset = DEFAULT_CHARSET + Font.Color = clBlack + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + Kind = knNone + ParentFont = False + FlatAlwaysEdge = True + OnClick = btnLoadClick + end + object MxLabel1: TMxLabel + Left = 0 + Top = 29 + Width = 56 + Height = 13 + Caption = 'BoundRect' + end + object MxLabel2: TMxLabel + Left = 72 + Top = 5 + Width = 39 + Height = 13 + Caption = 'LeftTop' + end + object MxLabel3: TMxLabel + Left = 184 + Top = 5 + Width = 60 + Height = 13 + Caption = 'RightBottom' + end + object ElFloatSpinEditX1: TElFloatSpinEdit + Left = 64 + Top = 24 + Width = 100 + Height = 21 + Cursor = crIBeam + VertScrollBarStyles.ShowTrackHint = False + VertScrollBarStyles.Width = 17 + VertScrollBarStyles.ButtonSize = 17 + HorzScrollBarStyles.ShowTrackHint = False + HorzScrollBarStyles.Width = 17 + HorzScrollBarStyles.ButtonSize = 17 + UseCustomScrollBars = True + Increment = 1 + LargeIncrement = 10 + MaxValue = 10000 + MinValue = -10000 + Alignment = taLeftJustify + TopMargin = 2 + BorderSides = [ebsLeft, ebsRight, ebsTop, ebsBottom] + Transparent = False + OnChange = ElFloatSpinEditX1Change + BorderStyle = bsSingle + Ctl3D = True + LineBorderActiveColor = clBlack + LineBorderInactiveColor = clBlack + ParentColor = False + ParentCtl3D = False + TabOrder = 0 + end + object ElFloatSpinEditZ1: TElFloatSpinEdit + Left = 64 + Top = 48 + Width = 100 + Height = 21 + Cursor = crIBeam + VertScrollBarStyles.ShowTrackHint = False + VertScrollBarStyles.Width = 17 + VertScrollBarStyles.ButtonSize = 17 + HorzScrollBarStyles.ShowTrackHint = False + HorzScrollBarStyles.Width = 17 + HorzScrollBarStyles.ButtonSize = 17 + UseCustomScrollBars = True + Increment = 1 + LargeIncrement = 10 + MaxValue = 10000 + MinValue = -10000 + Alignment = taLeftJustify + TopMargin = 2 + BorderSides = [ebsLeft, ebsRight, ebsTop, ebsBottom] + Transparent = False + OnChange = ElFloatSpinEditX1Change + BorderStyle = bsSingle + Ctl3D = True + LineBorderActiveColor = clBlack + LineBorderInactiveColor = clBlack + ParentColor = False + ParentCtl3D = False + TabOrder = 1 + end + object ElFloatSpinEditX2: TElFloatSpinEdit + Left = 184 + Top = 24 + Width = 100 + Height = 21 + Cursor = crIBeam + VertScrollBarStyles.ShowTrackHint = False + VertScrollBarStyles.Width = 17 + VertScrollBarStyles.ButtonSize = 17 + HorzScrollBarStyles.ShowTrackHint = False + HorzScrollBarStyles.Width = 17 + HorzScrollBarStyles.ButtonSize = 17 + UseCustomScrollBars = True + Increment = 1 + LargeIncrement = 10 + MaxValue = 10000 + MinValue = -10000 + Alignment = taLeftJustify + TopMargin = 2 + BorderSides = [ebsLeft, ebsRight, ebsTop, ebsBottom] + Transparent = False + OnChange = ElFloatSpinEditX1Change + BorderStyle = bsSingle + Ctl3D = True + LineBorderActiveColor = clBlack + LineBorderInactiveColor = clBlack + ParentColor = False + ParentCtl3D = False + TabOrder = 2 + end + object ElFloatSpinEditZ2: TElFloatSpinEdit + Left = 184 + Top = 48 + Width = 100 + Height = 21 + Cursor = crIBeam + VertScrollBarStyles.ShowTrackHint = False + VertScrollBarStyles.Width = 17 + VertScrollBarStyles.ButtonSize = 17 + HorzScrollBarStyles.ShowTrackHint = False + HorzScrollBarStyles.Width = 17 + HorzScrollBarStyles.ButtonSize = 17 + UseCustomScrollBars = True + Increment = 1 + LargeIncrement = 10 + MaxValue = 10000 + MinValue = -10000 + Alignment = taLeftJustify + TopMargin = 2 + BorderSides = [ebsLeft, ebsRight, ebsTop, ebsBottom] + Transparent = False + OnChange = ElFloatSpinEditX1Change + BorderStyle = bsSingle + Ctl3D = True + LineBorderActiveColor = clBlack + LineBorderInactiveColor = clBlack + ParentColor = False + ParentCtl3D = False + TabOrder = 3 + end + object result_edit: TElAdvancedEdit + Left = 296 + Top = 48 + Width = 265 + Height = 21 + BorderSides = [ebsLeft, ebsRight, ebsTop, ebsBottom] + LineBorderActiveColor = clBlack + LineBorderInactiveColor = clBlack + ReadOnly = True + TabOrder = 4 + Text = 'bound_rect=' + end + end + object imgPanel: TMxPanel + Left = 0 + Top = 0 + Width = 593 + Height = 334 + Align = alClient + Color = 10528425 + TabOrder = 1 + OnMouseDown = imgPanelMouseDown + OnResize = imgPanelResize + OnPaint = imgPanelPaint + end +end diff --git a/src/editors/xrECore/Editor/ParticleEffectActions.cpp b/src/editors/xrECore/Editor/ParticleEffectActions.cpp new file mode 100644 index 00000000000..6d1a449be06 --- /dev/null +++ b/src/editors/xrECore/Editor/ParticleEffectActions.cpp @@ -0,0 +1,7 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "ParticleEffectActions.h" + +_CreateEAction pCreateEAction = 0; diff --git a/src/editors/xrECore/Editor/ParticleEffectActions.h b/src/editors/xrECore/Editor/ParticleEffectActions.h new file mode 100644 index 00000000000..d4f3efd1910 --- /dev/null +++ b/src/editors/xrECore/Editor/ParticleEffectActions.h @@ -0,0 +1,424 @@ +//--------------------------------------------------------------------------- +#ifndef ParticleEffectActionsH +#define ParticleEffectActionsH + +struct PBool +{ + BOOL val; + PBool() : val(FALSE) {} + PBool(BOOL _val) : val(_val) {} + void set(BOOL v) { val = v; } +}; +struct PFloat +{ + float val; + float mn; + float mx; + PFloat() + { + val = 0.f; + mn = 0.f; + mx = 0.f; + } + PFloat(float _val, float _mn, float _mx) : val(_val), mn(_mn), mx(_mx) {} + void set(float v) { val = v; } +}; +struct PInt +{ + int val; + int mn; + int mx; + PInt() + { + val = 0; + mn = 0; + mx = 0; + } + PInt(int _val, int _mn, int _mx) : val(_val), mn(_mn), mx(_mx) {} + void set(int v) { val = v; } +}; +struct PVector +{ + Fvector val; + float mn; + float mx; + enum EType + { + vNum, + vAngle, + vColor, + _force_u32 = u32(-1), + }; + EType type; + PVector() + { + val.set(0, 0, 0); + mn = 0.f; + mx = 0.f; + } + PVector(EType t, Fvector _val, float _mn, float _mx) : type(t), val(_val), mn(_mn), mx(_mx) {} + void set(const Fvector &v) { val.set(v); } + void set(float x, float y, float z) { val.set(x, y, z); } +}; +struct PDomain +{ +public: + PAPI::PDomainEnum type; + union + { + float f[9]; + Fvector v[3]; + }; + enum EType + { + vNum, + vAngle, + vColor, + _force_u32 = u32(-1), + }; + enum + { + flRenderable = (1 << 0) + }; + EType e_type; + Flags32 flags; + u32 clr; + +protected: + void OnTypeChange(PropValue *sender); + +public: + PDomain() {} + PDomain(EType et, BOOL renderable, u32 color = 0x00000000, PAPI::PDomainEnum type = PAPI::PDPoint, + float inA0 = 0.0f, float inA1 = 0.0f, float inA2 = 0.0f, + float inA3 = 0.0f, float inA4 = 0.0f, float inA5 = 0.0f, + float inA6 = 0.0f, float inA7 = 0.0f, float inA8 = 0.0f); + ~PDomain(); + PDomain(const PDomain &in); + + void MoveXYZ(float x, float y, float z); + void RotateXYZ(float x, float y, float z); + void ScaleXYZ(float x, float y, float z); + + Fvector &GetCenter(); + + void Load(IReader &F); + void Save(IWriter &F); + + void Load2(CInifile &ini, const shared_str §); + void Save2(CInifile &ini, const shared_str §); + + void Render(u32 color, const Fmatrix &parent); + void FillProp(PropItemVec &items, LPCSTR pref, u32 clr); +}; +struct EParticleAction +{ + DEFINE_MAP(xr_string, PDomain, PDomainMap, PDomainMapIt); + DEFINE_MAP(xr_string, PBool, PBoolMap, PBoolMapIt); + DEFINE_MAP(xr_string, PFloat, PFloatMap, PFloatMapIt); + DEFINE_MAP(xr_string, PInt, PIntMap, PIntMapIt); + DEFINE_MAP(xr_string, PVector, PVectorMap, PVectorMapIt); + + shared_str actionName; + shared_str actionType; + shared_str hint; + enum + { + flEnabled = (1 << 0), + flDraw = (1 << 1), + }; + Flags32 flags; + PAPI::PActionEnum type; + + PDomainMap domains; + PBoolMap bools; + PFloatMap floats; + PIntMap ints; + PVectorMap vectors; + + enum EValType + { + tpDomain, + tpVector, + tpFloat, + tpBool, + tpInt, + }; + struct SOrder + { + EValType type; + xr_string name; + SOrder(EValType _type, xr_string _name) : type(_type), name(_name) {} + }; + DEFINE_VECTOR(SOrder, OrderVec, OrderVecIt); + OrderVec orders; + + EParticleAction(PAPI::PActionEnum _type) + { + flags.assign(flEnabled); + type = _type; + } + +public: + void appendFloat(LPCSTR name, float v, float mn, float mx); + void appendInt(LPCSTR name, int v, int mn = -P_MAXINT, int mx = P_MAXINT); + void appendVector(LPCSTR name, PVector::EType type, float vx, float vy, float vz, float mn = -P_MAXFLOAT, float mx = P_MAXFLOAT); + void appendDomain(LPCSTR name, PDomain v); + void appendBool(LPCSTR name, BOOL b); + PFloat &_float(LPCSTR name) + { + PFloatMapIt it = floats.find(name); + R_ASSERT2(it != floats.end(), name); + return it->second; + } + PInt &_int(LPCSTR name) + { + PIntMapIt it = ints.find(name); + R_ASSERT2(it != ints.end(), name); + return it->second; + } + PVector &_vector(LPCSTR name) + { + PVectorMapIt it = vectors.find(name); + R_ASSERT2(it != vectors.end(), name); + return it->second; + } + PDomain &_domain(LPCSTR name) + { + PDomainMapIt it = domains.find(name); + R_ASSERT2(it != domains.end(), name); + return it->second; + } + PBool &_bool(LPCSTR name) + { + PBoolMapIt it = bools.find(name); + R_ASSERT2(it != bools.end(), name); + return it->second; + } + PBool *_bool_safe(LPCSTR name) + { + PBoolMapIt it = bools.find(name); + return (it != bools.end()) ? &it->second : 0; + } + +public: + virtual void Compile(IWriter &F) = 0; + virtual void FillProp(PropItemVec &items, LPCSTR pref, u32 clr); + + virtual void Load(IReader &F); + virtual void Save(IWriter &F); + virtual void Load2(CInifile &ini, const shared_str §); + virtual void Save2(CInifile &ini, const shared_str §); + virtual void Render(const Fmatrix &parent); +}; + +struct EPAAvoid : public EParticleAction +{ + EPAAvoid(); + virtual void Compile(IWriter &F); +}; + +struct EPABounce : public EParticleAction +{ + EPABounce(); + virtual void Compile(IWriter &F); +}; + +struct EPACopyVertexB : public EParticleAction +{ + EPACopyVertexB(); + virtual void Compile(IWriter &F); +}; + +struct EPADamping : public EParticleAction +{ + EPADamping(); + virtual void Compile(IWriter &F); +}; + +struct EPAExplosion : public EParticleAction +{ + EPAExplosion(); + virtual void Compile(IWriter &F); +}; + +struct EPAFollow : public EParticleAction +{ + EPAFollow(); + virtual void Compile(IWriter &F); +}; + +struct EPAGravitate : public EParticleAction +{ + EPAGravitate(); + virtual void Compile(IWriter &F); +}; + +struct EPAGravity : public EParticleAction +{ + EPAGravity(); + virtual void Compile(IWriter &F); +}; + +struct EPAJet : public EParticleAction +{ + EPAJet(); + virtual void Compile(IWriter &F); + virtual void Render(const Fmatrix &parent); +}; + +struct EPAKillOld : public EParticleAction +{ + EPAKillOld(); + virtual void Compile(IWriter &F); +}; + +struct EPAMatchVelocity : public EParticleAction +{ + EPAMatchVelocity(); + virtual void Compile(IWriter &F); +}; + +struct EPAMove : public EParticleAction +{ + EPAMove(); + virtual void Compile(IWriter &F); +}; + +struct EPAOrbitLine : public EParticleAction +{ + EPAOrbitLine(); + virtual void Compile(IWriter &F); + virtual void Render(const Fmatrix &parent); +}; + +struct EPAOrbitPoint : public EParticleAction +{ + EPAOrbitPoint(); + virtual void Compile(IWriter &F); + virtual void Render(const Fmatrix &parent); +}; + +struct EPARandomAccel : public EParticleAction +{ + EPARandomAccel(); + virtual void Compile(IWriter &F); +}; + +struct EPARandomDisplace : public EParticleAction +{ + EPARandomDisplace(); + virtual void Compile(IWriter &F); +}; + +struct EPARandomVelocity : public EParticleAction +{ + EPARandomVelocity(); + virtual void Compile(IWriter &F); +}; + +struct EPARestore : public EParticleAction +{ + EPARestore(); + virtual void Compile(IWriter &F); +}; + +struct EPAScatter : public EParticleAction +{ + EPAScatter(); + virtual void Compile(IWriter &F); + virtual void Render(const Fmatrix &parent); +}; + +struct EPASink : public EParticleAction +{ + EPASink(); + virtual void Compile(IWriter &F); +}; + +struct EPASinkVelocity : public EParticleAction +{ + EPASinkVelocity(); + virtual void Compile(IWriter &F); +}; + +struct EPASpeedLimit : public EParticleAction +{ + EPASpeedLimit(); + virtual void Compile(IWriter &F); +}; + +struct EPASource : public EParticleAction +{ + EPASource(); + virtual void Compile(IWriter &F); +}; + +struct EPATargetColor : public EParticleAction +{ + EPATargetColor(); + virtual void Compile(IWriter &F); +}; + +struct EPATargetSize : public EParticleAction +{ + EPATargetSize(); + virtual void Compile(IWriter &F); +}; + +struct EPATargetRotate : public EParticleAction +{ + EPATargetRotate(); + virtual void Compile(IWriter &F); +}; + +struct EPATargetVelocity : public EParticleAction +{ + EPATargetVelocity(); + virtual void Compile(IWriter &F); +}; + +struct EPAVortex : public EParticleAction +{ + EPAVortex(); + virtual void Compile(IWriter &F); + virtual void Render(const Fmatrix &parent); +}; + +struct EPATurbulence : public EParticleAction +{ + float ***nval; + float age; + +public: + EPATurbulence(); + + virtual void Compile(IWriter &F); + virtual void Render(const Fmatrix &parent); +}; + +struct XRCORE_API xr_token2 +{ + LPCSTR name; + LPCSTR info; + int id; +}; + +extern xr_token2 actions_token[]; + +typedef EParticleAction *(*_CreateEAction)(PAPI::PActionEnum type); +extern ECORE_API _CreateEAction pCreateEAction; +//--------------------------------------------------------------------------- +#endif + +/* + + void pTargetVelocityD(float scale, PDomainEnum dtype, + float a0 = 0.0f, float a1 = 0.0f, float a2 = 0.0f, + float a3 = 0.0f, float a4 = 0.0f, float a5 = 0.0f, + float a6 = 0.0f, float a7 = 0.0f, float a8 = 0.0f, BOOL allow_translate=TRUE, BOOL allow_rotate=TRUE); + + void pVertex(float x, float y, float z); + +} +*/ diff --git a/src/editors/xrECore/Editor/PhysicsShellHolderEditorBase.cpp b/src/editors/xrECore/Editor/PhysicsShellHolderEditorBase.cpp new file mode 100644 index 00000000000..361a46f5507 --- /dev/null +++ b/src/editors/xrECore/Editor/PhysicsShellHolderEditorBase.cpp @@ -0,0 +1,62 @@ +#include "stdafx.h" +#include "PhysicsShellHolderEditorBase.h" +#include "../../xrphysics/physicsshell.h" +#include "xrEngine/GameMtlLib.h" + +static void SetBoneMaterials(IKinematics &K) +{ + const u16 count = K.LL_BoneCount(); + for (u16 i = 0; i < count; ++i) + { + CBoneData &bd = K.LL_GetData(i); + if (*(bd.game_mtl_name)) + bd.game_mtl_idx = GMLib.GetMaterialIdx(bd.game_mtl_name.c_str()); + else + bd.game_mtl_idx = 0; + } +} + +void CPhysicsShellHolderEditorBase::CreatePhysicsShell(Fmatrix *obj_xform) +{ + IKinematics *K = ObjectKinematics(); + if (!K) + return; + VERIFY(K); + string1024 s; + if (!can_create_phys_shell(s, *this)) + { + Msg(s); + return; + } + m_object_xform.set(*obj_xform); + if (K->dcast_RenderVisual()) + SetBoneMaterials(*K); + K->CalculateBones_Invalidate(); + K->CalculateBones(TRUE); + m_physics_shell = P_build_Shell(this, false); + K->CalculateBones_Invalidate(); + K->CalculateBones(TRUE); +} + +void CPhysicsShellHolderEditorBase::DeletePhysicsShell() +{ + destroy_physics_shell(m_physics_shell); + m_object_xform = Fidentity; +} + +void CPhysicsShellHolderEditorBase::UpdateObjectXform(Fmatrix &obj_xform) +{ + if (m_physics_shell) + { + IKinematics *K = ObjectKinematics(); + VERIFY(K); + // K->CalculateBones(); + m_physics_shell->InterpolateGlobalTransform(&m_object_xform); + } + obj_xform.set(m_object_xform); +} +void CPhysicsShellHolderEditorBase::ApplyDragForce(const Fvector &force) +{ + VERIFY(m_physics_shell); + m_physics_shell->applyGravityAccel(force); +} diff --git a/src/editors/xrECore/Editor/PhysicsShellHolderEditorBase.h b/src/editors/xrECore/Editor/PhysicsShellHolderEditorBase.h new file mode 100644 index 00000000000..0cba6fba975 --- /dev/null +++ b/src/editors/xrECore/Editor/PhysicsShellHolderEditorBase.h @@ -0,0 +1,71 @@ +#ifndef _PHYSICS_SHELL_HOLDER_EDITOR_BASE_ +#define _PHYSICS_SHELL_HOLDER_EDITOR_BASE_ + +#include "../../../xrphysics/iphysicsshellholder.h" + +class ECORE_API CPhysicsShellHolderEditorBase : public IPhysicsShellHolder +{ +public: + void CreatePhysicsShell(Fmatrix *obj_xform); + void DeletePhysicsShell(); + void UpdateObjectXform(Fmatrix &obj_xform); + void ApplyDragForce(const Fvector &force); + +protected: + CPhysicsShellHolderEditorBase() : m_physics_shell(0), m_object_xform(Fidentity) {} + ~CPhysicsShellHolderEditorBase() + { /*DeletePhysicsShell ();*/ + } + +protected: + CPhysicsShell *m_physics_shell; + Fmatrix m_object_xform; + +private: + virtual LPCSTR ObjectName() const { return "EditorActor"; } + virtual LPCSTR ObjectNameVisual() const { return "unknown"; } + virtual LPCSTR ObjectNameSect() const { return "unknown"; } + virtual bool ObjectGetDestroy() const { return false; }; + virtual ICollisionHitCallback *ObjectGetCollisionHitCallback() { return 0; } + virtual u16 ObjectID() const { return u16(-1); } + virtual ICollisionForm *ObjectCollisionModel() + { + VERIFY(false); + return 0; + } + // virtual IRenderVisual* ObjectVisual () { return m_pVisual;} + virtual IDamageSource *ObjectCastIDamageSource() { return 0; } + virtual void ObjectProcessingDeactivate() { ; } + virtual void ObjectProcessingActivate() {} + virtual void ObjectSpatialMove() {} + virtual CPhysicsShell *&ObjectPPhysicsShell() { return m_physics_shell; } + virtual void enable_notificate() {} + virtual bool has_parent_object() { return false; } + virtual void on_physics_disable() {} + virtual IPHCapture *PHCapture() { return 0; } + virtual bool IsInventoryItem() { return false; } + virtual bool IsActor() { return false; } + virtual bool IsStalker() { return false; } + // virtual void SetWeaponHideState ( u16 State, bool bSet )=0; + virtual void HideAllWeapons(bool v) {} //(SetWeaponHideState(INV_STATE_BLOCK_ALL,true)) + virtual void MovementCollisionEnable(bool enable) {} + virtual CPHSoundPlayer *ObjectPhSoundPlayer() { return 0; } + virtual ICollisionDamageReceiver *ObjectPhCollisionDamageReceiver() { return 0; } + virtual void BonceDamagerCallback(float &damage_factor) {} + +public: + virtual Fmatrix &ObjectXFORM() { return m_object_xform; } + +private: + virtual Fvector &ObjectPosition() { return m_object_xform.c; } + +#ifdef DEBUG + virtual std::string dump(EDumpType type) const + { + VERIFY(false); + return std::string("ActorEditor!"); + } +#endif +}; + +#endif diff --git a/src/editors/xrECore/Editor/PropSlimTools.h b/src/editors/xrECore/Editor/PropSlimTools.h new file mode 100644 index 00000000000..a1739aa285d --- /dev/null +++ b/src/editors/xrECore/Editor/PropSlimTools.h @@ -0,0 +1,43 @@ +#ifndef PropSlimToolsH +#define PropSlimToolsH + +#ifdef ETOOLS_EXPORTS +#define ETOOLS_API __declspec(dllexport) +#else +#define ETOOLS_API __declspec(dllimport) +#endif + +#include "ArbitraryList.h" + +#pragma pack(push, 1) +struct VIPM_SWR +{ + u32 offset; // Offset of the first index in the index buffer to start at (note! no retrictions. Can easily be >64k) + u16 num_tris; // Number of tris to render (most cards can't do more than 65536) + u16 num_verts; // Number of vertices to render with (using WORD indices) +}; +#pragma pack(pop) + +struct VIPM_Result +{ + ArbitraryList permute_verts; + ArbitraryList swr_records; // The records of the collapses. + ArbitraryList indices; + ~VIPM_Result() + { + permute_verts.resize(0); + swr_records.resize(0); + indices.resize(0); + } +}; + +extern "C" +{ + ETOOLS_API void VIPM_Init(); + ETOOLS_API void VIPM_AppendVertex(const Fvector3 &pt, const Fvector2 &uv); + ETOOLS_API void VIPM_AppendFace(u16 v0, u16 v1, u16 v2); + ETOOLS_API VIPM_Result *VIPM_Convert(u32 max_sliding_window = u32(-1), float error_tolerance = 0.1f, u32 optimize_vertex_order = 1); + ETOOLS_API void VIPM_Destroy(); +}; + +#endif // PropSlimToolsH \ No newline at end of file diff --git a/src/editors/xrECore/Editor/SkeletonFace.h b/src/editors/xrECore/Editor/SkeletonFace.h new file mode 100644 index 00000000000..112bae64042 --- /dev/null +++ b/src/editors/xrECore/Editor/SkeletonFace.h @@ -0,0 +1,40 @@ +#ifndef _SkeletonFace_H_ +#define _SkeletonFace_H_ +#pragma once + +#include "SkeletonVert.h" + +struct st_SFACE; +void RegisterSFACE(st_SFACE *f); + +struct st_SFACE +{ + st_SVERT *v[3]; + DWORD m; + + st_SFACE() + { + RegisterSFACE(this); + } + void VSet(int id, st_SVERT *V) + { + v[id] = V; + } + void SetVerts(st_SVERT *v1, st_SVERT *v2, st_SVERT *v3) + { + VSet(0, v1); + VSet(1, v2); + VSet(2, v3); + } + void ReplaceVert(st_SVERT *from, st_SVERT *to) + { + if (v[0] == from) + VSet(0, to); + if (v[1] == from) + VSet(1, to); + if (v[2] == from) + VSet(2, to); + } +}; +DEFINE_VECTOR(st_SFACE *, vSFACE, SFACEIt); +#endif // _SkeletonFace_H_ diff --git a/src/editors/xrECore/Editor/SkeletonVert.h b/src/editors/xrECore/Editor/SkeletonVert.h new file mode 100644 index 00000000000..cd64dd0bbd4 --- /dev/null +++ b/src/editors/xrECore/Editor/SkeletonVert.h @@ -0,0 +1,62 @@ +#ifndef _SkeletonVert_H_ +#define _SkeletonVert_H_ +#pragma once + +struct st_SVERT; +void RegisterSVERT(st_SVERT *v); + +const DWORD BONE_NONE = 0xffffffff; + +struct st_SVERT +{ + Fvector P; + Fvector O; + Fvector N; + DWORD sm_group; + Fvector2Vec uv; + DWORD bone; + + st_SVERT() + { + P.set(0, 0, 0); + N.set(0, 1, 0); + uv.clear(); + bone = BONE_NONE; + RegisterSVERT(this); + } + void AppendUV(float _u, float _v) + { + uv.push_back(Fvector2()); + uv.back().set(_u, _v); + } + void SetBone(DWORD B) + { + if (bone == BONE_NONE) + { + bone = B; + } + else + R_ASSERT(bone == B); + } + BOOL similar(st_SVERT &V) + { + if (bone != V.bone) + return FALSE; + if (uv.size() != V.uv.size()) + return FALSE; + for (DWORD i = 0; i < uv.size(); i++) + { + if (!fsimilar(uv[i].x, V.uv[i].x)) + return FALSE; + if (!fsimilar(uv[i].y, V.uv[i].y)) + return FALSE; + } + if (!O.similar(V.O)) + return FALSE; + if (!N.similar(V.N)) + return FALSE; + return TRUE; + } +}; +DEFINE_VECTOR(st_SVERT *, vSVERT, SVERTIt); +#endif //_SkeletonVert_H_ diff --git a/src/editors/xrECore/Editor/SoundManager.cpp b/src/editors/xrECore/Editor/SoundManager.cpp new file mode 100644 index 00000000000..2bbd661f937 --- /dev/null +++ b/src/editors/xrECore/Editor/SoundManager.cpp @@ -0,0 +1,440 @@ +#include "stdafx.h" +#include "SoundManager.h" +#include "EThumbnail.h" +#include "ui_main.h" + +CSoundManager *SndLib = 0; + +extern "C" int ogg_enc(const char *in_fn, const char *out_fn, float quality, void *comment, int size); + +xr_string CSoundManager::UpdateFileName(xr_string &fn) +{ + return EFS.AppendFolderToName(fn, -1, FALSE); +} + +// возвращает список всех звуков +int CSoundManager::GetSounds(FS_FileSet &files, BOOL bFolders) +{ + return FS.file_list(files, _sounds_, (bFolders ? FS_ListFolders : 0) | FS_ListFiles | FS_ClampExt, "*.wav"); +} + +int CSoundManager::GetGameSounds(FS_FileSet &files) +{ + return FS.file_list(files, _game_sounds_, FS_ListFiles | FS_ClampExt, "*.ogg"); +} + +int CSoundManager::GetSoundEnvs(AStringVec &items) +{ + /* + SoundEnvironment_LIB* Lib = Sound->get_env_library(); + if (Lib){ + for (SoundEnvironment_LIB::SE_IT it=Lib->Library().begin(); it!=Lib->Library().end(); it++) + items.push_back(*(*it)->name); + } + return items.size(); + */ + return 0; +} + +bool CSoundManager::OnCreate() +{ + //. psSoundFreq = sf_44K; + // psSoundFlags.set (ssHardware,FALSE); + ISoundManager::_create_devices_list(); + ISoundManager::_create(); + return true; +} + +void CSoundManager::OnDestroy() +{ + ISoundManager::_destroy(); +} + +void CSoundManager::OnFrame() +{ + ::psSoundVEffects = psDeviceFlags.is(rsMuteSounds) ? 0.f : 1.f; + GEnv.Sound->update(EDevice.m_Camera.GetPosition(), EDevice.m_Camera.GetDirection(), EDevice.m_Camera.GetNormal()); +} + +void CSoundManager::MuteSounds(BOOL bVal) +{ + if (bVal) + ::psSoundVEffects = 0.f; + else + ::psSoundVEffects = psDeviceFlags.is(rsMuteSounds) ? 0.f : 1.f; +} + +void CSoundManager::RenameSound(LPCSTR nm0, LPCSTR nm1, EItemType type) +{ + if (TYPE_FOLDER == type) + { + FS.dir_delete(_sounds_, nm0, FALSE); + FS.dir_delete(_game_sounds_, nm0, FALSE); + } + else if (TYPE_OBJECT == type) + { + string_path fn0, fn1, temp; + // rename base file + FS.update_path(fn0, _sounds_, nm0); + strcat(fn0, ".wav"); + FS.update_path(fn1, _sounds_, nm1); + strcat(fn1, ".wav"); + FS.file_rename(fn0, fn1, false); + + // rename thm + FS.update_path(fn0, _sounds_, nm0); + strcat(fn0, ".thm"); + FS.update_path(fn1, _sounds_, nm1); + strcat(fn1, ".thm"); + FS.file_rename(fn0, fn1, false); + + // rename ogg + FS.update_path(fn0, _game_sounds_, nm0); + strcat(fn0, ".ogg"); + FS.update_path(fn1, _game_sounds_, nm1); + strcat(fn1, ".ogg"); + FS.file_rename(fn0, fn1, false); + GEnv.Sound->refresh_sources(); + } +} + +BOOL CSoundManager::RemoveSound(LPCSTR fname, EItemType type) +{ + if (TYPE_FOLDER == type) + { + FS.dir_delete(_sounds_, fname, FALSE); + FS.dir_delete(_game_sounds_, fname, FALSE); + return TRUE; + } + else if (TYPE_OBJECT == type) + { + xr_string src_name; + src_name = EFS.ChangeFileExt(fname, ".wav"); + if (FS.exist(_sounds_, src_name.c_str())) + { + xr_string thm_name = EFS.ChangeFileExt(fname, ".thm"); + xr_string game_name = EFS.ChangeFileExt(fname, ".ogg"); + // source + FS.file_delete(_sounds_, src_name.c_str()); + // thumbnail + FS.file_delete(_sounds_, thm_name.c_str()); + // game + FS.file_delete(_game_sounds_, game_name.c_str()); + GEnv.Sound->refresh_sources(); + return TRUE; + } + } + return FALSE; +} + +//------------------------------------------------------------------------------ +// возвращает список новых звуков +//------------------------------------------------------------------------------ +int CSoundManager::GetLocalNewSounds(FS_FileSet &files) +{ + return FS.file_list(files, _import_, FS_ListFiles | FS_RootOnly | FS_ClampExt, "*.wav"); +} + +//------------------------------------------------------------------------------ +// копирует обновленные звуки с Import'a в Sounds +// files - список файлов для копирование +//------------------------------------------------------------------------------ +/* +void CSoundManager::SafeCopyLocalToServer(FS_FileSet& files) +{ + xr_string p_import,p_sounds; + xr_string src_name,dest_name; + FS.update_path (p_import,_import_,""); + FS.update_path (p_sounds,_sounds_,""); + + auto it = files.begin(); + auto _E = files.end(); + for (; it!=_E; it++){ + // copy thm + xr_string fn = EFS.ChangeFileExt(it->first,".thm"); + src_name = p_import + fn; + UpdateFileName (fn); + dest_name = p_sounds + fn; + FS.file_rename (src_name.c_str(),dest_name.c_str(),true); + // copy sources + fn = EFS.ChangeFileExt(it->first,".wav"); + src_name = p_import + fn; + UpdateFileName (fn); + dest_name = p_sounds + fn; + if (FS.exist(dest_name.c_str())){ + EFS.BackupFile (_sounds_,EFS.ChangeFileExt(fn,".wav").c_str()); + EFS.BackupFile (_sounds_,EFS.ChangeFileExt(fn,".thm").c_str()); + } + FS.file_copy (src_name.c_str(),dest_name.c_str()); + FS.set_file_age (dest_name.c_str(),FS.get_file_age(src_name.c_str())); + EFS.WriteAccessLog (dest_name.c_str(),"Replace"); + EFS.MarkFile (src_name.c_str(),true); + } +} +*/ +//------------------------------------------------------------------------------ +// создает тхм +//------------------------------------------------------------------------------ +void CSoundManager::CreateSoundThumbnail(ESoundThumbnail *THM, const xr_string &src_name, LPCSTR initial, bool bSetDefParam) +{ + R_ASSERT(src_name.size()); + string_path base_name; + if (initial) + FS.update_path(base_name, initial, src_name.c_str()); + else + FS.update_path(base_name, _sounds_, src_name.c_str()); + strcpy(base_name, EFS.ChangeFileExt(base_name, ".wav").c_str()); + + // выставить начальные параметры + if (bSetDefParam) + { + THM->m_Age = FS.get_file_age(base_name); + THM->m_fQuality = 0.f; + THM->m_fMinDist = 1.f; + THM->m_uGameType = 0; + } +} + +void CSoundManager::MakeGameSound(ESoundThumbnail *THM, LPCSTR src_name, LPCSTR game_name) +{ + VerifyPath(game_name); + CMemoryWriter F; + F.w_u32(OGG_COMMENT_VERSION); + F.w_float(THM->m_fMinDist); + F.w_float(THM->m_fMaxDist); + F.w_float(THM->m_fBaseVolume); + F.w_u32(THM->m_uGameType); + F.w_float(THM->m_fMaxAIDist); + + if (!ogg_enc(src_name, game_name, THM->m_fQuality, F.pointer(), F.size())) + { + FS.file_delete(game_name); + ELog.DlgMsg(mtError, "Can't make game sound '%s'.", game_name); + } +} + +//------------------------------------------------------------------------------ +// возвращает список не синхронизированных (модифицированных) текстур +// source_list - содержит список текстур с расширениями +// sync_list - реально сохраненные файлы (после использования освободить) +//------------------------------------------------------------------------------ +void CSoundManager::SynchronizeSounds(bool sync_thm, bool sync_game, bool bForceGame, FS_FileSet *source_list, AStringVec *sync_list, FS_FileSet *modif_map) +{ + FS_FileSet M_BASE; + FS_FileSet M_THUM; + FS_FileSet M_GAME; + + if (source_list) + M_BASE = *source_list; + else + FS.file_list(M_BASE, _sounds_, FS_ListFiles | FS_ClampExt, "*.wav"); + + if (M_BASE.empty()) + return; + + if (sync_thm) + FS.file_list(M_THUM, _sounds_, FS_ListFiles | FS_ClampExt, "*.thm"); + + if (sync_game) + FS.file_list(M_GAME, _game_sounds_, FS_ListFiles | FS_ClampExt, "*.ogg"); + + bool bProgress = (M_BASE.size() > 1); + + int m_age = time(NULL); + + SPBItem *pb = 0; + if (bProgress) + pb = UI->ProgressStart(static_cast(M_BASE.size()), "Synchronize sounds..."); + + auto it = M_BASE.begin(); + auto it_e = M_BASE.end(); + for (; it != it_e; ++it) + { + BOOL bUpdated = FALSE; + xr_string base_name = EFS.ChangeFileExt(it->name, ""); + xr_strlwr(base_name); + string_path fn; + FS.update_path(fn, _sounds_, EFS.ChangeFileExt(base_name, ".wav").c_str()); + if (!FS.exist(fn)) + continue; + + auto th = M_THUM.find(base_name); + bool bThm = ((th == M_THUM.end()) || ((th != M_THUM.end()) && (th->time_write != it->time_write))); + auto gm = M_GAME.find(base_name); + bool bGame = bThm || ((gm == M_GAME.end()) || ((gm != M_GAME.end()) && (gm->time_write != it->time_write))); + + ESoundThumbnail *THM = 0; + + // backup base sound + // check thumbnail + if (sync_thm && bThm) + { + THM = xr_new(it->name.c_str()); + THM->Save(m_age); + bUpdated = TRUE; + } + // check game sounds + if (bForceGame || (sync_game && bGame)) + { + if (!THM) + THM = xr_new(it->name.c_str()); + R_ASSERT(THM); + string_path src_name; + strconcat(sizeof(src_name), src_name, base_name.c_str(), ".wav"); + + FS.update_path(src_name, _sounds_, src_name); + string_path game_name; + strconcat(sizeof(game_name), game_name, base_name.c_str(), ".ogg"); + FS.update_path(game_name, _game_sounds_, game_name); + MakeGameSound(THM, src_name, game_name); + + if (sync_list) + sync_list->push_back(base_name.c_str()); + + if (modif_map) + modif_map->insert(*it); + + bUpdated = TRUE; + } + + if (THM) + xr_delete(THM); + + if (UI->NeedAbort()) + break; + + if (bProgress) + pb->Inc(bUpdated ? xr_string(base_name + " - UPDATED.").c_str() : "", bUpdated); + + if (bUpdated) + { + string_path wav_fn, thm_fn, ogg_fn; + FS.update_path(wav_fn, _sounds_, EFS.ChangeFileExt(base_name, ".wav").c_str()); + FS.update_path(thm_fn, _sounds_, EFS.ChangeFileExt(base_name, ".thm").c_str()); + FS.update_path(ogg_fn, _game_sounds_, EFS.ChangeFileExt(base_name, ".ogg").c_str()); + FS.set_file_age(wav_fn, m_age); + FS.set_file_age(thm_fn, m_age); + FS.set_file_age(ogg_fn, m_age); + } + } + if (bProgress) + UI->ProgressEnd(pb); +} + +void CSoundManager::CleanupSounds() +{ + FS_FileSet M_BASE; + FS_FileSet M_THUM; + FS_FileSet M_GAME; + FS_FileSet M_GAME_DEL; + FS_FileSet M_THM_DEL; + + FS.file_list(M_BASE, _sounds_, FS_ListFiles | FS_ClampExt, "*.wav"); + FS.file_list(M_THUM, _sounds_, FS_ListFiles | FS_ClampExt, "*.thm"); + FS.file_list(M_GAME, _game_sounds_, FS_ListFiles | FS_ClampExt, "*.ogg"); + + // check source exist + auto it = M_GAME.begin(); + auto it_e = M_GAME.end(); + + for (; it != it_e; ++it) + { + xr_string base_name = EFS.ChangeFileExt(it->name, ""); + xr_strlwr(base_name); + auto bs = M_BASE.find(base_name); + + if (bs == M_BASE.end()) + M_GAME_DEL.insert(*it); + } + it = M_THUM.begin(); + it_e = M_THUM.end(); + + for (; it != it_e; ++it) + { + xr_string base_name = EFS.ChangeFileExt(it->name, ""); + xr_strlwr(base_name); + auto bs = M_BASE.find(base_name); + if (bs == M_BASE.end()) + M_THM_DEL.insert(*it); + } + + SPBItem *pb = UI->ProgressStart(static_cast(M_GAME_DEL.size() + M_THM_DEL.size()), "Cleanup sounds..."); + // mark game del sounds + it = M_GAME_DEL.begin(); + it_e = M_GAME_DEL.end(); + + for (; it != it_e; ++it) + { + xr_string base_name = EFS.ChangeFileExt(it->name, ""); + xr_strlwr(base_name); + string_path fn; + FS.update_path(fn, _game_sounds_, EFS.ChangeFileExt(base_name, ".ogg").c_str()); + EFS.MarkFile(fn, true); + pb->Inc(); + } + // mark thm sounds + it = M_THM_DEL.begin(); + it_e = M_THM_DEL.end(); + for (; it != it_e; ++it) + { + xr_string base_name = EFS.ChangeFileExt(it->name, ""); + xr_strlwr(base_name); + string_path fn; + FS.update_path(fn, _sounds_, EFS.ChangeFileExt(base_name, ".thm").c_str()); + EFS.MarkFile(fn, true); + pb->Inc(); + } + UI->ProgressEnd(pb); +} + +/* +void CSoundManager::ChangeFileAgeTo(FS_FileSet* tgt_map, int age) +{ + VERIFY(tgt_map); + FS_FileSet* M_BASE = tgt_map; + + // lock rescanning + FS.lock_rescan (); + // change + SPBItem* pb=0; + if (M_BASE->size()>1) pb = UI->ProgressStart(M_BASE->size(),"Change sounds age..."); + auto it = M_BASE->begin(); + auto _E = M_BASE->end(); + for (; it!=_E; it++){ + xr_string base_name = EFS.ChangeFileExt(it->first,""); xr_strlwr(base_name); + xr_string wav_fn,thm_fn,ogg_fn; + FS.update_path (wav_fn,_sounds_, EFS.ChangeFileExt(base_name,".wav").c_str()); + FS.update_path (thm_fn,_sounds_, EFS.ChangeFileExt(base_name,".thm").c_str()); + FS.update_path (ogg_fn,_game_sounds_, EFS.ChangeFileExt(base_name,".ogg").c_str()); + FS.set_file_age (wav_fn.c_str(),age); + FS.set_file_age (thm_fn.c_str(),age); + FS.set_file_age (ogg_fn.c_str(),age); + if (pb) pb->Inc(); + } + if (pb) UI->ProgressEnd(pb); + // lock rescanning + FS.unlock_rescan (); +} +*/ +//------------------------------------------------------------------------------ +// если передан параметр modif - обновляем DX-Surface only и только из списка +// иначе полная синхронизация +//------------------------------------------------------------------------------ +void CSoundManager::RefreshSounds(bool bSync) +{ + if (FS.can_write_to_alias(_sounds_)) + { + UI->SetStatus("Refresh sounds..."); + if (bSync) + { + SynchronizeSounds(true, true, false, 0, 0); + CleanupSounds(); + } + GEnv.Sound->refresh_sources(); + UI->SetStatus(""); + } + else + { + Log("#!You don't have permisions to modify sounds."); + } +} diff --git a/src/editors/xrECore/Editor/SoundManager.h b/src/editors/xrECore/Editor/SoundManager.h new file mode 100644 index 00000000000..8ee106cf422 --- /dev/null +++ b/src/editors/xrECore/Editor/SoundManager.h @@ -0,0 +1,46 @@ +//--------------------------------------------------------------------------- +#ifndef SoundManagerH +#define SoundManagerH + +// refs +class ESoundThumbnail; + +class ECORE_API CSoundManager +{ +public: + void MakeGameSound(ESoundThumbnail *THM, LPCSTR src_name, LPCSTR game_name); + CSoundManager() {} + virtual ~CSoundManager() { ; } + + BOOL RemoveSound(LPCSTR fname, EItemType type); + void RenameSound(LPCSTR p0, LPCSTR p1, EItemType type); + + // texture routines + int GetSounds(FS_FileSet &files, BOOL bFolders = FALSE); + int GetGameSounds(FS_FileSet &files); + int GetSoundEnvs(AStringVec &items); + + int GetLocalNewSounds(FS_FileSet &files); + // void SafeCopyLocalToServer(FS_FileSet& files); + void SynchronizeSounds(bool sync_thm, bool sync_game, bool bForceGame, FS_FileSet *source_map, AStringVec *sync_list_without_extention, FS_FileSet *modif_map = 0); + // void ChangeFileAgeTo (FS_FileSet* tgt_map, int age); + void CreateSoundThumbnail(ESoundThumbnail *THM, const xr_string &src_name, LPCSTR path = 0, bool bSetDefParam = true); + void CleanupSounds(); + + bool OnCreate(); + void OnDestroy(); + + virtual void OnFrame(); + + virtual bool Validate() { return true; } + + void MuteSounds(BOOL bVal); + + void RefreshSounds(bool bSync); + + xr_string UpdateFileName(xr_string &fn); +}; + +extern ECORE_API CSoundManager *SndLib; +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/xrECore/Editor/TLSPRITE.CPP b/src/editors/xrECore/Editor/TLSPRITE.CPP new file mode 100644 index 00000000000..cc7491b3f56 --- /dev/null +++ b/src/editors/xrECore/Editor/TLSPRITE.CPP @@ -0,0 +1,237 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "tlsprite.h" +#include "ui_main.h" +#include "d3dutils.h" + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// +CTLSprite::CTLSprite() +{ + mesh.setcolor(0xFFFFFFFF); + mesh.setdepth(); + mesh.settex(0, 0, 1, 1); +} + +CTLSprite::~CTLSprite() +{ +} + +void CTLSprite::Render(Fvector &pos, float radius, bool bFixedSize, u32 clr) +{ + FVF::TL P; + float cx, cy, sz; + + P.transform(pos, EDevice.mFullTransform); + cx = EDevice._x2real(P.p.x); + cy = EDevice._y2real(P.p.y); + if (bFixedSize) + sz = EDevice._x2real(radius) - EDevice._x2real(0); + else + sz = UI->GetRenderWidth() * radius / P.p.w; + mesh.m[0].p.x = cx - sz; + mesh.m[0].p.y = cy + sz; + mesh.m[1].p.x = cx - sz; + mesh.m[1].p.y = cy - sz; + mesh.m[3].p.x = cx + sz; + mesh.m[3].p.y = cy - sz; + mesh.m[2].p.x = cx + sz; + mesh.m[2].p.y = cy + sz; + mesh.setdepth(P.p.z, P.p.w); + mesh.setcolor(clr); + + DU_impl.DrawPrimitiveTL(D3DPT_TRIANGLESTRIP, 2, (FVF::TL *)&mesh, 4, false, false); +} + +void CTLSprite::Render(Fvector &pos, u32 color, float radius, float angle) +{ + FVF::TL P; + + P.transform(pos, EDevice.mFullTransform); + if (P.p.w <= 0) + return; + + float cx = EDevice._x2real(P.p.x); + float cy = EDevice._y2real(P.p.y); + + float sz = (UI->GetRenderWidth() * radius) / P.p.w; + if (sz < 1.5f) + return; + + // Rotation + float _sin1 = _sin(angle), _cos1 = _cos(angle); + float _sin2 = _sin(angle + PI_DIV_2), _cos2 = _cos(angle + PI_DIV_2); + + mesh.m[0].p.x = cx + sz * _sin1; + mesh.m[0].p.y = cy + sz * _cos1; + mesh.m[1].p.x = cx - sz * _sin2; + mesh.m[1].p.y = cy - sz * _cos2; + mesh.m[2].p.x = cx + sz * _sin2; + mesh.m[2].p.y = cy + sz * _cos2; + mesh.m[3].p.x = cx - sz * _sin1; + mesh.m[3].p.y = cy - sz * _cos1; + + mesh.setdepth(P.p.z, P.p.w); + mesh.setcolor(color); + + DU_impl.DrawPrimitiveTL(D3DPT_TRIANGLESTRIP, 2, (FVF::TL *)&mesh, 4, false, false); +} + +void CTLSprite::Render(Fvector &pos, u32 color, float radius, const Fvector &D) +{ + Fvector P1, P2; + P1.mad(pos, D, -radius); + P2.mad(pos, D, radius); + + FVF::TL s1, s2; + s1.transform(P1, EDevice.mFullTransform); + s2.transform(P2, EDevice.mFullTransform); + + if ((s1.p.w <= 0) || (s2.p.w <= 0)) + return; + + float l1 = radius / s1.p.w * 1.4142f; + float l2 = radius / s2.p.w * 1.4142f; + + Fvector2 dir, R; + dir.set(s2.p.x - s1.p.x, s2.p.y - s1.p.y); + dir.norm(); + R.cross(dir); + + mesh.m[0].p.x = EDevice._x2real(s1.p.x + l1 * R.x); + mesh.m[0].p.y = EDevice._y2real(s1.p.y + l1 * R.y); + mesh.m[0].p.z = s2.p.z; + mesh.m[0].p.w = s2.p.w; + mesh.m[1].p.x = EDevice._x2real(s2.p.x + l2 * R.x); + mesh.m[1].p.y = EDevice._y2real(s2.p.y + l2 * R.y); + mesh.m[1].p.z = s2.p.z; + mesh.m[1].p.w = s2.p.w; + mesh.m[2].p.x = EDevice._x2real(s1.p.x - l1 * R.x); + mesh.m[2].p.y = EDevice._y2real(s1.p.y - l1 * R.y); + mesh.m[2].p.z = s2.p.z; + mesh.m[2].p.w = s2.p.w; + mesh.m[3].p.x = EDevice._x2real(s2.p.x - l2 * R.x); + mesh.m[3].p.y = EDevice._y2real(s2.p.y - l2 * R.y); + mesh.m[3].p.z = s2.p.z; + mesh.m[3].p.w = s2.p.w; + + mesh.setcolor(color); + + DU_impl.DrawPrimitiveTL(D3DPT_TRIANGLESTRIP, 2, (FVF::TL *)&mesh, 4, false, false); + /* + float radius = size*0.5f; + + Fvector P1,P2; + P1.direct (pos,D,radius); + P2.direct (pos,D,-radius); + + FVF::TL s1,s2; + s1.transform (P1,EDevice.m_FullTransform); + s2.transform (P2,EDevice.m_FullTransform); + + if ((s1.p.w<=0)||(s2.p.w<=0)) return; + + float l1 = radius/s1.p.w*1.4142f; + float l2 = radius/s2.p.w*1.4142f; + + Fvector2 dir,R; + dir.set (s2.p.x-s1.p.x,s2.p.y-s1.p.y); + dir.norm (); + R.cross (dir); + + mesh.m[0].p.x = X_TO_REAL(s1.p.x+l1*R.x); mesh.m[0].p.y = Y_TO_REAL(s1.p.y+l1*R.y); mesh.m[0].p.z = s1.p.z; mesh.m[0].p.w = s1.p.w; + mesh.m[1].p.x = X_TO_REAL(s2.p.x+l2*R.x); mesh.m[1].p.y = Y_TO_REAL(s2.p.y+l2*R.y); mesh.m[1].p.z = s2.p.z; mesh.m[1].p.w = s2.p.w; + mesh.m[2].p.x = X_TO_REAL(s1.p.x-l1*R.x); mesh.m[2].p.y = Y_TO_REAL(s1.p.y-l1*R.y); mesh.m[2].p.z = s1.p.z; mesh.m[2].p.w = s1.p.w; + mesh.m[3].p.x = X_TO_REAL(s2.p.x-l2*R.x); mesh.m[3].p.y = Y_TO_REAL(s2.p.y-l2*R.y); mesh.m[3].p.z = s2.p.z; mesh.m[3].p.w = s2.p.w; + // mesh.m[1].p.x = X_TO_REAL(s2.p.x); mesh.m[1].p.y = Y_TO_REAL(s2.p.y); mesh.m[1].p.z = s2.p.z; mesh.m[1].p.w = s2.p.w; + // mesh.m[1].tu = 0.5f; mesh.m[1].tv = 0.f; + + mesh.setcolor (RGBA_MAKE(iFloor(color.r),iFloor(color.g),iFloor(color.b),iFloor(color.a))); + + EDevice.DP (D3DPT_TRIANGLESTRIP, FVF::F_TL, &mesh, 4); + */ + /* Fvector2 dir; + dir.x = p1.x-p0.x; + dir.y = p1.y-p0.y; + dir.norm_safe (); + + Fvector P0,P1; + P0.direct (pos,); + + FVF::TL P; + P.transform (pos,EDevice.m_FullTransform); + float sz = UI->GetRenderWidth()*radius/P.p.w; + float sz0 = radius/P.p.w;//(radius/p0.w)/2; + float sz1 = radius/P.p.w;//radius/p1.w; + Fvector2 D,R; + D.x = (dir.x-dir.y)*0.7071f; + D.y = (dir.x+dir.y)*0.7071f; + R.cross (D); + + float cx = X_TO_REAL(P.p.x); + float cy = Y_TO_REAL(P.p.y); + + mesh.m[0].p.x = X_TO_REAL(p0.x+sz0*R.x); mesh.m[0].p.y = Y_TO_REAL(p0.y+sz0*R.y); + mesh.m[1].p.x = X_TO_REAL(p1.x+sz1*R.x); mesh.m[1].p.y = Y_TO_REAL(p1.y+sz1*R.y); + mesh.m[2].p.x = X_TO_REAL(p0.x-sz0*R.x); mesh.m[2].p.y = Y_TO_REAL(p0.y-sz0*R.y); + mesh.m[3].p.x = X_TO_REAL(p1.x-sz1*R.x); mesh.m[3].p.y = Y_TO_REAL(p1.y-sz1*R.y); + + mesh.setdepth (P.p.z, P.p.w); + mesh.setcolor (RGBA_MAKE(iFloor(color.r),iFloor(color.g),iFloor(color.b),iFloor(color.a))); + + EDevice.DP (D3DPT_TRIANGLESTRIP, FVF::F_TL, &mesh, 4); + */ +} + +/* +void CTLSprite::UpdateTC(){ + float tu,tv; + int frame; + + float fSPF = fPlayTime/float(iCount); + fLocalTime +=EDevice.fTimeDelta; + if (fLocalTime>=fPlayTime) fLocalTime-=fPlayTime; + frame = iFloor( fLocalTime/fSPF ); + + tu =(frame%iFrameDim)*fTexSize; + tv =(frame/iFrameDim)*fTexSize; + + mesh.m[0].tu=tu+fTexSize; mesh.m[0].tv=tv+fTexSize; + mesh.m[1].tu=tu; mesh.m[1].tv=tv+fTexSize; + mesh.m[2].tu=tu; mesh.m[2].tv=tv; + mesh.m[3].tu=tu+fTexSize; mesh.m[3].tv=tv; +} + +void CTLSprite::Render( Fvector &pos, float alpha, float size, float scale ) +{ + FTLvertex P; + FPcolor cur; + float s_da, s_da2, c_da, c_da2; + uchar cc; + + P.s_transform ( pos, UI->m_FullTransform ); + float cx = X_TO_REAL(P.sx); + float cy = Y_TO_REAL(P.sy); + + float dx = size/P.rhw * scale * UI->GetRenderWidth() / 2; + float dy = size/P.rhw / scale * UI->GetRenderWidth() / 2; + + cc = uchar(255.f*alpha); + cur.set (cc,cc,cc,255); + + c_da = dy*0.707106f; + s_da = -dx*0.707106f; + + mesh.m[0].sx = cx + s_da; mesh.m[0].sy = cy + c_da; + mesh.m[1].sx = cx + s_da; mesh.m[1].sy = cy - c_da; + mesh.m[3].sx = cx - s_da; mesh.m[3].sy = cy - c_da; + mesh.m[2].sx = cx - s_da; mesh.m[2].sy = cy + c_da; + + mesh.setdepth ( P.sz, P.rhw ); + mesh.setcolor ( cur ); + + CDX( UI->d3d()->DrawPrimitive( D3DPT_TRIANGLESTRIP, FTLVERTEX, &mesh, 4, 0 )); + UI->stat->lRenderPolyCount += 2; +}*/ diff --git a/src/editors/xrECore/Editor/TLSPRITE.h b/src/editors/xrECore/Editor/TLSPRITE.h new file mode 100644 index 00000000000..b1332842c4b --- /dev/null +++ b/src/editors/xrECore/Editor/TLSPRITE.h @@ -0,0 +1,169 @@ +#ifndef TLSpriteH +#define TLSpriteH + +#define TO_REAL(_X_, _S_) ((_X_) + 1.f) * float(_S_ / 2) + +typedef struct _TLpolygon +{ +public: + union + { + struct + { + FVF::TL lb, lt, rb, rt; + }; + FVF::TL m[4]; + }; + + IC void *d3d(void) { return this; } + IC void setpos(Frect &r) + { + lb.p.x = r.x1; + lb.p.y = r.y2; + lt.p.x = r.x1; + lt.p.y = r.y1; + rb.p.x = r.x2; + rb.p.y = r.y2; + rt.p.x = r.x2; + rt.p.y = r.y1; + } + IC void setpos(float x1, float y1, float x2, float y2) + { + lb.p.x = x1; + lb.p.y = y2; + lt.p.x = x1; + lt.p.y = y1; + rb.p.x = x2; + rb.p.y = y2; + rt.p.x = x2; + rt.p.y = y1; + } + IC void setdepth(float z = 0.f, float rhw = 1.f) + { + lb.p.z = z; + rb.p.z = z; + lt.p.z = z; + rt.p.z = z; + lb.p.w = rhw; + rb.p.w = rhw; + lt.p.w = rhw; + rt.p.w = rhw; + }; + IC void setcolor(u32 c) + { + lb.color = c; + rb.color = c; + lt.color = c; + rt.color = c; + }; + IC void settex(Frect &r) + { + lb.uv.x = r.x1; + lb.uv.y = r.y2; + lt.uv.x = r.x1; + lt.uv.y = r.y1; + rb.uv.x = r.x2; + rb.uv.y = r.y2; + rt.uv.x = r.x2; + rt.uv.y = r.y1; + } + IC void settex(float x1, float y1, float x2, float y2) + { + lb.uv.x = x1; + lb.uv.y = y2; + lt.uv.x = x1; + lt.uv.y = y1; + rb.uv.x = x2; + rb.uv.y = y2; + rt.uv.x = x2; + rt.uv.y = y1; + } + + IC void to_real(int w, int h) + { + lt.p.x = lb.p.x = TO_REAL(lb.p.x, w); + rb.p.x = rt.p.x = TO_REAL(rb.p.x, w); + lt.p.y = rt.p.y = TO_REAL(lt.p.y, h); + lb.p.y = rb.p.y = TO_REAL(lb.p.y, h); + } + + IC void to_real(Frect &r, int w, int h) + { + lt.p.x = lb.p.x = TO_REAL(r.x1, w); + lt.p.y = rt.p.y = TO_REAL(r.y1, h); + rb.p.x = rt.p.x = TO_REAL(r.x2, w); + lb.p.y = rb.p.y = TO_REAL(r.y2, h); + } + + IC void add(float dx, float dy) + { + lb.p.x += dx; + lb.p.y += dy; + lt.p.x += dx; + lt.p.y += dy; + rb.p.x += dx; + rb.p.y += dy; + rt.p.x += dx; + rt.p.y += dy; + } + + IC void add(Frect &r, float dx, float dy) + { + lb.p.x = r.x1 + dx; + lb.p.y = r.y2 + dy; + lt.p.x = r.x1 + dx; + lt.p.y = r.y1 + dy; + rb.p.x = r.x2 + dx; + rb.p.y = r.y2 + dy; + rt.p.x = r.x2 + dx; + rt.p.y = r.y1 + dy; + } + + IC void sub(float dx, float dy) + { + lb.p.x -= dx; + lb.p.y -= dy; + lt.p.x -= dx; + lt.p.y -= dy; + rb.p.x -= dx; + rb.p.y -= dy; + rt.p.x -= dx; + rt.p.y -= dy; + } + + IC void sub(Frect &r, float dx, float dy) + { + lb.p.x = r.x1 - dx; + lb.p.y = r.y2 - dy; + lt.p.x = r.x1 - dx; + lt.p.y = r.y1 - dy; + rb.p.x = r.x2 - dx; + rb.p.y = r.y2 - dy; + rt.p.x = r.x2 - dx; + rt.p.y = r.y1 - dy; + } +} FTLpolygon; + +class ECORE_API CTLSprite +{ + FTLpolygon mesh; + +public: + CTLSprite(); + virtual ~CTLSprite(); + void Render(Fvector &pos, u32 color, float radius, float angle); + IC void Render(Fvector &pos, u32 color, float radius, float angle, const Fvector2 <, const Fvector2 &rb) + { + mesh.settex(lt.x, lt.y, rb.x, rb.y); + Render(pos, color, radius, angle); + } + void Render(Fvector &pos, u32 color, float radius, const Fvector &D); + IC void Render(Fvector &pos, u32 color, float radius, const Fvector &D, const Fvector2 <, const Fvector2 &rb) + { + mesh.settex(lt.x, lt.y, rb.x, rb.y); + Render(pos, color, radius, D); + } + void Render(Fvector &pos, float radius, bool bFixedSize, u32 clr = 0xffffffff); +}; + +#endif //__TLSPRITE_H__ diff --git a/src/editors/xrECore/Editor/UIEditLightAnim.cpp b/src/editors/xrECore/Editor/UIEditLightAnim.cpp new file mode 100644 index 00000000000..85fc3e986ef --- /dev/null +++ b/src/editors/xrECore/Editor/UIEditLightAnim.cpp @@ -0,0 +1,607 @@ +#include "stdafx.h" +#include "UIEditLightAnim.h" +#include "xrEngine/LightAnimLibrary.h" + +#define POINTER_HEIGHT 35 + +UIEditLightAnim *UIEditLightAnim::Form = nullptr; +UIEditLightAnim::UIEditLightAnim() +{ + m_Modife = false; + m_Items = xr_new(); + m_Items->SetOnItemFocusedEvent(TOnILItemFocused(this, &UIEditLightAnim::OnItemFocused)); + m_Items->SetOnItemCreaetEvent(TOnItemCreate(this, &UIEditLightAnim::OnCreateItem)); + m_Items->SetOnItemCloneEvent(TOnItemClone(this, &UIEditLightAnim::OnCloneItem)); + m_Items->SetOnItemRemoveEvent(TOnItemRemove(this, &UIEditLightAnim::OnRemoveItem)); + m_Items->SetOnItemRenameEvent(TOnItemRename(this, &UIEditLightAnim::OnRenameItem)); + m_Items->m_Flags.set(UIItemListForm::fMenuEdit, true); + m_Props = xr_new(); + m_Props->SetModifiedEvent(TOnModifiedEvent(this, &UIEditLightAnim::OnModified)); + m_CurrentItem = nullptr; + + m_TextureNull.create("ed\\ed_nodata"); + m_TextureNull->Load(); + m_Texture = nullptr; + m_PointerWeight = -1; + m_PointerResize = true; + m_PointerTexture = nullptr; + m_PointerValue = 0; + m_RenderAlpha = false; + R_CHK(HW.pDevice->CreateTexture(32, 32, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_ItemTexture, 0)); + + InitializeItems(); +} + +UIEditLightAnim::~UIEditLightAnim() +{ + if (m_Modife) + { + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Save current change?") == mrYes) + { + LALib.Save(); + } + else + { + LALib.Reload(); + } + } + m_ItemTexture->Release(); + if (m_PointerTexture) + { + m_PointerTexture->Release(); + xr_delete(m_PointerRawImage); + } + if (m_Texture) + { + m_Texture->Release(); + } + m_TextureNull.destroy(); + xr_delete(m_Props); + xr_delete(m_Items); +} + +void UIEditLightAnim::Draw() +{ + if (ImGui::BeginChild("Left", ImVec2(230, 0))) + { + + if (ImGui::Button("Save", ImVec2(0, ImGui::GetFrameHeight()))) + { + m_Modife = false; + LALib.Save(); + } + ImGui::SameLine(); + if (ImGui::Button("Reload", ImVec2(0, ImGui::GetFrameHeight()))) + { + m_Modife = false; + LALib.Reload(); + OnItemFocused(nullptr); + InitializeItems(); + } + ImGui::SameLine(); + ImGui::Checkbox("Render Alpha", &m_RenderAlpha); + if (ImGui::BeginChild("Left", ImVec2(0, 0), true)) + { + m_Items->Draw(); + } + ImGui::EndChild(); + } + ImGui::EndChild(); + ImGui::SameLine(); + if (ImGui::BeginChild("Midle", ImVec2(-230, 0))) + { + { + ImGui::SetNextItemWidth(-1); + float width = ImGui::CalcItemWidth(); + if (width >= 1) + { + + if (m_PointerWeight != floorf(width)) + { + m_PointerWeight = iFloor(width); + m_PointerResize = true; + } + if (m_CurrentItem) + { + ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); + ImVec2 canvas_size = ImGui::GetContentRegionAvail(); + if (canvas_size.x > static_cast(m_PointerWeight - 2)) + canvas_size.x = static_cast(m_PointerWeight) - 2; + if (canvas_size.y > POINTER_HEIGHT) + canvas_size.y = POINTER_HEIGHT; + if ((ImGui::GetIO().MousePos.x >= canvas_pos.x && ImGui::GetIO().MousePos.y >= canvas_pos.y) && + (ImGui::GetIO().MousePos.x <= (canvas_pos.x + canvas_size.x) && ImGui::GetIO().MousePos.y <= (canvas_pos.y + canvas_size.y))) + { + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + { + OnCreateKeyClick(); + } + if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + { + if (float(ImGui::GetIO().MousePos.x - canvas_pos.x) >= 1) + m_PointerValue = iFloor(float(m_CurrentItem->iFrameCount) * float(ImGui::GetIO().MousePos.x - canvas_pos.x) / float(m_PointerWeight - 2)); + UpdateProperties(); + } + } + } + RenderPointer(); + ImGui::Image(m_PointerTexture, ImVec2(static_cast(m_PointerWeight), POINTER_HEIGHT)); + } + m_Props->Draw(); + } + } + ImGui::EndChild(); + ImGui::SameLine(); + if (ImGui::BeginChild("Right", ImVec2(230, 0))) + { + ImGui::BeginGroup(); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 1)); + { + if (ImGui::Button("|<<", ImVec2(ImGui::GetFrameHeight() * 3, ImGui::GetFrameHeight()))) + { + m_PointerValue = 0; + } + ImGui::SameLine(); + ImGui::SetNextItemWidth(-ImGui::GetFrameHeight() * 3); + if (ImGui::InputInt("##value", &m_PointerValue, 1, 2)) + { + if (m_CurrentItem) + { + if (m_PointerValue > m_CurrentItem->iFrameCount - 1) + m_PointerValue = m_CurrentItem->iFrameCount - 1; + if (m_PointerValue < 0) + m_PointerValue = 0; + } + else + { + m_PointerValue = 0; + } + } + ImGui::SameLine(); + if (ImGui::Button(">>|", ImVec2(ImGui::GetFrameHeight() * 3, ImGui::GetFrameHeight())) && m_CurrentItem) + { + m_PointerValue = m_CurrentItem->iFrameCount - 1; + } + } + { + + float button_w = ImGui::GetWindowWidth() - (12 * ImGui::GetFrameHeight() + 6 * 2); + button_w = button_w / 2; + if (button_w < ImGui::GetFrameHeight()) + button_w = ImGui::GetFrameHeight(); + if (ImGui::Button("<-", ImVec2(ImGui::GetFrameHeight() * 2, ImGui::GetFrameHeight())) && m_CurrentItem) + { + if ((m_PointerValue != 0) && (m_CurrentItem->IsKey(m_PointerValue))) + { + int f0, f1; + f1 = f0 = m_PointerValue; + f1--; + while (f1 >= 0) + { + if (!(m_CurrentItem->IsKey(f1))) + { + m_CurrentItem->MoveKey(f0, f1); + m_PointerValue = f1; + OnModified(); + break; + } + f1--; + } + } + } + ImGui::SameLine(); + if (ImGui::Button("|<<", ImVec2(ImGui::GetFrameHeight() * 3, ImGui::GetFrameHeight())) && m_CurrentItem) + { + m_PointerValue = m_CurrentItem->FirstKeyFrame(); + } + ImGui::SameLine(); + if (ImGui::Button("<", ImVec2(ImGui::GetFrameHeight() * 1, ImGui::GetFrameHeight())) && m_CurrentItem) + { + m_PointerValue = m_CurrentItem->PrevKeyFrame(m_PointerValue); + } + ImGui::SameLine(); + if (ImGui::Button("+", ImVec2(button_w, ImGui::GetFrameHeight())) && m_CurrentItem) + { + OnCreateKeyClick(); + } + ImGui::SameLine(); + if (ImGui::Button("-", ImVec2(button_w, ImGui::GetFrameHeight())) && m_CurrentItem) + { + m_CurrentItem->DeleteKey(m_PointerValue); + if (m_PointerValue > m_CurrentItem->iFrameCount - 1) + m_PointerValue = m_CurrentItem->iFrameCount - 1; + if (m_PointerValue < 0) + m_PointerValue = 0; + UpdateProperties(); + OnModified(); + } + ImGui::SameLine(); + if (ImGui::Button(">", ImVec2(ImGui::GetFrameHeight() * 1, ImGui::GetFrameHeight())) && m_CurrentItem) + { + m_PointerValue = m_CurrentItem->NextKeyFrame(m_PointerValue); + } + ImGui::SameLine(); + if (ImGui::Button(">>|", ImVec2(ImGui::GetFrameHeight() * 3, ImGui::GetFrameHeight())) && m_CurrentItem) + { + m_PointerValue = m_CurrentItem->LastKeyFrame(); + } + ImGui::SameLine(); + if (ImGui::Button("->", ImVec2(ImGui::GetFrameHeight() * 2, ImGui::GetFrameHeight())) && m_CurrentItem) + { + if ((m_PointerValue != m_CurrentItem->iFrameCount - 1) && (m_CurrentItem->IsKey(m_PointerValue))) + { + int f0, f1; + f1 = f0 = m_PointerValue; + f1++; + while (f1 <= m_CurrentItem->iFrameCount - 1) + { + if (!(m_CurrentItem->IsKey(f1))) + { + m_CurrentItem->MoveKey(f0, f1); + m_PointerValue = f1; + OnModified(); + break; + } + f1++; + } + } + } + } + ImGui::PopStyleVar(2); + ImGui::EndGroup(); + if (m_CurrentItem) + { + + RenderItem(); + } + ImGui::Image(m_CurrentItem ? m_ItemTexture : m_TextureNull->surface_get(), ImGui::CalcItemSize(ImVec2(-1, -1), 32, 32)); + } + ImGui::EndChild(); +} + +void UIEditLightAnim::Update() +{ + if (Form) + { + if (!Form->IsClosed()) + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(800, 400)); + if (ImGui::BeginPopupModal("LightAnim Editor", &Form->bOpen, 0, true)) + { + ImGui::PopStyleVar(1); + Form->Draw(); + ImGui::EndPopup(); + } + else + { + ImGui::PopStyleVar(1); + } + } + else + { + xr_delete(Form); + } + } +} + +void UIEditLightAnim::Show() +{ + if (Form == nullptr) + Form = xr_new(); +} + +void UIEditLightAnim::UpdateProperties() +{ + PropItemVec items; + if (m_CurrentItem) + { + // PHelper().CreateName(items, "Name", &m_CurrentItem->cName, m_CurrentOwner); + PHelper().CreateFloat(items, "FPS", &m_CurrentItem->fFPS, 0.1f, 1000, 1.f, 1); + S32Value *V; + V = PHelper().CreateS32(items, "Frame Count", &m_CurrentItem->iFrameCount, 1, 100000, 1); + V->OnAfterEditEvent.bind(this, &UIEditLightAnim::OnFrameCountAfterEdit); + + u32 frame = m_PointerValue; + PHelper().CreateCaption(items, "Current\\Frame", shared_str().printf("%d", frame)); + u32 *val = m_CurrentItem->GetKey(m_PointerValue); + if (val) + { + PHelper().CreateColor(items, "Current\\Color", val); + PHelper().CreateU8(items, "Current\\Alpha", ((u8 *)val) + 3, 0x00, 0xFF); + } + } + m_Props->AssignItems(items); +} + +void UIEditLightAnim::InitializeItems() +{ + ListItemsVec items; + for (LAItemIt it = LALib.Items.begin(); it != LALib.Items.end(); it++) + LHelper().CreateItem(items, (*it)->cName.c_str(), 0, 0, 0); + m_Items->AssignItems(items); +} + +void UIEditLightAnim::RenderItem() +{ + u32 Color; + { + int frame; + Color = m_CurrentItem->CalculateBGR(EDevice.fTimeGlobal, frame); + if (!m_RenderAlpha) + Color = subst_alpha(Color, 0xFF); + } + { + D3DLOCKED_RECT rect; + R_CHK(m_ItemTexture->LockRect(0, &rect, 0, 0)); + u32 *dest = nullptr; + + for (u32 y = 0; y < 32; y++) + { + dest = reinterpret_cast(reinterpret_cast(rect.pBits) + (rect.Pitch * y)); + for (u32 i = 0; i < 32; i++) + { + dest[i] = Color; + } + } + R_CHK(m_ItemTexture->UnlockRect(0)); + } +} + +void UIEditLightAnim::OnCreateKeyClick() +{ + if (!(m_CurrentItem->IsKey(m_PointerValue))) + { + u32 color = m_CurrentItem->InterpolateRGB(m_PointerValue); + + m_CurrentItem->InsertKey(m_PointerValue, color); + UpdateProperties(); + OnModified(); + } +} + +void UIEditLightAnim::OnModified() +{ + m_Modife = true; +} + +void UIEditLightAnim::OnItemFocused(ListItem *item) +{ + m_CurrentItem = nullptr; + if (item) + { + m_CurrentItem = LALib.FindItem(item->Key()); + UpdateProperties(); + } + else + { + m_Props->ClearProperties(); + } +} + +bool UIEditLightAnim::OnFrameCountAfterEdit(PropValue *v, s32 &val) +{ + if (val != m_CurrentItem->iFrameCount) + OnModified(); + m_CurrentItem->Resize(val); + if (m_PointerValue > m_CurrentItem->iFrameCount - 1) + m_PointerValue = m_CurrentItem->iFrameCount - 1; + if (m_PointerValue < 0) + m_PointerValue = 0; + return true; +} + +void UIEditLightAnim::OnCloneItem(LPCSTR parent_path, LPCSTR new_full_name) +{ + LALib.AppendItem(new_full_name, LALib.FindItem(parent_path)); + ; + InitializeItems(); + m_Items->SelectItem(new_full_name); + OnModified(); +} + +void UIEditLightAnim::OnCreateItem(LPCSTR path) +{ + LALib.AppendItem(path, 0); + ; + InitializeItems(); + m_Items->SelectItem(path); + OnModified(); +} + +void UIEditLightAnim::OnRemoveItem(LPCSTR name, EItemType type) +{ + bool res = false; + if (m_CurrentItem->cName == name) + { + OnItemFocused(nullptr); + } + LALib.RemoveObject(name, type, res); + + OnModified(); +} + +void UIEditLightAnim::OnRenameItem(LPCSTR old_full_name, LPCSTR new_full_name, EItemType type) +{ + bool res = false; + LALib.RenameObject(old_full_name, new_full_name, type); + + OnModified(); +} + +void UIEditLightAnim::RenderPointer() +{ + if (m_PointerResize) + { + if (m_PointerTexture) + { + m_PointerTexture->Release(); + xr_delete(m_PointerRawImage); + } + R_CHK(HW.pDevice->CreateTexture(m_PointerWeight, POINTER_HEIGHT, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_PointerTexture, 0)); + m_PointerRawImage = xr_alloc(POINTER_HEIGHT * m_PointerWeight); + } + for (int x = 0; x < m_PointerWeight; x++) + { + for (int y = 0; y < POINTER_HEIGHT; y++) + { + { + m_PointerRawImage[y * int(m_PointerWeight) + x] = 0xFF000000; + } + } + } + if (m_CurrentItem) + { + float segment = float(m_PointerWeight - 2) / (float(m_CurrentItem->iFrameCount)); + int half_segment = iFloor(segment / 2); + + { + CLAItem::KeyMap &Keys = m_CurrentItem->Keys; + int last = m_CurrentItem->iFrameCount; + Keys[last] = Keys.rbegin()->second; + auto prev_key = Keys.begin(); + auto it = prev_key; + it++; + float x_prev = (float(prev_key->first) / float(m_CurrentItem->iFrameCount)) * (m_PointerWeight - 2); + ImVec4 cb; + cb.y = 1; + cb.w = floorf((POINTER_HEIGHT - 2) - (POINTER_HEIGHT - 2) * 0.3f); + for (; it != Keys.end(); it++) + { + float x = (it->first / float(m_CurrentItem->iFrameCount)) * (m_PointerWeight - 2); + float g_cnt = static_cast(it->first - prev_key->first); + for (int k = 0; k < g_cnt; k++) + { + cb.x = floorf(x_prev + k * segment + 1); + cb.z = floorf(x_prev + k * segment + segment + 1); + if (!m_RenderAlpha) + FillRectPointer(cb, subst_alpha(m_CurrentItem->InterpolateBGR(prev_key->first + k), 0xFF), true); + else + FillRectPointer(cb, m_CurrentItem->InterpolateBGR(prev_key->first + k), true); + } + prev_key = it; + x_prev = x; + } + Keys.erase(Keys.find(last)); + } + { + // draw keys + u32 Color = 0xFFBFFFFF; + ImVec4 cb; + cb.y = floorf((POINTER_HEIGHT - 2) - (POINTER_HEIGHT - 2) * 0.1f) + 1; + cb.w = floorf(POINTER_HEIGHT - 2); + for (auto it = m_CurrentItem->Keys.begin(); it != m_CurrentItem->Keys.end(); it++) + { + int t = iFloor((it->first / float(m_CurrentItem->iFrameCount)) * (m_PointerWeight)); + cb.x = static_cast(t - 1 + half_segment); + cb.z = static_cast(t + 2 + half_segment); + FillRectPointer(cb, Color); + } + } + // draw pointer + { + u32 Color = 0xFF00FF00; + int t = iFloor((float(m_PointerValue) / float(m_CurrentItem->iFrameCount)) * (m_PointerWeight)) + half_segment; + ImVec4 rp; + rp.x = static_cast(t); + rp.w = static_cast(1 + (POINTER_HEIGHT - 2)); + rp.z = static_cast(t + 1); + rp.y = static_cast(1 + (POINTER_HEIGHT - 2) * 0.75f); + FillRectPointer(rp, 0xFF00FF00); + /* if ((iMoveKey >= 0) && (iTgtMoveKey != iMoveKey)) + t = iFloor((iTgtMoveKey / float(m_CurrentItem->iFrameCount)) * R.Width()) + half_segment;*/ + + rp.x = static_cast(t - 2); + rp.y = static_cast(1 + 1); + rp.z = static_cast(t + 3); + rp.w = static_cast((POINTER_HEIGHT - 2) - (POINTER_HEIGHT - 2) * 0.3f - 1); + FrameRectPointer(rp, 0xFFAAAAAA); + rp.x -= 1; + rp.z += 1; + rp.y -= 1; + rp.w += 1; + FrameRectPointer(rp, 0xFF000000); + } + } + for (int x = 0; x < m_PointerWeight; x++) + { + for (int y = 0; y < POINTER_HEIGHT; y++) + { + if (x == 0 || x == m_PointerWeight - 1) + { + m_PointerRawImage[y * int(m_PointerWeight) + x] = 0xFF707070; + } + else if (y == 0 || y == POINTER_HEIGHT - 1) + { + m_PointerRawImage[y * int(m_PointerWeight) + x] = 0xFF707070; + } + } + } + { + D3DLOCKED_RECT rect; + R_CHK(m_PointerTexture->LockRect(0, &rect, 0, 0)); + u32 *dest = nullptr; + + for (u32 y = 0; y < POINTER_HEIGHT; y++) + { + dest = reinterpret_cast(reinterpret_cast(rect.pBits) + (rect.Pitch * y)); + for (u32 i = 0; i < m_PointerWeight; i++) + { + dest[i] = m_PointerRawImage[y * int(m_PointerWeight) + i]; + } + } + R_CHK(m_PointerTexture->UnlockRect(0)); + } +} + +void UIEditLightAnim::FillRectPointer(const ImVec4 &rect, u32 color, bool plus_one) +{ + int r_x = iFloor(rect.x); + int r_y = iFloor(rect.y); + int r_z = iFloor(rect.z); + int r_w = iFloor(rect.w); + for (int x = 0; x < m_PointerWeight; x++) + { + for (int y = 0; y < POINTER_HEIGHT; y++) + { + if (plus_one) + { + if (x >= r_x && x <= r_z) + if (y >= r_y && y <= r_w) + { + m_PointerRawImage[y * int(m_PointerWeight) + x] = color; + } + } + else + { + if (x >= r_x && x < r_z) + if (y >= r_y && y < r_w) + { + m_PointerRawImage[y * int(m_PointerWeight) + x] = color; + } + } + } + } +} + +void UIEditLightAnim::FrameRectPointer(const ImVec4 &rect, u32 color) +{ + int r_x = iFloor(rect.x); + int r_y = iFloor(rect.y); + int r_z = iFloor(rect.z); + int r_w = iFloor(rect.w); + for (int x = 0; x < m_PointerWeight; x++) + { + for (int y = 0; y < POINTER_HEIGHT; y++) + { + if (x >= r_x && x < r_z) + if (y >= r_y && y < r_w) + { + if ((x == r_x || x == r_z - 1) || (y == r_y || y == r_w - 1)) + { + m_PointerRawImage[y * int(m_PointerWeight) + x] = color; + } + } + } + } +} diff --git a/src/editors/xrECore/Editor/UIEditLightAnim.h b/src/editors/xrECore/Editor/UIEditLightAnim.h new file mode 100644 index 00000000000..bf10d1396ac --- /dev/null +++ b/src/editors/xrECore/Editor/UIEditLightAnim.h @@ -0,0 +1,51 @@ +#pragma once +class CLAItem; +class UIEditLightAnim : public xrUI +{ +public: + UIEditLightAnim(); + virtual ~UIEditLightAnim(); + virtual void Draw(); + +public: + static void Update(); + static void Show(); + +private: + static UIEditLightAnim *Form; + +private: + void UpdateProperties(); + UIItemListForm *m_Items; + UIPropertiesForm *m_Props; + ref_texture m_TextureNull; + ImTextureID m_Texture; + void InitializeItems(); + +private: + void RenderItem(); + ID3DTexture2D *m_ItemTexture; + CLAItem *m_CurrentItem; + bool m_Modife; + +private: + void OnCreateKeyClick(); + void OnModified(); + void OnItemFocused(ListItem *); + bool OnFrameCountAfterEdit(PropValue *v, s32 &val); + void OnCloneItem(LPCSTR parent_path, LPCSTR new_full_name); + void OnCreateItem(LPCSTR path); + void OnRemoveItem(LPCSTR name, EItemType type); + void OnRenameItem(LPCSTR old_full_name, LPCSTR new_full_name, EItemType type); + +private: + void RenderPointer(); + void FillRectPointer(const ImVec4 &rect, u32 color, bool plus_one = false); + void FrameRectPointer(const ImVec4 &rect, u32 color); + u32 m_PointerWeight; + bool m_PointerResize; + ID3DTexture2D *m_PointerTexture; + u32 *m_PointerRawImage; + int m_PointerValue; + bool m_RenderAlpha; +}; diff --git a/src/editors/xrECore/Editor/UIImageEditorForm.cpp b/src/editors/xrECore/Editor/UIImageEditorForm.cpp new file mode 100644 index 00000000000..60f7fa09f2b --- /dev/null +++ b/src/editors/xrECore/Editor/UIImageEditorForm.cpp @@ -0,0 +1,365 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#include "UIImageEditorForm.h" +#include "EThumbnail.h" +UIImageEditorForm *UIImageEditorForm::Form = nullptr; +UIImageEditorForm::UIImageEditorForm() +{ + m_ItemProps = xr_new(); + m_ItemList = xr_new(); + m_ItemList->SetOnItemFocusedEvent(TOnILItemFocused(this, &UIImageEditorForm::OnItemsFocused)); + m_ItemList->SetOnItemRemoveEvent(TOnItemRemove(&ImageLib, &CImageManager::RemoveTexture)); + m_Texture = nullptr; + m_bFilterImage = true; + m_bFilterCube = true; + m_bFilterBump = true; + m_bFilterNormal = true; + m_bFilterTerrain = true; + m_bUpdateProperties = false; + m_TextureRemove = nullptr; +} + +UIImageEditorForm::~UIImageEditorForm() +{ + if (m_Texture) + m_Texture->Release(); + xr_delete(m_ItemList); + xr_delete(m_ItemProps); +} + +void UIImageEditorForm::Draw() +{ + if (m_bUpdateProperties) + { + UpdateProperties(); + m_bUpdateProperties = false; + } + + if (m_TextureRemove) + { + m_TextureRemove->Release(); + m_TextureRemove = nullptr; + } + ImGui::BeginChild("Left", ImVec2(200, 400), true); + { + m_ItemList->Draw(); + } + ImGui::EndChild(); + ImGui::SameLine(); + ImGui::BeginChild("Right", ImVec2(300, 400)); + { + if (m_Texture == nullptr) + { + u32 mem = 0; + m_Texture = RImplementation.texture_load("ed\\ed_nodata", mem); + } + ImGui::Image(m_Texture, ImVec2(128, 128)); + m_ItemProps->Draw(); + } + ImGui::EndChild(); + ImGui::Separator(); + if (!bImportMode) + { + if (ImGui::Checkbox("Image", &m_bFilterImage)) + FilterUpdate(); + ImGui::SameLine(); + if (ImGui::Checkbox("Cube", &m_bFilterCube)) + FilterUpdate(); + ImGui::SameLine(); + if (ImGui::Checkbox("Bump", &m_bFilterBump)) + FilterUpdate(); + ImGui::SameLine(); + if (ImGui::Checkbox("Normal", &m_bFilterNormal)) + FilterUpdate(); + ImGui::SameLine(); + if (ImGui::Checkbox("Terrain", &m_bFilterTerrain)) + FilterUpdate(); + ImGui::Separator(); + } + if (ImGui::Button("Close")) + { + HideLib(); + } + ImGui::SameLine(); + if (ImGui::Button("Ok")) + { + UpdateLib(); + HideLib(); + } + if (!bImportMode) + { + ImGui::SameLine(); + if (ImGui::Button("Remove Texture")) + { + m_ItemList->RemoveSelectItem(); + } + } +} + +void UIImageEditorForm::Update() +{ + if (Form) + { + if (!Form->IsClosed()) + { + if (ImGui::BeginPopupModal("ImageEditor", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize, true)) + { + Form->Draw(); + ImGui::EndPopup(); + } + } + else + { + xr_delete(Form); + } + } +} + +void UIImageEditorForm::Show(bool bImport) +{ + if (Form == nullptr) + Form = xr_new(); + Form->bImportMode = bImport; + //. form->ebRebuildAssociation->Enabled = !bImport; + Form->bReadonlyMode = !FS.can_write_to_alias(_textures_); + if (Form->bReadonlyMode) + { + Log("#!You don't have permisions to modify textures."); + Form->m_ItemProps->SetReadOnly(TRUE); + } + Form->modif_map.clear(); + Form->InitItemList(); +} + +void UIImageEditorForm::ImportTextures() +{ + VERIFY(!Form); + FS_FileSet TextureMap; + int new_cnt = ImageLib.GetLocalNewTextures(TextureMap); + if (new_cnt) + { + if (ELog.DlgMsg(mtInformation, "Found %d new texture(s)", new_cnt)) + { + Form = xr_new(); + Form->texture_map.swap(TextureMap); + Show(true); + } + } + else + { + ELog.DlgMsg(mtInformation, "Can't find new textures."); + } +} + +ETextureThumbnail *UIImageEditorForm::FindUsedTHM(const shared_str &name) +{ + THMMapIt it = m_THM_Used.find(name); + if (it != m_THM_Used.end()) + return it->second; + + ETextureThumbnail *thm = xr_new(name.c_str(), false); + m_THM_Used[name] = thm; + + if (bImportMode) + { + xr_string fn = name.c_str(); + ImageLib.UpdateFileName(fn); + + if (!thm->Load(name.c_str(), _import_)) + { + bool bLoad = thm->Load(fn.c_str(), _game_textures_); + ImageLib.CreateTextureThumbnail(thm, name.c_str(), _import_, !bLoad); + } + } + else + { + thm->Load(); + } + return thm; +} + +void UIImageEditorForm::RegisterModifiedTHM() +{ + if (m_ItemProps->IsModified() || bImportMode) + { + for (THMIt t_it = m_THM_Current.begin(); t_it != m_THM_Current.end(); ++t_it) + { + auto it = texture_map.find(FS_File((*t_it)->SrcName())); + R_ASSERT(it != texture_map.end()); + modif_map.insert(*it); + } + } +} + +void UIImageEditorForm::OnCubeMapBtnClick(ButtonValue *value, bool &bModif, bool &bSafe) +{ + ButtonValue *B = dynamic_cast(value); + R_ASSERT(B); + bModif = false; + switch (B->btn_num) + { + case 0: + { + RStringVec items; + if (0 != m_ItemList->GetSelected(items)) + { + for (RStringVecIt it = items.begin(); it != items.end(); it++) + { + xr_string new_name = xr_string(it->c_str()) + "#small"; + ImageLib.CreateSmallerCubeMap(it->c_str(), new_name.c_str()); + } + } + } + break; + } +} + +void UIImageEditorForm::OnTypeChange(PropValue *prop) +{ + m_bUpdateProperties = true; +} + +void UIImageEditorForm::InitItemList() +{ + R_ASSERT(m_THM_Used.empty()); + if (!bImportMode) + ImageLib.GetTexturesRaw(texture_map); + + ListItemsVec items; + // fill + auto it = texture_map.begin(); + auto _E = texture_map.end(); + for (; it != _E; it++) + { + ListItem *I = LHelper().CreateItem(items, it->name.c_str(), 0); + I->m_Object = (void *)(FindUsedTHM(it->name.c_str())); + R_ASSERT2(I->m_Object, it->name.c_str()); + } + m_ItemList->AssignItems(items); +} + +void UIImageEditorForm::HideLib() +{ + bOpen = false; + ImGui::CloseCurrentPopup(); +} + +void UIImageEditorForm::UpdateLib() +{ + VERIFY(!bReadonlyMode); + RegisterModifiedTHM(); + SaveUsedTHM(); + if (bImportMode && !texture_map.empty()) + { + AStringVec modif; + ImageLib.SafeCopyLocalToServer(texture_map); + // rename with folder + FS_FileSet files = texture_map; + texture_map.clear(); + xr_string fn; + auto it = files.begin(); + auto _E = files.end(); + + for (; it != _E; it++) + { + fn = EFS.ChangeFileExt(it->name.c_str(), ""); + ImageLib.UpdateFileName(fn); + FS_File F(*it); + F.name = fn; + texture_map.insert(F); + } + // sync + ImageLib.SynchronizeTextures(true, true, true, &texture_map, &modif); + ImageLib.RefreshTextures(&modif); + } + else + { + // save game textures + if (modif_map.size()) + { + AStringVec modif; + ImageLib.SynchronizeTextures(true, true, true, &modif_map, &modif); + ImageLib.RefreshTextures(&modif); + } + } +} + +void UIImageEditorForm::OnItemsFocused(ListItem* item) +{ + PropItemVec props; + + RegisterModifiedTHM(); + m_THM_Current.clear(); + m_TextureRemove = m_Texture; + m_Texture = nullptr; + + if (ListItem* prop = item) + { + ETextureThumbnail* thm = FindUsedTHM(prop->Key()); + m_THM_Current.push_back(thm); + m_ItemProps->ClearProperties(); + + // fill prop + thm->FillProp(props, PropValue::TOnChange(this, &UIImageEditorForm::OnTypeChange)); + + if (thm->_Format().type == STextureParams::ttCubeMap) + { + ButtonValue* B = PHelper().CreateButton(props, "CubeMap\\Edit", "Make Small", 0); + B->OnBtnClickEvent.bind(this, &UIImageEditorForm::OnCubeMapBtnClick); + } + + thm->Update(m_Texture); + } + + m_ItemProps->AssignItems(props); +} + +void UIImageEditorForm::UpdateProperties() +{ + ListItemsVec vec; + m_ItemList->GetSelected(nullptr, vec, false); + + if (vec.size() == 1) + { + m_ItemProps->ClearProperties(); + OnItemsFocused(vec[0]); + } +} + +void UIImageEditorForm::SaveUsedTHM() +{ + for (THMMapIt t_it = m_THM_Used.begin(); t_it != m_THM_Used.end(); ++t_it) + { + if (modif_map.find(FS_File(t_it->second->SrcName())) != modif_map.end()) + t_it->second->Save(); + } +} + +void UIImageEditorForm::FilterUpdate() +{ + const ListItemsVec &items = m_ItemList->GetItems(); + + u32 cnt = items.size(); + for (u32 k = 0; k < cnt; ++k) + { + ListItem *I = items[k]; + + ETextureThumbnail *thm = (ETextureThumbnail *)I->m_Object; + + BOOL bVis = FALSE; + int type = thm->_Format().type; + if (STextureParams::ttImage == type && m_bFilterImage) + bVis = TRUE; + else if (STextureParams::ttCubeMap == type && m_bFilterCube) + bVis = TRUE; + else if (STextureParams::ttBumpMap == type && m_bFilterBump) + bVis = TRUE; + else if (STextureParams::ttNormalMap == type && m_bFilterNormal) + bVis = TRUE; + else if (STextureParams::ttTerrain == type && m_bFilterTerrain) + bVis = TRUE; + + I->Visible(bVis); + } + m_ItemList->ClearSelected(); +} diff --git a/src/editors/xrECore/Editor/UIImageEditorForm.h b/src/editors/xrECore/Editor/UIImageEditorForm.h new file mode 100644 index 00000000000..7b7f7fe7e80 --- /dev/null +++ b/src/editors/xrECore/Editor/UIImageEditorForm.h @@ -0,0 +1,50 @@ +#pragma once + +class UIImageEditorForm : public xrUI +{ +public: + UIImageEditorForm(); + virtual ~UIImageEditorForm(); + virtual void Draw(); + +public: + static void Update(); + static void Show(bool bImport); + static void ImportTextures(); + +private: + DEFINE_VECTOR(ETextureThumbnail *, THMVec, THMIt); + DEFINE_MAP(shared_str, ETextureThumbnail *, THMMap, THMMapIt); + THMMap m_THM_Used; + THMVec m_THM_Current; + UIItemListForm *m_ItemList; + UIPropertiesForm *m_ItemProps; + FS_FileSet texture_map; + FS_FileSet modif_map; + bool bImportMode; + bool bReadonlyMode; + static UIImageEditorForm *Form; + ImTextureID m_Texture; + ImTextureID m_TextureRemove; + +private: + ETextureThumbnail *FindUsedTHM(const shared_str &name); + void RegisterModifiedTHM(); + void OnCubeMapBtnClick(ButtonValue *value, bool &bModif, bool &bSafe); + void OnTypeChange(PropValue *prop); + void InitItemList(); + void HideLib(); + void UpdateLib(); + void OnItemsFocused(ListItem *item); + void SaveUsedTHM(); + void UpdateProperties(); + +private: + bool m_bFilterImage; + bool m_bFilterTerrain; + bool m_bFilterBump; + bool m_bFilterNormal; + bool m_bFilterCube; + bool m_bUpdateProperties; + void FilterUpdate(); +}; diff --git a/src/editors/xrECore/Editor/UILogForm.cpp b/src/editors/xrECore/Editor/UILogForm.cpp new file mode 100644 index 00000000000..519c65e940e --- /dev/null +++ b/src/editors/xrECore/Editor/UILogForm.cpp @@ -0,0 +1,144 @@ +#include "stdafx.h" +#include "ELog.h" +#include "UILogForm.h" +#include "xrCore/os_clipboard.h" + +#define MSG_ERROR 0x00C4C4FF +#define MSG_INFO 0x00E6FFE7 +#define MSG_CONF 0x00FFE6E7 +#define MSG_DEF 0x00E8E8E8 + +bool UILogForm::bAutoScroll = true; +bool UILogForm::bOnlyError = false; +xr_vector *UILogForm::List = nullptr; + +extern bool bAllowLogCommands; + +void UILogForm::AddMessage(TMsgDlgType mt, const xr_string &msg) +{ + xr_string M; + for (int i = 0; i < msg.size(); i++) + { + if (msg[i] == '\r') + continue; + if (msg[i] == '\n') + M += " "; + else + M += msg[i]; + } + switch (mt) + { + case mtError: + M.insert(0, "###"); + break; + case mtConfirmation: + M.insert(0, "##@"); + break; + } + GetList()->push_back(M); +} + +void UILogForm::AddDlgMessage(TMsgDlgType mt, const xr_string &msg) +{ + GetList()->push_back(msg); +} + +void UILogForm::Show() +{ + bAllowLogCommands = true; +} + +void UILogForm::Hide() +{ + bAllowLogCommands = false; +} + +void UILogForm::Update() +{ + if (bAllowLogCommands) + { + bool NeedCopy = false; + if (!ImGui::Begin("Log", &bAllowLogCommands)) + { + ImGui::End(); + return; + } + if (ImGui::Button("Clear")) + { + GetList()->clear(); + } + ImGui::SameLine(); + if (ImGui::Button("Flush")) + { + FlushLog(); + } + ImGui::SameLine(); + if (ImGui::Button("Copy")) + { + NeedCopy = true; + } + ImGui::SameLine(); + ImGui::Checkbox("Auto Scroll", &bAutoScroll); + ImGui::SameLine(); + ImGui::Checkbox("Only Error", &bOnlyError); + + ImGui::Spacing(); + if (ImGui::BeginChild("Log", ImVec2(0, 0), true)) + { + xr_string CopyLog; + for (int i = 0; i < GetList()->size(); i++) + { + if (bOnlyError) + { + const char *Str = GetList()->at(i).c_str(); + if (strncmp(Str, "###", 3) == 0) + { + Str += 3; + ImGui::Text(Str); + if (NeedCopy) + CopyLog.append(Str).append("\r\n"); + } + } + else + { + ImVec4 Color = {1, 1, 1, 1}; + const char *Str = GetList()->at(i).c_str(); + if (strncmp(Str, "###", 3) == 0) + { + Color = {1, 0, 0, 1}; + Str += 3; + } + else if (strncmp(Str, "##@", 3) == 0) + { + Color = {1, 1, 0, 1}; + Str += 3; + } + + ImGui::TextColored(Color, Str); + if (NeedCopy) + CopyLog.append(Str).append("\r\n"); + } + } + if (NeedCopy) + { + os_clipboard::copy_to_clipboard(CopyLog.c_str()); + } + if (bAutoScroll) + ImGui::SetScrollHereY(); + } + ImGui::EndChild(); + ImGui::End(); + } +} + +void UILogForm::Destroy() +{ + xr_delete(List); +} + +xr_vector *UILogForm::GetList() +{ + if (!List) + List = xr_new>(); + return List; +} diff --git a/src/editors/xrECore/Editor/UILogForm.h b/src/editors/xrECore/Editor/UILogForm.h new file mode 100644 index 00000000000..98948f96c52 --- /dev/null +++ b/src/editors/xrECore/Editor/UILogForm.h @@ -0,0 +1,25 @@ +//--------------------------------------------------------------------------- +#ifndef LogFormH +#define LogFormH +//--------------------------------------------------------------------------- + +class UILogForm +{ +public: + static void AddMessage(TMsgDlgType mt, const xr_string &msg); + static void AddMessage(const xr_string &msg) { AddMessage(mtCustom, msg); } + static void AddDlgMessage(TMsgDlgType mt, const xr_string &msg); + static void AddDlgMessage(const xr_string &msg) { AddDlgMessage(mtCustom, msg); } + static void Show(); + static void Hide(); + static void Update(); + static void Destroy(); + +private: + static xr_vector *List; + static xr_vector *GetList(); + static bool bAutoScroll; + static bool bOnlyError; +}; +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/xrECore/Editor/UIMinimapEditorForm.cpp b/src/editors/xrECore/Editor/UIMinimapEditorForm.cpp new file mode 100644 index 00000000000..3e63da0948e --- /dev/null +++ b/src/editors/xrECore/Editor/UIMinimapEditorForm.cpp @@ -0,0 +1,122 @@ +#include "stdafx.h" +#include "xrCore/_fbox2.h" +#include "UIMinimapEditorForm.h" + +UIMinimapEditorForm *UIMinimapEditorForm::Form = nullptr; + +UIMinimapEditorForm::UIMinimapEditorForm() +{ + m_TextureRemove = nullptr; + m_Texture = nullptr; +} + +UIMinimapEditorForm::~UIMinimapEditorForm() +{ + if (m_Texture) + m_Texture->Release(); +} + +void UIMinimapEditorForm::Draw() +{ + if (m_TextureRemove) + { + m_TextureRemove->Release(); + m_TextureRemove = nullptr; + } + + if (!m_Texture) + { + u32 mem = 0; + m_Texture = RImplementation.texture_load("ed\\ed_nodata", mem); + } + + ImGui::Image(m_Texture, ImVec2(330, 530)); + + if (ImGui::Button("Load")) + LoadClick(); +} + +void UIMinimapEditorForm::Update() +{ + if (Form) + { + if (!Form->IsClosed()) + { + if (ImGui::BeginPopupModal("MinimapEditor", &Form->bOpen, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize, true)) + { + Form->Draw(); + ImGui::EndPopup(); + } + else + { + Form->bOpen = false; + ImGui::CloseCurrentPopup(); + } + } + else + { + xr_delete(Form); + } + } +} + +void UIMinimapEditorForm::Show() +{ + VERIFY(!Form); + Form = xr_new(); + Form->bOpen = true; +} + +extern bool Stbi_Load(LPCSTR full_name, U32Vec &data, u32 &w, u32 &h, u32 &a); + +void UIMinimapEditorForm::LoadClick() +{ + xr_string fn; + m_ImageData.clear(); + + if (EFS.GetOpenName(EDevice.m_hWnd, "$app_root$", fn, false, NULL, 0)) + { + if (Stbi_Load(fn.c_str(), m_ImageData, m_ImageW, m_ImageH, m_ImageA)) + { + m_TextureRemove = m_Texture; + ID3DTexture2D *pTexture = nullptr; + { + R_CHK(HW.pDevice->CreateTexture(m_ImageW, m_ImageH, 1, 0, D3DFMT_X8R8G8B8, D3DPOOL_MANAGED, &pTexture, 0)); + m_Texture = pTexture; + + { + D3DLOCKED_RECT rect; + R_CHK(pTexture->LockRect(0, &rect, 0, D3DLOCK_DISCARD)); + for (int i = 0; i < m_ImageH; i++) + { + + unsigned char *dest = static_cast(rect.pBits) + (rect.Pitch * i); + memcpy(dest, m_ImageData.data() + (m_ImageW * i), sizeof(unsigned char) * m_ImageW * 4); + } + R_CHK(pTexture->UnlockRect(0)); + } + } + /*LPCSTR _mark = "_["; + if (fn.find(_mark) != fn.npos) + { + LPCSTR _str = fn.c_str() + fn.find(_mark); + int cnt = sscanf(_str, "_[%f, %f]-[%f, %f]", &map_bb.min.x, &map_bb.min.y, &map_bb.max.x, &map_bb.max.y); + // "ss_andy_05-08-07_15-24-11_#ai_test_[-150.000, -100.000]-[52.927, 50.000].tga" + if (cnt != 4) { + map_bb.min.x = 0.0f; + map_bb.min.y = 0.0f; + map_bb.max.x = 100.0f; + map_bb.max.y = 100.0f; + map_bb_loaded = map_bb; + + ApplyPoints(true); + return; + } + map_bb_loaded = map_bb; + + ApplyPoints(true); + imgPanelResize(NULL); + }*/ + } + } +} diff --git a/src/editors/xrECore/Editor/UIMinimapEditorForm.h b/src/editors/xrECore/Editor/UIMinimapEditorForm.h new file mode 100644 index 00000000000..4705e05187a --- /dev/null +++ b/src/editors/xrECore/Editor/UIMinimapEditorForm.h @@ -0,0 +1,26 @@ + +class UIMinimapEditorForm : public xrUI +{ +public: + UIMinimapEditorForm(); + virtual ~UIMinimapEditorForm(); + virtual void Draw(); + + static void Update(); + static void Show(); + +private: + static UIMinimapEditorForm* Form; + + ImTextureID m_Texture; + ImTextureID m_TextureRemove; + + void LoadClick(); + U32Vec m_ImageData; + u32 m_ImageW; + u32 m_ImageH; + u32 m_ImageA; + Fbox2 map_bb; + Fbox2 map_bb_loaded; + Ivector2 image_draw_size; +}; diff --git a/src/editors/xrECore/Editor/UIRenderForm.cpp b/src/editors/xrECore/Editor/UIRenderForm.cpp new file mode 100644 index 00000000000..446deb44dd2 --- /dev/null +++ b/src/editors/xrECore/Editor/UIRenderForm.cpp @@ -0,0 +1,121 @@ +#include "stdafx.h" +#include "UIRenderForm.h" +#include "ui_main.h" +UIRenderForm::UIRenderForm() +{ + m_mouse_down = false; + m_mouse_move = false; + m_shiftstate_down = false; +} + +UIRenderForm::~UIRenderForm() +{ +} + +void UIRenderForm::Draw() +{ + + ImGui::Begin("Render"); + if (UI && UI->RT->pSurface) + { + int ShiftState = ssNone; + + if (ImGui::GetIO().KeyShift) + ShiftState |= ssShift; + if (ImGui::GetIO().KeyCtrl) + ShiftState |= ssCtrl; + if (ImGui::GetIO().KeyAlt) + ShiftState |= ssAlt; + + if (ImGui::IsMouseDown(ImGuiMouseButton_Left)) + ShiftState |= ssLeft; + if (ImGui::IsMouseDown(ImGuiMouseButton_Right)) + ShiftState |= ssRight; + // VERIFY(!(ShiftState & ssLeft && ShiftState & ssRight)); + ImDrawList *draw_list = ImGui::GetWindowDrawList(); + ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); + ImVec2 canvas_size = ImGui::GetContentRegionAvail(); + ImVec2 mouse_pos = ImGui::GetIO().MousePos; + bool cursor_in_zone = true; + if (mouse_pos.x < canvas_pos.x) + { + cursor_in_zone = false; + mouse_pos.x = canvas_pos.x; + } + if (mouse_pos.y < canvas_pos.y) + { + cursor_in_zone = false; + mouse_pos.y = canvas_pos.y; + } + + if (mouse_pos.x > canvas_pos.x + canvas_size.x) + { + cursor_in_zone = false; + mouse_pos.x = canvas_pos.x + canvas_size.x; + } + if (mouse_pos.y > canvas_pos.y + canvas_size.y) + { + cursor_in_zone = false; + mouse_pos.y = canvas_pos.y + canvas_size.y; + } + + bool curent_shiftstate_down = m_shiftstate_down; + if (ImGui::IsWindowFocused()) + { + + if ((ImGui::IsMouseDown(ImGuiMouseButton_Left) || ImGui::IsMouseDown(ImGuiMouseButton_Right)) && !m_mouse_down && cursor_in_zone) + { + UI->MousePress(TShiftState(ShiftState), static_cast(mouse_pos.x - canvas_pos.x), static_cast(mouse_pos.y - canvas_pos.y)); + m_mouse_down = true; + } + + else if ((ImGui::IsMouseReleased(ImGuiMouseButton_Left) || ImGui::IsMouseReleased(ImGuiMouseButton_Right)) && m_mouse_down) + { + if (!ImGui::IsMouseDown(ImGuiMouseButton_Left) && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) + { + UI->MouseRelease(TShiftState(ShiftState), static_cast(mouse_pos.x - canvas_pos.x), static_cast(mouse_pos.y - canvas_pos.y)); + m_mouse_down = false; + m_mouse_move = false; + m_shiftstate_down = false; + } + } + else if (m_mouse_down) + { + UI->MouseMove(TShiftState(ShiftState), static_cast(mouse_pos.x - canvas_pos.x), + static_cast(mouse_pos.y - canvas_pos.y)); + m_mouse_move = true; + m_shiftstate_down = m_shiftstate_down || (ShiftState & (ssShift | ssCtrl | ssAlt)); + } + } + else if (m_mouse_down) + { + if (!ImGui::IsMouseDown(ImGuiMouseButton_Left) && !ImGui::IsMouseDown(ImGuiMouseButton_Right)) + { + UI->MouseRelease(TShiftState(ShiftState), static_cast(mouse_pos.x - canvas_pos.x), static_cast(mouse_pos.y - canvas_pos.y)); + m_mouse_down = false; + m_mouse_move = false; + m_shiftstate_down = false; + } + } + m_mouse_position.set(mouse_pos.x - canvas_pos.x, mouse_pos.y - canvas_pos.y); + + if (canvas_size.x < 32.0f) + canvas_size.x = 32.0f; + if (canvas_size.y < 32.0f) + canvas_size.y = 32.0f; + UI->RTSize.set(canvas_size.x, canvas_size.y); + + ImGui::InvisibleButton("canvas", canvas_size); + if (!m_OnContextMenu.empty() && !curent_shiftstate_down) + { + if (ImGui::BeginPopupContextItem("Menu")) + { + m_OnContextMenu(); + ImGui::EndPopup(); + } + } + + draw_list->AddImage(UI->RT->pSurface, canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y)); + } + ImGui::End(); +} diff --git a/src/editors/xrECore/Editor/UIRenderForm.h b/src/editors/xrECore/Editor/UIRenderForm.h new file mode 100644 index 00000000000..e803c9ed313 --- /dev/null +++ b/src/editors/xrECore/Editor/UIRenderForm.h @@ -0,0 +1,19 @@ +#pragma once +typedef fastdelegate::FastDelegate0<> TOnRenderContextMenu; +class ECORE_API UIRenderForm : public xrUI +{ +public: + UIRenderForm(); + virtual ~UIRenderForm(); + virtual void Draw(); + IC Ivector2 GetMousePos() const { return m_mouse_position; } + IC void SetContextMenuEvent(TOnRenderContextMenu e) { m_OnContextMenu = e; } + +private: + Ivector2 m_mouse_position; + ref_texture m_rt; + TOnRenderContextMenu m_OnContextMenu; + bool m_mouse_down; + bool m_mouse_move; + bool m_shiftstate_down; +}; \ No newline at end of file diff --git a/src/editors/xrECore/Editor/UISoundEditorForm.cpp b/src/editors/xrECore/Editor/UISoundEditorForm.cpp new file mode 100644 index 00000000000..a64eb8567a1 --- /dev/null +++ b/src/editors/xrECore/Editor/UISoundEditorForm.cpp @@ -0,0 +1,338 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#include "UISoundEditorForm.h" +#include "SoundManager.h" +#include "../../../xrSound/stdafx.h" +#include "../../../xrSound/soundrender_source.h" +UISoundEditorForm *UISoundEditorForm::Form = nullptr; + +UISoundEditorForm::UISoundEditorForm() +{ + m_ItemProps = xr_new(); + m_ItemList = xr_new(); + m_ItemList->SetOnItemFocusedEvent(TOnILItemFocused(this, &UISoundEditorForm::OnItemsFocused)); + modif_map.clear(); + m_Flags.zero(); + InitItemList(); + if (!FS.can_write_to_alias(_sounds_)) + { + Log("#!You don't have permisions to modify sounds."); + m_ItemProps->SetReadOnly(TRUE); + m_Flags.set(flReadOnly, TRUE); + bAutoPlay = TRUE; + } +} + +UISoundEditorForm::~UISoundEditorForm() +{ + xr_delete(m_ItemProps); + xr_delete(m_ItemList); +} + +void UISoundEditorForm::Draw() +{ + ImGui::BeginChild("Left", ImVec2(200, 400), true); + m_ItemList->Draw(); + ImGui::EndChild(); + ImGui::SameLine(); + ImGui::BeginChild("Right", ImVec2(300, 400)); + m_ItemProps->Draw(); + ImGui::EndChild(); + ImGui::Separator(); + if (ImGui::Button("Close")) + { + bOpen = false; + ImGui::CloseCurrentPopup(); + HideLib(); + } + ImGui::SameLine(); + if (ImGui::Button("Ok")) + { + m_Snd.destroy(); + UpdateLib(); + HideLib(); + } +} + +void UISoundEditorForm::Update() +{ + if (Form) + { + if (!Form->IsClosed()) + { + if (ImGui::BeginPopupModal("SoundEditor", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize, true)) + { + Form->Draw(); + ImGui::EndPopup(); + } + } + else + { + xr_delete(Form); + } + } +} + +void UISoundEditorForm::Show() +{ + VERIFY(!Form); + Form = xr_new(); +} + +void UISoundEditorForm::HideLib() +{ + m_Snd.destroy(); + bOpen = false; + ImGui::CloseCurrentPopup(); +} + +void UISoundEditorForm::RegisterModifiedTHM() +{ + if (m_ItemProps->IsModified()) + { + for (THMIt t_it = m_THM_Current.begin(); t_it != m_THM_Current.end(); t_it++) + { + //. (*t_it)->Save (0,0); + AppendModif((*t_it)->SrcName()); + } + } +} + +void UISoundEditorForm::OnModified() +{ +} + +void UISoundEditorForm::UpdateLib() +{ + RegisterModifiedTHM(); + SaveUsedTHM(); + // save game sounds + if (modif_map.size()) + { + AStringVec modif; + SndLib->SynchronizeSounds(true, true, true, &modif_map, 0); + // SndLib->ChangeFileAgeTo (&modif_map,time(NULL)); + SndLib->RefreshSounds(false); + modif_map.clear(); + } +} + +void UISoundEditorForm::AppendModif(LPCSTR nm) +{ + FS_File dest; + string_path fname; + FS.update_path(fname, _sounds_, EFS.ChangeFileExt(nm, ".wav").c_str()); + BOOL bFind = FS.file_find(fname, dest); + R_ASSERT(bFind); + modif_map.insert(dest); +} + +void UISoundEditorForm::OnControlClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + switch (V->btn_num) + { + case 0: + m_Snd.play(0, sm_2D); + break; + case 1: + m_Snd.stop(); + break; + case 2: + { + bAutoPlay = !bAutoPlay; + V->value[V->btn_num] = shared_str().printf("Auto (%s)", bAutoPlay ? "on" : "off"); + } + break; + } + bModif = false; +} + +void UISoundEditorForm::OnControl2Click(ButtonValue *V, bool &bModif, bool &bSafe) +{ + switch (V->btn_num) + { + case 0: + { + bAutoPlay = !bAutoPlay; + V->value[V->btn_num] = bAutoPlay ? "on" : "off"; + } + break; + } + bModif = false; +} + +void UISoundEditorForm::OnSyncCurrentClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + THMIt it = m_THM_Current.begin(); + THMIt it_e = m_THM_Current.end(); + + for (; it != it_e; ++it) + { + ESoundThumbnail *pTHM = *it; + + string_path src_name, game_name; + FS.update_path(src_name, _sounds_, pTHM->SrcName()); + strconcat(sizeof(src_name), src_name, src_name, ".wav"); + + FS.update_path(game_name, _game_sounds_, pTHM->SrcName()); + strconcat(sizeof(game_name), game_name, game_name, ".ogg"); + + Msg("synchronizing [%s]", game_name); + SndLib->MakeGameSound(pTHM, src_name, game_name); + } + Msg("Done."); +} + +void UISoundEditorForm::OnAttClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + bModif = true; + ESoundThumbnail *thm = m_THM_Current.back(); + switch (V->btn_num) + { + case 0: + { + float dist = thm->MinDist() / (0.01f * psSoundRolloff); + thm->SetMaxDist(dist + 0.1f * dist); + } + break; + case 1: + { + float dist = psSoundRolloff * (thm->MaxDist() - (0.1f / 1.1f) * thm->MaxDist()) * 0.01f; + thm->SetMinDist(dist); + } + break; + } +} + +void UISoundEditorForm::InitItemList() +{ + FS_FileSet sound_map; + SndLib->GetSounds(sound_map, TRUE); + + ListItemsVec items; + + // fill items + auto it = sound_map.begin(); + auto _E = sound_map.end(); + for (; it != _E; it++) + LHelper().CreateItem(items, it->name.c_str(), 0); + + m_ItemList->AssignItems(items /*, false, true*/); +} + +void UISoundEditorForm::OnItemsFocused(ListItem *item) +{ + PropItemVec props; + + RegisterModifiedTHM(); + m_Snd.destroy(); + m_THM_Current.clear(); + + if (item != nullptr) + { + ListItem *prop = item; + if (prop) + { + ESoundThumbnail *thm = FindUsedTHM(prop->Key()); + if (!thm) + m_THM_Used.push_back(thm = xr_new(prop->Key())); + m_THM_Current.push_back(thm); + thm->FillProp(props); + } + } + + ButtonValue *B = 0; + if (m_THM_Current.size() == 1) + { + ESoundThumbnail *thm = m_THM_Current.back(); + u32 size = 0; + u32 time = 0; + PlaySound(thm->SrcName(), size, time); + + CanvasValue *C = 0; + C = PHelper().CreateCanvas(props, "Attenuation", "", 64); + C->tag = (size_t)this; + C->OnDrawCanvasEvent.bind(this, &UISoundEditorForm::OnAttenuationDraw); + // C->OnTestEqual.bind (this,&TfrmSoundLib::OnPointDataTestEqual); + B = PHelper().CreateButton(props, "Auto Att", "By Min,By Max", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &UISoundEditorForm::OnAttClick); + + PHelper().CreateCaption(props, "File Length", shared_str().printf("%.2f Kb", float(size) / 1024.f)); + PHelper().CreateCaption(props, "Total Time", shared_str().printf("%.2f sec", float(time) / 1000.f)); + if (!m_Flags.is(flReadOnly)) + { + B = PHelper().CreateButton(props, "Control", "Play,Stop", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &UISoundEditorForm::OnControlClick); + } + } + if (!m_Flags.is(flReadOnly)) + { + B = PHelper().CreateButton(props, "Auto Play", bAutoPlay ? "on" : "off", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &UISoundEditorForm::OnControl2Click); + } + + if (!m_Flags.is(flReadOnly) && m_THM_Current.size()) + { + B = PHelper().CreateButton(props, "MANAGE", "SyncCurrent", ButtonValue::flFirstOnly); + B->OnBtnClickEvent.bind(this, &UISoundEditorForm::OnSyncCurrentClick); + } + + m_ItemProps->AssignItems(props); +} +void UISoundEditorForm::PlaySound(LPCSTR name, u32 &size, u32 &time) +{ + string_path fname; + FS.update_path(fname, _game_sounds_, EFS.ChangeFileExt(name, ".ogg").c_str()); + FS_File F; + if (FS.file_find(fname, F)) + { + m_Snd.create(name, st_Effect, sg_Undefined); + m_Snd.play(0, sm_2D); + CSoundRender_Source *src = (CSoundRender_Source *)m_Snd._handle(); + VERIFY(src); + size = F.size; + time = iFloor(src->fTimeTotal / 1000.0f); + if (!bAutoPlay) + m_Snd.stop(); + } +} +void UISoundEditorForm::OnAttenuationDraw(CanvasValue *sender) +{ +#define WIETH 90 +#define HEIGHT 80.f + ESoundThumbnail *thm = m_THM_Current.back(); + float d_cost = thm->MaxDist() / WIETH; + static float values[WIETH] = {}; + for (int d = 1; d < WIETH + 1; d++) + { + float R = d * d_cost; + float b = thm->MinDist() / (psSoundRolloff * R); + // float b = m_Brightness/(m_Attenuation0+m_Attenuation1*R+m_Attenuation2*R*R); + float bb = (HEIGHT * b); + float y = floorf(bb); + clamp(y, 0.f, HEIGHT); + values[d - 1] = y; + } + ImGui::PlotLines("##LinesSound", values, IM_ARRAYSIZE(values), 0, 0, 0, HEIGHT, ImVec2(0, HEIGHT), 4); +} +ESoundThumbnail *UISoundEditorForm::FindUsedTHM(LPCSTR name) +{ + for (THMIt it = m_THM_Used.begin(); it != m_THM_Used.end(); it++) + if (0 == strcmp((*it)->SrcName(), name)) + return *it; + return 0; +} + +void UISoundEditorForm::SaveUsedTHM() +{ + int m_age = time(NULL); + for (THMIt t_it = m_THM_Used.begin(); t_it != m_THM_Used.end(); t_it++) + (*t_it)->Save(m_age, 0); +} + +void UISoundEditorForm::DestroyUsedTHM() +{ + for (THMIt it = m_THM_Used.begin(); it != m_THM_Used.end(); it++) + xr_delete(*it); + m_THM_Used.clear(); +} diff --git a/src/editors/xrECore/Editor/UISoundEditorForm.h b/src/editors/xrECore/Editor/UISoundEditorForm.h new file mode 100644 index 00000000000..d0693a610b7 --- /dev/null +++ b/src/editors/xrECore/Editor/UISoundEditorForm.h @@ -0,0 +1,60 @@ +//--------------------------------------------------------------------------- + +#ifndef SoundLibH +#define SoundLibH +#endif +class UISoundEditorForm : public xrUI +{ +public: + UISoundEditorForm(); + virtual ~UISoundEditorForm(); + virtual void Draw(); + +public: + static void Update(); + static void Show(); + +private: + void HideLib(); + static UISoundEditorForm *Form; + + void InitItemList(); + void OnItemsFocused(ListItem *item); + UIPropertiesForm *m_ItemProps; + UIItemListForm *m_ItemList; + +private: + enum + { + flUpdateProperties = (1 << 0), + flReadOnly = (1 << 1), + }; + Flags32 m_Flags; + DEFINE_VECTOR(ESoundThumbnail *, THMVec, THMIt); + THMVec m_THM_Used; + THMVec m_THM_Current; + ESoundThumbnail *FindUsedTHM(LPCSTR name); + void SaveUsedTHM(); + void DestroyUsedTHM(); + + void RegisterModifiedTHM(); + + void OnModified(); + void UpdateLib(); + + bool bFormLocked; + BOOL bAutoPlay; + + FS_FileSet modif_map; + ref_sound m_Snd; + + void AppendModif(LPCSTR nm); + +private: + void OnControlClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnControl2Click(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnSyncCurrentClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void OnAttClick(ButtonValue *sender, bool &bModif, bool &bSafe); + void PlaySound(LPCSTR name, u32 &size, u32 &time); + void OnAttenuationDraw(CanvasValue *sender); +}; diff --git a/src/editors/xrECore/Editor/UI_Camera.cpp b/src/editors/xrECore/Editor/UI_Camera.cpp new file mode 100644 index 00000000000..b171d29e0be --- /dev/null +++ b/src/editors/xrECore/Editor/UI_Camera.cpp @@ -0,0 +1,421 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "UI_Camera.h" +#include "ui_main.h" +#include "ui_toolscustom.h" + +CUI_Camera::CUI_Camera() +{ + m_Style = csPlaneMove; + + m_Znear = 0.2f; + m_Zfar = 1500.f; + m_HPB.set(0, 0, 0); + m_Position.set(0, 0, 0); + m_Target.set(0, 0, 0); + m_CamMat.identity(); + + m_FlySpeed = 5.f; + m_FlyAltitude = 1.8f; + + m_bMoving = false; +} + +CUI_Camera::~CUI_Camera() +{ +} + +void CUI_Camera::SetStyle(ECameraStyle new_style) +{ + if (new_style == cs3DArcBall) + { + Fvector dir; + dir.sub(m_Target, m_Position); + // parse heading + Fvector DYaw; + DYaw.set(dir.x, 0.f, dir.z); + DYaw.normalize_safe(); + if (DYaw.x < 0) + m_HPB.x = acosf(DYaw.z); + else + m_HPB.x = 2 * PI - acosf(DYaw.z); + // parse pitch + dir.normalize_safe(); + m_HPB.y = asinf(dir.y); + + BuildCamera(); + } + m_Style = new_style; + UI->RedrawScene(); +} + +void CUI_Camera::Reset() +{ + m_HPB.set(0, 0, 0); + m_Position.set(0, 3, -10); + SetStyle(m_Style); + BuildCamera(); +} + +void CUI_Camera::Set(float h, float p, float b, float x, float y, float z) +{ + m_HPB.set(h, p, b); + m_Position.set(x, y, z); + BuildCamera(); +} + +void CUI_Camera::Set(const Fvector &hpb, const Fvector &pos) +{ + m_HPB.set(hpb); + m_Position.set(pos); + BuildCamera(); +} + +void CUI_Camera::BuildCamera() +{ + if (m_HPB.x > PI_MUL_2) + m_HPB.x -= PI_MUL_2; + if (m_HPB.x < -PI_MUL_2) + m_HPB.x += PI_MUL_2; + if (m_HPB.y > PI_MUL_2) + m_HPB.y -= PI_MUL_2; + if (m_HPB.y < -PI_MUL_2) + m_HPB.y += PI_MUL_2; + if (m_HPB.z > PI_MUL_2) + m_HPB.z -= PI_MUL_2; + if (m_HPB.z < -PI_MUL_2) + m_HPB.z += PI_MUL_2; + + if (m_Style == cs3DArcBall) + { + Fvector D; + D.setHP(m_HPB.x, m_HPB.y); + float dist = m_Position.distance_to(m_Target); + m_Position.mul(D, -dist); + m_Position.add(m_Target); + } + + m_CamMat.setHPB(m_HPB.x, m_HPB.y, m_HPB.z); + m_CamMat.translate_over(m_Position); + UI->OutCameraPos(); + + EDevice.vCameraPosition.set(m_CamMat.c); + EDevice.vCameraDirection.set(m_CamMat.k); + EDevice.vCameraTop.set(m_CamMat.j); + EDevice.vCameraRight.set(m_CamMat.i); +} + +void CUI_Camera::SetDepth(float _far, bool bForcedUpdate) +{ + if (m_Zfar != _far) + { + m_Zfar = _far; + UI->Resize(bForcedUpdate); + } +} + +void CUI_Camera::SetViewport(float _near, float _far, float _fov) +{ + if (m_Znear != _near) + { + m_Znear = _near; + UI->Resize(); + } + if (m_Zfar != _far) + { + m_Zfar = _far; + UI->Resize(); + } + if (EDevice.fFOV != _fov) + { + EDevice.fFOV = _fov; + UI->Resize(); + } +} + +void CUI_Camera::SetSensitivity(float sm, float sr) +{ + m_SM = 0.2f * (sm * sm); + m_SR = 0.02f * (sr * sr); +} + +static const Fvector down_dir = {0.f, -1.f, 0.f}; + +void CUI_Camera::Update(float dt) +{ + if (m_bMoving) + { + BOOL bLeftDn = m_Shift & ssLeft; + BOOL bRightDn = m_Shift & ssRight; + if ((m_Style == csFreeFly) && (bLeftDn || bRightDn) && !(bLeftDn && bRightDn)) + { + Fvector vmove; + vmove.set(m_CamMat.k); + vmove.mul(m_FlySpeed * dt); + if (bLeftDn) + m_Position.add(vmove); + else if (bRightDn) + m_Position.sub(vmove); + + if (m_Shift & ssCtrl) + { + float dist = UI->ZFar(); + if (Tools->RayPick(m_Position, down_dir, dist)) // UI->R PickGround(pos,m_Position,dir,-1)) + m_Position.y = m_Position.y + down_dir.y * dist + m_FlyAltitude; + else + m_Position.y = m_FlyAltitude; + } + + UI->RedrawScene(); + } + BuildCamera(); + } +} + +void CUI_Camera::Pan(float dx, float dz) +{ + Fvector vmove; + vmove.set(m_CamMat.k); + vmove.y = 0; + vmove.normalize_safe(); + vmove.mul(dz * -m_SM); + m_Position.add(vmove); + + vmove.set(m_CamMat.i); + vmove.y = 0; + vmove.normalize_safe(); + vmove.mul(dx * m_SM); + m_Position.add(vmove); + + BuildCamera(); +} + +void CUI_Camera::Scale(float dy) +{ + Fvector vmove; + vmove.set(0.f, dy, 0.f); + vmove.y *= -m_SM; + m_Position.add(vmove); + + BuildCamera(); +} + +void CUI_Camera::Rotate(float dx, float dy) +{ + m_HPB.x -= m_SR * dx; + m_HPB.y -= m_SR * dy * EDevice.fASPECT; + + BuildCamera(); +} + +void IR_GetMousePosScreen(Ivector2& p) { GetCursorPos((LPPOINT)&p); } + +bool CUI_Camera::MoveStart(TShiftState Shift) +{ + if (Shift & ssShift) + { + if (!m_bMoving) + { + ShowCursor(FALSE); + IR_GetMousePosScreen(m_StartPos); + m_bMoving = true; + } + m_Shift = Shift; + return true; + } + m_Shift = Shift; + return false; +} + +bool CUI_Camera::MoveEnd(TShiftState Shift) +{ + m_Shift = Shift; + if ((~Shift & ssLeft) || (~Shift & ssShift)) + { + SetCursorPos(m_StartPos.x, m_StartPos.y); + ShowCursor(TRUE); + m_bMoving = false; + return true; + } + return false; +} + +bool CUI_Camera::Process(TShiftState Shift, int dx, int dy) +{ + if (m_bMoving) + { + m_Shift = Shift; + // camera move + if (dx || dy) + { + SetCursorPos(m_StartPos.x, m_StartPos.y); + switch (m_Style) + { + case csPlaneMove: + if ((m_Shift & ssLeft) && (m_Shift & ssRight)) + { + Rotate(dx, dy); + } + else if (m_Shift & ssLeft) + { + Pan(dx, dy); + } + else if (m_Shift & ssRight) + { + Scale(dy); + } + break; + case csFreeFly: + if ((m_Shift & ssLeft) || (m_Shift & ssRight)) + Rotate(dx, dy); + // if (Shift&ssLeft)) Rotate (d.x,d.y); + // else if (Shift&ssRight)) Scale(d.y); + break; + case cs3DArcBall: + ArcBall(m_Shift, static_cast(dx), static_cast(dy)); + break; + } + UI->RedrawScene(); + } + return true; + } + return false; +} + +bool CUI_Camera::KeyDown(WORD Key, TShiftState Shift) +{ + if (m_bMoving) + { + switch (Key) + { + case VK_CONTROL: + m_Shift = ssCtrl | m_Shift; + break; + default: + return false; + } + return true; + } + return false; +} + +bool CUI_Camera::KeyUp(WORD Key, TShiftState Shift) +{ + if (m_bMoving) + { + switch (Key) + { + case VK_SHIFT: + m_Shift = ~ssShift & m_Shift; + MoveEnd(m_Shift); + break; + case VK_CONTROL: + m_Shift = ~ssCtrl & m_Shift; + break; + default: + return false; + } + return true; + } + return false; +} + +void CUI_Camera::MouseRayFromPoint(Fvector &start, Fvector &direction, const Ivector2 &point) +{ + int halfwidth = static_cast(UI->GetRenderWidth() * 0.5f / EDevice.m_ScreenQuality); + int halfheight = static_cast(UI->GetRenderHeight() * 0.5f / EDevice.m_ScreenQuality); + + if (!halfwidth || !halfheight) + return; + + Ivector2 point2; + point2.set(point.x - halfwidth, halfheight - point.y); + + start.set(m_Position); + + float size_y = m_Znear * tan(deg2rad(EDevice.fFOV) * 0.5f); + float size_x = size_y / EDevice.fASPECT; + + float r_pt = float(point2.x) * size_x / (float)halfwidth; + float u_pt = float(point2.y) * size_y / (float)halfheight; + + direction.mul(m_CamMat.k, m_Znear); + direction.mad(direction, m_CamMat.j, u_pt); + direction.mad(direction, m_CamMat.i, r_pt); + direction.normalize(); +} + +void CUI_Camera::ZoomExtents(const Fbox &bb) +{ + Fvector C, D; + float R, H1, H2; + bb.getsphere(C, R); + D.mul(m_CamMat.k, -1); + H1 = R / sinf(deg2rad(EDevice.fFOV) * 0.5f); + H2 = R / sinf(deg2rad(EDevice.fFOV) * 0.5f / EDevice.fASPECT); + m_Position.mad(C, D, _max(H1, H2)); + m_Target.set(C); + + BuildCamera(); + /* + eye_k - фокусное расстояние, eye_k=eye_width/2 + camera.alfa:=0; + camera.beta:=-30*pi/180; + camera.gama:=0; + s:=(maxx-minx)*eye_k/eye_width*0.5*0.5; + camera.posx:=(maxx+minx)/2; + camera.posy:=maxy+s*tan(30*pi/180); + camera.posz:=minz-s; + */ +} + +void CUI_Camera::ArcBall(TShiftState Shift, float dx, float dy) +{ + float dist = m_Position.distance_to(m_Target); + if (Shift & ssAlt) + { + if (Shift & ssLeft) + { + Fvector vmove; + vmove.set(m_CamMat.k); + vmove.y = 0; + vmove.normalize_safe(); + vmove.mul(dy * -m_SM); + m_Target.add(vmove); + + vmove.set(m_CamMat.i); + vmove.y = 0; + vmove.normalize_safe(); + vmove.mul(dx * m_SM); + m_Target.add(vmove); + } + else if (Shift & ssRight) + { + Fvector vmove; + vmove.set(0.f, dy, 0.f); + vmove.y *= -m_SM; + m_Target.add(vmove); + } + } + else + { + if (Shift & ssRight) + { + dist -= dx * m_SM; + } + else if (Shift & ssLeft) + { + m_HPB.x -= m_SR * dx; + m_HPB.y -= m_SR * dy * EDevice.fASPECT; + } + } + + Fvector D; + D.setHP(m_HPB.x, m_HPB.y); + + m_Position.mul(D, -dist); + m_Position.add(m_Target); + + BuildCamera(); +} diff --git a/src/editors/xrECore/Editor/UI_Camera.h b/src/editors/xrECore/Editor/UI_Camera.h new file mode 100644 index 00000000000..9161b0dd394 --- /dev/null +++ b/src/editors/xrECore/Editor/UI_Camera.h @@ -0,0 +1,122 @@ +//--------------------------------------------------------------------------- +#ifndef UI_CameraH +#define UI_CameraH + +enum ECameraStyle +{ + csPlaneMove = 0, + cs3DArcBall, + csFreeFly +}; + +class ECORE_API CUI_Camera +{ + ECameraStyle m_Style; + bool m_bMoving; + TShiftState m_Shift; + Ivector2 m_StartPos; + float m_FlySpeed; + float m_FlyAltitude; + + Fmatrix m_CamMat; + Fvector m_HPB; + Fvector m_Position; + Fvector m_Target; + +protected: + friend class CEditorRenderDevice; + friend class TUI; + + float m_Znear; + float m_Zfar; + float m_SR, m_SM; + + void Pan(float X, float Z); + void Pan(int X, int Y) { Pan(static_cast(X), static_cast(Y)); } + void Scale(float Y); + void Scale(int Y) { Scale(static_cast(Y)); } + void Rotate(float X, float Y); + void Rotate(int X, int Y) { Rotate(static_cast(X), static_cast(Y)); } + void ArcBall(TShiftState Shift, float X, float Y); + +public: + CUI_Camera(); + virtual ~CUI_Camera(); + + IC float _Znear() { return m_Znear; } + IC float _Zfar() { return m_Zfar; } + + void BuildCamera(); + void Reset(); + void Update(float dt); + void SetStyle(ECameraStyle style); + ECameraStyle GetStyle() { return m_Style; } + + bool MoveStart(TShiftState Shift); + bool MoveEnd(TShiftState Shift); + bool IsMoving() { return m_bMoving; } + bool Process(TShiftState Shift, int dx, int dy); + bool KeyDown(WORD Key, TShiftState Shift); + bool KeyUp(WORD Key, TShiftState Shift); + + void ViewFront() + { + m_HPB.set(0.f, 0.f, 0.f); + BuildCamera(); + } + void ViewBack() + { + m_HPB.set(M_PI, 0.f, 0.f); + BuildCamera(); + } + void ViewLeft() + { + m_HPB.set(-PI_DIV_2, 0.f, 0.f); + BuildCamera(); + } + void ViewRight() + { + m_HPB.set(PI_DIV_2, 0.f, 0.f); + BuildCamera(); + } + void ViewTop() + { + m_HPB.set(0.f, -PI_DIV_2, 0.f); + BuildCamera(); + } + void ViewBottom() + { + m_HPB.set(0.f, PI_DIV_2, 0.f); + BuildCamera(); + } + void ViewReset() + { + m_HPB.set(0.f, 0, 0.f); + m_Position.set(0, 0, 0); + m_Target.set(0, 0, 0); + BuildCamera(); + } + + const Fmatrix &GetTransform() const { return m_CamMat; } + const Fmatrix &GetView(Fmatrix &V) const { return V.invert(m_CamMat); } + const Fvector &GetHPB() const { return m_HPB; } + const Fvector &GetPosition() const { return m_Position; } + const Fvector &GetRight() const { return m_CamMat.i; } + const Fvector &GetNormal() const { return m_CamMat.j; } + const Fvector &GetDirection() const { return m_CamMat.k; } + void Set(float h, float p, float b, float x, float y, float z); + void Set(const Fvector &hpb, const Fvector &pos); + void SetSensitivity(float sm, float sr); + void SetViewport(float _near, float _far, float _fov); + void SetDepth(float _far, bool bForcedUpdate); + void SetFlyParams(float speed, float fAltitude) + { + m_FlySpeed = speed; + m_FlyAltitude = fAltitude; + } + + void ZoomExtents(const Fbox &bb); + + void MouseRayFromPoint(Fvector &start, Fvector &direction, const Ivector2 &point); +}; +#endif diff --git a/src/editors/xrECore/Editor/UI_MainCommand.cpp b/src/editors/xrECore/Editor/UI_MainCommand.cpp new file mode 100644 index 00000000000..9fa8b7b5622 --- /dev/null +++ b/src/editors/xrECore/Editor/UI_MainCommand.cpp @@ -0,0 +1,846 @@ +#include "stdafx.h" +#include "xrCore/_fbox2.h" + +#include "ui_main.h" +#include "UI_ToolsCustom.h" + +#include "UIEditLightAnim.h" +#include "UIImageEditorForm.h" +#include "UIMinimapEditorForm.h" +#include "UISoundEditorForm.h" +#include "d3dutils.h" + +#include "Library.h" +#include "xrEngine/LightAnimLibrary.h" + +#include "ImageManager.h" +#include "SoundManager.h" +#include "Layers/xrRender/ResourceManager.h" +#include "xrEngine/igame_persistent.h" + +ECommandVec ECommands; +BOOL bAllowReceiveCommand = FALSE; +bool bAllowLogCommands = false; +// TfrmText* frmEditCommandList = 0; +xr_string sCommandListText; + +BOOL AllowLogCommands() +{ + return bAllowLogCommands; +} + +ECommandVec &GetEditorCommands() +{ + return ECommands; +} +void EnableReceiveCommands() +{ + bAllowReceiveCommand = TRUE; +} +SESubCommand *FindCommandByShortcut(const xr_shortcut &val) +{ + ECommandVec &cmds = GetEditorCommands(); + for (u32 cmd_idx = 0; cmd_idx < cmds.size(); cmd_idx++) + { + SECommand *&CMD = cmds[cmd_idx]; + if (CMD && CMD->editable) + { + VERIFY(!CMD->sub_commands.empty()); + for (u32 sub_cmd_idx = 0; sub_cmd_idx < CMD->sub_commands.size(); sub_cmd_idx++) + { + SESubCommand *&SUB_CMD = CMD->sub_commands[sub_cmd_idx]; + if (SUB_CMD->shortcut.similar(val)) + return SUB_CMD; + } + } + } + return 0; +} +SECommand *FindCommandByName(LPCSTR nm) +{ + ECommandVec &cmds = GetEditorCommands(); + for (u32 cmd_idx = 0; cmd_idx < cmds.size(); cmd_idx++) + { + SECommand *&CMD = cmds[cmd_idx]; + if (CMD && (0 == stricmp(CMD->name, nm))) + return CMD; + } + return 0; +} +SESubCommand *FindSubCommandByName(SECommand *CMD, LPCSTR nm) +{ + VERIFY(CMD && !CMD->sub_commands.empty()); + for (u32 sub_cmd_idx = 0; sub_cmd_idx < CMD->sub_commands.size(); sub_cmd_idx++) + { + SESubCommand *SUB_CMD = CMD->sub_commands[sub_cmd_idx]; + if (0 == stricmp(SUB_CMD->desc.c_str(), nm)) + return SUB_CMD; + } + return 0; +} +void ParseParam(xr_string sp, CCommandVar &res) +{ + if (!sp.empty()) + { + u32 rs = 0, ip = 0; + if (0 == strstr(sp.c_str(), "\"")) + rs = sscanf(sp.c_str(), "%d", &ip); + if (1 != rs) + { + _GetItem(sp.c_str(), 1, sp, '\"'); + if (!sp.empty()) + res = sp; + } + else + res = ip; + } +} +CCommandVar ExecCommand(const xr_shortcut &val) +{ + SESubCommand *SUB = FindCommandByShortcut(val); + CCommandVar res = CCommandVar(u32(0)); + if (SUB) + res = ExecCommand(SUB->parent->idx, SUB->p0, SUB->p1); + return res; +} +CCommandVar ExecCommand(u32 cmd, CCommandVar p1, CCommandVar p2) +{ + if (!bAllowReceiveCommand) + return 0; + + VERIFY(cmd < ECommands.size()); + CCommandVar res; + SECommand *CMD = ECommands[cmd]; + VERIFY(CMD && !CMD->command.empty()); + static int exec_level = 0; + if (bAllowLogCommands) + { + string128 level; + strcpy(level, exec_level == 0 ? "" : ";"); + for (int k = 0; k < exec_level; ++k) + strcat(level, "."); + xr_string sp1 = p1.IsString() ? xr_string(p1) : xr_string(""); + xr_string sp2 = p2.IsString() ? xr_string(p2) : xr_string(""); + if (p1.IsString()) + sp1 = ((sp1.find("\n") == sp1.npos) && (sp1.find("\r") == sp1.npos)) ? sp1 : xr_string("..."); + if (p2.IsString()) + sp2 = ((sp2.find("\n") == sp2.npos) && (sp2.find("\r") == sp2.npos)) ? sp2 : xr_string("..."); + if (p1.IsString() && p2.IsString()) + Msg("%s%s (\"%s\",\"%s\")", level, CMD->Name(), sp1.c_str(), sp2.c_str()); + else if (p1.IsInteger() && p2.IsInteger()) + Msg("%s%s (%d,%d)", level, CMD->Name(), u32(p1), u32(p2)); + else if (p1.IsInteger() && p2.IsString()) + Msg("%s%s (%d,\"%s\")", level, CMD->Name(), u32(p1), sp2.c_str()); + else if (p1.IsString() && p2.IsInteger()) + Msg("%s%s (\"%s\",%d)", level, CMD->Name(), sp1.c_str(), u32(p2)); + } + exec_level++; + res = CMD->command(p1, p2); + exec_level--; + VERIFY(exec_level >= 0); + return res; +} +void RegisterCommand(u32 cmd, SECommand *cmd_impl) +{ + if (cmd >= ECommands.size()) + ECommands.resize(cmd + 1, 0); + SECommand *&CMD = ECommands[cmd]; + if (CMD) + { + Msg("RegisterCommand: command '%s' overridden by command '%s'.", *CMD->desc, *cmd_impl->desc); + xr_delete(CMD); + } + CMD = cmd_impl; +} +void RegisterSubCommand(SECommand *cmd_impl, LPCSTR desc, CCommandVar p0, CCommandVar p1) +{ + VERIFY(cmd_impl); + cmd_impl->AppendSubCommand(desc, p0, p1); +} +BOOL LoadShortcuts(CInifile *ini) +{ + for (u32 cmd_idx = 0; cmd_idx < ECommands.size(); cmd_idx++) + { + SECommand *&CMD = ECommands[cmd_idx]; + if (CMD && CMD->editable) + { + for (u32 sub_cmd_idx = 0; sub_cmd_idx < CMD->sub_commands.size(); sub_cmd_idx++) + { + SESubCommand *&SUB = CMD->sub_commands[sub_cmd_idx]; + string256 nm, tmp; + if (SUB->desc.size()) + sprintf(nm, "%s.\"%s\"", CMD->Name(), SUB->desc.c_str()); + else + sprintf(nm, "%s", CMD->Name()); + if (ini->line_exist("shortcuts", nm)) + { + LPCSTR val = ini->r_string("shortcuts", nm); + int res = sscanf(val, "%hd,%s", &SUB->shortcut.hotkey, tmp); + if (2 == res) + { + xr_string sp; + _GetItem(tmp, 0, sp); + ParseParam(sp, SUB->p0); + _GetItem(tmp, 1, sp); + ParseParam(sp, SUB->p1); + } + } + } + } + } + return TRUE; +} +BOOL SaveShortcuts(CInifile *ini) +{ + for (u32 cmd_idx = 0; cmd_idx < ECommands.size(); cmd_idx++) + { + SECommand *&CMD = ECommands[cmd_idx]; + if (CMD && CMD->editable) + { + for (u32 sub_cmd_idx = 0; sub_cmd_idx < CMD->sub_commands.size(); sub_cmd_idx++) + { + SESubCommand *&SUB = CMD->sub_commands[sub_cmd_idx]; + string256 nm, tmp; + if (SUB->desc.size()) + sprintf(nm, "%s.\"%s\"", CMD->Name(), SUB->desc.c_str()); + else + sprintf(nm, "%s", CMD->Name()); + if (SUB->p0.IsString() && SUB->p1.IsString()) + sprintf(tmp, "%d, \"%s\",\"%s\"", SUB->shortcut.hotkey, xr_string(SUB->p0).c_str(), xr_string(SUB->p1).c_str()); + else if (SUB->p0.IsInteger() && SUB->p1.IsInteger()) + sprintf(tmp, "%d, %d,%d", SUB->shortcut.hotkey, u32(SUB->p0), u32(SUB->p1)); + else if (SUB->p0.IsInteger() && SUB->p1.IsString()) + sprintf(tmp, "%d, %d,\"%s\"", SUB->shortcut.hotkey, u32(SUB->p0), xr_string(SUB->p1).c_str()); + else if (SUB->p0.IsString() && SUB->p1.IsInteger()) + sprintf(tmp, "%d, \"%s\",%d", SUB->shortcut.hotkey, xr_string(SUB->p0).c_str(), u32(SUB->p1)); + ini->w_string("shortcuts", nm, tmp); + } + } + } + return TRUE; +} +void ClearCommands() +{ + for (ECommandVecIt it = ECommands.begin(); it != ECommands.end(); it++) + xr_delete(*it); + ECommands.clear(); +} + +void TUI::ClearCommands() +{ + ::ClearCommands(); +} + +// UI Commands +CCommandVar TUI::CommandRenderFocus(CCommandVar p1, CCommandVar p2) +{ + SetFocus(EDevice.m_hWnd); + return 1; +} + +CCommandVar TUI::CommandBreakLastOperation(CCommandVar p1, CCommandVar p2) +{ + if (mrYes == ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to break current action?")) + { + NeedBreak(); + ELog.Msg(mtInformation, "Execution canceled."); + } + return 1; +} + +CCommandVar TUI::CommandRenderResize(CCommandVar p1, CCommandVar p2) +{ + /* if (psDeviceFlags.is(rsDrawSafeRect)){ + int w=m_D3DPanel->Width,h=m_D3DPanel->Height,w_2=w/2,h_2=h/2; + Irect rect; + if ((0.75f*float(w))>float(h)) rect.set(w_2-1.33f*float(h_2),0,1.33f*h,h); + else rect.set(0,h_2-0.75f*float(w_2),w,0.75f*w); + m_D3DWindow->Left = rect.x1; + m_D3DWindow->Top = rect.y1; + m_D3DWindow->Width = rect.x2; + m_D3DWindow->Height = rect.y2; + }else{ + m_D3DWindow->Left = 0; + m_D3DWindow->Top = 0; + m_D3DWindow->Width = m_D3DPanel->Width; + m_D3DWindow->Height = m_D3DPanel->Height; + } + UI->RedrawScene ();*/ + return 1; +} + +//------------------------------------------------------------------------------ +// Common Commands +//------------------------------------------------------------------------------ +CCommandVar CommandInitialize(CCommandVar p1, CCommandVar p2) +{ + CCommandVar res = TRUE; + Engine.Initialize(); + // make interface + //---------------- + if (EPrefs) + EPrefs->OnCreate(); + if (UI->OnCreate(/*(TD3DWindow*)(u32)p1,(TPanel*)(u32)p2)*/)) + { + ExecCommand(COMMAND_CREATE_SOUND_LIB); + R_ASSERT(SndLib); + SndLib->OnCreate(); + LALib.OnCreate(); + Lib.OnCreate(); + BOOL bWeather = psDeviceFlags.is(rsEnvironment); + psDeviceFlags.set(rsEnvironment, FALSE); + g_pGamePersistent = xr_new(); + if (Tools) + { + if (Tools->OnCreate()) + { + if (EPrefs) + EPrefs->Load(); + EDevice.seqAppStart.Process(); + ExecCommand(COMMAND_RESTORE_UI_BAR); + ExecCommand(COMMAND_REFRESH_UI_BAR); + ExecCommand(COMMAND_CLEAR); + ExecCommand(COMMAND_RENDER_FOCUS); + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + ExecCommand(COMMAND_RENDER_RESIZE); + /* + if(bWeather && EPrefs->sWeather.size() ) + { + psDeviceFlags.set(rsEnvironment, TRUE); + g_pGamePersistent->Environment().SetWeather(EPrefs->sWeather, true); + + } + */ + } + else + { + res = FALSE; + } + } + } + else + { + res = FALSE; + } + return res; +} +CCommandVar CommandDestroy(CCommandVar p1, CCommandVar p2) +{ + ExecCommand(COMMAND_SAVE_UI_BAR); + EPrefs->OnDestroy(); + ExecCommand(COMMAND_CLEAR); + EDevice.seqAppEnd.Process(); + xr_delete(g_pGamePersistent); + LALib.OnDestroy(); + Tools->OnDestroy(); + SndLib->OnDestroy(); + xr_delete(SndLib); + DU_impl.DestroyObjects(); + Lib.OnDestroy(); + UI->OnDestroy(); + Engine.Destroy(); + ELog.Close(); + for (auto &item : ECommands) + { + xr_delete(item); + } + ECommands.clear(); + return TRUE; +} +CCommandVar CommandQuit(CCommandVar p1, CCommandVar p2) +{ + if (UI->IsModified()) + UI->Quit(); + return TRUE; +} +CCommandVar CommandEditorPrefs(CCommandVar p1, CCommandVar p2) +{ + EPrefs->Edit(); + return TRUE; +} +CCommandVar CommandChangeAction(CCommandVar p1, CCommandVar p2) +{ + Tools->SetAction(ETAction(u32(p1))); + return TRUE; +} +CCommandVar CommandChangeAxis(CCommandVar p1, CCommandVar p2) +{ + Tools->SetAxis(ETAxis(u32(p1))); + return TRUE; +} + +CCommandVar CommandSimulate(CCommandVar p1, CCommandVar p2) +{ + + Tools->Simulate(); + + return TRUE; +} + +CCommandVar CommandUseSimulatePositions(CCommandVar p1, CCommandVar p2) +{ + + Tools->UseSimulatePositions(); + + return TRUE; +} + +CCommandVar CommandSetSettings(CCommandVar p1, CCommandVar p2) +{ + Tools->SetSettings(p1, p2); + return TRUE; +} + +CCommandVar CommandSoundEditor(CCommandVar p1, CCommandVar p2) +{ + UISoundEditorForm::Show(); + return TRUE; +} + +CCommandVar CommandSyncSounds(CCommandVar p1, CCommandVar p2) +{ + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to synchronize sounds?") == mrYes) + SndLib->RefreshSounds(true); + return TRUE; +} + +CCommandVar CommandImageEditor(CCommandVar p1, CCommandVar p2) +{ + UIImageEditorForm::Show(false); + return TRUE; +} + +CCommandVar CommandLightAnimEditor(CCommandVar p1, CCommandVar p2) +{ + UIEditLightAnim::Show(); + return TRUE; +} + +CCommandVar CommandMinimapEditor(CCommandVar p1, CCommandVar p2) +{ + UIMinimapEditorForm::Show(); + return TRUE; +} + +CCommandVar CommandCheckTextures(CCommandVar p1, CCommandVar p2) +{ + UIImageEditorForm::ImportTextures(); + return TRUE; +} +CCommandVar CommandRefreshTextures(CCommandVar p1, CCommandVar p2) +{ + if (ELog.DlgMsg(mtConfirmation, mbYes | mbNo, "Are you sure to synchronize textures?") == mrYes) + ImageLib.RefreshTextures(0); + return TRUE; +} +CCommandVar CommandReloadTextures(CCommandVar p1, CCommandVar p2) +{ + EDevice.ReloadTextures(); + UI->RedrawScene(); + return TRUE; +} +CCommandVar CommandChangeSnap(CCommandVar p1, CCommandVar p2) +{ + not_implemented(); + // ((TExtBtn*)(u32)p1)->Down = !((TExtBtn*)(u32)p1)->Down; + return TRUE; +} +CCommandVar CommandUnloadTextures(CCommandVar p1, CCommandVar p2) +{ + EDevice.UnloadTextures(); + return TRUE; +} +CCommandVar CommandEvictObjects(CCommandVar p1, CCommandVar p2) +{ + Lib.EvictObjects(); + return TRUE; +} +CCommandVar CommandEvictTextures(CCommandVar p1, CCommandVar p2) +{ + EDevice.Resources->Evict(); + return TRUE; +} +CCommandVar CommandCheckModified(CCommandVar p1, CCommandVar p2) +{ + return Tools->IsModified(); +} +CCommandVar CommandExit(CCommandVar p1, CCommandVar p2) +{ + return Tools->IfModified(); +} +CCommandVar CommandShowProperties(CCommandVar p1, CCommandVar p2) +{ + if (p1.IsString()) + { + xr_string SSS = p1; + Tools->ShowProperties(SSS.c_str()); + } + else + Tools->ShowProperties(NULL); + return TRUE; +} +CCommandVar CommandUpdateProperties(CCommandVar p1, CCommandVar p2) +{ + Tools->UpdateProperties(p1); + return TRUE; +} +CCommandVar CommandRefreshProperties(CCommandVar p1, CCommandVar p2) +{ + Tools->RefreshProperties(); + return TRUE; +} +CCommandVar CommandZoomExtents(CCommandVar p1, CCommandVar p2) +{ + Tools->ZoomObject(p1); + UI->RedrawScene(); + return TRUE; +} +CCommandVar CommandToggleRenderWire(CCommandVar p1, CCommandVar p2) +{ + if (EDevice.dwFillMode != D3DFILL_WIREFRAME) + EDevice.dwFillMode = D3DFILL_WIREFRAME; + else + EDevice.dwFillMode = D3DFILL_SOLID; + UI->RedrawScene(); + return TRUE; +} +CCommandVar CommandToggleSafeRect(CCommandVar p1, CCommandVar p2) +{ + psDeviceFlags.set(rsDrawSafeRect, !psDeviceFlags.is(rsDrawSafeRect)); + ExecCommand(COMMAND_RENDER_RESIZE); + UI->RedrawScene(); + return TRUE; +} +CCommandVar CommandToggleGrid(CCommandVar p1, CCommandVar p2) +{ + psDeviceFlags.set(rsDrawGrid, !psDeviceFlags.is(rsDrawGrid)); + UI->RedrawScene(); + return TRUE; +} +CCommandVar CommandUpdateGrid(CCommandVar p1, CCommandVar p2) +{ + DU_impl.UpdateGrid(EPrefs->grid_cell_count, EPrefs->grid_cell_size); + UI->OutGridSize(); + UI->RedrawScene(); + return TRUE; +} +CCommandVar CommandGridNumberOfSlots(CCommandVar p1, CCommandVar p2) +{ + if (p1) + EPrefs->grid_cell_count += 2; + else + EPrefs->grid_cell_count -= 2; + ExecCommand(COMMAND_UPDATE_GRID); + UI->RedrawScene(); + return TRUE; +} +CCommandVar CommandGridSlotSize(CCommandVar p1, CCommandVar p2) +{ + float step = 1.f; + float val = EPrefs->grid_cell_size; + if (p1) + { + if (val < 1) + step /= 10.f; + EPrefs->grid_cell_size += step; + } + else + { + if (fsimilar(val, 1.f) || (val < 1)) + step /= 10.f; + EPrefs->grid_cell_size -= step; + } + ExecCommand(COMMAND_UPDATE_GRID); + UI->RedrawScene(); + return TRUE; +} +CCommandVar CommandCreateSoundLib(CCommandVar p1, CCommandVar p2) +{ + SndLib = xr_new(); + return TRUE; +} +CCommandVar CommandMuteSound(CCommandVar p1, CCommandVar p2) +{ + SndLib->MuteSounds(p1); + return TRUE; +} +CCommandVar CommandMoveCameraTo(CCommandVar p1, CCommandVar p2) +{ + not_implemented(); + Fvector pos = EDevice.m_Camera.GetPosition(); + /*if (NumericVectorRun ("Move to",&pos,3)) + EDevice.m_Camera.Set (EDevice.m_Camera.GetHPB(),pos);*/ + return TRUE; +} + +CCommandVar ExecuteCommandList(LPCSTR text) +{ + CCommandVar res = TRUE; + IReader F((void *)text, xr_strlen(text)); + while (!F.eof()) + { + xr_string line, cmd, params, sp1, sp2; + F.r_string(line); + line = _Trim(line); + if (!line.empty()) + { + if (line[0] == ';' || (line[0] == '/' && line[1] == '/')) + continue; + _GetItem(line.c_str(), 0, cmd, '('); + _GetItem(line.c_str(), 1, params, '('); + _GetItem(params.c_str(), 0, params, ')'); + _GetItem(params.c_str(), 0, sp1, ','); + _GetItem(params.c_str(), 1, sp2, ','); + // parse cmd + xr_string cmd_name, sub_cmd_name; + _GetItem(cmd.c_str(), 0, cmd_name, '.'); + _GetItem(cmd.c_str(), 1, sub_cmd_name, '.'); + + SECommand *CMD = FindCommandByName(cmd_name.c_str()); + if (CMD) + { + SESubCommand *SUB = FindSubCommandByName(CMD, sub_cmd_name.c_str()); + if (!sub_cmd_name.empty() && !SUB) + { + ELog.DlgMsg(mtError, "Can't find sub-command: '%s'", sub_cmd_name.c_str()); + res = FALSE; + break; + } + // parse params + CCommandVar p1, p2; + if (SUB) + { + p1 = SUB->p0; + p2 = SUB->p1; + } + ParseParam(sp1, p1); + ParseParam(sp2, p2); + // execute command + if (FALSE == ExecCommand(CMD->idx, p1, p2)) + { + ELog.DlgMsg(mtError, "Can't execute command: '%s'", cmd.c_str()); + res = FALSE; + break; + } + } + else + { + ELog.DlgMsg(mtError, "Can't find command: '%s'", cmd.c_str()); + res = FALSE; + break; + } + } + } + return res; +} + +bool OnRunExecuteListClick(LPCSTR txt) +{ + ExecuteCommandList(txt); + return true; +} + +CCommandVar CommandExecuteCommandList(CCommandVar _p1, CCommandVar _p2) +{ + xr_string cmds_text = _p1; + return ExecuteCommandList(cmds_text.c_str()); +} + +bool OnCloseCommandListEditor() +{ + not_implemented(); + // frmEditCommandList = 0; + return true; +} + +CCommandVar CommandEditCommandList(CCommandVar _p1, CCommandVar _p2) +{ + not_implemented(); + /* if (NULL==frmEditCommandList){ + // frmEditCommandList = TfrmText::CreateForm(sCommandListText,"Execute command list",0,0,"Run",OnRunExecuteListClick,OnCloseCommandListEditor); + return TRUE; + }*/ + return FALSE; +} + +CCommandVar CommandLogCommands(CCommandVar _p1, CCommandVar _p2) +{ + + bAllowLogCommands = !_p1; + return TRUE; +} +CCommandVar CommandRunMacro(CCommandVar p1, CCommandVar p2) +{ + xr_string fn; + if (p1.IsString()) + { + fn = xr_string(p1); + IReader *F = FS.r_open(fn.c_str()); + if (NULL == F) + F = FS.r_open(_import_, fn.c_str()); + if (F) + { + ExecCommand(COMMAND_EXECUTE_COMMAND_LIST, xr_string((LPCSTR)F->pointer())); + FS.r_close(F); + return TRUE; + } + } + else + { + SECommand *CMD = GetEditorCommands()[COMMAND_RUN_MACRO]; + VERIFY(CMD); + u32 num = p1; + VERIFY(num < CMD->sub_commands.size()); + SESubCommand *SUB = CMD->sub_commands[num]; + fn = xr_string(SUB->p0); + return ExecCommand(COMMAND_RUN_MACRO, fn, p2); + } + return FALSE; +} +CCommandVar CommandAssignMacro(CCommandVar p1, CCommandVar p2) +{ + xr_string fn = p2.IsString() ? xr_string(p2) : xr_string(""); + if (p2.IsString()) + { + if (0 == fn.find(FS.get_path(_import_)->m_Path)) + fn = xr_string(fn.c_str() + xr_strlen(FS.get_path(_import_)->m_Path)); + ECommands[COMMAND_RUN_MACRO]->sub_commands[p1]->p0 = fn; + return TRUE; + } + else + { + if (EFS.GetOpenName(EDevice.m_hWnd, _import_, fn, false, NULL, 2)) + return ExecCommand(COMMAND_ASSIGN_MACRO, p1, fn); + } + return FALSE; +} +void TUI::RegisterCommands() +{ + REGISTER_CMD_S(COMMAND_INITIALIZE, CommandInitialize); + REGISTER_CMD_S(COMMAND_DESTROY, CommandDestroy); + REGISTER_CMD_SE(COMMAND_EXIT, "Exit", CommandExit, true); + REGISTER_CMD_S(COMMAND_QUIT, CommandQuit); + REGISTER_CMD_SE(COMMAND_EDITOR_PREF, "Editor Preference", CommandEditorPrefs, false); + + REGISTER_CMD_SE(COMMAND_SIMULATE, "Simulate", CommandSimulate, true); + REGISTER_CMD_SE(COMMAND_USE_SIMULATE_POSITIONS, "Use Simulate Positions", CommandUseSimulatePositions, true); + + REGISTER_SUB_CMD_SE(COMMAND_CHANGE_ACTION, "Change Action", CommandChangeAction, false); + APPEND_SUB_CMD("Select", etaSelect, 0); + APPEND_SUB_CMD("Add", etaAdd, 0); + APPEND_SUB_CMD("Move", etaMove, 0); + APPEND_SUB_CMD("Rotate", etaRotate, 0); + APPEND_SUB_CMD("Scale", etaScale, 0); + REGISTER_SUB_CMD_END; + REGISTER_SUB_CMD_SE(COMMAND_CHANGE_AXIS, "Change Axis", CommandChangeAxis, false); + APPEND_SUB_CMD("X", etAxisX, 0); + APPEND_SUB_CMD("Y", etAxisY, 0); + APPEND_SUB_CMD("Z", etAxisZ, 0); + APPEND_SUB_CMD("ZX", etAxisZX, 0); + REGISTER_SUB_CMD_END; + REGISTER_CMD_S(COMMAND_SET_SETTINGS, CommandSetSettings); + REGISTER_CMD_S(COMMAND_SOUND_EDITOR, CommandSoundEditor); + REGISTER_CMD_S(COMMAND_SYNC_SOUNDS, CommandSyncSounds); + REGISTER_CMD_S(COMMAND_IMAGE_EDITOR, CommandImageEditor); + REGISTER_CMD_S(COMMAND_LIGHTANIM_EDITOR, CommandLightAnimEditor); + REGISTER_CMD_S(COMMAND_MINIMAP_EDITOR, CommandMinimapEditor); + REGISTER_CMD_S(COMMAND_CHECK_TEXTURES, CommandCheckTextures); + REGISTER_CMD_S(COMMAND_REFRESH_TEXTURES, CommandRefreshTextures); + REGISTER_CMD_S(COMMAND_RELOAD_TEXTURES, CommandReloadTextures); + REGISTER_CMD_S(COMMAND_CHANGE_SNAP, CommandChangeSnap); + REGISTER_CMD_S(COMMAND_UNLOAD_TEXTURES, CommandUnloadTextures); + REGISTER_CMD_S(COMMAND_EVICT_OBJECTS, CommandEvictObjects); + REGISTER_CMD_S(COMMAND_EVICT_TEXTURES, CommandEvictTextures); + REGISTER_CMD_S(COMMAND_CHECK_MODIFIED, CommandCheckModified); + REGISTER_CMD_SE(COMMAND_SHOW_PROPERTIES, "Show Properties", CommandShowProperties, false); + REGISTER_CMD_S(COMMAND_UPDATE_PROPERTIES, CommandUpdateProperties); + REGISTER_CMD_S(COMMAND_REFRESH_PROPERTIES, CommandRefreshProperties); + REGISTER_SUB_CMD_SE(COMMAND_ZOOM_EXTENTS, "Zoom", CommandZoomExtents, false); + APPEND_SUB_CMD("Extent", 0, 0); + APPEND_SUB_CMD("Selected", 1, 0); + REGISTER_SUB_CMD_END; + REGISTER_CMD_SE(COMMAND_MOVE_CAMERA_TO, "Scene\\Move Camera To", CommandMoveCameraTo, false); + REGISTER_CMD_SE(COMMAND_TOGGLE_RENDER_WIRE, "Toggle Wireframe", CommandToggleRenderWire, false); + REGISTER_CMD_C(COMMAND_RENDER_FOCUS, this, TUI::CommandRenderFocus); + REGISTER_CMD_CE(COMMAND_BREAK_LAST_OPERATION, "Break Last Operation", this, TUI::CommandBreakLastOperation, false); + REGISTER_CMD_SE(COMMAND_TOGGLE_SAFE_RECT, "Toggle Safe Rect", CommandToggleSafeRect, false); + REGISTER_CMD_C(COMMAND_RENDER_RESIZE, this, TUI::CommandRenderResize); + REGISTER_CMD_SE(COMMAND_TOGGLE_GRID, "Toggle Grid", CommandToggleGrid, false); + REGISTER_CMD_S(COMMAND_UPDATE_GRID, CommandUpdateGrid); + REGISTER_CMD_S(COMMAND_GRID_NUMBER_OF_SLOTS, CommandGridNumberOfSlots); + REGISTER_SUB_CMD_SE(COMMAND_GRID_SLOT_SIZE, "Change Grid Size", CommandGridSlotSize, false); + APPEND_SUB_CMD("Decrease", 0, 0); + APPEND_SUB_CMD("Increase", 1, 0); + REGISTER_SUB_CMD_END; + REGISTER_CMD_S(COMMAND_CREATE_SOUND_LIB, CommandCreateSoundLib); + REGISTER_CMD_S(COMMAND_MUTE_SOUND, CommandMuteSound); + REGISTER_CMD_S(COMMAND_EDIT_COMMAND_LIST, CommandEditCommandList); + REGISTER_CMD_S(COMMAND_EXECUTE_COMMAND_LIST, CommandExecuteCommandList); + REGISTER_CMD_S(COMMAND_LOG_COMMANDS, CommandLogCommands); + REGISTER_SUB_CMD_SE(COMMAND_RUN_MACRO, "Run Macro", CommandRunMacro, false); + APPEND_SUB_CMD("Slot #1", xr_string(""), 0); + APPEND_SUB_CMD("Slot #2", xr_string(""), 0); + APPEND_SUB_CMD("Slot #3", xr_string(""), 0); + APPEND_SUB_CMD("Slot #4", xr_string(""), 0); + APPEND_SUB_CMD("Slot #5", xr_string(""), 0); + APPEND_SUB_CMD("Slot #6", xr_string(""), 0); + APPEND_SUB_CMD("Slot #7", xr_string(""), 0); + APPEND_SUB_CMD("Slot #8", xr_string(""), 0); + REGISTER_SUB_CMD_END; + REGISTER_CMD_S(COMMAND_ASSIGN_MACRO, CommandAssignMacro); +} + +//--------------------------------------------------------------------------- +bool TUI::ApplyShortCut(DWORD Key, TShiftState Shift) +{ + VERIFY(m_bReady); + + if (ApplyGlobalShortCut(Key, Shift)) + return true; + + if (Key == VK_ESCAPE) + { + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); + return true; + } + + xr_shortcut SC; + SC.key = Key; + SC.ext.assign(u8((Shift & ssShift ? xr_shortcut::flShift : 0) | + (Shift & ssCtrl ? xr_shortcut::flCtrl : 0) | + (Shift & ssAlt ? xr_shortcut::flAlt : 0))); + SESubCommand *SUB = FindCommandByShortcut(SC); + + if (!SUB || SUB->parent->global_shortcut) + return false; + + return ExecCommand(SC); +} +//--------------------------------------------------------------------------- + +bool TUI::ApplyGlobalShortCut(DWORD Key, TShiftState Shift) +{ + VERIFY(m_bReady); + + xr_shortcut SC; + SC.key = Key; + SC.ext.assign(u8((Shift & ssShift ? xr_shortcut::flShift : 0) | + (Shift & ssCtrl ? xr_shortcut::flCtrl : 0) | + (Shift & ssAlt ? xr_shortcut::flAlt : 0))); + + if (UIKeyPressForm::SetResult(SC)) + return true; + if (Key == VK_OEM_3) + { + ExecCommand(COMMAND_RENDER_FOCUS); + return true; + } + + SESubCommand *SUB = FindCommandByShortcut(SC); + + if (!SUB || !SUB->parent->global_shortcut) + return false; + + return ExecCommand(SUB->parent->idx, SUB->p0, SUB->p1); +} +//--------------------------------------------------------------------------- diff --git a/src/editors/xrECore/Editor/UI_MainCommand.h b/src/editors/xrECore/Editor/UI_MainCommand.h new file mode 100644 index 00000000000..851b9d6c7d5 --- /dev/null +++ b/src/editors/xrECore/Editor/UI_MainCommand.h @@ -0,0 +1,189 @@ +#ifndef UI_MainCommandH +#define UI_MainCommandH + +enum +{ + COMMAND_INITIALIZE = 0, // p1 - D3DWindow, p2 - TPanel + COMMAND_DESTROY, + COMMAND_QUIT, + COMMAND_EDITOR_PREF, + COMMAND_CHANGE_ACTION, + COMMAND_IMAGE_EDITOR, + COMMAND_LIGHTANIM_EDITOR, + COMMAND_MINIMAP_EDITOR, + COMMAND_CHECK_TEXTURES, + COMMAND_REFRESH_TEXTURES, + COMMAND_RELOAD_TEXTURES, + COMMAND_CHANGE_AXIS, + COMMAND_CHANGE_SNAP, + COMMAND_SET_SETTINGS, + COMMAND_UNLOAD_TEXTURES, + COMMAND_EVICT_OBJECTS, + COMMAND_EVICT_TEXTURES, + COMMAND_CHECK_MODIFIED, + COMMAND_EXIT, + COMMAND_SHOW_PROPERTIES, + COMMAND_UPDATE_PROPERTIES, // p1 - forced update if needed + COMMAND_REFRESH_PROPERTIES, + COMMAND_MOVE_CAMERA_TO, + COMMAND_ZOOM_EXTENTS, + COMMAND_RENDER_FOCUS, + COMMAND_RENDER_RESIZE, + COMMAND_TOGGLE_RENDER_WIRE, + COMMAND_UPDATE_CAPTION, + COMMAND_BREAK_LAST_OPERATION, + COMMAND_UPDATE_TOOLBAR, + COMMAND_TOGGLE_SAFE_RECT, + COMMAND_TOGGLE_GRID, + COMMAND_UPDATE_GRID, + COMMAND_GRID_NUMBER_OF_SLOTS, + COMMAND_GRID_SLOT_SIZE, + + COMMAND_REFRESH_UI_BAR, + COMMAND_RESTORE_UI_BAR, + COMMAND_SAVE_UI_BAR, + + COMMAND_MUTE_SOUND, + + // имеют разную реализацию + COMMAND_CLEAR, + COMMAND_LOAD, + COMMAND_SAVE, + COMMAND_SAVE_BACKUP, + + COMMAND_CREATE_SOUND_LIB, + COMMAND_TOGGLE_AIMAP_VISIBILITY, + + // sound + COMMAND_SOUND_EDITOR, + COMMAND_SYNC_SOUNDS, + + COMMAND_UNDO, + COMMAND_REDO, + + COMMAND_EDIT_COMMAND_LIST, + COMMAND_EXECUTE_COMMAND_LIST, + COMMAND_LOG_COMMANDS, + COMMAND_RUN_MACRO, // p1 - file name + COMMAND_ASSIGN_MACRO, // p1 - slot, p2 - file_name + + COMMAND_SIMULATE, + COMMAND_USE_SIMULATE_POSITIONS, + + COMMAND_MAIN_LAST +}; +//------------------------------------------------------------------------------ + +class CCommandVar +{ + enum EType + { + tpStr, + tpInt + }; + u32 i; + xr_string s; + EType type; + +public: + CCommandVar() : i(0), type(tpInt) {} + CCommandVar(xr_string str) : type(tpStr) { s = str; } + CCommandVar(u32 val) : type(tpInt) { i = val; } + IC operator u32() + { + VERIFY(type == tpInt); + return i; + } + IC operator xr_string() + { + VERIFY(type == tpStr); + return s; + } + IC bool IsString() { return type == tpStr; } + IC bool IsInteger() { return type == tpInt; } + // IC operator LPCSTR () {VERIFY(type==tpStr);return s.c_str();} +}; + +typedef fastdelegate::FastDelegate2 TECommandEvent; + +struct SECommand; + +struct ECORE_API SESubCommand +{ + SECommand *parent; + xr_string desc; + CCommandVar p0; + CCommandVar p1; + xr_shortcut shortcut; + +public: + SESubCommand(LPCSTR d, SECommand *p, CCommandVar _p0, CCommandVar _p1) + { + desc = d; + parent = p; + p0 = _p0; + p1 = _p1; + } +}; +DEFINE_VECTOR(SESubCommand *, ESubCommandVec, ESubCommandVecIt); +struct ECORE_API SECommand +{ + bool editable; + LPSTR name; + LPSTR desc; + ESubCommandVec sub_commands; + TECommandEvent command; + u32 idx; + bool global_shortcut; + +public: + SECommand(LPCSTR n, LPCSTR d, bool edit, bool multi, TECommandEvent cmd, u32 i, bool _gs) : editable(edit), command(cmd), idx(i), global_shortcut(_gs) + { + name = xr_strdup(n); + desc = xr_strdup(d); + if (!multi) + AppendSubCommand("", u32(0), u32(0)); + } + ~SECommand() + { + xr_free(name); + xr_free(desc); + for (ESubCommandVecIt it = sub_commands.begin(); it != sub_commands.end(); it++) + xr_delete(*it); + } + IC LPCSTR Name() { return name && name[0] ? name : ""; } + IC LPCSTR Desc() { return desc && desc[0] ? desc : ""; } + void AppendSubCommand(LPCSTR desc, CCommandVar p0, CCommandVar p1) { sub_commands.push_back(xr_new(desc, this, p0, p1)); } +}; +DEFINE_VECTOR(SECommand *, ECommandVec, ECommandVecIt); + +ECORE_API CCommandVar ExecCommand(u32 cmd, CCommandVar p1 = u32(0), CCommandVar p2 = u32(0)); +ECORE_API CCommandVar ExecCommand(const xr_shortcut &val); +ECORE_API void RegisterCommand(u32 cmd, SECommand *cmd_impl); +ECORE_API void RegisterSubCommand(SECommand *cmd_impl, LPCSTR desc, CCommandVar p0, CCommandVar p1); +ECORE_API void EnableReceiveCommands(); +ECORE_API ECommandVec &GetEditorCommands(); +ECORE_API SESubCommand *FindCommandByShortcut(const xr_shortcut &val); +ECORE_API BOOL LoadShortcuts(CInifile *ini); +ECORE_API BOOL SaveShortcuts(CInifile *ini); +ECORE_API BOOL AllowLogCommands(); + +#define BIND_CMD_EVENT_S(a) TECommandEvent(a) +#define BIND_CMD_EVENT_C(a, b) TECommandEvent(a, &b) + +#define REGISTER_CMD_S(id, cmd) RegisterCommand(id, xr_new(#id, "", false, false, BIND_CMD_EVENT_S(cmd), id, false)); +#define REGISTER_CMD_C(id, owner, cmd) RegisterCommand(id, xr_new(#id, "", false, false, BIND_CMD_EVENT_C(owner, cmd), id, false)); +#define REGISTER_CMD_SE(id, desc, cmd, gs) RegisterCommand(id, xr_new(#id, desc, true, false, BIND_CMD_EVENT_S(cmd), id, gs)); +#define REGISTER_CMD_CE(id, desc, owner, cmd, gs) RegisterCommand(id, xr_new(#id, desc, true, false, BIND_CMD_EVENT_C(owner, cmd), id, gs)); +#define REGISTER_SUB_CMD_SE(id, desc, cmd, gs) \ + { \ + SECommand *SUB_CMD_HOLDER; \ + RegisterCommand(id, SUB_CMD_HOLDER = xr_new(#id, desc, true, true, BIND_CMD_EVENT_S(cmd), id, gs)); +#define REGISTER_SUB_CMD_CE(id, desc, owner, cmd, gs) \ + { \ + SECommand *SUB_CMD_HOLDER; \ + RegisterCommand(id, SUB_CMD_HOLDER = xr_new(#id, desc, true, true, BIND_CMD_EVENT_C(owner, cmd), id, gs)); +#define APPEND_SUB_CMD(desc, p0, p1) RegisterSubCommand(SUB_CMD_HOLDER, desc, p0, p1); +#define REGISTER_SUB_CMD_END } + +#endif // UI_MainCommandH diff --git a/src/editors/xrECore/Editor/UI_MainMail.cpp b/src/editors/xrECore/Editor/UI_MainMail.cpp new file mode 100644 index 00000000000..119a26f34ab --- /dev/null +++ b/src/editors/xrECore/Editor/UI_MainMail.cpp @@ -0,0 +1,127 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +//--------------------------------------------------------------------------- +#if 0 +bool TUI::CreateMailslot() +{ + xr_string slot_name = xr_string("\\\\.\\mailslot\\")+xr_string(UI->EditorName()); + hMailSlot = ::CreateMailslot(slot_name.c_str(), + 0, // no maximum message size + MAILSLOT_WAIT_FOREVER, // no time-out for operations + (LPSECURITY_ATTRIBUTES) NULL); // no security attributes + return (hMailSlot != INVALID_HANDLE_VALUE); +} +//--------------------------------------------------------------------------- + +void TUI::CheckMailslot() +{ + DWORD cbMessage, cMessage, cbRead; + BOOL fResult; + LPSTR lpszBuffer; + + cbMessage = cMessage = cbRead = 0; + fResult = GetMailslotInfo(hMailSlot, // mailslot handle + (LPDWORD) NULL, // no maximum message size + &cbMessage, // size of next message + &cMessage, // number of messages + (LPDWORD) NULL); // no read time-out + R_ASSERT2(fResult,"Can't get mailslot info"); + if (cbMessage == MAILSLOT_NO_MESSAGE) return; + while (cMessage != 0) // retrieve all messages + { + // Allocate memory for the message. + lpszBuffer = (LPSTR) GlobalAlloc(GPTR, cbMessage); + lpszBuffer[0] = '\0'; + fResult = ReadFile(hMailSlot, lpszBuffer, cbMessage, &cbRead, (LPOVERLAPPED) NULL); + if (!fResult) { + GlobalFree((HGLOBAL) lpszBuffer); + R_ASSERT(0); + //throw Exception("Can't ReadFile"); + } + OnReceiveMail(lpszBuffer); + GlobalFree((HGLOBAL) lpszBuffer); + fResult = GetMailslotInfo(hMailSlot, // mailslot handle + (LPDWORD) NULL, // no maximum message size + &cbMessage, // size of next message + &cMessage, // number of messages + (LPDWORD) NULL); // no read time-out + R_ASSERT2(fResult,"Can't get mailslot info"); + } +} +//--------------------------------------------------------------------------- + +void TUI::OnReceiveMail(LPCSTR msg) +{ + int cnt = _GetItemCount(msg,' '); + if (cnt){ + xr_string M = xr_string(msg); + for (char& ch : M) + { + ch = tolower(ch); + } + xr_string name = UI->EditorName(); + for (char& ch : name) + { + ch = toupper(ch); + } + xr_string p[2]; + _GetItem(msg,0,p[0],' ',"",false); + if (cnt>1) _GetItems(msg,1,cnt,( char*)p[1].c_str(),' '); + if (p[0]=="exit") + { + ELog.DlgMsg(mtInformation,"'%s EDITOR': Critical update!", name.c_str()); + while (1){ + if (ExecCommand(COMMAND_EXIT)){ + ExecCommand(COMMAND_QUIT); + break; + } + } + }else if (p[0]=="quit") + { + ELog.Msg(mtInformation,"'%s EDITOR': Super critical update!", name.c_str()); + ExecCommand(COMMAND_SAVE_BACKUP); + ExecCommand(COMMAND_QUIT); + } + else if (p[0]=="info") + { + if (cnt>1) ELog.DlgMsg(mtInformation,"'%s EDITOR': %s", name.c_str(),p[1].c_str()); + }else if (p[0]=="error") + { + if (cnt>1) ELog.DlgMsg(mtError,"'%s EDITOR': %s", name.c_str(),p[1].c_str()); + } + } +} +//--------------------------------------------------------------------------- + +void TUI::SendMail(LPCSTR name, LPCSTR dest, LPCSTR msg) +{ + HANDLE hFile; + DWORD cbWritten; + BOOL fResult; + char cName[256]; + + sprintf(cName,"\\\\%s\\mailslot\\%s",name,dest); + hFile = CreateFile( + cName, + GENERIC_WRITE, + FILE_SHARE_READ, // required to write to a mailslot + (LPSECURITY_ATTRIBUTES) NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + (HANDLE) NULL); + if (hFile == INVALID_HANDLE_VALUE) return; + fResult = WriteFile( + hFile, + msg, + (u32) lstrlen(msg) + 1, + &cbWritten, + (LPOVERLAPPED) NULL); + if (!fResult) return; + fResult = CloseHandle(hFile); + if (!fResult) return; +} +//--------------------------------------------------------------------------- + +#endif \ No newline at end of file diff --git a/src/editors/xrECore/Editor/UI_ToolsCustom.cpp b/src/editors/xrECore/Editor/UI_ToolsCustom.cpp new file mode 100644 index 00000000000..dd743c30b76 --- /dev/null +++ b/src/editors/xrECore/Editor/UI_ToolsCustom.cpp @@ -0,0 +1,403 @@ +//--------------------------------------------------------------------------- + +#include "stdafx.h" +#pragma hdrstop + +#include "UI_ToolsCustom.h" +#include "EditObject.h" +#include "EditMesh.h" +#include "ui_main.h" +#include "library.h" +#include "d3dutils.h" + +//------------------------------------------------------------------------------ +CToolCustom *Tools = 0; +//------------------------------------------------------------------------------ +#define CHECK_SNAP(R, A, C) \ + { \ + R += A; \ + if (fabsf(R) >= C) \ + { \ + A = snapto(R, C); \ + R = 0; \ + } \ + else \ + { \ + A = 0; \ + } \ + } + +CToolCustom::CToolCustom() +{ + m_bReady = false; + m_Action = etaSelect; + m_Settings.assign(etfNormalAlign | etfGSnap | etfOSnap | etfMTSnap | etfVSnap | etfASnap | etfMSnap); + m_Axis = etAxisZX; + fFogness = 0.9f; + dwFogColor = 0xffffffff; + m_pAxisMoveObject = NULL; + m_axis_xform = Fidentity; +} +//--------------------------------------------------------------------------- + +CToolCustom::~CToolCustom() +{ +} +//--------------------------------------------------------------------------- + +bool CToolCustom::OnCreate() +{ + m_bReady = true; + + SetAction(etaSelect); + + return true; +} + +void CToolCustom::OnDestroy() +{ + Lib.RemoveEditObject(m_pAxisMoveObject); + VERIFY(m_bReady); + m_bReady = false; +} +//--------------------------------------------------------------------------- + +void CToolCustom::SetAction(ETAction action) +{ + switch (action) + { + case etaSelect: + m_bHiddenMode = false; + break; + case etaAdd: + case etaMove: + case etaRotate: + case etaScale: + m_bHiddenMode = true; + break; + } + m_Action = action; + /* switch(m_Action) + { + case etaSelect: + UI->GetD3DWindow()->Cursor = crCross; + break; + case etaAdd: + UI->GetD3DWindow()->Cursor = crArrow; + break; + case etaMove: + if(!EPrefs->tools_show_move_axis) + UI->GetD3DWindow()->Cursor = crSizeAll; + else + UI->GetD3DWindow()->Cursor = crHandPoint; + + break; + case etaRotate: + UI->GetD3DWindow()->Cursor = crSizeWE; + break; + case etaScale: + UI->GetD3DWindow()->Cursor = crVSplit; + break; + default: + UI->GetD3DWindow()->Cursor = crHelp; + }*/ + + if (m_Action == etaMove) + { + if (!m_pAxisMoveObject && EPrefs->tools_show_move_axis) + { + m_pAxisMoveObject = Lib.CreateEditObject("editor\\axis"); + m_Axis = etAxisUndefined; + } + } + else + { + if (m_pAxisMoveObject) + Lib.RemoveEditObject(m_pAxisMoveObject); + } + UI->RedrawScene(); + ExecCommand(COMMAND_REFRESH_UI_BAR); +} + +void CToolCustom::SetAxis(ETAxis axis) +{ + m_Axis = axis; + UI->RedrawScene(); + ExecCommand(COMMAND_REFRESH_UI_BAR); +} + +void CToolCustom::SetSettings(u32 mask, BOOL val) +{ + m_Settings.set(mask, val); + UI->RedrawScene(); + ExecCommand(COMMAND_REFRESH_UI_BAR); +} + +bool CToolCustom::MouseStart(TShiftState Shift) +{ + switch (m_Action) + { + case etaSelect: + break; + case etaAdd: + break; + case etaMove: + if (etAxisY == m_Axis) + { + m_MoveXVector.set(0, 0, 0); + m_MoveYVector.set(0, 1, 0); + } + else + { + m_MoveXVector.set(EDevice.m_Camera.GetRight()); + m_MoveXVector.y = 0; + m_MoveYVector.set(EDevice.m_Camera.GetDirection()); + m_MoveYVector.y = 0; + m_MoveXVector.normalize_safe(); + m_MoveYVector.normalize_safe(); + } + m_MoveReminder.set(0, 0, 0); + m_MovedAmount.set(0, 0, 0); + break; + case etaRotate: + m_RotateCenter.set(0, 0, 0); + m_RotateVector.set(0, 0, 0); + if (etAxisX == m_Axis) + m_RotateVector.set(1, 0, 0); + else if (etAxisY == m_Axis) + m_RotateVector.set(0, 1, 0); + else if (etAxisZ == m_Axis) + m_RotateVector.set(0, 0, 1); + m_fRotateSnapValue = 0; + m_RotateAmount = 0; + break; + case etaScale: + m_ScaleAmount.set(0, 0, 0); + break; + } + + if (m_Action == etaMove && m_pAxisMoveObject) + { + Fmatrix inv_parent; + inv_parent.invert(m_axis_xform); + Fvector start_point, start_dir; + float dist; + SRayPickInfo pinfo; + + start_point = UI->m_CurrentRStart; + start_dir = UI->m_CurrentRDir; + dist = 10000; + m_pAxisMoveObject->RayPick(dist, start_point, start_dir, inv_parent, &pinfo); + if (pinfo.e_mesh) + { + LPCSTR mn = pinfo.e_mesh->Name().c_str(); + if (0 == stricmp(mn, "axis_x")) + SetAxis(etAxisX); + else if (0 == stricmp(mn, "axis_y")) + SetAxis(etAxisY); + else if (0 == stricmp(mn, "axis_z")) + SetAxis(etAxisZ); + else if (0 == stricmp(mn, "center")) + SetAxis(etAxisZX); + else + R_ASSERT2(0, "fix axis name"); + }; + } + + return m_bHiddenMode; +} + +bool CToolCustom::MouseEnd(TShiftState Shift) +{ + switch (m_Action) + { + case etaSelect: + break; + case etaAdd: + break; + case etaMove: + if (EPrefs->tools_show_move_axis) + m_Axis = etAxisUndefined; + break; + case etaRotate: + break; + case etaScale: + break; + } + return true; +} + +void CToolCustom::MouseMove(TShiftState Shift) +{ + switch (m_Action) + { + case etaSelect: + break; + case etaAdd: + break; + case etaMove: + { + m_MovedAmount.mul(m_MoveXVector, UI->m_MouseSM * UI->m_DeltaCpH.x); + m_MovedAmount.mad(m_MoveYVector, -UI->m_MouseSM * UI->m_DeltaCpH.y); + + if (m_Settings.is(etfMSnap)) + { + CHECK_SNAP(m_MoveReminder.x, m_MovedAmount.x, m_MoveSnap); + CHECK_SNAP(m_MoveReminder.y, m_MovedAmount.y, m_MoveSnap); + CHECK_SNAP(m_MoveReminder.z, m_MovedAmount.z, m_MoveSnap); + } + + if (!(etAxisX == m_Axis) && !(etAxisZX == m_Axis)) + m_MovedAmount.x = 0.f; + if (!(etAxisZ == m_Axis) && !(etAxisZX == m_Axis)) + m_MovedAmount.z = 0.f; + if (!(etAxisY == m_Axis)) + m_MovedAmount.y = 0.f; + } + break; + case etaRotate: + { + m_RotateAmount = -UI->m_DeltaCpH.x * UI->m_MouseSR; + if (m_Settings.is(etfASnap)) + CHECK_SNAP(m_fRotateSnapValue, m_RotateAmount, m_RotateSnapAngle); + } + break; + case etaScale: + { + float dy = UI->m_DeltaCpH.x * UI->m_MouseSS; + if (dy > 1.f) + dy = 1.f; + else if (dy < -1.f) + dy = -1.f; + + m_ScaleAmount.set(dy, dy, dy); + + if (m_Settings.is(etfNUScale)) + { + if (!(etAxisX == m_Axis) && !(etAxisZX == m_Axis)) + m_ScaleAmount.x = 0.f; + if (!(etAxisZ == m_Axis) && !(etAxisZX == m_Axis)) + m_ScaleAmount.z = 0.f; + if (!(etAxisY == m_Axis)) + m_ScaleAmount.y = 0.f; + } + } + break; + } +} + +void CToolCustom::GetCurrentFog(u32 &fog_color, float &s_fog, float &e_fog) +{ + s_fog = psDeviceFlags.is(rsFog) ? (1.0f - fFogness) * 0.85f * UI->ZFar() : 0.99f * UI->ZFar(); + e_fog = psDeviceFlags.is(rsFog) ? 0.91f * UI->ZFar() : UI->ZFar(); + fog_color = dwFogColor; +} + +void CToolCustom::RenderEnvironment() +{ +} + +void CToolCustom::Clear() +{ + ClearDebugDraw(); +} + +void CToolCustom::Render() +{ + // render errors + EDevice.SetShader(EDevice.m_SelectionShader); + RCache.set_xform_world(Fidentity); + EDevice.RenderNearer(0.0003f); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_NONE); + xr_string temp; + int cnt = 0; + for (SDebugDraw::PointIt vit = m_DebugDraw.m_Points.begin(); vit != m_DebugDraw.m_Points.end(); ++vit) + { + LPCSTR s = NULL; + if (vit->i) + { + temp = make_string("P: %d", cnt++); + s = temp.c_str(); + } + + if (vit->descr.size()) + { + s = vit->descr.c_str(); + } + DU_impl.dbgDrawVert(vit->p[0], vit->c, s ? s : ""); + } + EDevice.SetShader(EDevice.m_SelectionShader); + cnt = 0; + for (SDebugDraw::LineIt eit = m_DebugDraw.m_Lines.begin(); eit != m_DebugDraw.m_Lines.end(); eit++) + { + if (eit->i) + temp = make_string("L: %d", cnt++); + DU_impl.dbgDrawEdge(eit->p[0], eit->p[1], eit->c, eit->i ? temp.c_str() : ""); + } + EDevice.SetShader(EDevice.m_SelectionShader); + cnt = 0; + for (SDebugDraw::FaceIt fwit = m_DebugDraw.m_WireFaces.begin(); fwit != m_DebugDraw.m_WireFaces.end(); fwit++) + { + if (fwit->i) + temp = make_string("F: %d", cnt++); + DU_impl.dbgDrawFace(fwit->p[0], fwit->p[1], fwit->p[2], fwit->c, fwit->i ? temp.c_str() : ""); + } + cnt = 0; + if (!m_DebugDraw.m_SolidFaces.empty()) + { + EDevice.SetShader(EDevice.m_SelectionShader); + DU_impl.DD_DrawFace_begin(FALSE); + for (SDebugDraw::FaceIt fsit = m_DebugDraw.m_SolidFaces.begin(); fsit != m_DebugDraw.m_SolidFaces.end(); fsit++) + DU_impl.DD_DrawFace_push(fsit->p[0], fsit->p[1], fsit->p[2], fsit->c); + DU_impl.DD_DrawFace_end(); + } + EDevice.SetShader(EDevice.m_SelectionShader); + cnt = 0; + for (SDebugDraw::OBBVecIt oit = m_DebugDraw.m_OBB.begin(); oit != m_DebugDraw.m_OBB.end(); oit++) + { + temp = make_string("OBB: %d", cnt++); + DU_impl.DrawOBB(Fidentity, *oit, 0x2F00FF00, 0xFF00FF00); + DU_impl.OutText(oit->m_translate, temp.c_str(), 0xffff0000, 0x0000000); + } + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_CCW); + EDevice.ResetNearer(); + + if (m_pAxisMoveObject && GetSelectionPosition(m_axis_xform)) + { + for (SurfaceIt s_it = m_pAxisMoveObject->Surfaces().begin(); s_it != m_pAxisMoveObject->Surfaces().end(); ++s_it) + { + EDevice.SetShader((*s_it)->_Shader()); + RCache.set_xform_world(m_axis_xform); + + for (int idx = 0; idx < m_pAxisMoveObject->Meshes().size(); ++idx) + { + CEditableMesh *M = m_pAxisMoveObject->Meshes()[idx]; + if ((m_Axis == idx) || + (idx == etAxisZX) || + (m_Axis == etAxisZX && (idx == etAxisX || idx == etAxisZ)) || + (m_Axis == etAxisUndefined)) + M->Render(m_axis_xform, *s_it); + } + } + } + + if (m_pAxisMoveObject && GetSelectionPosition(m_axis_xform)) + { + for (SurfaceIt s_it = m_pAxisMoveObject->Surfaces().begin(); s_it != m_pAxisMoveObject->Surfaces().end(); ++s_it) + { + EDevice.SetShader((*s_it)->_Shader()); + RCache.set_xform_world(m_axis_xform); + + for (int idx = 0; idx < m_pAxisMoveObject->Meshes().size(); ++idx) + { + CEditableMesh *M = m_pAxisMoveObject->Meshes()[idx]; + if ((m_Axis == idx) || + (idx == etAxisZX) || + (m_Axis == etAxisZX && (idx == etAxisX || idx == etAxisZ)) || + (m_Axis == etAxisUndefined)) + M->Render(m_axis_xform, *s_it); + } + } + } +} +//------------------------------------------------------------------------------ diff --git a/src/editors/xrECore/Editor/UI_ToolsCustom.h b/src/editors/xrECore/Editor/UI_ToolsCustom.h new file mode 100644 index 00000000000..af241a7e76b --- /dev/null +++ b/src/editors/xrECore/Editor/UI_ToolsCustom.h @@ -0,0 +1,251 @@ +//--------------------------------------------------------------------------- +#ifndef UI_ToolsCustomH +#define UI_ToolsCustomH + +#include "EditObject.h" + +// refs +class UIPropertiesForm; +class CEditableObject; +class PropValue; +class TfrmKeyBar; +class CBlend; + +enum ETAction +{ + etaSelect = 0, + etaAdd, + etaMove, + etaRotate, + etaScale, + etaMaxActions +}; + +enum ETAxis +{ + etAxisY, + etAxisX, + etAxisZ, + etAxisZX, + etAxisUndefined, +}; + +enum ETFlags +{ + etfCSParent = (1 << 0), + etfNUScale = (1 << 1), + etfNormalAlign = (1 << 2), + etfGSnap = (1 << 3), + etfOSnap = (1 << 4), + etfMTSnap = (1 << 5), + etfVSnap = (1 << 6), + etfASnap = (1 << 7), + etfMSnap = (1 << 8), +}; + +class ECORE_API CToolCustom +{ + friend class CCustomPreferences; + +protected: + bool m_bReady; + + ETAction m_Action; + ETAxis m_Axis; + Flags32 m_Settings; + + bool m_bHiddenMode; + // move + Fvector m_MoveXVector; + Fvector m_MoveYVector; + Fvector m_MoveReminder; + Fvector m_MovedAmount; + // scale + Fvector m_ScaleCenter; + Fvector m_ScaleAmount; + // rotate + Fvector m_RotateCenter; + Fvector m_RotateVector; + float m_fRotateSnapValue; + float m_RotateAmount; + +public: + float m_MoveSnap; + float m_MoveSnapTo; + float m_RotateSnapAngle; + +public: + float fFogness; + u32 dwFogColor; + +public: + xr_string m_LastFileName; + +public: + struct SDebugDraw + { + struct Face + { + Fvector p[3]; + u32 c; + bool i; + bool m; + }; + struct Line + { + Fvector p[2]; + u32 c; + bool i; + bool m; + }; + struct Point + { + Fvector p[1]; + u32 c; + bool i; + bool m; + xr_string descr; + }; + DEFINE_VECTOR(Face, FaceVec, FaceIt); + DEFINE_VECTOR(Line, LineVec, LineIt); + DEFINE_VECTOR(Point, PointVec, PointIt); + DEFINE_VECTOR(Fobb, OBBVec, OBBVecIt); + FaceVec m_WireFaces; + FaceVec m_SolidFaces; + LineVec m_Lines; + PointVec m_Points; + OBBVec m_OBB; + void Clear() + { + m_WireFaces.clear(); + m_SolidFaces.clear(); + m_Lines.clear(); + m_Points.clear(); + m_OBB.clear(); + } + void AppendPoint(const Fvector &p0, u32 c = 0xff0000ff, bool i = true, bool m = true, LPCSTR descr = NULL) + { + m_Points.push_back(Point()); + m_Points.back().p[0].set(p0); + m_Points.back().c = c; + m_Points.back().i = i; + m_Points.back().m = m; + if (descr) + m_Points.back().descr = descr; + } + void AppendLine(const Fvector &p0, const Fvector &p1, u32 c = 0xff00ff00, bool i = true, bool m = true) + { + m_Lines.push_back(Line()); + m_Lines.back().p[0].set(p0); + m_Lines.back().p[1].set(p1); + m_Lines.back().c = c; + m_Lines.back().i = i; + m_Lines.back().m = m; + } + void AppendWireFace(const Fvector &p0, const Fvector &p1, const Fvector &p2, u32 c = 0xffff0000, bool i = true, bool m = true) + { + m_WireFaces.push_back(Face()); + m_WireFaces.back().p[0].set(p0); + m_WireFaces.back().p[1].set(p1); + m_WireFaces.back().p[2].set(p2); + m_WireFaces.back().c = c; + m_WireFaces.back().i = i; + m_WireFaces.back().m = m; + } + void AppendSolidFace(const Fvector &p0, const Fvector &p1, const Fvector &p2, u32 c = 0xffff0000, bool i = true, bool m = true) + { + m_SolidFaces.push_back(Face()); + m_SolidFaces.back().p[0].set(p0); + m_SolidFaces.back().p[1].set(p1); + m_SolidFaces.back().p[2].set(p2); + m_SolidFaces.back().c = c; + m_SolidFaces.back().i = i; + m_SolidFaces.back().m = m; + } + void AppendOBB(const Fobb &obb) + { + m_OBB.push_back(obb); + } + }; + SDebugDraw m_DebugDraw; + +public: + void ClearDebugDraw() { m_DebugDraw.Clear(); } + +public: + CToolCustom(); + virtual ~CToolCustom(); + + ETAction GetAction() { return m_Action; } + ETAxis GetAxis() { return m_Axis; } + BOOL GetSettings(u32 mask) { return m_Settings.is(mask); } + virtual void SetAction(ETAction act); + virtual void SetAxis(ETAxis axis); + virtual void SetSettings(u32 mask, BOOL val); + + virtual void Simulate(){}; + virtual void UseSimulatePositions(){}; + + virtual void SetFog(u32 fog_color, float fogness) + { + dwFogColor = fog_color; + fFogness = fogness; + } + virtual void GetCurrentFog(u32 &fog_color, float &s_fog, float &e_fog); + + virtual void Render() = 0; + virtual void RenderEnvironment() = 0; + virtual void OnFrame() = 0; + + virtual bool OnCreate() = 0; + virtual void OnDestroy() = 0; + + virtual bool IfModified() = 0; + virtual bool IsModified() = 0; + virtual void Modified() = 0; + + virtual LPCSTR GetInfo() = 0; + + virtual void ZoomObject(BOOL bSelOnly) = 0; + + virtual bool Load(LPCSTR name) = 0; + virtual bool Save(LPCSTR name, bool bInternal = false) = 0; + virtual void Reload() = 0; + + virtual void OnDeviceCreate() = 0; + virtual void OnDeviceDestroy() = 0; + + virtual void Clear() = 0; + + virtual void OnShowHint(AStringVec &SS) = 0; + + virtual bool MouseStart(TShiftState Shift) = 0; + virtual bool MouseEnd(TShiftState Shift) = 0; + virtual void MouseMove(TShiftState Shift) = 0; + virtual bool HiddenMode() { return m_bHiddenMode; } + virtual bool KeyDown(WORD Key, TShiftState Shift) { return false; } + virtual bool KeyUp(WORD Key, TShiftState Shift) { return false; } + virtual bool KeyPress(WORD Key, TShiftState Shift) { return false; } + + virtual bool Pick(TShiftState Shift) = 0; + virtual bool RayPick(const Fvector &start, const Fvector &dir, float &dist, Fvector *pt = 0, Fvector *n = 0) = 0; + + virtual void ShowProperties(LPCSTR focused_item) = 0; + virtual void UpdateProperties(BOOL bForced = FALSE) = 0; + virtual void RefreshProperties() = 0; + + const xr_string &GetEditFileName() { return m_LastFileName; } + + CEditableObject *m_pAxisMoveObject; + Fmatrix m_axis_xform; + + virtual bool GetSelectionPosition(Fmatrix &result) = 0; +}; +extern ECORE_API CToolCustom *Tools; + +#define SURFACES_PREFIX "Surfaces" +#define BONES_PREFIX "Bones" +#define MOTIONS_PREFIX "Motions" +#define OBJECT_PREFIX "Object" +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/xrECore/Editor/bone.cpp b/src/editors/xrECore/Editor/bone.cpp new file mode 100644 index 00000000000..77b472f8d47 --- /dev/null +++ b/src/editors/xrECore/Editor/bone.cpp @@ -0,0 +1,215 @@ +#include "stdafx.h" +#include "xrCore/Animation/Bone.hpp" +// +//#define BONE_VERSION 0x0002 +// +//#define BONE_CHUNK_VERSION 0x0001 +//#define BONE_CHUNK_DEF 0x0002 +//#define BONE_CHUNK_BIND_POSE 0x0003 +//#define BONE_CHUNK_MATERIAL 0x0004 +//#define BONE_CHUNK_SHAPE 0x0005 +//#define BONE_CHUNK_IK_JOINT 0x0006 +//#define BONE_CHUNK_MASS 0x0007 +//#define BONE_CHUNK_FLAGS 0x0008 +//#define BONE_CHUNK_IK_JOINT_BREAK 0x0009 +//#define BONE_CHUNK_IK_JOINT_FRICTION 0x0010 +// +//u16 CBone::get_game_mtl_idx() const +//{ +// return -1; +// // return GMLib.GetMaterialIdx(game_mtl.c_str()); +//} +// +//static const Fobb dummy = Fobb().identity(); +//const Fobb &CBone::get_obb() const +//{ +// return dummy; +//} +//const IBoneData &CBoneData::GetChild(u16 id) const +//{ +// return *children[id]; +//} +//IBoneData &CBoneData::GetChild(u16 id) +//{ +// return *children[id]; +//} +// +//u16 CBoneData::GetNumChildren() const +//{ +// return (u16)children.size(); +//} +// +//CBone::CBone() +//{ +// construct(); +// flags.zero(); +// rest_length = 0; +// SelfID = -1; +// parent = 0; +// +// ResetData(); +//} +// +//CBone::~CBone() +//{ +//} +// +//void CBone::ResetData() +//{ +// IK_data.Reset(); +// game_mtl = "default_object"; +// shape.Reset(); +// +// mass = 10.f; +// ; +// center_of_mass.set(0.f, 0.f, 0.f); +//} +// +//void CBone::Save(IWriter &F) +//{ +// F.open_chunk(BONE_CHUNK_VERSION); +// F.w_u16(BONE_VERSION); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_DEF); +// F.w_stringZ(name); +// F.w_stringZ(parent_name); +// F.w_stringZ(wmap); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_BIND_POSE); +// F.w_fvector3(rest_offset); +// F.w_fvector3(rest_rotate); +// F.w_float(rest_length); +// F.close_chunk(); +// +// SaveData(F); +//} +// +//void CBone::Load_0(IReader &F) +//{ +// F.r_stringZ(name); +// xr_strlwr(name); +// F.r_stringZ(parent_name); +// xr_strlwr(parent_name); +// F.r_stringZ(wmap); +// F.r_fvector3(rest_offset); +// F.r_fvector3(rest_rotate); +// rest_length = F.r_float(); +// std::swap(rest_rotate.x, rest_rotate.y); +// Reset(); +//} +// +//void CBone::Load_1(IReader &F) +//{ +// R_ASSERT(F.find_chunk(BONE_CHUNK_VERSION)); +// u16 ver = F.r_u16(); +// +// if ((ver != 0x0001) && (ver != BONE_VERSION)) +// return; +// +// R_ASSERT(F.find_chunk(BONE_CHUNK_DEF)); +// F.r_stringZ(name); +// xr_strlwr(name); +// F.r_stringZ(parent_name); +// xr_strlwr(parent_name); +// F.r_stringZ(wmap); +// +// R_ASSERT(F.find_chunk(BONE_CHUNK_BIND_POSE)); +// F.r_fvector3(rest_offset); +// F.r_fvector3(rest_rotate); +// rest_length = F.r_float(); +// +// if (ver == 0x0001) +// std::swap(rest_rotate.x, rest_rotate.y); +// +// LoadData(F); +//} +// +//void CBone::SaveData(IWriter &F) +//{ +// F.open_chunk(BONE_CHUNK_DEF); +// F.w_stringZ(name); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_MATERIAL); +// F.w_stringZ(game_mtl); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_SHAPE); +// F.w(&shape, sizeof(SBoneShape)); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_FLAGS); +// F.w_u32(IK_data.ik_flags.get()); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_IK_JOINT); +// F.w_u32(IK_data.type); +// F.w(IK_data.limits, sizeof(SJointLimit) * 3); +// F.w_float(IK_data.spring_factor); +// F.w_float(IK_data.damping_factor); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_IK_JOINT_BREAK); +// F.w_float(IK_data.break_force); +// F.w_float(IK_data.break_torque); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_IK_JOINT_FRICTION); +// F.w_float(IK_data.friction); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_MASS); +// F.w_float(mass); +// F.w_fvector3(center_of_mass); +// F.close_chunk(); +//} +// +//void CBone::LoadData(IReader &F) +//{ +// R_ASSERT(F.find_chunk(BONE_CHUNK_DEF)); +// F.r_stringZ(name); +// xr_strlwr(name); +// +// R_ASSERT(F.find_chunk(BONE_CHUNK_MATERIAL)); +// F.r_stringZ(game_mtl); +// +// R_ASSERT(F.find_chunk(BONE_CHUNK_SHAPE)); +// F.r(&shape, sizeof(SBoneShape)); +// +// if (F.find_chunk(BONE_CHUNK_FLAGS)) +// IK_data.ik_flags.assign(F.r_u32()); +// +// R_ASSERT(F.find_chunk(BONE_CHUNK_IK_JOINT)); +// IK_data.type = (EJointType)F.r_u32(); +// F.r(IK_data.limits, sizeof(SJointLimit) * 3); +// IK_data.spring_factor = F.r_float(); +// IK_data.damping_factor = F.r_float(); +// +// if (F.find_chunk(BONE_CHUNK_IK_JOINT_BREAK)) +// { +// IK_data.break_force = F.r_float(); +// IK_data.break_torque = F.r_float(); +// } +// +// if (F.find_chunk(BONE_CHUNK_IK_JOINT_FRICTION)) +// { +// IK_data.friction = F.r_float(); +// } +// +// if (F.find_chunk(BONE_CHUNK_MASS)) +// { +// mass = F.r_float(); +// F.r_fvector3(center_of_mass); +// } +//} +// +//void CBone::CopyData(CBone *bone) +//{ +// game_mtl = bone->game_mtl; +// shape = bone->shape; +// IK_data = bone->IK_data; +// mass = bone->mass; +// center_of_mass = bone->center_of_mass; +//} diff --git a/src/editors/xrECore/Editor/c_dinput.cpp b/src/editors/xrECore/Editor/c_dinput.cpp new file mode 100644 index 00000000000..8da87c7b158 --- /dev/null +++ b/src/editors/xrECore/Editor/c_dinput.cpp @@ -0,0 +1,544 @@ +/* + The "c_dfDI..." global instances of the DirectInput + DIDATAFORMAT structure for users of Borland compilers. + Author: Michael Fцtsch + + Visit my site: http://www.geocities.com/foetsch + Contact me: foetsch@crosswinds.net +*/ +#include "stdafx.h" +#pragma hdrstop + +//#pragma comment(lib, "dinput8.lib") + +//static DIOBJECTDATAFORMAT rgodfDIKeyboard[] = { +// {&GUID_Key, 0, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(0) | 0x80000000, 0}, +// {&GUID_Key, 1, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(1) | 0x80000000, 0}, +// {&GUID_Key, 2, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(2) | 0x80000000, 0}, +// {&GUID_Key, 3, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(3) | 0x80000000, 0}, +// {&GUID_Key, 4, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(4) | 0x80000000, 0}, +// {&GUID_Key, 5, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(5) | 0x80000000, 0}, +// {&GUID_Key, 6, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(6) | 0x80000000, 0}, +// {&GUID_Key, 7, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(7) | 0x80000000, 0}, +// {&GUID_Key, 8, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(8) | 0x80000000, 0}, +// {&GUID_Key, 9, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(9) | 0x80000000, 0}, +// {&GUID_Key, 10, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(10) | 0x80000000, 0}, +// {&GUID_Key, 11, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(11) | 0x80000000, 0}, +// {&GUID_Key, 12, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(12) | 0x80000000, 0}, +// {&GUID_Key, 13, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(13) | 0x80000000, 0}, +// {&GUID_Key, 14, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(14) | 0x80000000, 0}, +// {&GUID_Key, 15, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(15) | 0x80000000, 0}, +// {&GUID_Key, 16, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(16) | 0x80000000, 0}, +// {&GUID_Key, 17, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(17) | 0x80000000, 0}, +// {&GUID_Key, 18, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(18) | 0x80000000, 0}, +// {&GUID_Key, 19, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(19) | 0x80000000, 0}, +// {&GUID_Key, 20, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(20) | 0x80000000, 0}, +// {&GUID_Key, 21, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(21) | 0x80000000, 0}, +// {&GUID_Key, 22, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(22) | 0x80000000, 0}, +// {&GUID_Key, 23, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(23) | 0x80000000, 0}, +// {&GUID_Key, 24, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(24) | 0x80000000, 0}, +// {&GUID_Key, 25, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(25) | 0x80000000, 0}, +// {&GUID_Key, 26, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(26) | 0x80000000, 0}, +// {&GUID_Key, 27, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(27) | 0x80000000, 0}, +// {&GUID_Key, 28, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(28) | 0x80000000, 0}, +// {&GUID_Key, 29, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(29) | 0x80000000, 0}, +// {&GUID_Key, 30, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(30) | 0x80000000, 0}, +// {&GUID_Key, 31, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(31) | 0x80000000, 0}, +// {&GUID_Key, 32, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(32) | 0x80000000, 0}, +// {&GUID_Key, 33, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(33) | 0x80000000, 0}, +// {&GUID_Key, 34, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(34) | 0x80000000, 0}, +// {&GUID_Key, 35, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(35) | 0x80000000, 0}, +// {&GUID_Key, 36, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(36) | 0x80000000, 0}, +// {&GUID_Key, 37, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(37) | 0x80000000, 0}, +// {&GUID_Key, 38, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(38) | 0x80000000, 0}, +// {&GUID_Key, 39, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(39) | 0x80000000, 0}, +// {&GUID_Key, 40, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(40) | 0x80000000, 0}, +// {&GUID_Key, 41, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(41) | 0x80000000, 0}, +// {&GUID_Key, 42, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(42) | 0x80000000, 0}, +// {&GUID_Key, 43, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(43) | 0x80000000, 0}, +// {&GUID_Key, 44, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(44) | 0x80000000, 0}, +// {&GUID_Key, 45, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(45) | 0x80000000, 0}, +// {&GUID_Key, 46, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(46) | 0x80000000, 0}, +// {&GUID_Key, 47, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(47) | 0x80000000, 0}, +// {&GUID_Key, 48, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(48) | 0x80000000, 0}, +// {&GUID_Key, 49, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(49) | 0x80000000, 0}, +// {&GUID_Key, 50, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(50) | 0x80000000, 0}, +// {&GUID_Key, 51, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(51) | 0x80000000, 0}, +// {&GUID_Key, 52, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(52) | 0x80000000, 0}, +// {&GUID_Key, 53, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(53) | 0x80000000, 0}, +// {&GUID_Key, 54, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(54) | 0x80000000, 0}, +// {&GUID_Key, 55, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(55) | 0x80000000, 0}, +// {&GUID_Key, 56, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(56) | 0x80000000, 0}, +// {&GUID_Key, 57, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(57) | 0x80000000, 0}, +// {&GUID_Key, 58, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(58) | 0x80000000, 0}, +// {&GUID_Key, 59, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(59) | 0x80000000, 0}, +// {&GUID_Key, 60, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(60) | 0x80000000, 0}, +// {&GUID_Key, 61, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(61) | 0x80000000, 0}, +// {&GUID_Key, 62, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(62) | 0x80000000, 0}, +// {&GUID_Key, 63, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(63) | 0x80000000, 0}, +// {&GUID_Key, 64, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(64) | 0x80000000, 0}, +// {&GUID_Key, 65, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(65) | 0x80000000, 0}, +// {&GUID_Key, 66, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(66) | 0x80000000, 0}, +// {&GUID_Key, 67, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(67) | 0x80000000, 0}, +// {&GUID_Key, 68, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(68) | 0x80000000, 0}, +// {&GUID_Key, 69, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(69) | 0x80000000, 0}, +// {&GUID_Key, 70, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(70) | 0x80000000, 0}, +// {&GUID_Key, 71, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(71) | 0x80000000, 0}, +// {&GUID_Key, 72, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(72) | 0x80000000, 0}, +// {&GUID_Key, 73, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(73) | 0x80000000, 0}, +// {&GUID_Key, 74, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(74) | 0x80000000, 0}, +// {&GUID_Key, 75, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(75) | 0x80000000, 0}, +// {&GUID_Key, 76, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(76) | 0x80000000, 0}, +// {&GUID_Key, 77, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(77) | 0x80000000, 0}, +// {&GUID_Key, 78, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(78) | 0x80000000, 0}, +// {&GUID_Key, 79, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(79) | 0x80000000, 0}, +// {&GUID_Key, 80, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(80) | 0x80000000, 0}, +// {&GUID_Key, 81, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(81) | 0x80000000, 0}, +// {&GUID_Key, 82, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(82) | 0x80000000, 0}, +// {&GUID_Key, 83, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(83) | 0x80000000, 0}, +// {&GUID_Key, 84, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(84) | 0x80000000, 0}, +// {&GUID_Key, 85, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(85) | 0x80000000, 0}, +// {&GUID_Key, 86, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(86) | 0x80000000, 0}, +// {&GUID_Key, 87, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(87) | 0x80000000, 0}, +// {&GUID_Key, 88, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(88) | 0x80000000, 0}, +// {&GUID_Key, 89, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(89) | 0x80000000, 0}, +// {&GUID_Key, 90, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(90) | 0x80000000, 0}, +// {&GUID_Key, 91, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(91) | 0x80000000, 0}, +// {&GUID_Key, 92, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(92) | 0x80000000, 0}, +// {&GUID_Key, 93, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(93) | 0x80000000, 0}, +// {&GUID_Key, 94, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(94) | 0x80000000, 0}, +// {&GUID_Key, 95, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(95) | 0x80000000, 0}, +// {&GUID_Key, 96, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(96) | 0x80000000, 0}, +// {&GUID_Key, 97, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(97) | 0x80000000, 0}, +// {&GUID_Key, 98, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(98) | 0x80000000, 0}, +// {&GUID_Key, 99, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(99) | 0x80000000, 0}, +// {&GUID_Key, 100, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(100) | 0x80000000, 0}, +// {&GUID_Key, 101, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(101) | 0x80000000, 0}, +// {&GUID_Key, 102, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(102) | 0x80000000, 0}, +// {&GUID_Key, 103, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(103) | 0x80000000, 0}, +// {&GUID_Key, 104, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(104) | 0x80000000, 0}, +// {&GUID_Key, 105, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(105) | 0x80000000, 0}, +// {&GUID_Key, 106, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(106) | 0x80000000, 0}, +// {&GUID_Key, 107, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(107) | 0x80000000, 0}, +// {&GUID_Key, 108, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(108) | 0x80000000, 0}, +// {&GUID_Key, 109, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(109) | 0x80000000, 0}, +// {&GUID_Key, 110, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(110) | 0x80000000, 0}, +// {&GUID_Key, 111, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(111) | 0x80000000, 0}, +// {&GUID_Key, 112, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(112) | 0x80000000, 0}, +// {&GUID_Key, 113, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(113) | 0x80000000, 0}, +// {&GUID_Key, 114, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(114) | 0x80000000, 0}, +// {&GUID_Key, 115, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(115) | 0x80000000, 0}, +// {&GUID_Key, 116, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(116) | 0x80000000, 0}, +// {&GUID_Key, 117, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(117) | 0x80000000, 0}, +// {&GUID_Key, 118, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(118) | 0x80000000, 0}, +// {&GUID_Key, 119, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(119) | 0x80000000, 0}, +// {&GUID_Key, 120, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(120) | 0x80000000, 0}, +// {&GUID_Key, 121, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(121) | 0x80000000, 0}, +// {&GUID_Key, 122, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(122) | 0x80000000, 0}, +// {&GUID_Key, 123, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(123) | 0x80000000, 0}, +// {&GUID_Key, 124, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(124) | 0x80000000, 0}, +// {&GUID_Key, 125, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(125) | 0x80000000, 0}, +// {&GUID_Key, 126, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(126) | 0x80000000, 0}, +// {&GUID_Key, 127, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(127) | 0x80000000, 0}, +// {&GUID_Key, 128, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(128) | 0x80000000, 0}, +// {&GUID_Key, 129, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(129) | 0x80000000, 0}, +// {&GUID_Key, 130, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(130) | 0x80000000, 0}, +// {&GUID_Key, 131, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(131) | 0x80000000, 0}, +// {&GUID_Key, 132, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(132) | 0x80000000, 0}, +// {&GUID_Key, 133, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(133) | 0x80000000, 0}, +// {&GUID_Key, 134, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(134) | 0x80000000, 0}, +// {&GUID_Key, 135, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(135) | 0x80000000, 0}, +// {&GUID_Key, 136, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(136) | 0x80000000, 0}, +// {&GUID_Key, 137, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(137) | 0x80000000, 0}, +// {&GUID_Key, 138, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(138) | 0x80000000, 0}, +// {&GUID_Key, 139, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(139) | 0x80000000, 0}, +// {&GUID_Key, 140, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(140) | 0x80000000, 0}, +// {&GUID_Key, 141, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(141) | 0x80000000, 0}, +// {&GUID_Key, 142, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(142) | 0x80000000, 0}, +// {&GUID_Key, 143, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(143) | 0x80000000, 0}, +// {&GUID_Key, 144, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(144) | 0x80000000, 0}, +// {&GUID_Key, 145, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(145) | 0x80000000, 0}, +// {&GUID_Key, 146, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(146) | 0x80000000, 0}, +// {&GUID_Key, 147, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(147) | 0x80000000, 0}, +// {&GUID_Key, 148, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(148) | 0x80000000, 0}, +// {&GUID_Key, 149, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(149) | 0x80000000, 0}, +// {&GUID_Key, 150, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(150) | 0x80000000, 0}, +// {&GUID_Key, 151, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(151) | 0x80000000, 0}, +// {&GUID_Key, 152, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(152) | 0x80000000, 0}, +// {&GUID_Key, 153, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(153) | 0x80000000, 0}, +// {&GUID_Key, 154, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(154) | 0x80000000, 0}, +// {&GUID_Key, 155, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(155) | 0x80000000, 0}, +// {&GUID_Key, 156, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(156) | 0x80000000, 0}, +// {&GUID_Key, 157, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(157) | 0x80000000, 0}, +// {&GUID_Key, 158, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(158) | 0x80000000, 0}, +// {&GUID_Key, 159, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(159) | 0x80000000, 0}, +// {&GUID_Key, 160, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(160) | 0x80000000, 0}, +// {&GUID_Key, 161, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(161) | 0x80000000, 0}, +// {&GUID_Key, 162, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(162) | 0x80000000, 0}, +// {&GUID_Key, 163, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(163) | 0x80000000, 0}, +// {&GUID_Key, 164, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(164) | 0x80000000, 0}, +// {&GUID_Key, 165, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(165) | 0x80000000, 0}, +// {&GUID_Key, 166, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(166) | 0x80000000, 0}, +// {&GUID_Key, 167, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(167) | 0x80000000, 0}, +// {&GUID_Key, 168, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(168) | 0x80000000, 0}, +// {&GUID_Key, 169, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(169) | 0x80000000, 0}, +// {&GUID_Key, 170, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(170) | 0x80000000, 0}, +// {&GUID_Key, 171, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(171) | 0x80000000, 0}, +// {&GUID_Key, 172, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(172) | 0x80000000, 0}, +// {&GUID_Key, 173, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(173) | 0x80000000, 0}, +// {&GUID_Key, 174, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(174) | 0x80000000, 0}, +// {&GUID_Key, 175, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(175) | 0x80000000, 0}, +// {&GUID_Key, 176, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(176) | 0x80000000, 0}, +// {&GUID_Key, 177, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(177) | 0x80000000, 0}, +// {&GUID_Key, 178, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(178) | 0x80000000, 0}, +// {&GUID_Key, 179, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(179) | 0x80000000, 0}, +// {&GUID_Key, 180, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(180) | 0x80000000, 0}, +// {&GUID_Key, 181, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(181) | 0x80000000, 0}, +// {&GUID_Key, 182, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(182) | 0x80000000, 0}, +// {&GUID_Key, 183, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(183) | 0x80000000, 0}, +// {&GUID_Key, 184, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(184) | 0x80000000, 0}, +// {&GUID_Key, 185, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(185) | 0x80000000, 0}, +// {&GUID_Key, 186, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(186) | 0x80000000, 0}, +// {&GUID_Key, 187, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(187) | 0x80000000, 0}, +// {&GUID_Key, 188, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(188) | 0x80000000, 0}, +// {&GUID_Key, 189, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(189) | 0x80000000, 0}, +// {&GUID_Key, 190, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(190) | 0x80000000, 0}, +// {&GUID_Key, 191, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(191) | 0x80000000, 0}, +// {&GUID_Key, 192, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(192) | 0x80000000, 0}, +// {&GUID_Key, 193, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(193) | 0x80000000, 0}, +// {&GUID_Key, 194, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(194) | 0x80000000, 0}, +// {&GUID_Key, 195, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(195) | 0x80000000, 0}, +// {&GUID_Key, 196, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(196) | 0x80000000, 0}, +// {&GUID_Key, 197, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(197) | 0x80000000, 0}, +// {&GUID_Key, 198, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(198) | 0x80000000, 0}, +// {&GUID_Key, 199, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(199) | 0x80000000, 0}, +// {&GUID_Key, 200, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(200) | 0x80000000, 0}, +// {&GUID_Key, 201, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(201) | 0x80000000, 0}, +// {&GUID_Key, 202, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(202) | 0x80000000, 0}, +// {&GUID_Key, 203, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(203) | 0x80000000, 0}, +// {&GUID_Key, 204, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(204) | 0x80000000, 0}, +// {&GUID_Key, 205, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(205) | 0x80000000, 0}, +// {&GUID_Key, 206, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(206) | 0x80000000, 0}, +// {&GUID_Key, 207, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(207) | 0x80000000, 0}, +// {&GUID_Key, 208, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(208) | 0x80000000, 0}, +// {&GUID_Key, 209, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(209) | 0x80000000, 0}, +// {&GUID_Key, 210, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(210) | 0x80000000, 0}, +// {&GUID_Key, 211, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(211) | 0x80000000, 0}, +// {&GUID_Key, 212, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(212) | 0x80000000, 0}, +// {&GUID_Key, 213, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(213) | 0x80000000, 0}, +// {&GUID_Key, 214, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(214) | 0x80000000, 0}, +// {&GUID_Key, 215, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(215) | 0x80000000, 0}, +// {&GUID_Key, 216, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(216) | 0x80000000, 0}, +// {&GUID_Key, 217, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(217) | 0x80000000, 0}, +// {&GUID_Key, 218, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(218) | 0x80000000, 0}, +// {&GUID_Key, 219, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(219) | 0x80000000, 0}, +// {&GUID_Key, 220, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(220) | 0x80000000, 0}, +// {&GUID_Key, 221, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(221) | 0x80000000, 0}, +// {&GUID_Key, 222, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(222) | 0x80000000, 0}, +// {&GUID_Key, 223, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(223) | 0x80000000, 0}, +// {&GUID_Key, 224, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(224) | 0x80000000, 0}, +// {&GUID_Key, 225, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(225) | 0x80000000, 0}, +// {&GUID_Key, 226, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(226) | 0x80000000, 0}, +// {&GUID_Key, 227, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(227) | 0x80000000, 0}, +// {&GUID_Key, 228, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(228) | 0x80000000, 0}, +// {&GUID_Key, 229, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(229) | 0x80000000, 0}, +// {&GUID_Key, 230, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(230) | 0x80000000, 0}, +// {&GUID_Key, 231, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(231) | 0x80000000, 0}, +// {&GUID_Key, 232, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(232) | 0x80000000, 0}, +// {&GUID_Key, 233, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(233) | 0x80000000, 0}, +// {&GUID_Key, 234, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(234) | 0x80000000, 0}, +// {&GUID_Key, 235, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(235) | 0x80000000, 0}, +// {&GUID_Key, 236, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(236) | 0x80000000, 0}, +// {&GUID_Key, 237, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(237) | 0x80000000, 0}, +// {&GUID_Key, 238, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(238) | 0x80000000, 0}, +// {&GUID_Key, 239, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(239) | 0x80000000, 0}, +// {&GUID_Key, 240, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(240) | 0x80000000, 0}, +// {&GUID_Key, 241, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(241) | 0x80000000, 0}, +// {&GUID_Key, 242, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(242) | 0x80000000, 0}, +// {&GUID_Key, 243, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(243) | 0x80000000, 0}, +// {&GUID_Key, 244, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(244) | 0x80000000, 0}, +// {&GUID_Key, 245, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(245) | 0x80000000, 0}, +// {&GUID_Key, 246, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(246) | 0x80000000, 0}, +// {&GUID_Key, 247, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(247) | 0x80000000, 0}, +// {&GUID_Key, 248, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(248) | 0x80000000, 0}, +// {&GUID_Key, 249, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(249) | 0x80000000, 0}, +// {&GUID_Key, 250, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(250) | 0x80000000, 0}, +// {&GUID_Key, 251, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(251) | 0x80000000, 0}, +// {&GUID_Key, 252, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(252) | 0x80000000, 0}, +// {&GUID_Key, 253, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(253) | 0x80000000, 0}, +// {&GUID_Key, 254, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(254) | 0x80000000, 0}, +// {&GUID_Key, 255, DIDFT_BUTTON | DIDFT_MAKEINSTANCE(255) | 0x80000000, 0}}; +// +//extern const DIDATAFORMAT c_dfDIKeyboard = { +// sizeof(DIDATAFORMAT), +// sizeof(DIOBJECTDATAFORMAT), +// DIDFT_ABSAXIS, +// 256, +// 256, +// &rgodfDIKeyboard[0]}; +// +//static DIOBJECTDATAFORMAT rgodfDIMouse[] = { +// {&GUID_XAxis, 0, DIDFT_AXIS | DIDFT_ANYINSTANCE, 0}, +// {&GUID_YAxis, 4, DIDFT_AXIS | DIDFT_ANYINSTANCE, 0}, +// {&GUID_ZAxis, 8, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 12, DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0}, +// {NULL, 13, DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0}, +// {NULL, 14, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 15, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}}; +// +//extern const DIDATAFORMAT c_dfDIMouse = { +// sizeof(DIDATAFORMAT), +// sizeof(DIOBJECTDATAFORMAT), +// DIDFT_ABSAXIS, +// 16, +// 7, +// &rgodfDIMouse[0]}; +// +//static DIOBJECTDATAFORMAT rgodfDIMouse2[] = { +// {&GUID_XAxis, 0, DIDFT_AXIS | DIDFT_ANYINSTANCE, 0}, +// {&GUID_YAxis, 4, DIDFT_AXIS | DIDFT_ANYINSTANCE, 0}, +// {&GUID_ZAxis, 8, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 12, DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0}, +// {NULL, 13, DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0}, +// {NULL, 14, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 15, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 16, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 17, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 18, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 19, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}}; +// +//extern const DIDATAFORMAT c_dfDIMouse2 = { +// sizeof(DIDATAFORMAT), +// sizeof(DIOBJECTDATAFORMAT), +// DIDFT_ABSAXIS, +// 20, +// 11, +// &rgodfDIMouse2[0]}; +// +//static DIOBJECTDATAFORMAT rgodfDIJoystick[] = { +// {&GUID_XAxis, 0, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_YAxis, 4, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_ZAxis, 8, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_RxAxis, 12, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_RyAxis, 16, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_RzAxis, 20, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_Slider, 24, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_Slider, 28, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_POV, 32, DIDFT_POV | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {&GUID_POV, 36, DIDFT_POV | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {&GUID_POV, 40, DIDFT_POV | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {&GUID_POV, 44, DIDFT_POV | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 48, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 49, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 50, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 51, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 52, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 53, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 54, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 55, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 56, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 57, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 58, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 59, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 60, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 61, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 62, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 63, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 64, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 65, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 66, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 67, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 68, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 69, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 70, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 71, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 72, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 73, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 74, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 75, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 76, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 77, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 78, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 79, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}}; +// +//extern const DIDATAFORMAT c_dfDIJoystick = { +// sizeof(DIDATAFORMAT), +// sizeof(DIOBJECTDATAFORMAT), +// DIDFT_RELAXIS, +// 80, +// 44, +// &rgodfDIJoystick[0]}; +// +//static DIOBJECTDATAFORMAT rgodfDIJoystick2[] = { +// {&GUID_XAxis, 0, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_YAxis, 4, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_ZAxis, 8, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_RxAxis, 12, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_RyAxis, 16, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_RzAxis, 20, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_Slider, 24, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_Slider, 28, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTPOSITION}, +// {&GUID_POV, 32, DIDFT_POV | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {&GUID_POV, 36, DIDFT_POV | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {&GUID_POV, 40, DIDFT_POV | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {&GUID_POV, 44, DIDFT_POV | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 48, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 49, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 50, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 51, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 52, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 53, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 54, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 55, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 56, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 57, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 58, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 59, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 60, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 61, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 62, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 63, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 64, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 65, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 66, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 67, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 68, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 69, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 70, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 71, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 72, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 73, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 74, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 75, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 76, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 77, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 78, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 79, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 80, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 81, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 82, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 83, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 84, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 85, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 86, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 87, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 88, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 89, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 90, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 91, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 92, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 93, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 94, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 95, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 96, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 97, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 98, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 99, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 100, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 101, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 102, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 103, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 104, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 105, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 106, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 107, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 108, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 109, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 110, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 111, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 112, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 113, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 114, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 115, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 116, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 117, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 118, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 119, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 120, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 121, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 122, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 123, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 124, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 125, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 126, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 127, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 128, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 129, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 130, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 131, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 132, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 133, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 134, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 135, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 136, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 137, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 138, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 139, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 140, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 141, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 142, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 143, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 144, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 145, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 146, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 147, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 148, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 149, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 150, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 151, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 152, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 153, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 154, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 155, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 156, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 157, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 158, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 159, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 160, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 161, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 162, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 163, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 164, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 165, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 166, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 167, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 168, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 169, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 170, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 171, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 172, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 173, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 174, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {NULL, 175, DIDFT_BUTTON | DIDFT_ANYINSTANCE | 0x80000000, 0}, +// {&GUID_XAxis, 176, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTVELOCITY}, +// {&GUID_YAxis, 180, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTVELOCITY}, +// {&GUID_ZAxis, 184, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTVELOCITY}, +// {&GUID_RxAxis, 188, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTVELOCITY}, +// {&GUID_RyAxis, 192, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTVELOCITY}, +// {&GUID_RzAxis, 196, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTVELOCITY}, +// {&GUID_Slider, 24, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTVELOCITY}, +// {&GUID_Slider, 28, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTVELOCITY}, +// {&GUID_XAxis, 208, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTACCEL}, +// {&GUID_YAxis, 212, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTACCEL}, +// {&GUID_ZAxis, 216, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTACCEL}, +// {&GUID_RxAxis, 220, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTACCEL}, +// {&GUID_RyAxis, 224, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTACCEL}, +// {&GUID_RzAxis, 228, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTACCEL}, +// {&GUID_Slider, 24, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTACCEL}, +// {&GUID_Slider, 28, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTACCEL}, +// {&GUID_XAxis, 240, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTFORCE}, +// {&GUID_YAxis, 244, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTFORCE}, +// {&GUID_ZAxis, 248, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTFORCE}, +// {&GUID_RxAxis, 252, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTFORCE}, +// {&GUID_RyAxis, 256, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTFORCE}, +// {&GUID_RzAxis, 260, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTFORCE}, +// {&GUID_Slider, 24, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTFORCE}, +// {&GUID_Slider, 28, DIDFT_AXIS | DIDFT_ANYINSTANCE | 0x80000000, DIDOI_ASPECTFORCE}}; +// +//extern const DIDATAFORMAT c_dfDIJoystick2 = { +// sizeof(DIDATAFORMAT), +// sizeof(DIOBJECTDATAFORMAT), +// DIDFT_RELAXIS, +// 272, +// 164, +// &rgodfDIJoystick2[0]}; diff --git a/src/editors/xrECore/Editor/device.cpp b/src/editors/xrECore/Editor/device.cpp new file mode 100644 index 00000000000..67bef998c5e --- /dev/null +++ b/src/editors/xrECore/Editor/device.cpp @@ -0,0 +1,604 @@ +#include "stdafx.h" +#include "xrEngine/GameFont.h" +#include +#include "ui_main.h" +#include "render.h" +#include "xrEngine/GameMtlLib.h" +#include "Layers/xrRender/ResourceManager.h" + +//#pragma package(smart_init) + +CEditorRenderDevice EDevice; + +extern int rsDVB_Size; +extern int rsDIB_Size; + +ENGINE_API bool g_bRendering = FALSE; + +void CEditorRenderDevice::AddSeqFrame(pureFrame *f, bool mt) { seqFrame.Add(f, REG_PRIORITY_LOW); } +void CEditorRenderDevice::RemoveSeqFrame(pureFrame *f) { seqFrame.Remove(f); } + +//--------------------------------------------------------------------------- +CEditorRenderDevice::CEditorRenderDevice() +{ + RadiusRender = 400; + psDeviceFlags.assign(rsStatistic | rsFilterLinear | rsFog | rsDrawGrid); + // dynamic buffer size + rsDVB_Size = 2048; + rsDIB_Size = 2048; + // default initialization + m_ScreenQuality = 1.f; + dwMaximized = 0; + dwWidth = dwHeight = 256; + m_RenderWidth = m_RenderHeight = 256; + mProject.identity(); + mFullTransform.identity(); + mView.identity(); + m_WireShader = 0; + m_SelectionShader = 0; + + b_is_Ready = FALSE; + b_is_Active = FALSE; + + // Engine flow-control + fTimeDelta = 0; + fTimeGlobal = 0; + dwTimeDelta = 0; + dwTimeGlobal = 0; + + dwFillMode = D3DFILL_SOLID; + dwShadeMode = D3DSHADE_GOURAUD; + + m_CurrentShader = 0; + pSystemFont = 0; + + fASPECT = 1.f; + fFOV = 60.f; + dwPrecacheFrame = 0; +} + +CEditorRenderDevice::~CEditorRenderDevice() +{ + VERIFY(!b_is_Ready); +} + +void UpdateWindowProps(HWND m_hWnd) +{ + // BOOL bWindowed = strstr(Core.Params,"-dedicated") ? TRUE : !psDeviceFlags.is (rsFullscreen); + // #ifndef DEDICATED_SERVER + // BOOL bWindowed = !psDeviceFlags.is (rsFullscreen); + // #else + // BOOL bWindowed = TRUE; + // #endif + + BOOL bWindowed = TRUE; +#ifndef _EDITOR + if (!g_dedicated_server) + bWindowed = !psDeviceFlags.is(rsFullscreen); +#endif + + u32 dwWindowStyle = 0; + // Set window properties depending on what mode were in. + + if (strstr(Core.Params, "-no_dialog_header")) + SetWindowLong(m_hWnd, GWL_STYLE, dwWindowStyle = (WS_BORDER | WS_VISIBLE)); + else + SetWindowLong(m_hWnd, GWL_STYLE, dwWindowStyle = (WS_OVERLAPPEDWINDOW)); + // When moving from fullscreen to windowed mode, it is important to + // adjust the window size after recreating the device rather than + // beforehand to ensure that you get the window size you want. For + // example, when switching from 640x480 fullscreen to windowed with + // a 1000x600 window on a 1024x768 desktop, it is impossible to set + // the window size to 1000x600 until after the display mode has + // changed to 1024x768, because windows cannot be larger than the + // desktop. + + RECT m_rcWindowBounds; + BOOL bCenter = TRUE; + if (strstr(Core.Params, "-center_screen")) + bCenter = TRUE; + + if (bCenter) + { + RECT DesktopRect; + + GetClientRect(GetDesktopWindow(), &DesktopRect); + + SetRect(&m_rcWindowBounds, (DesktopRect.right - HW.GetBackBufferWidth()) / 2, + (DesktopRect.bottom - HW.GetBackBufferHeight()) / 2, (DesktopRect.right + HW.GetBackBufferWidth()) / 2, + (DesktopRect.bottom + HW.GetBackBufferHeight()) / 2); + } + else + { + SetRect(&m_rcWindowBounds, 0, 0, HW.GetBackBufferWidth(), HW.GetBackBufferHeight()); + } + + AdjustWindowRect(&m_rcWindowBounds, dwWindowStyle, FALSE); + + SetWindowPos(m_hWnd, HWND_NOTOPMOST, m_rcWindowBounds.left, m_rcWindowBounds.top, + (m_rcWindowBounds.right - m_rcWindowBounds.left), (m_rcWindowBounds.bottom - m_rcWindowBounds.top), + SWP_SHOWWINDOW | SWP_NOCOPYBITS | SWP_DRAWFRAME); +} + +// extern void Surface_Init(); +#include "Include/xrAPI/xrAPI.h" +#include "Layers/xrRender/dxRenderFactory.h" +void CEditorRenderDevice::Initialize() +{ + // m_Camera.Reset(); + + m_DefaultMat.set(1, 1, 1); + // Surface_Init(); + + // game materials + GMLib.Load(); + + // compiler shader + string_path fn; + FS.update_path(fn, _game_data_, "shaders_xrlc.xr"); + if (FS.exist(fn)) + { + ShaderXRLC.Load(fn); + } + else + { + ELog.DlgMsg(mtInformation, "Can't find file '%s'", fn); + } + + CreateWindow(); + + GEnv.Render = ::Render; + GEnv.RenderFactory = &RenderFactoryImpl; + + // Startup shaders + Create(); + + ::Render->Initialize(); + + Resize(EPrefs->start_w, EPrefs->start_h, EPrefs->start_maximized); + UpdateWindowProps(m_hWnd); + + ::ShowWindow(m_hWnd, EPrefs->start_maximized ? SW_SHOWMAXIMIZED : SW_SHOWDEFAULT); +} + +void CEditorRenderDevice::ShutDown() +{ + ::Render->ShutDown(); + + ShaderXRLC.Unload(); + GMLib.Unload(); + + // destroy context + Destroy(); + xr_delete(pSystemFont); + + // destroy shaders + // PSLib.xrShutDown (); +} + +void CEditorRenderDevice::InitTimer() +{ + Timer_MM_Delta = 0; + { + u32 time_mm = clock(); + while (clock() == time_mm) + ; // wait for next tick + u32 time_system = clock(); + u32 time_local = TimerAsync(); + Timer_MM_Delta = time_system - time_local; + } +} +//--------------------------------------------------------------------------- +void CEditorRenderDevice::RenderNearer(float n) +{ + mProject._43 = m_fNearer - n; + RCache.set_xform_project(mProject); +} +void CEditorRenderDevice::ResetNearer() +{ + mProject._43 = m_fNearer; + RCache.set_xform_project(mProject); +} +//--------------------------------------------------------------------------- +bool CEditorRenderDevice::Create() +{ + if (b_is_Ready) + return false; + Statistic = xr_new(); + ELog.Msg(mtInformation, "Starting RENDER device..."); + + HW.CreateDevice(m_hWnd); + if (UI) + { + string_path ini_path; + string_path ini_name; + xr_strcpy(ini_name, UI->EditorName()); + xr_strcat(ini_name, "_imgui.ini"); + FS.update_path(ini_path, "$local_root$", ini_name); + if (!FS.exist(ini_path)) + UI->ResetUI(); + UI->Initialize(m_hWnd, HW.pDevice, ini_path); + } + + // after creation + dwFrame = 0; + + string_path sh; + FS.update_path(sh, _game_data_, "shaders.xr"); + + IReader *F = 0; + if (FS.exist(sh)) + F = FS.r_open(0, sh); + Resources = xr_new(); + + // hack + RImplementation.Resources = Resources; + + // if build options - load textures immediately + if (strstr(Core.Params, "-build") || strstr(Core.Params, "-ebuild")) + EDevice.Resources->DeferredLoad(FALSE); + + _Create(F); + FS.r_close(F); + + ELog.Msg(mtInformation, "D3D: initialized"); + + return true; +} + +//--------------------------------------------------------------------------- +void CEditorRenderDevice::Destroy() +{ + if (!b_is_Ready) + return; + + ELog.Msg(mtInformation, "Destroying Direct3D..."); + + // before destroy + _Destroy(FALSE); + xr_delete(Resources); + RImplementation.Resources = nullptr; + + UI->Destroy(); + // real destroy + HW.DestroyDevice(); + + ELog.Msg(mtInformation, "D3D: device cleared"); + xr_delete(Statistic); +} +//--------------------------------------------------------------------------- +void CEditorRenderDevice::_SetupStates() +{ + HW.Caps.Update(); + for (u32 i = 0; i < HW.Caps.raster.dwStages; i++) + { + float fBias = -1.f; + CHK_DX(HW.pDevice->SetSamplerState(i, D3DSAMP_MIPMAPLODBIAS, *((LPDWORD)(&fBias)))); + } + EDevice.SetRS(D3DRS_DITHERENABLE, TRUE); + EDevice.SetRS(D3DRS_COLORVERTEX, TRUE); + EDevice.SetRS(D3DRS_STENCILENABLE, FALSE); + EDevice.SetRS(D3DRS_ZENABLE, TRUE); + EDevice.SetRS(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); + EDevice.SetRS(D3DRS_CULLMODE, D3DCULL_CCW); + EDevice.SetRS(D3DRS_ALPHAFUNC, D3DCMP_GREATER); + EDevice.SetRS(D3DRS_LOCALVIEWER, TRUE); + EDevice.SetRS(D3DRS_NORMALIZENORMALS, TRUE); + + EDevice.SetRS(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL); + EDevice.SetRS(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL); + EDevice.SetRS(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL); + EDevice.SetRS(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_COLOR1); + + ResetMaterial(); +} +//--------------------------------------------------------------------------- +void CEditorRenderDevice::_Create(IReader *F) +{ + b_is_Ready = TRUE; + + // General Render States + _SetupStates(); + + // TODO: inherit render from D3DXRenderBase and use that from its OnDeviceCreate + ::Render->CreateQuadIB(); + ::Render->Vertex.Create(); + ::Render->Index.Create(); + + RCache.OnDeviceCreate(); + Resources->OnDeviceCreate(F); + ::Render->OnDeviceCreate(); + + m_WireShader.create("editor\\wire"); + m_SelectionShader.create("editor\\selection"); + + // signal another objects + UI->OnDeviceCreate(); + //. seqDevCreate.Process (rp_DeviceCreate); + + pSystemFont = xr_new("hud_font_small"); + // pSystemFont = xr_new("hud_font_medium"); +} + +void CEditorRenderDevice::_Destroy(BOOL bKeepTextures) +{ + xr_delete(pSystemFont); + + b_is_Ready = FALSE; + m_CurrentShader = 0; + + UI->OnDeviceDestroy(); + + m_WireShader.destroy(); + m_SelectionShader.destroy(); + + //. seqDevDestroy.Process (rp_DeviceDestroy); + + ::Render->Models->OnDeviceDestroy(); + + Resources->OnDeviceDestroy(bKeepTextures); + + RCache.OnDeviceDestroy(); + ::Render->OnDeviceDestroy(); +} + +//--------------------------------------------------------------------------- +void CEditorRenderDevice::Resize(int w, int h, bool maximized) +{ + if (dwWidth == w && dwHeight == h && dwMaximized == maximized) + return; + m_RenderArea = static_cast(w * h); + + dwWidth = w; + dwHeight = h; + dwMaximized = maximized; + + Reset(); + UI->RedrawScene(); +} + +void CEditorRenderDevice::Reset() +{ + u32 tm_start = TimerAsync(); + Resources->reset_begin(); + UI->ResetBegin(); + Memory.mem_compact(); + HW.SetBackBufferWidth(dwWidth); + HW.SetBackBufferHeight(dwHeight); + HW.Reset(); + dwWidth = HW.GetBackBufferWidth(); + dwHeight = HW.GetBackBufferHeight(); + + Resources->reset_end(); + UI->ResetEnd(); + _SetupStates(); + u32 tm_end = TimerAsync(); + Msg("*** RESET [%d ms]", tm_end - tm_start); +} + +BOOL CEditorRenderDevice::Begin() +{ + VERIFY(b_is_Ready); + mFullTransformSaved = mFullTransform; + mProject_saved = mProject; + mView = mView_saved; + vCameraPosition_saved = vCameraPosition; + + HRESULT _hr = HW.pDevice->TestCooperativeLevel(); + if (FAILED(_hr)) + { + // If the device was lost, do not render until we get it back + if (D3DERR_DEVICELOST == _hr) + { + Sleep(33); + return FALSE; + } + + // Check if the device is ready to be reset + if (D3DERR_DEVICENOTRESET == _hr) + { + Reset(); + } + } + + VERIFY(FALSE == g_bRendering); + HW.pDevice->BeginScene(); //CHK_DX(HW.pDevice->BeginScene()); + CHK_DX(HW.pDevice->Clear(0, 0, + D3DCLEAR_ZBUFFER | D3DCLEAR_TARGET | + (HW.Caps.bStencil ? D3DCLEAR_STENCIL : 0), + EPrefs ? EPrefs->scene_clear_color : 0x0, 1, 0)); + RCache.OnFrameBegin(); + g_bRendering = TRUE; + return TRUE; +} + +void CEditorRenderDevice::End() +{ + VERIFY(HW.pDevice); + VERIFY(b_is_Ready); + g_bRendering = FALSE; + // end scene + RCache.OnFrameEnd(); + + #pragma TODO("TSMP: restore CHK_DX!") + // TSMP: when calling MakeScreenshot by user click on button, we are drawing imgui in render window + // so we call twice BeginScene and EndScene, and they return error. Need to reimplement this and + // restore CHK_DX for BeginScene and EndScene + HW.pDevice->EndScene(); //CHK_DX(HW.pDevice->EndScene()); + + CHK_DX(HW.pDevice->Present(NULL, NULL, NULL, NULL)); +} + +void CEditorRenderDevice::UpdateView() +{ + // set camera matrix + m_Camera.GetView(mView); + + RCache.set_xform_view(mView); + mFullTransform.mul(mProject, mView); + + // frustum culling sets + ::Render->ViewBase.CreateFromMatrix(mFullTransform, FRUSTUM_P_ALL); +} + +void CEditorRenderDevice::FrameMove() +{ + dwFrame++; + + // Timer + float fPreviousFrameTime = Timer.GetElapsed_sec(); + Timer.Start(); // previous frame + fTimeDelta = 0.1f * fTimeDelta + 0.9f * fPreviousFrameTime; // smooth random system activity - worst case ~7% error + if (fTimeDelta > .1f) + fTimeDelta = .1f; // limit to 15fps minimum + + fTimeGlobal = TimerGlobal.GetElapsed_sec(); // float(qTime)*CPU::cycles2seconds; + dwTimeGlobal = TimerGlobal.GetElapsed_ms(); // u32((qTime*u64(1000))/CPU::cycles_per_second); + dwTimeDelta = iFloor(fTimeDelta * 1000.f + 0.5f); + dwTimeContinual = dwTimeGlobal; + + m_Camera.Update(fTimeDelta); + + // process objects + seqFrame.Process(); +} + +void CEditorRenderDevice::DP(D3DPRIMITIVETYPE pt, ref_geom geom, u32 vBase, u32 pc) +{ + ref_shader S = m_CurrentShader ? m_CurrentShader : m_WireShader; + u32 dwRequired = S->E[0]->passes.size(); + RCache.set_Geometry(geom); + for (u32 dwPass = 0; dwPass < dwRequired; dwPass++) + { + RCache.set_Shader(S, dwPass); + RCache.Render(pt, vBase, pc); + } +} + +void CEditorRenderDevice::DIP(D3DPRIMITIVETYPE pt, ref_geom geom, u32 baseV, u32 startV, u32 countV, u32 startI, u32 PC) +{ + ref_shader S = m_CurrentShader ? m_CurrentShader : m_WireShader; + u32 dwRequired = S->E[0]->passes.size(); + RCache.set_Geometry(geom); + for (u32 dwPass = 0; dwPass < dwRequired; dwPass++) + { + RCache.set_Shader(S, dwPass); + RCache.Render(pt, baseV, startV, countV, startI, PC); + } +} + +void CEditorRenderDevice::ReloadTextures() +{ + UI->SetStatus("Reload textures..."); + Resources->ED_UpdateTextures(0); + UI->SetStatus(""); +} + +void CEditorRenderDevice::UnloadTextures() +{ +#ifndef _EDITOR + Resources->DeferredUnload(); +#endif +} + +void CEditorRenderDevice::Reset(IReader *F, BOOL bKeepTextures) +{ + CTimer tm; + tm.Start(); + _Destroy(bKeepTextures); + _Create(F); + Msg("*** RESET [%d ms]", tm.GetElapsed_ms()); +} + +void CEditorRenderDevice::time_factor(float v) +{ + Timer.time_factor(v); + TimerGlobal.time_factor(v); +} + +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +void CEditorRenderDevice::CreateWindow() +{ + m_WC = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), UI->EditorIcon() , NULL, NULL, NULL, TEXT("X-Ray editor") , NULL}; + ::RegisterClassEx(&m_WC); + m_hWnd = ::CreateWindowA(m_WC.lpszClassName, UI->EditorDesc(), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, m_WC.hInstance, NULL); + + ::UpdateWindow(m_hWnd); +} +void CEditorRenderDevice::DestryWindow() +{ + ::DestroyWindow(m_hWnd); + ::UnregisterClass(m_WC.lpszClassName, m_WC.hInstance); +} +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch (msg) + { + case WM_ACTIVATE: + { + u16 fActive = LOWORD(wParam); + BOOL fMinimized = (BOOL)HIWORD(wParam); + BOOL bActive = ((fActive != WA_INACTIVE) && (!fMinimized)) ? TRUE : FALSE; + if (bActive != EDevice.b_is_Active) + { + EDevice.b_is_Active = bActive; + + if (EDevice.b_is_Active) + { + if (UI) + UI->OnAppActivate(); + } + else + { + + if (UI) + UI->OnAppDeactivate(); + } + } + } + break; + } + if (UI && UI->WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + switch (msg) + { + case WM_KEYDOWN: + case WM_SYSKEYDOWN: + if (UI) + UI->KeyDown(wParam, UI->GetShiftState()); + break; + case WM_KEYUP: + case WM_SYSKEYUP: + if (UI) + UI->KeyUp(wParam, UI->GetShiftState()); + break; + + case WM_SIZE: + + if (UI && HW.pDevice) + { + UI->Resize(LOWORD(lParam), HIWORD(lParam), wParam == SIZE_MAXIMIZED); + } + /*if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) + { + g_d3dpp.BackBufferWidth = ; + g_d3dpp.BackBufferHeight = ; + ResetDevice(); + }*/ + return 0; + + case WM_SYSCOMMAND: + + if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu + { + return 0; + } + break; + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; + } + return ::DefWindowProc(hWnd, msg, wParam, lParam); +} diff --git a/src/editors/xrECore/Editor/device.h b/src/editors/xrECore/Editor/device.h new file mode 100644 index 00000000000..6afae29a5de --- /dev/null +++ b/src/editors/xrECore/Editor/device.h @@ -0,0 +1,301 @@ +#pragma once + +#include "ui_camera.h" +#include "../../../xrEngine/pure.h" +#include "Layers/xrRenderDX9/dx9HW.h" + +#include "estats.h" +#include "Utils\shader_xrlc.h" +#include "..\..\Layers\xrRender\Shader.h" + +// refs +class CGameFont; +class CInifile; +class CResourceManager; +#undef CreateWindow + +class ENGINE_API CRenderDeviceData +{ +public: + bool dwMaximized; + u32 dwWidth; + u32 dwHeight; + u32 dwPrecacheFrame; + BOOL b_is_Ready; + BOOL b_is_Active; + +public: + // Engine flow-control + u32 dwFrame; + + float fTimeDelta; + float fTimeGlobal; + u32 dwTimeDelta; + u32 dwTimeGlobal; + u32 dwTimeContinual; + + Fvector vCameraPosition; + Fvector vCameraDirection; + Fvector vCameraTop; + Fvector vCameraRight; + + Fmatrix mView; + Fmatrix mProject; + Fmatrix mFullTransform; + + // Copies of corresponding members. Used for synchronization. + Fvector vCameraPosition_saved; + + Fmatrix mView_saved; + Fmatrix mProject_saved; + Fmatrix mFullTransformSaved; + + float fFOV; + float fASPECT; + +protected: + u32 Timer_MM_Delta; + CTimer_paused Timer; + CTimer_paused TimerGlobal; + +public: + // Registrators + MessageRegistry seqRender; + MessageRegistry seqAppActivate; + MessageRegistry seqAppDeactivate; + MessageRegistry seqAppStart; + MessageRegistry seqAppEnd; + MessageRegistry seqFrame; + //MessageRegistry seqResolutionChanged; +#ifdef _EDITOR + MessageRegistry seqDrawUI; +#endif + + HWND m_hWnd; + // CStats* Statistic; +}; + +class ENGINE_API CRenderDeviceBase : public CRenderDeviceData +{ +public: +}; + +class ECORE_API CEditorRenderDevice : public CRenderDeviceBase +{ + friend class CUI_Camera; + friend class TUI; + + float m_fNearer; + + // u32 Timer_MM_Delta; + // CTimer Timer; + // CTimer TimerGlobal; + + ref_shader m_CurrentShader; + + void _SetupStates(); + void _Create(IReader *F); + void _Destroy(BOOL bKeepTextures); + void Reset(); + +public: + ref_shader m_WireShader; + ref_shader m_SelectionShader; + + Fmaterial m_DefaultMat; + +public: + float RadiusRender; + // u32 dwWidth, dwHeight; + u32 m_RenderWidth, m_RenderHeight; + float m_RenderArea; + float m_ScreenQuality; + + u32 dwFillMode; + u32 dwShadeMode; + +public: + // HWND m_hWnd; + + // u32 dwFrame; + // u32 dwPrecacheFrame; + + // BOOL b_is_Ready; + // BOOL b_is_Active; + + // Engine flow-control + // float fTimeDelta; + // float fTimeGlobal; + // u32 dwTimeDelta; + // u32 dwTimeGlobal; + // u32 dwTimeContinual; + + // camera + CUI_Camera m_Camera; + + // Fvector vCameraPosition; + // Fvector vCameraDirection; + // Fvector vCameraTop; + // Fvector vCameraRight; + // + // Fmatrix mView; + // Fmatrix mProjection; + // Fmatrix mFullTransform; + + // float fFOV; + // float fASPECT; + + // Dependent classes + CResourceManager *Resources; + CEStats *Statistic; + + CGameFont *pSystemFont; + + // registrators + // CRegistrator seqDevDestroy; + // CRegistrator seqDevCreate; + + // CRegistrator seqFrame; + // CRegistrator seqRender; + // CRegistrator seqAppStart; + // CRegistrator seqAppEnd; + // CRegistrator seqAppActivate; + // CRegistrator seqAppDeactivate; +public: + CEditorRenderDevice(); + virtual ~CEditorRenderDevice(); + + void Pause(BOOL bOn, BOOL bTimer, BOOL bSound, LPCSTR reason){}; + BOOL Paused() { return FALSE; }; + void time_factor(float); + bool Create(); + void Destroy(); + void Resize(int w, int h, bool maximized); + void ReloadTextures(); + void UnloadTextures(); + + void RenderNearer(float f_Near); + void ResetNearer(); + BOOL Begin(); + void End(); + + void Initialize(void); + void ShutDown(void); + void Reset(IReader *F, BOOL bKeepTextures); + + //IC CTimer *GetTimerGlobal() { return &TimerGlobal; } + + IC float GetRenderArea() { return m_RenderArea; } + // Sprite rendering + IC float _x2real(float x) + { + return (x + 1) * m_RenderWidth * 0.5f; + } + IC float _y2real(float y) + { + return (y + 1) * m_RenderHeight * 0.5f; + } + + // draw + void SetShader(ref_shader sh) { m_CurrentShader = sh; } + void DP(D3DPRIMITIVETYPE pt, ref_geom geom, u32 startV, u32 pc); + void DIP(D3DPRIMITIVETYPE pt, ref_geom geom, u32 baseV, u32 startV, u32 countV, u32 startI, u32 PC); + + IC void SetRS(D3DRENDERSTATETYPE p1, u32 p2) + { + VERIFY(b_is_Ready); + CHK_DX(HW.pDevice->SetRenderState(p1, p2)); + } + IC void SetSS(u32 sampler, D3DSAMPLERSTATETYPE type, u32 value) + { + VERIFY(b_is_Ready); + CHK_DX(HW.pDevice->SetSamplerState(sampler, type, value)); + } + + // light&material + IC void LightEnable(u32 dwLightIndex, BOOL bEnable) + { + CHK_DX(HW.pDevice->LightEnable(dwLightIndex, bEnable)); + } + IC void SetLight(u32 dwLightIndex, Flight &lpLight) + { + CHK_DX(HW.pDevice->SetLight(dwLightIndex, (D3DLIGHT9 *)&lpLight)); + } + IC void SetMaterial(Fmaterial &mat) + { + CHK_DX(HW.pDevice->SetMaterial((D3DMATERIAL9 *)&mat)); + } + IC void ResetMaterial() + { + CHK_DX(HW.pDevice->SetMaterial((D3DMATERIAL9 *)&m_DefaultMat)); + } + + // update + void UpdateView(); + void FrameMove(); + + bool MakeScreenshot(U32Vec &pixels, u32 width, u32 height); + + void InitTimer(); + // Mode control + IC u32 TimerAsync(void) + { + return TimerGlobal.GetElapsed_ms(); + } + IC u32 TimerAsync_MMT(void) + { + return TimerAsync() + Timer_MM_Delta; + } + +public: + Shader_xrLC_LIB ShaderXRLC; + +private: + virtual void AddSeqFrame(pureFrame *f, bool mt); + virtual void RemoveSeqFrame(pureFrame *f); + +private: + WNDCLASSEX m_WC; + +public: + void CreateWindow(); + void DestryWindow(); + +protected: + u32 Timer_MM_Delta; + CTimer_paused Timer; + CTimer_paused TimerGlobal; +}; + +extern ECORE_API CEditorRenderDevice EDevice; + +// video +enum +{ + rsFilterLinear = (1ul << 20ul), + rsEdgedFaces = (1ul << 21ul), + rsRenderTextures = (1ul << 22ul), + rsLighting = (1ul << 23ul), + rsFog = (1ul << 24ul), + rsRenderRealTime = (1ul << 25ul), + rsDrawGrid = (1ul << 26ul), + rsDrawSafeRect = (1ul << 27ul), + rsMuteSounds = (1ul << 28ul), + rsEnvironment = (1ul << 29ul), +}; + +#define DEFAULT_CLEARCOLOR 0x00555555 + +#define REQ_CREATE() \ + if (!EDevice.bReady) \ + return; +#define REQ_DESTROY() \ + if (EDevice.bReady) \ + return; + +//#include "../../../xrCPU_Pipe/xrCPU_Pipe.h" +//ENGINE_API extern xrDispatchTable PSGP; + +#include "xrCore/_plane.h" +#include "Layers/xrRender/R_Backend.h" +#include "Layers/xrRender/R_Backend_Runtime.h" diff --git a/src/editors/xrECore/Editor/du_box.cpp b/src/editors/xrECore/Editor/du_box.cpp new file mode 100644 index 00000000000..3970b8fd3ae --- /dev/null +++ b/src/editors/xrECore/Editor/du_box.cpp @@ -0,0 +1,30 @@ +#include "stdafx.h" +#include "Layers/xrRender/du_box.h" + +Fvector du_box_vertices2[DU_BOX_NUMVERTEX2] = { + {-0.5f, -0.5f, -0.5f}, {-0.5f, +0.5f, -0.5f}, {+0.5f, +0.5f, -0.5f}, {+0.5f, +0.5f, -0.5f}, {+0.5f, -0.5f, -0.5f}, {-0.5f, -0.5f, -0.5f}, {+0.5f, -0.5f, -0.5f}, {+0.5f, +0.5f, -0.5f}, {+0.5f, +0.5f, +0.5f}, {+0.5f, +0.5f, +0.5f}, {+0.5f, -0.5f, +0.5f}, {+0.5f, -0.5f, -0.5f}, {+0.5f, +0.5f, +0.5f}, {-0.5f, +0.5f, +0.5f}, {-0.5f, -0.5f, +0.5f}, {+0.5f, +0.5f, +0.5f}, {-0.5f, -0.5f, +0.5f}, {+0.5f, -0.5f, +0.5f}, {-0.5f, +0.5f, +0.5f}, {-0.5f, +0.5f, -0.5f}, {-0.5f, -0.5f, +0.5f}, {-0.5f, +0.5f, -0.5f}, {-0.5f, -0.5f, -0.5f}, {-0.5f, -0.5f, +0.5f}, {+0.5f, -0.5f, -0.5f}, {-0.5f, -0.5f, +0.5f}, {-0.5f, -0.5f, -0.5f}, {+0.5f, -0.5f, -0.5f}, {+0.5f, -0.5f, +0.5f}, {-0.5f, -0.5f, +0.5f}, {-0.5f, +0.5f, -0.5f}, {-0.5f, +0.5f, +0.5f}, {+0.5f, +0.5f, +0.5f}, {-0.5f, +0.5f, -0.5f}, {+0.5f, +0.5f, +0.5f}, {+0.5f, +0.5f, -0.5f}}; + +Fvector du_box_vertices[DU_BOX_NUMVERTEX] = { + {-0.5f, -0.5f, -0.5f}, + {-0.5f, +0.5f, -0.5f}, + {+0.5f, +0.5f, -0.5f}, + {+0.5f, -0.5f, -0.5f}, + {-0.5f, +0.5f, +0.5f}, + {-0.5f, -0.5f, +0.5f}, + {+0.5f, +0.5f, +0.5f}, + {+0.5f, -0.5f, +0.5f}, +}; + +WORD du_box_faces[DU_BOX_NUMFACES * 3] = { + 0, 1, 2, 2, 3, 0, + 3, 2, 6, 6, 7, 3, + 6, 4, 5, 6, 5, 7, + 4, 1, 5, 1, 0, 5, + 3, 5, 0, 3, 7, 5, // bottom + 1, 4, 6, 1, 6, 2 // top +}; + +WORD du_box_lines[DU_BOX_NUMLINES * 2] = { + 0, 1, 1, 2, 2, 3, 3, 0, + 4, 5, 5, 7, 6, 7, 6, 4, + 0, 5, 1, 4, 2, 6, 3, 7}; diff --git a/src/editors/xrECore/Editor/du_cone.cpp b/src/editors/xrECore/Editor/du_cone.cpp new file mode 100644 index 00000000000..b7dd10f3ab5 --- /dev/null +++ b/src/editors/xrECore/Editor/du_cone.cpp @@ -0,0 +1,124 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "du_cone.h" +//--------------------------------------------------------------------------- +//#pragma package(smart_init) +Fvector du_cone_vertices[DU_CONE_NUMVERTEX] = + { + {0.0000f, 0.0000f, 0.0000f}, + {0.5000f, 0.0000f, 1.0000f}, + {0.4619f, 0.1913f, 1.0000f}, + {0.3536f, 0.3536f, 1.0000f}, + {0.1913f, 0.4619f, 1.0000f}, + {-0.0000f, 0.5000f, 1.0000f}, + {-0.1913f, 0.4619f, 1.0000f}, + {-0.3536f, 0.3536f, 1.0000f}, + {-0.4619f, 0.1913f, 1.0000f}, + {-0.5000f, -0.0000f, 1.0000f}, + {-0.4619f, -0.1913f, 1.0000f}, + {-0.3536f, -0.3536f, 1.0000f}, + {-0.1913f, -0.4619f, 1.0000f}, + {0.0000f, -0.5000f, 1.0000f}, + {0.1913f, -0.4619f, 1.0000f}, + {0.3536f, -0.3536f, 1.0000f}, + {0.4619f, -0.1913f, 1.0000f}, + {0.0000f, 0.0000f, 1.0000f}}; +WORD du_cone_faces[DU_CONE_NUMFACES * 3] = + { + 0, 2, 1, + 0, 3, 2, + 0, 4, 3, + 0, 5, 4, + 0, 6, 5, + 0, 7, 6, + 0, 8, 7, + 0, 9, 8, + 0, 10, 9, + 0, 11, 10, + 0, 12, 11, + 0, 13, 12, + 0, 14, 13, + 0, 15, 14, + 0, 16, 15, + 0, 1, 16, + 17, 1, 2, + 17, 2, 3, + 17, 3, 4, + 17, 4, 5, + 17, 5, 6, + 17, 6, 7, + 17, 7, 8, + 17, 8, 9, + 17, 9, 10, + 17, 10, 11, + 17, 11, 12, + 17, 12, 13, + 17, 13, 14, + 17, 14, 15, + 17, 15, 16, + 17, 16, 1}; + +WORD du_cone_lines[DU_CONE_NUMLINES * 2] = + { + // tile + 0, + 1, + // 0, 2, + 0, + 3, + // 0, 4, + 0, + 5, + // 0, 6, + 0, + 7, + // 0, 8, + 0, + 9, + // 0, 10, + 0, + 11, + // 0, 12, + 0, + 13, + // 0, 14, + 0, + 15, + // 0, 16, + + // cape + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + 6, + 6, + 7, + 7, + 8, + 8, + 9, + 9, + 10, + 10, + 11, + 11, + 12, + 12, + 13, + 13, + 14, + 14, + 15, + 15, + 16, + 16, + 1, +}; diff --git a/src/editors/xrECore/Editor/du_cone.h b/src/editors/xrECore/Editor/du_cone.h new file mode 100644 index 00000000000..63d49a88387 --- /dev/null +++ b/src/editors/xrECore/Editor/du_cone.h @@ -0,0 +1,13 @@ +//--------------------------------------------------------------------------- + +#ifndef du_coneH +#define du_coneH +//--------------------------------------------------------------------------- +#define DU_CONE_NUMVERTEX 18 +#define DU_CONE_NUMFACES 32 +#define DU_CONE_NUMLINES 24 + +extern ECORE_API Fvector du_cone_vertices[]; +extern ECORE_API WORD du_cone_faces[]; +extern ECORE_API WORD du_cone_lines[]; +#endif diff --git a/src/editors/xrECore/Editor/du_cylinder.cpp b/src/editors/xrECore/Editor/du_cylinder.cpp new file mode 100644 index 00000000000..bcd907d0417 --- /dev/null +++ b/src/editors/xrECore/Editor/du_cylinder.cpp @@ -0,0 +1,254 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "du_cylinder.h" +//--------------------------------------------------------------------------- +//#pragma package(smart_init) +Fvector du_cylinder_vertices[DU_CYLINDER_NUMVERTEX] = { + {0.5000f, 0.0000f, 0.5000f}, // 0 + {0.5000f, -0.0000f, -0.5000f}, // 1 + {0.4330f, -0.2500f, -0.5000f}, // 2 + {0.4330f, -0.2500f, 0.5000f}, // 3 + {0.2500f, -0.4330f, -0.5000f}, // 4 + {0.2500f, -0.4330f, 0.5000f}, // 5 + {0.0000f, -0.5000f, -0.5000f}, // 6 + {-0.0000f, -0.5000f, 0.5000f}, // 7 + {-0.2500f, -0.4330f, -0.5000f}, // 8 + {-0.2500f, -0.4330f, 0.5000f}, // 9 + {-0.4330f, -0.2500f, -0.5000f}, // 10 + {-0.4330f, -0.2500f, 0.5000f}, // 11 + {-0.5000f, -0.0000f, -0.5000f}, // 12 + {-0.5000f, 0.0000f, 0.5000f}, // 13 + {-0.4330f, 0.2500f, -0.5000f}, // 14 + {-0.4330f, 0.2500f, 0.5000f}, // 15 + {-0.2500f, 0.4330f, -0.5000f}, // 16 + {-0.2500f, 0.4330f, 0.5000f}, // 17 + {0.0000f, 0.5000f, -0.5000f}, // 18 + {-0.0000f, 0.5000f, 0.5000f}, // 19 + {0.2500f, 0.4330f, -0.5000f}, // 20 + {0.2500f, 0.4330f, 0.5000f}, // 21 + {0.4330f, 0.2500f, -0.5000f}, // 22 + {0.4330f, 0.2500f, 0.5000f}, // 23 + {-0.0000f, 0.0000f, 0.5000f}, // 24 + {0.0000f, -0.0000f, -0.5000f}, // 25 +}; + +u16 du_cylinder_faces[DU_CYLINDER_NUMFACES * 3] = { + 0, + 2, + 1, + 3, + 2, + 0, + 3, + 4, + 2, + 5, + 4, + 3, + 5, + 6, + 4, + 7, + 6, + 5, + 8, + 6, + 9, + 9, + 6, + 7, + 10, + 8, + 11, + 11, + 8, + 9, + 12, + 10, + 13, + 13, + 10, + 11, + 14, + 12, + 15, + 12, + 13, + 15, + 16, + 14, + 17, + 17, + 14, + 15, + 18, + 16, + 19, + 19, + 16, + 17, + 19, + 20, + 18, + 21, + 20, + 19, + 21, + 22, + 20, + 23, + 22, + 21, + 23, + 1, + 22, + 23, + 0, + 1, + 23, + 24, + 0, + 21, + 24, + 23, + 19, + 24, + 21, + 17, + 24, + 19, + 15, + 24, + 17, + 13, + 24, + 15, + 11, + 24, + 13, + 9, + 24, + 11, + 7, + 24, + 9, + 5, + 24, + 7, + 3, + 24, + 5, + 0, + 24, + 3, + 8, + 25, + 6, + 10, + 25, + 8, + 12, + 25, + 10, + 14, + 25, + 12, + 16, + 25, + 14, + 18, + 25, + 16, + 20, + 25, + 18, + 22, + 25, + 20, + 1, + 25, + 22, + 2, + 25, + 1, + 4, + 25, + 2, + 6, + 25, + 4, +}; + +u16 du_cylinder_lines[DU_CYLINDER_NUMLINES * 2] = { + // tile + 0, + 1, + // 2, 3, + 4, + 5, + // 6, 7, + 8, + 9, + // 10, 11, + 12, + 13, + // 14, 15, + 16, + 17, + // 18, 19, + 20, + 21, + // 22, 23, + // cape 0 + 1, + 2, + 2, + 4, + 4, + 6, + 6, + 8, + 8, + 10, + 10, + 12, + 12, + 14, + 14, + 16, + 16, + 18, + 18, + 20, + 20, + 22, + 22, + 1, + // cape1 + 0, + 3, + 3, + 5, + 5, + 7, + 7, + 9, + 9, + 11, + 11, + 13, + 13, + 15, + 15, + 17, + 17, + 19, + 19, + 21, + 21, + 23, + 23, + 0, +}; diff --git a/src/editors/xrECore/Editor/du_cylinder.h b/src/editors/xrECore/Editor/du_cylinder.h new file mode 100644 index 00000000000..47a298fad20 --- /dev/null +++ b/src/editors/xrECore/Editor/du_cylinder.h @@ -0,0 +1,13 @@ +//--------------------------------------------------------------------------- + +#ifndef du_cylinderH +#define du_cylinderH +//--------------------------------------------------------------------------- +#define DU_CYLINDER_NUMVERTEX 26 +#define DU_CYLINDER_NUMFACES 48 +#define DU_CYLINDER_NUMLINES 30 // 36 +extern ECORE_API Fvector du_cylinder_vertices[]; +extern ECORE_API u16 du_cylinder_faces[]; +extern ECORE_API u16 du_cylinder_lines[]; + +#endif diff --git a/src/editors/xrECore/Editor/du_sphere.cpp b/src/editors/xrECore/Editor/du_sphere.cpp new file mode 100644 index 00000000000..676b523fc73 --- /dev/null +++ b/src/editors/xrECore/Editor/du_sphere.cpp @@ -0,0 +1,831 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "du_sphere.h" +//--------------------------------------------------------------------------- +//#pragma package(smart_init) +Fvector du_sphere_vertices[DU_SPHERE_NUMVERTEX] = { + {0.0000f, 1.0000f, 0.0000f}, + {0.8944f, 0.4472f, 0.0000f}, + {0.2764f, 0.4472f, 0.8507f}, + {-0.7236f, 0.4472f, 0.5257f}, + {-0.7236f, 0.4472f, -0.5257f}, + {0.2764f, 0.4472f, -0.8507f}, + {0.7236f, -0.4472f, 0.5257f}, + {-0.2764f, -0.4472f, 0.8507f}, + {-0.8944f, -0.4472f, -0.0000f}, + {-0.2764f, -0.4472f, -0.8507f}, + {0.7236f, -0.4472f, -0.5257f}, + {0.0000f, -1.0000f, 0.0000f}, + {0.3607f, 0.9327f, 0.0000f}, + {0.6729f, 0.7397f, 0.0000f}, + {0.1115f, 0.9327f, 0.3431f}, + {0.2079f, 0.7397f, 0.6399f}, + {-0.2918f, 0.9327f, 0.2120f}, + {-0.5444f, 0.7397f, 0.3955f}, + {-0.2918f, 0.9327f, -0.2120f}, + {-0.5444f, 0.7397f, -0.3955f}, + {0.1115f, 0.9327f, -0.3431f}, + {0.2079f, 0.7397f, -0.6399f}, + {0.7844f, 0.5168f, 0.3431f}, + {0.5687f, 0.5168f, 0.6399f}, + {-0.0839f, 0.5168f, 0.8520f}, + {-0.4329f, 0.5168f, 0.7386f}, + {-0.8362f, 0.5168f, 0.1835f}, + {-0.8362f, 0.5168f, -0.1835f}, + {-0.4329f, 0.5168f, -0.7386f}, + {-0.0839f, 0.5168f, -0.8520f}, + {0.5687f, 0.5168f, -0.6399f}, + {0.7844f, 0.5168f, -0.3431f}, + {0.9647f, 0.1561f, 0.2120f}, + {0.9051f, -0.1561f, 0.3955f}, + {0.0965f, 0.1561f, 0.9830f}, + {-0.0965f, -0.1561f, 0.9830f}, + {-0.9051f, 0.1561f, 0.3955f}, + {-0.9647f, -0.1561f, 0.2120f}, + {-0.6558f, 0.1561f, -0.7386f}, + {-0.4998f, -0.1561f, -0.8520f}, + {0.4998f, 0.1561f, -0.8520f}, + {0.6558f, -0.1561f, -0.7386f}, + {0.9647f, 0.1561f, -0.2120f}, + {0.9051f, -0.1561f, -0.3955f}, + {0.4998f, 0.1561f, 0.8520f}, + {0.6558f, -0.1561f, 0.7386f}, + {-0.6558f, 0.1561f, 0.7386f}, + {-0.4998f, -0.1561f, 0.8520f}, + {-0.9051f, 0.1561f, -0.3955f}, + {-0.9647f, -0.1561f, -0.2120f}, + {0.0965f, 0.1561f, -0.9830f}, + {-0.0965f, -0.1561f, -0.9830f}, + {0.4329f, -0.5168f, 0.7386f}, + {0.0839f, -0.5168f, 0.8520f}, + {-0.5687f, -0.5168f, 0.6399f}, + {-0.7844f, -0.5168f, 0.3431f}, + {-0.7844f, -0.5168f, -0.3431f}, + {-0.5687f, -0.5168f, -0.6399f}, + {0.0839f, -0.5168f, -0.8520f}, + {0.4329f, -0.5168f, -0.7386f}, + {0.8362f, -0.5168f, -0.1835f}, + {0.8362f, -0.5168f, 0.1835f}, + {0.2918f, -0.9327f, 0.2120f}, + {0.5444f, -0.7397f, 0.3955f}, + {-0.1115f, -0.9327f, 0.3431f}, + {-0.2079f, -0.7397f, 0.6399f}, + {-0.3607f, -0.9327f, -0.0000f}, + {-0.6729f, -0.7397f, -0.0000f}, + {-0.1115f, -0.9327f, -0.3431f}, + {-0.2079f, -0.7397f, -0.6399f}, + {0.2918f, -0.9327f, -0.2120f}, + {0.5444f, -0.7397f, -0.3955f}, + {0.4795f, 0.8054f, 0.3484f}, + {-0.1832f, 0.8054f, 0.5637f}, + {-0.5927f, 0.8054f, -0.0000f}, + {-0.1832f, 0.8054f, -0.5637f}, + {0.4795f, 0.8054f, -0.3484f}, + {0.9855f, -0.1699f, 0.0000f}, + {0.3045f, -0.1699f, 0.9372f}, + {-0.7973f, -0.1699f, 0.5792f}, + {-0.7973f, -0.1699f, -0.5792f}, + {0.3045f, -0.1699f, -0.9372f}, + {0.7973f, 0.1699f, 0.5792f}, + {-0.3045f, 0.1699f, 0.9372f}, + {-0.9855f, 0.1699f, -0.0000f}, + {-0.3045f, 0.1699f, -0.9372f}, + {0.7973f, 0.1699f, -0.5792f}, + {0.1832f, -0.8054f, 0.5637f}, + {-0.4795f, -0.8054f, 0.3484f}, + {-0.4795f, -0.8054f, -0.3484f}, + {0.1832f, -0.8054f, -0.5637f}, + {0.5927f, -0.8054f, 0.0000}}; + +WORD du_sphere_faces[DU_SPHERE_NUMFACES * 3] = { + 14, + 12, + 0, + 72, + 13, + 12, + 14, + 72, + 12, + 15, + 72, + 14, + 22, + 1, + 13, + 72, + 22, + 13, + 23, + 22, + 72, + 15, + 23, + 72, + 2, + 23, + 15, + 16, + 14, + 0, + 73, + 15, + 14, + 16, + 73, + 14, + 17, + 73, + 16, + 24, + 2, + 15, + 73, + 24, + 15, + 25, + 24, + 73, + 17, + 25, + 73, + 3, + 25, + 17, + 18, + 16, + 0, + 74, + 17, + 16, + 18, + 74, + 16, + 19, + 74, + 18, + 26, + 3, + 17, + 74, + 26, + 17, + 27, + 26, + 74, + 19, + 27, + 74, + 4, + 27, + 19, + 20, + 18, + 0, + 75, + 19, + 18, + 20, + 75, + 18, + 21, + 75, + 20, + 28, + 4, + 19, + 75, + 28, + 19, + 29, + 28, + 75, + 21, + 29, + 75, + 5, + 29, + 21, + 12, + 20, + 0, + 76, + 21, + 20, + 12, + 76, + 20, + 13, + 76, + 12, + 30, + 5, + 21, + 76, + 30, + 21, + 31, + 30, + 76, + 13, + 31, + 76, + 1, + 31, + 13, + 32, + 42, + 1, + 77, + 43, + 42, + 32, + 77, + 42, + 33, + 77, + 32, + 60, + 10, + 43, + 77, + 60, + 43, + 61, + 60, + 77, + 33, + 61, + 77, + 6, + 61, + 33, + 34, + 44, + 2, + 78, + 45, + 44, + 34, + 78, + 44, + 35, + 78, + 34, + 52, + 6, + 45, + 78, + 52, + 45, + 53, + 52, + 78, + 35, + 53, + 78, + 7, + 53, + 35, + 36, + 46, + 3, + 79, + 47, + 46, + 36, + 79, + 46, + 37, + 79, + 36, + 54, + 7, + 47, + 79, + 54, + 47, + 55, + 54, + 79, + 37, + 55, + 79, + 8, + 55, + 37, + 38, + 48, + 4, + 80, + 49, + 48, + 38, + 80, + 48, + 39, + 80, + 38, + 56, + 8, + 49, + 80, + 56, + 49, + 57, + 56, + 80, + 39, + 57, + 80, + 9, + 57, + 39, + 40, + 50, + 5, + 81, + 51, + 50, + 40, + 81, + 50, + 41, + 81, + 40, + 58, + 9, + 51, + 81, + 58, + 51, + 59, + 58, + 81, + 41, + 59, + 81, + 10, + 59, + 41, + 33, + 45, + 6, + 82, + 44, + 45, + 33, + 82, + 45, + 32, + 82, + 33, + 23, + 2, + 44, + 82, + 23, + 44, + 22, + 23, + 82, + 32, + 22, + 82, + 1, + 22, + 32, + 35, + 47, + 7, + 83, + 46, + 47, + 35, + 83, + 47, + 34, + 83, + 35, + 25, + 3, + 46, + 83, + 25, + 46, + 24, + 25, + 83, + 34, + 24, + 83, + 2, + 24, + 34, + 37, + 49, + 8, + 84, + 48, + 49, + 37, + 84, + 49, + 36, + 84, + 37, + 27, + 4, + 48, + 84, + 27, + 48, + 26, + 27, + 84, + 36, + 26, + 84, + 3, + 26, + 36, + 39, + 51, + 9, + 85, + 50, + 51, + 39, + 85, + 51, + 38, + 85, + 39, + 29, + 5, + 50, + 85, + 29, + 50, + 28, + 29, + 85, + 38, + 28, + 85, + 4, + 28, + 38, + 41, + 43, + 10, + 86, + 42, + 43, + 41, + 86, + 43, + 40, + 86, + 41, + 31, + 1, + 42, + 86, + 31, + 42, + 30, + 31, + 86, + 40, + 30, + 86, + 5, + 30, + 40, + 62, + 64, + 11, + 87, + 65, + 64, + 62, + 87, + 64, + 63, + 87, + 62, + 53, + 7, + 65, + 87, + 53, + 65, + 52, + 53, + 87, + 63, + 52, + 87, + 6, + 52, + 63, + 64, + 66, + 11, + 88, + 67, + 66, + 64, + 88, + 66, + 65, + 88, + 64, + 55, + 8, + 67, + 88, + 55, + 67, + 54, + 55, + 88, + 65, + 54, + 88, + 7, + 54, + 65, + 66, + 68, + 11, + 89, + 69, + 68, + 66, + 89, + 68, + 67, + 89, + 66, + 57, + 9, + 69, + 89, + 57, + 69, + 56, + 57, + 89, + 67, + 56, + 89, + 8, + 56, + 67, + 68, + 70, + 11, + 90, + 71, + 70, + 68, + 90, + 70, + 69, + 90, + 68, + 59, + 10, + 71, + 90, + 59, + 71, + 58, + 59, + 90, + 69, + 58, + 90, + 9, + 58, + 69, + 70, + 62, + 11, + 91, + 63, + 62, + 70, + 91, + 62, + 71, + 91, + 70, + 61, + 6, + 63, + 91, + 61, + 63, + 60, + 61, + 91, + 71, + 60, + 91, + 10, + 60, + 71, +}; + +Fvector du_sphere_verticesl[DU_SPHERE_NUMVERTEXL] = { + {0, -1.0, 0}, + {0.309018f, -0.951056f, 0}, + {0.587786f, -0.809018f, 0}, + {0.809018f, -0.587786f, 0}, + {0.951056f, -0.309018f, 0}, + {1.0, 0, 0}, + {0.951056f, 0.309018f, 0}, + {0.809018f, 0.587786f, 0}, + {0.587786f, 0.809018f, 0}, + {0.309018f, 0.951056f, 0}, + {0, 1.0, 0}, + {-0.309018f, 0.951056f, 0}, + {-0.587786f, 0.809018f, 0}, + {-0.809018f, 0.587786f, 0}, + {-0.951056f, 0.309018f, 0}, + {-1.0, 0, 0}, + {-0.951056f, -0.309018f, 0}, + {-0.809018f, -0.587786f, 0}, + {-0.587786f, -0.809018f, 0}, + {-0.309018f, -0.951056f, 0}, + {1.0, 0, 0}, + {0.951056f, 0, -0.309018f}, + {0.809018f, 0, -0.587786f}, + {0.587786f, 0, -0.809018f}, + {0.309018f, 0, -0.951056f}, + {0, 0, -1.0}, + {-0.309018f, 0, -0.951056f}, + {-0.587786f, 0, -0.809018f}, + {-0.809018f, 0, -0.587786f}, + {-0.951056f, 0, -0.309018f}, + {-1.0, 0, 0}, + {-0.951056f, 0, 0.309018f}, + {-0.809018f, 0, 0.587786f}, + {-0.587786f, 0, 0.809018f}, + {-0.309018f, 0, 0.951056f}, + {0, 0, 1.0}, + {0.309018f, 0, 0.951056f}, + {0.587786f, 0, 0.809018f}, + {0.809018f, 0, 0.587786f}, + {0.951056f, 0, 0.309018f}, + {0, -1.0, 0}, + {0, -0.951056f, -0.309018f}, + {0, -0.809018f, -0.587786f}, + {0, -0.587786f, -0.809018f}, + {0, -0.309018f, -0.951056f}, + {0, 0, -1.0}, + {0, 0.309018f, -0.951056f}, + {0, 0.587786f, -0.809018f}, + {0, 0.809018f, -0.587786f}, + {0, 0.951056f, -0.309018f}, + {0, 1.0, 0}, + {0, 0.951056f, 0.309018f}, + {0, 0.809018f, 0.587786f}, + {0, 0.587786f, 0.809018f}, + {0, 0.309018f, 0.951056f}, + {0, 0, 1.0}, + {0, -0.309018f, 0.951056f}, + {0, -0.587786f, 0.809018f}, + {0, -0.809018f, 0.587786f}, + {0, -0.951056f, 0.309018f}, +}; + +WORD du_sphere_lines[DU_SPHERE_NUMLINES * 2] = { + 0, + 1, + 1, + 2, + 2, + 3, + 3, + 4, + 4, + 5, + 5, + 6, + 6, + 7, + 7, + 8, + 8, + 9, + 9, + 10, + 10, + 11, + 11, + 12, + 12, + 13, + 13, + 14, + 14, + 15, + 15, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + 19, + 0, + + 20, + 21, + 21, + 22, + 22, + 23, + 23, + 24, + 24, + 25, + 25, + 26, + 26, + 27, + 27, + 28, + 28, + 29, + 29, + 30, + 30, + 31, + 31, + 32, + 32, + 33, + 33, + 34, + 34, + 35, + 35, + 36, + 36, + 37, + 37, + 38, + 38, + 39, + 39, + 20, + + 40, + 41, + 41, + 42, + 42, + 43, + 43, + 44, + 44, + 45, + 45, + 46, + 46, + 47, + 47, + 48, + 48, + 49, + 49, + 50, + 50, + 51, + 51, + 52, + 52, + 53, + 53, + 54, + 54, + 55, + 55, + 56, + 56, + 57, + 57, + 58, + 58, + 59, + 59, + 40, +}; diff --git a/src/editors/xrECore/Editor/du_sphere.h b/src/editors/xrECore/Editor/du_sphere.h new file mode 100644 index 00000000000..39c7eb4af1c --- /dev/null +++ b/src/editors/xrECore/Editor/du_sphere.h @@ -0,0 +1,15 @@ +//--------------------------------------------------------------------------- + +#ifndef du_sphereH +#define du_sphereH +//--------------------------------------------------------------------------- +#define DU_SPHERE_NUMVERTEX 92 +#define DU_SPHERE_NUMFACES 180 +#define DU_SPHERE_NUMVERTEXL 60 +#define DU_SPHERE_NUMLINES 60 +extern ECORE_API Fvector du_sphere_vertices[]; +extern ECORE_API WORD du_sphere_faces[]; +extern ECORE_API Fvector du_sphere_verticesl[]; +extern ECORE_API WORD du_sphere_lines[]; + +#endif diff --git a/src/editors/xrECore/Editor/du_sphere_part.cpp b/src/editors/xrECore/Editor/du_sphere_part.cpp new file mode 100644 index 00000000000..e7a8b384009 --- /dev/null +++ b/src/editors/xrECore/Editor/du_sphere_part.cpp @@ -0,0 +1,930 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "du_sphere_part.h" +//--------------------------------------------------------------------------- +#pragma warning(disable : 4305) +Fvector du_sphere_part_vertices[DU_SPHERE_PART_NUMVERTEX] = + { + {-.288675, -.288675, .288675}, + {.288675, -.288675, .288675}, + {-.288675, .288675, .288675}, + {.288675, .288675, .288675}, + {.000000, .000000, .500000}, + {.000000, -.353553, .353553}, + {.353553, .000000, .353553}, + {.000000, .353553, .353553}, + {-.353553, .000000, .353553}, + {-.204124, -.204124, .408248}, + {.204124, -.204124, .408248}, + {.204124, .204124, .408248}, + {-.204124, .204124, .408248}, + {-.166667, -.333333, .333333}, + {.000000, -.223607, .447214}, + {-.223607, .000000, .447214}, + {-.333333, -.166667, .333333}, + {.333333, -.166667, .333333}, + {.223607, .000000, .447214}, + {.166667, -.333333, .333333}, + {.166667, .333333, .333333}, + {.000000, .223607, .447214}, + {.333333, .166667, .333333}, + {-.333333, .166667, .333333}, + {-.166667, .333333, .333333}, + {-.257248, -.257248, .342997}, + {-.098058, -.294174, .392232}, + {-.117851, -.117851, .471405}, + {-.294174, -.098058, .392232}, + {.257248, -.257248, .342997}, + {.294174, -.098058, .392232}, + {.117851, -.117851, .471405}, + {.098058, -.294174, .392232}, + {.257248, .257248, .342997}, + {.098058, .294174, .392232}, + {.117851, .117851, .471405}, + {.294174, .098058, .392232}, + {-.257248, .257248, .342997}, + {-.294174, .098058, .392232}, + {-.117851, .117851, .471405}, + {-.098058, .294174, .392232}, + {-.234261, -.312348, .312348}, + {-.185695, -.278543, .371391}, + {-.278543, -.185695, .371391}, + {-.312348, -.234261, .312348}, + {.000000, -.300000, .400000}, + {-.109109, -.218218, .436436}, + {-.087039, -.348155, .348155}, + {-.121268, .000000, .485071}, + {-.218218, -.109109, .436436}, + {.000000, -.121268, .485071}, + {-.348155, -.087039, .348155}, + {-.300000, .000000, .400000}, + {.312348, -.234261, .312348}, + {.278543, -.185695, .371391}, + {.185695, -.278543, .371391}, + {.234261, -.312348, .312348}, + {.300000, .000000, .400000}, + {.218218, -.109109, .436436}, + {.348155, -.087039, .348155}, + {.109109, -.218218, .436436}, + {.121268, .000000, .485071}, + {.087039, -.348155, .348155}, + {.234261, .312348, .312348}, + {.185695, .278543, .371391}, + {.278543, .185695, .371391}, + {.312348, .234261, .312348}, + {.000000, .300000, .400000}, + {.109109, .218218, .436436}, + {.087039, .348155, .348155}, + {.218218, .109109, .436436}, + {.000000, .121268, .485071}, + {.348155, .087039, .348155}, + {-.312348, .234261, .312348}, + {-.278543, .185695, .371391}, + {-.185695, .278543, .371391}, + {-.234261, .312348, .312348}, + {-.218218, .109109, .436436}, + {-.348155, .087039, .348155}, + {-.109109, .218218, .436436}, + {-.087039, .348155, .348155}, + {.000000, .000000, .000000}}; +u16 du_sphere_part_faces[DU_SPHERE_PART_NUMFACES * 3] = + { + 0, + 41, + 25, + 25, + 44, + 0, + 13, + 42, + 25, + 25, + 41, + 13, + 9, + 43, + 25, + 25, + 42, + 9, + 16, + 44, + 25, + 25, + 43, + 16, + 5, + 45, + 26, + 26, + 47, + 5, + 14, + 46, + 26, + 26, + 45, + 14, + 9, + 42, + 26, + 26, + 46, + 9, + 13, + 47, + 26, + 26, + 42, + 13, + 4, + 48, + 27, + 27, + 50, + 4, + 15, + 49, + 27, + 27, + 48, + 15, + 9, + 46, + 27, + 27, + 49, + 9, + 14, + 50, + 27, + 27, + 46, + 14, + 8, + 51, + 28, + 28, + 52, + 8, + 16, + 43, + 28, + 28, + 51, + 16, + 9, + 49, + 28, + 28, + 43, + 9, + 15, + 52, + 28, + 28, + 49, + 15, + 1, + 53, + 29, + 29, + 56, + 1, + 17, + 54, + 29, + 29, + 53, + 17, + 10, + 55, + 29, + 29, + 54, + 10, + 19, + 56, + 29, + 29, + 55, + 19, + 6, + 57, + 30, + 30, + 59, + 6, + 18, + 58, + 30, + 30, + 57, + 18, + 10, + 54, + 30, + 30, + 58, + 10, + 17, + 59, + 30, + 30, + 54, + 17, + 4, + 50, + 31, + 31, + 61, + 4, + 14, + 60, + 31, + 31, + 50, + 14, + 10, + 58, + 31, + 31, + 60, + 10, + 18, + 61, + 31, + 31, + 58, + 18, + 5, + 62, + 32, + 32, + 45, + 5, + 19, + 55, + 32, + 32, + 62, + 19, + 10, + 60, + 32, + 32, + 55, + 10, + 14, + 45, + 32, + 32, + 60, + 14, + 3, + 63, + 33, + 33, + 66, + 3, + 20, + 64, + 33, + 33, + 63, + 20, + 11, + 65, + 33, + 33, + 64, + 11, + 22, + 66, + 33, + 33, + 65, + 22, + 7, + 67, + 34, + 34, + 69, + 7, + 21, + 68, + 34, + 34, + 67, + 21, + 11, + 64, + 34, + 34, + 68, + 11, + 20, + 69, + 34, + 34, + 64, + 20, + 4, + 61, + 35, + 35, + 71, + 4, + 18, + 70, + 35, + 35, + 61, + 18, + 11, + 68, + 35, + 35, + 70, + 11, + 21, + 71, + 35, + 35, + 68, + 21, + 6, + 72, + 36, + 36, + 57, + 6, + 22, + 65, + 36, + 36, + 72, + 22, + 11, + 70, + 36, + 36, + 65, + 11, + 18, + 57, + 36, + 36, + 70, + 18, + 2, + 73, + 37, + 37, + 76, + 2, + 23, + 74, + 37, + 37, + 73, + 23, + 12, + 75, + 37, + 37, + 74, + 12, + 24, + 76, + 37, + 37, + 75, + 24, + 8, + 52, + 38, + 38, + 78, + 8, + 15, + 77, + 38, + 38, + 52, + 15, + 12, + 74, + 38, + 38, + 77, + 12, + 23, + 78, + 38, + 38, + 74, + 23, + 4, + 71, + 39, + 39, + 48, + 4, + 21, + 79, + 39, + 39, + 71, + 21, + 12, + 77, + 39, + 39, + 79, + 12, + 15, + 48, + 39, + 39, + 77, + 15, + 7, + 80, + 40, + 40, + 67, + 7, + 24, + 75, + 40, + 40, + 80, + 24, + 12, + 79, + 40, + 40, + 75, + 12, + 21, + 67, + 40, + 40, + 79, + 21, + 41, + 0, + 81, + 0, + 44, + 81, + 13, + 41, + 81, + 44, + 16, + 81, + 5, + 47, + 81, + 47, + 13, + 81, + 51, + 8, + 81, + 16, + 51, + 81, + 53, + 1, + 81, + 1, + 56, + 81, + 17, + 53, + 81, + 56, + 19, + 81, + 6, + 59, + 81, + 59, + 17, + 81, + 62, + 5, + 81, + 19, + 62, + 81, + 63, + 3, + 81, + 3, + 66, + 81, + 20, + 63, + 81, + 66, + 22, + 81, + 7, + 69, + 81, + 69, + 20, + 81, + 72, + 6, + 81, + 22, + 72, + 81, + 73, + 2, + 81, + 2, + 76, + 81, + 23, + 73, + 81, + 76, + 24, + 81, + 8, + 78, + 81, + 78, + 23, + 81, + 80, + 7, + 81, + 24, + 80, + 81, +}; + +u16 du_sphere_part_lines[DU_SPHERE_PART_NUMLINES * 2] = + { + 0, + 41, + 0, + 44, + 0, + 81, + 1, + 53, + 1, + 56, + 1, + 81, + 2, + 73, + 2, + 76, + 2, + 81, + 3, + 63, + 3, + 66, + 3, + 81, + 4, + 48, + 4, + 50, + 4, + 61, + 4, + 71, + 5, + 45, + 5, + 47, + 5, + 62, + 5, + 81, + 6, + 57, + 6, + 59, + 6, + 72, + 6, + 81, + 7, + 67, + 7, + 69, + 7, + 80, + 7, + 81, + 8, + 51, + 8, + 52, + 8, + 78, + 8, + 81, + 9, + 42, + 9, + 43, + 9, + 46, + 9, + 49, + 10, + 54, + 10, + 55, + 10, + 58, + 10, + 60, + 11, + 64, + 11, + 65, + 11, + 68, + 11, + 70, + 12, + 74, + 12, + 75, + 12, + 77, + 12, + 79, + 13, + 41, + 13, + 42, + 13, + 47, + 13, + 81, + 14, + 45, + 14, + 46, + 14, + 50, + 14, + 60, + 15, + 48, + 15, + 49, + 15, + 52, + 15, + 77, + 16, + 43, + 16, + 44, + 16, + 51, + 16, + 81, + 17, + 53, + 17, + 54, + 17, + 59, + 17, + 81, + 18, + 57, + 18, + 58, + 18, + 61, + 18, + 70, + 19, + 55, + 19, + 56, + 19, + 62, + 19, + 81, + 20, + 63, + 20, + 64, + 20, + 69, + 20, + 81, + 21, + 67, + 21, + 68, + 21, + 71, + 21, + 79, + 22, + 65, + 22, + 66, + 22, + 72, + 22, + 81, + 23, + 73, + 23, + 74, + 23, + 78, + 23, + 81, + 24, + 75, + 24, + 76, + 24, + 80, + 24, + 81, + 25, + 41, + 25, + 42, + 25, + 43, + 25, + 44, + 26, + 42, + 26, + 45, + 26, + 46, + 26, + 47, + 27, + 46, + 27, + 48, + 27, + 49, + 27, + 50, + 28, + 43, + 28, + 49, + 28, + 51, + 28, + 52, + 29, + 53, + 29, + 54, + 29, + 55, + 29, + 56, + 30, + 54, + 30, + 57, + 30, + 58, + 30, + 59, + 31, + 50, + 31, + 58, + 31, + 60, + 31, + 61, + 32, + 45, + 32, + 55, + 32, + 60, + 32, + 62, + 33, + 63, + 33, + 64, + 33, + 65, + 33, + 66, + 34, + 64, + 34, + 67, + 34, + 68, + 34, + 69, + 35, + 61, + 35, + 68, + 35, + 70, + 35, + 71, + 36, + 57, + 36, + 65, + 36, + 70, + 36, + 72, + 37, + 73, + 37, + 74, + 37, + 75, + 37, + 76, + 38, + 52, + 38, + 74, + 38, + 77, + 38, + 78, + 39, + 48, + 39, + 71, + 39, + 77, + 39, + 79, + 40, + 67, + 40, + 75, + 40, + 79, + 40, + 80, + 41, + 81, + 44, + 81, + 47, + 81, + 51, + 81, + 53, + 81, + 56, + 81, + 59, + 81, + 62, + 81, + 63, + 81, + 66, + 81, + 69, + 81, + 72, + 81, + 73, + 81, + 76, + 81, + 78, + 81, + 80, + 81, +}; diff --git a/src/editors/xrECore/Editor/du_sphere_part.h b/src/editors/xrECore/Editor/du_sphere_part.h new file mode 100644 index 00000000000..da6c0f418e8 --- /dev/null +++ b/src/editors/xrECore/Editor/du_sphere_part.h @@ -0,0 +1,13 @@ +//--------------------------------------------------------------------------- + +#ifndef du_sphere_partH +#define du_sphere_partH +//--------------------------------------------------------------------------- +#define DU_SPHERE_PART_NUMVERTEX 82 +#define DU_SPHERE_PART_NUMFACES 160 +#define DU_SPHERE_PART_NUMLINES 176 + +extern ECORE_API Fvector du_sphere_part_vertices[]; +extern ECORE_API u16 du_sphere_part_faces[]; +extern ECORE_API u16 du_sphere_part_lines[]; +#endif diff --git a/src/editors/xrECore/Editor/engine.h b/src/editors/xrECore/Editor/engine.h new file mode 100644 index 00000000000..172d1de003a --- /dev/null +++ b/src/editors/xrECore/Editor/engine.h @@ -0,0 +1,36 @@ +// Engine.h: interface for the CEngine class. +// +////////////////////////////////////////////////////////////////////// + +#if !defined(AFX_ENGINE_H__22802DD7_D7EB_4234_9781_E237657471AC__INCLUDED_) +#define AFX_ENGINE_H__22802DD7_D7EB_4234_9781_E237657471AC__INCLUDED_ +#pragma once + +#include "ELog.h" +//#include "../../xrCPU_Pipe/xrCPU_Pipe.h" + +// TODO: this should be in render configuration +#define R__NUM_SUN_CASCADES (3u) // csm/s.ligts +#define R__NUM_AUX_CONTEXTS (1u) // rain/s.lights +#define R__NUM_PARALLEL_CONTEXTS (R__NUM_SUN_CASCADES + R__NUM_AUX_CONTEXTS) +#define R__NUM_CONTEXTS (R__NUM_PARALLEL_CONTEXTS + 1/* imm */) + +class ENGINE_API CEngine +{ + HMODULE hPSGP; + +public: + CEngine(); + ~CEngine(); + + void Initialize(); + void Destroy(); + LPCSTR LastWindowsError(); + + void ReloadSettings(); +}; + +//ENGINE_API extern xrDispatchTable PSGP; +ENGINE_API extern CEngine Engine; + +#endif // !defined(AFX_ENGINE_H__22802DD7_D7EB_4234_9781_E237657471AC__INCLUDED_) diff --git a/src/editors/xrECore/Editor/face_smoth_flags.h b/src/editors/xrECore/Editor/face_smoth_flags.h new file mode 100644 index 00000000000..8ffd12a6241 --- /dev/null +++ b/src/editors/xrECore/Editor/face_smoth_flags.h @@ -0,0 +1,59 @@ +#ifndef _FACE_SMOTH_FLAGS_H_ +#define _FACE_SMOTH_FLAGS_H_ +enum +{ + backface_flag = 1 << 3 +}; + +IC bool is_backface(u32 face_flags) +{ + return !!(face_flags & backface_flag); +} + +IC void set_backface(u32 &face_flags, bool value) +{ + if (value) + face_flags |= backface_flag; + else + face_flags &= ~backface_flag; +} + +IC u16 convert_edge_index(u32 face_flags, u16 edge_index) +{ + VERIFY(edge_index >= 0 && edge_index <= 2); + if (is_backface(face_flags)) + return (4 - edge_index) % 3; + else + return edge_index; +} + +IC bool is_soft_edge(u32 face_flags, u16 edge_index) +{ + edge_index = convert_edge_index(face_flags, edge_index); + VERIFY(edge_index >= 0 && edge_index <= 2); + return !(face_flags & (1 << edge_index)); +} + +IC void set_soft_edge(u32 &face_flags, u16 edge_index, bool value) +{ + edge_index = convert_edge_index(face_flags, edge_index); + VERIFY(edge_index >= 0 && edge_index <= 2); + if (value) + face_flags &= ~(1 << edge_index); + else + face_flags |= (1 << edge_index); +} + +IC bool do_connect_faces_by_faces_edge_flags(u32 start_face_flags, u32 test_face_flags, u16 start_common_edge_idx, u16 test_common_edge_idx) +{ + bool start_edge_back = is_backface(start_face_flags); + bool test_edge_back = is_backface(test_face_flags); + if (start_edge_back != test_edge_back) + return false; + + bool start_edge_smooth = is_soft_edge(start_face_flags, start_common_edge_idx); //!( start.sm_group & (1< +class itterate_adjacents +{ + + typedef typename itterate_adjacents_params::type_vertex type_vertex; + typedef typename itterate_adjacents_params::type_face type_face; + +public: + typedef itterate_adjacents_params recurse_tri_params; + + static void RecurseTri(u32 start_face_idx, recurse_tri_params &p) + { + + for (u32 test_face_idx = 0; test_face_idx < p.current_adjacents_size(); ++test_face_idx) + { + if (p.add_adjacents(start_face_idx, test_face_idx)) + RecurseTri(test_face_idx, p); + } + } +}; + +#endif \ No newline at end of file diff --git a/src/editors/xrECore/Editor/itterate_adjacents_dynamic.h b/src/editors/xrECore/Editor/itterate_adjacents_dynamic.h new file mode 100644 index 00000000000..54e4ab38409 --- /dev/null +++ b/src/editors/xrECore/Editor/itterate_adjacents_dynamic.h @@ -0,0 +1,141 @@ +#pragma once + +template +struct itterate_adjacents_params_dynamic +{ + typedef typeVertex type_vertex; + typedef typename typeVertex::type_face type_face; + // typedef xr_vector vecFace; + +private: + Fvector &normal; + const u32 *m_SmoothGroups; + const Fvector *m_FaceNormals; + const IntVec &a_lst; + const type_face *m_Faces; + u32 m_FaceCount; + U8Vec m_procesed; + +public: + itterate_adjacents_params_dynamic( + + Fvector &_normal, + const u32 *_SmoothGroups, + const Fvector *_FaceNormals, + const IntVec &_a_lst, + const type_face *_Faces, + u32 _FaceCount) : + + normal(_normal), + m_SmoothGroups(_SmoothGroups), + m_FaceNormals(_FaceNormals), + a_lst(_a_lst), + m_Faces(_Faces), + m_FaceCount(_FaceCount) + + { + normal.set(0, 0, 0); + m_procesed.resize(a_lst.size(), 0); + } + IC const u32 current_adjacents_size() const + { + return u32(a_lst.size()); + } + +private: + IC static bool has_same_edge(const type_face *F1, const type_face *F2, u16 &F1_edge_index, u16 &F2_edge_index) + { + F1_edge_index = u16(-1); + F2_edge_index = u16(-1); + + for (int e = 0; e < 3; e++) + { + type_vertex v1_a, v1_b; + F1->EdgeVerts(e, v1_a, v1_b); + if (v1_a.gt(v1_b)) + std::swap(v1_a, v1_b); + + for (int r = 0; r < 3; ++r) + { + type_vertex v2_a, v2_b; + F2->EdgeVerts(r, v2_a, v2_b); + if (v2_a.gt(v2_b)) + std::swap(v2_a, v2_b); + + if ((v1_a.eq(v2_a)) && (v1_b.eq(v2_b))) + { + F1_edge_index = e; + F2_edge_index = r; + return true; + } + } + } + return false; + } + IC u32 face_idx(u32 adj_idx) const + { + VERIFY(adj_idx < a_lst.size()); + return a_lst[adj_idx]; + } + IC const type_face *current_adjacents_face(u32 adj_idx) const + { + + VERIFY(m_Faces); + u32 index = face_idx(adj_idx); + VERIFY(index < m_FaceCount); + return &m_Faces[index]; + } + + IC bool do_connect_faces(u32 start_face_idx, u32 test_face_idx, u16 start_common_edge_idx, u16 test_common_edge_idx) + { + VERIFY(start_face_idx < m_FaceCount); + VERIFY(test_face_idx < m_FaceCount); + return do_connect_faces_by_faces_edge_flags(m_SmoothGroups[start_face_idx], m_SmoothGroups[test_face_idx], start_common_edge_idx, test_common_edge_idx); + } + + IC bool is_processed(u32 adj_idx) const + { + VERIFY(adj_idx < a_lst.size()); + return !!m_procesed[adj_idx]; + } + + IC void set_processed(u32 adj_idx) + { + VERIFY(adj_idx < a_lst.size()); + m_procesed[adj_idx] = u8(1); + } + + IC void add_adjacents(u32 test_face_idx) + { + VERIFY(test_face_idx < m_FaceCount); + + normal.add(m_FaceNormals[test_face_idx]); + } + +public: + IC bool add_adjacents(u32 start_face_adj_idx, u32 test_face_adj_idx) + { + if (is_processed(test_face_adj_idx)) + return false; + + const type_face *start_face = current_adjacents_face(start_face_adj_idx); + const type_face *test_face = current_adjacents_face(test_face_adj_idx); + + u32 test_face_idx = face_idx(test_face_adj_idx); + u32 start_face_idx = face_idx(start_face_adj_idx); + + u16 StartFace_common_edge_index = u16(-1); + u16 TestFace_common_edge_index = u16(-1); + + if (has_same_edge(start_face, test_face, StartFace_common_edge_index, TestFace_common_edge_index)) + { + if ((start_face_idx == test_face_idx) || do_connect_faces(start_face_idx, test_face_idx, StartFace_common_edge_index, TestFace_common_edge_index)) + { + set_processed(test_face_adj_idx); + add_adjacents(test_face_idx); + return true; + } + } + return false; + } +}; diff --git a/src/editors/xrECore/Editor/lwo2.h b/src/editors/xrECore/Editor/lwo2.h new file mode 100644 index 00000000000..0c5281c71bf --- /dev/null +++ b/src/editors/xrECore/Editor/lwo2.h @@ -0,0 +1,683 @@ +/* +====================================================================== +lwo2.h + +Definitions and typedefs for LWO2 files. + +Ernie Wright 17 Sep 00 +====================================================================== */ + +#ifndef LWO2_H +#define LWO2_H + +/* chunk and subchunk IDs */ + +#ifndef LWID_ +#define LWID_(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d)) +#endif + +#define ID_FORM LWID_('F', 'O', 'R', 'M') +#define ID_LWO2 LWID_('L', 'W', 'O', '2') +#define ID_LWOB LWID_('L', 'W', 'O', 'B') + +/* top-level chunks */ +#define ID_LAYR LWID_('L', 'A', 'Y', 'R') +#define ID_TAGS LWID_('T', 'A', 'G', 'S') +#define ID_PNTS LWID_('P', 'N', 'T', 'S') +#define ID_BBOX LWID_('B', 'B', 'O', 'X') +#define ID_VMAP LWID_('V', 'M', 'A', 'P') +#define ID_VMAD LWID_('V', 'M', 'A', 'D') +#define ID_POLS LWID_('P', 'O', 'L', 'S') +#define ID_PTAG LWID_('P', 'T', 'A', 'G') +#define ID_ENVL LWID_('E', 'N', 'V', 'L') +#define ID_CLIP LWID_('C', 'L', 'I', 'P') +#define ID_SURF LWID_('S', 'U', 'R', 'F') +#define ID_DESC LWID_('D', 'E', 'S', 'C') +#define ID_TEXT LWID_('T', 'E', 'X', 'T') +#define ID_ICON LWID_('I', 'C', 'O', 'N') + +/* polygon types */ +#define ID_FACE LWID_('F', 'A', 'C', 'E') +#define ID_CURV LWID_('C', 'U', 'R', 'V') +#define ID_PTCH LWID_('P', 'T', 'C', 'H') +#define ID_MBAL LWID_('M', 'B', 'A', 'L') +#define ID_BONE LWID_('B', 'O', 'N', 'E') + +/* polygon tags */ +#define ID_SURF LWID_('S', 'U', 'R', 'F') +#define ID_PART LWID_('P', 'A', 'R', 'T') +#define ID_SMGP LWID_('S', 'M', 'G', 'P') + +/* envelopes */ +#define ID_PRE LWID_('P', 'R', 'E', ' ') +#define ID_POST LWID_('P', 'O', 'S', 'T') +#define ID_KEY LWID_('K', 'E', 'Y', ' ') +#define ID_SPAN LWID_('S', 'P', 'A', 'N') +#define ID_TCB LWID_('T', 'C', 'B', ' ') +#define ID_HERM LWID_('H', 'E', 'R', 'M') +#define ID_BEZI LWID_('B', 'E', 'Z', 'I') +#define ID_BEZ2 LWID_('B', 'E', 'Z', '2') +#define ID_LINE LWID_('L', 'I', 'N', 'E') +#define ID_STEP LWID_('S', 'T', 'E', 'P') + +/* clips */ +#define ID_STIL LWID_('S', 'T', 'I', 'L') +#define ID_ISEQ LWID_('I', 'S', 'E', 'Q') +#define ID_ANIM LWID_('A', 'N', 'I', 'M') +#define ID_XREF LWID_('X', 'R', 'E', 'F') +#define ID_STCC LWID_('S', 'T', 'C', 'C') +#define ID_TIME LWID_('T', 'I', 'M', 'E') +#define ID_CONT LWID_('C', 'O', 'N', 'T') +#define ID_BRIT LWID_('B', 'R', 'I', 'T') +#define ID_SATR LWID_('S', 'A', 'T', 'R') +#define ID_HUE LWID_('H', 'U', 'E', ' ') +#define ID_GAMM LWID_('G', 'A', 'M', 'M') +#define ID_NEGA LWID_('N', 'E', 'G', 'A') +#define ID_IFLT LWID_('I', 'F', 'L', 'T') +#define ID_PFLT LWID_('P', 'F', 'L', 'T') + +/* surfaces */ +#define ID_COLR LWID_('C', 'O', 'L', 'R') +#define ID_LUMI LWID_('L', 'U', 'M', 'I') +#define ID_DIFF LWID_('D', 'I', 'F', 'F') +#define ID_SPEC LWID_('S', 'P', 'E', 'C') +#define ID_GLOS LWID_('G', 'L', 'O', 'S') +#define ID_REFL LWID_('R', 'E', 'F', 'L') +#define ID_RFOP LWID_('R', 'F', 'O', 'P') +#define ID_RIMG LWID_('R', 'I', 'M', 'G') +#define ID_RSAN LWID_('R', 'S', 'A', 'N') +#define ID_TRAN LWID_('T', 'R', 'A', 'N') +#define ID_TROP LWID_('T', 'R', 'O', 'P') +#define ID_TIMG LWID_('T', 'I', 'M', 'G') +#define ID_RIND LWID_('R', 'I', 'N', 'D') +#define ID_TRNL LWID_('T', 'R', 'N', 'L') +#define ID_BUMP LWID_('B', 'U', 'M', 'P') +#define ID_SMAN LWID_('S', 'M', 'A', 'N') +#define ID_SIDE LWID_('S', 'I', 'D', 'E') +#define ID_CLRH LWID_('C', 'L', 'R', 'H') +#define ID_CLRF LWID_('C', 'L', 'R', 'F') +#define ID_ADTR LWID_('A', 'D', 'T', 'R') +#define ID_SHRP LWID_('S', 'H', 'R', 'P') +#define ID_LINE LWID_('L', 'I', 'N', 'E') +#define ID_LSIZ LWID_('L', 'S', 'I', 'Z') +#define ID_ALPH LWID_('A', 'L', 'P', 'H') +#define ID_AVAL LWID_('A', 'V', 'A', 'L') +#define ID_GVAL LWID_('G', 'V', 'A', 'L') +#define ID_BLOK LWID_('B', 'L', 'O', 'K') + +/* texture layer */ +#define ID_TYPE LWID_('T', 'Y', 'P', 'E') +#define ID_CHAN LWID_('C', 'H', 'A', 'N') +#define ID_NAME LWID_('N', 'A', 'M', 'E') +#define ID_ENAB LWID_('E', 'N', 'A', 'B') +#define ID_OPAC LWID_('O', 'P', 'A', 'C') +#define ID_FLAG LWID_('F', 'L', 'A', 'G') +#define ID_PROJ LWID_('P', 'R', 'O', 'J') +#define ID_STCK LWID_('S', 'T', 'C', 'K') +#define ID_TAMP LWID_('T', 'A', 'M', 'P') + +/* texture coordinates */ +#define ID_TMAP LWID_('T', 'M', 'A', 'P') +#define ID_AXIS LWID_('A', 'X', 'I', 'S') +#define ID_CNTR LWID_('C', 'N', 'T', 'R') +#define ID_SIZE LWID_('S', 'I', 'Z', 'E') +#define ID_ROTA LWID_('R', 'O', 'T', 'A') +#define ID_OREF LWID_('O', 'R', 'E', 'F') +#define ID_FALL LWID_('F', 'A', 'L', 'L') +#define ID_CSYS LWID_('C', 'S', 'Y', 'S') + +/* image map */ +#define ID_IMAP LWID_('I', 'M', 'A', 'P') +#define ID_IMAG LWID_('I', 'M', 'A', 'G') +#define ID_WRAP LWID_('W', 'R', 'A', 'P') +#define ID_WRPW LWID_('W', 'R', 'P', 'W') +#define ID_WRPH LWID_('W', 'R', 'P', 'H') +#define ID_VMAP LWID_('V', 'M', 'A', 'P') +#define ID_AAST LWID_('A', 'A', 'S', 'T') +#define ID_PIXB LWID_('P', 'I', 'X', 'B') + +/* procedural */ +#define ID_PROC LWID_('P', 'R', 'O', 'C') +#define ID_COLR LWID_('C', 'O', 'L', 'R') +#define ID_VALU LWID_('V', 'A', 'L', 'U') +#define ID_FUNC LWID_('F', 'U', 'N', 'C') +#define ID_FTPS LWID_('F', 'T', 'P', 'S') +#define ID_ITPS LWID_('I', 'T', 'P', 'S') +#define ID_ETPS LWID_('E', 'T', 'P', 'S') + +/* gradient */ +#define ID_GRAD LWID_('G', 'R', 'A', 'D') +#define ID_GRST LWID_('G', 'R', 'S', 'T') +#define ID_GREN LWID_('G', 'R', 'E', 'N') +#define ID_PNAM LWID_('P', 'N', 'A', 'M') +#define ID_INAM LWID_('I', 'N', 'A', 'M') +#define ID_GRPT LWID_('G', 'R', 'P', 'T') +#define ID_FKEY LWID_('F', 'K', 'E', 'Y') +#define ID_IKEY LWID_('I', 'K', 'E', 'Y') + +/* shader */ +#define ID_SHDR LWID_('S', 'H', 'D', 'R') +#define ID_DATA LWID_('D', 'A', 'T', 'A') + +/* + * VMAPs are identifed by an extensible set of ID codes. Some common + * ones are included here. + */ +#define ID_PICK LWID_('P', 'I', 'C', 'K') +#define ID_WGHT LWID_('W', 'G', 'H', 'T') +#define ID_MNVW LWID_('M', 'N', 'V', 'W') +#define ID_TXUV LWID_('T', 'X', 'U', 'V') +#define ID_MORF LWID_('M', 'O', 'R', 'F') +#define ID_SPOT LWID_('S', 'P', 'O', 'T') +#define ID_RGB LWID_('R', 'G', 'B', ' ') +#define ID_RGBA LWID_('R', 'G', 'B', 'A') + +/* generic linked list */ + +typedef struct st_lwNode +{ + struct st_lwNode *next, *prev; + void *data; +} lwNode; + +/* plug-in reference */ + +typedef struct st_lwPlugin +{ + struct st_lwPlugin *next, *prev; + char *ord; + char *name; + int flags; + void *data; +} lwPlugin; + +/* envelopes */ + +typedef struct st_lwKey +{ + struct st_lwKey *next, *prev; + float value; + float time; + unsigned int shape; /* ID_TCB, ID_BEZ2, etc. */ + float tension; + float continuity; + float bias; + float param[4]; +} lwKey; + +typedef struct st_lwEnvelope +{ + struct st_lwEnvelope *next, *prev; + int index; + int type; + char *name; + lwKey *key; /* linked list of keys */ + int nkeys; + int behavior[2]; /* pre and post (extrapolation) */ + lwPlugin *cfilter; /* linked list of channel filters */ + int ncfilters; +} lwEnvelope; + +#define BEH_RESET 0 +#define BEH_CONSTANT 1 +#define BEH_REPEAT 2 +#define BEH_OSCILLATE 3 +#define BEH_OFFSET 4 +#define BEH_LINEAR 5 + +/* values that can be enveloped */ + +typedef struct st_lwEParam +{ + float val; + int eindex; +} lwEParam; + +typedef struct st_lwVParam +{ + float val[3]; + int eindex; +} lwVParam; + +/* clips */ + +typedef struct st_lwClipStill +{ + char *name; +} lwClipStill; + +typedef struct st_lwClipSeq +{ + char *prefix; /* filename before sequence digits */ + char *suffix; /* after digits, e.g. extensions */ + int digits; + int flags; + int offset; + int start; + int end; +} lwClipSeq; + +typedef struct st_lwClipAnim +{ + char *name; + char *server; /* anim loader plug-in */ + void *data; +} lwClipAnim; + +typedef struct st_lwClipXRef +{ + char *string; + int index; + struct st_Clip *clip; +} lwClipXRef; + +typedef struct st_lwClipCycle +{ + char *name; + int lo; + int hi; +} lwClipCycle; + +typedef struct st_lwClip +{ + struct st_lwClip *next, *prev; + int index; + unsigned int type; /* ID_STIL, ID_ISEQ, etc. */ + union + { + lwClipStill still; + lwClipSeq seq; + lwClipAnim anim; + lwClipXRef xref; + lwClipCycle cycle; + } source; + float start_time; + float duration; + float frame_rate; + lwEParam contrast; + lwEParam brightness; + lwEParam saturation; + lwEParam hue; + lwEParam gamma; + int negative; + lwPlugin *ifilter; /* linked list of image filters */ + int nifilters; + lwPlugin *pfilter; /* linked list of pixel filters */ + int npfilters; +} lwClip; + +/* textures */ + +typedef struct st_lwTMap +{ + lwVParam size; + lwVParam center; + lwVParam rotate; + lwVParam falloff; + int fall_type; + char *ref_object; + int coord_sys; +} lwTMap; + +typedef struct st_lwImageMap +{ + int cindex; + int projection; + char *vmap_name; + int axis; + int wrapw_type; + int wraph_type; + lwEParam wrapw; + lwEParam wraph; + float aa_strength; + int aas_flags; + int pblend; + lwEParam stck; + lwEParam amplitude; +} lwImageMap; + +#define PROJ_PLANAR 0 +#define PROJ_CYLINDRICAL 1 +#define PROJ_SPHERICAL 2 +#define PROJ_CUBIC 3 +#define PROJ_FRONT 4 + +#define WRAP_NONE 0 +#define WRAP_EDGE 1 +#define WRAP_REPEAT 2 +#define WRAP_MIRROR 3 + +typedef struct st_lwProcedural +{ + int axis; + float value[3]; + char *name; + void *data; +} lwProcedural; + +typedef struct st_lwGradKey +{ + struct st_lwGradKey *next, *prev; + float value; + float rgba[4]; +} lwGradKey; + +typedef struct st_lwGradient +{ + char *paramname; + char *itemname; + float start; + float end; + int repeat; + lwGradKey *key; /* array of gradient keys */ + short *ikey; /* array of interpolation codes */ +} lwGradient; + +typedef struct st_lwTexture +{ + struct st_lwTexture *next, *prev; + char *ord; + unsigned int type; + unsigned int chan; + lwEParam opacity; + short opac_type; + short enabled; + short negative; + short axis; + union + { + lwImageMap imap; + lwProcedural proc; + lwGradient grad; + } param; + lwTMap tmap; +} lwTexture; + +/* values that can be textured */ + +typedef struct st_lwTParam +{ + float val; + int eindex; + lwTexture *tex; /* linked list of texture layers */ +} lwTParam; + +typedef struct st_lwCParam +{ + float rgb[3]; + int eindex; + lwTexture *tex; /* linked list of texture layers */ +} lwCParam; + +/* surfaces */ +typedef struct st_lwGlow +{ + short enabled; + short type; + lwEParam intensity; + lwEParam size; +} Glow; + +typedef struct st_lwRMap +{ + lwTParam val; + int options; + int cindex; + float seam_angle; +} lwRMap; + +typedef struct st_lwLine +{ + short enabled; + unsigned short flags; + lwEParam size; +} lwLine; + +typedef struct st_lwSurface +{ + struct st_lwSurface *next, *prev; + char *name; + char *srcname; + lwCParam color; + lwTParam luminosity; + lwTParam diffuse; + lwTParam specularity; + lwTParam glossiness; + lwRMap reflection; + lwRMap transparency; + lwTParam eta; + lwTParam translucency; + lwTParam bump; + float smooth; + int sideflags; + float alpha; + int alpha_mode; + lwEParam color_hilite; + lwEParam color_filter; + lwEParam add_trans; + lwEParam dif_sharp; + lwEParam glow; + lwLine line; + lwPlugin *shader; /* linked list of shaders */ + int nshaders; +} lwSurface; + +/* vertex maps */ +typedef struct st_lwVMap +{ + struct st_lwVMap *next, *prev; + char *name; + unsigned int type; + int dim; + int nverts; + int perpoly; + int *vindex; /* array of point indexes */ + int *pindex; /* array of polygon indexes */ + float **val; +} lwVMap; + +typedef struct st_lwVMapPt +{ + lwVMap *vmap; + int index; /* vindex or pindex element */ +} lwVMapPt; + +/* points and polygons */ +typedef struct st_lwPoint +{ + float pos[3]; + int npols; /* number of polygons sharing the point */ + int *pol; /* array of polygon indexes */ + int nvmaps; + lwVMapPt *vm; /* array of vmap references */ +} lwPoint; + +typedef struct st_lwPolVert +{ + int index; /* index into the point array */ + float norm[3]; + int nvmaps; + lwVMapPt *vm; /* array of vmap references */ +} lwPolVert; + +typedef struct st_lwPolygon +{ + lwSurface *surf; + int part; /* part index */ + int smoothgrp; /* smoothing group */ + int flags; + unsigned int type; + float norm[3]; + int nverts; + lwPolVert *v; /* array of vertex records */ +} lwPolygon; + +typedef struct st_lwPointList +{ + int count; + int offset; /* only used during reading */ + lwPoint *pt; /* array of points */ +} lwPointList; + +typedef struct st_lwPolygonList +{ + int count; + int offset; /* only used during reading */ + int vcount; /* total number of vertices */ + int voffset; /* only used during reading */ + lwPolygon *pol; /* array of polygons */ +} lwPolygonList; + +/* geometry layers */ + +typedef struct st_lwLayer +{ + struct st_lwLayer *next, *prev; + char *name; + int index; + int parent; + int flags; + float pivot[3]; + float bbox[6]; + lwPointList point; + lwPolygonList polygon; + int nvmaps; + lwVMap *vmap; /* linked list of vmaps */ +} lwLayer; + +/* tag strings */ + +typedef struct st_lwTagList +{ + int count; + int offset; /* only used during reading */ + char **tag; /* array of strings */ +} lwTagList; + +/* an object */ + +typedef struct st_lwObject +{ + lwLayer *layer; /* linked list of layers */ + lwEnvelope *env; /* linked list of envelopes */ + lwClip *clip; /* linked list of clips */ + lwSurface *surf; /* linked list of surfaces */ + lwTagList taglist; + int nlayers; + int nenvs; + int nclips; + int nsurfs; +} lwObject; + +/* lwo2.c */ + +void lwFreeLayer(lwLayer *layer); +void lwFreeObject(lwObject *object); +lwObject *lwGetObject(char *filename, unsigned int *failID, int *failpos); + +/* pntspols.c */ + +void lwFreePoints(lwPointList *point); +void lwFreePolygons(lwPolygonList *plist); +int lwGetPoints(FILE *fp, int cksize, lwPointList *point); +void lwGetBoundingBox(lwPointList *point, float bbox[]); +int lwAllocPolygons(lwPolygonList *plist, int npols, int nverts); +int lwGetPolygons(FILE *fp, int cksize, lwPolygonList *plist, int ptoffset); +void lwGetPolyNormals(lwPointList *point, lwPolygonList *polygon); +int lwGetPointPolygons(lwPointList *point, lwPolygonList *polygon); +int lwResolvePolySurfaces(lwPolygonList *polygon, lwTagList *tlist, + lwSurface **surf, int *nsurfs); +void lwGetVertNormals(lwPointList *point, lwPolygonList *polygon); +void lwFreeTags(lwTagList *tlist); +int lwGetTags(FILE *fp, int cksize, lwTagList *tlist); +int lwGetPolygonTags(FILE *fp, int cksize, lwTagList *tlist, + lwPolygonList *plist); + +/* vmap.c */ + +void lwFreeVMap(lwVMap *vmap); +lwVMap *lwGetVMap(FILE *fp, int cksize, int ptoffset, int poloffset, + int perpoly); +int lwGetPointVMaps(lwPointList *point, lwVMap *vmap); +int lwGetPolyVMaps(lwPolygonList *polygon, lwVMap *vmap); + +/* clip.c */ + +void lwFreeClip(lwClip *clip); +lwClip *lwGetClip(FILE *fp, int cksize); +lwClip *lwFindClip(lwClip *list, int index); + +/* envelope.c */ + +void lwFreeEnvelope(lwEnvelope *env); +lwEnvelope *lwGetEnvelope(FILE *fp, int cksize); +lwEnvelope *lwFindEnvelope(lwEnvelope *list, int index); +float lwEvalEnvelope(lwEnvelope *env, float time); + +/* surface.c */ + +void lwFreePlugin(lwPlugin *p); +void lwFreeTexture(lwTexture *t); +void lwFreeSurface(lwSurface *surf); +int lwGetTHeader(FILE *fp, int hsz, lwTexture *tex); +int lwGetTMap(FILE *fp, int tmapsz, lwTMap *tmap); +int lwGetImageMap(FILE *fp, int rsz, lwTexture *tex); +int lwGetProcedural(FILE *fp, int rsz, lwTexture *tex); +int lwGetGradient(FILE *fp, int rsz, lwTexture *tex); +lwTexture *lwGetTexture(FILE *fp, int bloksz, unsigned int type); +lwPlugin *lwGetShader(FILE *fp, int bloksz); +lwSurface *lwGetSurface(FILE *fp, int cksize); +lwSurface *lwDefaultSurface(void); + +/* lwob.c */ + +lwSurface *lwGetSurface5(FILE *fp, int cksize, lwObject *obj); +int lwGetPolygons5(FILE *fp, int cksize, lwPolygonList *plist, int ptoffset); +lwObject *lwGetObject5(char *filename, unsigned int *failID, int *failpos); + +/* list.c */ + +void lwListFree(void *list, void (*freeNode)(void *)); +void lwListAdd(void **list, void *node); +void lwListInsert(void **vlist, void *vitem, + int (*compare)(void *, void *)); + +/* vecmath.c */ + +float dot(float a[], float b[]); +void cross(float a[], float b[], float c[]); +void normalize(float v[]); +#define vecangle(a, b) (float)acos(dot(a, b)) + +/* lwio.c */ + +void set_flen(int i); +int get_flen(void); +void *getbytes(FILE *fp, int size); +void skipbytes(FILE *fp, int n); +int getI1(FILE *fp); +short getI2(FILE *fp); +int getI4(FILE *fp); +unsigned char getU1(FILE *fp); +unsigned short getU2(FILE *fp); +unsigned int getU4(FILE *fp); +int getVX(FILE *fp); +float getF4(FILE *fp); +char *getS0(FILE *fp); +int sgetI1(unsigned char **bp); +short sgetI2(unsigned char **bp); +int sgetI4(unsigned char **bp); +unsigned char sgetU1(unsigned char **bp); +unsigned short sgetU2(unsigned char **bp); +unsigned int sgetU4(unsigned char **bp); +int sgetVX(unsigned char **bp); +float sgetF4(unsigned char **bp); +char *sgetS0(unsigned char **bp); + +#ifdef _WIN32 +void revbytes(void *bp, int elsize, int elcount); +#else +#define revbytes(b, s, c) +#endif + +#endif diff --git a/src/editors/xrECore/Editor/pDomain.cpp b/src/editors/xrECore/Editor/pDomain.cpp new file mode 100644 index 00000000000..6e8c4d2f0fb --- /dev/null +++ b/src/editors/xrECore/Editor/pDomain.cpp @@ -0,0 +1,707 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "d3dutils.h" +#include "ui_main.h" +#include "ParticleEffectActions.h" + +using namespace PAPI; + +PDomain::PDomain(EType et, BOOL ra, u32 color, PDomainEnum t, + float inA0, float inA1, float inA2, + float inA3, float inA4, float inA5, + float inA6, float inA7, float inA8) +{ + flags.set(flRenderable, ra); + e_type = et; + type = t; + clr = color; + f[0] = inA0; + f[1] = inA1; + f[2] = inA2; + f[3] = inA3; + f[4] = inA4; + f[5] = inA5; + f[6] = inA6; + f[7] = inA7; + f[8] = inA8; +} + +PDomain::PDomain(const PDomain &inDomain) +{ + e_type = inDomain.e_type; + flags = inDomain.flags; + type = inDomain.type; + clr = inDomain.clr; + f[0] = inDomain.f[0]; + f[1] = inDomain.f[1]; + f[2] = inDomain.f[2]; + f[3] = inDomain.f[3]; + f[4] = inDomain.f[4]; + f[5] = inDomain.f[5]; + f[6] = inDomain.f[6]; + f[7] = inDomain.f[7]; + f[8] = inDomain.f[8]; +} + +PDomain::~PDomain() +{ +} + +void PDomain::Load(IReader &F) +{ + type = PDomainEnum(F.r_u32()); + F.r_fvector3(v[0]); + F.r_fvector3(v[1]); + F.r_fvector3(v[2]); +} + +void PDomain::Load2(CInifile &ini, const shared_str §) +{ + type = PDomainEnum(ini.r_u32(sect, "type")); + v[0] = ini.r_fvector3(sect, "v0"); + v[1] = ini.r_fvector3(sect, "v1"); + v[2] = ini.r_fvector3(sect, "v2"); +} + +void PDomain::Save(IWriter &F) +{ + F.w_u32(type); + F.w_fvector3(v[0]); + F.w_fvector3(v[1]); + F.w_fvector3(v[2]); +} + +void PDomain::Save2(CInifile &ini, const shared_str §) +{ + ini.w_u32(sect.c_str(), "type", type); + ini.w_fvector3(sect.c_str(), "v0", v[0]); + ini.w_fvector3(sect.c_str(), "v1", v[1]); + ini.w_fvector3(sect.c_str(), "v2", v[2]); +} + +/* +void PDomain::set(PAPI::PDomainEnum t, float inA0, float inA1, float inA2, + float inA3, float inA4, float inA5, + float inA6, float inA7, float inA8 ) +{ + type = t; + f[0] = inA0; + f[1] = inA1; + f[2] = inA2; + f[3] = inA3; + f[4] = inA4; + f[5] = inA5; + f[6] = inA6; + f[7] = inA7; + f[8] = inA8; +} +*/ + +//-------------------------------------------------------------------- +void PDomain::Render(u32 clr, const Fmatrix &parent) +{ + if (!flags.is(flRenderable)) + return; + u32 clr_s = subst_alpha(clr, 0x60); + u32 clr_w = subst_alpha(clr, 0xff); + RCache.set_xform_world(parent); + switch (type) + { + case PDPoint: + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawCross(v[0], 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, clr_w); + break; + case PDLine: + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawCross(v[0], 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, clr_w); + DU_impl.DrawCross(v[1], 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, 0.05f, clr_w); + DU_impl.DrawLine(v[0], v[1], clr_w); + break; + case PDTriangle: + EDevice.SetShader(EDevice.m_SelectionShader); + DU_impl.DrawFace(v[0], v[1], v[2], clr_s, clr_w, true, true); + break; + case PDPlane: + { + EDevice.SetShader(EDevice.m_SelectionShader); + Fvector2 sz = {100.f, 100.f}; + DU_impl.DrawPlane(v[0], v[1], sz, clr_s, clr_w, true, true, true); + } + break; + case PDBox: + EDevice.SetShader(EDevice.m_SelectionShader); + DU_impl.DrawAABB(v[0], v[1], clr_s, clr_w, true, true); + break; + case PDSphere: + DU_impl.DrawSphere(parent, v[0], f[4], clr_s, clr_w, true, true); + DU_impl.DrawSphere(parent, v[0], f[3], clr_s, clr_w, true, true); + break; + case PDCylinder: + { + Fvector c, d; + float h = d.sub(v[1], v[0]).magnitude(); + c.add(v[0], v[1]).div(2.f); + if (!fis_zero(h)) + { + d.div(h); + DU_impl.DrawCylinder(parent, c, d, h, f[6], clr_s, clr_w, true, true); + DU_impl.DrawCylinder(parent, c, d, h, f[7], clr_s, clr_w, true, true); + } + } + break; + case PDCone: + { + Fvector d; + float h = d.sub(v[1], v[0]).magnitude(); + if (!fis_zero(h)) + { + d.div(h); + DU_impl.DrawCone(parent, v[0], d, h, f[6], clr_s, clr_w, true, true); + DU_impl.DrawCone(parent, v[0], d, h, f[7], clr_s, clr_w, true, true); + } + } + break; + case PDBlob: + EDevice.SetShader(EDevice.m_WireShader); + DU_impl.DrawCross(v[0], f[3], f[3], f[3], f[3], f[3], f[3], clr); + break; + case PDDisc: + DU_impl.DrawCylinder(parent, v[0], v[1], 0.f, f[6], clr_s, clr_w, true, true); + DU_impl.DrawCylinder(parent, v[0], v[1], 0.f, f[7], clr_s, clr_w, true, true); + break; + case PDRectangle: + DU_impl.DrawRectangle(v[0], v[1], v[2], clr_s, clr_w, true, true); + break; + } +} + +xr_token domain_token[] = { + {"Point", PDPoint}, + {"Line", PDLine}, + {"Triangle", PDTriangle}, + {"Plane", PDPlane}, + {"Box", PDBox}, + {"Sphere", PDSphere}, + {"Cylinder", PDCylinder}, + {"Cone", PDCone}, + {"Blob", PDBlob}, + {"Disc", PDDisc}, + {"Rectangle", PDRectangle}, + {0, 0}}; + +void PDomain::OnTypeChange(PropValue *sender) +{ + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +void PDomain::FillProp(PropItemVec &items, LPCSTR pref, u32 clr) +{ + PropValue *V; + V = PHelper().CreateToken32(items, pref, (u32 *)&type, domain_token); + V->OnChangeEvent.bind(this, &PDomain::OnTypeChange); + V->Owner()->prop_color = TColor(clr); + + switch (e_type) + { + case vNum: + switch (type) + { + case PDPoint: + V = PHelper().CreateVector(items, PrepareKey(pref, "Center"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDLine: + V = PHelper().CreateVector(items, PrepareKey(pref, "Point 1"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Point 2"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDTriangle: + V = PHelper().CreateVector(items, PrepareKey(pref, "Vertex 1"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Vertex 2"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Vertex 3"), &v[2], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDPlane: + V = PHelper().CreateVector(items, PrepareKey(pref, "Origin"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Normal"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDBox: + V = PHelper().CreateVector(items, PrepareKey(pref, "Min"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Max"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDSphere: + V = PHelper().CreateVector(items, PrepareKey(pref, "Center"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[3], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[4], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDCylinder: + V = PHelper().CreateVector(items, PrepareKey(pref, "Point 1"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Point 2"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[6], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[7], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDCone: + V = PHelper().CreateVector(items, PrepareKey(pref, "Apex"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "End Point"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[6], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[7], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDBlob: + V = PHelper().CreateVector(items, PrepareKey(pref, "Center"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[3], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDDisc: + V = PHelper().CreateVector(items, PrepareKey(pref, "Center"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Normal"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[6], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[7], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDRectangle: + V = PHelper().CreateVector(items, PrepareKey(pref, "Origin"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Basis U"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Basis V"), &v[2], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + default: + V = PHelper().CreateVector(items, PrepareKey(pref, "Translate"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Rotate"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVector(items, PrepareKey(pref, "Scale"), &v[2], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + } + break; + case vAngle: + switch (type) + { + case PDPoint: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Center"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDLine: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Point 1"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Point 2"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDTriangle: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Vertex 1"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Vertex 2"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Vertex 3"), &v[2], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDPlane: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Origin"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Normal"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDBox: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Min"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Max"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDSphere: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Center"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[3], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[4], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDCylinder: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Point 1"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Point 2"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[6], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[7], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDCone: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Apex"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "End Point"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[6], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[7], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDBlob: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Center"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[3], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDDisc: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Center"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Normal"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[6], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[7], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + case PDRectangle: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Origin"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Basis U"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Basis V"), &v[2], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + default: + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Translate"), &v[0], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Rotate"), &v[1], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateAngle3(items, PrepareKey(pref, "Scale"), &v[2], flt_min, flt_max, 0.001f, 3); + V->Owner()->prop_color = TColor(clr); + break; + } + break; + case vColor: + switch (type) + { + case PDPoint: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Center"), &v[0]); + V->Owner()->prop_color = TColor(clr); + break; + case PDLine: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Point 1"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Point 2"), &v[1]); + V->Owner()->prop_color = TColor(clr); + break; + case PDTriangle: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Vertex 1"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Vertex 2"), &v[1]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Vertex 3"), &v[2]); + V->Owner()->prop_color = TColor(clr); + break; + case PDPlane: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Origin"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Normal"), &v[1]); + V->Owner()->prop_color = TColor(clr); + break; + case PDBox: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Min"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Max"), &v[1]); + V->Owner()->prop_color = TColor(clr); + break; + case PDSphere: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Center"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[3]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[4]); + V->Owner()->prop_color = TColor(clr); + break; + case PDCylinder: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Point 1"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Point 2"), &v[1]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[6]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[7]); + V->Owner()->prop_color = TColor(clr); + break; + case PDCone: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Apex"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "End Point"), &v[1]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[6]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[7]); + V->Owner()->prop_color = TColor(clr); + break; + case PDBlob: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Center"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[3]); + V->Owner()->prop_color = TColor(clr); + break; + case PDDisc: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Center"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Normal"), &v[1]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Inner"), &f[6]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateFloat(items, PrepareKey(pref, "Radius Outer"), &f[7]); + V->Owner()->prop_color = TColor(clr); + break; + case PDRectangle: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Origin"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Basis U"), &v[1]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Basis V"), &v[2]); + V->Owner()->prop_color = TColor(clr); + break; + default: + V = PHelper().CreateVColor(items, PrepareKey(pref, "Translate"), &v[0]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Rotate"), &v[1]); + V->Owner()->prop_color = TColor(clr); + V = PHelper().CreateVColor(items, PrepareKey(pref, "Scale"), &v[2]); + V->Owner()->prop_color = TColor(clr); + break; + } + break; + } +} + +//-------------------------------------------------------------------- +/* +void PDomain::MoveXYZ(float x, float y, float z) +{ + switch(type) + { + case PDPoint: + a0+=x; a1+=y; a2+=z; + break; + case PDLine: + a0+=x; a1+=y; a2+=z; + a3+=x; a4+=y; a5+=z; + break; + case PDTriangle: + a0+=x; a1+=y; a2+=z; + a3+=x; a4+=y; a5+=z; + a6+=x; a7+=y; a8+=z; + break; + case PDPlane: + a0+=x; a1+=y; a2+=z; + break; + case PDBox: + a0+=x; a1+=y; a2+=z; + a3+=x; a4+=y; a5+=z; + break; + case PDSphere: + a0+=x; a1+=y; a2+=z; + break; + case PDCylinder: + a0+=x; a1+=y; a2+=z; + a3+=x; a4+=y; a5+=z; + break; + case PDCone: + a0+=x; a1+=y; a2+=z; + a3+=x; a4+=y; a5+=z; + break; + case PDBlob: + a0+=x; a1+=y; a2+=z; + break; + case PDDisc: + a0+=x; a1+=y; a2+=z; + break; + } + +} + +//---------------------------------------------------------- +void PDomain::RotateXYZ (float x, float y, float z) +{ + MVertex v1; + MVertex v2; + MVertex v3; + MVertex r1; + MVertex r2; + MVertex r3; +// MVertex tmpV; + MMatrix trans; + + MVertex c; + + trans.setIdentity(); + trans.rotateX(x); + trans.rotateZ(z); + trans.rotateY(y); +// float xloc; +// float yloc; +// float zloc; + switch(type) + { + case PDPoint: + break; + case PDLine: + r1 = trans*(v1.set( a0, a1, a2 )); + r2 = trans*(v2.set( a3, a4, a5 )); + a0 = r1.X(); a1 = r1.Y(); a2 = r1.Z(); + break; + case PDTriangle: + c = GetCenter(); + r1 = trans*(v1.set( (float)a0-c.X(), (float)a1-c.Y(), (float)a2-c.Z() )); + r2 = trans*(v2.set( (float)a3-c.X(), (float)a4-c.Y(), (float)a5-c.Z() )); + r3 = trans*(v3.set( (float)a6-c.X(), (float)a7-c.Y(), (float)a8-c.Z() )); + a0 = r1.X()+c.X(); a1 = r1.Y()+c.Y(); a2 = r1.Z()+c.Z(); + a3 = r2.X()+c.X(); a4 = r2.Y()+c.Y(); a5 = r2.Z()+c.Z(); + a6 = r3.X()+c.X(); a7 = r3.Y()+c.Y(); a8 = r3.Z()+c.Z(); + break; + case PDPlane: +// r2 = trans*(v2.set( a3, a4, a5 )); +// r3 = trans*(v3.set( a6, a7, a8 )); +// a3 = r2.X(); a4 = r2.Y(); a5 = r2.Z(); +// a6 = r3.X(); a7 = r3.Y(); a8 = r3.Z(); + + c = GetCenter(); + v1.set(a0-c.X(), a1-c.Y(), a2-c.Z()); + v2.set((float)a0+((float)a3/2.0), (float)a1+((float)a4/2.0), (float)a2+((float)a5/2.0)); + v3.set((float)a0+((float)a6/2.0), (float)a1+((float)a7/2.0), (float)a2+((float)a8/2.0)); + + r1 = trans*v1; + r2 = trans*v2; + r3 = trans*v3; + + a0 = r1.X()+c.X(); a1 = r1.Y()+c.Y(); a2 = r1.Z()+c.Z(); + + + break; + case PDBox: + r1 = trans*(v1.set( a0, a1, a2 )); + r2 = trans*(v2.set( a3, a4, a5 )); + a0 = r1.X(); a1 = r1.Y(); a2 = r1.Z(); + a3 = r2.X(); a4 = r2.Y(); a5 = r2.Z(); + break; + case PDSphere: + r1 = trans*(v1.set( a0, a1, a2 )); + a0 = r1.X(); a1 = r1.Y(); a2 = r1.Z(); + break; + case PDCylinder: + r1 = trans*(v1.set( a0, a1, a2 )); + r2 = trans*(v2.set( a3, a4, a5 )); + a0 = r1.X(); a1 = r1.Y(); a2 = r1.Z(); + a3 = r2.X(); a4 = r2.Y(); a5 = r2.Z(); + break; + case PDCone: + r1 = trans*(v1.set( a0, a1, a2 )); + r2 = trans*(v2.set( a3, a4, a5 )); + a0 = r1.X(); a1 = r1.Y(); a2 = r1.Z(); + a3 = r2.X(); a4 = r2.Y(); a5 = r2.Z(); + break; + case PDBlob: + r1 = trans*(v1.set( a0, a1, a2 )); + a0 = r1.X(); a1 = r1.Y(); a2 = r1.Z(); + break; + case PDDisc: + break; + } +} +//---------------------------------------------------------- +void PDomain::ScaleXYZ (float x, float y, float z) +{ + x = x; + y = y; + z = z; + + switch(type) + { + case PDPoint: + break; + case PDLine: + break; + case PDTriangle: + break; + case PDPlane: + break; + case PDBox: + break; + case PDSphere: + break; + case PDCylinder: + break; + case PDCone: + break; + case PDBlob: + break; + case PDDisc: + break; + } +} + +//---------------------------------------------------------- +MVertex& PDomain::GetCenter() +{ + static MVertex center; + MVertex v1; + MVertex v2; + MVertex v3; + MVertex v4; + + switch(type) + { + case PDPoint: + center.set(a0, a1, a2); + break; + case PDLine: + break; + case PDTriangle: + center.set( ((float)a0+(float)a3+(float)a6)/3.0, + ((float)a1+(float)a4+(float)a7)/3.0, + ((float)a2+(float)a5+(float)a8)/3.0 ); + break; + case PDPlane: + v1.set(a0, a1, a2); + v2.set(a0+(a3/2.0f), a1+(a4/2.0f), a2+(a5/2.0f)); + v3.set(a0+(a6/2.0f), a1+(a7/2.0f), a2+(a8/2.0f)); + v4.set(a0+(a6/2.0f)+(a3/2.0f), a1+(a7/2.0f)+(a4/2.0f), a2+(a8/2.0f)+(a5/2.0f)); + center.set( (v1.X()+v2.X()+v3.X()+v4.X())/4.0, + (v1.Y()+v2.Y()+v3.Y()+v4.Y())/4.0, + (v1.Z()+v2.Z()+v3.Z()+v4.Z())/4.0 ); + break; + case PDBox: + break; + case PDSphere: + break; + case PDCylinder: + break; + case PDCone: + break; + case PDBlob: + break; + case PDDisc: + center.set(a0, a1, a2); + break; + } + return center; +} +*/ diff --git a/src/editors/xrECore/Editor/pick_defs.h b/src/editors/xrECore/Editor/pick_defs.h new file mode 100644 index 00000000000..7c13020807f --- /dev/null +++ b/src/editors/xrECore/Editor/pick_defs.h @@ -0,0 +1,197 @@ +//---------------------------------------------------- +// file: SceneClassList.h +//---------------------------------------------------- + +#ifndef pick_defsH +#define pick_defsH +//---------------------------------------------------- + +class CEditableObject; +class CEditableMesh; +class CCustomObject; + +#ifdef _EDITOR +class SPickQuery +{ + Flags32 m_Flags; + +public: + Fvector m_Start; + Fvector m_Direction; + float m_Dist; + Fbox m_BB; + +public: + class SResult + { + public: + Fvector verts[3]; + float u, v; + float range; + CEditableObject *e_obj; + CEditableMesh *e_mesh; + //. u32 tag; + union + { + u32 tag; // 4b + struct + { + u32 material : 14; // + u32 suppress_shadows : 1; // + u32 suppress_wm : 1; // + u32 sector : 16; // + }; + }; + + bool operator<(const SResult &F) const { return range < F.range; } + SResult(const SResult &F) + { + verts[0] = F.verts[0]; + verts[1] = F.verts[1]; + verts[2] = F.verts[2]; + u = F.u; + v = F.v; + range = F.range; + tag = F.tag; + e_obj = F.e_obj; + e_mesh = F.e_mesh; + } + SResult(const Fmatrix &parent, CDB::RESULT *r, CEditableObject *obj, CEditableMesh *mesh) + { + parent.transform_tiny(verts[0], r->verts[0]); + parent.transform_tiny(verts[1], r->verts[1]); + parent.transform_tiny(verts[2], r->verts[2]); + u = r->u; + v = r->v; + range = r->range; + tag = r->dummy; + e_obj = obj; + e_mesh = mesh; + } + SResult(CDB::RESULT *r, CEditableObject *obj, CEditableMesh *mesh) + { + verts[0] = r->verts[0]; + verts[1] = r->verts[1]; + verts[2] = r->verts[2]; + u = r->u; + v = r->v; + range = r->range; + tag = r->dummy; + e_obj = obj; + e_mesh = mesh; + } + }; + DEFINE_VECTOR(SResult, ResultVec, ResultIt); + +protected: + ResultVec results; + +public: + IC void prepare_rq(const Fvector &start, const Fvector &dir, float dist, u32 flags) + { + m_Start.set(start); + m_Direction.set(dir); + m_Dist = dist; + m_Flags.assign(flags); + results.clear(); + } + IC void prepare_bq(const Fbox &bbox, u32 flags) + { + m_BB.set(bbox); + m_Flags.assign(flags); + results.clear(); + } + IC void append_mtx(const Fmatrix &parent, CDB::RESULT *R, CEditableObject *obj, CEditableMesh *mesh) + { + SResult D(parent, R, obj, mesh); + if (m_Flags.is(CDB::OPT_ONLYNEAREST) && !results.empty()) + { + SResult &S = results.back(); + if (D.range < S.range) + S = D; + } + else + results.push_back(D); + } + IC void append(CDB::RESULT *R, CEditableObject *obj, CEditableMesh *mesh) + { + SResult D(R, obj, mesh); + if (m_Flags.is(CDB::OPT_ONLYNEAREST) && !results.empty()) + { + SResult &S = results.back(); + if (D.range < S.range) + S = D; + } + else + results.push_back(D); + } + IC int r_count() + { + return results.size(); + } + IC SResult *r_begin() + { + return results.data(); + } + IC SResult *r_end() + { + return results.data() + results.size(); + } + IC void r_clear() + { + results.clear(); + } + IC void r_sort() + { + std::sort(results.begin(), results.end()); + } +}; +struct SRayPickObjVisualInfo +{ + IKinematics *K; + u16 bone_id; + Fvector normal; +}; +struct SRayPickInfo +{ + CDB::RESULT inf; + SRayPickObjVisualInfo visual_inf; + CCustomObject *s_obj; + CEditableObject *e_obj; + CEditableMesh *e_mesh; + Fvector pt; + SRayPickInfo() + { + Reset(); + visual_inf.bone_id = u16(-1); + } + IC void Reset() + { + ZeroMemory(this, sizeof(SRayPickInfo)); + inf.range = 5000; + } + IC void SetRESULT(CDB::MODEL *M, CDB::RESULT *R) + { + inf = *R; + inf.id = (M->get_tris() + inf.id)->dummy; + } +}; +DEFINE_VECTOR(CDB::RESULT, BPInfVec, BPInfIt); +struct SBoxPickInfo +{ + BPInfVec inf; + CCustomObject *s_obj; + CEditableObject *e_obj; + CEditableMesh *e_mesh; + SBoxPickInfo() { Reset(); } + IC void Reset() { ZeroMemory(this, sizeof(SBoxPickInfo)); } + IC void AddRESULT(CDB::MODEL *M, CDB::RESULT *R) + { + inf.push_back(*R); + inf.back().id = (M->get_tris() + inf.back().id)->dummy; + } +}; +DEFINE_VECTOR(SBoxPickInfo, SBoxPickInfoVec, SBoxPickInfoIt); +#endif +//---------------------------------------------------- +#endif // pick_definitionH diff --git a/src/editors/xrECore/Editor/render.cpp b/src/editors/xrECore/Editor/render.cpp new file mode 100644 index 00000000000..35f49252ee9 --- /dev/null +++ b/src/editors/xrECore/Editor/render.cpp @@ -0,0 +1,348 @@ +#include "stdafx.h" +#include "render.h" +#include "Layers/xrRender/ResourceManager.h" +#include "Layers/xrRender/ShaderResourceTraits.h" + +float ssaDISCARD = 4.f; +float ssaDONTSORT = 32.f; + +ECORE_API float r_ssaDISCARD; +ECORE_API float g_fSCREEN; + +CRender RImplementation; +ECORE_API CRender *Render = &RImplementation; + +CRender::CRender() +{ + m_skinning = 0; +} + +CRender::~CRender() +{ + xr_delete(Target); +} + +void CRender::Initialize() +{ + c_ssky0 = "s_sky0"; + c_ssky1 = "s_sky1"; + c_sclouds0 = "s_clouds0"; + c_sclouds1 = "s_clouds1"; + PSLibrary.OnCreate(); +} +void CRender::ShutDown() +{ + PSLibrary.OnDestroy(); +} + +void CRender::OnDeviceCreate(pcstr str) +{ + Models = xr_new(); + Models->Logging(FALSE); +} +void CRender::OnDeviceDestroy(bool keep_textures) +{ + xr_delete(Models); +} + +ref_shader CRender::getShader(int id) { return 0; } // VERIFY(id(); + D->Load(F); + return D; +} + +IRenderVisual *CRender::model_CreatePE(LPCSTR name) +{ + PS::CPEDef *source = PSLibrary.FindPED(name); + return Models->CreatePE(source); +} + +IRenderVisual *CRender::model_CreateParticles(LPCSTR name) +{ + PS::CPEDef *SE = PSLibrary.FindPED(name); + if (SE) + return Models->CreatePE(SE); + else + { + PS::CPGDef *SG = PSLibrary.FindPGD(name); + return SG ? Models->CreatePG(SG) : 0; + } +} + +void CRender::rmNear(CBackend& cmd_list) +{ + IRender_Target* T = getTarget(); + RCache.SetViewport({ 0, 0, T->get_width(RCache), T->get_height(RCache), 0, 0.02f }); +} + +void CRender::rmFar(CBackend& cmd_list) +{ + IRender_Target* T = getTarget(); + RCache.SetViewport({ 0, 0, T->get_width(RCache), T->get_height(RCache), 0.99999f, 1.f }); +} + +void CRender::rmNormal(CBackend& cmd_list) +{ + IRender_Target* T = getTarget(); + RCache.SetViewport({ 0, 0, T->get_width(RCache), T->get_height(RCache), 0, 1.f }); +} + +void CRender::set_Transform(Fmatrix *M) +{ + current_matrix.set(*M); +} + +void CRender::add_Visual(IRenderVisual *visual) { Models->RenderSingle(dynamic_cast(visual), current_matrix, 1.f); } +IRenderVisual *CRender::model_Create(LPCSTR name, IReader *data) { return Models->Create(name, data); } +IRenderVisual *CRender::model_CreateChild(LPCSTR name, IReader *data) { return Models->CreateChild(name, data); } +void CRender::model_Delete(IRenderVisual *&V, bool bDiscard) +{ + auto v = dynamic_cast(V); + Models->Delete(v, bDiscard); + if (v == nullptr) + V = nullptr; +} +IRenderVisual *CRender::model_Duplicate(IRenderVisual *V) { return Models->Instance_Duplicate(dynamic_cast(V)); } +void CRender::model_Render(IRenderVisual *m_pVisual, const Fmatrix &mTransform, int priority, bool strictB2F, float m_fLOD) { Models->Render(dynamic_cast(m_pVisual), mTransform, priority, strictB2F, m_fLOD); } +void CRender::model_RenderSingle(IRenderVisual *m_pVisual, const Fmatrix &mTransform, float m_fLOD) { Models->RenderSingle(dynamic_cast(m_pVisual), mTransform, m_fLOD); } + +//#pragma comment(lib,"d3dx_r1") +HRESULT CRender::CompileShader( + LPCSTR pSrcData, + UINT SrcDataLen, + void *_pDefines, + void *_pInclude, + LPCSTR pFunctionName, + LPCSTR pTarget, + DWORD Flags, + void *_ppShader, + void *_ppErrorMsgs, + void *_ppConstantTable) +{ + CONST D3DXMACRO *pDefines = (CONST D3DXMACRO *)_pDefines; + LPD3DXINCLUDE pInclude = (LPD3DXINCLUDE)_pInclude; + LPD3DXBUFFER *ppShader = (LPD3DXBUFFER *)_ppShader; + LPD3DXBUFFER *ppErrorMsgs = (LPD3DXBUFFER *)_ppErrorMsgs; + LPD3DXCONSTANTTABLE *ppConstantTable = (LPD3DXCONSTANTTABLE *)_ppConstantTable; + return D3DXCompileShader(pSrcData, SrcDataLen, pDefines, pInclude, pFunctionName, pTarget, Flags, ppShader, ppErrorMsgs, ppConstantTable); +} + + +class includer : public ID3DXInclude +{ +public: + HRESULT __stdcall Open( + D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID* ppData, UINT* pBytes) + { + string_path pname; + strconcat(sizeof(pname), pname, GEnv.Render->getShaderPath(), pFileName); + IReader* R = FS.r_open("$game_shaders$", pname); + if (nullptr == R) + { + // possibly in shared directory or somewhere else - open directly + R = FS.r_open("$game_shaders$", pFileName); + if (nullptr == R) + return E_FAIL; + } + + // duplicate and zero-terminate + const size_t size = R->length(); + u8* data = xr_alloc(size + 1); + CopyMemory(data, R->pointer(), size); + data[size] = 0; + FS.r_close(R); + + *ppData = data; + *pBytes = size; + return D3D_OK; + } + HRESULT __stdcall Close(LPCVOID pData) + { + xr_free(pData); + return D3D_OK; + } +}; + +template +static HRESULT create_shader(LPCSTR const pTarget, DWORD const* buffer, u32 const buffer_size, LPCSTR const file_name, + T*& result, bool const disasm) +{ + HRESULT _hr = ShaderTypeTraits::CreateHWShader(buffer, buffer_size, result->sh); + if (!SUCCEEDED(_hr)) + { + Log("! Shader: ", file_name); + Msg("! CreateHWShader hr == 0x%08x", _hr); + return E_FAIL; + } + + LPCVOID data = nullptr; + + _hr = D3DXFindShaderComment(buffer, MAKEFOURCC('C', 'T', 'A', 'B'), &data, nullptr); + + if (SUCCEEDED(_hr) && data) + { + // Parse constant table data + LPD3DXSHADER_CONSTANTTABLE pConstants = LPD3DXSHADER_CONSTANTTABLE(data); + result->constants.parse(pConstants, ShaderTypeTraits::GetShaderDest()); + } + else + Msg("! D3DXFindShaderComment %s hr == 0x%08x", file_name, _hr); + + if (disasm) + { + ID3DXBuffer* disasm = nullptr; + D3DXDisassembleShader(LPDWORD(buffer), FALSE, nullptr, &disasm); + if (!disasm) + return _hr; + + string_path dname; + strconcat(sizeof(dname), dname, "disasm" DELIMITER, file_name, ('v' == pTarget[0]) ? ".vs" : ".ps"); + IWriter* W = FS.w_open("$app_data_root$", dname); + W->w(disasm->GetBufferPointer(), disasm->GetBufferSize()); + FS.w_close(W); + _RELEASE(disasm); + } + + return _hr; +} + +inline HRESULT create_shader(LPCSTR const pTarget, DWORD const* buffer, u32 const buffer_size, LPCSTR const file_name, + void*& result, bool const disasm) +{ + if (pTarget[0] == 'p') + return create_shader(pTarget, buffer, buffer_size, file_name, (SPS*&)result, disasm); + + if (pTarget[0] == 'v') + return create_shader(pTarget, buffer, buffer_size, file_name, (SVS*&)result, disasm); + + NODEFAULT; + return E_FAIL; +} + +HRESULT CRender::shader_compile(pcstr name, IReader* fs, pcstr pFunctionName, pcstr pTarget, u32 Flags, void*& result) +{ + D3DXMACRO defines[128]; + int def_it = 0; + + // options + if (m_skinning < 0) + { + defines[def_it].Name = "SKIN_NONE"; + defines[def_it].Definition = "1"; + def_it++; + } + if (0 == m_skinning) + { + defines[def_it].Name = "SKIN_0"; + defines[def_it].Definition = "1"; + def_it++; + } + if (1 == m_skinning) + { + defines[def_it].Name = "SKIN_1"; + defines[def_it].Definition = "1"; + def_it++; + } + if (2 == m_skinning) + { + defines[def_it].Name = "SKIN_2"; + defines[def_it].Definition = "1"; + def_it++; + } + if (3 == m_skinning) + { + defines[def_it].Name = "SKIN_3"; + defines[def_it].Definition = "1"; + def_it++; + } + if (4 == m_skinning) + { + defines[def_it].Name = "SKIN_4"; + defines[def_it].Definition = "1"; + def_it++; + } + // finish + defines[def_it].Name = 0; + defines[def_it].Definition = 0; + def_it++; + + fs->seek(0); + + includer Includer; + LPD3DXBUFFER pShaderBuf = nullptr; + LPD3DXBUFFER pErrorBuf = nullptr; + LPD3DXCONSTANTTABLE pConstants = nullptr; + LPD3DXINCLUDE pInclude = (LPD3DXINCLUDE)&Includer; + + HRESULT _result = D3DXCompileShader((LPCSTR)fs->pointer(), fs->length(), defines, pInclude, pFunctionName, pTarget, + Flags | D3DXSHADER_USE_LEGACY_D3DX9_31_DLL, &pShaderBuf, &pErrorBuf, &pConstants); + if (SUCCEEDED(_result)) + { +#ifdef DEBUG + Log("- Compile shader:", name); +#endif + _result = create_shader( + pTarget, (DWORD*)pShaderBuf->GetBufferPointer(), pShaderBuf->GetBufferSize(), name, result, o.disasm); + } + else + { + Log("! ", name); + if (pErrorBuf) + Log("! error: ", (LPCSTR)pErrorBuf->GetBufferPointer()); + else + Msg("Can't compile shader hr=0x%08x", _result); + } + + return _result; +} + +void CRender::reset_begin() +{ + xr_delete(Target); +} +void CRender::reset_end() +{ + Target = xr_new(); +} diff --git a/src/editors/xrECore/Editor/render.h b/src/editors/xrECore/Editor/render.h new file mode 100644 index 00000000000..b136fb8e304 --- /dev/null +++ b/src/editors/xrECore/Editor/render.h @@ -0,0 +1,285 @@ +//--------------------------------------------------------------------------- +#ifndef renderH +#define renderH + +#include "..\..\..\xrCDB\frustum.h" +#include "..\..\..\xrEngine\vis_common.h" + +#include "Layers/xrRender/Blender.h" +#include "Layers/xrRender/Blender_CLSID.h" +#include "Layers/xrRender/xrRender_console.h" +#include "Layers/xrRender/PSLibrary.h" +#include "Layers/xrRender/IRenderDetailModel.h" +#include "Layers/xrRender/DetailModel.h" +#include "Layers/xrRender/ModelPool.h" +#include "Layers/xrRender/SkeletonCustom.h" + +#include "xrEngine/Render.h" + +static constexpr auto c_sbase = "s_base"; + +// definition (Renderer) +class CRenderTarget final : public IRender_Target +{ +public: + u32 get_width(CBackend&) override { return EDevice.m_RenderWidth; } + u32 get_height(CBackend&) override { return EDevice.m_RenderHeight; } + + // fake for interface + void set_blur(float f) override {} + void set_gray(float f) override {} + void set_duality_h(float f) override {} + void set_duality_v(float f) override {} + void set_noise(float f) override {} + void set_noise_scale(float f) override {} + void set_noise_fps(float f) override {} + void set_color_base(u32 f) override {} + void set_color_gray(u32 f) override {} + void set_color_add(const Fvector& f) override {} + void set_cm_imfluence(float f) override {} + void set_cm_interpolate(float f) override {} + void set_cm_textures(const shared_str& tex0, const shared_str& tex1) override {} +}; + +class ECORE_API CRender : public IRender +{ + CRenderTarget *Target; + Fmatrix current_matrix; + + CBackend cmd_list; + +public: + // Dynamic geometry streams + _VertexStream Vertex; + _IndexStream Index; + + IndexStagingBuffer QuadIB; + IndexBufferHandle old_QuadIB; + +public: + // options + s32 m_skinning; + + // Data + CFrustum ViewBase; + CPSLibrary PSLibrary; + bool m_hq_skinning = false; + + shared_str c_ssky0; + shared_str c_ssky1; + shared_str c_sclouds0; + shared_str c_sclouds1; + + CModelPool *Models; + IRender::RenderStatistics BasicStats; + // TODO: hack + CResourceManager* Resources; + + struct _options + { + u32 vis_intersect : 1; // config + u32 distortion : 1; // run-time modified + u32 color_mapping : 1; // true if SM 1.4 and higher + u32 disasm : 1; // config + u32 forceskinw : 1; // config + u32 no_detail_textures : 1; // config + u32 no_ram_textures : 1; // don't keep textures in RAM + u32 ffp : 1; + } o = {}; + +public: + // Occlusion culling + bool occ_visible(Fbox &B) override; + bool occ_visible(sPoly &P) override; + bool occ_visible(vis_data &P) override; + + // Constructor/destructor + CRender(); + ~CRender() override; + + void shader_option_skinning(u32 mode) { m_skinning = mode; } + + void Initialize(); + void ShutDown(); + + void OnDeviceCreate(pcstr shName = nullptr) override; + void OnDeviceDestroy(bool bKeepTextures = false) override; + + void Calculate() override; + void Render() override; + void RenderMenu() override; + + void set_Transform(Fmatrix *M); + void add_Visual(IRenderVisual *visual); + + virtual ref_shader getShader(int id); + CRenderTarget *getTarget() override { return Target; } + //. virtual IRender_Target* getTarget (){return Target;} + + void reset_begin() override; + void reset_end() override; + IRenderVisual* model_Create(pcstr name, IReader* data = 0) override; + IRenderVisual* model_CreateChild(pcstr name, IReader* data) override; + virtual IRenderVisual* model_CreatePE(pcstr name); + IRenderVisual* model_CreateParticles(pcstr name) override; + + virtual IRender_DetailModel *model_CreateDM(IReader *R); + IRenderVisual *model_Duplicate(IRenderVisual *V) override; + void model_Delete(IRenderVisual *&V, bool bDiscard = TRUE) override; + virtual void model_Delete(IRender_DetailModel *&F) + { + if (F) + { + CDetail *D = (CDetail *)F; + D->Unload(); + xr_delete(D); + F = NULL; + } + } + void model_Render(IRenderVisual *m_pVisual, const Fmatrix &mTransform, int priority, bool strictB2F, float m_fLOD); + void model_RenderSingle(IRenderVisual *m_pVisual, const Fmatrix &mTransform, float m_fLOD); + GenerationLevel GetGeneration() const override { return GENERATION_R1; } + bool is_sun_static() override { return true; }; + BackendAPI GetBackendAPI() const override { return IRender::BackendAPI::D3D9; } + u32 get_dx_level() override { return 0x00090000; } + + virtual void add_SkeletonWallmark(intrusive_ptr wm){}; + virtual void add_SkeletonWallmark(const Fmatrix *xf, CKinematics *obj, ref_shader &sh, const Fvector &start, const Fvector &dir, float size){}; + + // Render mode + void rmNear(CBackend& cmd_list) override; + void rmFar(CBackend& cmd_list) override; + void rmNormal(CBackend& cmd_list) override; + + void apply_lmaterial() {} + + LPCSTR getShaderPath() override + { +#ifndef _EDITOR + return "R1\\"; +#else + return "editor\\"; +#endif + } + + virtual HRESULT CompileShader( + LPCSTR pSrcData, + UINT SrcDataLen, + void *pDefines, + void *pInclude, + LPCSTR pFunctionName, + LPCSTR pTarget, + DWORD Flags, + void *ppShader, + void *ppErrorMsgs, + void *ppConstantTable); + + virtual IDirect3DBaseTexture9 *texture_load(LPCSTR fname, u32 &mem_size); + + HRESULT shader_compile( + pcstr name, IReader* fs, pcstr pFunctionName, pcstr pTarget, u32 Flags, void*& result) override; + + // fake for interface + void create() override {} + void destroy() override {} + void Destroy() override {} + + void level_Load(IReader* fs) override {} + void level_Unload() override {} + + void DumpStatistics(IGameFont& font, IPerformanceAlert* alert) override {} + + IRenderVisual* getVisual(int id) override { return nullptr; } + + void add_Visual(u32 context_id, IRenderable* root, IRenderVisual* V, Fmatrix& m) override {} + void add_StaticWallmark(const wm_shader& S, const Fvector& P, float s, CDB::TRI* T, Fvector* V) override {} + void add_StaticWallmark(IWallMarkArray* pArray, const Fvector& P, float s, CDB::TRI* T, Fvector* V) override {} + void clear_static_wallmarks() override {} + + void add_SkeletonWallmark(const Fmatrix* xf, IKinematics* obj, IWallMarkArray* pArray, const Fvector& start, + const Fvector& dir, float size) override {} + + IRender_ObjectSpecific* ros_create(IRenderable* parent) override { return nullptr; } + void ros_destroy(IRender_ObjectSpecific*&) override {} + + IRender_Light* light_create() override { return nullptr; } + IRender_Glow* glow_create() override { return nullptr; } + + void model_Logging(bool bEnable) override {} + void models_Prefetch() override {} + void models_Clear(bool b_complete) override {} + + void BeforeWorldRender() override {} //--#SM+#-- Перед рендерингом мира + void AfterWorldRender() override {} //--#SM+#-- После рендеринга мира (до UI) + + void Screenshot(ScreenshotMode mode = SM_NORMAL, pcstr name = 0) override {} + void Screenshot(ScreenshotMode mode, CMemoryWriter& memory_writer) override {} + void ScreenshotAsyncBegin() override {} + void ScreenshotAsyncEnd(CMemoryWriter& memory_writer) override {} + + // Gamma correction functions + void setGamma(float fGamma) override {} + void setBrightness(float fGamma) override {} + void setContrast(float fGamma) override {} + void updateGamma() override {} + + void Reset(SDL_Window* hWnd, u32& dwWidth, u32& dwHeight, float& fWidth_2, float& fHeight_2) override {} + + // Init + void ObtainRequiredWindowFlags(u32& windowFlags) override {} + void SetupStates() override {} + void Create(SDL_Window* hWnd, u32& dwWidth, u32& dwHeight, float& fWidth_2, float& fHeight_2) override {} + + // Overdraw + void overdrawBegin() override {} + void overdrawEnd() override {} + + // Resources control + void DeferredLoad(bool E) override {} + void ResourcesDeferredUpload() override {} + void ResourcesDeferredUnload() override {} + void ResourcesGetMemoryUsage(u32& m_base, u32& c_base, u32& m_lmaps, u32& c_lmaps) override {} + void ResourcesDestroyNecessaryTextures() override {} + void ResourcesStoreNecessaryTextures() override {} + void ResourcesDumpMemoryUsage() override {} + + // HWSupport + bool HWSupportsShaderYUV2RGB() override { return false; } + + // Device state + DeviceState GetDeviceState() override { return DeviceState::Normal; } + bool GetForceGPU_REF() override { return false; } + u32 GetCacheStatPolys() override { return 0; } + void BeforeRender() override {} + void Begin() override {} + void Clear() override {} + void End() override {} + void ClearTarget() override {} + void SetCacheXform(Fmatrix& mView, Fmatrix& mProject) override {} + void OnAssetsChanged() override {} + + RenderContext GetCurrentContext() const override { return RenderContext::NoContext; } + void MakeContextCurrent(RenderContext context) override {} + + CBackend& get_imm_command_list() override + { + return cmd_list; + } + + void CreateQuadIB(); + +protected: + void ScreenshotImpl(ScreenshotMode mode, pcstr name, CMemoryWriter* memory_writer) override {} +}; + +IC float CalcSSA(Fvector &C, float R) +{ + float distSQ = EDevice.m_Camera.GetPosition().distance_to_sqr(C); + return R * R / distSQ; +} + +extern ECORE_API CRender RImplementation; +extern ECORE_API CRender* Render; +//.extern ECORE_API CRender* Render; + +#endif diff --git a/src/editors/xrECore/Editor/ui_main.cpp b/src/editors/xrECore/Editor/ui_main.cpp new file mode 100644 index 00000000000..e05c99d4ab2 --- /dev/null +++ b/src/editors/xrECore/Editor/ui_main.cpp @@ -0,0 +1,773 @@ +#include "stdafx.h" +#include "xrCore/_fbox2.h" +#include "xrEngine/xr_input.h" +#include "UI_ToolsCustom.h" + +#include "UI_Main.h" +#include "d3dutils.h" +#include "SoundManager.h" + +#include "UIEditLightAnim.h" +#include "UIImageEditorForm.h" +#include "UISoundEditorForm.h" +#include "UIMinimapEditorForm.h" +#include "utils/ETools/ETools.h" +#include "UILogForm.h" +#include "xrEngine/GameFont.h" + +TUI *UI = 0; + +extern void IR_GetMousePosScreen(Ivector2& p); + +TUI::TUI() +{ + m_HConsole = 0; + UI = this; + m_AppClosed = false; + m_bAppActive = false; + m_bReady = false; + bNeedAbort = false; + + m_CurrentRStart.set(0, 0, 0); + m_CurrentRDir.set(0, 0, 0); + + m_Flags.assign(flResize); + + m_Pivot.set(0, 0, 0); + + m_MouseCaptured = false; + m_MouseMultiClickCaptured = false; + m_SelectionRect = false; + bMouseInUse = false; + + m_bHintShowing = false; + m_LastHint = ""; + m_Size.set(1280, 800); +} + +TUI::~TUI() +{ + VERIFY(m_ProgressItems.size() == 0); + VERIFY(m_EditorState.size() == 0); +} + +void TUI::OnDeviceCreate() +{ + DU_impl.OnDeviceCreate(); +} + +void TUI::OnDeviceDestroy() +{ + DU_impl.OnDeviceDestroy(); +} + +bool TUI::IsModified() +{ + return ExecCommand(COMMAND_CHECK_MODIFIED); +} +//--------------------------------------------------------------------------- + +void TUI::EnableSelectionRect(bool flag) +{ + m_SelectionRect = flag; + m_SelEnd.x = m_SelStart.x = 0; + m_SelEnd.y = m_SelStart.y = 0; +} + +void TUI::UpdateSelectionRect(const Ivector2 &from, const Ivector2 &to) +{ + m_SelStart.set(from); + m_SelEnd.set(to); +} + +bool TUI::KeyDown(WORD Key, TShiftState Shift) +{ + if (!m_bReady) + return false; + // m_ShiftState = Shift; + // Log("Dn ",Shift.Contains(ssShift)?"1":"0"); + if (EDevice.m_Camera.KeyDown(Key, Shift)) + return true; + return Tools->KeyDown(Key, Shift); +} + +bool TUI::KeyUp(WORD Key, TShiftState Shift) +{ + if (!m_bReady) + return false; + // m_ShiftState = Shift; + if (EDevice.m_Camera.KeyUp(Key, Shift)) + return true; + return Tools->KeyUp(Key, Shift); +} + +bool TUI::KeyPress(WORD Key, TShiftState Shift) +{ + if (!m_bReady) + return false; + return Tools->KeyPress(Key, Shift); +} + +void TUI::MousePress(TShiftState Shift, int X, int Y) +{ + if (!m_bReady) + return; + if (m_MouseCaptured) + return; + + bMouseInUse = true; + + m_ShiftState = Shift; + + // camera activate + if (!EDevice.m_Camera.MoveStart(m_ShiftState)) + { + if (Tools->Pick(Shift)) + return; + if (!m_MouseCaptured) + { + if (Tools->HiddenMode()) + { + IR_GetMousePosScreen(m_StartCpH); + m_DeltaCpH.set(0, 0); + } + else + { + m_CurrentCp = GetRenderMousePosition(); + m_StartCp = m_CurrentCp; + EDevice.m_Camera.MouseRayFromPoint(m_CurrentRStart, m_CurrentRDir, m_CurrentCp); + } + + if (Tools->MouseStart(m_ShiftState)) + { + if (Tools->HiddenMode()) + ShowCursor(FALSE); + m_MouseCaptured = true; + } + } + } + RedrawScene(); +} + +void TUI::MouseRelease(TShiftState Shift, int X, int Y) +{ + if (!m_bReady) + return; + + m_ShiftState = Shift; + + if (EDevice.m_Camera.IsMoving()) + { + if (EDevice.m_Camera.MoveEnd(m_ShiftState)) + bMouseInUse = false; + } + else + { + bMouseInUse = false; + if (m_MouseCaptured) + { + if (!Tools->HiddenMode()) + { + m_CurrentCp = GetRenderMousePosition(); + EDevice.m_Camera.MouseRayFromPoint(m_CurrentRStart, m_CurrentRDir, m_CurrentCp); + } + if (Tools->MouseEnd(m_ShiftState)) + { + if (Tools->HiddenMode()) + { + SetCursorPos(m_StartCpH.x, m_StartCpH.y); + ShowCursor(TRUE); + } + m_MouseCaptured = false; + } + } + } + // update tools (change action) + Tools->OnFrame(); + RedrawScene(); +} +//---------------------------------------------------- +void TUI::MouseMove(TShiftState Shift, int X, int Y) +{ + if (!m_bReady) + return; + m_ShiftState = Shift; +} +//---------------------------------------------------- +void TUI::IR_OnMouseMove(int x, int y) +{ + if (!m_bReady) + return; + bool bRayUpdated = false; + + if (!EDevice.m_Camera.Process(m_ShiftState, x, y)) + { + if (m_MouseCaptured || m_MouseMultiClickCaptured) + { + if (Tools->HiddenMode()) + { + m_DeltaCpH.set(x, y); + if (m_DeltaCpH.x || m_DeltaCpH.y) + { + Tools->MouseMove(m_ShiftState); + } + } + else + { + m_CurrentCp = GetRenderMousePosition(); + EDevice.m_Camera.MouseRayFromPoint(m_CurrentRStart, m_CurrentRDir, m_CurrentCp); + Tools->MouseMove(m_ShiftState); + } + RedrawScene(); + bRayUpdated = true; + } + } + if (!bRayUpdated) + { + m_CurrentCp = GetRenderMousePosition(); + EDevice.m_Camera.MouseRayFromPoint(m_CurrentRStart, m_CurrentRDir, m_CurrentCp); + } + // Out cursor pos + OutUICursorPos(); +} +//--------------------------------------------------------------------------- + +void TUI::OnAppActivate() +{ + m_bAppActive = true; + if (!m_bReady) + return; + if (pInput) + { + m_ShiftState = ssNone; + pInput->OnAppActivate(); + EDevice.seqAppActivate.Process(); + } +} +//--------------------------------------------------------------------------- + +void TUI::OnAppDeactivate() +{ + m_bAppActive = false; + if (!m_bReady) + return; + if (pInput) + { + pInput->OnAppDeactivate(); + m_ShiftState = ssNone; + EDevice.seqAppDeactivate.Process(); + } + HideHint(); +} +//--------------------------------------------------------------------------- + +bool TUI::ShowHint(const AStringVec &SS) +{ + VERIFY(m_bReady); + /* if (SS.size()){ + xr_string S=_ListToSequence2(SS); + if (m_bHintShowing&&(S==m_LastHint)) return true; + m_LastHint = S; + m_bHintShowing = true; + if (!m_pHintWindow){ + m_pHintWindow = xr_new((TComponent*)0); + m_pHintWindow->Brush->Color = (TColor)0x0d9F2FF; + } + TRect rect = m_pHintWindow->CalcHintRect(320,S,0); + rect.Left+=m_HintPoint.x; rect.Top+=m_HintPoint.y; + rect.Right+=m_HintPoint.x; rect.Bottom+=m_HintPoint.y; + m_pHintWindow->ActivateHint(rect,S); + }else{ + m_bHintShowing = false; + m_LastHint = ""; + }*/ + not_implemented(); + return m_bHintShowing; +} +//--------------------------------------------------------------------------- + +void TUI::HideHint() +{ + VERIFY(m_bReady); + m_bHintShowing = false; +} +//--------------------------------------------------------------------------- + +void TUI::ShowHint(const xr_string &s) +{ + VERIFY(m_bReady); + GetCursorPos(&m_HintPoint); + AStringVec SS; + SS.push_back(s); + Tools->OnShowHint(SS); + if (!ShowHint(SS)) + HideHint(); +} +//--------------------------------------------------------------------------- + +void TUI::ShowObjectHint() +{ + /*VERIFY(m_bReady); + if (!EPrefs->object_flags.is(epoShowHint)){ +// if (m_bHintShowing) HideHint(); + return; + } + if (EDevice.m_Camera.IsMoving()||m_MouseCaptured) return; + if (!m_bAppActive) return; + + GetCursorPos(&m_HintPoint); + TWinControl* ctr = FindVCLWindow(m_HintPoint); + if (ctr!=m_D3DWindow) return; + + AStringVec SS; + Tools->OnShowHint(SS); + if (!ShowHint(SS)&&m_pHintWindow) HideHint();*/ +} +//--------------------------------------------------------------------------- +void TUI::CheckWindowPos(HWND *form) +{ + /*if (form->Left+form->Width>Screen->Width) form->Left = Screen->Width-form->Width; + if (form->Top+form->Height>Screen->Height) form->Top = Screen->Height-form->Height; + if (form->Left<0) form->Left = 0; + if (form->Top<0) form->Top = 0;*/ +} +//--------------------------------------------------------------------------- +#ifndef _EDITOR +#include "environment.h" +#endif +void TUI::PrepareRedraw() +{ + VERIFY(m_bReady); + if (m_Flags.is(flResize)) + RealResize(); + // set render state + EDevice.SetRS(D3DRS_TEXTUREFACTOR, 0xffffffff); + // fog + u32 fog_color; + float fog_start, fog_end; + Tools->GetCurrentFog(fog_color, fog_start, fog_end); + /* + if (0==g_pGamePersistent->Environment().GetWeather().size()) + { + g_pGamePersistent->Environment().CurrentEnv->fog_color.set (color_get_R(fog_color),color_get_G(fog_color),color_get_B(fog_color)); + g_pGamePersistent->Environment().CurrentEnv->fog_far = fog_end; + g_pGamePersistent->Environment().CurrentEnv->fog_near = fog_start; + } + */ + EDevice.SetRS(D3DRS_FOGCOLOR, fog_color); + EDevice.SetRS(D3DRS_RANGEFOGENABLE, FALSE); + if (HW.Caps.bTableFog) + { + EDevice.SetRS(D3DRS_FOGTABLEMODE, D3DFOG_LINEAR); + EDevice.SetRS(D3DRS_FOGVERTEXMODE, D3DFOG_NONE); + } + else + { + EDevice.SetRS(D3DRS_FOGTABLEMODE, D3DFOG_NONE); + EDevice.SetRS(D3DRS_FOGVERTEXMODE, D3DFOG_LINEAR); + } + EDevice.SetRS(D3DRS_FOGSTART, *(DWORD *)(&fog_start)); + EDevice.SetRS(D3DRS_FOGEND, *(DWORD *)(&fog_end)); + // filter + for (u32 k = 0; k < HW.Caps.raster.dwStages; k++) + { + if (psDeviceFlags.is(rsFilterLinear)) + { + EDevice.SetSS(k, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); + EDevice.SetSS(k, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); + EDevice.SetSS(k, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); + } + else + { + EDevice.SetSS(k, D3DSAMP_MAGFILTER, D3DTEXF_POINT); + EDevice.SetSS(k, D3DSAMP_MINFILTER, D3DTEXF_POINT); + EDevice.SetSS(k, D3DSAMP_MIPFILTER, D3DTEXF_POINT); + } + } + // ligthing + if (psDeviceFlags.is(rsLighting)) + EDevice.SetRS(D3DRS_AMBIENT, 0x00000000); + else + EDevice.SetRS(D3DRS_AMBIENT, 0xFFFFFFFF); + + EDevice.SetRS(D3DRS_FILLMODE, EDevice.dwFillMode); + EDevice.SetRS(D3DRS_SHADEMODE, EDevice.dwShadeMode); + + RCache.set_xform_world(Fidentity); +} + +extern ENGINE_API bool g_bRendering; + +void TUI::Redraw() +{ + PrepareRedraw(); + try + { + + if (u32(RTSize.x * EDevice.m_ScreenQuality) != RT->dwWidth || u32(RTSize.y * EDevice.m_ScreenQuality) != RT->dwHeight || !RT->pSurface) + { + GetRenderWidth() = static_cast(RTSize.x * EDevice.m_ScreenQuality); + GetRenderHeight() = static_cast(RTSize.y * EDevice.m_ScreenQuality); + RT.destroy(); + ZB.destroy(); + RT.create("rt_color", static_cast(RTSize.x * EDevice.m_ScreenQuality), static_cast(RTSize.y * EDevice.m_ScreenQuality), HW.Caps.fTarget); + ZB.create("rt_depth", static_cast(RTSize.x * EDevice.m_ScreenQuality), static_cast(RTSize.y * EDevice.m_ScreenQuality), D3DFORMAT::D3DFMT_D24X8); + m_Flags.set(flRedraw, TRUE); + EDevice.fASPECT = ((float)RTSize.y) / ((float)RTSize.x); + EDevice.mProject.build_projection(deg2rad(EDevice.fFOV), EDevice.fASPECT, EDevice.m_Camera.m_Znear, EDevice.m_Camera.m_Zfar); + EDevice.m_fNearer = EDevice.mProject._43; + + RCache.set_xform_project(EDevice.mProject); + RCache.set_xform_world(Fidentity); + } + + if (EDevice.Begin()) + { + if (psDeviceFlags.is(rsRenderRealTime)) + m_Flags.set(flRedraw, TRUE); + if (m_Flags.is(flRedraw)) + { + + m_Flags.set(flRedraw, FALSE); + RCache.set_RT(RT->pRT); + RCache.set_ZB(ZB->pRT); + EDevice.Statistic->RenderDUMP_RT.Begin(); + { + CHK_DX(HW.pDevice->Clear(0, 0, D3DCLEAR_ZBUFFER | D3DCLEAR_TARGET, EPrefs ? EPrefs->scene_clear_color : 0x0, 1, 0)); + } + EDevice.UpdateView(); + EDevice.ResetMaterial(); + + Tools->RenderEnvironment(); + + //. temporary reset filter ( ) + for (u32 k = 0; k < HW.Caps.raster.dwStages; k++) + { + if (psDeviceFlags.is(rsFilterLinear)) + { + EDevice.SetSS(k, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); + EDevice.SetSS(k, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); + EDevice.SetSS(k, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); + } + else + { + EDevice.SetSS(k, D3DSAMP_MAGFILTER, D3DTEXF_POINT); + EDevice.SetSS(k, D3DSAMP_MINFILTER, D3DTEXF_POINT); + EDevice.SetSS(k, D3DSAMP_MIPFILTER, D3DTEXF_POINT); + } + } + + // draw grid + if (psDeviceFlags.is(rsDrawGrid)) + { + DU_impl.DrawGrid(); + DU_impl.DrawPivot(m_Pivot); + } + + try + { + Tools->Render(); + } + catch (...) + { + ELog.DlgMsg(mtError, "Please notify AlexMX!!! Critical error has occured in render routine!!! [Type B]"); + } + + // draw selection rect + if (m_SelectionRect) + DU_impl.DrawSelectionRect(m_SelStart, m_SelEnd); + + // draw axis + DU_impl.DrawAxis(EDevice.m_Camera.GetTransform()); + + EDevice.Statistic->RenderDUMP_RT.End(); + EDevice.Statistic->Show(EDevice.pSystemFont); + EDevice.SetRS(D3DRS_FILLMODE, D3DFILL_SOLID); + EDevice.pSystemFont->OnRender(); + EDevice.SetRS(D3DRS_FILLMODE, EDevice.dwFillMode); + EDevice.seqRender.Process(); + RCache.set_RT(HW.pBaseRT); + RCache.set_ZB(HW.pBaseZB); + } + + try + { + EDevice.SetRS(D3DRS_FILLMODE, D3DFILL_SOLID); + g_bRendering = FALSE; + Draw(); + EDevice.SetRS(D3DRS_FILLMODE, EDevice.dwFillMode); + // end draw + EDevice.End(); + } + catch (...) + { + ELog.DlgMsg(mtError, "Please notify AlexMX!!! Critical error has occured in render routine!!! [Type C]"); + } + } + } + catch (...) + { + ELog.DlgMsg(mtError, "Please notify AlexMX!!! Critical error has occured in render routine!!! [Type A]"); + // _clear87(); + // FPU::m24r(); + // ELog.DlgMsg(mtError, "Critical error has occured in render routine.\nEditor may work incorrectly."); + EDevice.End(); + // EDevice.Resize(m_D3DWindow->Width,m_D3DWindow->Height); + } + + OutInfo(); +} +//--------------------------------------------------------------------------- +void TUI::RealResize() +{ + m_Flags.set(flResize, FALSE); + if (m_Size.x && m_Size.y) + EDevice.Resize(m_Size.x, m_Size.y, m_Size_Maximize); + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} +void TUI::RealUpdateScene() +{ + Tools->UpdateProperties(false); + m_Flags.set(flUpdateScene, FALSE); +} +void TUI::RealRedrawScene() +{ + + Redraw(); +} +void TUI::OnFrame() +{ + EDevice.FrameMove(); + SndLib->OnFrame(); + // tools on frame + if (m_Flags.is(flUpdateScene)) + RealUpdateScene(); + Tools->OnFrame(); + // show hint + ShowObjectHint(); + ResetBreak(); +#if 0 + // check mail + CheckMailslot (); +#endif + // Progress + ProgressDraw(); +} +bool TUI::Idle() +{ + VERIFY(m_bReady); + // EDevice.b_is_Active = Application->Active; + // input + MSG msg; + do + { + ZeroMemory(&msg, sizeof(msg)); + if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) + { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + if (msg.message == WM_QUIT) + { + UI->Quit(); + } + continue; + } + + } while (msg.message); + if (m_Flags.is(flResetUI)) + RealResetUI(); + + pInput->OnFrame(); + Sleep(1); + + OnFrame(); + if (m_bAppActive && !m_Flags.is(flNeedQuit) && !m_AppClosed) + RealRedrawScene(); + + // test quit + if (m_Flags.is(flNeedQuit)) + RealQuit(); + return !m_AppClosed; +} +//--------------------------------------------------------------------------- +void ResetActionToSelect() +{ + ExecCommand(COMMAND_CHANGE_ACTION, etaSelect); +} +//--------------------------------------------------------------------------- + +#define MIN_PANEL_HEIGHT 15 + +bool TUI::OnCreate() +{ + // create base class + EDevice.InitTimer(); + + // m_D3DWindow = w; + // m_D3DPanel = p; + EDevice.Initialize(); + // Creation + ETOOLS::ray_options(CDB::OPT_ONLYNEAREST | CDB::OPT_CULL); + + pInput = xr_new(FALSE); + UI->IR_Capture(); + + m_bReady = true; + +#if 0 + if (!CreateMailslot()) { + ELog.DlgMsg(mtError, "Can't create mail slot.\nIt's possible two Editors started."); + return false; + } +#endif + string_path log_path; + if (!FS.exist(log_path, _temp_, "")) + { + VerifyPath(log_path); + } + if (!FS.path_exist(_local_root_)) + { + ELog.DlgMsg(mtError, "Undefined Editor local directory."); + return false; + } + + BeginEState(esEditScene); + GetRenderWidth() = 128; + GetRenderHeight() = 128; + RTSize.set(static_cast(GetRenderWidth()), static_cast(GetRenderHeight())); + EDevice.fASPECT = (float)RTSize.x / (float)RTSize.y; + EDevice.mProject.build_projection(deg2rad(EDevice.fFOV), EDevice.fASPECT, EDevice.m_Camera.m_Znear, EDevice.m_Camera.m_Zfar); + EDevice.m_fNearer = EDevice.mProject._43; + + RCache.set_xform_project(EDevice.mProject); + RCache.set_xform_world(Fidentity); + RT.create("rt_color", static_cast(RTSize.x * EDevice.m_ScreenQuality), static_cast(RTSize.y * EDevice.m_ScreenQuality), HW.Caps.fTarget); + ZB.create("rt_depth", static_cast(RTSize.x * EDevice.m_ScreenQuality), static_cast(RTSize.y * EDevice.m_ScreenQuality), D3DFORMAT::D3DFMT_D24X8); + + return true; +} + +void TUI::OnDestroy() +{ + RT.destroy(); + ZB.destroy(); + + VERIFY(m_bReady); + m_bReady = false; + UI->IR_Release(); + xr_delete(pInput); + EndEState(); + + EDevice.ShutDown(); +} + +SPBItem *TUI::ProgressStart(float max_val, LPCSTR text) +{ + VERIFY(m_bReady); + SPBItem *item = xr_new(text, "", max_val); + m_ProgressItems.push_back(item); + ELog.Msg(mtInformation, text); + ProgressDraw(); + if (!m_HConsole) + { + AllocConsole(); + m_HConsole = GetStdHandle(STD_OUTPUT_HANDLE); + } + return item; +} +void TUI::ProgressEnd(SPBItem *&pbi) +{ + VERIFY(m_bReady); + if (pbi) + { + PBVecIt it = std::find(m_ProgressItems.begin(), m_ProgressItems.end(), pbi); + VERIFY(it != m_ProgressItems.end()); + m_ProgressItems.erase(it); + xr_delete(pbi); + ProgressDraw(); + if (m_ProgressItems.size() == 0) + { + FreeConsole(); + m_HConsole = 0; + } + } +} + +void TUI::ProgressDraw() +{ + SPBItem *pbi = UI->ProgressLast(); + if (pbi) + { + xr_string txt; + float p, m; + pbi->GetInfo(txt, p, m); + // progress + int val = fis_zero(m) ? 0 : (int)((p / m) * 100); + string2048 out; + xr_sprintf(out, "[%d%%]%s\r\n", val, txt.c_str()); + DWORD dw; + WriteConsole(m_HConsole, out, xr_strlen(out), &dw, NULL); + } +} + +void TUI::OnDrawUI() +{ + UIKeyPressForm::Update(EDevice.fTimeGlobal); + UIEditLightAnim::Update(); + UIImageEditorForm::Update(); + UISoundEditorForm::Update(); + UIMinimapEditorForm::Update(); + UILogForm::Update(); + EDevice.seqDrawUI.Process(); +} + +void TUI::RealResetUI() +{ + m_Flags.set(flResetUI, FALSE); + string_path ini_path; + + const char* rootPath; + + if (Core.SocSdk) + rootPath = "$sdk_root_raw$"; + else + rootPath = "$server_data_root$"; + + if (FS.exist(ini_path, rootPath, UI->EditorName(), "_imgui_default.ini")) + { + UI->Resize(1280, 800); + ImGui::LoadIniSettingsFromDisk(ini_path); + } +} + +void SPBItem::GetInfo(xr_string &txt, float &p, float &m) +{ + if (info.size()) + txt = make_string("%s (%s)", text.c_str(), info.c_str()); + else + txt = make_string("%s", text.c_str()); + p = progress; + m = max; +} +void SPBItem::Inc(LPCSTR info, bool bWarn) +{ + Info(info, bWarn); + Update(progress + 1.f); +} +void SPBItem::Update(float val) +{ + progress = val; + UI->ProgressDraw(); +} +void SPBItem::Info(LPCSTR text, bool bWarn) +{ + if (text && text[0]) + { + info = text; + xr_string txt; + float p, m; + GetInfo(txt, p, m); + ELog.Msg(bWarn ? mtError : mtInformation, txt.c_str()); + UI->ProgressDraw(); + } +} diff --git a/src/editors/xrECore/Editor/ui_main.h b/src/editors/xrECore/Editor/ui_main.h new file mode 100644 index 00000000000..17437a5fc5a --- /dev/null +++ b/src/editors/xrECore/Editor/ui_main.h @@ -0,0 +1,311 @@ +#pragma once +#include "UI_MainCommand.h" +#include "xrEngine/IInputReceiver.h" + +// refs +class CCustomObject; +class TUI_Tools; +class TUI_Tools; +class C3DCursor; + +enum EEditorState +{ + esNone, + esEditScene, + esEditLibrary, + esEditLightAnim, + esBuildLevel +}; + +struct ECORE_API SPBItem +{ + shared_str text; + shared_str info; + float max; + float progress; + +public: + SPBItem(LPCSTR txt, LPCSTR inf, float mx) : text(txt), info(inf), max(mx), progress(0.f) {} + void GetInfo(xr_string &txt, float &p, float &m); + void Inc(LPCSTR info = 0, bool bWarn = false); + void Update(float val); + void Info(LPCSTR text, bool bWarn = false); +}; + +typedef xr_vector EStateList; +typedef EStateList::iterator EStateIt; + +class ECORE_API TUI : public IInputReceiver, public xrUIManager +{ + bool m_AppClosed; + inline void RealQuit() { m_AppClosed = true; } + +protected: + Ivector2 m_Size; + bool m_Size_Maximize; + +protected: + friend class CCustomPreferences; + friend class CEditorRenderDevice; + + TShiftState m_ShiftState; + + bool m_bAppActive; + +protected: + EStateList m_EditorState; + bool bNeedAbort; + +public: + bool m_bReady; + +protected: + Fvector m_Pivot; + +protected: + bool m_SelectionRect; + Ivector2 m_SelStart; + Ivector2 m_SelEnd; + +protected: + enum + { + flRedraw = (1 << 0), + flUpdateScene = (1 << 1), + flResize = (1 << 2), + flNeedQuit = (1 << 3), + flResetUI = (1 << 4), + }; + Flags32 m_Flags; + +protected: + long m_StartTime; + + void PrepareRedraw(); + void Redraw(); + +protected: + void D3D_CreateStateBlocks(); + void D3D_DestroyStateBlocks(); + +public: + virtual void OutUICursorPos() = 0; + virtual void OutGridSize() = 0; + virtual void OutInfo() = 0; + +public: + // non-hidden ops + Ivector2 m_StartCp; + Ivector2 m_CurrentCp; + + Fvector m_CurrentRStart; + Fvector m_CurrentRDir; + + // hidden ops + Ivector2 m_StartCpH; + Ivector2 m_DeltaCpH; + +protected: + bool m_MouseCaptured; + bool m_MouseMultiClickCaptured; + bool bMouseInUse; + + xr_string m_LastHint; + bool m_bHintShowing; + POINT m_HintPoint; + + // mailslot + HANDLE hMailSlot; + +public: + void ShowObjectHint(); + void ShowHint(const xr_string &s); + bool ShowHint(const AStringVec &SS); + void HideHint(); + +public: + // mouse sensetive + float m_MouseSM, m_MouseSS, m_MouseSR; + +protected: + virtual void RealUpdateScene() = 0; + void RealRedrawScene(); + void RealResize(); + void OnFrame(); + +public: + TUI(); + virtual ~TUI(); + + void Quit() { m_Flags.set(flNeedQuit, TRUE); } + + u32 &GetRenderWidth() { return EDevice.m_RenderWidth; } + u32 &GetRenderHeight() { return EDevice.m_RenderHeight; } + int GetRealWidth() { return EDevice.dwWidth; } + int GetRealHeight() { return EDevice.dwHeight; } + + IC float ZFar() { return EDevice.m_Camera.m_Zfar; } + IC TShiftState GetShiftState() { return m_ShiftState; } + + virtual bool OnCreate(); + virtual void OnDestroy(); + + virtual const char *GetCaption() = 0; + + bool IsModified(); + + bool Idle(); + void Resize(int x, int y, bool maximize = false, bool bForced = false) + { + m_Size.set(x, y); + m_Size_Maximize = maximize; + m_Flags.set(flResize | flRedraw, TRUE); + if (bForced) + RealResize(); + } + void Resize(bool bForced = false) + { + m_Flags.set(flResize | flRedraw, TRUE); + if (bForced) + RealResize(); + } + + // add, remove, changing objects/scene + void UpdateScene(bool bForced = false) + { + m_Flags.set(flUpdateScene, TRUE); + if (bForced) + RealUpdateScene(); + } + // only redraw scene + void RedrawScene(bool bForced = false) + { + m_Flags.set(flRedraw, TRUE); + if (bForced) + RealRedrawScene(); + } + + void SetRenderQuality(float q) { EDevice.m_ScreenQuality = q; } + // mouse action + void EnableSelectionRect(bool flag); + void UpdateSelectionRect(const Ivector2 &from, const Ivector2 &to); + + void MouseMultiClickCapture(bool b) { m_MouseMultiClickCaptured = b; } + + bool IsMouseCaptured() { return m_MouseCaptured | m_MouseMultiClickCaptured; } + bool IsMouseInUse() { return bMouseInUse; } + + bool KeyDown(WORD Key, TShiftState Shift); + bool KeyUp(WORD Key, TShiftState Shift); + bool KeyPress(WORD Key, TShiftState Shift); + void MousePress(TShiftState Shift, int X, int Y); + void MouseRelease(TShiftState Shift, int X, int Y); + void MouseMove(TShiftState Shift, int X, int Y); + + void BeginEState(EEditorState st) { m_EditorState.push_back(st); } + void EndEState() { m_EditorState.pop_back(); } + void EndEState(EEditorState st) + { + VERIFY(std::find(m_EditorState.begin(), m_EditorState.end(), st) != m_EditorState.end()); + for (EStateIt it = m_EditorState.end() - 1; it >= m_EditorState.begin(); it--) + if (*it == st) + { + m_EditorState.erase(it, m_EditorState.end()); + break; + } + } + EEditorState GetEState() { return m_EditorState.back(); } + bool ContainEState(EEditorState st) { return std::find(m_EditorState.begin(), m_EditorState.end(), st) != m_EditorState.end(); } + + virtual void OutCameraPos() = 0; + virtual void SetStatus(LPCSTR s, bool bOutLog = true) = 0; + virtual void ResetStatus() = 0; + + // direct input + virtual void IR_OnMouseMove(int x, int y); + + void OnAppActivate(); + void OnAppDeactivate(); + + bool NeedAbort() { return bNeedAbort; } + void NeedBreak() { bNeedAbort = true; } + void ResetBreak() { bNeedAbort = false; } + + virtual bool ApplyShortCut(DWORD Key, TShiftState Shift) = 0; + virtual bool ApplyGlobalShortCut(DWORD Key, TShiftState Shift) = 0; + + void SetGradient(u32 color) { ; } + + void OnDeviceCreate(); + void OnDeviceDestroy(); + + // mailslot +#if 0 + bool CreateMailslot (); + void CheckMailslot (); + void OnReceiveMail (LPCSTR msg); + void SendMail (LPCSTR name, LPCSTR dest, LPCSTR msg); +#endif + + void CheckWindowPos(HWND *form); + + virtual LPCSTR EditorName() = 0; + virtual LPCSTR EditorDesc() = 0; + virtual HICON EditorIcon() { return nullptr; } + + // commands + virtual void RegisterCommands() = 0; + void ClearCommands(); + + CCommandVar CommandRenderFocus(CCommandVar p1, CCommandVar p2); + CCommandVar CommandBreakLastOperation(CCommandVar p1, CCommandVar p2); + CCommandVar CommandRenderResize(CCommandVar p1, CCommandVar p2); + + virtual void SaveSettings(CInifile *) {} + virtual void LoadSettings(CInifile *) {} + +protected: + // progress bar + DEFINE_VECTOR(SPBItem *, PBVec, PBVecIt); + PBVec m_ProgressItems; + +public: + SPBItem *ProgressStart(float max_val, LPCSTR text); + void ProgressEnd(SPBItem *&); + virtual void ProgressDraw(); + SPBItem *ProgressLast() { return m_ProgressItems.empty() ? 0 : m_ProgressItems.back(); } + +public: + ref_rt RT; + ref_rt ZB; + _vector2 RTSize; + +protected: + virtual void OnDrawUI(); + void RealResetUI(); + HANDLE m_HConsole; + +public: + IC void ResetUI(bool bForced = false) + { + if (!bForced) + m_Flags.set(flResetUI, TRUE); + if (bForced) + RealResetUI(); + } + virtual Ivector2 GetRenderMousePosition() const { return Ivector2().set(0, 0); } +}; +//--------------------------------------------------------------------------- +extern ECORE_API TUI *UI; +//--------------------------------------------------------------------------- +void ECORE_API ResetActionToSelect(); +#define COMMAND0(cmd) \ + { \ + ExecCommand(cmd); \ + bExec = true; \ + } +#define COMMAND1(cmd, p0) \ + { \ + ExecCommand(cmd, p0); \ + bExec = true; \ + } diff --git a/src/editors/xrECore/Editor/xrLoadSurface.cpp b/src/editors/xrECore/Editor/xrLoadSurface.cpp new file mode 100644 index 00000000000..8cb3216382c --- /dev/null +++ b/src/editors/xrECore/Editor/xrLoadSurface.cpp @@ -0,0 +1,28 @@ +#include "stdafx.h" +#pragma hdrstop + +//#include "freeimage/freeimage.h" + +struct SExts +{ + xr_vector exts; + void format_register(LPCSTR ext) + { + if (ext && ext[0]) + { + for (u32 i = 0; i < exts.size(); i++) + if (0 == stricmp(exts[i], ext)) + return; + exts.push_back(xr_strdup(ext)); + } + } + u32 size() { return (u32)exts.size(); } + LPSTR operator[](int k) { return exts[k]; } + ~SExts() + { + for (u32 i = 0; i < exts.size(); i++) + xr_free(exts[i]); + exts.clear(); + } +}; +SExts formats; diff --git a/src/editors/xrECore/Engine/GameMtlLib.cpp b/src/editors/xrECore/Engine/GameMtlLib.cpp new file mode 100644 index 00000000000..a758e477d2e --- /dev/null +++ b/src/editors/xrECore/Engine/GameMtlLib.cpp @@ -0,0 +1,171 @@ +#pragma error +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "GameMtlLib.h" + +CGameMtlLibrary GMLib; + +void SGameMtl::Load(IReader &fs) +{ + R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_MAIN)); + ID = fs.r_u32(); + fs.r_stringZ(m_Name); + + if (fs.find_chunk(GAMEMTL_CHUNK_DESC)) + { + fs.r_stringZ(m_Desc); + } + + R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_FLAGS)); + Flags.assign(fs.r_u32()); + + R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_PHYSICS)); + fPHFriction = fs.r_float(); + fPHDamping = fs.r_float(); + fPHSpring = fs.r_float(); + fPHBounceStartVelocity = fs.r_float(); + fPHBouncing = fs.r_float(); + + R_ASSERT(fs.find_chunk(GAMEMTL_CHUNK_FACTORS)); + fShootFactor = fs.r_float(); + fBounceDamageFactor = fs.r_float(); + fVisTransparencyFactor = fs.r_float(); + fSndOcclusionFactor = fs.r_float(); + + if (fs.find_chunk(GAMEMTL_CHUNK_FLOTATION)) + fFlotationFactor = fs.r_float(); + + if (fs.find_chunk(GAMEMTL_CHUNK_INJURIOUS)) + fInjuriousSpeed = fs.r_float(); +} + +void CGameMtlLibrary::Load() +{ + string_path name; + if (!FS.exist(name, _game_data_, GAMEMTL_FILENAME)) + { + Log("! Can't find game material file: ", name); + return; + } + + R_ASSERT(material_pairs.empty()); + R_ASSERT(materials.empty()); + + IReader *F = FS.r_open(name); + IReader &fs = *F; + + R_ASSERT(fs.find_chunk(GAMEMTLS_CHUNK_VERSION)); + u16 version = fs.r_u16(); + if (GAMEMTL_CURRENT_VERSION != version) + { + Log("CGameMtlLibrary: invalid version. Library can't load."); + FS.r_close(F); + return; + } + + R_ASSERT(fs.find_chunk(GAMEMTLS_CHUNK_AUTOINC)); + material_index = fs.r_u32(); + material_pair_index = fs.r_u32(); + + materials.clear(); + material_pairs.clear(); + + IReader *OBJ = fs.open_chunk(GAMEMTLS_CHUNK_MTLS); + if (OBJ) + { + u32 count; + for (IReader *O = OBJ->open_chunk_iterator(count); O; O = OBJ->open_chunk_iterator(count, O)) + { + SGameMtl *M = xr_new(); + M->Load(*O); + materials.push_back(M); + } + OBJ->close(); + } + + OBJ = fs.open_chunk(GAMEMTLS_CHUNK_MTLS_PAIR); + if (OBJ) + { + u32 count; + for (IReader *O = OBJ->open_chunk_iterator(count); O; O = OBJ->open_chunk_iterator(count, O)) + { + SGameMtlPair *M = xr_new(this); + M->Load(*O); + material_pairs.push_back(M); + } + OBJ->close(); + } + +#ifndef _EDITOR + material_count = (u32)materials.size(); + material_pairs_rt.resize(material_count * material_count, 0); + for (GameMtlPairIt p_it = material_pairs.begin(); material_pairs.end() != p_it; ++p_it) + { + SGameMtlPair *S = *p_it; + int idx0 = GetMaterialIdx(S->mtl0) * material_count + GetMaterialIdx(S->mtl1); + int idx1 = GetMaterialIdx(S->mtl1) * material_count + GetMaterialIdx(S->mtl0); + material_pairs_rt[idx0] = S; + material_pairs_rt[idx1] = S; + } +#endif + + /* + for (GameMtlPairIt p_it=material_pairs.begin(); material_pairs.end() != p_it; ++p_it){ + SGameMtlPair* S = *p_it; + for (int k=0; kStepSounds.size(); k++){ + Msg("%40s - 0x%x", S->StepSounds[k].handle->file_name(), S->StepSounds[k].g_type); + } + } + */ + FS.r_close(F); +} + +#ifdef GM_NON_GAME +SGameMtlPair::~SGameMtlPair() +{ +} +void SGameMtlPair::Load(IReader &fs) +{ + shared_str buf; + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_PAIR)); + mtl0 = fs.r_u32(); + mtl1 = fs.r_u32(); + ID = fs.r_u32(); + ID_parent = fs.r_u32(); + u32 own_mask = fs.r_u32(); + if (GAMEMTL_NONE_ID == ID_parent) + OwnProps.one(); + else + OwnProps.assign(own_mask); + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_BREAKING)); + fs.r_stringZ(buf); + BreakingSounds = buf.size() ? *buf : ""; + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_STEP)); + fs.r_stringZ(buf); + StepSounds = buf.size() ? *buf : ""; + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_COLLIDE)); + fs.r_stringZ(buf); + CollideSounds = buf.size() ? *buf : ""; + fs.r_stringZ(buf); + CollideParticles = buf.size() ? *buf : ""; + fs.r_stringZ(buf); + CollideMarks = buf.size() ? *buf : ""; +} +#endif + +#ifdef DEBUG +LPCSTR SGameMtlPair::dbg_Name() +{ + static string256 nm; + SGameMtl *M0 = GMLib.GetMaterialByID(GetMtl0()); + SGameMtl *M1 = GMLib.GetMaterialByID(GetMtl1()); + sprintf(nm, "Pair: %s - %s", *M0->m_Name, *M1->m_Name); + return nm; +} +#endif diff --git a/src/editors/xrECore/Engine/GameMtlLib_Engine.cpp b/src/editors/xrECore/Engine/GameMtlLib_Engine.cpp new file mode 100644 index 00000000000..7543dc1bbde --- /dev/null +++ b/src/editors/xrECore/Engine/GameMtlLib_Engine.cpp @@ -0,0 +1,93 @@ +//--------------------------------------------------------------------------- +#include "stdafx.h" +#pragma hdrstop + +#include "GameMtlLib.h" + +void DestroySounds(SoundVec &lst) +{ + for (SoundIt it = lst.begin(); lst.end() != it; ++it) + it->destroy(); +} + +void DestroyMarks(ShaderVec &lst) +{ + for (ShaderIt it = lst.begin(); lst.end() != it; ++it) + it->destroy(); +} + +void DestroyPSs(PSVec &lst) +{ + // for (PSIt it=lst.begin(); lst.end() != it; ++it) + // EDevice.Resources->Delete(*it); +} + +void CreateSounds(SoundVec &lst, LPCSTR buf) +{ + string128 tmp; + int cnt = _GetItemCount(buf); + R_ASSERT(cnt <= GAMEMTL_SUBITEM_COUNT); + lst.resize(cnt); + for (int k = 0; k < cnt; ++k) + lst[k].create(_GetItem(buf, k, tmp), st_Effect, sg_SourceType); +} + +void CreateMarks(ShaderVec &lst, LPCSTR buf) +{ + string256 tmp; + int cnt = _GetItemCount(buf); + R_ASSERT(cnt <= GAMEMTL_SUBITEM_COUNT); + ref_shader s; + for (int k = 0; k < cnt; ++k) + { + s.create("effects\\wallmark", _GetItem(buf, k, tmp)); + lst.push_back(s); + } +} + +void CreatePSs(PSVec &lst, LPCSTR buf) +{ + string256 tmp; + int cnt = _GetItemCount(buf); + R_ASSERT(cnt <= GAMEMTL_SUBITEM_COUNT); + for (int k = 0; k < cnt; ++k) + lst.push_back(_GetItem(buf, k, tmp)); +} + +SGameMtlPair::~SGameMtlPair() +{ + // destroy all media + DestroySounds(BreakingSounds); + DestroySounds(StepSounds); + DestroySounds(CollideSounds); + DestroyPSs(CollideParticles); + DestroyMarks(CollideMarks); +} + +void SGameMtlPair::Load(IReader &fs) +{ + shared_str buf; + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_PAIR)); + mtl0 = fs.r_u32(); + mtl1 = fs.r_u32(); + ID = fs.r_u32(); + ID_parent = fs.r_u32(); + OwnProps.assign(fs.r_u32()); + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_BREAKING)); + fs.r_stringZ(buf); + CreateSounds(BreakingSounds, *buf); + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_STEP)); + fs.r_stringZ(buf); + CreateSounds(StepSounds, *buf); + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_COLLIDE)); + fs.r_stringZ(buf); + CreateSounds(CollideSounds, *buf); + fs.r_stringZ(buf); + CreatePSs(CollideParticles, *buf); + fs.r_stringZ(buf); + CreateMarks(CollideMarks, *buf); +} diff --git a/src/editors/xrECore/Engine/Image.cpp b/src/editors/xrECore/Engine/Image.cpp new file mode 100644 index 00000000000..db5cdbc96a6 --- /dev/null +++ b/src/editors/xrECore/Engine/Image.cpp @@ -0,0 +1,332 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "Image.h" +#include "tga.h" + +void CImage::Create(u32 w, u32 h, u32 *data) +{ + Create(w, h); + CopyMemory(pData, data, w * h * sizeof(u32)); +} + +void CImage::Create(u32 w, u32 h) +{ + xr_free(pData); + dwWidth = w; + dwHeight = h; + pData = (u32 *)(xr_malloc(w * h * sizeof(u32))); +} + +void CImage::SaveTGA(LPCSTR name, BOOL b24) +{ + // Save + TGAdesc tga; + tga.data = pData; + tga.format = b24 ? IMG_24B : IMG_32B; + tga.height = dwHeight; + tga.width = dwWidth; + tga.scanlenght = dwWidth * 4; + + IWriter *F = FS.w_open(name); + if (F) + { + tga.maketga(*F); + FS.w_close(F); + } + else + { + Log("!Can't save tga:", name); + } +} + +void CImage::Vflip() +{ + R_ASSERT(pData); + for (u32 y = 0; y < dwHeight / 2; y++) + { + u32 y2 = dwHeight - y - 1; + for (u32 x = 0; x < dwWidth; x++) + { + u32 t = GetPixel(x, y); + PutPixel(x, y, GetPixel(x, y2)); + PutPixel(x, y2, t); + } + } +} +void CImage::Hflip() +{ + R_ASSERT(pData); + for (u32 y = 0; y < dwHeight; y++) + { + for (u32 x = 0; x < dwWidth / 2; x++) + { + u32 x2 = dwWidth - x - 1; + u32 t = GetPixel(x, y); + PutPixel(x, y, GetPixel(x2, y)); + PutPixel(x2, y, t); + } + } +} + +IC BYTE ClampColor(float a) +{ + int c = iFloor(a); + if (c < 0) + c = 0; + else if (c > 255) + c = 255; + return BYTE(c); +} + +void CImage::Contrast(float _fc) +{ + R_ASSERT(pData); + + // Apply contrast correction + char *ptr = (char *)pData; + float fc = _fc * 2.f; + for (u32 i = 0; i < dwHeight; i++) + { + for (u32 j = 0; j < dwWidth; j++) + { + BYTE *p = (BYTE *)&(ptr[i * dwWidth * 4 + j * 4]); + p[0] = ClampColor(128.f + fc * (float(p[0]) - 128.f)); // red + p[1] = ClampColor(128.f + fc * (float(p[1]) - 128.f)); // green + p[2] = ClampColor(128.f + fc * (float(p[2]) - 128.f)); // blue + } + } +} +void CImage::Grayscale() +{ + R_ASSERT(pData); + + char *ptr = (char *)pData; + for (u32 i = 0; i < dwHeight; i++) + { + for (u32 j = 0; j < dwWidth; j++) + { + BYTE *p = (BYTE *)&(ptr[i * dwWidth * 4 + j * 4]); + // Approximate values for each component's contribution to luminance. + // Based upon the NTSC standard described in ITU-R Recommendation BT.709. + float grey = float(p[0]) * 0.2125f + float(p[1]) * 0.7154f + float(p[2]) * 0.0721f; + p[0] = p[1] = p[2] = ClampColor(grey); + } + } +} + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// +/* +#pragma pack(push,8) +struct _fileT { + D3DFORMAT fmt; + u32 dwFlags; + u32 dwWidth; + u32 dwHeight; + u32 dwMipCount; + + u32 dwPitch; + + u32 reserved[32-6]; +}; +#pragma pack(pop) + +void CImage::LoadT(char *name) +{ + void* data = DownloadFile(name); + _fileT* hdr = (_fileT*)data; + u32* pixels = (u32 *) ((char *)data + sizeof(_fileT)); + dwWidth = hdr->dwWidth; + dwHeight= hdr->dwHeight; + bAlpha = TUisAlphaPresents(hdr->fmt); + + pData = (u32*)xr_malloc(dwWidth*dwHeight*4); + // CopyMemory(pData,pixels,dwWidth*dwHeight*4); + + xr_free(data); +} +*/ + +//----------------------------------------------------------------------------- +// Load an TGA file +//----------------------------------------------------------------------------- + +#define UPPER_LEFT 0x20 +#define LOWER_LEFT 0x00 + +#define TWO_INTERLEAVE 0x40 +#define FOUR_INTERLEAVE 0x80 + +#define BASE 0 +#define RUN 1 +#define LITERAL 2 + +#ifndef RGBA_GETALPHA +#define RGBA_GETALPHA(rgb) u32((rgb) >> 24) +#define RGBA_GETRED(rgb) u32(((rgb) >> 16) & 0xff) +#define RGBA_GETGREEN(rgb) u32(((rgb) >> 8) & 0xff) +#define RGBA_GETBLUE(rgb) u32((rgb)&0xff) +#endif + +#pragma pack(push, 1) // Gotta pack these structures! +struct TGAHeader +{ + BYTE idlen; + BYTE cmtype; + BYTE imgtype; + + u16 cmorg; + u16 cmlen; + BYTE cmes; + + short xorg; + short yorg; + short width; + short height; + BYTE pixsize; + BYTE desc; +}; +#pragma pack(pop) + +extern u32 *Stbi_Load(const char *, u32 &, u32 &); + +void CImage::Load(LPCSTR name) +{ + VERIFY(!pData); + pData = Stbi_Load((LPSTR)name, dwWidth, dwHeight); +} + +bool CImage::LoadTGA(LPCSTR name) +{ + destructor TGA(FS.r_open(name)); + + TGAHeader hdr; + BOOL hflip, vflip; + + TGA().r(&hdr, sizeof(TGAHeader)); + + if (!((hdr.imgtype == 2) || (hdr.imgtype == 10))) + { + Msg("Unsupported texture format (%s)", name); + return false; + } + if (!((hdr.pixsize == 24) || (hdr.pixsize == 32))) + { + Msg("Texture (%s) - invalid pixsize: %d", name, hdr.pixsize); + return false; + } +#ifndef _EDITOR + if (!btwIsPow2(hdr.width)) + { + Msg("Texture (%s) - invalid width: %d", name, hdr.width); + return false; + } + if (!btwIsPow2(hdr.height)) + { + Msg("Texture (%s) - invalid height: %d", name, hdr.height); + return false; + } +#endif + + // Skip funky stuff + if (hdr.idlen) + TGA().advance(hdr.idlen); + if (hdr.cmlen) + TGA().advance(hdr.cmlen * ((hdr.cmes + 7) / 8)); + + hflip = (hdr.desc & 0x10) ? TRUE : FALSE; // Need hflip + vflip = (hdr.desc & 0x20) ? TRUE : FALSE; // Need vflip + + dwWidth = hdr.width; + dwHeight = hdr.height; + bAlpha = (hdr.pixsize == 32); + + // Alloc memory + pData = (u32 *)xr_malloc(dwWidth * dwHeight * 4); + + u32 pixel; + u32 *ptr = pData; + for (int y = 0; y < hdr.height; y++) + { + u32 dwOffset = y * hdr.width; + + if (0 == (hdr.desc & 0x0010)) + dwOffset = (hdr.height - y - 1) * hdr.width; + for (int x = 0; x < hdr.width;) + { + if (hdr.imgtype == 10) + { + BYTE PacketInfo; + TGA().r(&PacketInfo, 1); + u16 PacketType = u16(0x80 & PacketInfo); + u16 PixelCount = u16((0x007f & PacketInfo) + 1); + if (PacketType) + { + pixel = 0xffffffff; + if (hdr.pixsize == 32) + TGA().r(&pixel, 4); + else + TGA().r(&pixel, 3); + while (PixelCount--) + { + *(ptr + dwOffset + x) = pixel; + x++; + } + } + else + { + while (PixelCount--) + { + pixel = 0xffffffff; + if (hdr.pixsize == 32) + TGA().r(&pixel, 4); + else + TGA().r(&pixel, 3); + *(ptr + dwOffset + x) = pixel; + x++; + } + } + } + else + { + pixel = 0xffffffff; + if (hdr.pixsize == 32) + TGA().r(&pixel, 4); + else + TGA().r(&pixel, 3); + *(ptr + dwOffset + x) = pixel; + x++; + } + } + } + /* + if (hdr.pixsize==24) + { // 24bpp + bAlpha = FALSE; + u32 pixel = 0; + u32* ptr = pData; + for(int iy = 0; iy 0.5 + // across a single edge. Therefore, if you pass in a single quad or cube, it won't work. Any more + // complicated or tessellated mesh should work fine. + +******************************************************************************/ + +#include "stdafx.h" +#pragma hdrstop + +#include "NVMeshMender.h" +#include "nv_math.h" + +bool NVMeshMender::Munge(const NVMeshMender::VAVector &input, + NVMeshMender::VAVector &output, + const float bSmoothCreaseAngleRadians, + const float *pTextureMatrix, + const Option _FixTangents, + const Option _FixCylindricalTexGen, + const Option _WeightNormalsByFaceSize) +{ + typedef xr_map Mapping; + typedef xr_set EdgeSet; + typedef xr_vector> IdenticalVertices; + + IdenticalVertices IdenticalVertices_; + + // make room for potential tex coords, normals, binormals and tangents + output.resize(input.size() + 4); + + Mapping inmap; + Mapping outmap; + + for (unsigned int a = 0; a < input.size(); ++a) + { + inmap[input[a].Name_] = a; + } + + for (unsigned int b = 0; b < output.size(); ++b) + { + output[b].intVector_.clear(); + output[b].floatVector_.clear(); + outmap[output[b].Name_] = b; + } + + for (unsigned int c = 0; c < output.size(); ++c) + { + // for every output that has a match in the input, just copy it over + Mapping::iterator in = inmap.find(output[c].Name_); + if (in != inmap.end()) + { + // copy over existing indices, position, or whatever + output[c] = input[(*in).second]; + } + } + + if (inmap.find("indices") == inmap.end()) + { + SetLastError("Missing indices from input"); + return false; + } + if (outmap.find("indices") == outmap.end()) + { + SetLastError("Missing indices from output"); + return false; + } + + // Go through all required outputs & generate as necessary + if (inmap.find("position") == inmap.end()) + { + SetLastError("Missing position from input"); + return false; + } + if (outmap.find("position") == outmap.end()) + { + SetLastError("Missing position from output"); + return false; + } + + Mapping::iterator pos = outmap.find("position"); + VertexAttribute::FloatVector &positions = output[(*pos).second].floatVector_; + vec3 *pPositions = (vec3 *)(&(positions[0])); + + xr_set EmptySet; + + for (unsigned int i = 0; i < positions.size(); i += 3) + { + IdenticalVertices_.push_back(EmptySet); + } + + // initialize all attributes + for (unsigned int att = 0; att < output.size(); ++att) + { + if (output[att].Name_ != "indices") + { + if (output[att].floatVector_.size() == 0) + { + output[att].floatVector_ = positions; + } + } + } + + Mapping::iterator ind = outmap.find("indices"); + VertexAttribute::IntVector &indices = output[(*ind).second].intVector_; + int *pIndices = (int *)(&(indices[0])); + + vec3 *pNormals = 0; + // vec3* pBiNormals = 0; + // vec3* pTangents = 0; + vec3 *pTex0 = 0; + + bool bNeedNormals = false; + bool bNeedTexCoords = false; + bool bComputeTangentSpace = false; + + // see if texture coords are needed + if (outmap.find("tex0") != outmap.end()) + { + bNeedTexCoords = true; + } + + // see if tangent or binormal are needed + if ((outmap.find("binormal") != outmap.end()) || + (outmap.find("tangent") != outmap.end())) + { + bComputeTangentSpace = true; + } + + // see if normals are needed + if (outmap.find("normal") != outmap.end()) + { + bNeedNormals = true; + } + + // Compute normals. + Mapping::iterator want = outmap.find("normal"); + bool have_normals = (inmap.find("normal") != inmap.end()) ? true : false; + + if (bNeedNormals || bComputeTangentSpace) + { + // see if normals are provided + if (!have_normals) + { + // create normals + if (want == outmap.end()) + { + VertexAttribute norAtt; + norAtt.Name_ = "normal"; + output.push_back(norAtt); + + outmap["normal"] = output.size() - 1; + want = outmap.find("normal"); + } + + // just initialize array so it's the correct size + output[(*want).second].floatVector_ = positions; + + // VertexAttribute::FloatVector& normals = output[ (*want).second ].floatVector_; + + // zero out normals + for (unsigned n = 0; n < positions.size(); ++n) + { + output[(*want).second].floatVector_[n] = nv_zero; + } + + pNormals = (vec3 *)(&(output[(*want).second].floatVector_[0])); + + // calculate face normals for each face + // & add its normal to vertex normal total + for (unsigned int t = 0; t < indices.size(); t += 3) + { + vec3 edge0; + vec3 edge1; + + edge0 = pPositions[indices[t + 1]] - pPositions[indices[t + 0]]; + edge1 = pPositions[indices[t + 2]] - pPositions[indices[t + 0]]; + + exact_normalize(&edge0.x); + exact_normalize(&edge1.x); + + vec3 faceNormal = edge0 ^ edge1; + + if (_WeightNormalsByFaceSize == DontWeightNormalsByFaceSize) + { + // Renormalize face normal, so it's not weighted by face size + exact_normalize(&faceNormal.x); + } + else + { + // Leave it as-is, to weight by face size naturally by the cross product result + } + + pNormals[indices[t + 0]] += faceNormal; + pNormals[indices[t + 1]] += faceNormal; + pNormals[indices[t + 2]] += faceNormal; + } + + // Renormalize each vertex normal + for (unsigned int v = 0; v < output[(*want).second].floatVector_.size() / 3; ++v) + pNormals[v].normalize(); + } + } + + // Compute texture coordinates. + if (bNeedTexCoords || bComputeTangentSpace) + { + if (outmap.find("tex0") == outmap.end()) + { + VertexAttribute texCoordAtt; + texCoordAtt.Name_ = "tex0"; + output.push_back(texCoordAtt); + outmap["tex0"] = output.size() - 1; + } + want = outmap.find("tex0"); + Mapping::iterator have = inmap.find("tex0"); + bool have_texcoords = (have != inmap.end()); + + // see if texcoords are provided + if (have_texcoords) + output[(*want).second].floatVector_ = input[(*have).second].floatVector_; + else + { + // just initialize array so it's the correct size + output[(*want).second].floatVector_ = positions; + + pTex0 = (vec3 *)(&(output[(*want).second].floatVector_[0])); + + // Generate cylindrical coordinates + + // Find min and max positions for object bounding box + + vec3 maxPosition(-flt_max, -flt_max, -flt_max); + vec3 minPosition(flt_max, flt_max, flt_max); + + // there are 1/3 as many vectors as floats + const unsigned int theCount = static_cast(positions.size() / 3.0f); + + for (unsigned int i = 0; i < theCount; ++i) + { + maxPosition.x = nv_max(maxPosition.x, pPositions[i].x); + maxPosition.y = nv_max(maxPosition.y, pPositions[i].y); + maxPosition.z = nv_max(maxPosition.z, pPositions[i].z); + + minPosition.x = nv_min(minPosition.x, pPositions[i].x); + minPosition.y = nv_min(minPosition.y, pPositions[i].y); + minPosition.z = nv_min(minPosition.z, pPositions[i].z); + } + + // Find major, minor and other axis for cylindrical texgen + + vec3 delta = maxPosition - minPosition; + + delta.x = _abs(delta.x); + delta.y = _abs(delta.y); + delta.z = _abs(delta.z); + + bool maxx, maxy, maxz; + maxx = maxy = maxz = false; + bool minz, miny, minx; + minx = miny = minz = false; + + nv_scalar deltaMajor; + + if ((delta.x >= delta.y) && (delta.x >= delta.z)) + { + maxx = true; + deltaMajor = delta.x; + if (delta.y > delta.z) + { + minz = true; + } + else + { + miny = true; + } + } + else if ((delta.z >= delta.y) && (delta.z >= delta.x)) + { + maxz = true; + deltaMajor = delta.z; + if (delta.y > delta.x) + { + minx = true; + } + else + { + miny = true; + } + } + else if ((delta.y >= delta.z) && (delta.y >= delta.x)) + { + maxy = true; + deltaMajor = delta.y; + if (delta.x > delta.z) + { + minz = true; + } + else + { + minx = true; + } + } + + for (unsigned int p = 0; p < theCount; ++p) + { + // Find position relative to center of bounding box + + vec3 texCoords = ((maxPosition + minPosition) / 2.0f) - pPositions[p]; + + nv_scalar Major, Minor, Other = nv_zero; + + if (maxx) + { + Major = texCoords.x; + if (miny) + { + Minor = texCoords.y; + Other = texCoords.z; + } + else + { + Minor = texCoords.z; + Other = texCoords.y; + } + } + else if (maxy) + { + Major = texCoords.y; + if (minx) + { + Minor = texCoords.x; + Other = texCoords.z; + } + else + { + Minor = texCoords.z; + Other = texCoords.x; + } + } + else if (maxz) + { + Major = texCoords.z; + if (miny) + { + Minor = texCoords.y; + Other = texCoords.x; + } + else + { + Minor = texCoords.x; + Other = texCoords.y; + } + } + + nv_scalar longitude = nv_zero; + + // Prevent zero or near-zero from being passed into atan2 + if (_abs(Other) < 0.0001f) + { + if (Other >= nv_zero) + { + Other = 0.0001f; + } + else + { + Other = -0.0001f; + } + } + + // perform cylindrical mapping onto object, and remap from -pi,pi to -1,1 + + longitude = ((atan2(Minor, Other)) / nv_scalar(3.141592654)); + + texCoords.x = 0.5f * longitude + 0.5f; + texCoords.y = (Major / deltaMajor) + 0.5f; + + texCoords.x = nv_max(texCoords.x, nv_zero); + texCoords.y = nv_max(texCoords.y, nv_zero); + + texCoords.x = nv_min(texCoords.x, 1.0f); + texCoords.y = nv_min(texCoords.y, 1.0f); + + pTex0[p].x = texCoords.x - 0.25f; + if (pTex0[p].x < nv_zero) + pTex0[p].x += 1.0; + pTex0[p].y = 1.0f - texCoords.y; + pTex0[p].z = 1.0f; + } + } + + if (_FixCylindricalTexGen == FixCylindricalTexGen) + { + Mapping::iterator texIter = outmap.find("tex0"); + + VertexAttribute::FloatVector &texcoords = (output[(*texIter).second].floatVector_); + + const unsigned int theSize = indices.size(); + + for (unsigned int f = 0; f < theSize; f += 3) + { + for (int v = 0; v < 3; ++v) + { + int start = f + v; + int end = start + 1; + + if (v == 2) + { + end = f; + } + + nv_scalar dS = texcoords[indices[end] * 3 + 0] - texcoords[indices[start] * 3 + 0]; + + nv_scalar newS = nv_zero; + + bool bDoS = false; + + unsigned int theOneToChange = start; + + if (_abs(dS) >= 0.5f) + { + bDoS = true; + if (texcoords[indices[start] * 3 + 0] < texcoords[indices[end] * 3 + 0]) + { + newS = texcoords[indices[start] * 3 + 0] + 1.0f; + } + else + { + theOneToChange = end; + newS = texcoords[indices[end] * 3 + 0] + 1.0f; + } + } + + if (bDoS == true) + { + unsigned int theNewIndex = texcoords.size() / 3; + // Duplicate every part of the vertex + for (unsigned int att = 0; att < output.size(); ++att) + { + // No new indices are created, just vertex attributes + if (output[att].Name_ != "indices") + { + if (output[att].Name_ == "tex0") + { + output[att].floatVector_.push_back((float)newS); // y + output[att].floatVector_.push_back(output[att].floatVector_[indices[theOneToChange] * 3 + 1]); // x + output[att].floatVector_.push_back(output[att].floatVector_[indices[theOneToChange] * 3 + 2]); // z + } + else + { + // *3 b/c we are looking up 3vectors in an array of floats + output[att].floatVector_.push_back(output[att].floatVector_[indices[theOneToChange] * 3 + 0]); // x + output[att].floatVector_.push_back(output[att].floatVector_[indices[theOneToChange] * 3 + 1]); // y + output[att].floatVector_.push_back(output[att].floatVector_[indices[theOneToChange] * 3 + 2]); // z + } + } + } + + IdenticalVertices_.push_back(EmptySet); + + IdenticalVertices_[indices[theOneToChange]].insert(theNewIndex); + IdenticalVertices_[theNewIndex].insert(indices[theOneToChange]); + + // point to where the new vertices will go + indices[theOneToChange] = theNewIndex; + } + + } // for v + + { + + for (int v = 0; v < 3; ++v) + { + int start = f + v; + int end = start + 1; + + if (v == 2) + { + end = f; + } + + nv_scalar dT = texcoords[indices[end] * 3 + 1] - texcoords[indices[start] * 3 + 1]; + + nv_scalar newT = nv_zero; + + bool bDoT = false; + + unsigned int theOneToChange = start; + + if (_abs(dT) >= 0.5f) + { + bDoT = true; + if (texcoords[indices[start] * 3 + 1] < texcoords[indices[end] * 3 + 1]) + { + newT = texcoords[indices[start] * 3 + 1] + 1.0f; + } + else + { + theOneToChange = end; + newT = texcoords[indices[end] * 3 + 1] + 1.0f; + } + } + + if (bDoT == true) + { + unsigned int theNewIndex = texcoords.size() / 3; + // Duplicate every part of the vertex + for (unsigned int att = 0; att < output.size(); ++att) + { + // No new indices are created, just vertex attributes + if (output[att].Name_ != "indices") + { + if (output[att].Name_ == "tex0") + { + output[att].floatVector_.push_back(output[att].floatVector_[indices[theOneToChange] * 3 + 0]); // x + output[att].floatVector_.push_back((float)newT); // y + output[att].floatVector_.push_back(output[att].floatVector_[indices[theOneToChange] * 3 + 2]); // z + } + else + { + // *3 b/c we are looking up 3vectors in an array of floats + output[att].floatVector_.push_back(output[att].floatVector_[indices[theOneToChange] * 3 + 0]); // x + output[att].floatVector_.push_back(output[att].floatVector_[indices[theOneToChange] * 3 + 1]); // y + output[att].floatVector_.push_back(output[att].floatVector_[indices[theOneToChange] * 3 + 2]); // z + } + } + } + + IdenticalVertices_.push_back(EmptySet); + + IdenticalVertices_[theNewIndex].insert(indices[theOneToChange]); + IdenticalVertices_[indices[theOneToChange]].insert(theNewIndex); + + // point to where the new vertices will go + indices[theOneToChange] = theNewIndex; + } + } + + } // for v + + } // for f + } // if fix texgen + if (pTextureMatrix) + { + const mat4 M(pTextureMatrix[0], pTextureMatrix[1], pTextureMatrix[2], pTextureMatrix[3], + pTextureMatrix[4], pTextureMatrix[5], pTextureMatrix[6], pTextureMatrix[7], + pTextureMatrix[8], pTextureMatrix[9], pTextureMatrix[10], pTextureMatrix[11], + pTextureMatrix[12], pTextureMatrix[13], pTextureMatrix[14], pTextureMatrix[15]); + Mapping::iterator texIter = outmap.find("tex0"); + VertexAttribute::FloatVector &texcoords = output[(*texIter).second].floatVector_; + + // now apply matrix + for (unsigned int v = 0; v < texcoords.size(); v += 3) + { + vec3 &V = *reinterpret_cast(&texcoords[v]); + V = V * M; + } + } + } + + if (bComputeTangentSpace) + { + EdgeSet Edges; + + Mapping::iterator texIter = outmap.find("tex0"); + + vec3 *tex = (vec3 *)&(output[(*texIter).second].floatVector_[0]); + + typedef xr_vector VecVector; + + // create tangents + want = outmap.find("tangent"); + if (want == outmap.end()) + { + VertexAttribute tanAtt; + tanAtt.Name_ = "tangent"; + output.push_back(tanAtt); + outmap["tangent"] = output.size() - 1; + want = outmap.find("tangent"); + } + // just initialize array so it's the correct size + output[(*want).second].floatVector_ = positions; + + // create binormals + want = outmap.find("binormal"); + if (want == outmap.end()) + { + VertexAttribute binAtt; + binAtt.Name_ = "binormal"; + output.push_back(binAtt); + outmap["binormal"] = output.size() - 1; + want = outmap.find("binormal"); + } + // just initialize array so it's the correct size + output[(*want).second].floatVector_ = positions; + + // Create a vector of s,t and sxt for each face of the model + VecVector sVector; + VecVector tVector; + VecVector sxtVector; + + const unsigned int theSize = indices.size(); + // for each face, calculate its S,T & SxT vector, & store its edges + for (unsigned int f = 0; f < theSize; f += 3) + { + vec3d edge0; + vec3d edge1; + + vec3d s; + vec3d t; + + // grap position & tex coords again in case they were reallocated + pPositions = (vec3 *)(&(positions[0])); + tex = (vec3 *)(&(output[(*texIter).second].floatVector_[0])); + + double _eps = type_epsilon * 10; + double a, b, c; + vec3d sxt; + + // create an edge(s) out of s and t + edge0.y = tex[indices[f + 1]].x - tex[indices[f]].x; + edge0.z = tex[indices[f + 1]].y - tex[indices[f]].y; + edge1.y = tex[indices[f + 2]].x - tex[indices[f]].x; + edge1.z = tex[indices[f + 2]].y - tex[indices[f]].y; + + // create an edge out of x, s and t + edge0.x = pPositions[indices[f + 1]].x - pPositions[indices[f]].x; + edge1.x = pPositions[indices[f + 2]].x - pPositions[indices[f]].x; + sxt = edge0 ^ edge1; + + a = sxt.x; + b = sxt.y; + c = sxt.z; + double ds_dx = nv_zero; + if (_abs(a) > _eps) + ds_dx = -b / a; + double dt_dx = nv_zero; + if (_abs(a) > _eps) + dt_dx = -c / a; + + // create an edge out of y, s and t + edge0.x = pPositions[indices[f + 1]].y - pPositions[indices[f]].y; + edge1.x = pPositions[indices[f + 2]].y - pPositions[indices[f]].y; + sxt = edge0 ^ edge1; + + a = sxt.x; + b = sxt.y; + c = sxt.z; + double ds_dy = nv_zero; + if (_abs(a) > _eps) + ds_dy = -b / a; + double dt_dy = nv_zero; + if (_abs(a) > _eps) + dt_dy = -c / a; + + // create an edge out of z, s and t + edge0.x = pPositions[indices[f + 1]].z - pPositions[indices[f]].z; + edge1.x = pPositions[indices[f + 2]].z - pPositions[indices[f]].z; + sxt = edge0 ^ edge1; + + a = sxt.x; + b = sxt.y; + c = sxt.z; + double ds_dz = nv_zero; + if (_abs(a) > _eps) + ds_dz = -b / a; + double dt_dz = nv_zero; + if (_abs(a) > _eps) + dt_dz = -c / a; + + // generate coordinate frame from the gradients + s = vec3d(ds_dx, ds_dy, ds_dz); + t = vec3d(dt_dx, dt_dy, dt_dz); + + s.normalize(); + t.normalize(); + sxt = s ^ t; + sxt.normalize(); + + // save vectors for this face + sVector.push_back(vec3(s)); + tVector.push_back(vec3(t)); + sxtVector.push_back(vec3(sxt)); + + if (_FixTangents == FixTangents) + { + // Look for each edge of the triangle in the edge map, in order to find + // a neighboring face along the edge + + for (int e = 0; e < 3; ++e) + { + Edge edge; + + int start = f + e; + int end = start + 1; + + if (e == 2) + { + end = f; + } + // order vertex indices ( low, high ) + edge.v0 = (unsigned int)nv_min((nv_scalar)indices[start], (nv_scalar)indices[end]); + edge.v1 = (unsigned int)nv_max((nv_scalar)indices[start], (nv_scalar)indices[end]); + + EdgeSet::iterator iter = Edges.find(edge); + + // if we are the only triangle with this edge... + if (iter == Edges.end()) + { + // ...then add us to the set of edges + edge.face = f / 3; + Edges.insert(edge); + } + else + { + // otherwise, check our neighbor's s,t & sxt vectors vs our own + const nv_scalar sAgreement = dot(s, sVector[(*iter).face]); + const nv_scalar tAgreement = dot(t, tVector[(*iter).face]); + const nv_scalar sxtAgreement = dot(sxt, sxtVector[(*iter).face]); + + // Check Radian angle split limit + const nv_scalar epsilon = _cos(bSmoothCreaseAngleRadians); + + // if the discontinuity in s, t, or sxt is greater than some epsilon, + // duplicate the vertex so it won't smooth with its neighbor anymore + + if ((_abs(sAgreement) < epsilon) || + (_abs(tAgreement) < epsilon) || + (_abs(sxtAgreement) < epsilon)) + { + // Duplicate two vertices of this edge for this triangle only. + // This way the faces won't smooth with each other, thus + // preventing the tangent basis from becoming degenerate + + // divide by 3 b/c vector is of floats and not vectors + const unsigned int theNewIndex = positions.size() / 3; + + // Duplicate every part of the vertex + for (unsigned int att = 0; att < output.size(); ++att) + { + // No new indices are created, just vertex attributes + if (output[att].Name_ != "indices") + { + // *3 b/c we are looking up 3vectors in an array of floats + output[att].floatVector_.push_back(output[att].floatVector_[indices[start] * 3 + 0]); // x + output[att].floatVector_.push_back(output[att].floatVector_[indices[start] * 3 + 1]); // y + output[att].floatVector_.push_back(output[att].floatVector_[indices[start] * 3 + 2]); // z + + output[att].floatVector_.push_back(output[att].floatVector_[indices[end] * 3 + 0]); // x + output[att].floatVector_.push_back(output[att].floatVector_[indices[end] * 3 + 1]); // y + output[att].floatVector_.push_back(output[att].floatVector_[indices[end] * 3 + 2]); // z + } + } + + IdenticalVertices_.push_back(EmptySet); + IdenticalVertices_.push_back(EmptySet); + + // point to where the new vertices will go + indices[start] = theNewIndex; + indices[end] = theNewIndex + 1; + } + + // Now that the vertices are duplicated, smoothing won't occur over this edge, + // because the two faces will sum their tangent basis vectors into separate indices + } + } + } // if fixtangents + } + + // Allocate std::vector & Zero out average basis for tangent space smoothing + VecVector avgS; + VecVector avgT; + + for (unsigned int p = 0; p < positions.size(); p += 3) + { + avgS.push_back(vec3_null); // do S + avgT.push_back(vec3_null); // now t + } + + // go through faces and add up the bases for each vertex + const int theFaceCount = indices.size() / 3; + + for (unsigned int face = 0; face < (unsigned int)theFaceCount; ++face) + { + // sum bases, so we smooth the tangent space across edges + avgS[pIndices[face * 3]] += sVector[face]; + avgT[pIndices[face * 3]] += tVector[face]; + + avgS[pIndices[face * 3 + 1]] += sVector[face]; + avgT[pIndices[face * 3 + 1]] += tVector[face]; + + avgS[pIndices[face * 3 + 2]] += sVector[face]; + avgT[pIndices[face * 3 + 2]] += tVector[face]; + } + + if (_FixCylindricalTexGen == FixCylindricalTexGen) + { + for (unsigned int v = 0; v < IdenticalVertices_.size(); ++v) + { + // go through each vertex & sum up it's true neighbors + for (xr_set::iterator iter = IdenticalVertices_[v].begin(); + iter != IdenticalVertices_[v].end(); + ++iter) + { + avgS[v] += avgS[*iter]; + avgT[v] += avgT[*iter]; + } + } + } + + Mapping::iterator tangent = outmap.find("tangent"); + Mapping::iterator binormal = outmap.find("binormal"); + + // now renormalize + for (unsigned int b = 0; b < positions.size(); b += 3) + { + *reinterpret_cast(&output[(*tangent).second].floatVector_[b]) = normalize(avgS[b / 3]); // s + *reinterpret_cast(&output[(*binormal).second].floatVector_[b]) = normalize(avgT[b / 3]); // T + } + } + + // At this point, tex coords, normals, binormals and tangents should be generated if necessary, + // and other attributes are simply copied as available + + return true; +} diff --git a/src/editors/xrECore/Engine/NVMeshMender.h b/src/editors/xrECore/Engine/NVMeshMender.h new file mode 100644 index 00000000000..f76362499ad --- /dev/null +++ b/src/editors/xrECore/Engine/NVMeshMender.h @@ -0,0 +1,246 @@ +#ifndef NVMeshMenderH +#define NVMeshMenderH + +/*********************************************************************NVMH2**** +Copyright (C) 1999, 2000, 2001, 2002 NVIDIA Corporation +This file is provided without support, instruction, or implied warranty of any +kind. NVIDIA makes no guarantee of its fitness for a particular purpose and is +not liable under any circumstances for any damages or loss whatsoever arising +from the use or inability to use this file or items derived from it. + +Questions to sim.dietrich@nvidia.com + +Comments: + + This tool is designed to help condition meshes for use in vertex & pixel shaders. + + It can generate normals, texture coordinates, and perhaps most importantly, texture space + basis matrices. It also can fix common texuring problems that come up when bump mapping, including + + Texture Mirroring - When two one halves of a character use the same part of a texture. + + Cylindrical TexGen - When the rendering relies on cylindrical wrapping, texture space computation + won't work right. + + Stretched Basis - When two adjacend faces use wildly different texture mappings, causing stretching + that can ruin per-pixel lighting. + + + Here is an example usage scenario : + + Say you have positions & indices & normals, and want textures, and tangents, and binormals. + and assume that positions, indices, and normals are in STL arrays: vpos, triIndices and vnor respectively. + + xr_vector vpos; + xr_vector triIndices; + xr_vector vnor; + ... + + NVMeshMender aMender; + + + xr_vector inputAtts; // What you have + xr_vector outputAtts; // What you want. + + NVMeshMender::VertexAttribute posAtt; + posAtt.Name_ = "position"; + posAtt.floatVector_ = vpos; + + NVMeshMender::VertexAttribute triIndAtt; + triIndAtt.Name_ = "indices"; + triIndAtt.intVector_ = triIndices; + + NVMeshMender::VertexAttribute norAtt; + norAtt.Name_ = "normal"; + norAtt.floatVector_ = vnor; + + xr_vector texCoords; + NVMeshMender::VertexAttribute texCoordAtt; + texCoordAtt.Name_ = "tex0"; + texCoordAtt.floatVector_;// = texCoords; + + NVMeshMender::VertexAttribute tgtSpaceAtt; + tgtSpaceAtt.Name_ = "tangent"; + + NVMeshMender::VertexAttribute binormalAtt; + binormalAtt.Name_ = "binormal"; + + inputAtts.push_back(posAtt); + inputAtts.push_back(triIndAtt); + inputAtts.push_back(norAtt); + + outputAtts.push_back(posAtt); + outputAtts.push_back(triIndAtt); + outputAtts.push_back(norAtt); + outputAtts.push_back(texCoordAtt); + outputAtts.push_back(tgtSpaceAtt); + outputAtts.push_back(binormalAtt); + + // All inputs except for indices are assumed to be sets of 3 floats + + // "indices" are assumed to be unsigned ints + + // "tex0" is used for the tangent space calculation + + // "tex0" is the only coordinate set generated, and the texture matrix applies only to it + + // All unknown attribute types, including "tex1", "tex2", "random_attribute", "weights", "bones", etc. + // are simply passed through. They will be duplicated as needed just like positions, normals, etc. + + bool bSuccess = aMender.Munge( inputAtts, // these are my positions & indices + outputAtts, // these are the outputs I requested, plus extra stuff generated on my behalf + 3.141592654f / 2.5f, // tangent space smooth angle + NULL, // no Texture matrix applied to my tex0 coords + FixTangents, // fix degenerate bases & texture mirroring + FixCylindricalTexGen // handle cylidrically mapped textures via vertex duplication + WeightNormalsByFaceSize // weight vertex normals by the triangle's size + ); + + + if ( !bSuccess ) return false; + + vpos = outputAtts[0].floatVector_; // Note that there may be more vertices than you sent in. + vnor = outputAtts[2].floatVector_; + xr_vector texCoords = outputAtts[3].floatVector_; // texcoords + xr_vector vtgt = outputAtts[4].floatVector_; // tgts + triIndices = outputAtts[1].intVector_; // new indices. + xr_vector vbin = outputAtts[5].floatVector_; // binormals. + + // Now the outputAtts may contain more vertex then you sent in ! + // This is because in handling tangent space smoothing, and solving texture mirroring & + // cylindrical texture wrapping problems, we partially duplicate vertices. + + // All attributes are duplicated, even unknowns. + + // You may also get things you didn't ask for. For instance, if you ask for tangent space, + // in other words, you ask for "tangent" or "binormal", you will get "normal", "tex0", + // "tangent" and "binormal". You can then ignore things in the output vector that you don't want. + + // If you ask for FixCylindricalTexGen, it will fix any absolute change in texture coordinates > 0.5 + // across a single edge. Therefore, if you pass in a single quad or cube, it won't work. Any more + // complicated or tessellated mesh should work fine. + + +******************************************************************************/ + +#pragma warning(disable : 4995) +#pragma warning(default : 4995) + +class NVMeshMender +{ +private: + mutable xr_vector LastErrors_; + + struct Edge + { + unsigned int v0; + unsigned int v1; + + unsigned int face; + unsigned int face2; + + bool operator==(const Edge &rhs) const + { + return ((v0 == rhs.v0) && (v1 == rhs.v1)); + } + + bool operator<(const Edge &rhs) const + { + if (v0 < rhs.v0) + { + return true; + } + + if (v0 > rhs.v0) + { + return false; + } + + return (v1 < rhs.v1); + } + }; + +public: + void SetLastError(const xr_string &rhs) const + { + LastErrors_.push_back(rhs); + } + + xr_string GetLastError() const + { + xr_string aString; + + if (LastErrors_.size() > 0) + { + aString = LastErrors_.back(); + } + return aString; + } + + struct VertexAttribute + { + xr_string Name_; + + typedef xr_vector IntVector; + IntVector intVector_; + + typedef xr_vector FloatVector; + FloatVector floatVector_; + + VertexAttribute &operator=(const VertexAttribute &rhs) + { + Name_ = rhs.Name_; + intVector_ = rhs.intVector_; + floatVector_ = rhs.floatVector_; + return *this; + } + + VertexAttribute(const char *pName = "") : Name_(pName) { ; } + + VertexAttribute(const VertexAttribute &rhs) + { + *this = rhs; + } + + bool operator==(const VertexAttribute &rhs) + { + return (Name_ == rhs.Name_); + } + + bool operator<(const VertexAttribute &rhs) + { + return (Name_ < rhs.Name_); + } + }; + + typedef xr_vector VAVector; + + enum Option + { + FixTangents, + DontFixTangents, + + FixCylindricalTexGen, + DontFixCylindricalTexGen, + + WeightNormalsByFaceSize, + DontWeightNormalsByFaceSize + }; + + bool Munge(const NVMeshMender::VAVector &input, + NVMeshMender::VAVector &output, + const float bSmoothCreaseAngleRadians = 3.141592654f / 3.0f, + const float *pTextureMatrix = 0, + const Option _FixTangents = FixTangents, + const Option _FixCylindricalTexGen = FixCylindricalTexGen, + const Option _WeightNormalsByFaceSize = WeightNormalsByFaceSize); + bool MungeD3DX(const NVMeshMender::VAVector &input, + NVMeshMender::VAVector &output, + const float bSmoothCreaseAngleRadians = 3.141592654f / 3.0f, + const float *pTextureMatrix = 0, + const Option _FixTangents = FixTangents, + const Option _FixCylindricalTexGen = FixCylindricalTexGen, + const Option _WeightNormalsByFaceSize = WeightNormalsByFaceSize); +}; + +#endif //_NVMeshMender_H_ diff --git a/src/editors/xrECore/Engine/Texture.h b/src/editors/xrECore/Engine/Texture.h new file mode 100644 index 00000000000..99117be4d76 --- /dev/null +++ b/src/editors/xrECore/Engine/Texture.h @@ -0,0 +1,12 @@ +// Texture.h: interface for the CTexture class. +// +////////////////////////////////////////////////////////////////////// + +#if !defined(AFX_TEXTURE_H__0E25CF47_FFEC_11D3_B4E3_4854E82A090D__INCLUDED_) +#define AFX_TEXTURE_H__0E25CF47_FFEC_11D3_B4E3_4854E82A090D__INCLUDED_ +#pragma once + +// Wizzard pack +extern ENGINE_API IDirect3DBaseTexture9 *TWLoader2D(LPCSTR fname); + +#endif // !defined(AFX_TEXTURE_H__0E25CF47_FFEC_11D3_B4E3_4854E82A090D__INCLUDED_) diff --git a/src/editors/xrECore/Engine/ai_sounds.cpp b/src/editors/xrECore/Engine/ai_sounds.cpp new file mode 100644 index 00000000000..2e95eabd491 --- /dev/null +++ b/src/editors/xrECore/Engine/ai_sounds.cpp @@ -0,0 +1,28 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "ai_sounds.h" + +xr_token anomaly_type_token[] = { + {"undefined", sg_Undefined}, + {"Item picking up", SOUND_TYPE_ITEM_PICKING_UP}, + {"Item dropping", SOUND_TYPE_ITEM_DROPPING}, + {"Item taking", SOUND_TYPE_ITEM_TAKING}, + {"Item hiding", SOUND_TYPE_ITEM_HIDING}, + {"Item using", SOUND_TYPE_ITEM_USING}, + {"Weapon shooting", SOUND_TYPE_WEAPON_SHOOTING}, + {"Weapon empty clicking", SOUND_TYPE_WEAPON_EMPTY_CLICKING}, + {"Weapon bullet hit", SOUND_TYPE_WEAPON_BULLET_HIT}, + {"Weapon recharging", SOUND_TYPE_WEAPON_RECHARGING}, + {"NPC dying", SOUND_TYPE_MONSTER_DYING}, + {"NPC injuring", SOUND_TYPE_MONSTER_INJURING}, + {"NPC step", SOUND_TYPE_MONSTER_STEP}, + {"NPC talking", SOUND_TYPE_MONSTER_TALKING}, + {"NPC attacking", SOUND_TYPE_MONSTER_ATTACKING}, + {"NPC eating", SOUND_TYPE_MONSTER_EATING}, + {"Anomaly idle", SOUND_TYPE_ANOMALY_IDLE}, + {"Object breaking", SOUND_TYPE_WORLD_OBJECT_BREAKING}, + {"Object colliding", SOUND_TYPE_WORLD_OBJECT_COLLIDING}, + {"Object exploding", SOUND_TYPE_WORLD_OBJECT_EXPLODING}, + {"World ambient", SOUND_TYPE_WORLD_AMBIENT}, + {0, 0}}; diff --git a/src/editors/xrECore/Engine/ai_sounds.h b/src/editors/xrECore/Engine/ai_sounds.h new file mode 100644 index 00000000000..39ac52e6a05 --- /dev/null +++ b/src/editors/xrECore/Engine/ai_sounds.h @@ -0,0 +1,86 @@ +//////////////////////////////////////////////////////////////////////////// +// Module : ai_sounds.h +// Created : 15.08.2002 +// Modified : 15.08.2002 +// Author : Dmitriy Iassenev +// Description : Sounds for AI personalities +//////////////////////////////////////////////////////////////////////////// + +#ifndef ai_soundsH +#define ai_soundsH + +enum ESoundTypes +{ + SOUND_TYPE_NO_SOUND = 0x00000000ui32, + + SOUND_TYPE_WEAPON = 0x80000000ui32, + SOUND_TYPE_ITEM = 0x40000000ui32, + SOUND_TYPE_MONSTER = 0x20000000ui32, + SOUND_TYPE_ANOMALY = 0x10000000ui32, + SOUND_TYPE_WORLD = 0x08000000ui32, + + SOUND_TYPE_PICKING_UP = 0x04000000ui32, + SOUND_TYPE_DROPPING = 0x02000000ui32, + SOUND_TYPE_HIDING = 0x01000000ui32, + SOUND_TYPE_TAKING = 0x00800000ui32, + SOUND_TYPE_USING = 0x00400000ui32, + + SOUND_TYPE_SHOOTING = 0x00200000ui32, + SOUND_TYPE_EMPTY_CLICKING = 0x00100000ui32, + SOUND_TYPE_BULLET_HIT = 0x00080000ui32, + SOUND_TYPE_RECHARGING = 0x00040000ui32, + + SOUND_TYPE_DYING = 0x00020000ui32, + SOUND_TYPE_INJURING = 0x00010000ui32, + SOUND_TYPE_STEP = 0x00008000ui32, + SOUND_TYPE_TALKING = 0x00004000ui32, + SOUND_TYPE_ATTACKING = 0x00002000ui32, + SOUND_TYPE_EATING = 0x00001000ui32, + + SOUND_TYPE_IDLE = 0x00000800ui32, + + SOUND_TYPE_OBJECT_BREAKING = 0x00000400ui32, + SOUND_TYPE_OBJECT_COLLIDING = 0x00000200ui32, + SOUND_TYPE_OBJECT_EXPLODING = 0x00000100ui32, + SOUND_TYPE_AMBIENT = 0x00000080ui32, + + SOUND_TYPE_ITEM_PICKING_UP = SOUND_TYPE_ITEM | SOUND_TYPE_PICKING_UP, + SOUND_TYPE_ITEM_DROPPING = SOUND_TYPE_ITEM | SOUND_TYPE_DROPPING, + SOUND_TYPE_ITEM_HIDING = SOUND_TYPE_ITEM | SOUND_TYPE_HIDING, + SOUND_TYPE_ITEM_TAKING = SOUND_TYPE_ITEM | SOUND_TYPE_TAKING, + SOUND_TYPE_ITEM_USING = SOUND_TYPE_ITEM | SOUND_TYPE_USING, + + SOUND_TYPE_WEAPON_SHOOTING = SOUND_TYPE_WEAPON | SOUND_TYPE_SHOOTING, + SOUND_TYPE_WEAPON_EMPTY_CLICKING = SOUND_TYPE_WEAPON | SOUND_TYPE_EMPTY_CLICKING, + SOUND_TYPE_WEAPON_BULLET_HIT = SOUND_TYPE_WEAPON | SOUND_TYPE_BULLET_HIT, + SOUND_TYPE_WEAPON_RECHARGING = SOUND_TYPE_WEAPON | SOUND_TYPE_RECHARGING, + + SOUND_TYPE_MONSTER_DYING = SOUND_TYPE_MONSTER | SOUND_TYPE_DYING, + SOUND_TYPE_MONSTER_INJURING = SOUND_TYPE_MONSTER | SOUND_TYPE_INJURING, + SOUND_TYPE_MONSTER_STEP = SOUND_TYPE_MONSTER | SOUND_TYPE_STEP, + SOUND_TYPE_MONSTER_TALKING = SOUND_TYPE_MONSTER | SOUND_TYPE_TALKING, + SOUND_TYPE_MONSTER_ATTACKING = SOUND_TYPE_MONSTER | SOUND_TYPE_ATTACKING, + SOUND_TYPE_MONSTER_EATING = SOUND_TYPE_MONSTER | SOUND_TYPE_EATING, + + SOUND_TYPE_ANOMALY_IDLE = SOUND_TYPE_ANOMALY | SOUND_TYPE_IDLE, + + SOUND_TYPE_WORLD_OBJECT_BREAKING = SOUND_TYPE_WORLD | SOUND_TYPE_OBJECT_BREAKING, + SOUND_TYPE_WORLD_OBJECT_COLLIDING = SOUND_TYPE_WORLD | SOUND_TYPE_OBJECT_COLLIDING, + SOUND_TYPE_WORLD_OBJECT_EXPLODING = SOUND_TYPE_WORLD | SOUND_TYPE_OBJECT_EXPLODING, + SOUND_TYPE_WORLD_AMBIENT = SOUND_TYPE_WORLD | SOUND_TYPE_AMBIENT, + + SOUND_TYPE_WEAPON_PISTOL = SOUND_TYPE_WEAPON, + SOUND_TYPE_WEAPON_GUN = SOUND_TYPE_WEAPON, + SOUND_TYPE_WEAPON_SUBMACHINEGUN = SOUND_TYPE_WEAPON, + SOUND_TYPE_WEAPON_MACHINEGUN = SOUND_TYPE_WEAPON, + SOUND_TYPE_WEAPON_SNIPERRIFLE = SOUND_TYPE_WEAPON, + SOUND_TYPE_WEAPON_GRENADELAUNCHER = SOUND_TYPE_WEAPON, + SOUND_TYPE_WEAPON_ROCKETLAUNCHER = SOUND_TYPE_WEAPON, +}; + +#define CROUCH_SOUND_FACTOR .3f +#define ACCELERATED_SOUND_FACTOR .5f + +extern xr_token anomaly_type_token[]; + +#endif diff --git a/src/editors/xrECore/Engine/bone.cpp b/src/editors/xrECore/Engine/bone.cpp new file mode 100644 index 00000000000..f839ff84fb0 --- /dev/null +++ b/src/editors/xrECore/Engine/bone.cpp @@ -0,0 +1,198 @@ +#include "stdafx.h" +// +//#include "bone.h" +// +//#define BONE_VERSION 0x0002 +////------------------------------------------------------------------------------ +//#define BONE_CHUNK_VERSION 0x0001 +//#define BONE_CHUNK_DEF 0x0002 +//#define BONE_CHUNK_BIND_POSE 0x0003 +//#define BONE_CHUNK_MATERIAL 0x0004 +//#define BONE_CHUNK_SHAPE 0x0005 +//#define BONE_CHUNK_IK_JOINT 0x0006 +//#define BONE_CHUNK_MASS 0x0007 +//#define BONE_CHUNK_FLAGS 0x0008 +//#define BONE_CHUNK_IK_JOINT_BREAK 0x0009 +//#define BONE_CHUNK_IK_JOINT_FRICTION 0x0010 +// +//CBone::CBone() +//{ +// construct(); +// flags.zero(); +// rest_length = 0; +// SelfID = -1; +// parent = 0; +// +// ResetData(); +//} +// +//CBone::~CBone() +//{ +//} +// +//void CBone::ResetData() +//{ +// IK_data.Reset(); +// game_mtl = "default_object"; +// shape.Reset(); +// +// mass = 10.f; +// ; +// center_of_mass.set(0.f, 0.f, 0.f); +//} +// +//void CBone::Save(IWriter &F) +//{ +//#ifdef _LW_EXPORT +// extern void ReplaceSpaceAndLowerCase(shared_str & s); +// ReplaceSpaceAndLowerCase(name); +// ReplaceSpaceAndLowerCase(parent_name); +//#endif +// F.open_chunk(BONE_CHUNK_VERSION); +// F.w_u16(BONE_VERSION); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_DEF); +// F.w_stringZ(name); +// F.w_stringZ(parent_name); +// F.w_stringZ(wmap); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_BIND_POSE); +// F.w_fvector3(rest_offset); +// F.w_fvector3(rest_rotate); +// F.w_float(rest_length); +// F.close_chunk(); +// +// SaveData(F); +//} +// +//void CBone::Load_0(IReader &F) +//{ +// F.r_stringZ(name); +// xr_strlwr(name); +// F.r_stringZ(parent_name); +// xr_strlwr(parent_name); +// F.r_stringZ(wmap); +// F.r_fvector3(rest_offset); +// F.r_fvector3(rest_rotate); +// rest_length = F.r_float(); +// std::swap(rest_rotate.x, rest_rotate.y); +// Reset(); +//} +// +//void CBone::Load_1(IReader &F) +//{ +// R_ASSERT(F.find_chunk(BONE_CHUNK_VERSION)); +// u16 ver = F.r_u16(); +// +// if ((ver != 0x0001) && (ver != BONE_VERSION)) +// return; +// +// R_ASSERT(F.find_chunk(BONE_CHUNK_DEF)); +// F.r_stringZ(name); +// xr_strlwr(name); +// F.r_stringZ(parent_name); +// xr_strlwr(parent_name); +// F.r_stringZ(wmap); +// +// R_ASSERT(F.find_chunk(BONE_CHUNK_BIND_POSE)); +// F.r_fvector3(rest_offset); +// F.r_fvector3(rest_rotate); +// rest_length = F.r_float(); +// +// if (ver == 0x0001) +// std::swap(rest_rotate.x, rest_rotate.y); +// +// LoadData(F); +//} +// +//void CBone::SaveData(IWriter &F) +//{ +// F.open_chunk(BONE_CHUNK_DEF); +// F.w_stringZ(name); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_MATERIAL); +// F.w_stringZ(game_mtl); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_SHAPE); +// F.w(&shape, sizeof(SBoneShape)); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_FLAGS); +// F.w_u32(IK_data.ik_flags.get()); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_IK_JOINT); +// F.w_u32(IK_data.type); +// F.w(IK_data.limits, sizeof(SJointLimit) * 3); +// F.w_float(IK_data.spring_factor); +// F.w_float(IK_data.damping_factor); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_IK_JOINT_BREAK); +// F.w_float(IK_data.break_force); +// F.w_float(IK_data.break_torque); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_IK_JOINT_FRICTION); +// F.w_float(IK_data.friction); +// F.close_chunk(); +// +// F.open_chunk(BONE_CHUNK_MASS); +// F.w_float(mass); +// F.w_fvector3(center_of_mass); +// F.close_chunk(); +//} +// +//void CBone::LoadData(IReader &F) +//{ +// R_ASSERT(F.find_chunk(BONE_CHUNK_DEF)); +// F.r_stringZ(name); +// xr_strlwr(name); +// +// R_ASSERT(F.find_chunk(BONE_CHUNK_MATERIAL)); +// F.r_stringZ(game_mtl); +// +// R_ASSERT(F.find_chunk(BONE_CHUNK_SHAPE)); +// F.r(&shape, sizeof(SBoneShape)); +// +// if (F.find_chunk(BONE_CHUNK_FLAGS)) +// IK_data.ik_flags.assign(F.r_u32()); +// +// R_ASSERT(F.find_chunk(BONE_CHUNK_IK_JOINT)); +// IK_data.type = (EJointType)F.r_u32(); +// F.r(IK_data.limits, sizeof(SJointLimit) * 3); +// IK_data.spring_factor = F.r_float(); +// IK_data.damping_factor = F.r_float(); +// +// if (F.find_chunk(BONE_CHUNK_IK_JOINT_BREAK)) +// { +// IK_data.break_force = F.r_float(); +// IK_data.break_torque = F.r_float(); +// } +// +// if (F.find_chunk(BONE_CHUNK_IK_JOINT_FRICTION)) +// { +// IK_data.friction = F.r_float(); +// } +// +// if (F.find_chunk(BONE_CHUNK_MASS)) +// { +// mass = F.r_float(); +// F.r_fvector3(center_of_mass); +// } +//} +// +//void CBone::CopyData(CBone *bone) +//{ +// game_mtl = bone->game_mtl; +// shape = bone->shape; +// IK_data = bone->IK_data; +// mass = bone->mass; +// center_of_mass = bone->center_of_mass; +//} +// +//#include "../../../xrEngine/bone.cpp" diff --git a/src/editors/xrECore/Engine/cl_collector.cpp b/src/editors/xrECore/Engine/cl_collector.cpp new file mode 100644 index 00000000000..69966916e73 --- /dev/null +++ b/src/editors/xrECore/Engine/cl_collector.cpp @@ -0,0 +1,12 @@ +// cl_collector.cpp: implementation of the Collector class. +// +////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#pragma hdrstop + +#include "cl_collector.h" + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// diff --git a/src/editors/xrECore/Engine/cl_collector.h b/src/editors/xrECore/Engine/cl_collector.h new file mode 100644 index 00000000000..85b72fbac85 --- /dev/null +++ b/src/editors/xrECore/Engine/cl_collector.h @@ -0,0 +1,9 @@ +// cl_collector.h: interface for the Collector class. +// +////////////////////////////////////////////////////////////////////// + +#if !defined(AFX_CL_COLLECTOR_H__F107ABA0_E877_4C5A_8EFF_DAB3A86ABDB6__INCLUDED_) +#define AFX_CL_COLLECTOR_H__F107ABA0_E877_4C5A_8EFF_DAB3A86ABDB6__INCLUDED_ +#pragma once + +#endif // !defined(AFX_CL_COLLECTOR_H__F107ABA0_E877_4C5A_8EFF_DAB3A86ABDB6__INCLUDED_) diff --git a/src/editors/xrECore/Engine/guid_generator.cpp b/src/editors/xrECore/Engine/guid_generator.cpp new file mode 100644 index 00000000000..bc7f82cb9be --- /dev/null +++ b/src/editors/xrECore/Engine/guid_generator.cpp @@ -0,0 +1,43 @@ +//////////////////////////////////////////////////////////////////////////// +// Module : guid_generator.cpp +// Created : 21.03.2005 +// Modified : 21.03.2005 +// Author : Dmitriy Iassenev +// Description : GUID generator +//////////////////////////////////////////////////////////////////////////// +#include "stdafx.h" +#pragma hdrstop + +#include "guid_generator.h" + +#ifdef WINVER +#include +#include +#pragma comment(lib, "rpcrt4.lib") +#endif + +xrGUID generate_guid() +{ + xrGUID result; +#ifdef WINVER + static_assert(sizeof(xrGUID) == sizeof(GUID), "Different_GUID_types"); + GUID _result; + RPC_STATUS gen_result = UuidCreate(&_result); + memcpy(&result, &_result, sizeof(_result)); + switch (gen_result) + { + case RPC_S_OK: + return (result); + case RPC_S_UUID_LOCAL_ONLY: + return (result); + case RPC_S_UUID_NO_ADDRESS: + default: + break; + } +#endif + static_assert(sizeof(result) >= sizeof(u64), "GUID_must_have_size_greater_or_equal_to_the_long_long"); + ZeroMemory(&result, sizeof(result)); + u64 temp = __rdtsc(); + memcpy(&result, &temp, sizeof(temp)); + return (result); +} diff --git a/src/editors/xrECore/Engine/guid_generator.h b/src/editors/xrECore/Engine/guid_generator.h new file mode 100644 index 00000000000..b64ba0163b9 --- /dev/null +++ b/src/editors/xrECore/Engine/guid_generator.h @@ -0,0 +1,4 @@ +#pragma once +#include "Common/GUID.hpp" + +ENGINE_API extern xrGUID generate_guid(); diff --git a/src/editors/xrECore/Engine/nv_algebra.cpp b/src/editors/xrECore/Engine/nv_algebra.cpp new file mode 100644 index 00000000000..3628c04ea01 --- /dev/null +++ b/src/editors/xrECore/Engine/nv_algebra.cpp @@ -0,0 +1,1494 @@ +/*********************************************************************NVMH1**** +File: +nv_algebra.cpp + +Copyright (C) 1999, 2000 NVIDIA Corporation +This file is provided without support, instruction, or implied warranty of any +kind. NVIDIA makes no guarantee of its fitness for a particular purpose and is +not liable under any circumstances for any damages or loss whatsoever arising +from the use or inability to use this file or items derived from it. + +Comments: + + +******************************************************************************/ +#include "stdafx.h" +#pragma hdrstop + +#ifndef nv_algebraH +#include "nv_math.h" +#endif + +#ifndef _WIN32 +#define _isnan isnan +#define _finite finite +#endif + +mat3::mat3() +{ +} + +mat3::mat3(const nv_scalar *array) +{ + memcpy(mat_array, array, sizeof(nv_scalar) * 9); +} + +mat3::mat3(const mat3 &M) +{ + memcpy(mat_array, M.mat_array, sizeof(nv_scalar) * 9); +} + +mat4::mat4() +{ +} + +mat4::mat4(const nv_scalar *array) +{ + memcpy(mat_array, array, sizeof(nv_scalar) * 16); +} + +mat4::mat4(const mat4 &M) +{ + memcpy(mat_array, M.mat_array, sizeof(nv_scalar) * 16); +} + +vec3 &cross(vec3 &u, const vec3 &v, const vec3 &w) +{ + u.x = v.y * w.z - v.z * w.y; + u.y = v.z * w.x - v.x * w.z; + u.z = v.x * w.y - v.y * w.x; + return u; +} + +nv_scalar &dot(nv_scalar &u, const vec3 &v, const vec3 &w) +{ + u = v.x * w.x + v.y * w.y + v.z * w.z; + return u; +} + +nv_scalar dot(const vec3 &v, const vec3 &w) +{ + return v.x * w.x + v.y * w.y + v.z * w.z; +} + +nv_scalar &dot(nv_scalar &u, const vec4 &v, const vec4 &w) +{ + u = v.x * w.x + v.y * w.y + v.z * w.z + v.w * w.w; + return u; +} + +nv_scalar dot(const vec4 &v, const vec4 &w) +{ + return v.x * w.x + v.y * w.y + v.z * w.z + v.w * w.w; +} + +nv_scalar &dot(nv_scalar &u, const vec3 &v, const vec4 &w) +{ + u = v.x * w.x + v.y * w.y + v.z * w.z; + return u; +} + +nv_scalar dot(const vec3 &v, const vec4 &w) +{ + return v.x * w.x + v.y * w.y + v.z * w.z; +} + +nv_scalar &dot(nv_scalar &u, const vec4 &v, const vec3 &w) +{ + u = v.x * w.x + v.y * w.y + v.z * w.z; + return u; +} + +nv_scalar dot(const vec4 &v, const vec3 &w) +{ + return v.x * w.x + v.y * w.y + v.z * w.z; +} + +vec3 &reflect(vec3 &r, const vec3 &n, const vec3 &l) +{ + nv_scalar n_dot_l; + n_dot_l = nv_two * dot(n_dot_l, n, l); + mult(r, l, -nv_one); + madd(r, n, n_dot_l); + return r; +} + +vec3 &madd(vec3 &u, const vec3 &v, const nv_scalar &lambda) +{ + u.x += v.x * lambda; + u.y += v.y * lambda; + u.z += v.z * lambda; + return u; +} + +vec3 &mult(vec3 &u, const vec3 &v, const nv_scalar &lambda) +{ + u.x = v.x * lambda; + u.y = v.y * lambda; + u.z = v.z * lambda; + return u; +} + +vec3 &mult(vec3 &u, const vec3 &v, const vec3 &w) +{ + u.x = v.x * w.x; + u.y = v.y * w.y; + u.z = v.z * w.z; + return u; +} + +vec3 &sub(vec3 &u, const vec3 &v, const vec3 &w) +{ + u.x = v.x - w.x; + u.y = v.y - w.y; + u.z = v.z - w.z; + return u; +} + +vec3 &add(vec3 &u, const vec3 &v, const vec3 &w) +{ + u.x = v.x + w.x; + u.y = v.y + w.y; + u.z = v.z + w.z; + return u; +} + +vec3 &scale(vec3 &u, const nv_scalar s) +{ + u.x *= s; + u.y *= s; + u.z *= s; + return u; +} + +vec4 &scale(vec4 &u, const nv_scalar s) +{ + u.x *= s; + u.y *= s; + u.z *= s; + u.w *= s; + return u; +} + +vec3 &mult(vec3 &u, const mat3 &M, const vec3 &v) +{ + u.x = M.a00 * v.x + M.a01 * v.y + M.a02 * v.z; + u.y = M.a10 * v.x + M.a11 * v.y + M.a12 * v.z; + u.z = M.a20 * v.x + M.a21 * v.y + M.a22 * v.z; + return u; +} + +vec3 &mult(vec3 &u, const vec3 &v, const mat3 &M) +{ + u.x = M.a00 * v.x + M.a10 * v.y + M.a20 * v.z; + u.y = M.a01 * v.x + M.a11 * v.y + M.a21 * v.z; + u.z = M.a02 * v.x + M.a12 * v.y + M.a22 * v.z; + return u; +} + +const vec3 operator*(const mat3 &M, const vec3 &v) +{ + vec3 u; + u.x = M.a00 * v.x + M.a01 * v.y + M.a02 * v.z; + u.y = M.a10 * v.x + M.a11 * v.y + M.a12 * v.z; + u.z = M.a20 * v.x + M.a21 * v.y + M.a22 * v.z; + return u; +} + +const vec3 operator*(const vec3 &v, const mat3 &M) +{ + vec3 u; + u.x = M.a00 * v.x + M.a10 * v.y + M.a20 * v.z; + u.y = M.a01 * v.x + M.a11 * v.y + M.a21 * v.z; + u.z = M.a02 * v.x + M.a12 * v.y + M.a22 * v.z; + return u; +} + +vec4 &mult(vec4 &u, const mat4 &M, const vec4 &v) +{ + u.x = M.a00 * v.x + M.a01 * v.y + M.a02 * v.z + M.a03 * v.w; + u.y = M.a10 * v.x + M.a11 * v.y + M.a12 * v.z + M.a13 * v.w; + u.z = M.a20 * v.x + M.a21 * v.y + M.a22 * v.z + M.a23 * v.w; + u.w = M.a30 * v.x + M.a31 * v.y + M.a32 * v.z + M.a33 * v.w; + return u; +} + +vec4 &mult(vec4 &u, const vec4 &v, const mat4 &M) +{ + u.x = M.a00 * v.x + M.a10 * v.y + M.a20 * v.z + M.a30 * v.w; + u.y = M.a01 * v.x + M.a11 * v.y + M.a21 * v.z + M.a31 * v.w; + u.z = M.a02 * v.x + M.a12 * v.y + M.a22 * v.z + M.a32 * v.w; + u.w = M.a03 * v.x + M.a13 * v.y + M.a23 * v.z + M.a33 * v.w; + return u; +} + +const vec4 operator*(const mat4 &M, const vec4 &v) +{ + vec4 u; + u.x = M.a00 * v.x + M.a01 * v.y + M.a02 * v.z + M.a03 * v.w; + u.y = M.a10 * v.x + M.a11 * v.y + M.a12 * v.z + M.a13 * v.w; + u.z = M.a20 * v.x + M.a21 * v.y + M.a22 * v.z + M.a23 * v.w; + u.w = M.a30 * v.x + M.a31 * v.y + M.a32 * v.z + M.a33 * v.w; + return u; +} + +const vec4 operator*(const vec4 &v, const mat4 &M) +{ + vec4 u; + u.x = M.a00 * v.x + M.a10 * v.y + M.a20 * v.z + M.a30 * v.w; + u.y = M.a01 * v.x + M.a11 * v.y + M.a21 * v.z + M.a31 * v.w; + u.z = M.a02 * v.x + M.a12 * v.y + M.a22 * v.z + M.a32 * v.w; + u.w = M.a03 * v.x + M.a13 * v.y + M.a23 * v.z + M.a33 * v.w; + return u; +} + +vec3 &mult_pos(vec3 &u, const mat4 &M, const vec3 &v) +{ + nv_scalar oow = nv_one / (v.x * M.a30 + v.y * M.a31 + v.z * M.a32 + M.a33); + u.x = (M.a00 * v.x + M.a01 * v.y + M.a02 * v.z + M.a03) * oow; + u.y = (M.a10 * v.x + M.a11 * v.y + M.a12 * v.z + M.a13) * oow; + u.z = (M.a20 * v.x + M.a21 * v.y + M.a22 * v.z + M.a23) * oow; + return u; +} + +vec3 &mult_pos(vec3 &u, const vec3 &v, const mat4 &M) +{ + nv_scalar oow = nv_one / (v.x * M.a03 + v.y * M.a13 + v.z * M.a23 + M.a33); + u.x = (M.a00 * v.x + M.a10 * v.y + M.a20 * v.z + M.a30) * oow; + u.y = (M.a01 * v.x + M.a11 * v.y + M.a21 * v.z + M.a31) * oow; + u.z = (M.a02 * v.x + M.a12 * v.y + M.a22 * v.z + M.a32) * oow; + return u; +} + +vec3 &mult_dir(vec3 &u, const mat4 &M, const vec3 &v) +{ + u.x = M.a00 * v.x + M.a01 * v.y + M.a02 * v.z; + u.y = M.a10 * v.x + M.a11 * v.y + M.a12 * v.z; + u.z = M.a20 * v.x + M.a21 * v.y + M.a22 * v.z; + return u; +} + +vec3 &mult_dir(vec3 &u, const vec3 &v, const mat4 &M) +{ + u.x = M.a00 * v.x + M.a10 * v.y + M.a20 * v.z; + u.y = M.a01 * v.x + M.a11 * v.y + M.a21 * v.z; + u.z = M.a02 * v.x + M.a12 * v.y + M.a22 * v.z; + return u; +} + +vec3 &mult(vec3 &u, const mat4 &M, const vec3 &v) +{ + u.x = M.a00 * v.x + M.a01 * v.y + M.a02 * v.z + M.a03; + u.y = M.a10 * v.x + M.a11 * v.y + M.a12 * v.z + M.a13; + u.z = M.a20 * v.x + M.a21 * v.y + M.a22 * v.z + M.a23; + return u; +} + +vec3 &mult(vec3 &u, const vec3 &v, const mat4 &M) +{ + u.x = M.a00 * v.x + M.a10 * v.y + M.a20 * v.z + M.a30; + u.y = M.a01 * v.x + M.a11 * v.y + M.a21 * v.z + M.a31; + u.z = M.a02 * v.x + M.a12 * v.y + M.a22 * v.z + M.a32; + return u; +} + +mat4 &add(mat4 &A, const mat4 &B) +{ + A.a00 += B.a00; + A.a10 += B.a10; + A.a20 += B.a20; + A.a30 += B.a30; + A.a01 += B.a01; + A.a11 += B.a11; + A.a21 += B.a21; + A.a31 += B.a31; + A.a02 += B.a02; + A.a12 += B.a12; + A.a22 += B.a22; + A.a32 += B.a32; + A.a03 += B.a03; + A.a13 += B.a13; + A.a23 += B.a23; + A.a33 += B.a33; + return A; +} + +mat3 &add(mat3 &A, const mat3 &B) +{ + A.a00 += B.a00; + A.a10 += B.a10; + A.a20 += B.a20; + A.a01 += B.a01; + A.a11 += B.a11; + A.a21 += B.a21; + A.a02 += B.a02; + A.a12 += B.a12; + A.a22 += B.a22; + return A; +} + +// C = A * B + +// C.a00 C.a01 C.a02 C.a03 A.a00 A.a01 A.a02 A.a03 B.a00 B.a01 B.a02 B.a03 +// +// C.a10 C.a11 C.a12 C.a13 A.a10 A.a11 A.a12 A.a13 B.a10 B.a11 B.a12 B.a13 +// +// C.a20 C.a21 C.a22 C.a23 A.a20 A.a21 A.a22 A.a23 B.a20 B.a21 B.a22 B.a23 +// +// C.a30 C.a31 C.a32 C.a33 = A.a30 A.a31 A.a32 A.a33 * B.a30 B.a31 B.a32 B.a33 + +mat4 &mult(mat4 &C, const mat4 &A, const mat4 &B) +{ + C.a00 = A.a00 * B.a00 + A.a01 * B.a10 + A.a02 * B.a20 + A.a03 * B.a30; + C.a10 = A.a10 * B.a00 + A.a11 * B.a10 + A.a12 * B.a20 + A.a13 * B.a30; + C.a20 = A.a20 * B.a00 + A.a21 * B.a10 + A.a22 * B.a20 + A.a23 * B.a30; + C.a30 = A.a30 * B.a00 + A.a31 * B.a10 + A.a32 * B.a20 + A.a33 * B.a30; + C.a01 = A.a00 * B.a01 + A.a01 * B.a11 + A.a02 * B.a21 + A.a03 * B.a31; + C.a11 = A.a10 * B.a01 + A.a11 * B.a11 + A.a12 * B.a21 + A.a13 * B.a31; + C.a21 = A.a20 * B.a01 + A.a21 * B.a11 + A.a22 * B.a21 + A.a23 * B.a31; + C.a31 = A.a30 * B.a01 + A.a31 * B.a11 + A.a32 * B.a21 + A.a33 * B.a31; + C.a02 = A.a00 * B.a02 + A.a01 * B.a12 + A.a02 * B.a22 + A.a03 * B.a32; + C.a12 = A.a10 * B.a02 + A.a11 * B.a12 + A.a12 * B.a22 + A.a13 * B.a32; + C.a22 = A.a20 * B.a02 + A.a21 * B.a12 + A.a22 * B.a22 + A.a23 * B.a32; + C.a32 = A.a30 * B.a02 + A.a31 * B.a12 + A.a32 * B.a22 + A.a33 * B.a32; + C.a03 = A.a00 * B.a03 + A.a01 * B.a13 + A.a02 * B.a23 + A.a03 * B.a33; + C.a13 = A.a10 * B.a03 + A.a11 * B.a13 + A.a12 * B.a23 + A.a13 * B.a33; + C.a23 = A.a20 * B.a03 + A.a21 * B.a13 + A.a22 * B.a23 + A.a23 * B.a33; + C.a33 = A.a30 * B.a03 + A.a31 * B.a13 + A.a32 * B.a23 + A.a33 * B.a33; + return C; +} + +mat4 mat4::operator*(const mat4 &B) const +{ + mat4 C; + C.a00 = a00 * B.a00 + a01 * B.a10 + a02 * B.a20 + a03 * B.a30; + C.a10 = a10 * B.a00 + a11 * B.a10 + a12 * B.a20 + a13 * B.a30; + C.a20 = a20 * B.a00 + a21 * B.a10 + a22 * B.a20 + a23 * B.a30; + C.a30 = a30 * B.a00 + a31 * B.a10 + a32 * B.a20 + a33 * B.a30; + C.a01 = a00 * B.a01 + a01 * B.a11 + a02 * B.a21 + a03 * B.a31; + C.a11 = a10 * B.a01 + a11 * B.a11 + a12 * B.a21 + a13 * B.a31; + C.a21 = a20 * B.a01 + a21 * B.a11 + a22 * B.a21 + a23 * B.a31; + C.a31 = a30 * B.a01 + a31 * B.a11 + a32 * B.a21 + a33 * B.a31; + C.a02 = a00 * B.a02 + a01 * B.a12 + a02 * B.a22 + a03 * B.a32; + C.a12 = a10 * B.a02 + a11 * B.a12 + a12 * B.a22 + a13 * B.a32; + C.a22 = a20 * B.a02 + a21 * B.a12 + a22 * B.a22 + a23 * B.a32; + C.a32 = a30 * B.a02 + a31 * B.a12 + a32 * B.a22 + a33 * B.a32; + C.a03 = a00 * B.a03 + a01 * B.a13 + a02 * B.a23 + a03 * B.a33; + C.a13 = a10 * B.a03 + a11 * B.a13 + a12 * B.a23 + a13 * B.a33; + C.a23 = a20 * B.a03 + a21 * B.a13 + a22 * B.a23 + a23 * B.a33; + C.a33 = a30 * B.a03 + a31 * B.a13 + a32 * B.a23 + a33 * B.a33; + return C; +} + +// C = A * B + +// C.a00 C.a01 C.a02 A.a00 A.a01 A.a02 B.a00 B.a01 B.a02 +// +// C.a10 C.a11 C.a12 A.a10 A.a11 A.a12 B.a10 B.a11 B.a12 +// +// C.a20 C.a21 C.a22 = A.a20 A.a21 A.a22 * B.a20 B.a21 B.a22 + +mat3 &mult(mat3 &C, const mat3 &A, const mat3 &B) +{ + C.a00 = A.a00 * B.a00 + A.a01 * B.a10 + A.a02 * B.a20; + C.a10 = A.a10 * B.a00 + A.a11 * B.a10 + A.a12 * B.a20; + C.a20 = A.a20 * B.a00 + A.a21 * B.a10 + A.a22 * B.a20; + C.a01 = A.a00 * B.a01 + A.a01 * B.a11 + A.a02 * B.a21; + C.a11 = A.a10 * B.a01 + A.a11 * B.a11 + A.a12 * B.a21; + C.a21 = A.a20 * B.a01 + A.a21 * B.a11 + A.a22 * B.a21; + C.a02 = A.a00 * B.a02 + A.a01 * B.a12 + A.a02 * B.a22; + C.a12 = A.a10 * B.a02 + A.a11 * B.a12 + A.a12 * B.a22; + C.a22 = A.a20 * B.a02 + A.a21 * B.a12 + A.a22 * B.a22; + return C; +} + +mat3 &transpose(mat3 &A) +{ + nv_scalar tmp; + tmp = A.a01; + A.a01 = A.a10; + A.a10 = tmp; + + tmp = A.a02; + A.a02 = A.a20; + A.a20 = tmp; + + tmp = A.a12; + A.a12 = A.a21; + A.a21 = tmp; + return A; +} + +mat4 &transpose(mat4 &A) +{ + nv_scalar tmp; + tmp = A.a01; + A.a01 = A.a10; + A.a10 = tmp; + + tmp = A.a02; + A.a02 = A.a20; + A.a20 = tmp; + + tmp = A.a03; + A.a03 = A.a30; + A.a30 = tmp; + + tmp = A.a12; + A.a12 = A.a21; + A.a21 = tmp; + + tmp = A.a13; + A.a13 = A.a31; + A.a31 = tmp; + + tmp = A.a23; + A.a23 = A.a32; + A.a32 = tmp; + return A; +} + +mat4 &transpose(mat4 &B, const mat4 &A) +{ + B.a00 = A.a00; + B.a01 = A.a10; + B.a02 = A.a20; + B.a03 = A.a30; + B.a10 = A.a01; + B.a11 = A.a11; + B.a12 = A.a21; + B.a13 = A.a31; + B.a20 = A.a02; + B.a21 = A.a12; + B.a22 = A.a22; + B.a23 = A.a32; + B.a30 = A.a03; + B.a31 = A.a13; + B.a32 = A.a23; + B.a33 = A.a33; + return B; +} + +mat3 &transpose(mat3 &B, const mat3 &A) +{ + B.a00 = A.a00; + B.a01 = A.a10; + B.a02 = A.a20; + B.a10 = A.a01; + B.a11 = A.a11; + B.a12 = A.a21; + B.a20 = A.a02; + B.a21 = A.a12; + B.a22 = A.a22; + return B; +} + +/* + calculate the determinent of a 2x2 matrix in the from + + | a1 a2 | + | b1 b2 | + +*/ +nv_scalar det2x2(nv_scalar a1, nv_scalar a2, nv_scalar b1, nv_scalar b2) +{ + return a1 * b2 - b1 * a2; +} + +/* + calculate the determinent of a 3x3 matrix in the from + + | a1 a2 a3 | + | b1 b2 b3 | + | c1 c2 c3 | + +*/ +nv_scalar det3x3(nv_scalar a1, nv_scalar a2, nv_scalar a3, + nv_scalar b1, nv_scalar b2, nv_scalar b3, + nv_scalar c1, nv_scalar c2, nv_scalar c3) +{ + return a1 * det2x2(b2, b3, c2, c3) - b1 * det2x2(a2, a3, c2, c3) + c1 * det2x2(a2, a3, b2, b3); +} + +mat4 &invert(mat4 &B, const mat4 &A) +{ + nv_scalar det, oodet; + + B.a00 = det3x3(A.a11, A.a21, A.a31, A.a12, A.a22, A.a32, A.a13, A.a23, A.a33); + B.a10 = -det3x3(A.a10, A.a20, A.a30, A.a12, A.a22, A.a32, A.a13, A.a23, A.a33); + B.a20 = det3x3(A.a10, A.a20, A.a30, A.a11, A.a21, A.a31, A.a13, A.a23, A.a33); + B.a30 = -det3x3(A.a10, A.a20, A.a30, A.a11, A.a21, A.a31, A.a12, A.a22, A.a32); + + B.a01 = -det3x3(A.a01, A.a21, A.a31, A.a02, A.a22, A.a32, A.a03, A.a23, A.a33); + B.a11 = det3x3(A.a00, A.a20, A.a30, A.a02, A.a22, A.a32, A.a03, A.a23, A.a33); + B.a21 = -det3x3(A.a00, A.a20, A.a30, A.a01, A.a21, A.a31, A.a03, A.a23, A.a33); + B.a31 = det3x3(A.a00, A.a20, A.a30, A.a01, A.a21, A.a31, A.a02, A.a22, A.a32); + + B.a02 = det3x3(A.a01, A.a11, A.a31, A.a02, A.a12, A.a32, A.a03, A.a13, A.a33); + B.a12 = -det3x3(A.a00, A.a10, A.a30, A.a02, A.a12, A.a32, A.a03, A.a13, A.a33); + B.a22 = det3x3(A.a00, A.a10, A.a30, A.a01, A.a11, A.a31, A.a03, A.a13, A.a33); + B.a32 = -det3x3(A.a00, A.a10, A.a30, A.a01, A.a11, A.a31, A.a02, A.a12, A.a32); + + B.a03 = -det3x3(A.a01, A.a11, A.a21, A.a02, A.a12, A.a22, A.a03, A.a13, A.a23); + B.a13 = det3x3(A.a00, A.a10, A.a20, A.a02, A.a12, A.a22, A.a03, A.a13, A.a23); + B.a23 = -det3x3(A.a00, A.a10, A.a20, A.a01, A.a11, A.a21, A.a03, A.a13, A.a23); + B.a33 = det3x3(A.a00, A.a10, A.a20, A.a01, A.a11, A.a21, A.a02, A.a12, A.a22); + + det = (A.a00 * B.a00) + (A.a01 * B.a10) + (A.a02 * B.a20) + (A.a03 * B.a30); + + oodet = nv_one / det; + + B.a00 *= oodet; + B.a10 *= oodet; + B.a20 *= oodet; + B.a30 *= oodet; + + B.a01 *= oodet; + B.a11 *= oodet; + B.a21 *= oodet; + B.a31 *= oodet; + + B.a02 *= oodet; + B.a12 *= oodet; + B.a22 *= oodet; + B.a32 *= oodet; + + B.a03 *= oodet; + B.a13 *= oodet; + B.a23 *= oodet; + B.a33 *= oodet; + + return B; +} + +mat4 &invert_rot_trans(mat4 &B, const mat4 &A) +{ + B.a00 = A.a00; + B.a10 = A.a01; + B.a20 = A.a02; + B.a30 = A.a30; + B.a01 = A.a10; + B.a11 = A.a11; + B.a21 = A.a12; + B.a31 = A.a31; + B.a02 = A.a20; + B.a12 = A.a21; + B.a22 = A.a22; + B.a32 = A.a32; + B.a03 = -(A.a00 * A.a03 + A.a10 * A.a13 + A.a20 * A.a23); + B.a13 = -(A.a01 * A.a03 + A.a11 * A.a13 + A.a21 * A.a23); + B.a23 = -(A.a02 * A.a03 + A.a12 * A.a13 + A.a22 * A.a23); + B.a33 = A.a33; + return B; +} + +nv_scalar det(const mat3 &A) +{ + return det3x3(A.a00, A.a01, A.a02, + A.a10, A.a11, A.a12, + A.a20, A.a21, A.a22); +} + +mat3 &invert(mat3 &B, const mat3 &A) +{ + nv_scalar det, oodet; + + B.a00 = (A.a11 * A.a22 - A.a21 * A.a12); + B.a10 = -(A.a10 * A.a22 - A.a20 * A.a12); + B.a20 = (A.a10 * A.a21 - A.a20 * A.a11); + B.a01 = -(A.a01 * A.a22 - A.a21 * A.a02); + B.a11 = (A.a00 * A.a22 - A.a20 * A.a02); + B.a21 = -(A.a00 * A.a21 - A.a20 * A.a01); + B.a02 = (A.a01 * A.a12 - A.a11 * A.a02); + B.a12 = -(A.a00 * A.a12 - A.a10 * A.a02); + B.a22 = (A.a00 * A.a11 - A.a10 * A.a01); + + det = (A.a00 * B.a00) + (A.a01 * B.a10) + (A.a02 * B.a20); + + oodet = nv_one / det; + + B.a00 *= oodet; + B.a01 *= oodet; + B.a02 *= oodet; + B.a10 *= oodet; + B.a11 *= oodet; + B.a12 *= oodet; + B.a20 *= oodet; + B.a21 *= oodet; + B.a22 *= oodet; + return B; +} + +vec3 &normalize(vec3 &u) +{ + nv_scalar norm = _sqrt(u.x * u.x + u.y * u.y + u.z * u.z); + if (norm > nv_eps) + norm = nv_one / norm; + else + norm = nv_zero; + return scale(u, norm); +} + +vec4 &normalize(vec4 &u) +{ + nv_scalar norm = _sqrt(u.x * u.x + u.y * u.y + u.z * u.z + u.w * u.w); + if (norm > nv_eps) + norm = nv_one / norm; + else + norm = nv_zero; + return scale(u, norm); +} + +quat &normalize(quat &p) +{ + nv_scalar norm = _sqrt(p.x * p.x + p.y * p.y + p.z * p.z + p.w * p.w); + if (norm > nv_eps) + norm = nv_one / norm; + else + norm = nv_zero; + p.x *= norm; + p.y *= norm; + p.z *= norm; + p.w *= norm; + return p; +} + +mat4 &look_at(mat4 &M, const vec3 &eye, const vec3 ¢er, const vec3 &up) +{ + vec3 x, y, z; + + // make rotation matrix + + // Z vector + z.x = eye.x - center.x; + z.y = eye.y - center.y; + z.z = eye.z - center.z; + normalize(z); + + // Y vector + y.x = up.x; + y.y = up.y; + y.z = up.z; + + // X vector = Y cross Z + cross(x, y, z); + + // Recompute Y = Z cross X + cross(y, z, x); + + // cross product gives area of parallelogram, which is < 1.0 for + // non-perpendicular unit-length vectors; so normalize x, y here + normalize(x); + normalize(y); + + M.a00 = x.x; + M.a01 = x.y; + M.a02 = x.z; + M.a03 = -x.x * eye.x - x.y * eye.y - x.z * eye.z; + M.a10 = y.x; + M.a11 = y.y; + M.a12 = y.z; + M.a13 = -y.x * eye.x - y.y * eye.y - y.z * eye.z; + M.a20 = z.x; + M.a21 = z.y; + M.a22 = z.z; + M.a23 = -z.x * eye.x - z.y * eye.y - z.z * eye.z; + M.a30 = nv_zero; + M.a31 = nv_zero; + M.a32 = nv_zero; + M.a33 = nv_one; + return M; +} + +mat4 &frustum(mat4 &M, const nv_scalar l, const nv_scalar r, const nv_scalar b, + const nv_scalar t, const nv_scalar n, const nv_scalar f) +{ + M.a00 = (nv_two * n) / (r - l); + M.a10 = 0.0; + M.a20 = 0.0; + M.a30 = 0.0; + + M.a01 = 0.0; + M.a11 = (nv_two * n) / (t - b); + M.a21 = 0.0; + M.a31 = 0.0; + + M.a02 = (r + l) / (r - l); + M.a12 = (t + b) / (t - b); + M.a22 = -(f + n) / (f - n); + M.a32 = -nv_one; + + M.a03 = 0.0; + M.a13 = 0.0; + M.a23 = -(nv_two * f * n) / (f - n); + M.a33 = 0.0; + return M; +} + +mat4 &perspective(mat4 &M, const nv_scalar fovy, const nv_scalar aspect, const nv_scalar n, const nv_scalar f) +{ + nv_scalar xmin, xmax, ymin, ymax; + + ymax = n * tan(fovy * nv_to_rad * nv_zero_5); + ymin = -ymax; + + xmin = ymin * aspect; + xmax = ymax * aspect; + + return frustum(M, xmin, xmax, ymin, ymax, n, f); +} + +const quat quat::Identity(0, 0, 0, 1); + +quat::quat(nv_scalar x, nv_scalar y, nv_scalar z, nv_scalar w) : x(x), y(y), z(z), w(w) +{ +} + +quat::quat(const quat &quat) +{ + x = quat.x; + y = quat.y; + z = quat.z; + w = quat.w; +} + +quat::quat(const vec3 &axis, nv_scalar angle) +{ + nv_scalar len = axis.norm(); + if (len) + { + nv_scalar invLen = 1 / len; + nv_scalar angle2 = angle / 2; + nv_scalar scale = _sin(angle2) * invLen; + x = scale * axis[0]; + y = scale * axis[1]; + z = scale * axis[2]; + w = _cos(angle2); + } +} + +quat::quat(const mat3 &rot) +{ + FromMatrix(rot); +} + +quat &quat::operator=(const quat &quat) +{ + x = quat.x; + y = quat.y; + z = quat.z; + w = quat.w; + return *this; +} + +quat quat::Inverse() +{ + return quat(-x, -y, -z, w); +} + +void quat::Normalize() +{ + nv_scalar len = _sqrt(x * x + y * y + z * z + w * w); + if (len > 0) + { + nv_scalar invLen = 1 / len; + x *= invLen; + y *= invLen; + z *= invLen; + w *= invLen; + } +} + +void quat::FromMatrix(const mat3 &mat) +{ + nv_scalar trace = mat(0, 0) + mat(1, 1) + mat(2, 2); + if (trace > 0) + { + nv_scalar scale = _sqrt(trace + 1.0f); + w = 0.5f * scale; + scale = 0.5f / scale; + x = scale * (mat(2, 1) - mat(1, 2)); + y = scale * (mat(0, 2) - mat(2, 0)); + z = scale * (mat(1, 0) - mat(0, 1)); + } + else + { + static int next[] = {1, 2, 0}; + int i = 0; + if (mat(1, 1) > mat(0, 0)) + i = 1; + if (mat(2, 2) > mat(i, i)) + i = 2; + int j = next[i]; + int k = next[j]; + nv_scalar scale = _sqrt(mat(i, i) - mat(j, j) - mat(k, k) + 1); + nv_scalar *q[] = {&x, &y, &z}; + *q[i] = 0.5f * scale; + scale = 0.5f / scale; + w = scale * (mat(k, j) - mat(j, k)); + *q[j] = scale * (mat(j, i) + mat(i, j)); + *q[k] = scale * (mat(k, i) + mat(i, k)); + } +} + +void quat::ToMatrix(mat3 &mat) const +{ + nv_scalar x2 = x * 2; + nv_scalar y2 = y * 2; + nv_scalar z2 = z * 2; + nv_scalar wx = x2 * w; + nv_scalar wy = y2 * w; + nv_scalar wz = z2 * w; + nv_scalar xx = x2 * x; + nv_scalar xy = y2 * x; + nv_scalar xz = z2 * x; + nv_scalar yy = y2 * y; + nv_scalar yz = z2 * y; + nv_scalar zz = z2 * z; + mat(0, 0) = 1 - (yy + zz); + mat(0, 1) = xy - wz; + mat(0, 2) = xz + wy; + mat(1, 0) = xy + wz; + mat(1, 1) = 1 - (xx + zz); + mat(1, 2) = yz - wx; + mat(2, 0) = xz - wy; + mat(2, 1) = yz + wx; + mat(2, 2) = 1 - (xx + yy); +} + +const quat operator*(const quat &p, const quat &q) +{ + return quat( + p.w * q.x + p.x * q.w + p.y * q.z - p.z * q.y, + p.w * q.y + p.y * q.w + p.z * q.x - p.x * q.z, + p.w * q.z + p.z * q.w + p.x * q.y - p.y * q.x, + p.w * q.w - p.x * q.x - p.y * q.y - p.z * q.z); +} + +quat &quat::operator*=(const quat &quat) +{ + *this = *this * quat; + return *this; +} + +mat3 &quat_2_mat(mat3 &M, const quat &q) +{ + q.ToMatrix(M); + return M; +} + +quat &mat_2_quat(quat &q, const mat3 &M) +{ + q.FromMatrix(M); + return q; +} + +quat &mat_2_quat(quat &q, const mat4 &M) +{ + mat3 m; + M.get_rot(m); + q.FromMatrix(m); + return q; +} + +/* + Given an axis and angle, compute quaternion. + */ +quat &axis_to_quat(quat &q, const vec3 &a, const nv_scalar phi) +{ + vec3 tmp(a.x, a.y, a.z); + + normalize(tmp); + nv_scalar s = _sin(phi / nv_two); + q.x = s * tmp.x; + q.y = s * tmp.y; + q.z = s * tmp.z; + q.w = _cos(phi / nv_two); + return q; +} + +quat &conj(quat &p) +{ + p.x = -p.x; + p.y = -p.y; + p.z = -p.z; + return p; +} + +quat &conj(quat &p, const quat &q) +{ + p.x = -q.x; + p.y = -q.y; + p.z = -q.z; + p.w = q.w; + return p; +} + +quat &add_quats(quat &p, const quat &q1, const quat &q2) +{ + quat t1, t2; + + t1 = q1; + t1.x *= q2.w; + t1.y *= q2.w; + t1.z *= q2.w; + + t2 = q2; + t2.x *= q1.w; + t2.y *= q1.w; + t2.z *= q1.w; + + p.x = (q2.y * q1.z) - (q2.z * q1.y) + t1.x + t2.x; + p.y = (q2.z * q1.x) - (q2.x * q1.z) + t1.y + t2.y; + p.z = (q2.x * q1.y) - (q2.y * q1.x) + t1.z + t2.z; + p.w = q1.w * q2.w - (q1.x * q2.x + q1.y * q2.y + q1.z * q2.z); + + return p; +} + +nv_scalar &dot(nv_scalar &s, const quat &q1, const quat &q2) +{ + s = q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w; + return s; +} + +nv_scalar dot(const quat &q1, const quat &q2) +{ + return q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w; +} + +#ifndef acosf +#define acosf acos +#endif + +quat &slerp_quats(quat &p, nv_scalar s, const quat &q1, const quat &q2) +{ + nv_scalar cosine = dot(q1, q2); + if (cosine < -1) + cosine = -1; + else if (cosine > 1) + cosine = 1; + nv_scalar angle = (nv_scalar)acosf(cosine); + if (_abs(angle) < nv_eps) + { + p = q1; + return p; + } + nv_scalar sine = _sin(angle); + nv_scalar sineInv = 1.0f / sine; + nv_scalar c1 = _sin((1.0f - s) * angle) * sineInv; + nv_scalar c2 = _sin(s * angle) * sineInv; + p.x = c1 * q1.x + c2 * q2.x; + p.y = c1 * q1.y + c2 * q2.y; + p.z = c1 * q1.z + c2 * q2.z; + p.w = c1 * q1.w + c2 * q2.w; + return p; +} + +const int HALF_RAND = (RAND_MAX / 2); + +nv_scalar nv_random() +{ + return ((nv_scalar)(rand() - HALF_RAND) / (nv_scalar)HALF_RAND); +} + +// v is normalized +// theta in radians +void mat3::set_rot(const nv_scalar &theta, const vec3 &v) +{ + nv_scalar ct = nv_scalar(_cos(theta)); + nv_scalar st = nv_scalar(_sin(theta)); + + nv_scalar xx = v.x * v.x; + nv_scalar yy = v.y * v.y; + nv_scalar zz = v.z * v.z; + nv_scalar xy = v.x * v.y; + nv_scalar xz = v.x * v.z; + nv_scalar yz = v.y * v.z; + + a00 = xx + ct * (1 - xx); + a01 = xy + ct * (-xy) + st * -v.z; + a02 = xz + ct * (-xz) + st * v.y; + + a10 = xy + ct * (-xy) + st * v.z; + a11 = yy + ct * (1 - yy); + a12 = yz + ct * (-yz) + st * -v.x; + + a20 = xz + ct * (-xz) + st * -v.y; + a21 = yz + ct * (-yz) + st * v.x; + a22 = zz + ct * (1 - zz); +} + +void mat3::set_rot(const vec3 &u, const vec3 &v) +{ + nv_scalar phi; + nv_scalar h; + nv_scalar lambda; + vec3 w; + + cross(w, u, v); + dot(phi, u, v); + dot(lambda, w, w); + if (lambda > nv_eps) + h = (nv_one - phi) / lambda; + else + h = lambda; + + nv_scalar hxy = w.x * w.y * h; + nv_scalar hxz = w.x * w.z * h; + nv_scalar hyz = w.y * w.z * h; + + a00 = phi + w.x * w.x * h; + a01 = hxy - w.z; + a02 = hxz + w.y; + + a10 = hxy + w.z; + a11 = phi + w.y * w.y * h; + a12 = hyz - w.x; + + a20 = hxz - w.y; + a21 = hyz + w.x; + a22 = phi + w.z * w.z * h; +} + +void mat4::set_rot(const quat &q) +{ + mat3 m; + q.ToMatrix(m); + set_rot(m); +} + +// v is normalized +// theta in radians +void mat4::set_rot(const nv_scalar &theta, const vec3 &v) +{ + nv_scalar ct = nv_scalar(_cos(theta)); + nv_scalar st = nv_scalar(_sin(theta)); + + nv_scalar xx = v.x * v.x; + nv_scalar yy = v.y * v.y; + nv_scalar zz = v.z * v.z; + nv_scalar xy = v.x * v.y; + nv_scalar xz = v.x * v.z; + nv_scalar yz = v.y * v.z; + + a00 = xx + ct * (1 - xx); + a01 = xy + ct * (-xy) + st * -v.z; + a02 = xz + ct * (-xz) + st * v.y; + + a10 = xy + ct * (-xy) + st * v.z; + a11 = yy + ct * (1 - yy); + a12 = yz + ct * (-yz) + st * -v.x; + + a20 = xz + ct * (-xz) + st * -v.y; + a21 = yz + ct * (-yz) + st * v.x; + a22 = zz + ct * (1 - zz); +} + +void mat4::set_rot(const vec3 &u, const vec3 &v) +{ + nv_scalar phi; + nv_scalar h; + nv_scalar lambda; + vec3 w; + + cross(w, u, v); + dot(phi, u, v); + dot(lambda, w, w); + if (lambda > nv_eps) + h = (nv_one - phi) / lambda; + else + h = lambda; + + nv_scalar hxy = w.x * w.y * h; + nv_scalar hxz = w.x * w.z * h; + nv_scalar hyz = w.y * w.z * h; + + a00 = phi + w.x * w.x * h; + a01 = hxy - w.z; + a02 = hxz + w.y; + + a10 = hxy + w.z; + a11 = phi + w.y * w.y * h; + a12 = hyz - w.x; + + a20 = hxz - w.y; + a21 = hyz + w.x; + a22 = phi + w.z * w.z * h; +} + +void mat4::set_rot(const mat3 &M) +{ + // copy the 3x3 rotation block + a00 = M.a00; + a10 = M.a10; + a20 = M.a20; + a01 = M.a01; + a11 = M.a11; + a21 = M.a21; + a02 = M.a02; + a12 = M.a12; + a22 = M.a22; +} + +void mat4::set_translation(const vec3 &t) +{ + a03 = t.x; + a13 = t.y; + a23 = t.z; +} + +vec3 &mat4::get_translation(vec3 &t) const +{ + t.x = a03; + t.y = a13; + t.z = a23; + return t; +} + +mat3 &mat4::get_rot(mat3 &M) const +{ + // assign the 3x3 rotation block + M.a00 = a00; + M.a10 = a10; + M.a20 = a20; + M.a01 = a01; + M.a11 = a11; + M.a21 = a21; + M.a02 = a02; + M.a12 = a12; + M.a22 = a22; + return M; +} + +quat &mat4::get_rot(quat &q) const +{ + mat3 m; + get_rot(m); + q.FromMatrix(m); + return q; +} + +mat3 &tangent_basis(mat3 &basis, const vec3 &v0, const vec3 &v1, const vec3 &v2, const vec2 &t0, const vec2 &t1, const vec2 &t2, const vec3 &n) +{ + vec3 cp; + vec3 e0(v1.x - v0.x, t1.s - t0.s, t1.t - t0.t); + vec3 e1(v2.x - v0.x, t2.s - t0.s, t2.t - t0.t); + + cross(cp, e0, e1); + if (_abs(cp.x) > nv_eps) + { + basis.a00 = -cp.y / cp.x; + basis.a10 = -cp.z / cp.x; + } + + e0.x = v1.y - v0.y; + e1.x = v2.y - v0.y; + + cross(cp, e0, e1); + if (_abs(cp.x) > nv_eps) + { + basis.a01 = -cp.y / cp.x; + basis.a11 = -cp.z / cp.x; + } + + e0.x = v1.z - v0.z; + e1.x = v2.z - v0.z; + + cross(cp, e0, e1); + if (_abs(cp.x) > nv_eps) + { + basis.a02 = -cp.y / cp.x; + basis.a12 = -cp.z / cp.x; + } + + // tangent... + nv_scalar oonorm = nv_one / _sqrt(basis.a00 * basis.a00 + basis.a01 * basis.a01 + basis.a02 * basis.a02); + basis.a00 *= oonorm; + basis.a01 *= oonorm; + basis.a02 *= oonorm; + + // binormal... + oonorm = nv_one / _sqrt(basis.a10 * basis.a10 + basis.a11 * basis.a11 + basis.a12 * basis.a12); + basis.a10 *= oonorm; + basis.a11 *= oonorm; + basis.a12 *= oonorm; + + // normal... + // compute the cross product TxB + basis.a20 = basis.a01 * basis.a12 - basis.a02 * basis.a11; + basis.a21 = basis.a02 * basis.a10 - basis.a00 * basis.a12; + basis.a22 = basis.a00 * basis.a11 - basis.a01 * basis.a10; + + oonorm = nv_one / _sqrt(basis.a20 * basis.a20 + basis.a21 * basis.a21 + basis.a22 * basis.a22); + basis.a20 *= oonorm; + basis.a21 *= oonorm; + basis.a22 *= oonorm; + + // Gram-Schmidt orthogonalization process for B + // compute the cross product B=NxT to obtain + // an orthogonal basis + basis.a10 = basis.a21 * basis.a02 - basis.a22 * basis.a01; + basis.a11 = basis.a22 * basis.a00 - basis.a20 * basis.a02; + basis.a12 = basis.a20 * basis.a01 - basis.a21 * basis.a00; + + if (basis.a20 * n.x + basis.a21 * n.y + basis.a22 * n.z < nv_zero) + { + basis.a20 = -basis.a20; + basis.a21 = -basis.a21; + basis.a22 = -basis.a22; + } + return basis; +} + +/* + * Project an x,y pair onto a sphere of radius r OR a hyperbolic sheet + * if we are away from the center of the sphere. + */ +nv_scalar tb_project_to_sphere(nv_scalar r, nv_scalar x, nv_scalar y) +{ + nv_scalar d, t, z; + + d = _sqrt(x * x + y * y); + if (d < r * 0.70710678118654752440) + { /* Inside sphere */ + z = _sqrt(r * r - d * d); + } + else + { /* On hyperbola */ + t = r / (nv_scalar)1.41421356237309504880; + z = t * t / d; + } + return z; +} + +/* + * Ok, simulate a track-ball. Project the points onto the virtual + * trackball, then figure out the axis of rotation, which is the cross + * product of P1 P2 and O P1 (O is the center of the ball, 0,0,0) + * Note: This is a deformed trackball-- is a trackball in the center, + * but is deformed into a hyperbolic sheet of rotation away from the + * center. This particular function was chosen after trying out + * several variations. + * + * It is assumed that the arguments to this routine are in the range + * (-1.0 ... 1.0) + */ +quat &trackball(quat &q, vec2 &pt1, vec2 &pt2, nv_scalar trackballsize) +{ + vec3 a; // Axis of rotation + nv_scalar phi; // how much to rotate about axis + vec3 d; + nv_scalar t; + + if (pt1.x == pt2.x && pt1.y == pt2.y) + { + // Zero rotation + q = quat_id; + return q; + } + + // First, figure out z-coordinates for projection of P1 and P2 to + // deformed sphere + vec3 p1(pt1.x, pt1.y, tb_project_to_sphere(trackballsize, pt1.x, pt1.y)); + vec3 p2(pt2.x, pt2.y, tb_project_to_sphere(trackballsize, pt2.x, pt2.y)); + + // Now, we want the cross product of P1 and P2 + cross(a, p1, p2); + + // Figure out how much to rotate around that axis. + d.x = p1.x - p2.x; + d.y = p1.y - p2.y; + d.z = p1.z - p2.z; + t = _sqrt(d.x * d.x + d.y * d.y + d.z * d.z) / (trackballsize); + + // Avoid problems with out-of-control values... + + if (t > nv_one) + t = nv_one; + if (t < -nv_one) + t = -nv_one; + phi = nv_two * nv_scalar(asin(t)); + axis_to_quat(q, a, phi); + return q; +} + +vec3 &cube_map_normal(int i, int x, int y, int cubesize, vec3 &v) +{ + nv_scalar s, t, sc, tc; + s = (nv_scalar(x) + nv_zero_5) / nv_scalar(cubesize); + t = (nv_scalar(y) + nv_zero_5) / nv_scalar(cubesize); + sc = s * nv_two - nv_one; + tc = t * nv_two - nv_one; + + switch (i) + { + case 0: + v.x = nv_one; + v.y = -tc; + v.z = -sc; + break; + case 1: + v.x = -nv_one; + v.y = -tc; + v.z = sc; + break; + case 2: + v.x = sc; + v.y = nv_one; + v.z = tc; + break; + case 3: + v.x = sc; + v.y = -nv_one; + v.z = -tc; + break; + case 4: + v.x = sc; + v.y = -tc; + v.z = nv_one; + break; + case 5: + v.x = -sc; + v.y = -tc; + v.z = -nv_one; + break; + } + normalize(v); + return v; +} + +// computes the area of a triangle +nv_scalar nv_area(const vec3 &v1, const vec3 &v2, const vec3 &v3) +{ + vec3 cp_sum; + vec3 cp; + cross(cp_sum, v1, v2); + cp_sum += cross(cp, v2, v3); + cp_sum += cross(cp, v3, v1); + return nv_norm(cp_sum) * nv_zero_5; +} + +// computes the perimeter of a triangle +nv_scalar nv_perimeter(const vec3 &v1, const vec3 &v2, const vec3 &v3) +{ + nv_scalar perim; + vec3 diff; + sub(diff, v1, v2); + perim = nv_norm(diff); + sub(diff, v2, v3); + perim += nv_norm(diff); + sub(diff, v3, v1); + perim += nv_norm(diff); + return perim; +} + +// compute the center and radius of the inscribed circle defined by the three vertices +nv_scalar nv_find_in_circle(vec3 ¢er, const vec3 &v1, const vec3 &v2, const vec3 &v3) +{ + nv_scalar area = nv_area(v1, v2, v3); + // if the area is null + if (area < nv_eps) + { + center = v1; + return nv_zero; + } + + nv_scalar oo_perim = nv_one / nv_perimeter(v1, v2, v3); + + vec3 diff; + + sub(diff, v2, v3); + mult(center, v1, nv_norm(diff)); + + sub(diff, v3, v1); + madd(center, v2, nv_norm(diff)); + + sub(diff, v1, v2); + madd(center, v3, nv_norm(diff)); + + center *= oo_perim; + + return nv_two * area * oo_perim; +} + +// compute the center and radius of the circumscribed circle defined by the three vertices +// i.e. the osculating circle of the three vertices +nv_scalar nv_find_circ_circle(vec3 ¢er, const vec3 &v1, const vec3 &v2, const vec3 &v3) +{ + vec3 e0; + vec3 e1; + nv_scalar d1, d2, d3; + nv_scalar c1, c2, c3, oo_c; + + sub(e0, v3, v1); + sub(e1, v2, v1); + dot(d1, e0, e1); + + sub(e0, v3, v2); + sub(e1, v1, v2); + dot(d2, e0, e1); + + sub(e0, v1, v3); + sub(e1, v2, v3); + dot(d3, e0, e1); + + c1 = d2 * d3; + c2 = d3 * d1; + c3 = d1 * d2; + oo_c = nv_one / (c1 + c2 + c3); + + mult(center, v1, c2 + c3); + madd(center, v2, c3 + c1); + madd(center, v3, c1 + c2); + center *= oo_c * nv_zero_5; + + return nv_zero_5 * _sqrt((d1 + d2) * (d2 + d3) * (d3 + d1) * oo_c); +} + +nv_scalar ffast_cos(const nv_scalar x) +{ + // assert: 0 <= fT <= PI/2 + // maximum absolute error = 1.1880e-03 + // speedup = 2.14 + + nv_scalar x_sqr = x * x; + nv_scalar res = nv_scalar(3.705e-02); + res *= x_sqr; + res -= nv_scalar(4.967e-01); + res *= x_sqr; + res += nv_one; + return res; +} + +nv_scalar fast_cos(const nv_scalar x) +{ + // assert: 0 <= fT <= PI/2 + // maximum absolute error = 2.3082e-09 + // speedup = 1.47 + + nv_scalar x_sqr = x * x; + nv_scalar res = nv_scalar(-2.605e-07); + res *= x_sqr; + res += nv_scalar(2.47609e-05); + res *= x_sqr; + res -= nv_scalar(1.3888397e-03); + res *= x_sqr; + res += nv_scalar(4.16666418e-02); + res *= x_sqr; + res -= nv_scalar(4.999999963e-01); + res *= x_sqr; + res += nv_one; + return res; +} + +void nv_is_valid(const vec3 &v) +{ + assert(!_isnan(v.x) && !_isnan(v.y) && !_isnan(v.z) && + _finite(v.x) && _finite(v.y) && _finite(v.z)); +} + +void nv_is_valid(nv_scalar lambda) +{ + assert(!_isnan(lambda) && _finite(lambda)); +} diff --git a/src/editors/xrECore/Engine/nv_algebra.h b/src/editors/xrECore/Engine/nv_algebra.h new file mode 100644 index 00000000000..87cbe09415c --- /dev/null +++ b/src/editors/xrECore/Engine/nv_algebra.h @@ -0,0 +1,791 @@ +/*********************************************************************NVMH1**** +File: +nv_algebra.h + +Copyright (C) 1999, 2002 NVIDIA Corporation +This file is provided without support, instruction, or implied warranty of any +kind. NVIDIA makes no guarantee of its fitness for a particular purpose and is +not liable under any circumstances for any damages or loss whatsoever arising +from the use or inability to use this file or items derived from it. + +Comments: + + +******************************************************************************/ + +#ifndef nv_algebraH +#define nv_algebraH + +struct DECLSPEC_NV_MATH vec2 +{ + vec2() {} + vec2(nv_scalar x, nv_scalar y) : x(x), y(y) {} + vec2(const nv_scalar *xy) : x(xy[0]), y(xy[1]) {} + vec2(const vec2 &u) : x(u.x), y(u.y) {} + vec2(const vec3t &); + + bool operator==(const vec2 &u) const + { + return (u.x == x && u.y == y) ? true : false; + } + + bool operator!=(const vec2 &u) const + { + return !(*this == u); + } + + vec2 &operator*=(const nv_scalar &lambda) + { + x *= lambda; + y *= lambda; + return *this; + } + + vec2 &operator-=(const vec2 &u) + { + x -= u.x; + y -= u.y; + return *this; + } + + vec2 &operator+=(const vec2 &u) + { + x += u.x; + y += u.y; + return *this; + } + + nv_scalar &operator[](int i) + { + return vec_array[i]; + } + + const nv_scalar operator[](int i) const + { + return vec_array[i]; + } + + union + { + struct + { + nv_scalar x, y; // standard names for components + }; + struct + { + nv_scalar s, t; // standard names for components + }; + nv_scalar vec_array[2]; // array access + }; +}; + +inline const vec2 operator+(const vec2 &u, const vec2 &v) +{ + return vec2(u.x + v.x, u.y + v.y); +} + +inline const vec2 operator-(const vec2 &u, const vec2 &v) +{ + return vec2(u.x - v.x, u.y - v.y); +} + +inline const vec2 operator*(const nv_scalar s, const vec2 &u) +{ + return vec2(s * u.x, s * u.y); +} + +inline const vec2 operator/(const vec2 &u, const nv_scalar s) +{ + return vec2(u.x / s, u.y / s); +} + +inline const vec2 operator*(const vec2 &u, const vec2 &v) +{ + return vec2(u.x * v.x, u.y * v.y); +} + +template +struct vec3t +{ + vec3t() {} + vec3t(_T x, _T y, _T z) : x(x), y(y), z(z) {} + vec3t(const _T *xyz) : x(xyz[0]), y(xyz[1]), z(xyz[2]) {} + vec3t(const vec2 &u) : x(u.x), y(u.y), z(1.0f) {} + vec3t(const vec3t &u) : x(_T(u.x)), y(_T(u.y)), z(_T(u.z)) {} + vec3t(const vec3t &u) : x(_T(u.x)), y(_T(u.y)), z(_T(u.z)) {} + vec3t(const vec4 &); + + bool operator==(const vec3t<_T> &u) const + { + return (u.x == x && u.y == y && u.z == z) ? true : false; + } + bool operator!=(const vec3t<_T> &rhs) const + { + return !(*this == rhs); + } + vec3t<_T> &operator*=(const _T &lambda) + { + x *= lambda; + y *= lambda; + z *= lambda; + return *this; + } + vec3t<_T> operator-() const + { + return vec3t<_T>(-x, -y, -z); + } + vec3t<_T> &operator-=(const vec3t<_T> &u) + { + x -= u.x; + y -= u.y; + z -= u.z; + return *this; + } + vec3t<_T> &operator+=(const vec3t<_T> &u) + { + x += u.x; + y += u.y; + z += u.z; + return *this; + } + _T sq_norm() const { return x * x + y * y + z * z; } + _T norm() const { return _sqrt(sq_norm()); } + _T normalize() + { + _T _norm = norm(); + if (_norm > nv_eps) + _norm = nv_one / _norm; + else + _norm = nv_zero; + x *= _norm; + y *= _norm; + z *= _norm; + return _norm; + } + + _T &operator[](int i) + { + return vec_array[i]; + } + + union + { + struct + { + _T x, y, z; // standard names for components + }; + struct + { + _T s, t, r; // standard names for components + }; + _T vec_array[3]; // array access + }; + + const _T operator[](int i) const + { + return vec_array[i]; + } +}; + +template +inline const vec3t<_T> operator+(const vec3t<_T> &u, const vec3t<_T> &v) +{ + return vec3t<_T>(u.x + v.x, u.y + v.y, u.z + v.z); +} +template +inline const vec3t<_T> operator-(const vec3t<_T> &u, const vec3t<_T> &v) +{ + return vec3t<_T>(u.x - v.x, u.y - v.y, u.z - v.z); +} +template +inline const vec3t<_T> operator^(const vec3t<_T> &u, const vec3t<_T> &v) +{ + return vec3t<_T>(u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x); +} +template +inline const vec3t<_T> operator*(const _T s, const vec3t<_T> &u) +{ + return vec3t<_T>(s * u.x, s * u.y, s * u.z); +} +template +inline const vec3t<_T> operator/(const vec3t<_T> &u, const _T s) +{ + return vec3t<_T>(u.x / s, u.y / s, u.z / s); +} +template +inline const vec3t<_T> operator*(const vec3t<_T> &u, const vec3t<_T> &v) +{ + return vec3t<_T>(u.x * v.x, u.y * v.y, u.z * v.z); +} + +// +typedef vec3t vec3; +typedef vec3t vec3f; +typedef vec3t vec3d; + +inline vec2::vec2(const vec3 &u) +{ + nv_scalar k = 1 / u.z; + x = k * u.x; + y = k * u.y; +} + +struct DECLSPEC_NV_MATH vec4 +{ + vec4() {} + vec4(nv_scalar x, nv_scalar y, nv_scalar z, nv_scalar w) : x(x), y(y), z(z), w(w) {} + vec4(const nv_scalar *xyzw) : x(xyzw[0]), y(xyzw[1]), z(xyzw[2]), w(xyzw[3]) {} + vec4(const vec3 &u) : x(u.x), y(u.y), z(u.z), w(1.0f) {} + vec4(const vec4 &u) : x(u.x), y(u.y), z(u.z), w(u.w) {} + + bool operator==(const vec4 &u) const + { + return (u.x == x && u.y == y && u.z == z && u.w == w) ? true : false; + } + + bool operator!=(const vec4 &rhs) const + { + return !(*this == rhs); + } + + vec4 &operator*=(const nv_scalar &lambda) + { + x *= lambda; + y *= lambda; + z *= lambda; + w *= lambda; + return *this; + } + + vec4 &operator-=(const vec4 &u) + { + x -= u.x; + y -= u.y; + z -= u.z; + w -= u.w; + return *this; + } + + vec4 &operator+=(const vec4 &u) + { + x += u.x; + y += u.y; + z += u.z; + w += u.w; + return *this; + } + + vec4 operator-() const + { + return vec4(-x, -y, -z, -w); + } + + nv_scalar &operator[](int i) + { + return vec_array[i]; + } + + const nv_scalar operator[](int i) const + { + return vec_array[i]; + } + + union + { + struct + { + nv_scalar x, y, z, w; // standard names for components + }; + struct + { + nv_scalar s, t, r, q; // standard names for components + }; + nv_scalar vec_array[4]; // array access + }; +}; + +inline const vec4 operator+(const vec4 &u, const vec4 &v) +{ + return vec4(u.x + v.x, u.y + v.y, u.z + v.z, u.w + v.w); +} + +inline const vec4 operator-(const vec4 &u, const vec4 &v) +{ + return vec4(u.x - v.x, u.y - v.y, u.z - v.z, u.w - v.w); +} + +inline const vec4 operator*(const nv_scalar s, const vec4 &u) +{ + return vec4(s * u.x, s * u.y, s * u.z, s * u.w); +} + +inline const vec4 operator/(const vec4 &u, const nv_scalar s) +{ + return vec4(u.x / s, u.y / s, u.z / s, u.w / s); +} + +inline const vec4 operator*(const vec4 &u, const vec4 &v) +{ + return vec4(u.x * v.x, u.y * v.y, u.z * v.z, u.w * v.w); +} + +template +inline vec3t<_T>::vec3t(const vec4 &u) +{ + x = u.x; + y = u.y; + z = u.z; +} + +// quaternion +struct quat; + +/* + for all the matrices...a indicates the element at row x, col y + + For example: + a01 <-> row 0, col 1 +*/ + +struct DECLSPEC_NV_MATH mat3 +{ + mat3(); + mat3(const nv_scalar *array); + mat3(const mat3 &M); + mat3(const nv_scalar &f0, const nv_scalar &f1, const nv_scalar &f2, + const nv_scalar &f3, const nv_scalar &f4, const nv_scalar &f5, + const nv_scalar &f6, const nv_scalar &f7, const nv_scalar &f8) + : a00(f0), a10(f1), a20(f2), + a01(f3), a11(f4), a21(f5), + a02(f6), a12(f7), a22(f8) {} + + const vec3 col(const int i) const + { + return vec3(&mat_array[i * 3]); + } + + const vec3 operator[](int i) const + { + return vec3(mat_array[i], mat_array[i + 3], mat_array[i + 6]); + } + + const nv_scalar &operator()(const int &i, const int &j) const + { + return mat_array[j * 3 + i]; + } + + nv_scalar &operator()(const int &i, const int &j) + { + return mat_array[j * 3 + i]; + } + + void set_row(int i, const vec3 &v) + { + mat_array[i] = v.x; + mat_array[i + 3] = v.y; + mat_array[i + 6] = v.z; + } + + void set_col(int i, const vec3 &v) + { + mat_array[i * 3] = v.x; + mat_array[i * 3 + 1] = v.y; + mat_array[i * 3 + 2] = v.z; + } + + void set_rot(const nv_scalar &theta, const vec3 &v); + void set_rot(const vec3 &u, const vec3 &v); + + union + { + struct + { + nv_scalar a00, a10, a20; // standard names for components + nv_scalar a01, a11, a21; // standard names for components + nv_scalar a02, a12, a22; // standard names for components + }; + nv_scalar mat_array[9]; // array access + }; +}; + +const vec3 operator*(const mat3 &, const vec3 &); +const vec3 operator*(const vec3 &, const mat3 &); + +struct DECLSPEC_NV_MATH mat4 +{ + mat4(); + mat4(const nv_scalar *array); + mat4(const mat4 &M); + + mat4(const nv_scalar &f0, const nv_scalar &f1, const nv_scalar &f2, const nv_scalar &f3, + const nv_scalar &f4, const nv_scalar &f5, const nv_scalar &f6, const nv_scalar &f7, + const nv_scalar &f8, const nv_scalar &f9, const nv_scalar &f10, const nv_scalar &f11, + const nv_scalar &f12, const nv_scalar &f13, const nv_scalar &f14, const nv_scalar &f15) + : a00(f0), a10(f1), a20(f2), a30(f3), + a01(f4), a11(f5), a21(f6), a31(f7), + a02(f8), a12(f9), a22(f10), a32(f11), + a03(f12), a13(f13), a23(f14), a33(f15) {} + + const vec4 col(const int i) const + { + return vec4(&mat_array[i * 4]); + } + + const vec4 operator[](const int &i) const + { + return vec4(mat_array[i], mat_array[i + 4], mat_array[i + 8], mat_array[i + 12]); + } + + const nv_scalar &operator()(const int &i, const int &j) const + { + return mat_array[j * 4 + i]; + } + + nv_scalar &operator()(const int &i, const int &j) + { + return mat_array[j * 4 + i]; + } + + void set_col(int i, const vec4 &v) + { + mat_array[i * 4] = v.x; + mat_array[i * 4 + 1] = v.y; + mat_array[i * 4 + 2] = v.z; + mat_array[i * 4 + 3] = v.w; + } + + void set_row(int i, const vec4 &v) + { + mat_array[i] = v.x; + mat_array[i + 4] = v.y; + mat_array[i + 8] = v.z; + mat_array[i + 12] = v.w; + } + + mat3 &get_rot(mat3 &M) const; + quat &get_rot(quat &q) const; + void set_rot(const quat &q); + void set_rot(const mat3 &M); + void set_rot(const nv_scalar &theta, const vec3 &v); + void set_rot(const vec3 &u, const vec3 &v); + + void set_translation(const vec3 &t); + vec3 &get_translation(vec3 &t) const; + + mat4 operator*(const mat4 &) const; + + union + { + struct + { + nv_scalar a00, a10, a20, a30; // standard names for components + nv_scalar a01, a11, a21, a31; // standard names for components + nv_scalar a02, a12, a22, a32; // standard names for components + nv_scalar a03, a13, a23, a33; // standard names for components + }; + struct + { + nv_scalar _11, _12, _13, _14; // standard names for components + nv_scalar _21, _22, _23, _24; // standard names for components + nv_scalar _31, _32, _33, _34; // standard names for components + nv_scalar _41, _42, _43, _44; // standard names for components + }; + union + { + struct + { + nv_scalar b00, b10, b20, p; // standard names for components + nv_scalar b01, b11, b21, q; // standard names for components + nv_scalar b02, b12, b22, r; // standard names for components + nv_scalar x, y, z, w; // standard names for components + }; + }; + nv_scalar mat_array[16]; // array access + }; +}; + +const vec4 operator*(const mat4 &, const vec4 &); +const vec4 operator*(const vec4 &, const mat4 &); + +// quaternion +struct DECLSPEC_NV_MATH quat +{ +public: + quat(nv_scalar x = 0, nv_scalar y = 0, nv_scalar z = 0, nv_scalar w = 1); + quat(const quat &quat); + quat(const vec3 &axis, nv_scalar angle); + quat(const mat3 &rot); + quat &operator=(const quat &quat); + quat operator-() + { + return quat(-x, -y, -z, -w); + } + quat Inverse(); + void Normalize(); + void FromMatrix(const mat3 &mat); + void ToMatrix(mat3 &mat) const; + quat &operator*=(const quat &quat); + static const quat Identity; + nv_scalar &operator[](int i) { return comp[i]; } + const nv_scalar operator[](int i) const { return comp[i]; } + union + { + struct + { + nv_scalar x, y, z, w; + }; + nv_scalar comp[4]; + }; +}; +const quat operator*(const quat &, const quat &); +extern quat &conj(quat &p, const quat &q); +extern quat &add_quats(quat &p, const quat &q1, const quat &q2); +extern nv_scalar dot(const quat &p, const quat &q); +extern quat &dot(nv_scalar s, const quat &p, const quat &q); +extern quat &slerp_quats(quat &p, nv_scalar s, const quat &q1, const quat &q2); +extern quat &axis_to_quat(quat &q, const vec3 &a, const nv_scalar phi); +extern mat3 &quat_2_mat(mat3 &M, const quat &q); +extern quat &mat_2_quat(quat &q, const mat3 &M); + +// constant algebraic values +const nv_scalar array16_id[] = {nv_one, nv_zero, nv_zero, nv_zero, + nv_zero, nv_one, nv_zero, nv_zero, + nv_zero, nv_zero, nv_one, nv_zero, + nv_zero, nv_zero, nv_zero, nv_one}; + +const nv_scalar array16_null[] = {nv_zero, nv_zero, nv_zero, nv_zero, + nv_zero, nv_zero, nv_zero, nv_zero, + nv_zero, nv_zero, nv_zero, nv_zero, + nv_zero, nv_zero, nv_zero, nv_zero}; + +const nv_scalar array16_scale_bias[] = {nv_zero_5, nv_zero, nv_zero, nv_zero, + nv_zero, nv_zero_5, nv_zero, nv_zero, + nv_zero, nv_zero, nv_zero_5, nv_zero, + nv_zero_5, nv_zero_5, nv_zero_5, nv_one}; + +const nv_scalar array9_id[] = {nv_one, nv_zero, nv_zero, + nv_zero, nv_one, nv_zero, + nv_zero, nv_zero, nv_one}; + +const vec2 vec2_null(nv_zero, nv_zero); +const vec4 vec4_one(nv_one, nv_one, nv_one, nv_one); +const vec3 vec3_one(nv_one, nv_one, nv_one); +const vec3 vec3_null(nv_zero, nv_zero, nv_zero); +const vec3 vec3_x(nv_one, nv_zero, nv_zero); +const vec3 vec3_y(nv_zero, nv_one, nv_zero); +const vec3 vec3_z(nv_zero, nv_zero, nv_one); +const vec3 vec3_neg_x(-nv_one, nv_zero, nv_zero); +const vec3 vec3_neg_y(nv_zero, -nv_one, nv_zero); +const vec3 vec3_neg_z(nv_zero, nv_zero, -nv_one); +const vec4 vec4_null(nv_zero, nv_zero, nv_zero, nv_zero); +const vec4 vec4_x(nv_one, nv_zero, nv_zero, nv_zero); +const vec4 vec4_neg_x(-nv_one, nv_zero, nv_zero, nv_zero); +const vec4 vec4_y(nv_zero, nv_one, nv_zero, nv_zero); +const vec4 vec4_neg_y(nv_zero, -nv_one, nv_zero, nv_zero); +const vec4 vec4_z(nv_zero, nv_zero, nv_one, nv_zero); +const vec4 vec4_neg_z(nv_zero, nv_zero, -nv_one, nv_zero); +const vec4 vec4_w(nv_zero, nv_zero, nv_zero, nv_one); +const vec4 vec4_neg_w(nv_zero, nv_zero, nv_zero, -nv_one); +const quat quat_id(nv_zero, nv_zero, nv_zero, nv_one); +const mat4 mat4_id(array16_id); +const mat3 mat3_id(array9_id); +const mat4 mat4_null(array16_null); +const mat4 mat4_scale_bias(array16_scale_bias); + +// normalizes a vector and return a reference of itself +extern vec3 &normalize(vec3 &u); +extern vec4 &normalize(vec4 &u); + +// Computes the squared magnitude +inline nv_scalar nv_sq_norm(const vec3 &n) +{ + return n.x * n.x + n.y * n.y + n.z * n.z; +} + +inline nv_scalar nv_sq_norm(const vec4 &n) +{ + return n.x * n.x + n.y * n.y + n.z * n.z + n.w * n.w; +} + +// Computes the magnitude +inline nv_scalar nv_norm(const vec3 &n) +{ + return _sqrt(nv_sq_norm(n)); +} + +inline nv_scalar nv_norm(const vec4 &n) +{ + return _sqrt(nv_sq_norm(n)); +} + +// computes the cross product ( v cross w) and stores the result in u +// i.e. u = v cross w +extern vec3 &cross(vec3 &u, const vec3 &v, const vec3 &w); + +// computes the dot product ( v dot w) and stores the result in u +// i.e. u = v dot w +extern nv_scalar &dot(nv_scalar &u, const vec3 &v, const vec3 &w); +extern nv_scalar dot(const vec3 &v, const vec3 &w); +extern nv_scalar &dot(nv_scalar &u, const vec4 &v, const vec4 &w); +extern nv_scalar dot(const vec4 &v, const vec4 &w); +extern nv_scalar &dot(nv_scalar &u, const vec3 &v, const vec4 &w); +extern nv_scalar dot(const vec3 &v, const vec4 &w); +extern nv_scalar &dot(nv_scalar &u, const vec4 &v, const vec3 &w); +extern nv_scalar dot(const vec4 &v, const vec3 &w); + +// compute the reflected vector R of L w.r.t N - vectors need to be +// normalized +// +// R N L +// _ _ +// |\ ^ /| +// \ | / +// \ | / +// \|/ +// + +extern vec3 &reflect(vec3 &r, const vec3 &n, const vec3 &l); + +// Computes u = v * lambda + u +extern vec3 &madd(vec3 &u, const vec3 &v, const nv_scalar &lambda); +// Computes u = v * lambda +extern vec3 &mult(vec3 &u, const vec3 &v, const nv_scalar &lambda); +// Computes u = v * w +extern vec3 &mult(vec3 &u, const vec3 &v, const vec3 &w); +// Computes u = v + w +extern vec3 &add(vec3 &u, const vec3 &v, const vec3 &w); +// Computes u = v - w +extern vec3 &sub(vec3 &u, const vec3 &v, const vec3 &w); + +// Computes u = u * s +extern vec3 &scale(vec3 &u, const nv_scalar s); +extern vec4 &scale(vec4 &u, const nv_scalar s); + +// Computes u = M * v +extern vec3 &mult(vec3 &u, const mat3 &M, const vec3 &v); +extern vec4 &mult(vec4 &u, const mat4 &M, const vec4 &v); + +// Computes u = v * M +extern vec3 &mult(vec3 &u, const vec3 &v, const mat3 &M); +extern vec4 &mult(vec4 &u, const vec4 &v, const mat4 &M); + +// Computes u = M(4x4) * v and divides by w +extern vec3 &mult_pos(vec3 &u, const mat4 &M, const vec3 &v); +// Computes u = M(4x4) * v +extern vec3 &mult_dir(vec3 &u, const mat4 &M, const vec3 &v); +// Computes u = M(4x4) * v and does not divide by w (assumed to be 1) +extern vec3 &mult(vec3 &u, const mat4 &M, const vec3 &v); + +// Computes u = v * M(4x4) and divides by w +extern vec3 &mult_pos(vec3 &u, const vec3 &v, const mat4 &M); +// Computes u = v * M(4x4) +extern vec3 &mult_dir(vec3 &u, const vec3 &v, const mat4 &M); +// Computes u = v * M(4x4) and does not divide by w (assumed to be 1) +extern vec3 &mult(vec3 &u, const vec3 &v, const mat4 &M); + +// Computes A += B +extern mat4 &add(mat4 &A, const mat4 &B); +extern mat3 &add(mat3 &A, const mat3 &B); + +// Computes C = A * B +extern mat4 &mult(mat4 &C, const mat4 &A, const mat4 &B); +extern mat3 &mult(mat3 &C, const mat3 &A, const mat3 &B); + +// Computes B = Transpose(A) +// T +// B = A +extern mat3 &transpose(mat3 &B, const mat3 &A); +extern mat4 &transpose(mat4 &B, const mat4 &A); +extern mat3 &transpose(mat3 &B); +extern mat4 &transpose(mat4 &B); + +// Computes B = inverse(A) +// -1 +// B = A +extern mat4 &invert(mat4 &B, const mat4 &A); +extern mat3 &invert(mat3 &B, const mat3 &A); + +// Computes B = inverse(A) +// T T +// (R t) (R -R t) +// assuming that A = (0 1) so that B = (0 1) +// B = A +extern mat4 &invert_rot_trans(mat4 &B, const mat4 &A); + +extern mat4 &look_at(mat4 &M, const vec3 &eye, const vec3 ¢er, const vec3 &up); +extern mat4 &frustum(mat4 &M, const nv_scalar l, const nv_scalar r, const nv_scalar b, + const nv_scalar t, const nv_scalar n, const nv_scalar f); + +extern mat4 &perspective(mat4 &M, const nv_scalar fovy, const nv_scalar aspect, const nv_scalar n, const nv_scalar f); + +// quaternion +extern quat &normalize(quat &p); +extern quat &conj(quat &p); +extern quat &conj(quat &p, const quat &q); +extern quat &add_quats(quat &p, const quat &q1, const quat &q2); +extern quat &axis_to_quat(quat &q, const vec3 &a, const nv_scalar phi); +extern mat3 &quat_2_mat(mat3 &M, const quat &q); +extern quat &mat_2_quat(quat &q, const mat3 &M); +extern quat &mat_2_quat(quat &q, const mat4 &M); + +// surface properties +extern mat3 &tangent_basis(mat3 &basis, const vec3 &v0, const vec3 &v1, const vec3 &v2, const vec2 &t0, const vec2 &t1, const vec2 &t2, const vec3 &n); + +// linear interpolation +inline nv_scalar lerp(nv_scalar t, nv_scalar a, nv_scalar b) +{ + return a * (nv_one - t) + t * b; +} + +inline vec3 &lerp(vec3 &w, const nv_scalar &t, const vec3 &u, const vec3 &v) +{ + w.x = lerp(t, u.x, v.x); + w.y = lerp(t, u.y, v.y); + w.z = lerp(t, u.z, v.z); + return w; +} + +// utilities +inline nv_scalar nv_min(const nv_scalar &lambda, const nv_scalar &n) +{ + return (lambda < n) ? lambda : n; +} + +inline nv_scalar nv_max(const nv_scalar &lambda, const nv_scalar &n) +{ + return (lambda > n) ? lambda : n; +} + +inline nv_scalar nv_clamp(nv_scalar u, const nv_scalar min, const nv_scalar max) +{ + u = (u < min) ? min : u; + u = (u > max) ? max : u; + return u; +} + +extern nv_scalar nv_random(); + +extern quat &trackball(quat &q, vec2 &pt1, vec2 &pt2, nv_scalar trackballsize); + +extern vec3 &cube_map_normal(int i, int x, int y, int cubesize, vec3 &v); + +// geometry +// computes the area of a triangle +extern nv_scalar nv_area(const vec3 &v1, const vec3 &v2, const vec3 &v3); +// computes the perimeter of a triangle +extern nv_scalar nv_perimeter(const vec3 &v1, const vec3 &v2, const vec3 &v3); +// find the inscribed circle +extern nv_scalar nv_find_in_circle(vec3 ¢er, const vec3 &v1, const vec3 &v2, const vec3 &v3); +// find the circumscribed circle +extern nv_scalar nv_find_circ_circle(vec3 ¢er, const vec3 &v1, const vec3 &v2, const vec3 &v3); + +// fast cosine functions +extern nv_scalar fast_cos(const nv_scalar x); +extern nv_scalar ffast_cos(const nv_scalar x); + +// determinant +nv_scalar det(const mat3 &A); + +extern void nv_is_valid(const vec3 &v); +extern void nv_is_valid(nv_scalar lambda); + +#endif // nv_algebraH diff --git a/src/editors/xrECore/Engine/nv_math.h b/src/editors/xrECore/Engine/nv_math.h new file mode 100644 index 00000000000..14d5e9cd54d --- /dev/null +++ b/src/editors/xrECore/Engine/nv_math.h @@ -0,0 +1,53 @@ +/*********************************************************************NVMH1**** +File: +nv_math.h + +Copyright (C) 1999, 2002 NVIDIA Corporation +This file is provided without support, instruction, or implied warranty of any +kind. NVIDIA makes no guarantee of its fitness for a particular purpose and is +not liable under any circumstances for any damages or loss whatsoever arising +from the use or inability to use this file or items derived from it. + +Comments: + + +******************************************************************************/ +#ifndef _nv_math_h_ +#define _nv_math_h_ + +#ifndef _nv_mathdecl_h_ +#include "nv_mathdecl.h" + +#endif // _nv_mathdecl_h_ + +typedef f32 nv_scalar; + +#define nv_zero nv_scalar(0) +#define nv_zero_5 nv_scalar(0.5) +#define nv_one nv_scalar(1.0) +#define nv_two nv_scalar(2) +#define nv_half_pi nv_scalar(3.14159265358979323846264338327950288419716939937510582 * 0.5) +#define nv_quarter_pi nv_scalar(3.14159265358979323846264338327950288419716939937510582 * 0.25) +#define nv_pi nv_scalar(3.14159265358979323846264338327950288419716939937510582) +#define nv_two_pi nv_scalar(3.14159265358979323846264338327950288419716939937510582 * 2.0) +#define nv_oo_pi nv_one / nv_pi +#define nv_oo_two_pi nv_one / nv_two_pi +#define nv_oo_255 nv_one / nv_scalar(255) +#define nv_oo_128 nv_one / nv_scalar(128) +#define nv_to_rad nv_pi / nv_scalar(180) +#define nv_to_deg nv_scalar(180) / nv_pi +#define nv_eps nv_scalar(10e-6) +#define nv_double_eps nv_scalar(10e-6) * nv_two +#define nv_big_eps nv_scalar(10e-6) +#define nv_small_eps nv_scalar(10e-2) + +template +struct vec3t; +struct vec2; +struct vec4; + +#ifndef _nv_algebra_h_ +#include "nv_algebra.h" +#endif // _nv_algebra_h_ + +#endif //_nv_math_h_ diff --git a/src/editors/xrECore/Engine/nv_mathdecl.h b/src/editors/xrECore/Engine/nv_mathdecl.h new file mode 100644 index 00000000000..e2f2c7c0af2 --- /dev/null +++ b/src/editors/xrECore/Engine/nv_mathdecl.h @@ -0,0 +1,31 @@ +/*********************************************************************NVMH1**** +File: +nv_mathdecl.h + +Copyright (C) 1999, 2002 NVIDIA Corporation +This file is provided without support, instruction, or implied warranty of any +kind. NVIDIA makes no guarantee of its fitness for a particular purpose and is +not liable under any circumstances for any damages or loss whatsoever arising +from the use or inability to use this file or items derived from it. + +Comments: + + +******************************************************************************/ + +#ifndef _nv_mathdecl_h_ +#define _nv_mathdecl_h_ + +#ifdef NV_MATH_DLL + +#ifdef NV_MATH_EXPORTS +#define DECLSPEC_NV_MATH __declspec(dllexport) +#else +#define DECLSPEC_NV_MATH __declspec(dllimport) +#endif + +#else +#define DECLSPEC_NV_MATH +#endif + +#endif // _nv_mathdecl_h_ diff --git a/src/editors/xrECore/FS2.cpp b/src/editors/xrECore/FS2.cpp new file mode 100644 index 00000000000..49e603ba9ee --- /dev/null +++ b/src/editors/xrECore/FS2.cpp @@ -0,0 +1,27 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "FS2.h" + +// memory +CMemoryStream::~CMemoryStream() +{ + xr_free(data); +} + +void CMemoryStream::write(const void *ptr, u32 count) +{ + if (position + count > mem_size) + { + // reallocate + if (mem_size == 0) + mem_size = 128; + while (mem_size <= (position + count)) + mem_size *= 2; + data = (u8 *)xr_realloc(data, mem_size); + } + CopyMemory(data + position, ptr, count); + position += count; + if (position > file_size) + file_size = position; +} diff --git a/src/editors/xrECore/FS2.h b/src/editors/xrECore/FS2.h new file mode 100644 index 00000000000..ab86481666f --- /dev/null +++ b/src/editors/xrECore/FS2.h @@ -0,0 +1,358 @@ +#pragma once +#include +#include +#include "lwchunks.h" + +class IBasicStream +{ +private: + std::stack chunk_pos; + std::stack subchunk_pos; + + void revbytes(void *bp, int elsize, int elcount) + { + unsigned char *p, *q; + + p = (unsigned char *)bp; + + if (elsize == 2) + { + q = p + 1; + while (elcount--) + { + *p ^= *q; + *q ^= *p; + *p ^= *q; + p += 2; + q += 2; + } + return; + } + + while (elcount--) + { + q = p + elsize - 1; + while (p < q) + { + *p ^= *q; + *q ^= *p; + *p ^= *q; + ++p; + --q; + } + p += elsize >> 1; + } + } + +public: + virtual ~IBasicStream() + { + R_ASSERT(subchunk_pos.empty()); + while (!chunk_pos.empty()) + close_chunk(); + } + + // kernel + virtual void write(const void *ptr, u32 count) = 0; + virtual void seek(u32 pos) = 0; + virtual u32 tell() = 0; + + // generalized writing functions + IC void w_u32(u32 d) + { + revbytes(&d, 4, 1); + write(&d, sizeof(u32)); + } + + IC void w_u16(u16 d) + { + revbytes(&d, 2, 1); + write(&d, sizeof(u16)); + } + + IC void w_float(float d) + { + revbytes(&d, 4, 1); + write(&d, sizeof(float)); + } + + IC void w_u8(u8 d) { write(&d, sizeof(u8)); } + + IC void w_string(const char *p) + { + write(p, xr_strlen(p)); + w_u8(13); + w_u8(10); + } + + IC void w_stringZ(const char *p) + { + write(p, xr_strlen(p) + 1); + if (!(xr_strlen(p) & 1)) + w_u8(0); + } + + IC void w_vector(Fvector v) + { + revbytes(&v, 4, 3); + write(&v, 3 * sizeof(float)); + } + + IC void w_color(Fcolor c) + { + revbytes(&c, 4, 4); + write(&c, 4 * sizeof(float)); + } + + // generalized chunking + IC void open_chunk(u32 type) + { + w_u32(type); + chunk_pos.push(tell()); + w_u32(0); // the place for 'size' + } + + IC void close_chunk() + { + VERIFY(!chunk_pos.empty()); + + int pos = tell(); + seek(chunk_pos.top()); + w_u32(pos - chunk_pos.top() - 4); + seek(pos); + chunk_pos.pop(); + } + + // generalized chunking + IC void open_subchunk(u32 type) + { + w_u32(type); + subchunk_pos.push((u16)tell()); + w_u16(0); // the place for 'size' + } + + IC void close_subchunk() + { + VERIFY(!subchunk_pos.empty()); + + int pos = tell(); + seek(subchunk_pos.top()); + w_u16(u16(pos - subchunk_pos.top() - 2)); + seek(pos); + subchunk_pos.pop(); + } + + IC void write_chunk(u32 type, void *data, u32 size) + { + open_chunk(type); + write(data, size); + close_chunk(); + } +}; + +class CMemoryStream : public IBasicStream +{ + u8 *data; + u32 position; + u32 mem_size; + u32 file_size; + +public: + CMemoryStream() + { + data = 0; + position = 0; + mem_size = 0; + file_size = 0; + } + + virtual ~CMemoryStream(); + + // kernel + virtual void write(const void *ptr, u32 count); + + virtual void seek(u32 pos) + { + position = pos; + } + + virtual u32 tell() + { + return position; + } + + // specific + u8 *pointer() { return data; } + u32 size() { return file_size; } + + void clear() + { + file_size = 0; + position = 0; + } + + void SaveTo(const char *fn) + { +#ifdef M_BORLAND + int H = open(fn, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IREAD | S_IWRITE); +#else + int H = _open(fn, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IREAD | S_IWRITE); +#endif + R_ASSERT(H > 0); + _write(H, pointer(), size()); + _close(H); + } +}; + + + +class CLWMemoryStream : public CMemoryStream +{ + IC void make_ord(int nbloks, int index, unsigned char *ord) + { + int i, d; + + for (i = 8, d = 16; i < 128; i *= 2) + { + if (i >= nbloks) + break; + d /= 2; + } + ord[0] = u8(128 + index * d); + ord[1] = 0; + } + +public: + IC void begin_save() + { + open_chunk(ID_FORM); + w_u32(ID_LWO2); + } + + IC void end_save(LPCSTR name) + { + close_chunk(); + SaveTo(name); + } + + IC void w_layer(u16 number, LPCSTR name) + { + open_chunk(ID_LAYR); + w_u16(number); // num + w_u16(0); + w_float(0); // pivot + w_float(0); + w_float(0); + w_stringZ(name); + close_chunk(); + } + + IC void w_vx(int idx) + { + if (idx >= 0xFF00) + { + idx |= 0xff000000; + w_u32(idx); + } + else + w_u16((u16)idx); + } + + IC void w_face3(int i0, int i1, int i2) + { + w_u16(3); + w_vx(i0); + w_vx(i1); + w_vx(i2); + } + + IC void begin_vmap(BOOL polymap, u32 type, int dim, LPCSTR name) + { + open_chunk(polymap ? ID_VMAD : ID_VMAP); + w_u32(type); + w_u16((u16)dim); + R_ASSERT2(name && name[0], "Empty vmap name!"); + w_stringZ(name); + } + IC void end_vmap() + { + close_chunk(); + } + + IC void w_vmap(int v_index, int dim, float *uv) + { + w_vx(v_index); + w_float(uv[0]); + if (dim == 2) + w_float(1.f - uv[1]); + } + + IC void w_vmad(int v_index, int f_index, int dim, float *uv) + { + w_vx(v_index); + w_vx(f_index); + w_float(uv[0]); + if (dim == 2) + w_float(1.f - uv[1]); + } + + IC void Wsurface(LPCSTR name, BOOL b2Sided, u16 image, LPCSTR vmap, LPCSTR sh_eng, LPCSTR sh_comp) + { + // surf screen + char ord[2]; + open_chunk(ID_SURF); + w_stringZ(name); + w_stringZ(""); + open_subchunk(ID_COLR); + w_float(1.f); + w_float(1.f); + w_float(1.f); + w_u16(0); + close_subchunk(); + open_subchunk(ID_SIDE); + w_u16(u16(b2Sided ? 3 : 1)); + close_subchunk(); + open_subchunk(ID_BLOK); + open_subchunk(ID_IMAP); + make_ord(128, 0, (u8 *)ord); + w_stringZ(ord); + open_subchunk(ID_CHAN); + w_u32(ID_COLR); + close_subchunk(); + open_subchunk(ID_OPAC); + w_u16(0); + w_float(1.f); + w_u16(0); + close_subchunk(); + open_subchunk(ID_ENAB); + w_u16(1); + close_subchunk(); + close_subchunk(); + open_subchunk(ID_PROJ); + w_u16(5); + close_subchunk(); + open_subchunk(ID_IMAG); + w_u16(image); + close_subchunk(); + open_subchunk(ID_VMAP); + w_stringZ(vmap); + close_subchunk(); + open_subchunk(ID_AAST); + w_u16(1); + w_float(1.f); + close_subchunk(); + open_subchunk(ID_PIXB); + w_u16(1); + close_subchunk(); + open_subchunk(ID_STCK); + w_float(0.f); + w_u16(0); + close_subchunk(); + open_subchunk(ID_TAMP); + w_float(1.f); + w_u16(0); + close_subchunk(); + close_subchunk(); + close_chunk(); + } +}; diff --git a/src/editors/xrECore/GameMtlLib_Editor.cpp b/src/editors/xrECore/GameMtlLib_Editor.cpp new file mode 100644 index 00000000000..d1e3d33697e --- /dev/null +++ b/src/editors/xrECore/GameMtlLib_Editor.cpp @@ -0,0 +1,725 @@ +#include "stdafx.h" +#include "xrEngine/GameMtlLib.h" +#include "Editor/UI_MainCommand.h" + +// material routines +void SGameMtl::FillProp(PropItemVec &items, ListItem *owner) +{ + PropValue *V = 0; + PHelper().CreateRText(items, "Desc", &m_Desc); + // flags + V = PHelper().CreateFlag32(items, "Flags\\Dynamic", &Flags, flDynamic); + V->Owner()->Enable(FALSE); + PHelper().CreateFlag32(items, "Flags\\Passable", &Flags, flPassable); + if (Flags.is(flDynamic)) + PHelper().CreateFlag32(items, "Flags\\Breakable", &Flags, flBreakable); + PHelper().CreateFlag32(items, "Flags\\Bounceable", &Flags, flBounceable); + PHelper().CreateFlag32(items, "Flags\\Skidmark", &Flags, flSkidmark); + PHelper().CreateFlag32(items, "Flags\\Bloodmark", &Flags, flBloodmark); + PHelper().CreateFlag32(items, "Flags\\Climable", &Flags, flClimable); + PHelper().CreateFlag32(items, "Flags\\Liquid", &Flags, flLiquid); + PHelper().CreateFlag32(items, "Flags\\Suppress Shadows", &Flags, flSuppressShadows); + PHelper().CreateFlag32(items, "Flags\\Suppress Wallmarks", &Flags, flSuppressWallmarks); + PHelper().CreateFlag32(items, "Flags\\Actor Obstacle", &Flags, flActorObstacle); + PHelper().CreateFlag32(items, "Flags\\Bullet No Ricoshet", &Flags, flNoRicoshet); + // physics part + PHelper().CreateFloat(items, "Physics\\Friction", &fPHFriction, 0.f, 100.f, 0.001f, 3); + PHelper().CreateFloat(items, "Physics\\Damping", &fPHDamping, 0.001f, 100.f, 0.001f, 3); + PHelper().CreateFloat(items, "Physics\\Spring", &fPHSpring, 0.001f, 100.f, 0.001f, 3); + PHelper().CreateFloat(items, "Physics\\Bounce start vel", &fPHBounceStartVelocity, 0.f, 100.f, 0.01f, 2); + PHelper().CreateFloat(items, "Physics\\Bouncing", &fPHBouncing, 0.f, 1.f, 0.001f, 3); + // factors + PHelper().CreateFloat(items, "Factors\\Bounce Damage", &fBounceDamageFactor, 0.f, 100.f, 0.1f, 1); + PHelper().CreateFloat(items, "Factors\\Injurious", &fInjuriousSpeed, 0.f, 10000.f); + PHelper().CreateFloat(items, "Factors\\Shooting (1-went through)", &fShootFactor); + PHelper().CreateFloat(items, "Factors\\Shooting MP (1-went through)", &fShootFactorMP); + PHelper().CreateFloat(items, "Factors\\Transparency (1-full transp)", &fVisTransparencyFactor); + PHelper().CreateFloat(items, "Factors\\Sound occlusion (1-full hear)", &fSndOcclusionFactor); + PHelper().CreateFloat(items, "Factors\\Flotation (1-full passable)", &fFlotationFactor); + + PHelper().CreateFloat(items, "Factors\\Density Factor", &fDensityFactor, 0.0f, 1000.0f, 1.0f, 1); +} + +void CGameMtlLibrary::CopyMtlPairs(SGameMtl *from, SGameMtl *to) +{ + for (GameMtlIt m1_it = materials.begin(); m1_it != materials.end(); ++m1_it) + { + SGameMtl *M1 = *m1_it; + SGameMtlPair *p_from = GetMaterialPair(from->GetID(), M1->GetID()); + SGameMtlPair *p_to = GetMaterialPair(to->GetID(), M1->GetID()); + + if (p_from && p_to) + p_to->CopyFrom(p_from); + } +} + +bool CGameMtlLibrary::UpdateMtlPairs(SGameMtl *src) +{ + bool bRes = false; + SGameMtl *M0 = src; + for (GameMtlIt m1_it = materials.begin(); m1_it != materials.end(); ++m1_it) + { + SGameMtl *M1 = *m1_it; + GameMtlPairIt p_it = GetMaterialPairIt(M0->GetID(), M1->GetID()); + if ((!M0->Flags.is(SGameMtl::flDynamic)) && (!M1->Flags.is(SGameMtl::flDynamic))) + { + R_ASSERT(p_it == material_pairs.end()); + continue; + } + else + { + if (p_it == material_pairs.end()) + { + // create pair + CreateMaterialPair(M0->GetID(), M1->GetID(), 0); + bRes = true; + } + } + } + return bRes; +} + +bool CGameMtlLibrary::UpdateMtlPairs() +{ + bool bRes = false; + for (GameMtlIt m0_it = materials.begin(); m0_it != materials.end(); m0_it++) + if (UpdateMtlPairs(*m0_it)) + bRes = true; + return bRes; +} + +SGameMtl *CGameMtlLibrary::AppendMaterial(SGameMtl *parent) +{ + SGameMtl *M = xr_new(); + if (parent) + *M = *parent; // base params + + M->ID = material_index++; + + materials.push_back(M); + UpdateMtlPairs(M); + if (parent) + CopyMtlPairs(parent, M); + return M; +} +void CGameMtlLibrary::RemoveMaterial(pcstr name) +{ + // find material + GameMtlIt rem_it = GetMaterialIt(name); + R_ASSERT(rem_it != materials.end()); + // remove dependent pairs + RemoveMaterialPair((*rem_it)->GetID()); + // destroy material + xr_delete(*rem_it); + materials.erase(rem_it); +} + +//------------------------------------------------------------------------------ +// material pair routines +//------------------------------------------------------------------------------ +void SGameMtlPair::OnFlagChange(PropValue *sender) +{ + bool bChecked = sender->Owner()->m_Flags.is(PropItem::flCBChecked); + u32 mask = 0; + if (sender == propBreakingSounds) + mask = flBreakingSounds; + else if (sender == propStepSounds) + mask = flStepSounds; + else if (sender == propCollideSounds) + mask = flCollideSounds; + else if (sender == propCollideParticles) + mask = flCollideParticles; + else if (sender == propCollideMarks) + mask = flCollideMarks; + else + THROW; + + OwnProps.set(mask, bChecked); + sender->Owner()->m_Flags.set(PropItem::flDisabled, !bChecked); + + ExecCommand(COMMAND_UPDATE_PROPERTIES); +} + +IC u32 SetMask(u32 mask, Flags32 flags, u32 flag) +{ + return mask ? (mask | (flags.is(flag) ? PropItem::flCBChecked : PropItem::flDisabled)) : 0; +} + +IC SGameMtlPair *GetLastParentValue(SGameMtlPair *who, u32 flag) +{ + if (!who) + return 0; + if ((GAMEMTL_NONE_ID == who->GetParent()) || (who->OwnProps.is(flag))) + return who; + else + return GetLastParentValue(who->m_Owner->GetMaterialPair(who->GetParent()), flag); +} + +IC BOOL ValidateParent(SGameMtlPair *who, SGameMtlPair *parent) +{ + if (!parent) + return TRUE; + if (who == parent) + return FALSE; + else + return ValidateParent(who, parent->m_Owner->GetMaterialPair(parent->GetParent())); +} + +bool SGameMtlPair::SetParent(int parent) +{ + int ID_parent_save = ID_parent; + ID_parent = parent; + + for (GameMtlPairIt it = m_Owner->FirstMaterialPair(); it != m_Owner->LastMaterialPair(); it++) + { + if (!ValidateParent(*it, m_Owner->GetMaterialPair((*it)->GetParent()))) + { + ID_parent = ID_parent_save; + return FALSE; + } + } + // all right + if (GAMEMTL_NONE_ID == ID_parent) + { + OwnProps.one(); + } + else + { + OwnProps.zero(); + OwnProps.set(flBreakingSounds, BreakingSounds.size()); + OwnProps.set(flStepSounds, StepSounds.size()); + OwnProps.set(flCollideSounds, CollideSounds.size()); + OwnProps.set(flCollideParticles, CollideParticles.size()); + OwnProps.set(flCollideMarks, CollideMarks.size()); + } + return true; +} + +void SGameMtlPair::FillChooseMtl(ChooseItemVec &items, void *param) +{ + for (GameMtlIt m0_it = m_Owner->FirstMaterial(); m0_it != m_Owner->LastMaterial(); m0_it++) + { + SGameMtl *M0 = *m0_it; + for (GameMtlIt m1_it = m_Owner->FirstMaterial(); m1_it != m_Owner->LastMaterial(); m1_it++) + { + SGameMtl *M1 = *m1_it; + GameMtlPairIt p_it = GMLib.GetMaterialPairIt(M0->GetID(), M1->GetID()); + if (p_it != GMLib.LastMaterialPair()) + items.push_back(SChooseItem(GMLib.MtlPairToName(M0->GetID(), M1->GetID()), "")); + } + } +} + +void SGameMtlPair::OnParentClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + bModif = false; + switch (V->btn_num) + { + case 0: + { + LPCSTR MP = 0; + SGameMtlPair *P = m_Owner->GetMaterialPair(ID_parent); + xr_string nm = P ? m_Owner->MtlPairToName(P->GetMtl0(), P->GetMtl1()) : NONE_CAPTION; + UIChooseForm::SelectItem(smCustom, 1, (nm == NONE_CAPTION) ? 0 : nm.c_str(), TOnChooseFillItems(this, &SGameMtlPair::FillChooseMtl)); + m_EditParent = true; + } + break; + } +} + +void SGameMtlPair::OnCommandClick(ButtonValue *V, bool &bModif, bool &bSafe) +{ + bModif = false; + switch (V->btn_num) + { + case 0: + { + SGameMtlPair *P = m_Owner->GetMaterialPair(ID_parent); + xr_string nm = P ? m_Owner->MtlPairToName(P->GetMtl0(), P->GetMtl1()) : NONE_CAPTION; + UIChooseForm::SelectItem(smCustom, 128, 0, TOnChooseFillItems(this, &SGameMtlPair::FillChooseMtl)); + m_EditCommand = true; + } + break; + } +} + +void SGameMtlPair::FillProp(PropItemVec &items) +{ + PropValue::TOnChange OnChange = 0; + u32 show_CB = 0; + SGameMtlPair *P = 0; + if (ID_parent != GAMEMTL_NONE_ID) + { + OnChange.bind(this, &SGameMtlPair::OnFlagChange); + show_CB = PropItem::flShowCB; + P = m_Owner->GetMaterialPair(ID_parent); + } + ButtonValue *B; + B = PHelper().CreateButton(items, "Command", "Set As Parent To...", 0); + B->OnBtnClickEvent.bind(this, &SGameMtlPair::OnCommandClick); + B = PHelper().CreateButton(items, "Parent", P ? m_Owner->MtlPairToName(P->GetMtl0(), P->GetMtl1()) : NONE_CAPTION, 0); + B->OnBtnClickEvent.bind(this, &SGameMtlPair::OnParentClick); + + propBreakingSounds = PHelper().CreateChoose(items, "Breaking Sounds", &BreakingSounds, smSoundSource, 0, 0, GAMEMTL_SUBITEM_COUNT); + propStepSounds = PHelper().CreateChoose(items, "Step Sounds", &StepSounds, smSoundSource, 0, 0, GAMEMTL_SUBITEM_COUNT + 2); + propCollideSounds = PHelper().CreateChoose(items, "Collide Sounds", &CollideSounds, smSoundSource, 0, 0, GAMEMTL_SUBITEM_COUNT); + propCollideParticles = PHelper().CreateChoose(items, "Collide Particles", &CollideParticles, smParticles, 0, 0, GAMEMTL_SUBITEM_COUNT); + propCollideMarks = PHelper().CreateChoose(items, "Collide Marks", &CollideMarks, smTexture, 0, 0, GAMEMTL_SUBITEM_COUNT); + + propBreakingSounds->Owner()->m_Flags.assign(SetMask(show_CB, OwnProps, flBreakingSounds)); + propStepSounds->Owner()->m_Flags.assign(SetMask(show_CB, OwnProps, flStepSounds)); + propCollideSounds->Owner()->m_Flags.assign(SetMask(show_CB, OwnProps, flCollideSounds)); + propCollideParticles->Owner()->m_Flags.assign(SetMask(show_CB, OwnProps, flCollideParticles)); + propCollideMarks->Owner()->m_Flags.assign(SetMask(show_CB, OwnProps, flCollideMarks)); + + propBreakingSounds->OnChangeEvent = OnChange; + propStepSounds->OnChangeEvent = OnChange; + propCollideSounds->OnChangeEvent = OnChange; + propCollideParticles->OnChangeEvent = OnChange; + propCollideMarks->OnChangeEvent = OnChange; + + if (show_CB) + { + SGameMtlPair *O; + if (0 != (O = GetLastParentValue(this, flBreakingSounds))) + BreakingSounds = O->BreakingSounds; + if (0 != (O = GetLastParentValue(this, flStepSounds))) + StepSounds = O->StepSounds; + if (0 != (O = GetLastParentValue(this, flCollideSounds))) + CollideSounds = O->CollideSounds; + if (0 != (O = GetLastParentValue(this, flCollideParticles))) + CollideParticles = O->CollideParticles; + if (0 != (O = GetLastParentValue(this, flCollideMarks))) + CollideMarks = O->CollideMarks; + } +} + +void SGameMtlPair::TransferFromParent(SGameMtlPair *parent) +{ + R_ASSERT(parent); + if (!OwnProps.is(flBreakingSounds)) + BreakingSounds = parent->BreakingSounds; + if (!OwnProps.is(flStepSounds)) + StepSounds = parent->StepSounds; + if (!OwnProps.is(flCollideSounds)) + CollideSounds = parent->CollideSounds; + if (!OwnProps.is(flCollideParticles)) + CollideParticles = parent->CollideParticles; + if (!OwnProps.is(flCollideMarks)) + CollideMarks = parent->CollideMarks; +} + +void SGameMtlPair::CopyFrom(SGameMtlPair *parent) +{ + R_ASSERT(parent); + OwnProps = parent->OwnProps; + ID_parent = parent->ID_parent; + + BreakingSounds = parent->BreakingSounds; + + StepSounds = parent->StepSounds; + + CollideSounds = parent->CollideSounds; + + CollideParticles = parent->CollideParticles; + + CollideMarks = parent->CollideMarks; +} + +//------------------------------------------------------------------------------ +// material library routines +//------------------------------------------------------------------------------ +LPCSTR CGameMtlLibrary::MtlPairToName(int mtl0, int mtl1) +{ + static string512 buf; + SGameMtl *M0 = GetMaterialByID(mtl0); + R_ASSERT(M0); + SGameMtl *M1 = GetMaterialByID(mtl1); + R_ASSERT(M1); + string256 buf0, buf1; + strcpy(buf0, *M0->m_Name); + _ChangeSymbol(buf0, '\\', '/'); + strcpy(buf1, *M1->m_Name); + _ChangeSymbol(buf1, '\\', '/'); + sprintf(buf, "%s \\ %s", buf0, buf1); + return buf; +} +void CGameMtlLibrary::NameToMtlPair(pcstr name, int &mtl0, int &mtl1) +{ + string256 buf0, buf1; + if (_GetItemCount(name, '\\') < 2) + { + mtl0 = GAMEMTL_NONE_ID; + mtl1 = GAMEMTL_NONE_ID; + return; + } + _GetItem(name, 0, buf0, '\\'); + _GetItem(name, 1, buf1, '\\'); + _ChangeSymbol(buf0, '/', '\\'); + _ChangeSymbol(buf1, '/', '\\'); + SGameMtl *M0 = GetMaterial(buf0); + mtl0 = M0 ? M0->GetID() : GAMEMTL_NONE_ID; + SGameMtl *M1 = GetMaterial(buf1); + mtl1 = M1 ? M1->GetID() : GAMEMTL_NONE_ID; +} +void CGameMtlLibrary::MtlNameToMtlPair(pcstr name, int &mtl0, int &mtl1) +{ + string256 buf; + SGameMtl *M0 = GetMaterial(_GetItem(name, 0, buf, ',')); + R_ASSERT(M0); + mtl0 = M0->GetID(); + SGameMtl *M1 = GetMaterial(_GetItem(name, 1, buf, ',')); + R_ASSERT(M1); + mtl1 = M1->GetID(); +} + +SGameMtlPair *CGameMtlLibrary::CreateMaterialPair(int m0, int m1, SGameMtlPair *parent) +{ + SGameMtlPair *M = xr_new(this); + if (parent) + { + M->ID_parent = parent->ID; + M->OwnProps.zero(); + } + M->ID = material_pair_index++; + M->SetPair(m0, m1); + material_pairs.push_back(M); + return M; +} + +SGameMtlPair *CGameMtlLibrary::AppendMaterialPair(int m0, int m1, SGameMtlPair *parent) +{ + SGameMtlPair *S = GetMaterialPair(m0, m1); + if (!S) + { + return CreateMaterialPair(m0, m1, parent); + } + else + { + return S; + } +} + +void CGameMtlLibrary::RemoveMaterialPair(pcstr name) +{ + int mtl0, mtl1; + NameToMtlPair(name, mtl0, mtl1); + RemoveMaterialPair(mtl0, mtl1); +} + +void CGameMtlLibrary::RemoveMaterialPair(GameMtlPairIt rem_it) +{ + if (rem_it == material_pairs.end()) + return; + // delete parent dependent + for (GameMtlPairIt it = material_pairs.begin(); it != material_pairs.end(); it++) + if ((*it)->ID_parent == (*rem_it)->ID) + { + // transfer parented props to child + (*it)->TransferFromParent(*rem_it); + // reset parenting + (*it)->ID_parent = -1; + } + // erase from list and remove physically + xr_delete(*rem_it); + material_pairs.erase(rem_it); +} + +void CGameMtlLibrary::RemoveMaterialPair(int mtl) +{ + for (int i = 0; i < (int)material_pairs.size(); i++) + { + GameMtlPairIt it = material_pairs.begin() + i; + if (((*it)->mtl0 == mtl) || ((*it)->mtl1 == mtl)) + { + RemoveMaterialPair(it); + i--; + } + } +} + +void CGameMtlLibrary::RemoveMaterialPair(int mtl0, int mtl1) +{ + GameMtlPairIt rem_it = GetMaterialPairIt(mtl0, mtl1); + if (rem_it == material_pairs.end()) + return; + RemoveMaterialPair(rem_it); +} + +GameMtlPairIt CGameMtlLibrary::GetMaterialPairIt(int id) +{ + for (GameMtlPairIt it = material_pairs.begin(); it != material_pairs.end(); it++) + if ((*it)->ID == id) + return it; + return material_pairs.end(); +} + +SGameMtlPair *CGameMtlLibrary::GetMaterialPair(int id) +{ + GameMtlPairIt it = GetMaterialPairIt(id); + return it != material_pairs.end() ? *it : 0; +} +GameMtlPairIt CGameMtlLibrary::GetMaterialPairIt(int mtl0, int mtl1) +{ + for (GameMtlPairIt it = material_pairs.begin(); it != material_pairs.end(); it++) + if ((*it)->IsPair(mtl0, mtl1)) + return it; + return material_pairs.end(); +} + +SGameMtlPair *CGameMtlLibrary::GetMaterialPair(int mtl0, int mtl1) +{ + GameMtlPairIt it = GetMaterialPairIt(mtl0, mtl1); + return it != material_pairs.end() ? *it : 0; +} + +SGameMtlPair *CGameMtlLibrary::GetMaterialPair(pcstr name) +{ + if (name && name[0]) + { + int mtl0, mtl1; + NameToMtlPair(name, mtl0, mtl1); + GameMtlPairIt it = GetMaterialPairIt(mtl0, mtl1); + return it != material_pairs.end() ? *it : 0; + } + return 0; +} + +//------------------------------------------------------------------------------ +// IO - routines +//------------------------------------------------------------------------------ +void SGameMtl::Save(IWriter &fs) +{ + Flags.set(flSlowDown, !fis_zero(1.f - fFlotationFactor, EPS_L)); + Flags.set(flShootable, fis_zero(fShootFactor, EPS_L)); + Flags.set(flTransparent, fis_zero(fVisTransparencyFactor, EPS_L)); + Flags.set(flInjurious, !fis_zero(fInjuriousSpeed, EPS_L)); + + fs.open_chunk(GAMEMTL_CHUNK_MAIN); + fs.w_u32(ID); + fs.w_stringZ(m_Name); + fs.close_chunk(); + + fs.open_chunk(GAMEMTL_CHUNK_DESC); + fs.w_stringZ(m_Desc); + fs.close_chunk(); + + fs.open_chunk(GAMEMTL_CHUNK_FLAGS); + fs.w_u32(Flags.get()); + fs.close_chunk(); + + fs.open_chunk(GAMEMTL_CHUNK_PHYSICS); + fs.w_float(fPHFriction); + fs.w_float(fPHDamping); + fs.w_float(fPHSpring); + fs.w_float(fPHBounceStartVelocity); + fs.w_float(fPHBouncing); + fs.close_chunk(); + + fs.open_chunk(GAMEMTL_CHUNK_FACTORS); + fs.w_float(fShootFactor); + fs.w_float(fBounceDamageFactor); + fs.w_float(fVisTransparencyFactor); + fs.w_float(fSndOcclusionFactor); + fs.close_chunk(); + + fs.open_chunk(GAMEMTL_CHUNK_FACTORS_MP); + fs.w_float(fShootFactorMP); + fs.close_chunk(); + + fs.open_chunk(GAMEMTL_CHUNK_FLOTATION); + fs.w_float(fFlotationFactor); + fs.close_chunk(); + + fs.open_chunk(GAMEMTL_CHUNK_INJURIOUS); + fs.w_float(fInjuriousSpeed); + fs.close_chunk(); + + fs.open_chunk(GAMEMTL_CHUNK_DENSITY); + fs.w_float(fDensityFactor); + fs.close_chunk(); +} + +void SGameMtlPair::Load(IReader &fs) +{ + shared_str buf; + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_PAIR)); + mtl0 = fs.r_u32(); + mtl1 = fs.r_u32(); + ID = fs.r_u32(); + ID_parent = fs.r_u32(); + OwnProps.assign(fs.r_u32()); + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_BREAKING)); + fs.r_stringZ(buf); + BreakingSounds = *buf; + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_STEP)); + fs.r_stringZ(buf); + StepSounds = *buf; + + R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_COLLIDE)); + fs.r_stringZ(buf); + CollideSounds = *buf; + fs.r_stringZ(buf); + CollideParticles = *buf; + fs.r_stringZ(buf); + CollideMarks = *buf; +} + +void SGameMtlPair::Save(IWriter &fs) +{ + fs.open_chunk(GAMEMTLPAIR_CHUNK_PAIR); + fs.w_u32(mtl0); + fs.w_u32(mtl1); + fs.w_u32(ID); + fs.w_u32(ID_parent); + fs.w_u32(OwnProps.get()); + fs.close_chunk(); + + // copy from parent + if (ID_parent != GAMEMTL_NONE_ID) + { + SGameMtlPair *P; + if ((0 != (P = GetLastParentValue(this, flBreakingSounds))) && (P != this)) + BreakingSounds = P->BreakingSounds; + if ((0 != (P = GetLastParentValue(this, flStepSounds))) && (P != this)) + StepSounds = P->StepSounds; + if ((0 != (P = GetLastParentValue(this, flCollideSounds))) && (P != this)) + CollideSounds = P->CollideSounds; + if ((0 != (P = GetLastParentValue(this, flCollideParticles))) && (P != this)) + CollideParticles = P->CollideParticles; + if ((0 != (P = GetLastParentValue(this, flCollideMarks))) && (P != this)) + CollideMarks = P->CollideMarks; + } + /* + else{ + OwnProps.zero(); + if (!BreakingSounds.IsEmpty()) OwnProps.set(flBreakingSounds,TRUE); + if (!StepSounds.IsEmpty()) OwnProps.set(flStepSounds,TRUE); + if (!CollideSounds.IsEmpty()) OwnProps.set(flCollideSounds,TRUE); + if (!CollideParticles.IsEmpty())OwnProps.set(flCollideParticles,TRUE); + if (!CollideMarks.IsEmpty()) OwnProps.set(flCollideMarks,TRUE); + } + */ + // save + fs.open_chunk(GAMEMTLPAIR_CHUNK_BREAKING); + fs.w_stringZ(BreakingSounds); + fs.close_chunk(); + + fs.open_chunk(GAMEMTLPAIR_CHUNK_STEP); + fs.w_stringZ(StepSounds); + fs.close_chunk(); + + fs.open_chunk(GAMEMTLPAIR_CHUNK_COLLIDE); + fs.w_stringZ(CollideSounds); + fs.w_stringZ(CollideParticles); + fs.w_stringZ(CollideMarks); + fs.close_chunk(); +} + +bool CGameMtlLibrary::Save() +{ + R_ASSERT(FALSE == UpdateMtlPairs()); + // save + CMemoryWriter fs; + fs.open_chunk(GAMEMTLS_CHUNK_VERSION); + fs.w_u16(GAMEMTL_CURRENT_VERSION); + fs.close_chunk(); + + fs.open_chunk(GAMEMTLS_CHUNK_AUTOINC); + fs.w_u32(material_index); + fs.w_u32(material_pair_index); + fs.close_chunk(); + + fs.open_chunk(GAMEMTLS_CHUNK_MTLS); + int count = 0; + for (GameMtlIt m_it = materials.begin(); m_it != materials.end(); m_it++) + { + fs.open_chunk(count++); + (*m_it)->Save(fs); + fs.close_chunk(); + } + fs.close_chunk(); + + fs.open_chunk(GAMEMTLS_CHUNK_MTLS_PAIR); + count = 0; + for (GameMtlPairIt p_it = material_pairs.begin(); p_it != material_pairs.end(); p_it++) + { + fs.open_chunk(count++); + (*p_it)->Save(fs); + fs.close_chunk(); + } + fs.close_chunk(); + + string_path fn; + FS.update_path(fn, _game_data_, GAMEMTL_FILENAME); + return fs.save_to(fn); +} + +void SGameMtlPair::OnDrawUI() +{ + if (m_EditParent) + { + bool change = true; + shared_str result; + if (UIChooseForm::GetResult(change, result)) + { + if (change) + { + int m0, m1; + m_Owner->NameToMtlPair(result.c_str(), m0, m1); + SGameMtlPair *p = m_Owner->GetMaterialPair(m0, m1); + VERIFY(p); + if (!SetParent(p->GetID())) + { + ELog.DlgMsg(mtError, "Pair can't inherit from self."); + } + else + { + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + } + else + { + SetParent(GAMEMTL_NONE_ID); + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + m_EditParent = false; + } + UIChooseForm::Update(); + } + if (m_EditCommand) + { + bool change = true; + shared_str result; + if (UIChooseForm::GetResult(change, result)) + { + if (change) + { + AStringVec lst; + _SequenceToList(lst, result.c_str()); + for (AStringIt it = lst.begin(); it != lst.end(); it++) + { + int m0, m1; + m_Owner->NameToMtlPair(it->c_str(), m0, m1); + SGameMtlPair *p = m_Owner->GetMaterialPair(m0, m1); + VERIFY(p); + if (!p->SetParent(GetID())) + { + ELog.DlgMsg(mtError, "Pair can't inherit from self."); + } + } + ExecCommand(COMMAND_UPDATE_PROPERTIES); + } + m_EditCommand = FALSE; + } + UIChooseForm::Update(); + } +} + +SGameMtlPair::~SGameMtlPair() +{ + +} diff --git a/src/xrCore/FMesh.cpp b/src/editors/xrECore/OgfDesc.cpp similarity index 93% rename from src/xrCore/FMesh.cpp rename to src/editors/xrECore/OgfDesc.cpp index 2aa811d1a1b..913f18ffe95 100644 --- a/src/xrCore/FMesh.cpp +++ b/src/editors/xrECore/OgfDesc.cpp @@ -1,7 +1,5 @@ #include "stdafx.h" -#pragma hdrstop - -#include "FMesh.hpp" +#include "OgfDesc.h" void ogf_desc::Load(IReader& F) { diff --git a/src/editors/xrECore/OgfDesc.h b/src/editors/xrECore/OgfDesc.h new file mode 100644 index 00000000000..09597ec033f --- /dev/null +++ b/src/editors/xrECore/OgfDesc.h @@ -0,0 +1,16 @@ +#pragma once + +// OGF_DESC +struct ECORE_API ogf_desc +{ + shared_str source_file; + shared_str build_name; + time_t build_time; + shared_str create_name; + time_t create_time; + shared_str modif_name; + time_t modif_time; + ogf_desc() : build_time(0), create_time(0), modif_time(0) {} + void Load(IReader& F); + void Save(IWriter& F); +}; diff --git a/src/editors/xrECore/StbImage.cpp b/src/editors/xrECore/StbImage.cpp new file mode 100644 index 00000000000..31f9ce6fe54 --- /dev/null +++ b/src/editors/xrECore/StbImage.cpp @@ -0,0 +1,3 @@ +#include "stdafx.h" +#define STB_IMAGE_IMPLEMENTATION +//#include "..\BearBundle\External\Public\StbImage\stb_image.h" \ No newline at end of file diff --git a/src/editors/xrECore/WildMagic/RAPIDMinBox.cpp b/src/editors/xrECore/WildMagic/RAPIDMinBox.cpp new file mode 100644 index 00000000000..f28b4705535 --- /dev/null +++ b/src/editors/xrECore/WildMagic/RAPIDMinBox.cpp @@ -0,0 +1,293 @@ +#include "stdafx.h" +#pragma hdrstop + +struct moment +{ + float A; + Fvector m; + Fmatrix33 s; +}; + +struct accum +{ + float A; + Fvector m; + Fmatrix33 s; +}; + +void compute_moment(moment &M, Fvector &p, Fvector &q, Fvector &r) +{ + Fvector u, v, w; + + // compute the area of the triangle + u.sub(q, p); + v.sub(r, p); + w.crossproduct(u, v); + M.A = 0.5f * w.magnitude(); + + if (M.A == 0.0f) + { + // This triangle has zero area. The second order components + // would be eliminated with the usual formula, so, for the + // sake of robustness we use an alternative form. These are the + // centroid and second-order components of the triangle's vertices. + + // centroid + M.m.x = (p.x + q.x + r.x) / 3; + M.m.y = (p.y + q.y + r.y) / 3; + M.m.z = (p.z + q.z + r.z) / 3; + + // second-order components + M.s.m[0][0] = (p.x * p.x + q.x * q.x + r.x * r.x); + M.s.m[0][1] = (p.x * p.y + q.x * q.y + r.x * r.y); + M.s.m[0][2] = (p.x * p.z + q.x * q.z + r.x * r.z); + M.s.m[1][1] = (p.y * p.y + q.y * q.y + r.y * r.y); + M.s.m[1][2] = (p.y * p.z + q.y * q.z + r.y * r.z); + M.s.m[2][2] = (p.z * p.z + q.z * q.z + r.z * r.z); + M.s.m[2][1] = M.s.m[1][2]; + M.s.m[1][0] = M.s.m[0][1]; + M.s.m[2][0] = M.s.m[0][2]; + + return; + } + + // get the centroid + M.m.x = (p.x + q.x + r.x) / 3; + M.m.y = (p.y + q.y + r.y) / 3; + M.m.z = (p.z + q.z + r.z) / 3; + + // get the second order components -- note the weighting by the area + M.s.m[0][0] = M.A * (9 * M.m[0] * M.m[0] + p[0] * p[0] + q[0] * q[0] + r[0] * r[0]) / 12; + M.s.m[0][1] = M.A * (9 * M.m[0] * M.m[1] + p[0] * p[1] + q[0] * q[1] + r[0] * r[1]) / 12; + M.s.m[1][1] = M.A * (9 * M.m[1] * M.m[1] + p[1] * p[1] + q[1] * q[1] + r[1] * r[1]) / 12; + M.s.m[0][2] = M.A * (9 * M.m[0] * M.m[2] + p[0] * p[2] + q[0] * q[2] + r[0] * r[2]) / 12; + M.s.m[1][2] = M.A * (9 * M.m[1] * M.m[2] + p[1] * p[2] + q[1] * q[2] + r[1] * r[2]) / 12; + M.s.m[2][2] = M.A * (9 * M.m[2] * M.m[2] + p[2] * p[2] + q[2] * q[2] + r[2] * r[2]) / 12; + M.s.m[2][1] = M.s.m[1][2]; + M.s.m[1][0] = M.s.m[0][1]; + M.s.m[2][0] = M.s.m[0][2]; +} + +void compute_moments(moment *M, Fvector *vertices, int num_tris) +{ + int i; + + // first collect all the moments, and obtain the area of the + // smallest nonzero area triangle. + + float Amin = 0.0f; + int zero = 0; + for (i = 0; i < num_tris; i++) + { + compute_moment(M[i], vertices[i * 3 + 0], vertices[i * 3 + 1], vertices[i * 3 + 2]); + if (M[i].A == 0.0f) + { + zero = 1; + } + else + { + if (Amin == 0.0f) + Amin = M[i].A; + else if (M[i].A < Amin) + Amin = M[i].A; + } + } + + if (zero) + { + // if there are any zero area triangles, go back and set their area + + // if ALL the triangles have zero area, then set the area thingy + // to some arbitrary value. + if (Amin == 0.0f) + Amin = 1.0f; + + for (i = 0; i < num_tris; i++) + { + if (M[i].A == 0.0f) + M[i].A = Amin; + } + } +} + +void clear_accum(accum &a) +{ + a.m.set(0.f, 0.f, 0.f); + a.s.m[0][0] = a.s.m[0][1] = a.s.m[0][2] = 0.0; + a.s.m[1][0] = a.s.m[1][1] = a.s.m[1][2] = 0.0; + a.s.m[2][0] = a.s.m[2][1] = a.s.m[2][2] = 0.0; + a.A = 0.0; +} + +void accum_moment(accum &a, moment &b) +{ + a.m.x += b.m.x * b.A; + a.m.y += b.m.y * b.A; + a.m.z += b.m.z * b.A; + + a.s.m[0][0] += b.s.m[0][0]; + a.s.m[0][1] += b.s.m[0][1]; + a.s.m[0][2] += b.s.m[0][2]; + a.s.m[1][0] += b.s.m[1][0]; + a.s.m[1][1] += b.s.m[1][1]; + a.s.m[1][2] += b.s.m[1][2]; + a.s.m[2][0] += b.s.m[2][0]; + a.s.m[2][1] += b.s.m[2][1]; + a.s.m[2][2] += b.s.m[2][2]; + + a.A += b.A; +} + +void mean_from_moment(Fvector &M, moment &m) +{ + M.set(m.m); +} + +void mean_from_accum(Fvector &M, accum &a) +{ + M.div(a.m, a.A); +} + +void covariance_from_accum(Fmatrix33 &C, accum &a) +{ + int i, j; + for (i = 0; i < 3; i++) + for (j = 0; j < 3; j++) + C.m[i][j] = a.s.m[i][j] - a.m[i] * a.m[j] / a.A; +} + +// not a full sort -- just makes column 1 the largest +int eigen_and_sort1(Fmatrix33 &evecs, Fmatrix33 &cov) +{ + float t; + Fvector evals; + int n; + + n = evecs.Meigen(evals, cov); + + if (evals.z > evals.x) + { + if (evals.z > evals.y) + { + // 2 is largest, swap with column 0 + t = evecs.m[0][2]; + evecs.m[0][2] = evecs.m[0][0]; + evecs.m[0][0] = t; + t = evecs.m[1][2]; + evecs.m[1][2] = evecs.m[1][0]; + evecs.m[1][0] = t; + t = evecs.m[2][2]; + evecs.m[2][2] = evecs.m[2][0]; + evecs.m[2][0] = t; + } + else + { + // 1 is largest, swap with column 0 + t = evecs.m[0][1]; + evecs.m[0][1] = evecs.m[0][0]; + evecs.m[0][0] = t; + t = evecs.m[1][1]; + evecs.m[1][1] = evecs.m[1][0]; + evecs.m[1][0] = t; + t = evecs.m[2][1]; + evecs.m[2][1] = evecs.m[2][0]; + evecs.m[2][0] = t; + } + } + else + { + if (evals.x > evals.y) + { + // 0 is largest, do nothing + } + else + { + // 1 is largest + t = evecs.m[0][1]; + evecs.m[0][1] = evecs.m[0][0]; + evecs.m[0][0] = t; + t = evecs.m[1][1]; + evecs.m[1][1] = evecs.m[1][0]; + evecs.m[1][0] = t; + t = evecs.m[2][1]; + evecs.m[2][1] = evecs.m[2][0]; + evecs.m[2][0] = t; + } + } + + // we are returning the number of iterations Meigen took. + // too many iterations means our chosen orientation is bad. + return n; +} + +void minmax(float &mn, float &mx, float v) +{ + if (v < mn) + mn = v; + else if (v > mx) + mx = v; +} + +void reaccum_moments(accum &A, int n, moment *RAPID_moment) +{ + clear_accum(A); + for (int i = 0; i < n; i++) + accum_moment(A, RAPID_moment[i]); +} + +BOOL RAPIDMinBox(Fobb &B, Fvector *vertices, u32 v_count) +{ + u32 num_tris = v_count / 3; + + // Determine initial orientation, mean point, and splitting axis. + accum M; + Fmatrix33 C; + + moment *RAPID_moment = xr_alloc(num_tris); + VERIFY(RAPID_moment); + + compute_moments(RAPID_moment, vertices, num_tris); + + clear_accum(M); + for (u32 i = 0; i < num_tris; i++) + accum_moment(M, RAPID_moment[i]); + + mean_from_accum(B.m_translate, M); + covariance_from_accum(C, M); + + eigen_and_sort1(B.m_rotate, C); + + // do the build + Fvector c; + Fvector minval, maxval; + B.m_rotate.MTxV(c, vertices[0]); + minval.set(c); + maxval.set(c); + for (u32 i = 0; i < v_count; i++) + { + B.m_rotate.MTxV(c, vertices[i]); + minmax(minval.x, maxval.x, c.x); + minmax(minval.y, maxval.y, c.y); + minmax(minval.z, maxval.z, c.z); + } + + // With the max and min data, determine the center point and dimensions + // of the parent box. + c.add(minval, maxval); + c.mul(0.5f); + + B.m_translate.x = c[0] * B.m_rotate.m[0][0] + c[1] * B.m_rotate.m[0][1] + c[2] * B.m_rotate.m[0][2]; + B.m_translate.y = c[0] * B.m_rotate.m[1][0] + c[1] * B.m_rotate.m[1][1] + c[2] * B.m_rotate.m[1][2]; + B.m_translate.z = c[0] * B.m_rotate.m[2][0] + c[1] * B.m_rotate.m[2][1] + c[2] * B.m_rotate.m[2][2]; + B.m_halfsize.sub(maxval, minval); + B.m_halfsize.mul(0.5f); + + // free the moment list + xr_free(RAPID_moment); + + // need for our use (RAPID has OpenGL column<->line) + B.m_rotate.transpose(); + + return TRUE; +} +//------------------------------------------------------------------------------ diff --git a/src/editors/xrECore/WildMagic/WmlApprGaussPointsFit3.cpp b/src/editors/xrECore/WildMagic/WmlApprGaussPointsFit3.cpp new file mode 100644 index 00000000000..388e05a2107 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlApprGaussPointsFit3.cpp @@ -0,0 +1,155 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlEigen.h" +#include "WmlApprGaussPointsFit3.h" +using namespace Wml; + +//---------------------------------------------------------------------------- +template +void Wml::GaussPointsFit(int iQuantity, const Vector3 *akPoint, + Vector3 &rkCenter, Vector3 akAxis[3], Real afExtent[3]) +{ + // compute mean of points + rkCenter = akPoint[0]; + int i; + for (i = 1; i < iQuantity; i++) + rkCenter += akPoint[i]; + Real fInvQuantity = ((Real)1.0) / iQuantity; + rkCenter *= fInvQuantity; + + // compute covariances of points + Real fSumXX = (Real)0.0, fSumXY = (Real)0.0, fSumXZ = (Real)0.0; + Real fSumYY = (Real)0.0, fSumYZ = (Real)0.0, fSumZZ = (Real)0.0; + for (i = 0; i < iQuantity; i++) + { + Vector3 kDiff = akPoint[i] - rkCenter; + fSumXX += kDiff.X() * kDiff.X(); + fSumXY += kDiff.X() * kDiff.Y(); + fSumXZ += kDiff.X() * kDiff.Z(); + fSumYY += kDiff.Y() * kDiff.Y(); + fSumYZ += kDiff.Y() * kDiff.Z(); + fSumZZ += kDiff.Z() * kDiff.Z(); + } + fSumXX *= fInvQuantity; + fSumXY *= fInvQuantity; + fSumXZ *= fInvQuantity; + fSumYY *= fInvQuantity; + fSumYZ *= fInvQuantity; + fSumZZ *= fInvQuantity; + + // compute eigenvectors for covariance matrix + Eigen kES(3); + kES(0, 0) = fSumXX; + kES(0, 1) = fSumXY; + kES(0, 2) = fSumXZ; + kES(1, 0) = fSumXY; + kES(1, 1) = fSumYY; + kES(1, 2) = fSumYZ; + kES(2, 0) = fSumXZ; + kES(2, 1) = fSumYZ; + kES(2, 2) = fSumZZ; + kES.IncrSortEigenStuff3(); + + for (i = 0; i < 3; i++) + { + afExtent[i] = kES.GetEigenvalue(i); + kES.GetEigenvector(i, akAxis[i]); + } +} +//---------------------------------------------------------------------------- +template +bool Wml::GaussPointsFit(int iQuantity, const Vector3 *akPoint, + const bool *abValid, Vector3 &rkCenter, Vector3 akAxis[3], + Real afExtent[3]) +{ + // compute mean of points + rkCenter = Vector3::ZERO; + int i, iValidQuantity = 0; + for (i = 0; i < iQuantity; i++) + { + if (abValid[i]) + { + rkCenter += akPoint[i]; + iValidQuantity++; + } + } + if (iValidQuantity == 0) + return false; + + Real fInvQuantity = ((Real)1.0) / iValidQuantity; + rkCenter *= fInvQuantity; + + // compute covariances of points + Real fSumXX = (Real)0.0, fSumXY = (Real)0.0, fSumXZ = (Real)0.0; + Real fSumYY = (Real)0.0, fSumYZ = (Real)0.0, fSumZZ = (Real)0.0; + for (i = 0; i < iQuantity; i++) + { + if (abValid[i]) + { + Vector3 kDiff = akPoint[i] - rkCenter; + fSumXX += kDiff.X() * kDiff.X(); + fSumXY += kDiff.X() * kDiff.Y(); + fSumXZ += kDiff.X() * kDiff.Z(); + fSumYY += kDiff.Y() * kDiff.Y(); + fSumYZ += kDiff.Y() * kDiff.Z(); + fSumZZ += kDiff.Z() * kDiff.Z(); + } + } + fSumXX *= fInvQuantity; + fSumXY *= fInvQuantity; + fSumXZ *= fInvQuantity; + fSumYY *= fInvQuantity; + fSumYZ *= fInvQuantity; + fSumZZ *= fInvQuantity; + + // compute eigenvectors for covariance matrix + Eigen kES(3); + kES(0, 0) = fSumXX; + kES(0, 1) = fSumXY; + kES(0, 2) = fSumXZ; + kES(1, 0) = fSumXY; + kES(1, 1) = fSumYY; + kES(1, 2) = fSumYZ; + kES(2, 0) = fSumXZ; + kES(2, 1) = fSumYZ; + kES(2, 2) = fSumZZ; + kES.IncrSortEigenStuff3(); + + for (i = 0; i < 3; i++) + { + afExtent[i] = kES.GetEigenvalue(i); + kES.GetEigenvector(i, akAxis[i]); + } + + return true; +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// explicit instantiation +//---------------------------------------------------------------------------- +namespace Wml +{ + template WML_ITEM void GaussPointsFit(int, + const Vector3 *, Vector3 &, Vector3[3], float[3]); + template WML_ITEM bool GaussPointsFit(int, + const Vector3 *, const bool *, Vector3 &, Vector3[3], + float[3]); + + template WML_ITEM void GaussPointsFit(int, + const Vector3 *, Vector3 &, Vector3[3], double[3]); + template WML_ITEM bool GaussPointsFit(int, + const Vector3 *, const bool *, Vector3 &, Vector3[3], + double[3]); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlApprGaussPointsFit3.h b/src/editors/xrECore/WildMagic/WmlApprGaussPointsFit3.h new file mode 100644 index 00000000000..c1a4a943187 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlApprGaussPointsFit3.h @@ -0,0 +1,37 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLAPPR3DGAUSSPOINTSFITH +#define WMLAPPR3DGAUSSPOINTSFITH + +// Fit points with a Gaussian distribution. The center is the mean of the +// points, the axes are the eigenvectors of the covariance matrix, and the +// extents are the eigenvalues of the covariance matrix and are returned in +// increasing order. The last function allows selection of valid vertices +// from a pool. The return value is 'true' if and only if at least one +// vertex was valid. + +#include "WmlVector3.h" + +namespace Wml +{ + + template + WML_ITEM void GaussPointsFit(int iQuantity, const Vector3 *akPoint, + Vector3 &rkCenter, Vector3 akAxis[3], Real afExtent[3]); + + template + WML_ITEM bool GaussPointsFit(int iQuantity, const Vector3 *akPoint, + const bool *abValid, Vector3 &rkCenter, Vector3 akAxis[3], + Real afExtent[3]); + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlBox3.cpp b/src/editors/xrECore/WildMagic/WmlBox3.cpp new file mode 100644 index 00000000000..11ce21d7ce7 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlBox3.cpp @@ -0,0 +1,114 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlBox3.h" +using namespace Wml; + +//---------------------------------------------------------------------------- +template +Box3::Box3() +{ + // no initialization for efficiency +} +//---------------------------------------------------------------------------- +template +Vector3 &Box3::Center() +{ + return m_kCenter; +} +//---------------------------------------------------------------------------- +template +const Vector3 &Box3::Center() const +{ + return m_kCenter; +} +//---------------------------------------------------------------------------- +template +Vector3 &Box3::Axis(int i) +{ + assert(0 <= i && i < 3); + return m_akAxis[i]; +} +//---------------------------------------------------------------------------- +template +const Vector3 &Box3::Axis(int i) const +{ + assert(0 <= i && i < 3); + return m_akAxis[i]; +} +//---------------------------------------------------------------------------- +template +Vector3 *Box3::Axes() +{ + return m_akAxis; +} +//---------------------------------------------------------------------------- +template +const Vector3 *Box3::Axes() const +{ + return m_akAxis; +} +//---------------------------------------------------------------------------- +template +Real &Box3::Extent(int i) +{ + assert(0 <= i && i < 3); + return m_afExtent[i]; +} +//---------------------------------------------------------------------------- +template +const Real &Box3::Extent(int i) const +{ + assert(0 <= i && i < 3); + return m_afExtent[i]; +} +//---------------------------------------------------------------------------- +template +Real *Box3::Extents() +{ + return m_afExtent; +} +//---------------------------------------------------------------------------- +template +const Real *Box3::Extents() const +{ + return m_afExtent; +} +//---------------------------------------------------------------------------- +template +void Box3::ComputeVertices(Vector3 akVertex[8]) const +{ + Vector3 akEAxis[3]; + akEAxis[0] = m_akAxis[0] * m_afExtent[0]; + akEAxis[1] = m_akAxis[1] * m_afExtent[1]; + akEAxis[2] = m_akAxis[2] * m_afExtent[2]; + + akVertex[0] = m_kCenter - akEAxis[0] - akEAxis[1] - akEAxis[2]; + akVertex[1] = m_kCenter + akEAxis[0] - akEAxis[1] - akEAxis[2]; + akVertex[2] = m_kCenter + akEAxis[0] + akEAxis[1] - akEAxis[2]; + akVertex[3] = m_kCenter - akEAxis[0] + akEAxis[1] - akEAxis[2]; + akVertex[4] = m_kCenter - akEAxis[0] - akEAxis[1] + akEAxis[2]; + akVertex[5] = m_kCenter + akEAxis[0] - akEAxis[1] + akEAxis[2]; + akVertex[6] = m_kCenter + akEAxis[0] + akEAxis[1] + akEAxis[2]; + akVertex[7] = m_kCenter - akEAxis[0] + akEAxis[1] + akEAxis[2]; +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// explicit instantiation +//---------------------------------------------------------------------------- +namespace Wml +{ + template WML_ITEM class Box3; + template WML_ITEM class Box3; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlBox3.h b/src/editors/xrECore/WildMagic/WmlBox3.h new file mode 100644 index 00000000000..3328cc3c3b0 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlBox3.h @@ -0,0 +1,51 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLBOX3H +#define WMLBOX3H + +#include "WmlVector3.h" + +namespace Wml +{ + + template + class WML_ITEM Box3 + { + public: + Box3(); + + Vector3 &Center(); + const Vector3 &Center() const; + + Vector3 &Axis(int i); + const Vector3 &Axis(int i) const; + Vector3 *Axes(); + const Vector3 *Axes() const; + + Real &Extent(int i); + const Real &Extent(int i) const; + Real *Extents(); + const Real *Extents() const; + + void ComputeVertices(Vector3 akVertex[8]) const; + + protected: + Vector3 m_kCenter; + Vector3 m_akAxis[3]; + Real m_afExtent[3]; + }; + + typedef Box3 Box3f; + typedef Box3 Box3d; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlContBox3.cpp b/src/editors/xrECore/WildMagic/WmlContBox3.cpp new file mode 100644 index 00000000000..fb382836cc4 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlContBox3.cpp @@ -0,0 +1,301 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlApprGaussPointsFit3.h" +#include "WmlContBox3.h" +#include "WmlQuaternion.h" +using namespace Wml; + +//---------------------------------------------------------------------------- +template +void Wml::ContAlignedBox(int iQuantity, const Vector3 *akPoint, + Vector3 &rkMin, Vector3 &rkMax) +{ + rkMin = akPoint[0]; + rkMax = rkMin; + + for (int i = 1; i < iQuantity; i++) + { + if (akPoint[i].X() < rkMin.X()) + rkMin.X() = akPoint[i].X(); + else if (akPoint[i].X() > rkMax.X()) + rkMax.X() = akPoint[i].X(); + + if (akPoint[i].Y() < rkMin.Y()) + rkMin.Y() = akPoint[i].Y(); + else if (akPoint[i].Y() > rkMax.Y()) + rkMax.Y() = akPoint[i].Y(); + + if (akPoint[i].Z() < rkMin.Z()) + rkMin.Z() = akPoint[i].Z(); + else if (akPoint[i].Z() > rkMax.Z()) + rkMax.Z() = akPoint[i].Z(); + } +} +//---------------------------------------------------------------------------- +template +Box3 Wml::ContOrientedBox(int iQuantity, const Vector3 *akPoint) +{ + Box3 kBox; + + GaussPointsFit(iQuantity, akPoint, kBox.Center(), kBox.Axes(), + kBox.Extents()); + + // Let C be the box center and let U0, U1, and U2 be the box axes. Each + // input point is of the form X = C + y0*U0 + y1*U1 + y2*U2. The + // following code computes min(y0), max(y0), min(y1), max(y1), min(y2), + // and max(y2). The box center is then adjusted to be + // C' = C + 0.5*(min(y0)+max(y0))*U0 + 0.5*(min(y1)+max(y1))*U1 + + // 0.5*(min(y2)+max(y2))*U2 + + Vector3 kDiff = akPoint[0] - kBox.Center(); + Real fY0Min = kDiff.Dot(kBox.Axis(0)), fY0Max = fY0Min; + Real fY1Min = kDiff.Dot(kBox.Axis(1)), fY1Max = fY1Min; + Real fY2Min = kDiff.Dot(kBox.Axis(2)), fY2Max = fY2Min; + + for (int i = 1; i < iQuantity; i++) + { + kDiff = akPoint[i] - kBox.Center(); + + Real fY0 = kDiff.Dot(kBox.Axis(0)); + if (fY0 < fY0Min) + fY0Min = fY0; + else if (fY0 > fY0Max) + fY0Max = fY0; + + Real fY1 = kDiff.Dot(kBox.Axis(1)); + if (fY1 < fY1Min) + fY1Min = fY1; + else if (fY1 > fY1Max) + fY1Max = fY1; + + Real fY2 = kDiff.Dot(kBox.Axis(2)); + if (fY2 < fY2Min) + fY2Min = fY2; + else if (fY2 > fY2Max) + fY2Max = fY2; + } + + kBox.Center() += (((Real)0.5) * (fY0Min + fY0Max)) * kBox.Axis(0) + + (((Real)0.5) * (fY1Min + fY1Max)) * kBox.Axis(1) + + (((Real)0.5) * (fY2Min + fY2Max)) * kBox.Axis(2); + + kBox.Extent(0) = ((Real)0.5) * (fY0Max - fY0Min); + kBox.Extent(1) = ((Real)0.5) * (fY1Max - fY1Min); + kBox.Extent(2) = ((Real)0.5) * (fY2Max - fY2Min); + + return kBox; +} +//---------------------------------------------------------------------------- +template +bool Wml::ContOrientedBox(int iQuantity, const Vector3 *akPoint, + const bool *abValid, Box3 &rkBox) +{ + if (!GaussPointsFit(iQuantity, akPoint, abValid, rkBox.Center(), + rkBox.Axes(), rkBox.Extents())) + { + return false; + } + + // Let C be the box center and let U0, U1, and U2 be the box axes. Each + // input point is of the form X = C + y0*U0 + y1*U1 + y2*U2. The + // following code computes min(y0), max(y0), min(y1), max(y1), min(y2), + // and max(y2). The box center is then adjusted to be + // C' = C + 0.5*(min(y0)+max(y0))*U0 + 0.5*(min(y1)+max(y1))*U1 + + // 0.5*(min(y2)+max(y2))*U2 + + // get first valid vertex + Vector3 kDiff; + Real fY0Min = (Real)0.0, fY0Max = (Real)0.0; + Real fY1Min = (Real)0.0, fY1Max = (Real)0.0; + Real fY2Min = (Real)0.0, fY2Max = (Real)0.0; + int i; + for (i = 0; i < iQuantity; i++) + { + if (abValid[i]) + { + kDiff = akPoint[i] - rkBox.Center(); + fY0Min = kDiff.Dot(rkBox.Axis(0)); + fY0Max = fY0Min; + fY1Min = kDiff.Dot(rkBox.Axis(1)); + fY1Max = fY1Min; + fY2Min = kDiff.Dot(rkBox.Axis(2)); + fY2Max = fY2Min; + break; + } + } + + for (i++; i < iQuantity; i++) + { + if (abValid[i]) + { + kDiff = akPoint[i] - rkBox.Center(); + + Real fY0 = kDiff.Dot(rkBox.Axis(0)); + if (fY0 < fY0Min) + fY0Min = fY0; + else if (fY0 > fY0Max) + fY0Max = fY0; + + Real fY1 = kDiff.Dot(rkBox.Axis(1)); + if (fY1 < fY1Min) + fY1Min = fY1; + else if (fY1 > fY1Max) + fY1Max = fY1; + + Real fY2 = kDiff.Dot(rkBox.Axis(2)); + if (fY2 < fY2Min) + fY2Min = fY2; + else if (fY2 > fY2Max) + fY2Max = fY2; + } + } + + rkBox.Center() += (0.5f * (fY0Min + fY0Max)) * rkBox.Axis(0) + (0.5f * (fY1Min + fY1Max)) * rkBox.Axis(1) + + (0.5f * (fY2Min + fY2Max)) * rkBox.Axis(2); + + rkBox.Extent(0) = 0.5f * (fY0Max - fY0Min); + rkBox.Extent(1) = 0.5f * (fY1Max - fY1Min); + rkBox.Extent(2) = 0.5f * (fY2Max - fY2Min); + + return true; +} +//---------------------------------------------------------------------------- +template +Box3 Wml::MergeBoxes(const Box3 &rkBox0, + const Box3 &rkBox1) +{ + // construct a box that contains the input boxes + Box3 kBox; + + // The first guess at the box center. This value will be updated later + // after the input box vertices are projected onto axes determined by an + // average of box axes. + kBox.Center() = ((Real)0.5) * (rkBox0.Center() + rkBox1.Center()); + + // A box's axes, when viewed as the columns of a matrix, form a rotation + // matrix. The input box axes are converted to quaternions. The average + // quaternion is computed, then normalized to unit length. The result is + // the slerp of the two input quaternions with t-value of 1/2. The result + // is converted back to a rotation matrix and its columns are selected as + // the merged box axes. + Quaternion kQ0, kQ1; + kQ0.FromRotationMatrix(rkBox0.Axes()); + kQ1.FromRotationMatrix(rkBox1.Axes()); + if (kQ0.Dot(kQ1) < 0.0f) + kQ1 = -kQ1; + + Quaternion kQ = kQ0 + kQ1; + Real fInvLength = Math::InvSqrt(kQ.Dot(kQ)); + kQ = fInvLength * kQ; + kQ.ToRotationMatrix(kBox.Axes()); + + // Project the input box vertices onto the merged-box axes. Each axis + // D[i] containing the current center C has a minimum projected value + // pmin[i] and a maximum projected value pmax[i]. The corresponding end + // points on the axes are C+pmin[i]*D[i] and C+pmax[i]*D[i]. The point C + // is not necessarily the midpoint for any of the intervals. The actual + // box center will be adjusted from C to a point C' that is the midpoint + // of each interval, + // C' = C + sum_{i=0}^2 0.5*(pmin[i]+pmax[i])*D[i] + // The box extents are + // e[i] = 0.5*(pmax[i]-pmin[i]) + + int i, j; + Real fDot; + Vector3 akVertex[8], kDiff; + Vector3 kMin = Vector3::ZERO; + Vector3 kMax = Vector3::ZERO; + + rkBox0.ComputeVertices(akVertex); + for (i = 0; i < 8; i++) + { + kDiff = akVertex[i] - kBox.Center(); + for (j = 0; j < 3; j++) + { + fDot = kDiff.Dot(kBox.Axis(j)); + if (fDot > kMax[j]) + kMax[j] = fDot; + else if (fDot < kMin[j]) + kMin[j] = fDot; + } + } + + rkBox1.ComputeVertices(akVertex); + for (i = 0; i < 8; i++) + { + kDiff = akVertex[i] - kBox.Center(); + for (j = 0; j < 3; j++) + { + fDot = kDiff.Dot(kBox.Axis(j)); + if (fDot > kMax[j]) + kMax[j] = fDot; + else if (fDot < kMin[j]) + kMin[j] = fDot; + } + } + + // [kMin,kMax] is the axis-aligned box in the coordinate system of the + // merged box axes. Update the current box center to be the center of + // the new box. Compute the extens based on the new center. + for (j = 0; j < 3; j++) + { + kBox.Center() += (((Real)0.5) * (kMax[j] + kMin[j])) * kBox.Axis(j); + kBox.Extent(j) = ((Real)0.5) * (kMax[j] - kMin[j]); + } + + return kBox; +} +//---------------------------------------------------------------------------- +template +bool Wml::InBox(const Vector3 &rkPoint, const Box3 &rkBox, + Real fEpsilon) +{ + Vector3 kDiff = rkPoint - rkBox.Center(); + for (int i = 0; i < 3; i++) + { + Real fCoeff = kDiff.Dot(rkBox.Axis(i)); + if (Math::FAbs(fCoeff) > rkBox.Extent(i) + fEpsilon) + return false; + } + return true; +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// explicit instantiation +//---------------------------------------------------------------------------- +namespace Wml +{ + template WML_ITEM void ContAlignedBox(int, + const Vector3 *, Vector3 &, Vector3 &); + template WML_ITEM Box3 ContOrientedBox(int, + const Vector3 *); + template WML_ITEM bool ContOrientedBox(int, + const Vector3 *, const bool *, Box3 &); + template WML_ITEM bool InBox(const Vector3 &, + const Box3 &, float); + template WML_ITEM Box3 MergeBoxes(const Box3 &, + const Box3 &); + + template WML_ITEM void ContAlignedBox(int, + const Vector3 *, Vector3 &, Vector3 &); + template WML_ITEM Box3 ContOrientedBox(int, + const Vector3 *); + template WML_ITEM bool ContOrientedBox(int, + const Vector3 *, const bool *, Box3 &); + template WML_ITEM bool InBox(const Vector3 &, + const Box3 &, double); + template WML_ITEM Box3 MergeBoxes(const Box3 &, + const Box3 &); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlContBox3.h b/src/editors/xrECore/WildMagic/WmlContBox3.h new file mode 100644 index 00000000000..b63ea5a2dbf --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlContBox3.h @@ -0,0 +1,47 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLCONTBOX3H +#define WMLCONTBOX3H + +#include "WmlBox3.h" + +namespace Wml +{ + + template + WML_ITEM void ContAlignedBox(int iQuantity, const Vector3 *akPoint, + Vector3 &rkMin, Vector3 &rkMax); + + template + WML_ITEM Box3 ContOrientedBox(int iQuantity, + const Vector3 *akPoint); + + // This function allows for selection of vertices from a pool. The return + // value is 'true' if and only if at least one vertex is valid. + template + WML_ITEM bool ContOrientedBox(int iQuantity, const Vector3 *akPoint, + const bool *abValid, Box3 &rkBox); + + // Test for containment. Let X = C + y0*U0 + y1*U1 + y2*U2 where C is the + // box center and U0, U1, U2 are the orthonormal axes of the box. X is in + // the box if |y_i| <= E_i for all i where E_i are the extents of the box. + // If an epsilon e is supplied, the tests are |y_i| <= E_i + e. + template + WML_ITEM bool InBox(const Vector3 &rkPoint, const Box3 &rkBox, + Real fEpsilon = (Real)0.0); + + template + WML_ITEM Box3 MergeBoxes(const Box3 &rkBox0, + const Box3 &rkBox1); + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlContMinBox3.cpp b/src/editors/xrECore/WildMagic/WmlContMinBox3.cpp new file mode 100644 index 00000000000..6bf59ac32b1 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlContMinBox3.cpp @@ -0,0 +1,163 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlContMinBox3.h" +#include "WmlMatrix3.h" +#include "WmlMinimizeN.h" +using namespace Wml; + +//---------------------------------------------------------------------------- +template +MinBox3::MinBox3(int iQuantity, const Vector3 *akPoint, + Box3 &rkBox) +{ + m_iQuantity = iQuantity; + m_akPoint = akPoint; + + MinimizeN kMinimizer(3, Volume, 8, 8, 32, this); + + Real afA0[3] = + { + (Real)0.0, + (Real)0.0, + (Real)0.0}; + + Real afA1[3] = + { + Math::_PI, + Math::HALF_PI, + Math::_PI}; + + // compute some samples to narrow down the search region + Real fMinVolume = Math::MAX_REAL; + Real afAngle[3], afAInitial[3]; + const int iMax = 3; + const Real fInvMax = ((Real)1.0) / (Real)iMax; + for (int i0 = 0; i0 <= iMax; i0++) + { + afAngle[0] = afA0[0] + i0 * (afA1[0] - afA0[0]) * fInvMax; + for (int i1 = 0; i1 <= iMax; i1++) + { + afAngle[1] = afA0[1] + i1 * (afA1[1] - afA0[1]) * fInvMax; + for (int i2 = 0; i2 <= iMax; i2++) + { + afAngle[2] = afA0[2] + i2 * (afA1[2] - afA0[2]) * fInvMax; + Real fVolume = Volume(afAngle, this); + if (fVolume < fMinVolume) + { + fMinVolume = fVolume; + afAInitial[0] = afAngle[0]; + afAInitial[1] = afAngle[1]; + afAInitial[2] = afAngle[2]; + } + } + } + } + + Real afAMin[3], fVMin; + kMinimizer.GetMinimum(afA0, afA1, afAInitial, afAMin, fVMin); + + MinimalBoxForAngles(iQuantity, akPoint, afAMin, rkBox); +} +//---------------------------------------------------------------------------- +template +Real MinBox3::Volume(const Real *afAngle, void *pvData) +{ + MinBox3 &rkSelf = *(MinBox3 *)pvData; + + Real fCos0 = Math::Cos(afAngle[0]); + Real fSin0 = Math::Sin(afAngle[0]); + Real fCos1 = Math::Cos(afAngle[1]); + Real fSin1 = Math::Sin(afAngle[1]); + Vector3 kAxis(fCos0 * fSin1, fSin0 * fSin1, fCos1); + Matrix3 kRot(kAxis, afAngle[2]); + + Vector3 kMin = rkSelf.m_akPoint[0] * kRot, kMax = kMin; + for (int i = 1; i < rkSelf.m_iQuantity; i++) + { + Vector3 kTest = rkSelf.m_akPoint[i] * kRot; + + if (kTest.X() < kMin.X()) + kMin.X() = kTest.X(); + else if (kTest.X() > kMax.X()) + kMax.X() = kTest.X(); + + if (kTest.Y() < kMin.Y()) + kMin.Y() = kTest.Y(); + else if (kTest.Y() > kMax.Y()) + kMax.Y() = kTest.Y(); + + if (kTest.Z() < kMin.Z()) + kMin.Z() = kTest.Z(); + else if (kTest.Z() > kMax.Z()) + kMax.Z() = kTest.Z(); + } + + Real fVolume = (kMax.X() - kMin.X()) * (kMax.Y() - kMin.Y()) * + (kMax.Z() - kMin.Z()); + return fVolume; +} +//---------------------------------------------------------------------------- +template +void MinBox3::MinimalBoxForAngles(int iQuantity, + const Vector3 *akPoint, Real afAngle[3], Box3 &rkBox) +{ + Real fCos0 = Math::Cos(afAngle[0]); + Real fSin0 = Math::Sin(afAngle[0]); + Real fCos1 = Math::Cos(afAngle[1]); + Real fSin1 = Math::Sin(afAngle[1]); + Vector3 kAxis(fCos0 * fSin1, fSin0 * fSin1, fCos1); + Matrix3 kRot(kAxis, afAngle[2]); + + Vector3 kMin = akPoint[0] * kRot, kMax = kMin; + for (int i = 1; i < iQuantity; i++) + { + Vector3 kTest = akPoint[i] * kRot; + + if (kTest.X() < kMin.X()) + kMin.X() = kTest.X(); + else if (kTest.X() > kMax.X()) + kMax.X() = kTest.X(); + + if (kTest.Y() < kMin.Y()) + kMin.Y() = kTest.Y(); + else if (kTest.Y() > kMax.Y()) + kMax.Y() = kTest.Y(); + + if (kTest.Z() < kMin.Z()) + kMin.Z() = kTest.Z(); + else if (kTest.Z() > kMax.Z()) + kMax.Z() = kTest.Z(); + } + + Vector3 kMid = ((Real)0.5) * (kMax + kMin); + Vector3 kRng = ((Real)0.5) * (kMax - kMin); + + rkBox.Center() = kRot * kMid; + rkBox.Axis(0) = kRot.GetColumn(0); + rkBox.Axis(1) = kRot.GetColumn(1); + rkBox.Axis(2) = kRot.GetColumn(2); + rkBox.Extent(0) = kRng.X(); + rkBox.Extent(1) = kRng.Y(); + rkBox.Extent(2) = kRng.Z(); +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// explicit instantiation +//---------------------------------------------------------------------------- +namespace Wml +{ + template WML_ITEM class MinBox3; + template WML_ITEM class MinBox3; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlContMinBox3.h b/src/editors/xrECore/WildMagic/WmlContMinBox3.h new file mode 100644 index 00000000000..260a39fe130 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlContMinBox3.h @@ -0,0 +1,42 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLCONTMINBOX3H +#define WMLCONTMINBOX3H + +// Compute minimum volume oriented box containing the specified points. + +#include "WmlBox3.h" + +namespace Wml +{ + + template + class WML_ITEM MinBox3 + { + public: + MinBox3(int iQuantity, const Vector3 *akPoint, Box3 &kBox); + + private: + static Real Volume(const Real *afAngle, void *pvData); + + static void MinimalBoxForAngles(int iQuantity, + const Vector3 *akPoint, Real afAngle[3], Box3 &rkBox); + + int m_iQuantity; + const Vector3 *m_akPoint; + }; + + typedef MinBox3 MinBox3f; + typedef MinBox3 MinBox3d; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlEigen.cpp b/src/editors/xrECore/WildMagic/WmlEigen.cpp new file mode 100644 index 00000000000..f1e1c795717 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlEigen.cpp @@ -0,0 +1,895 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlEigen.h" +#include "WmlMath.h" +using namespace Wml; + +//---------------------------------------------------------------------------- +template +Eigen::Eigen(int iSize) + : m_kMat(iSize, iSize) +{ + assert(iSize >= 2); + m_iSize = iSize; + m_afDiag = new Real[m_iSize]; + m_afSubd = new Real[m_iSize]; + + // set according to the parity of the number of Householder reflections + m_bIsRotation = ((iSize % 2) == 0); +} +//---------------------------------------------------------------------------- +template +Eigen::Eigen(const Matrix2 &rkM) + : m_kMat(2, 2, (const Real *)rkM) +{ + m_iSize = 2; + m_afDiag = new Real[m_iSize]; + m_afSubd = new Real[m_iSize]; + + // set according to the parity of the number of Householder reflections + m_bIsRotation = true; +} +//---------------------------------------------------------------------------- +template +Eigen::Eigen(const Matrix3 &rkM) + : m_kMat(3, 3, (const Real *)rkM) +{ + m_iSize = 3; + m_afDiag = new Real[m_iSize]; + m_afSubd = new Real[m_iSize]; + + // set according to the parity of the number of Householder reflections + m_bIsRotation = false; +} +//---------------------------------------------------------------------------- +template +Eigen::Eigen(const Matrix4 &rkM) + : m_kMat(4, 4, (const Real *)rkM) +{ + m_iSize = 4; + m_afDiag = new Real[m_iSize]; + m_afSubd = new Real[m_iSize]; + + // set according to the parity of the number of Householder reflections + m_bIsRotation = true; +} +//---------------------------------------------------------------------------- +template +Eigen::Eigen(const GMatrix &rkM) + : m_kMat(rkM) +{ + m_iSize = rkM.GetRows(); + assert(m_iSize >= 2 && (rkM.GetColumns() == m_iSize)); + m_afDiag = new Real[m_iSize]; + m_afSubd = new Real[m_iSize]; + + // set according to the parity of the number of Householder reflections + m_bIsRotation = ((m_iSize % 2) == 0); +} +//---------------------------------------------------------------------------- +template +Eigen::~Eigen() +{ + delete[] m_afSubd; + delete[] m_afDiag; +} +//---------------------------------------------------------------------------- +template +Real &Eigen::operator()(int iRow, int iCol) +{ + return m_kMat[iRow][iCol]; +} +//---------------------------------------------------------------------------- +template +Eigen &Eigen::operator=(const Matrix2 &rkM) +{ + m_kMat.SetMatrix(2, 2, (const Real *)rkM); + m_iSize = 2; + delete[] m_afDiag; + delete[] m_afSubd; + m_afDiag = new Real[m_iSize]; + m_afSubd = new Real[m_iSize]; + + // set according to the parity of the number of Householder reflections + m_bIsRotation = true; + + return *this; +} +//---------------------------------------------------------------------------- +template +Eigen &Eigen::operator=(const Matrix3 &rkM) +{ + m_kMat.SetMatrix(3, 3, (const Real *)rkM); + m_iSize = 3; + delete[] m_afDiag; + delete[] m_afSubd; + m_afDiag = new Real[m_iSize]; + m_afSubd = new Real[m_iSize]; + + // set according to the parity of the number of Householder reflections + m_bIsRotation = false; + + return *this; +} +//---------------------------------------------------------------------------- +template +Eigen &Eigen::operator=(const Matrix4 &rkM) +{ + m_kMat.SetMatrix(4, 4, (const Real *)rkM); + m_iSize = 4; + delete[] m_afDiag; + delete[] m_afSubd; + m_afDiag = new Real[m_iSize]; + m_afSubd = new Real[m_iSize]; + + // set according to the parity of the number of Householder reflections + m_bIsRotation = true; + + return *this; +} +//---------------------------------------------------------------------------- +template +Eigen &Eigen::operator=(const GMatrix &rkM) +{ + m_kMat = rkM; + return *this; +} +//---------------------------------------------------------------------------- +template +Real Eigen::GetEigenvalue(int i) const +{ + return m_afDiag[i]; +} +//---------------------------------------------------------------------------- +template +const Real *Eigen::GetEigenvalues() const +{ + return m_afDiag; +} +//---------------------------------------------------------------------------- +template +void Eigen::GetEigenvector(int i, Vector2 &rkV) const +{ + assert(m_iSize == 2); + if (m_iSize == 2) + { + for (int iRow = 0; iRow < m_iSize; iRow++) + rkV[iRow] = m_kMat[iRow][i]; + } + else + { + rkV = Vector2::ZERO; + } +} +//---------------------------------------------------------------------------- +template +void Eigen::GetEigenvector(int i, Vector3 &rkV) const +{ + assert(m_iSize == 3); + if (m_iSize == 3) + { + for (int iRow = 0; iRow < m_iSize; iRow++) + rkV[iRow] = m_kMat[iRow][i]; + } + else + { + rkV = Vector3::ZERO; + } +} +//---------------------------------------------------------------------------- +template +void Eigen::GetEigenvector(int i, Vector4 &rkV) const +{ + assert(m_iSize == 4); + if (m_iSize == 4) + { + for (int iRow = 0; iRow < m_iSize; iRow++) + rkV[iRow] = m_kMat[iRow][i]; + } + else + { + rkV = Vector4::ZERO; + } +} +//---------------------------------------------------------------------------- +template +GVector Eigen::GetEigenvector(int i) const +{ + return m_kMat.GetColumn(i); +} +//---------------------------------------------------------------------------- +template +const GMatrix &Eigen::GetEigenvectors() const +{ + return m_kMat; +} +//---------------------------------------------------------------------------- +template +void Eigen::Tridiagonal2() +{ + // matrix is already tridiagonal + m_afDiag[0] = m_kMat[0][0]; + m_afDiag[1] = m_kMat[1][1]; + m_afSubd[0] = m_kMat[0][1]; + m_afSubd[1] = (Real)0.0; + m_kMat[0][0] = (Real)1.0; + m_kMat[0][1] = (Real)0.0; + m_kMat[1][0] = (Real)0.0; + m_kMat[1][1] = (Real)1.0; +} +//---------------------------------------------------------------------------- +template +void Eigen::Tridiagonal3() +{ + Real fM00 = m_kMat[0][0]; + Real fM01 = m_kMat[0][1]; + Real fM02 = m_kMat[0][2]; + Real fM11 = m_kMat[1][1]; + Real fM12 = m_kMat[1][2]; + Real fM22 = m_kMat[2][2]; + + m_afDiag[0] = fM00; + m_afSubd[2] = (Real)0.0; + if (fM02 != (Real)0.0) + { + Real fLength = Math::Sqrt(fM01 * fM01 + fM02 * fM02); + Real fInvLength = ((Real)1.0) / fLength; + fM01 *= fInvLength; + fM02 *= fInvLength; + Real fQ = ((Real)2.0) * fM01 * fM12 + fM02 * (fM22 - fM11); + m_afDiag[1] = fM11 + fM02 * fQ; + m_afDiag[2] = fM22 - fM02 * fQ; + m_afSubd[0] = fLength; + m_afSubd[1] = fM12 - fM01 * fQ; + m_kMat[0][0] = (Real)1.0; + m_kMat[0][1] = (Real)0.0; + m_kMat[0][2] = (Real)0.0; + m_kMat[1][0] = (Real)0.0; + m_kMat[1][1] = fM01; + m_kMat[1][2] = fM02; + m_kMat[2][0] = (Real)0.0; + m_kMat[2][1] = fM02; + m_kMat[2][2] = -fM01; + } + else + { + m_afDiag[1] = fM11; + m_afDiag[2] = fM22; + m_afSubd[0] = fM01; + m_afSubd[1] = fM12; + m_kMat[0][0] = (Real)1.0; + m_kMat[0][1] = (Real)0.0; + m_kMat[0][2] = (Real)0.0; + m_kMat[1][0] = (Real)0.0; + m_kMat[1][1] = (Real)1.0; + m_kMat[1][2] = (Real)0.0; + m_kMat[2][0] = (Real)0.0; + m_kMat[2][1] = (Real)0.0; + m_kMat[2][2] = (Real)1.0; + } +} +//---------------------------------------------------------------------------- +template +void Eigen::Tridiagonal4() +{ + // save matrix M + Real fM00 = m_kMat[0][0]; + Real fM01 = m_kMat[0][1]; + Real fM02 = m_kMat[0][2]; + Real fM03 = m_kMat[0][3]; + Real fM11 = m_kMat[1][1]; + Real fM12 = m_kMat[1][2]; + Real fM13 = m_kMat[1][3]; + Real fM22 = m_kMat[2][2]; + Real fM23 = m_kMat[2][3]; + Real fM33 = m_kMat[3][3]; + + m_afDiag[0] = fM00; + m_afSubd[3] = (Real)0.0; + + m_kMat[0][0] = (Real)1.0; + m_kMat[0][1] = (Real)0.0; + m_kMat[0][2] = (Real)0.0; + m_kMat[0][3] = (Real)0.0; + m_kMat[1][0] = (Real)0.0; + m_kMat[2][0] = (Real)0.0; + m_kMat[3][0] = (Real)0.0; + + Real fLength, fInvLength; + + if (fM02 != (Real)0.0 || fM03 != (Real)0.0) + { + Real fQ11, fQ12, fQ13; + Real fQ21, fQ22, fQ23; + Real fQ31, fQ32, fQ33; + + // build column Q1 + fLength = Math::Sqrt(fM01 * fM01 + fM02 * fM02 + fM03 * fM03); + fInvLength = ((Real)1.0) / fLength; + fQ11 = fM01 * fInvLength; + fQ21 = fM02 * fInvLength; + fQ31 = fM03 * fInvLength; + + m_afSubd[0] = fLength; + + // compute S*Q1 + Real fV0 = fM11 * fQ11 + fM12 * fQ21 + fM13 * fQ31; + Real fV1 = fM12 * fQ11 + fM22 * fQ21 + fM23 * fQ31; + Real fV2 = fM13 * fQ11 + fM23 * fQ21 + fM33 * fQ31; + + m_afDiag[1] = fQ11 * fV0 + fQ21 * fV1 + fQ31 * fV2; + + // build column Q3 = Q1x(S*Q1) + fQ13 = fQ21 * fV2 - fQ31 * fV1; + fQ23 = fQ31 * fV0 - fQ11 * fV2; + fQ33 = fQ11 * fV1 - fQ21 * fV0; + fLength = Math::Sqrt(fQ13 * fQ13 + fQ23 * fQ23 + fQ33 * fQ33); + if (fLength > (Real)0.0) + { + fInvLength = ((Real)1.0) / fLength; + fQ13 *= fInvLength; + fQ23 *= fInvLength; + fQ33 *= fInvLength; + + // build column Q2 = Q3xQ1 + fQ12 = fQ23 * fQ31 - fQ33 * fQ21; + fQ22 = fQ33 * fQ11 - fQ13 * fQ31; + fQ32 = fQ13 * fQ21 - fQ23 * fQ11; + + fV0 = fQ12 * fM11 + fQ22 * fM12 + fQ32 * fM13; + fV1 = fQ12 * fM12 + fQ22 * fM22 + fQ32 * fM23; + fV2 = fQ12 * fM13 + fQ22 * fM23 + fQ32 * fM33; + m_afSubd[1] = fQ11 * fV0 + fQ21 * fV1 + fQ31 * fV2; + m_afDiag[2] = fQ12 * fV0 + fQ22 * fV1 + fQ32 * fV2; + m_afSubd[2] = fQ13 * fV0 + fQ23 * fV1 + fQ33 * fV2; + + fV0 = fQ13 * fM11 + fQ23 * fM12 + fQ33 * fM13; + fV1 = fQ13 * fM12 + fQ23 * fM22 + fQ33 * fM23; + fV2 = fQ13 * fM13 + fQ23 * fM23 + fQ33 * fM33; + m_afDiag[3] = fQ13 * fV0 + fQ23 * fV1 + fQ33 * fV2; + } + else + { + // S*Q1 parallel to Q1, choose any valid Q2 and Q3 + m_afSubd[1] = (Real)0.0; + + fLength = fQ21 * fQ21 + fQ31 * fQ31; + if (fLength > (Real)0.0) + { + fInvLength = ((Real)1.0) / fLength; + Real fTmp = fQ11 - (Real)1.0; + fQ12 = -fQ21; + fQ22 = ((Real)1.0) + fTmp * fQ21 * fQ21 * fInvLength; + fQ32 = fTmp * fQ21 * fQ31 * fInvLength; + + fQ13 = -fQ31; + fQ23 = fQ32; + fQ33 = ((Real)1.0) + fTmp * fQ31 * fQ31 * fInvLength; + + fV0 = fQ12 * fM11 + fQ22 * fM12 + fQ32 * fM13; + fV1 = fQ12 * fM12 + fQ22 * fM22 + fQ32 * fM23; + fV2 = fQ12 * fM13 + fQ22 * fM23 + fQ32 * fM33; + m_afDiag[2] = fQ12 * fV0 + fQ22 * fV1 + fQ32 * fV2; + m_afSubd[2] = fQ13 * fV0 + fQ23 * fV1 + fQ33 * fV2; + + fV0 = fQ13 * fM11 + fQ23 * fM12 + fQ33 * fM13; + fV1 = fQ13 * fM12 + fQ23 * fM22 + fQ33 * fM23; + fV2 = fQ13 * fM13 + fQ23 * fM23 + fQ33 * fM33; + m_afDiag[3] = fQ13 * fV0 + fQ23 * fV1 + fQ33 * fV2; + } + else + { + // Q1 = (+-1,0,0) + fQ12 = (Real)0.0; + fQ22 = (Real)1.0; + fQ32 = (Real)0.0; + fQ13 = (Real)0.0; + fQ23 = (Real)0.0; + fQ33 = (Real)1.0; + + m_afDiag[2] = fM22; + m_afDiag[3] = fM33; + m_afSubd[2] = fM23; + } + } + + m_kMat[1][1] = fQ11; + m_kMat[1][2] = fQ12; + m_kMat[1][3] = fQ13; + m_kMat[2][1] = fQ21; + m_kMat[2][2] = fQ22; + m_kMat[2][3] = fQ23; + m_kMat[3][1] = fQ31; + m_kMat[3][2] = fQ32; + m_kMat[3][3] = fQ33; + } + else + { + m_afDiag[1] = fM11; + m_afSubd[0] = fM01; + m_kMat[1][1] = (Real)1.0; + m_kMat[2][1] = (Real)0.0; + m_kMat[3][1] = (Real)0.0; + + if (fM13 != (Real)0.0) + { + fLength = Math::Sqrt(fM12 * fM12 + fM13 * fM13); + fInvLength = ((Real)1.0) / fLength; + fM12 *= fInvLength; + fM13 *= fInvLength; + Real fQ = ((Real)2.0) * fM12 * fM23 + fM13 * (fM33 - fM22); + + m_afDiag[2] = fM22 + fM13 * fQ; + m_afDiag[3] = fM33 - fM13 * fQ; + m_afSubd[1] = fLength; + m_afSubd[2] = fM23 - fM12 * fQ; + m_kMat[1][2] = (Real)0.0; + m_kMat[1][3] = (Real)0.0; + m_kMat[2][2] = fM12; + m_kMat[2][3] = fM13; + m_kMat[3][2] = fM13; + m_kMat[3][3] = -fM12; + } + else + { + m_afDiag[2] = fM22; + m_afDiag[3] = fM33; + m_afSubd[1] = fM12; + m_afSubd[2] = fM23; + m_kMat[1][2] = (Real)0.0; + m_kMat[1][3] = (Real)0.0; + m_kMat[2][2] = (Real)1.0; + m_kMat[2][3] = (Real)0.0; + m_kMat[3][2] = (Real)0.0; + m_kMat[3][3] = (Real)1.0; + } + } +} +//---------------------------------------------------------------------------- +template +void Eigen::TridiagonalN() +{ + int i0, i1, i2, i3; + + for (i0 = m_iSize - 1, i3 = m_iSize - 2; i0 >= 1; i0--, i3--) + { + Real fH = (Real)0.0, fScale = (Real)0.0; + + if (i3 > 0) + { + for (i2 = 0; i2 <= i3; i2++) + fScale += Math::FAbs(m_kMat[i0][i2]); + if (fScale == (Real)0.0) + { + m_afSubd[i0] = m_kMat[i0][i3]; + } + else + { + Real fInvScale = ((Real)1.0) / fScale; + for (i2 = 0; i2 <= i3; i2++) + { + m_kMat[i0][i2] *= fInvScale; + fH += m_kMat[i0][i2] * m_kMat[i0][i2]; + } + Real fF = m_kMat[i0][i3]; + Real fG = Math::Sqrt(fH); + if (fF > (Real)0.0) + fG = -fG; + m_afSubd[i0] = fScale * fG; + fH -= fF * fG; + m_kMat[i0][i3] = fF - fG; + fF = (Real)0.0; + Real fInvH = ((Real)1.0) / fH; + for (i1 = 0; i1 <= i3; i1++) + { + m_kMat[i1][i0] = m_kMat[i0][i1] * fInvH; + fG = (Real)0.0; + for (i2 = 0; i2 <= i1; i2++) + fG += m_kMat[i1][i2] * m_kMat[i0][i2]; + for (i2 = i1 + 1; i2 <= i3; i2++) + fG += m_kMat[i2][i1] * m_kMat[i0][i2]; + m_afSubd[i1] = fG * fInvH; + fF += m_afSubd[i1] * m_kMat[i0][i1]; + } + Real fHalfFdivH = ((Real)0.5) * fF * fInvH; + for (i1 = 0; i1 <= i3; i1++) + { + fF = m_kMat[i0][i1]; + fG = m_afSubd[i1] - fHalfFdivH * fF; + m_afSubd[i1] = fG; + for (i2 = 0; i2 <= i1; i2++) + { + m_kMat[i1][i2] -= fF * m_afSubd[i2] + + fG * m_kMat[i0][i2]; + } + } + } + } + else + { + m_afSubd[i0] = m_kMat[i0][i3]; + } + + m_afDiag[i0] = fH; + } + + m_afDiag[0] = (Real)0.0; + m_afSubd[0] = (Real)0.0; + for (i0 = 0, i3 = -1; i0 <= m_iSize - 1; i0++, i3++) + { + if (m_afDiag[i0] != (Real)0.0) + { + for (i1 = 0; i1 <= i3; i1++) + { + Real fSum = (Real)0.0; + for (i2 = 0; i2 <= i3; i2++) + fSum += m_kMat[i0][i2] * m_kMat[i2][i1]; + for (i2 = 0; i2 <= i3; i2++) + m_kMat[i2][i1] -= fSum * m_kMat[i2][i0]; + } + } + m_afDiag[i0] = m_kMat[i0][i0]; + m_kMat[i0][i0] = (Real)1.0; + for (i1 = 0; i1 <= i3; i1++) + { + m_kMat[i1][i0] = (Real)0.0; + m_kMat[i0][i1] = (Real)0.0; + } + } + + // re-ordering if Eigen::QLAlgorithm is used subsequently + for (i0 = 1, i3 = 0; i0 < m_iSize; i0++, i3++) + m_afSubd[i3] = m_afSubd[i0]; + m_afSubd[m_iSize - 1] = (Real)0.0; +} +//---------------------------------------------------------------------------- +template +bool Eigen::QLAlgorithm() +{ + const int iMaxIter = 32; + + for (int i0 = 0; i0 < m_iSize; i0++) + { + int i1; + for (i1 = 0; i1 < iMaxIter; i1++) + { + int i2; + for (i2 = i0; i2 <= m_iSize - 2; i2++) + { + Real fTmp = Math::FAbs(m_afDiag[i2]) + + Math::FAbs(m_afDiag[i2 + 1]); + if (Math::FAbs(m_afSubd[i2]) + fTmp == fTmp) + break; + } + if (i2 == i0) + break; + + Real fG = (m_afDiag[i0 + 1] - m_afDiag[i0]) / (((Real)2.0) * + m_afSubd[i0]); + Real fR = Math::Sqrt(fG * fG + (Real)1.0); + if (fG < (Real)0.0) + fG = m_afDiag[i2] - m_afDiag[i0] + m_afSubd[i0] / (fG - fR); + else + fG = m_afDiag[i2] - m_afDiag[i0] + m_afSubd[i0] / (fG + fR); + Real fSin = (Real)1.0, fCos = (Real)1.0, fP = (Real)0.0; + for (int i3 = i2 - 1; i3 >= i0; i3--) + { + Real fF = fSin * m_afSubd[i3]; + Real fB = fCos * m_afSubd[i3]; + if (Math::FAbs(fF) >= Math::FAbs(fG)) + { + fCos = fG / fF; + fR = Math::Sqrt(fCos * fCos + (Real)1.0); + m_afSubd[i3 + 1] = fF * fR; + fSin = ((Real)1.0) / fR; + fCos *= fSin; + } + else + { + fSin = fF / fG; + fR = Math::Sqrt(fSin * fSin + (Real)1.0); + m_afSubd[i3 + 1] = fG * fR; + fCos = ((Real)1.0) / fR; + fSin *= fCos; + } + fG = m_afDiag[i3 + 1] - fP; + fR = (m_afDiag[i3] - fG) * fSin + ((Real)2.0) * fB * fCos; + fP = fSin * fR; + m_afDiag[i3 + 1] = fG + fP; + fG = fCos * fR - fB; + + for (int i4 = 0; i4 < m_iSize; i4++) + { + fF = m_kMat[i4][i3 + 1]; + m_kMat[i4][i3 + 1] = fSin * m_kMat[i4][i3] + fCos * fF; + m_kMat[i4][i3] = fCos * m_kMat[i4][i3] - fSin * fF; + } + } + m_afDiag[i0] -= fP; + m_afSubd[i0] = fG; + m_afSubd[i2] = (Real)0.0; + } + if (i1 == iMaxIter) + return false; + } + + return true; +} +//---------------------------------------------------------------------------- +template +void Eigen::DecreasingSort() +{ + // sort eigenvalues in decreasing order, e[0] >= ... >= e[iSize-1] + for (int i0 = 0, i1; i0 <= m_iSize - 2; i0++) + { + // locate maximum eigenvalue + i1 = i0; + Real fMax = m_afDiag[i1]; + int i2; + for (i2 = i0 + 1; i2 < m_iSize; i2++) + { + if (m_afDiag[i2] > fMax) + { + i1 = i2; + fMax = m_afDiag[i1]; + } + } + + if (i1 != i0) + { + // swap eigenvalues + m_afDiag[i1] = m_afDiag[i0]; + m_afDiag[i0] = fMax; + + // swap eigenvectors + for (i2 = 0; i2 < m_iSize; i2++) + { + Real fTmp = m_kMat[i2][i0]; + m_kMat[i2][i0] = m_kMat[i2][i1]; + m_kMat[i2][i1] = fTmp; + m_bIsRotation = !m_bIsRotation; + } + } + } +} +//---------------------------------------------------------------------------- +template +void Eigen::IncreasingSort() +{ + // sort eigenvalues in increasing order, e[0] <= ... <= e[iSize-1] + for (int i0 = 0, i1; i0 <= m_iSize - 2; i0++) + { + // locate minimum eigenvalue + i1 = i0; + Real fMin = m_afDiag[i1]; + int i2; + for (i2 = i0 + 1; i2 < m_iSize; i2++) + { + if (m_afDiag[i2] < fMin) + { + i1 = i2; + fMin = m_afDiag[i1]; + } + } + + if (i1 != i0) + { + // swap eigenvalues + m_afDiag[i1] = m_afDiag[i0]; + m_afDiag[i0] = fMin; + + // swap eigenvectors + for (i2 = 0; i2 < m_iSize; i2++) + { + Real fTmp = m_kMat[i2][i0]; + m_kMat[i2][i0] = m_kMat[i2][i1]; + m_kMat[i2][i1] = fTmp; + m_bIsRotation = !m_bIsRotation; + } + } + } +} +//---------------------------------------------------------------------------- +template +void Eigen::GuaranteeRotation() +{ + if (!m_bIsRotation) + { + // change sign on the first column + for (int iRow = 0; iRow < m_iSize; iRow++) + m_kMat[iRow][0] = -m_kMat[iRow][0]; + } +} +//---------------------------------------------------------------------------- +template +void Eigen::EigenStuff2() +{ + Tridiagonal2(); + QLAlgorithm(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::EigenStuff3() +{ + Tridiagonal3(); + QLAlgorithm(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::EigenStuff4() +{ + Tridiagonal4(); + QLAlgorithm(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::EigenStuffN() +{ + TridiagonalN(); + QLAlgorithm(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::EigenStuff() +{ + switch (m_iSize) + { + case 2: + Tridiagonal2(); + break; + case 3: + Tridiagonal3(); + break; + case 4: + Tridiagonal4(); + break; + default: + TridiagonalN(); + break; + } + QLAlgorithm(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::DecrSortEigenStuff2() +{ + Tridiagonal2(); + QLAlgorithm(); + DecreasingSort(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::DecrSortEigenStuff3() +{ + Tridiagonal3(); + QLAlgorithm(); + DecreasingSort(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::DecrSortEigenStuff4() +{ + Tridiagonal4(); + QLAlgorithm(); + DecreasingSort(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::DecrSortEigenStuffN() +{ + TridiagonalN(); + QLAlgorithm(); + DecreasingSort(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::DecrSortEigenStuff() +{ + switch (m_iSize) + { + case 2: + Tridiagonal2(); + break; + case 3: + Tridiagonal3(); + break; + case 4: + Tridiagonal4(); + break; + default: + TridiagonalN(); + break; + } + QLAlgorithm(); + DecreasingSort(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::IncrSortEigenStuff2() +{ + Tridiagonal2(); + QLAlgorithm(); + IncreasingSort(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::IncrSortEigenStuff3() +{ + Tridiagonal3(); + QLAlgorithm(); + IncreasingSort(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::IncrSortEigenStuff4() +{ + Tridiagonal4(); + QLAlgorithm(); + IncreasingSort(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::IncrSortEigenStuffN() +{ + TridiagonalN(); + QLAlgorithm(); + IncreasingSort(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- +template +void Eigen::IncrSortEigenStuff() +{ + switch (m_iSize) + { + case 2: + Tridiagonal2(); + break; + case 3: + Tridiagonal3(); + break; + case 4: + Tridiagonal4(); + break; + default: + TridiagonalN(); + break; + } + QLAlgorithm(); + IncreasingSort(); + GuaranteeRotation(); +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// explicit instantiation +//---------------------------------------------------------------------------- +namespace Wml +{ + template class WML_ITEM Eigen; + template class WML_ITEM Eigen; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlEigen.h b/src/editors/xrECore/WildMagic/WmlEigen.h new file mode 100644 index 00000000000..42a55cfc867 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlEigen.h @@ -0,0 +1,116 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLEIGENH +#define WMLEIGENH + +#include "WmlMatrix2.h" +#include "WmlMatrix3.h" +#include "WmlMatrix4.h" +#include "WmlGMatrix.h" + +namespace Wml +{ + + template + class WML_ITEM Eigen + { + public: + Eigen(int iSize); + Eigen(const Matrix2 &rkM); + Eigen(const Matrix3 &rkM); + Eigen(const Matrix4 &rkM); + Eigen(const GMatrix &rkM); + ~Eigen(); + + // set the matrix for eigensolving + Real &operator()(int iRow, int iCol); + Eigen &operator=(const Matrix2 &rkM); + Eigen &operator=(const Matrix3 &rkM); + Eigen &operator=(const Matrix4 &rkM); + Eigen &operator=(const GMatrix &rkM); + + // Get the eigenresults (eigenvectors are columns of eigenmatrix). The + // GetEigenvector calls involving Vector2, Vector3, and Vector4 should + // only be called if you know that the eigenmatrix is of the appropriate + // size. + Real GetEigenvalue(int i) const; + const Real *GetEigenvalues() const; + void GetEigenvector(int i, Vector2 &rkV) const; + void GetEigenvector(int i, Vector3 &rkV) const; + void GetEigenvector(int i, Vector4 &rkV) const; + GVector GetEigenvector(int i) const; + const GMatrix &GetEigenvectors() const; + + // solve eigensystem + void EigenStuff2(); + void EigenStuff3(); + void EigenStuff4(); + void EigenStuffN(); + void EigenStuff(); + + // solve eigensystem, use decreasing sort on eigenvalues + void DecrSortEigenStuff2(); + void DecrSortEigenStuff3(); + void DecrSortEigenStuff4(); + void DecrSortEigenStuffN(); + void DecrSortEigenStuff(); + + // solve eigensystem, use increasing sort on eigenvalues + void IncrSortEigenStuff2(); + void IncrSortEigenStuff3(); + void IncrSortEigenStuff4(); + void IncrSortEigenStuffN(); + void IncrSortEigenStuff(); + + protected: + int m_iSize; + GMatrix m_kMat; + Real *m_afDiag; + Real *m_afSubd; + + // For odd size matrices, the Householder reduction involves an odd + // number of reflections. The product of these is a reflection. The + // QL algorithm uses rotations for further reductions. The final + // orthogonal matrix whose columns are the eigenvectors is a reflection, + // so its determinant is -1. For even size matrices, the Householder + // reduction involves an even number of reflections whose product is a + // rotation. The final orthogonal matrix has determinant +1. Many + // algorithms that need an eigendecomposition want a rotation matrix. + // We want to guarantee this is the case, so m_bRotation keeps track of + // this. The DecrSort and IncrSort further complicate the issue since + // they swap columns of the orthogonal matrix, causing the matrix to + // toggle between rotation and reflection. The value m_bRotation must + // be toggled accordingly. + bool m_bIsRotation; + void GuaranteeRotation(); + + // Householder reduction to tridiagonal form + void Tridiagonal2(); + void Tridiagonal3(); + void Tridiagonal4(); + void TridiagonalN(); + + // QL algorithm with implicit shifting, applies to tridiagonal matrices + bool QLAlgorithm(); + + // sort eigenvalues from largest to smallest + void DecreasingSort(); + + // sort eigenvalues from smallest to largest + void IncreasingSort(); + }; + + typedef Eigen Eigenf; + typedef Eigen Eigend; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlGMatrix.h b/src/editors/xrECore/WildMagic/WmlGMatrix.h new file mode 100644 index 00000000000..41c9ed84fe7 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlGMatrix.h @@ -0,0 +1,135 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLGMATRIX_H +#define WMLGMATRIX_H + +// Matrix operations are applied on the left. For example, given a matrix M +// and a vector V, matrix-times-vector is M*V. That is, V is treated as a +// column vector. Some graphics APIs use V*M where V is treated as a row +// vector. In this context the "M" matrix is really a transpose of the M as +// represented in Wild Magic. Similarly, to apply two matrix operations M0 +// and M1, in that order, you compute M1*M0 so that the transform of a vector +// is (M1*M0)*V = M1*(M0*V). Some graphics APIs use M0*M1, but again these +// matrices are the transpose of those as represented in Wild Magic. You +// must therefore be careful about how you interface the transformation code +// with graphics APIS. +// +// Matrices are stored in row-major order, matrix[row][col]. + +#include "WmlGVector.h" + +namespace Wml +{ + + template + class GMatrix + { + public: + // construction and destruction + GMatrix(int iRows = 0, int iCols = 0); + GMatrix(int iRows, int iCols, const Real *afData); + GMatrix(int iRows, int iCols, const Real **aafEntry); + GMatrix(const GMatrix &rkM); + ~GMatrix(); + + // member access + void SetSize(int iRows, int iCols); + void GetSize(int &riRows, int &riCols) const; + int GetRows() const; + int GetColumns() const; + int GetQuantity() const; + operator const Real *() const; + operator Real *(); + const Real *operator[](int iRow) const; + Real *operator[](int iRow); + void SwapRows(int iRow0, int iRow1); + Real operator()(int iRow, int iCol) const; + Real &operator()(int iRow, int iCol); + void SetRow(int iRow, const GVector &rkV); + GVector GetRow(int iRow) const; + void SetColumn(int iCol, const GVector &rkV); + GVector GetColumn(int iCol) const; + void SetMatrix(int iRows, int iCols, const Real *afEntry); + void SetMatrix(int iRows, int iCols, const Real **aafMatrix); + void GetColumnMajor(Real *afCMajor) const; + + // assignment + GMatrix &operator=(const GMatrix &rkM); + + // comparison + bool operator==(const GMatrix &rkM) const; + bool operator!=(const GMatrix &rkM) const; + bool operator<(const GMatrix &rkM) const; + bool operator<=(const GMatrix &rkM) const; + bool operator>(const GMatrix &rkM) const; + bool operator>=(const GMatrix &rkM) const; + + // arithmetic operations + GMatrix operator+(const GMatrix &rkM) const; + GMatrix operator-(const GMatrix &rkM) const; + GMatrix operator*(const GMatrix &rkM) const; + GMatrix operator*(Real fScalar) const; + GMatrix operator/(Real fScalar) const; + GMatrix operator-() const; + + // arithmetic updates + GMatrix &operator+=(const GMatrix &rkM); + GMatrix &operator-=(const GMatrix &rkM); + GMatrix &operator*=(Real fScalar); + GMatrix &operator/=(Real fScalar); + + // matrix products + GMatrix Transpose() const; // M^T + GMatrix TransposeTimes(const GMatrix &rkM) const; // this^T * M + GMatrix TimesTranspose(const GMatrix &rkM) const; // this * M^T + + // matrix-vector operations + GVector operator*(const GVector &rkV) const; // M * v + Real QForm(const GVector &rkU, const GVector &rkV) + const; // u^T*M*v + + protected: + // Support for allocation and deallocation. The allocation call requires + // m_iRows, m_iCols, and m_iQuantity to have already been correctly + // initialized. + void Allocate(bool bSetToZero); + void Deallocate(); + + // support for comparisons + int CompareArrays(const GMatrix &rkM) const; + + int m_iRows, m_iCols, m_iQuantity; + + // the matrix is stored in row-major form as a 1-dimensional array + Real *m_afData; + + // An array of pointers to the rows of the matrix. The separation of + // row pointers and actual data supports swapping of rows in linear + // algebraic algorithms such as solving linear systems of equations. + Real **m_aafEntry; + }; + + // c * M + template + GMatrix operator*(Real fScalar, const GMatrix &rkM); + + // v^T * M + template + GVector operator*(const GVector &rkV, const GMatrix &rkM); + +#include "WmlGMatrix.inl" + + typedef GMatrix GMatrixf; + typedef GMatrix GMatrixd; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlGMatrix.inl b/src/editors/xrECore/WildMagic/WmlGMatrix.inl new file mode 100644 index 00000000000..253a9b964b8 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlGMatrix.inl @@ -0,0 +1,554 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +GMatrix::GMatrix(int iRows, int iCols) +{ + m_afData = 0; + m_aafEntry = 0; + SetSize(iRows, iCols); +} +//---------------------------------------------------------------------------- +template +GMatrix::GMatrix(int iRows, int iCols, const Real *afEntry) +{ + m_afData = 0; + m_aafEntry = 0; + SetMatrix(iRows, iCols, afEntry); +} +//---------------------------------------------------------------------------- +template +GMatrix::GMatrix(int iRows, int iCols, const Real **aafMatrix) +{ + m_afData = 0; + m_aafEntry = 0; + SetMatrix(iRows, iCols, aafMatrix); +} +//---------------------------------------------------------------------------- +template +GMatrix::GMatrix(const GMatrix &rkM) +{ + m_iRows = 0; + m_iCols = 0; + m_iQuantity = 0; + m_afData = 0; + m_aafEntry = 0; + *this = rkM; +} +//---------------------------------------------------------------------------- +template +GMatrix::~GMatrix() +{ + Deallocate(); +} +//---------------------------------------------------------------------------- +template +void GMatrix::Allocate(bool bSetToZero) +{ + // assert: m_iRows, m_iCols, and m_iQuantity already initialized + + m_afData = new Real[m_iQuantity]; + if (bSetToZero) + memset(m_afData, 0, m_iQuantity * sizeof(Real)); + + m_aafEntry = new Real *[m_iRows]; + for (int iRow = 0; iRow < m_iRows; iRow++) + m_aafEntry[iRow] = &m_afData[iRow * m_iCols]; +} +//---------------------------------------------------------------------------- +template +void GMatrix::Deallocate() +{ + delete[] m_afData; + delete[] m_aafEntry; +} +//---------------------------------------------------------------------------- +template +void GMatrix::SetSize(int iRows, int iCols) +{ + Deallocate(); + if (iRows > 0 && iCols > 0) + { + m_iRows = iRows; + m_iCols = iCols; + m_iQuantity = m_iRows * m_iCols; + Allocate(true); + } + else + { + m_iRows = 0; + m_iCols = 0; + m_iQuantity = 0; + m_afData = 0; + m_aafEntry = 0; + } +} +//---------------------------------------------------------------------------- +template +void GMatrix::GetSize(int &riRows, int &riCols) const +{ + riRows = m_iRows; + riCols = m_iCols; +} +//---------------------------------------------------------------------------- +template +int GMatrix::GetRows() const +{ + return m_iRows; +} +//---------------------------------------------------------------------------- +template +int GMatrix::GetColumns() const +{ + return m_iCols; +} +//---------------------------------------------------------------------------- +template +int GMatrix::GetQuantity() const +{ + return m_iQuantity; +} +//---------------------------------------------------------------------------- +template +GMatrix::operator const Real *() const +{ + return m_afData; +} +//---------------------------------------------------------------------------- +template +GMatrix::operator Real *() +{ + return m_afData; +} +//---------------------------------------------------------------------------- +template +const Real *GMatrix::operator[](int iRow) const +{ + assert(0 <= iRow && iRow < m_iRows); + return m_aafEntry[iRow]; +} +//---------------------------------------------------------------------------- +template +Real *GMatrix::operator[](int iRow) +{ + assert(0 <= iRow && iRow < m_iRows); + return m_aafEntry[iRow]; +} +//---------------------------------------------------------------------------- +template +void GMatrix::SwapRows(int iRow0, int iRow1) +{ + assert(0 <= iRow0 && iRow0 < m_iRows && 0 <= iRow1 && iRow1 < m_iRows); + Real *afSave = m_aafEntry[iRow0]; + m_aafEntry[iRow0] = m_aafEntry[iRow1]; + m_aafEntry[iRow1] = afSave; +} +//---------------------------------------------------------------------------- +template +Real GMatrix::operator()(int iRow, int iCol) const +{ + return m_aafEntry[iRow][iCol]; +} +//---------------------------------------------------------------------------- +template +Real &GMatrix::operator()(int iRow, int iCol) +{ + assert(0 <= iRow && iRow < m_iRows && 0 <= iCol && iCol <= m_iCols); + return m_aafEntry[iRow][iCol]; +} +//---------------------------------------------------------------------------- +template +void GMatrix::SetRow(int iRow, const GVector &rkV) +{ + assert((0 <= iRow && iRow < m_iRows) && (rkV.GetSize() == m_iCols)); + for (int iCol = 0; iCol < m_iCols; iCol++) + m_aafEntry[iRow][iCol] = rkV[iCol]; +} +//---------------------------------------------------------------------------- +template +GVector GMatrix::GetRow(int iRow) const +{ + assert(0 <= iRow && iRow < m_iRows); + GVector kV(m_iCols); + for (int iCol = 0; iCol < m_iCols; iCol++) + kV[iCol] = m_aafEntry[iRow][iCol]; + return kV; +} +//---------------------------------------------------------------------------- +template +void GMatrix::SetColumn(int iCol, const GVector &rkV) +{ + assert((0 <= iCol && iCol < m_iCols) && (rkV.GetSize() == m_iRows)); + for (int iRow = 0; iRow < m_iRows; iRow++) + m_aafEntry[iRow][iCol] = rkV[iRow]; +} +//---------------------------------------------------------------------------- +template +GVector GMatrix::GetColumn(int iCol) const +{ + assert(0 <= iCol && iCol < m_iCols); + GVector kV(m_iRows); + for (int iRow = 0; iRow < m_iRows; iRow++) + kV[iRow] = m_aafEntry[iRow][iCol]; + return kV; +} +//---------------------------------------------------------------------------- +template +void GMatrix::SetMatrix(int iRows, int iCols, const Real *afData) +{ + Deallocate(); + if (iRows > 0 && iCols > 0) + { + m_iRows = iRows; + m_iCols = iCols; + m_iQuantity = m_iRows * m_iCols; + Allocate(false); + memcpy(m_afData, afData, m_iQuantity * sizeof(Real)); + } + else + { + m_iRows = 0; + m_iCols = 0; + m_iQuantity = 0; + m_afData = 0; + m_aafEntry = 0; + } +} +//---------------------------------------------------------------------------- +template +void GMatrix::SetMatrix(int iRows, int iCols, const Real **aafEntry) +{ + Deallocate(); + if (iRows > 0 && iCols > 0) + { + m_iRows = iRows; + m_iCols = iCols; + m_iQuantity = m_iRows * m_iCols; + Allocate(false); + for (int iRow = 0; iRow < m_iRows; iRow++) + { + for (int iCol = 0; iCol < m_iCols; iCol++) + m_aafEntry[iRow][iCol] = aafEntry[iRow][iCol]; + } + } + else + { + m_iRows = 0; + m_iCols = 0; + m_iQuantity = 0; + m_afData = 0; + m_aafEntry = 0; + } +} +//---------------------------------------------------------------------------- +template +void GMatrix::GetColumnMajor(Real *afCMajor) const +{ + for (int iRow = 0, i = 0; iRow < m_iRows; iRow++) + { + for (int iCol = 0; iCol < m_iCols; iCol++) + afCMajor[i++] = m_aafEntry[iCol][iRow]; + } +} +//---------------------------------------------------------------------------- +template +GMatrix &GMatrix::operator=(const GMatrix &rkM) +{ + if (rkM.m_iQuantity > 0) + { + if (m_iRows != rkM.m_iRows || m_iCols != rkM.m_iCols) + { + Deallocate(); + m_iRows = rkM.m_iRows; + m_iCols = rkM.m_iCols; + m_iQuantity = rkM.m_iQuantity; + Allocate(false); + } + for (int iRow = 0; iRow < m_iRows; iRow++) + { + for (int iCol = 0; iCol < m_iCols; iCol++) + m_aafEntry[iRow][iCol] = rkM.m_aafEntry[iRow][iCol]; + } + } + else + { + Deallocate(); + m_iRows = 0; + m_iCols = 0; + m_iQuantity = 0; + m_afData = 0; + m_aafEntry = 0; + } + return *this; +} +//---------------------------------------------------------------------------- +template +bool GMatrix::operator==(const GMatrix &rkM) const +{ + return memcmp(m_afData, rkM.m_afData, m_iQuantity * sizeof(Real)) == 0; +} +//---------------------------------------------------------------------------- +template +bool GMatrix::operator!=(const GMatrix &rkM) const +{ + return memcmp(m_afData, rkM.m_afData, m_iQuantity * sizeof(Real)) != 0; +} +//---------------------------------------------------------------------------- +template +int GMatrix::CompareArrays(const GMatrix &rkM) const +{ + return memcmp(m_afData, rkM.m_afData, m_iQuantity * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +bool GMatrix::operator<(const GMatrix &rkM) const +{ + return CompareArrays(rkM) < 0; +} +//---------------------------------------------------------------------------- +template +bool GMatrix::operator<=(const GMatrix &rkM) const +{ + return CompareArrays(rkM) <= 0; +} +//---------------------------------------------------------------------------- +template +bool GMatrix::operator>(const GMatrix &rkM) const +{ + return CompareArrays(rkM) > 0; +} +//---------------------------------------------------------------------------- +template +bool GMatrix::operator>=(const GMatrix &rkM) const +{ + return CompareArrays(rkM) >= 0; +} +//---------------------------------------------------------------------------- +template +GMatrix GMatrix::operator+(const GMatrix &rkM) const +{ + GMatrix kSum(rkM.m_iRows, rkM.m_iCols); + for (int i = 0; i < m_iQuantity; i++) + kSum.m_afData[i] = m_afData[i] + rkM.m_afData[i]; + return kSum; +} +//---------------------------------------------------------------------------- +template +GMatrix GMatrix::operator-(const GMatrix &rkM) const +{ + GMatrix kDiff(rkM.m_iRows, rkM.m_iCols); + for (int i = 0; i < m_iQuantity; i++) + kDiff.m_afData[i] = m_afData[i] - rkM.m_afData[i]; + return kDiff; +} +//---------------------------------------------------------------------------- +template +GMatrix GMatrix::operator*(const GMatrix &rkM) const +{ + // 'this' is RxN, 'M' is NxC, 'product = this*M' is RxC + assert(m_iCols == rkM.m_iRows); + GMatrix kProd(m_iRows, rkM.m_iCols); + for (int iRow = 0; iRow < kProd.m_iRows; iRow++) + { + for (int iCol = 0; iCol < kProd.m_iCols; iCol++) + { + for (int iMid = 0; iMid < m_iCols; iMid++) + { + kProd.m_aafEntry[iRow][iCol] += m_aafEntry[iRow][iMid] * + rkM.m_aafEntry[iMid][iCol]; + } + } + } + return kProd; +} +//---------------------------------------------------------------------------- +template +GMatrix GMatrix::operator*(Real fScalar) const +{ + GMatrix kProd(m_iRows, m_iCols); + for (int i = 0; i < m_iQuantity; i++) + kProd.m_afData[i] = fScalar * m_afData[i]; + return kProd; +} +//---------------------------------------------------------------------------- +template +GMatrix GMatrix::operator/(Real fScalar) const +{ + GMatrix kQuot(m_iRows, m_iCols); + int i; + + if (fScalar != (Real)0.0) + { + Real fInvScalar = ((Real)1.0) / fScalar; + for (i = 0; i < m_iQuantity; i++) + kQuot.m_afData[i] = fInvScalar * m_afData[i]; + } + else + { + for (i = 0; i < m_iQuantity; i++) + kQuot.m_afData[i] = Math::MAX_REAL; + } + + return kQuot; +} +//---------------------------------------------------------------------------- +template +GMatrix GMatrix::operator-() const +{ + GMatrix kNeg(m_iRows, m_iCols); + for (int i = 0; i < m_iQuantity; i++) + kNeg.m_afData[i] = -m_afData[i]; + return kNeg; +} +//---------------------------------------------------------------------------- +template +GMatrix Wml::operator*(Real fScalar, const GMatrix &rkM) +{ + GMatrix kProd(rkM.GetRows(), rkM.GetColumns()); + const Real *afMEntry = rkM; + Real *afPEntry = kProd; + for (int i = 0; i < rkM.GetQuantity(); i++) + afPEntry[i] = fScalar * afMEntry[i]; + return kProd; +} +//---------------------------------------------------------------------------- +template +GMatrix &GMatrix::operator+=(const GMatrix &rkM) +{ + for (int i = 0; i < m_iQuantity; i++) + m_afData[i] += rkM.m_afData[i]; + return *this; +} +//---------------------------------------------------------------------------- +template +GMatrix &GMatrix::operator-=(const GMatrix &rkM) +{ + for (int i = 0; i < m_iQuantity; i++) + m_afData[i] -= rkM.m_afData[i]; + return *this; +} +//---------------------------------------------------------------------------- +template +GMatrix &GMatrix::operator*=(Real fScalar) +{ + for (int i = 0; i < m_iQuantity; i++) + m_afData[i] *= fScalar; + return *this; +} +//---------------------------------------------------------------------------- +template +GMatrix &GMatrix::operator/=(Real fScalar) +{ + int i; + + if (fScalar != (Real)0.0) + { + Real fInvScalar = ((Real)1.0) / fScalar; + for (i = 0; i < m_iQuantity; i++) + m_afData[i] *= fInvScalar; + } + else + { + for (i = 0; i < m_iQuantity; i++) + m_afData[i] = Math::MAX_REAL; + } + + return *this; +} +//---------------------------------------------------------------------------- +template +GMatrix GMatrix::Transpose() const +{ + GMatrix kTranspose(m_iCols, m_iRows); + for (int iRow = 0; iRow < m_iRows; iRow++) + { + for (int iCol = 0; iCol < m_iCols; iCol++) + kTranspose.m_aafEntry[iCol][iRow] = m_aafEntry[iRow][iCol]; + } + return kTranspose; +} +//---------------------------------------------------------------------------- +template +GMatrix GMatrix::TransposeTimes(const GMatrix &rkM) const +{ + // P = A^T*B, P[r][c] = sum_m A[m][r]*B[m][c] + assert(m_iRows == rkM.m_iRows); + GMatrix kProd(m_iCols, rkM.m_iCols); + for (int iRow = 0; iRow < kProd.m_iRows; iRow++) + { + for (int iCol = 0; iCol < kProd.m_iCols; iCol++) + { + for (int iMid = 0; iMid < m_iRows; iMid++) + { + kProd.m_aafEntry[iRow][iCol] += m_aafEntry[iMid][iRow] * + rkM.m_aafEntry[iMid][iCol]; + } + } + } + return kProd; +} +//---------------------------------------------------------------------------- +template +GMatrix GMatrix::TimesTranspose(const GMatrix &rkM) const +{ + // P = A*B^T, P[r][c] = sum_m A[r][m]*B[c][m] + assert(m_iCols == rkM.m_iCols); + GMatrix kProd(m_iRows, rkM.m_iRows); + for (int iRow = 0; iRow < kProd.m_iRows; iRow++) + { + for (int iCol = 0; iCol < kProd.m_iCols; iCol++) + { + for (int iMid = 0; iMid < m_iCols; iMid++) + { + kProd.m_aafEntry[iRow][iCol] += m_aafEntry[iRow][iMid] * + rkM.m_aafEntry[iCol][iRow]; + } + } + } + return kProd; +} +//---------------------------------------------------------------------------- +template +GVector GMatrix::operator*(const GVector &rkV) const +{ + assert(rkV.GetSize() == m_iCols); + GVector kProd(m_iRows); + for (int iRow = 0; iRow < m_iRows; iRow++) + { + for (int iCol = 0; iCol < m_iCols; iCol++) + kProd[iRow] += m_aafEntry[iRow][iCol] * rkV[iCol]; + } + return kProd; +} +//---------------------------------------------------------------------------- +template +GVector Wml::operator*(const GVector &rkV, + const GMatrix &rkM) +{ + assert(rkV.GetSize() == rkM.GetRows()); + GVector kProd(rkM.GetColumns()); + Real *afPEntry = kProd; + for (int iCol = 0; iCol < rkM.GetColumns(); iCol++) + { + for (int iRow = 0; iRow < rkM.GetRows(); iRow++) + afPEntry[iCol] += rkV[iRow] * rkM[iRow][iCol]; + } + return kProd; +} +//---------------------------------------------------------------------------- +template +Real GMatrix::QForm(const GVector &rkU, const GVector &rkV) + const +{ + assert(rkU.GetSize() == m_iRows && rkV.GetSize() == m_iCols); + return rkU.Dot((*this) * rkV); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlGVector.h b/src/editors/xrECore/WildMagic/WmlGVector.h new file mode 100644 index 00000000000..3205663e09e --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlGVector.h @@ -0,0 +1,85 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLGVECTOR_H +#define WMLGVECTOR_H + +#include "WmlMath.h" + +namespace Wml +{ + + template + class GVector + { + public: + // construction + GVector(int iSize = 0); + GVector(int iSize, const Real *afTuple); + GVector(const GVector &rkV); + ~GVector(); + + // coordinate access + void SetSize(int iSize); + int GetSize() const; + operator const Real *() const; + operator Real *(); + Real operator[](int i) const; + Real &operator[](int i); + + // assignment + GVector &operator=(const GVector &rkV); + + // comparison + bool operator==(const GVector &rkV) const; + bool operator!=(const GVector &rkV) const; + bool operator<(const GVector &rkV) const; + bool operator<=(const GVector &rkV) const; + bool operator>(const GVector &rkV) const; + bool operator>=(const GVector &rkV) const; + + // arithmetic operations + GVector operator+(const GVector &rkV) const; + GVector operator-(const GVector &rkV) const; + GVector operator*(Real fScalar) const; + GVector operator/(Real fScalar) const; + GVector operator-() const; + + // arithmetic updates + GVector &operator+=(const GVector &rkV); + GVector &operator-=(const GVector &rkV); + GVector &operator*=(Real fScalar); + GVector &operator/=(Real fScalar); + + // vector operations + Real Length() const; + Real SquaredLength() const; + Real Dot(const GVector &rkV) const; + Real Normalize(); + + protected: + // support for comparisons + int CompareArrays(const GVector &rkV) const; + + int m_iSize; + Real *m_afTuple; + }; + + template + GVector operator*(Real fScalar, const GVector &rkV); + +#include "WmlGVector.inl" + + typedef GVector GVectorf; + typedef GVector GVectord; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlGVector.inl b/src/editors/xrECore/WildMagic/WmlGVector.inl new file mode 100644 index 00000000000..80504f16b1c --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlGVector.inl @@ -0,0 +1,336 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +GVector::GVector(int iSize) +{ + if (iSize > 0) + { + m_iSize = iSize; + m_afTuple = new Real[m_iSize]; + memset(m_afTuple, 0, m_iSize * sizeof(Real)); + } + else + { + m_iSize = 0; + m_afTuple = 0; + } +} +//---------------------------------------------------------------------------- +template +GVector::GVector(int iSize, const Real *afTuple) +{ + if (iSize > 0) + { + m_iSize = iSize; + m_afTuple = new Real[m_iSize]; + memcpy(m_afTuple, afTuple, m_iSize * sizeof(Real)); + } + else + { + m_iSize = 0; + m_afTuple = 0; + } +} +//---------------------------------------------------------------------------- +template +GVector::GVector(const GVector &rkV) +{ + m_iSize = rkV.m_iSize; + if (m_iSize > 0) + { + m_afTuple = new Real[m_iSize]; + memcpy(m_afTuple, rkV.m_afTuple, m_iSize * sizeof(Real)); + } + else + { + m_afTuple = 0; + } +} +//---------------------------------------------------------------------------- +template +GVector::~GVector() +{ + delete[] m_afTuple; +} +//---------------------------------------------------------------------------- +template +void GVector::SetSize(int iSize) +{ + delete[] m_afTuple; + if (iSize > 0) + { + m_iSize = iSize; + m_afTuple = new Real[m_iSize]; + memset(m_afTuple, 0, m_iSize * sizeof(Real)); + } + else + { + m_iSize = 0; + m_afTuple = 0; + } +} +//---------------------------------------------------------------------------- +template +int GVector::GetSize() const +{ + return m_iSize; +} +//---------------------------------------------------------------------------- +template +GVector::operator const Real *() const +{ + return m_afTuple; +} +//---------------------------------------------------------------------------- +template +GVector::operator Real *() +{ + return m_afTuple; +} +//---------------------------------------------------------------------------- +template +Real GVector::operator[](int i) const +{ + assert(0 <= i && i < m_iSize); + return m_afTuple[i]; +} +//---------------------------------------------------------------------------- +template +Real &GVector::operator[](int i) +{ + assert(0 <= i && i < m_iSize); + return m_afTuple[i]; +} +//---------------------------------------------------------------------------- +template +GVector &GVector::operator=(const GVector &rkV) +{ + if (rkV.m_iSize > 0) + { + if (m_iSize != rkV.m_iSize) + { + delete[] m_afTuple; + m_iSize = rkV.m_iSize; + m_afTuple = new Real[m_iSize]; + } + memcpy(m_afTuple, rkV.m_afTuple, m_iSize * sizeof(Real)); + } + else + { + delete[] m_afTuple; + m_iSize = 0; + m_afTuple = 0; + } + return *this; +} +//---------------------------------------------------------------------------- +template +bool GVector::operator==(const GVector &rkV) const +{ + return memcmp(m_afTuple, rkV.m_afTuple, m_iSize * sizeof(Real)) == 0; +} +//---------------------------------------------------------------------------- +template +bool GVector::operator!=(const GVector &rkV) const +{ + return memcmp(m_afTuple, rkV.m_afTuple, m_iSize * sizeof(Real)) != 0; +} +//---------------------------------------------------------------------------- +template +int GVector::CompareArrays(const GVector &rkV) const +{ + return memcmp(m_afTuple, rkV.m_afTuple, m_iSize * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +bool GVector::operator<(const GVector &rkV) const +{ + return CompareArrays(rkV) < 0; +} +//---------------------------------------------------------------------------- +template +bool GVector::operator<=(const GVector &rkV) const +{ + return CompareArrays(rkV) <= 0; +} +//---------------------------------------------------------------------------- +template +bool GVector::operator>(const GVector &rkV) const +{ + return CompareArrays(rkV) > 0; +} +//---------------------------------------------------------------------------- +template +bool GVector::operator>=(const GVector &rkV) const +{ + return CompareArrays(rkV) >= 0; +} +//---------------------------------------------------------------------------- +template +GVector GVector::operator+(const GVector &rkV) const +{ + GVector kSum(m_iSize); + for (int i = 0; i < m_iSize; i++) + kSum.m_afTuple[i] = m_afTuple[i] + rkV.m_afTuple[i]; + return kSum; +} +//---------------------------------------------------------------------------- +template +GVector GVector::operator-(const GVector &rkV) const +{ + GVector kDiff(m_iSize); + for (int i = 0; i < m_iSize; i++) + kDiff.m_afTuple[i] = m_afTuple[i] - rkV.m_afTuple[i]; + return kDiff; +} +//---------------------------------------------------------------------------- +template +GVector GVector::operator*(Real fScalar) const +{ + GVector kProd(m_iSize); + for (int i = 0; i < m_iSize; i++) + kProd.m_afTuple[i] = fScalar * m_afTuple[i]; + return kProd; +} +//---------------------------------------------------------------------------- +template +GVector GVector::operator/(Real fScalar) const +{ + GVector kQuot(m_iSize); + int i; + + if (fScalar != (Real)0.0) + { + Real fInvScalar = ((Real)1.0) / fScalar; + for (i = 0; i < m_iSize; i++) + kQuot.m_afTuple[i] = fInvScalar * m_afTuple[i]; + } + else + { + for (i = 0; i < m_iSize; i++) + kQuot.m_afTuple[i] = Math::MAX_REAL; + } + + return kQuot; +} +//---------------------------------------------------------------------------- +template +GVector GVector::operator-() const +{ + GVector kNeg(m_iSize); + for (int i = 0; i < m_iSize; i++) + kNeg.m_afTuple[i] = -m_afTuple[i]; + return kNeg; +} +//---------------------------------------------------------------------------- +template +GVector Wml::operator*(Real fScalar, const GVector &rkV) +{ + GVector kProd(rkV.GetSize()); + for (int i = 0; i < rkV.GetSize(); i++) + kProd[i] = fScalar * rkV[i]; + return kProd; +} +//---------------------------------------------------------------------------- +template +GVector &GVector::operator+=(const GVector &rkV) +{ + for (int i = 0; i < m_iSize; i++) + m_afTuple[i] += rkV.m_afTuple[i]; + return *this; +} +//---------------------------------------------------------------------------- +template +GVector &GVector::operator-=(const GVector &rkV) +{ + for (int i = 0; i < m_iSize; i++) + m_afTuple[i] -= rkV.m_afTuple[i]; + return *this; +} +//---------------------------------------------------------------------------- +template +GVector &GVector::operator*=(Real fScalar) +{ + for (int i = 0; i < m_iSize; i++) + m_afTuple[i] *= fScalar; + return *this; +} +//---------------------------------------------------------------------------- +template +GVector &GVector::operator/=(Real fScalar) +{ + int i; + + if (fScalar != (Real)0.0) + { + Real fInvScalar = ((Real)1.0) / fScalar; + for (i = 0; i < m_iSize; i++) + m_afTuple[i] *= fInvScalar; + } + else + { + for (i = 0; i < m_iSize; i++) + m_afTuple[i] = Math::MAX_REAL; + } + + return *this; +} +//---------------------------------------------------------------------------- +template +Real GVector::Length() const +{ + Real fSqrLen = (Real)0.0; + for (int i = 0; i < m_iSize; i++) + fSqrLen += m_afTuple[i] * m_afTuple[i]; + return Math::Sqrt(fSqrLen); +} +//---------------------------------------------------------------------------- +template +Real GVector::SquaredLength() const +{ + Real fSqrLen = (Real)0.0; + for (int i = 0; i < m_iSize; i++) + fSqrLen += m_afTuple[i] * m_afTuple[i]; + return fSqrLen; +} +//---------------------------------------------------------------------------- +template +Real GVector::Dot(const GVector &rkV) const +{ + Real fDot = (Real)0.0; + for (int i = 0; i < m_iSize; i++) + fDot += m_afTuple[i] * rkV.m_afTuple[i]; + return fDot; +} +//---------------------------------------------------------------------------- +template +Real GVector::Normalize() +{ + Real fLength = Length(); + int i; + + if (fLength > Math::EPSILON) + { + Real fInvLength = ((Real)1.0) / fLength; + for (i = 0; i < m_iSize; i++) + m_afTuple[i] *= fInvLength; + } + else + { + fLength = (Real)0.0; + for (i = 0; i < m_iSize; i++) + m_afTuple[i] = (Real)0.0; + } + + return fLength; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlMath.cpp b/src/editors/xrECore/WildMagic/WmlMath.cpp new file mode 100644 index 00000000000..1b5620a4b3f --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMath.cpp @@ -0,0 +1,62 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlMath.h" +using namespace Wml; + +template <> +const float Math::EPSILON = FLT_EPSILON; +template <> +const float Math::ZERO_TOLERANCE = 1e-06f; +template <> +const float Math::MAX_REAL = flt_max; //.FLT_MAX; +template <> +const float Math::_PI = (float)(4.0 * atan(1.0)); +template <> +const float Math::TWO_PI = 2.0f * Math::_PI; +template <> +const float Math::HALF_PI = 0.5f * Math::_PI; +template <> +const float Math::INV_PI = 1.0f / Math::_PI; +template <> +const float Math::INV_TWO_PI = 1.0f / Math::TWO_PI; +template <> +const float Math::DEG_TO_RAD = Math::_PI / 180.0f; +template <> +const float Math::RAD_TO_DEG = 180.0f / Math::_PI; + +template <> +const double Math::EPSILON = DBL_EPSILON; +template <> +const double Math::ZERO_TOLERANCE = 1e-08; +template <> +const double Math::MAX_REAL = DBL_MAX; +template <> +const double Math::_PI = 4.0 * atan(1.0); +template <> +const double Math::TWO_PI = 2.0 * Math::_PI; +template <> +const double Math::HALF_PI = 0.5 * Math::_PI; +template <> +const double Math::INV_PI = 1.0 / Math::_PI; +template <> +const double Math::INV_TWO_PI = 1.0 / Math::TWO_PI; +template <> +const double Math::DEG_TO_RAD = Math::_PI / 180.0; +template <> +const double Math::RAD_TO_DEG = 180.0 / Math::_PI; + +namespace Wml +{ + template WML_ITEM class Math; + template WML_ITEM class Math; +}; diff --git a/src/editors/xrECore/WildMagic/WmlMath.h b/src/editors/xrECore/WildMagic/WmlMath.h new file mode 100644 index 00000000000..64f9ef49ec1 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMath.h @@ -0,0 +1,145 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLMATHH +#define WMLMATHH + +#include "WmlSystem.h" + +namespace Wml +{ + + template + class Math + { + public: + // Wrappers to hide implementations of functions. The ACos and ASin + // functions clamp the input argument to [-1,1] to avoid NaN issues + // when the input is slightly larger than 1 or slightly smaller than -1. + // Other functions have the potential for using a fast and approximate + // algorithm rather than calling the standard math library functions. + static Real ACos(Real fValue); + static Real ASin(Real fValue); + static Real ATan(Real fValue); + static Real ATan2(Real fY, Real fX); + static Real Ceil(Real fValue); + static Real Cos(Real fValue); + static Real Exp(Real fValue); + static Real FAbs(Real fValue); + static Real Floor(Real fValue); + static Real FMod(Real fX, Real fY); + static Real InvSqrt(Real fValue); + static Real Log(Real fValue); + static Real Pow(Real fBase, Real fExponent); + static Real Sin(Real fValue); + static Real Sqr(Real fValue); + static Real Sqrt(Real fValue); + static Real Tan(Real fValue); + + // Return -1 if the input is negative, 0 if the input is zero, and +1 + // if the input is positive. + static int Sign(int iValue); + static Real Sign(Real fValue); + + // Generate a random number in [0,1). The random number generator may + // be seeded by a first call to UnitRandom with a positive seed. + static Real UnitRandom(unsigned int uiSeed = 0); + + // Generate a random number in [-1,1). The random number generator may + // be seeded by a first call to SymmetricRandom with a positive seed. + static Real SymmetricRandom(unsigned int uiSeed = 0); + + // Generate a random number in [min,max). The random number generator may + // be seeded by a first call to IntervalRandom with a positive seed. + static Real IntervalRandom(Real fMin, Real fMax, + unsigned int uiSeed = 0); + + // Fast evaluation of sin(angle) by polynomial approximations. The angle + // must be in [0,pi/2]. The maximum absolute error is about 1.7e-04 for + // FastSin0 and about 2.3e-09 for FastSin1. The speed up is about 2 for + // FastSin0 and about 1.5 for FastSin1. + static Real FastSin0(Real fAngle); + static Real FastSin1(Real fAngle); + + // Fast evaluation of cos(angle) by polynomial approximations. The angle + // must be in [0,pi/2]. The maximum absolute error is about 1.2e-03 for + // FastCos0 and about 2.3e-09 for FastCos1. The speed up is about 2 for + // FastCos0 and about 1.5 for FastCos1. + static Real FastCos0(Real fAngle); + static Real FastCos1(Real fAngle); + + // Fast evaluation of tan(angle) by polynomial approximations. The angle + // must be in [0,pi/4]. The maximum absolute error is about 8.1e-04 for + // FastTan0 and about 1.9e-08 for FastTan1. The speed up is about 2.5 for + // FastTan0 and about 1.75 for FastTan1. + static Real FastTan0(Real fAngle); + static Real FastTan1(Real fAngle); + + // Fast evaluation of asin(value) by a sqrt times a polynomial. The value + // must be in [0,1]. The maximum absolute error is about 6.8e-05 and the + // speed up is about 2.5. + static Real FastInvSin(Real fValue); + + // Fast evaluation of acos(value) by a sqrt times a polynomial. The value + // must be in [0,1]. The maximum absolute error is about 6.8e-05 and the + // speed up is about 2.5. + static Real FastInvCos(Real fValue); + + // Fast evaluation of atan(value) by polynomial approximations. The value + // must be in [-1,1]. The maximum absolute error is about 1.2e-05 for + // FastInvTan0 and about 1.43-08 for FastInvTan1. The speed up is about + // 2.2 for FastInvTan0 and about 1.5 for FastInvTan1. + static Real FastInvTan0(Real fValue); + static Real FastInvTan1(Real fValue); + + // A fast approximation to 1/sqrt. + static Real FastInvSqrt(Real fValue); + + // gamma and related functions + static Real LogGamma(Real fX); + static Real Gamma(Real fX); + static Real IncompleteGamma(Real fA, Real fX); + + // error functions + static Real Erf(Real fX); // polynomial approximation + static Real Erfc(Real fX); // erfc(x) = 1-erf(x) + + // modified Bessel functions of order 0 and 1 + static Real ModBessel0(Real fX); + static Real ModBessel1(Real fX); + + // common constants + WML_ITEM static const Real EPSILON; + WML_ITEM static const Real ZERO_TOLERANCE; + WML_ITEM static const Real MAX_REAL; + WML_ITEM static const Real _PI; + WML_ITEM static const Real TWO_PI; + WML_ITEM static const Real HALF_PI; + WML_ITEM static const Real INV_PI; + WML_ITEM static const Real INV_TWO_PI; + WML_ITEM static const Real DEG_TO_RAD; + WML_ITEM static const Real RAD_TO_DEG; + + protected: + // series form (used when fX < 1+fA) + static Real IncompleteGammaS(Real fA, Real fX); + + // continued fraction form (used when fX >= 1+fA) + static Real IncompleteGammaCF(Real fA, Real fX); + }; + +#include "WmlMath.inl" + + typedef Math Mathf; + typedef Math Mathd; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlMath.inl b/src/editors/xrECore/WildMagic/WmlMath.inl new file mode 100644 index 00000000000..6db022c31f3 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMath.inl @@ -0,0 +1,644 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +const float PI = 3.1415926535897932384626433832795f; + +template +Real Math::ACos(Real fValue) +{ + if (-(Real)1.0 < fValue) + { + if (fValue < (Real)1.0) + return (Real)acos((double)fValue); + else + return (Real)0.0; + } + else + { + return PI; + } +} +//---------------------------------------------------------------------------- +template +Real Math::ASin(Real fValue) +{ + if (-(Real)1.0 < fValue) + { + if (fValue < (Real)1.0) + return (Real)asin((double)fValue); + else + return HALF_PI; + } + else + { + return -HALF_PI; + } +} +//---------------------------------------------------------------------------- +template +Real Math::ATan(Real fValue) +{ + return (Real)atan((double)fValue); +} +//---------------------------------------------------------------------------- +template +Real Math::ATan2(Real fY, Real fX) +{ + return (Real)atan2((double)fY, (double)fX); +} +//---------------------------------------------------------------------------- +template +Real Math::Ceil(Real fValue) +{ + return (Real)ceil((double)fValue); +} +//---------------------------------------------------------------------------- +template +Real Math::Cos(Real fValue) +{ + return (Real)cos((double)fValue); +} +//---------------------------------------------------------------------------- +template +Real Math::Exp(Real fValue) +{ + return (Real)exp((double)fValue); +} +//---------------------------------------------------------------------------- +template +Real Math::FAbs(Real fValue) +{ + return (Real)fabs((double)fValue); +} +//---------------------------------------------------------------------------- +template +Real Math::Floor(Real fValue) +{ + return (Real)floor((double)fValue); +} +//---------------------------------------------------------------------------- +template +Real Math::FMod(Real fX, Real fY) +{ + return (Real)fmod((double)fX, (double)fY); +} +//---------------------------------------------------------------------------- +template +Real Math::InvSqrt(Real fValue) +{ + return (Real)(1.0 / sqrt((double)fValue)); +} +//---------------------------------------------------------------------------- +template +Real Math::Log(Real fValue) +{ + return (Real)log((double)fValue); +} +//---------------------------------------------------------------------------- +template +Real Math::Pow(Real fBase, Real fExponent) +{ + return (Real)pow((double)fBase, (double)fExponent); +} +//---------------------------------------------------------------------------- +template +Real Math::Sin(Real fValue) +{ + return (Real)sin((double)fValue); +} +//---------------------------------------------------------------------------- +template +Real Math::Sqr(Real fValue) +{ + return fValue * fValue; +} +//---------------------------------------------------------------------------- +template +Real Math::Sqrt(Real fValue) +{ + return (Real)sqrt((double)fValue); +} +//---------------------------------------------------------------------------- +template +Real Math::Tan(Real fValue) +{ + return (Real)tan((double)fValue); +} +//---------------------------------------------------------------------------- +template +int Math::Sign(int iValue) +{ + if (iValue > 0) + return 1; + + if (iValue < 0) + return -1; + + return 0; +} +//---------------------------------------------------------------------------- +template +Real Math::Sign(Real fValue) +{ + if (fValue > (Real)0.0) + return (Real)1.0; + + if (fValue < (Real)0.0) + return -(Real)1.0; + + return (Real)0.0; +} +//---------------------------------------------------------------------------- +template +Real Math::UnitRandom(unsigned int uiSeed) +{ + if (uiSeed > 0) + srand(uiSeed); + + double dRatio = ((double)rand()) / ((double)(RAND_MAX)); + return (Real)dRatio; +} +//---------------------------------------------------------------------------- +template +Real Math::SymmetricRandom(unsigned int uiSeed) +{ + if (uiSeed > 0.0) + srand(uiSeed); + + double dRatio = ((double)rand()) / ((double)(RAND_MAX)); + return (Real)(2.0 * dRatio - 1.0); +} +//---------------------------------------------------------------------------- +template +Real Math::IntervalRandom(Real fMin, Real fMax, unsigned int uiSeed) +{ + if (uiSeed > 0) + srand(uiSeed); + + double dRatio = ((double)rand()) / ((double)(RAND_MAX)); + return fMin + (fMax - fMin) * ((Real)dRatio); +} +//---------------------------------------------------------------------------- +template +Real Math::FastSin0(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = (Real)7.61e-03; + fResult *= fASqr; + fResult -= (Real)1.6605e-01; + fResult *= fASqr; + fResult += (Real)1.0; + fResult *= fAngle; + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::FastSin1(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = -(Real)2.39e-08; + fResult *= fASqr; + fResult += (Real)2.7526e-06; + fResult *= fASqr; + fResult -= (Real)1.98409e-04; + fResult *= fASqr; + fResult += (Real)8.3333315e-03; + fResult *= fASqr; + fResult -= (Real)1.666666664e-01; + fResult *= fASqr; + fResult += (Real)1.0; + fResult *= fAngle; + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::FastCos0(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = (Real)3.705e-02; + fResult *= fASqr; + fResult -= (Real)4.967e-01; + fResult *= fASqr; + fResult += (Real)1.0; + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::FastCos1(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = -(Real)2.605e-07; + fResult *= fASqr; + fResult += (Real)2.47609e-05; + fResult *= fASqr; + fResult -= (Real)1.3888397e-03; + fResult *= fASqr; + fResult += (Real)4.16666418e-02; + fResult *= fASqr; + fResult -= (Real)4.999999963e-01; + fResult *= fASqr; + fResult += (Real)1.0; + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::FastTan0(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = (Real)2.033e-01; + fResult *= fASqr; + fResult += (Real)3.1755e-01; + fResult *= fASqr; + fResult += (Real)1.0; + fResult *= fAngle; + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::FastTan1(Real fAngle) +{ + Real fASqr = fAngle * fAngle; + Real fResult = (Real)9.5168091e-03; + fResult *= fASqr; + fResult += (Real)2.900525e-03; + fResult *= fASqr; + fResult += (Real)2.45650893e-02; + fResult *= fASqr; + fResult += (Real)5.33740603e-02; + fResult *= fASqr; + fResult += (Real)1.333923995e-01; + fResult *= fASqr; + fResult += (Real)3.333314036e-01; + fResult *= fASqr; + fResult += (Real)1.0; + fResult *= fAngle; + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::FastInvSin(Real fValue) +{ + Real fRoot = Math::Sqrt(((Real)1.0) - fValue); + Real fResult = -(Real)0.0187293; + fResult *= fValue; + fResult += (Real)0.0742610; + fResult *= fValue; + fResult -= (Real)0.2121144; + fResult *= fValue; + fResult += (Real)1.5707288; + fResult = HALF_PI - fRoot * fResult; + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::FastInvCos(Real fValue) +{ + Real fRoot = Math::Sqrt(((Real)1.0) - fValue); + Real fResult = -(Real)0.0187293; + fResult *= fValue; + fResult += (Real)0.0742610; + fResult *= fValue; + fResult -= (Real)0.2121144; + fResult *= fValue; + fResult += (Real)1.5707288; + fResult *= fRoot; + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::FastInvTan0(Real fValue) +{ + Real fVSqr = fValue * fValue; + Real fResult = (Real)0.0208351; + fResult *= fVSqr; + fResult -= (Real)0.085133; + fResult *= fVSqr; + fResult += (Real)0.180141; + fResult *= fVSqr; + fResult -= (Real)0.3302995; + fResult *= fVSqr; + fResult += (Real)0.999866; + fResult *= fValue; + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::FastInvTan1(Real fValue) +{ + Real fVSqr = fValue * fValue; + Real fResult = (Real)0.0028662257; + fResult *= fVSqr; + fResult -= (Real)0.0161657367; + fResult *= fVSqr; + fResult += (Real)0.0429096138; + fResult *= fVSqr; + fResult -= (Real)0.0752896400; + fResult *= fVSqr; + fResult += (Real)0.1065626393; + fResult *= fVSqr; + fResult -= (Real)0.1420889944; + fResult *= fVSqr; + fResult += (Real)0.1999355085; + fResult *= fVSqr; + fResult -= (Real)0.3333314528; + fResult *= fVSqr; + fResult += (Real)1.0; + fResult *= fValue; + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::FastInvSqrt(Real fValue) +{ + // TO DO. This routine was designed for 'float'. Come up with an + // equivalent one for 'double' and specialize the templates for 'float' + // and 'double'. + float fFValue = (float)fValue; + float fHalf = 0.5f * fFValue; + int i = *(int *)&fFValue; + i = 0x5f3759df - (i >> 1); + fFValue = *(float *)&i; + fFValue = fFValue * (1.5f - fHalf * fFValue * fFValue); + return (Real)fFValue; +} +//---------------------------------------------------------------------------- +template +Real Math::LogGamma(Real fX) +{ + const Real afCoeff[6] = + { + +(Real)76.18009173, + -(Real)86.50532033, + +(Real)24.01409822, + -(Real)1.231739516, + +(Real)0.120858003e-02, + -(Real)0.536382000e-05}; + + fX -= (Real)1.0; + Real fTmp = fX + (Real)5.5; + fTmp -= (fX + ((Real)0.5)) * Math::Log(fTmp); + Real fSeries = (Real)1.0; + for (int j = 0; j <= 5; j++) + { + fX += (Real)1.0; + fSeries += afCoeff[j] / fX; + } + return -fTmp + Math::Log(((Real)2.50662827465) * fSeries); +} +//---------------------------------------------------------------------------- +template +Real Math::Gamma(Real fX) +{ + return Math::Exp(LogGamma(fX)); +} +//---------------------------------------------------------------------------- +template +Real Math::IncompleteGammaS(Real fA, Real fX) +{ + const int iMaxIterations = 100; + const Real fTolerance = (Real)3e-07; + + if (fX > (Real)0.0) + { + Real fAp = fA; + Real fSum = ((Real)1.0) / fA, fDel = fSum; + for (int i = 1; i <= iMaxIterations; i++) + { + fAp += (Real)1.0; + fDel *= fX / fAp; + fSum += fDel; + if (Math::FAbs(fDel) < Math::FAbs(fSum) * fTolerance) + { + Real fArg = -fX + fA * Math::Log(fX) - LogGamma(fA); + return fSum * Math::Exp(fArg); + } + } + } + + if (fX == (Real)0.0) + return (Real)0.0; + + return Math::MAX_REAL; // LogGamma not defined for x < 0 +} +//---------------------------------------------------------------------------- +template +Real Math::IncompleteGammaCF(Real fA, Real fX) +{ + const int iMaxIterations = 100; + const Real fTolerance = (Real)3e-07; + + Real fA0 = (Real)1.0, fA1 = fX; + Real fB0 = 0, fB1 = (Real)1.0; + Real fGold = (Real)0.0, fFac = (Real)1.0; + + for (int i = 1; i <= iMaxIterations; i++) + { + Real fI = (Real)i; + Real fImA = fI - fA; + fA0 = (fA1 + fA0 * fImA) * fFac; + fB0 = (fB1 + fB0 * fImA) * fFac; + Real fItF = fI * fFac; + fA1 = fX * fA0 + fItF * fA1; + fB1 = fX * fB0 + fItF * fB1; + if (fA1 != (Real)0.0) + { + fFac = ((Real)1.0) / fA1; + Real fG = fB1 * fFac; + if (Math::FAbs((fG - fGold) / fG) < fTolerance) + { + Real fArg = -fX + fA * Math::Log(fX) - LogGamma(fA); + return fG * Math::Exp(fArg); + } + fGold = fG; + } + } + + return Math::MAX_REAL; // numerical error if you get here +} +//---------------------------------------------------------------------------- +template +Real Math::IncompleteGamma(Real fA, Real fX) +{ + if (fX < (Real)1.0 + fA) + return IncompleteGammaS(fA, fX); + else + return (Real)1.0 - IncompleteGammaCF(fA, fX); +} +//---------------------------------------------------------------------------- +template +Real Math::Erf(Real fX) +{ + return (Real)1.0 - Erfc(fX); +} +//---------------------------------------------------------------------------- +template +Real Math::Erfc(Real fX) +{ + const Real afCoeff[10] = + { + -(Real)1.26551223, + +(Real)1.00002368, + +(Real)0.37409196, + +(Real)0.09678418, + -(Real)0.18628806, + +(Real)0.27886807, + -(Real)1.13520398, + +(Real)1.48851587, + -(Real)0.82215223, + +(Real)0.17087277}; + + Real fZ = Math::FAbs(fX); + Real fT = ((Real)1.0) / ((Real)1.0 + ((Real)0.5) * fZ); + Real fSum = afCoeff[9]; + + for (int i = 9; i >= 0; i--) + fSum = fT * fSum + afCoeff[i]; + + Real fResult = fT * Math::Exp(-fZ * fZ + fSum); + + return (fX >= (Real)0.0 ? fResult : (Real)2.0 - fResult); +} +//---------------------------------------------------------------------------- +template +Real Math::ModBessel0(Real fX) +{ + if (fX < (Real)0.0) // function is even + fX = -fX; + + Real fT, fResult; + int i; + + if (fX <= (Real)3.75) + { + const Real afCoeff[7] = + { + (Real)1.0000000, + (Real)3.5156229, + (Real)3.0899424, + (Real)1.2067492, + (Real)0.2659732, + (Real)0.0360768, + (Real)0.0045813}; + + fT = fX / (Real)3.75; + Real fT2 = fT * fT; + fResult = afCoeff[6]; + for (i = 5; i >= 0; i--) + { + fResult *= fT2; + fResult += afCoeff[i]; + } + // |error| < 1.6e-07 + } + else + { + const Real afCoeff[9] = + { + +(Real)0.39894228, + +(Real)0.01328592, + +(Real)0.00225319, + -(Real)0.00157565, + +(Real)0.00916281, + -(Real)0.02057706, + +(Real)0.02635537, + -(Real)0.01647633, + +(Real)0.00392377}; + + fT = fX / (Real)3.75; + Real fInvT = ((Real)1.0) / fT; + fResult = afCoeff[8]; + for (i = 7; i >= 0; i--) + { + fResult *= fInvT; + fResult += afCoeff[i]; + } + fResult *= Math::Exp(fX); + fResult /= Math::Sqrt(fX); + // |error| < 1.9e-07 + } + + return fResult; +} +//---------------------------------------------------------------------------- +template +Real Math::ModBessel1(Real fX) +{ + int iSign; + if (fX > (Real)0.0) + { + iSign = 1; + } + else if (fX < (Real)0.0) + { + fX = -fX; + iSign = -1; + } + else + { + return (Real)0.0; + } + + Real fT, fResult; + int i; + + if (fX <= (Real)3.75) + { + const Real afCoeff[7] = + { + (Real)0.50000000, + (Real)0.87890549, + (Real)0.51498869, + (Real)0.15084934, + (Real)0.02658733, + (Real)0.00301532, + (Real)0.00032411}; + + fT = fX / (Real)3.75; + Real fT2 = fT * fT; + fResult = afCoeff[6]; + for (i = 5; i >= 0; i--) + { + fResult *= fT2; + fResult += afCoeff[i]; + } + fResult *= fX; + // |error| < 8e-09 + } + else + { + const Real afCoeff[9] = + { + +(Real)0.39894228, + -(Real)0.03988024, + -(Real)0.00362018, + +(Real)0.00163801, + -(Real)0.01031555, + +(Real)0.02282967, + -(Real)0.02895312, + +(Real)0.01787654, + -(Real)0.00420059}; + + fT = fX / (Real)3.75; + Real fInvT = ((Real)1.0) / fT; + fResult = afCoeff[8]; + for (i = 7; i >= 0; i--) + { + fResult *= fInvT; + fResult += afCoeff[i]; + } + fResult *= Math::Exp(fX); + fResult /= Math::Sqrt(fX); + // |error| < 2.2e-07 + } + + fResult *= iSign; + return fResult; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlMatrix.h b/src/editors/xrECore/WildMagic/WmlMatrix.h new file mode 100644 index 00000000000..6c695109487 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix.h @@ -0,0 +1,124 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLMATRIX_H +#define WMLMATRIX_H + +// Matrix operations are applied on the left. For example, given a matrix M +// and a vector V, matrix-times-vector is M*V. That is, V is treated as a +// column vector. Some graphics APIs use V*M where V is treated as a row +// vector. In this context the "M" matrix is really a transpose of the M as +// represented in Wild Magic. Similarly, to apply two matrix operations M0 +// and M1, in that order, you compute M1*M0 so that the transform of a vector +// is (M1*M0)*V = M1*(M0*V). Some graphics APIs use M0*M1, but again these +// matrices are the transpose of those as represented in Wild Magic. You +// must therefore be careful about how you interface the transformation code +// with graphics APIS. +// +// For memory organization it might seem natural to chose Real[N][N] for the +// matrix storage, but this can be a problem on a platform/console that +// chooses to store the data in column-major rather than row-major format. +// To avoid potential portability problems, the matrix is stored as Real[N*N] +// and organized in row-major order. That is, the entry of the matrix in row +// r (0 <= r < N) and column c (0 <= c < N) is stored at index i = c+N*r +// (0 <= i < N*N). + +#include "WmlVector.h" + +namespace Wml +{ + + template + class Matrix + { + public: + // Construction. In the second constructor, if bZero is 'true', the + // matrix is set to the zero matrix. If bZero is 'false', the matrix + // is set to the identity matrix. + Matrix(); + Matrix(bool bZero); + Matrix(const Matrix &rkM); + + void MakeZero(); + void MakeIdentity(); + void MakeDiagonal(const Real *afDiag); + + // member access + operator const Real *() const; + operator Real *(); + const Real *operator[](int iRow) const; + Real *operator[](int iRow); + Real operator()(int iRow, int iCol) const; + Real &operator()(int iRow, int iCol); + void SetRow(int iRow, const Vector &rkV); + Vector GetRow(int iRow) const; + void SetColumn(int iCol, const Vector &rkV); + Vector GetColumn(int iCol) const; + void GetColumnMajor(Real *afCMajor) const; + + // assignment + Matrix &operator=(const Matrix &rkM); + + // comparison + bool operator==(const Matrix &rkM) const; + bool operator!=(const Matrix &rkM) const; + bool operator<(const Matrix &rkM) const; + bool operator<=(const Matrix &rkM) const; + bool operator>(const Matrix &rkM) const; + bool operator>=(const Matrix &rkM) const; + + // arithmetic operations + Matrix operator+(const Matrix &rkM) const; + Matrix operator-(const Matrix &rkM) const; + Matrix operator*(const Matrix &rkM) const; + Matrix operator*(Real fScalar) const; + Matrix operator/(Real fScalar) const; + Matrix operator-() const; + + // arithmetic updates + Matrix &operator+=(const Matrix &rkM); + Matrix &operator-=(const Matrix &rkM); + Matrix &operator*=(Real fScalar); + Matrix &operator/=(Real fScalar); + + // matrix products + Matrix Transpose() const; // M^T + Matrix TransposeTimes(const Matrix &rkM) const; // this^T * M + Matrix TimesTranspose(const Matrix &rkM) const; // this * M^T + + // matrix-vector operations + Vector operator*(const Vector &rkV) const; // M * v + Real QForm(const Vector &rkU, const Vector &rkV) + const; // u^T*M*v + + protected: + // for indexing into the 1D array of the matrix, iCol+N*iRow + static int I(int iRow, int iCol); + + // support for comparisons + int CompareArrays(const Matrix &rkM) const; + + Real m_afEntry[N * N]; + }; + + // c * M + template + Matrix operator*(Real fScalar, const Matrix &rkM); + + // v^T * M + template + Vector operator*(const Vector &rkV, + const Matrix &rkM); + +#include "WmlMatrix.inl" + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlMatrix.inl b/src/editors/xrECore/WildMagic/WmlMatrix.inl new file mode 100644 index 00000000000..6ea14e08872 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix.inl @@ -0,0 +1,419 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +Matrix::Matrix() +{ + // the matrix is uninitialized +} +//---------------------------------------------------------------------------- +template +Matrix::Matrix(bool bZero) +{ + memset(Matrix::m_afEntry, 0, N * N * sizeof(Real)); + + if (!bZero) + { + for (int i = 0; i < N; i++) + Matrix::m_afEntry[I(i, i)] = (Real)1.0; + } +} +//---------------------------------------------------------------------------- +template +Matrix::Matrix(const Matrix &rkM) +{ + memcpy(Matrix::m_afEntry, rkM.Matrix::m_afEntry, N * N * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +void Matrix::MakeZero() +{ + memset(Matrix::m_afEntry, 0, N * N * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +void Matrix::MakeIdentity() +{ + memset(Matrix::m_afEntry, 0, N * N * sizeof(Real)); + for (int i = 0; i < N; i++) + Matrix::m_afEntry[I(i, i)] = (Real)1.0; +} +//---------------------------------------------------------------------------- +template +void Matrix::MakeDiagonal(const Real *afDiag) +{ + memset(Matrix::m_afEntry, 0, N * N * sizeof(Real)); + for (int i = 0; i < N; i++) + Matrix::m_afEntry[I(i, i)] = afDiag[i]; +} +//---------------------------------------------------------------------------- +template +Matrix::operator const Real *() const +{ + return Matrix::m_afEntry; +} +//---------------------------------------------------------------------------- +template +Matrix::operator Real *() +{ + return Matrix::m_afEntry; +} +//---------------------------------------------------------------------------- +template +const Real *Matrix::operator[](int iRow) const +{ + assert(0 <= iRow && iRow < N); + return &Matrix::m_afEntry[N * iRow]; +} +//---------------------------------------------------------------------------- +template +Real *Matrix::operator[](int iRow) +{ + assert(0 <= iRow && iRow < N); + return &Matrix::m_afEntry[N * iRow]; +} +//---------------------------------------------------------------------------- +template +Real Matrix::operator()(int iRow, int iCol) const +{ + return Matrix::m_afEntry[I(iRow, iCol)]; +} +//---------------------------------------------------------------------------- +template +Real &Matrix::operator()(int iRow, int iCol) +{ + return Matrix::m_afEntry[I(iRow, iCol)]; +} +//---------------------------------------------------------------------------- +template +void Matrix::SetRow(int iRow, const Vector &rkV) +{ + assert(0 <= iRow && iRow < N); + for (int iCol = 0, i = N * iRow; iCol < N; iCol++, i++) + Matrix::m_afEntry[i] = rkV[iCol]; +} +//---------------------------------------------------------------------------- +template +Vector Matrix::GetRow(int iRow) const +{ + assert(0 <= iRow && iRow < N); + Vector kV; + for (int iCol = 0, i = N * iRow; iCol < N; iCol++, i++) + kV[iCol] = Matrix::m_afEntry[i]; + return kV; +} +//---------------------------------------------------------------------------- +template +void Matrix::SetColumn(int iCol, const Vector &rkV) +{ + assert(0 <= iCol && iCol < N); + for (int iRow = 0, i = iCol; iRow < N; iRow++, i += N) + Matrix::m_afEntry[i] = rkV[iRow]; +} +//---------------------------------------------------------------------------- +template +Vector Matrix::GetColumn(int iCol) const +{ + assert(0 <= iCol && iCol < N); + Vector kV; + for (int iRow = 0, i = iCol; iRow < N; iRow++, i += N) + kV[iRow] = Matrix::m_afEntry[i]; + return kV; +} +//---------------------------------------------------------------------------- +template +void Matrix::GetColumnMajor(Real *afCMajor) const +{ + for (int iRow = 0, i = 0; iRow < N; iRow++) + { + for (int iCol = 0; iCol < N; iCol++) + afCMajor[i++] = Matrix::m_afEntry[I(iCol, iRow)]; + } +} +//---------------------------------------------------------------------------- +template +Matrix &Matrix::operator=(const Matrix &rkM) +{ + memcpy(Matrix::m_afEntry, rkM.Matrix::m_afEntry, N * N * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +bool Matrix::operator==(const Matrix &rkM) const +{ + return memcmp(Matrix::m_afEntry, rkM.Matrix::m_afEntry, N * N * sizeof(Real)) == 0; +} +//---------------------------------------------------------------------------- +template +bool Matrix::operator!=(const Matrix &rkM) const +{ + return memcmp(Matrix::m_afEntry, rkM.Matrix::m_afEntry, N * N * sizeof(Real)) != 0; +} +//---------------------------------------------------------------------------- +template +int Matrix::CompareArrays(const Matrix &rkM) const +{ + return memcmp(Matrix::m_afEntry, rkM.Matrix::m_afEntry, N * N * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +bool Matrix::operator<(const Matrix &rkM) const +{ + return CompareArrays(rkM) < 0; +} +//---------------------------------------------------------------------------- +template +bool Matrix::operator<=(const Matrix &rkM) const +{ + return CompareArrays(rkM) <= 0; +} +//---------------------------------------------------------------------------- +template +bool Matrix::operator>(const Matrix &rkM) const +{ + return CompareArrays(rkM) > 0; +} +//---------------------------------------------------------------------------- +template +bool Matrix::operator>=(const Matrix &rkM) const +{ + return CompareArrays(rkM) >= 0; +} +//---------------------------------------------------------------------------- +template +Matrix Matrix::operator+(const Matrix &rkM) const +{ + Matrix kSum; + for (int i = 0; i < N * N; i++) + kSum.Matrix::m_afEntry[i] = Matrix::m_afEntry[i] + rkM.Matrix::m_afEntry[i]; + return kSum; +} +//---------------------------------------------------------------------------- +template +Matrix Matrix::operator-(const Matrix &rkM) const +{ + Matrix kDiff; + for (int i = 0; i < N * N; i++) + kDiff.Matrix::m_afEntry[i] = Matrix::m_afEntry[i] - rkM.Matrix::m_afEntry[i]; + return kDiff; +} +//---------------------------------------------------------------------------- +template +Matrix Matrix::operator*(const Matrix &rkM) const +{ + Matrix kProd; + for (int iRow = 0; iRow < N; iRow++) + { + for (int iCol = 0; iCol < N; iCol++) + { + int i = I(iRow, iCol); + kProd.Matrix::m_afEntry[i] = (Real)0.0f; + for (int iMid = 0; iMid < N; iMid++) + { + kProd.Matrix::m_afEntry[i] += + Matrix::m_afEntry[I(iRow, iMid)] * rkM.Matrix::m_afEntry[I(iMid, iCol)]; + } + } + } + return kProd; +} +//---------------------------------------------------------------------------- +template +Matrix Matrix::operator*(Real fScalar) const +{ + Matrix kProd; + for (int i = 0; i < N * N; i++) + kProd.Matrix::m_afEntry[i] = fScalar * Matrix::m_afEntry[i]; + return kProd; +} +//---------------------------------------------------------------------------- +template +Matrix Matrix::operator/(Real fScalar) const +{ + Matrix kQuot; + int i; + + if (fScalar != (Real)0.0) + { + Real fInvScalar = ((Real)1.0) / fScalar; + for (i = 0; i < N * N; i++) + kQuot.Matrix::m_afEntry[i] = fInvScalar * Matrix::m_afEntry[i]; + } + else + { + for (i = 0; i < N * N; i++) + kQuot.Matrix::m_afEntry[i] = Math::MAX_REAL; + } + + return kQuot; +} +//---------------------------------------------------------------------------- +template +Matrix Matrix::operator-() const +{ + Matrix kNeg; + for (int i = 0; i < N * N; i++) + kNeg.Matrix::m_afEntry[i] = -Matrix::m_afEntry[i]; + return kNeg; +} +//---------------------------------------------------------------------------- +template +Matrix operator*(Real fScalar, const Matrix &rkM) +{ + Matrix kProd; + const Real *afMEntry = rkM; + Real *afPEntry = kProd; + for (int i = 0; i < N * N; i++) + afPEntry[i] = fScalar * afMEntry[i]; + return kProd; +} +//---------------------------------------------------------------------------- +template +Matrix &Matrix::operator+=(const Matrix &rkM) +{ + for (int i = 0; i < N * N; i++) + Matrix::m_afEntry[i] += rkM.Matrix::m_afEntry[i]; + return *this; +} +//---------------------------------------------------------------------------- +template +Matrix &Matrix::operator-=(const Matrix &rkM) +{ + for (int i = 0; i < N * N; i++) + Matrix::m_afEntry[i] -= rkM.Matrix::m_afEntry[i]; + return *this; +} +//---------------------------------------------------------------------------- +template +Matrix &Matrix::operator*=(Real fScalar) +{ + for (int i = 0; i < N * N; i++) + Matrix::m_afEntry[i] *= fScalar; + return *this; +} +//---------------------------------------------------------------------------- +template +Matrix &Matrix::operator/=(Real fScalar) +{ + int i; + + if (fScalar != (Real)0.0) + { + Real fInvScalar = ((Real)1.0) / fScalar; + for (i = 0; i < N * N; i++) + Matrix::m_afEntry[i] *= fInvScalar; + } + else + { + for (i = 0; i < N * N; i++) + Matrix::m_afEntry[i] = Math::MAX_REAL; + } + + return *this; +} +//---------------------------------------------------------------------------- +template +Matrix Matrix::Transpose() const +{ + Matrix kTranspose; + for (int iRow = 0; iRow < N; iRow++) + { + for (int iCol = 0; iCol < N; iCol++) + kTranspose.Matrix::m_afEntry[I(iRow, iCol)] = Matrix::m_afEntry[I(iCol, iRow)]; + } + return kTranspose; +} +//---------------------------------------------------------------------------- +template +Matrix Matrix::TransposeTimes(const Matrix &rkM) const +{ + // P = A^T*B, P[r][c] = sum_m A[m][r]*B[m][c] + Matrix kProd; + for (int iRow = 0; iRow < N; iRow++) + { + for (int iCol = 0; iCol < N; iCol++) + { + int i = I(iRow, iCol); + kProd.Matrix::m_afEntry[i] = (Real)0.0; + for (int iMid = 0; iMid < N; iMid++) + { + kProd.Matrix::m_afEntry[i] += + Matrix::m_afEntry[I(iMid, iRow)] * rkM.Matrix::m_afEntry[I(iMid, iCol)]; + } + } + } + return kProd; +} +//---------------------------------------------------------------------------- +template +Matrix Matrix::TimesTranspose(const Matrix &rkM) const +{ + // P = A*B^T, P[r][c] = sum_m A[r][m]*B[c][m] + Matrix kProd; + for (int iRow = 0; iRow < N; iRow++) + { + for (int iCol = 0; iCol < N; iCol++) + { + int i = I(iRow, iCol); + kProd.Matrix::m_afEntry[i] = (Real)0.0; + for (int iMid = 0; iMid < N; iMid++) + { + kProd.Matrix::m_afEntry[i] += + Matrix::m_afEntry[I(iRow, iMid)] * rkM.Matrix::m_afEntry[I(iCol, iRow)]; + } + } + } + return kProd; +} +//---------------------------------------------------------------------------- +template +Vector Matrix::operator*(const Vector &rkV) const +{ + Vector kProd; + for (int iRow = 0; iRow < N; iRow++) + { + kProd[iRow] = (Real)0.0; + for (int iCol = 0; iCol < N; iCol++) + kProd[iRow] += Matrix::m_afEntry[I(iRow, iCol)] * rkV[iCol]; + } + return kProd; +} +//---------------------------------------------------------------------------- +template +Vector operator*(const Vector &rkV, + const Matrix &rkM) +{ + Vector kProd; + const Real *afMEntry = rkM; + Real *afPEntry = kProd; + for (int iCol = 0; iCol < N; iCol++) + { + afPEntry[iCol] = (Real)0.0; + for (int iRow = 0; iRow < N; iRow++) + afPEntry[iCol] += rkV[iRow] * afMEntry[iCol + N * iRow]; + } + return kProd; +} +//---------------------------------------------------------------------------- +template +Real Matrix::QForm(const Vector &rkU, + const Vector &rkV) const +{ + return rkU.Dot((*this) * rkV); +} +//---------------------------------------------------------------------------- +template +int Matrix::I(int iRow, int iCol) +{ + assert(0 <= iRow && iRow < N && 0 <= iCol && iCol < N); + return iCol + N * iRow; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlMatrix2.cpp b/src/editors/xrECore/WildMagic/WmlMatrix2.cpp new file mode 100644 index 00000000000..365eda1a402 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix2.cpp @@ -0,0 +1,30 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#include "WmlMatrix2.h" +using namespace Wml; + +template <> +const Matrix2 Matrix2::ZERO( + 0.0f, 0.0f, + 0.0f, 0.0f); +template <> +const Matrix2 Matrix2::IDENTITY( + 1.0f, 0.0f, + 0.0f, 1.0f); + +template <> +const Matrix2 Matrix2::ZERO( + 0.0, 0.0, + 0.0, 0.0); +template <> +const Matrix2 Matrix2::IDENTITY( + 1.0, 0.0, + 0.0, 1.0); diff --git a/src/editors/xrECore/WildMagic/WmlMatrix2.h b/src/editors/xrECore/WildMagic/WmlMatrix2.h new file mode 100644 index 00000000000..7f69eafd0f5 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix2.h @@ -0,0 +1,97 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLMATRIX2_H +#define WMLMATRIX2_H + +// Rotation matrices are of the form +// R = cos(t) -sin(t) +// sin(t) cos(t) +// where t > 0 indicates a counterclockwise rotation in the xy-plane. + +#include "WmlMatrix.h" +#include "WmlVector2.h" + +namespace Wml +{ + + template + class Matrix2 : public Matrix<2, Real> + { + public: + // construction + Matrix2(); + Matrix2(const Matrix2 &rkM); + Matrix2(const Matrix<2, Real> &rkM); + + // input Mrc is in row r, column c. + Matrix2(Real fM00, Real fM01, Real fM10, Real fM11); + + // Create a matrix from an array of numbers. The input array is + // interpreted based on the Boolean input as + // true: entry[0..3] = {m00,m01,m10,m11} [row major] + // false: entry[0..3] = {m00,m10,m01,m11} [column major] + Matrix2(const Real afEntry[4], bool bRowMajor); + + // Create matrices based on vector input. The Boolean is interpreted as + // true: vectors are columns of the matrix + // false: vectors are rows of the matrix + Matrix2(const Vector2 &rkU, const Vector2 &rkV, + bool bColumns); + Matrix2(const Vector2 *akV, bool bColumns); + + // create a tensor product U*V^T + Matrix2(const Vector2 &rkU, const Vector2 &rkV); + void MakeTensorProduct(const Vector2 &rkU, + const Vector2 &rkV); + + // create a diagonal matrix + Matrix2(Real fM00, Real fM11); + void MakeDiagonal(Real fM00, Real fM11); + + // create a rotation matrix (positive angle - counterclockwise) + Matrix2(Real fAngle); + void FromAngle(Real fAngle); + + // assignment + Matrix2 &operator=(const Matrix2 &rkM); + Matrix2 &operator=(const Matrix<2, Real> &rkM); + + // matrix operations + Matrix2 Inverse() const; + Matrix2 Adjoint() const; + Real Determinant() const; + + // The matrix must be a rotation for these functions to be valid. The + // last function uses Gram-Schmidt orthonormalization applied to the + // columns of the rotation matrix. The angle must be in radians, not + // degrees. + void ToAngle(Real &rfAngle) const; + void Orthonormalize(); + + // The matrix must be symmetric. Factor M = R * D * R^T where + // R = [u0|u1] is a rotation matrix with columns u0 and u1 and + // D = diag(d0,d1) is a diagonal matrix whose diagonal entries are d0 and + // d1. The eigenvector u[i] corresponds to eigenvector d[i]. The + // eigenvalues are ordered as d0 <= d1. + void EigenDecomposition(Matrix2 &rkRot, Matrix2 &rkDiag) const; + + WML_ITEM static const Matrix2 ZERO; + WML_ITEM static const Matrix2 IDENTITY; + }; + +#include "WmlMatrix2.inl" + + typedef Matrix2 Matrix2f; + typedef Matrix2 Matrix2d; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlMatrix2.inl b/src/editors/xrECore/WildMagic/WmlMatrix2.inl new file mode 100644 index 00000000000..81097410a9d --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix2.inl @@ -0,0 +1,274 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +Matrix2::Matrix2() +{ + // the matrix is uninitialized +} +//---------------------------------------------------------------------------- +template +Matrix2::Matrix2(const Matrix2 &rkM) +{ + memcpy(Matrix2::m_afEntry, rkM.Matrix2::m_afEntry, 4 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Matrix2::Matrix2(const Matrix<2, Real> &rkM) +{ + memcpy(Matrix2::m_afEntry, (const Real *)rkM, 4 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Matrix2::Matrix2(Real fM00, Real fM01, Real fM10, Real fM11) +{ + Matrix2::m_afEntry[0] = fM00; + Matrix2::m_afEntry[1] = fM01; + Matrix2::m_afEntry[2] = fM10; + Matrix2::m_afEntry[3] = fM11; +} +//---------------------------------------------------------------------------- +template +Matrix2::Matrix2(const Real afEntry[4], bool bRowMajor) +{ + if (bRowMajor) + { + memcpy(Matrix2::m_afEntry, afEntry, 4 * sizeof(Real)); + } + else + { + Matrix2::m_afEntry[0] = afEntry[0]; + Matrix2::m_afEntry[1] = afEntry[2]; + Matrix2::m_afEntry[2] = afEntry[1]; + Matrix2::m_afEntry[3] = afEntry[3]; + } +} +//---------------------------------------------------------------------------- +template +Matrix2::Matrix2(const Vector2 &rkU, + const Vector2 &rkV, bool bColumns) +{ + if (bColumns) + { + Matrix2::m_afEntry[0] = rkU[0]; + Matrix2::m_afEntry[1] = rkV[0]; + Matrix2::m_afEntry[2] = rkU[1]; + Matrix2::m_afEntry[3] = rkV[1]; + } + else + { + Matrix2::m_afEntry[0] = rkU[0]; + Matrix2::m_afEntry[1] = rkU[1]; + Matrix2::m_afEntry[2] = rkV[0]; + Matrix2::m_afEntry[3] = rkV[1]; + } +} +//---------------------------------------------------------------------------- +template +Matrix2::Matrix2(const Vector2 *akV, bool bColumns) +{ + if (bColumns) + { + Matrix2::m_afEntry[0] = akV[0][0]; + Matrix2::m_afEntry[1] = akV[1][0]; + Matrix2::m_afEntry[2] = akV[0][1]; + Matrix2::m_afEntry[3] = akV[1][1]; + } + else + { + Matrix2::m_afEntry[0] = akV[0][0]; + Matrix2::m_afEntry[1] = akV[0][1]; + Matrix2::m_afEntry[2] = akV[1][0]; + Matrix2::m_afEntry[3] = akV[1][1]; + } +} +//---------------------------------------------------------------------------- +template +Matrix2::Matrix2(const Vector2 &rkU, + const Vector2 &rkV) +{ + MakeTensorProduct(rkU, rkV); +} +//---------------------------------------------------------------------------- +template +void Matrix2::MakeTensorProduct(const Vector2 &rkU, + const Vector2 &rkV) +{ + Matrix2::m_afEntry[0] = rkU[0] * rkV[0]; + Matrix2::m_afEntry[1] = rkU[0] * rkV[1]; + Matrix2::m_afEntry[2] = rkU[1] * rkV[0]; + Matrix2::m_afEntry[3] = rkU[1] * rkV[1]; +} +//---------------------------------------------------------------------------- +template +Matrix2::Matrix2(Real fM00, Real fM11) +{ + MakeDiagonal(fM00, fM11); +} +//---------------------------------------------------------------------------- +template +void Matrix2::MakeDiagonal(Real fM00, Real fM11) +{ + Matrix2::m_afEntry[0] = fM00; + Matrix2::m_afEntry[1] = (Real)0.0; + Matrix2::m_afEntry[2] = (Real)0.0; + Matrix2::m_afEntry[3] = fM11; +} +//---------------------------------------------------------------------------- +template +Matrix2::Matrix2(Real fAngle) +{ + FromAngle(fAngle); +} +//---------------------------------------------------------------------------- +template +void Matrix2::FromAngle(Real fAngle) +{ + Matrix2::m_afEntry[0] = Math::Cos(fAngle); + Matrix2::m_afEntry[1] = -Math::Sin(fAngle); + Matrix2::m_afEntry[2] = Matrix2::m_afEntry[1]; + Matrix2::m_afEntry[3] = Matrix2::m_afEntry[0]; +} +//---------------------------------------------------------------------------- +template +Matrix2 &Matrix2::operator=(const Matrix2 &rkM) +{ + memcpy(Matrix2::m_afEntry, rkM.Matrix2::m_afEntry, 4 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Matrix2 &Matrix2::operator=(const Matrix<2, Real> &rkM) +{ + memcpy(Matrix2::m_afEntry, (const Real *)rkM, 4 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Matrix2 Matrix2::Inverse() const +{ + Matrix2 kInverse; + + Real fDet = Matrix2::m_afEntry[0] * Matrix2::m_afEntry[3] - Matrix2::m_afEntry[1] * Matrix2::m_afEntry[2]; + if (Math::FAbs(fDet) > Math::EPSILON) + { + Real fInvDet = ((Real)1.0) / fDet; + kInverse[0][0] = Matrix2::m_afEntry[3] * fInvDet; + kInverse[0][1] = -Matrix2::m_afEntry[1] * fInvDet; + kInverse[1][0] = -Matrix2::m_afEntry[2] * fInvDet; + kInverse[1][1] = Matrix2::m_afEntry[0] * fInvDet; + } + else + { + kInverse.MakeZero(); + } + + return kInverse; +} +//---------------------------------------------------------------------------- +template +Matrix2 Matrix2::Adjoint() const +{ + return Matrix2( + Matrix2::m_afEntry[3], -Matrix2::m_afEntry[1], + -Matrix2::m_afEntry[2], Matrix2::m_afEntry[0]); +} +//---------------------------------------------------------------------------- +template +Real Matrix2::Determinant() const +{ + return Matrix2::m_afEntry[0] * Matrix2::m_afEntry[3] - Matrix2::m_afEntry[1] * Matrix2::m_afEntry[2]; +} +//---------------------------------------------------------------------------- +template +void Matrix2::ToAngle(Real &rfAngle) const +{ + // assert: matrix is a rotation + rfAngle = Math::ATan2(Matrix2::m_afEntry[2], Matrix2::m_afEntry[0]); +} +//---------------------------------------------------------------------------- +template +void Matrix2::Orthonormalize() +{ + // Algorithm uses Gram-Schmidt orthogonalization. If 'this' matrix is + // M = [m0|m1], then orthonormal output matrix is Q = [q0|q1], + // + // q0 = m0/|m0| + // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| + // + // where |V| indicates length of vector V and A*B indicates dot + // product of vectors A and B. + + // compute q0 + Real fInvLength = Math::InvSqrt(Matrix2::m_afEntry[0] * Matrix2::m_afEntry[0] + + Matrix2::m_afEntry[2] * Matrix2::m_afEntry[2]); + + Matrix2::m_afEntry[0] *= fInvLength; + Matrix2::m_afEntry[2] *= fInvLength; + + // compute q1 + Real fDot0 = Matrix2::m_afEntry[0] * Matrix2::m_afEntry[1] + Matrix2::m_afEntry[2] * Matrix2::m_afEntry[3]; + Matrix2::m_afEntry[1] -= fDot0 * Matrix2::m_afEntry[0]; + Matrix2::m_afEntry[3] -= fDot0 * Matrix2::m_afEntry[2]; + + fInvLength = Math::InvSqrt(Matrix2::m_afEntry[1] * Matrix2::m_afEntry[1] + + Matrix2::m_afEntry[3] * Matrix2::m_afEntry[3]); + + Matrix2::m_afEntry[1] *= fInvLength; + Matrix2::m_afEntry[3] *= fInvLength; +} +//---------------------------------------------------------------------------- +template +void Matrix2::EigenDecomposition(Matrix2 &rkRot, Matrix2 &rkDiag) const +{ + Real fTrace = Matrix2::m_afEntry[0] + Matrix2::m_afEntry[3]; + Real fDiff = Matrix2::m_afEntry[0] - Matrix2::m_afEntry[3]; + Real fDiscr = Math::Sqrt(fDiff * fDiff + + ((Real)4.0) * Matrix2::m_afEntry[1] * Matrix2::m_afEntry[1]); + Real fEVal0 = ((Real)0.5) * (fTrace - fDiscr); + Real fEVal1 = ((Real)0.5) * (fTrace + fDiscr); + rkDiag.MakeDiagonal(fEVal0, fEVal1); + + Vector2 kRow0(Matrix2::m_afEntry[0] - fEVal0, Matrix2::m_afEntry[1]); + Vector2 kRow1(Matrix2::m_afEntry[1], Matrix2::m_afEntry[3] - fEVal0); + Real fLength0 = kRow0.Length(); + Real fLength1 = kRow1.Length(); + + if (fLength0 > fLength1) + { + if (fLength0 > Math::EPSILON) + { + rkRot.Matrix2::m_afEntry[0] = kRow0[1]; + rkRot.Matrix2::m_afEntry[1] = kRow0[0]; + rkRot.Matrix2::m_afEntry[2] = -kRow0[0]; + rkRot.Matrix2::m_afEntry[3] = kRow0[1]; + } + else + { + rkRot.MakeIdentity(); + } + } + else + { + if (fLength1 > Math::EPSILON) + { + rkRot.Matrix2::m_afEntry[0] = kRow1[1]; + rkRot.Matrix2::m_afEntry[1] = kRow1[0]; + rkRot.Matrix2::m_afEntry[2] = -kRow1[0]; + rkRot.Matrix2::m_afEntry[3] = kRow1[1]; + } + else + { + rkRot.MakeIdentity(); + } + } +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlMatrix3.cpp b/src/editors/xrECore/WildMagic/WmlMatrix3.cpp new file mode 100644 index 00000000000..2286feaefc6 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix3.cpp @@ -0,0 +1,36 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlMatrix3.h" +using namespace Wml; + +template <> +const Matrix3 Matrix3::ZERO( + 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f); +template <> +const Matrix3 Matrix3::IDENTITY( + 1.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 1.0f); + +template <> +const Matrix3 Matrix3::ZERO( + 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0); +template <> +const Matrix3 Matrix3::IDENTITY( + 1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0); diff --git a/src/editors/xrECore/WildMagic/WmlMatrix3.h b/src/editors/xrECore/WildMagic/WmlMatrix3.h new file mode 100644 index 00000000000..bf48019e32c --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix3.h @@ -0,0 +1,158 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLMATRIX3H +#define WMLMATRIX3H + +// The (x,y,z) coordinate system is assumed to be right-handed. Coordinate +// axis rotation matrices are of the form +// RX = 1 0 0 +// 0 cos(t) -sin(t) +// 0 sin(t) cos(t) +// where t > 0 indicates a counterclockwise rotation in the yz-plane +// RY = cos(t) 0 sin(t) +// 0 1 0 +// -sin(t) 0 cos(t) +// where t > 0 indicates a counterclockwise rotation in the zx-plane +// RZ = cos(t) -sin(t) 0 +// sin(t) cos(t) 0 +// 0 0 1 +// where t > 0 indicates a counterclockwise rotation in the xy-plane. + +#include "WmlMatrix.h" +#include "WmlVector3.h" + +namespace Wml +{ + + template + class Matrix3 : public Matrix<3, Real> + { + public: + // construction + Matrix3(); + Matrix3(const Matrix3 &rkM); + Matrix3(const Matrix<3, Real> &rkM); + + // input Mrc is in row r, column c. + Matrix3(Real fM00, Real fM01, Real fM02, + Real fM10, Real fM11, Real fM12, + Real fM20, Real fM21, Real fM22); + + // Create a matrix from an array of numbers. The input array is + // interpreted based on the Boolean input as + // true: entry[0..8]={m00,m01,m02,m10,m11,m12,m20,m21,m22} [row major] + // false: entry[0..8]={m00,m10,m20,m01,m11,m21,m02,m12,m22} [col major] + Matrix3(const Real afEntry[9], bool bRowMajor); + + // Create matrices based on vector input. The Boolean is interpreted as + // true: vectors are columns of the matrix + // false: vectors are rows of the matrix + Matrix3(const Vector3 &rkU, const Vector3 &rkV, + const Vector3 &rkW, bool bColumns); + Matrix3(const Vector3 *akV, bool bColumns); + + // create a tensor product U*V^T + Matrix3(const Vector3 &rkU, const Vector3 &rkV); + void MakeTensorProduct(const Vector3 &rkU, + const Vector3 &rkV); + + // create a diagonal matrix + Matrix3(Real fM00, Real fM11, Real fM22); + void MakeDiagonal(Real fM00, Real fM11, Real fM22); + + // Create rotation matrices (positive angle - counterclockwise). The + // angle must be in radians, not degrees. + Matrix3(const Vector3 &rkAxis, Real fAngle); + void FromAxisAngle(const Vector3 &rkAxis, Real fAngle); + + // assignment + Matrix3 &operator=(const Matrix3 &rkM); + Matrix3 &operator=(const Matrix<3, Real> &rkM); + + // matrix operations + Matrix3 Inverse() const; + Matrix3 Adjoint() const; + Real Determinant() const; + + // The matrix must be a rotation for these functions to be valid. The + // last function uses Gram-Schmidt orthonormalization applied to the + // columns of the rotation matrix. The angle must be in radians, not + // degrees. + void ToAxisAngle(Vector3 &rkAxis, Real &rfAngle) const; + void Orthonormalize(); + + // The matrix must be orthonormal. The decomposition is yaw*pitch*roll + // where yaw is rotation about the Up vector, pitch is rotation about the + // Right axis, and roll is rotation about the Direction axis. + bool ToEulerAnglesXYZ(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + bool ToEulerAnglesXZY(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + bool ToEulerAnglesYXZ(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + bool ToEulerAnglesYZX(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + bool ToEulerAnglesZXY(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + bool ToEulerAnglesZYX(Real &rfYAngle, Real &rfPAngle, + Real &rfRAngle) const; + void FromEulerAnglesXYZ(Real fYAngle, Real fPAngle, Real fRAngle); + void FromEulerAnglesXZY(Real fYAngle, Real fPAngle, Real fRAngle); + void FromEulerAnglesYXZ(Real fYAngle, Real fPAngle, Real fRAngle); + void FromEulerAnglesYZX(Real fYAngle, Real fPAngle, Real fRAngle); + void FromEulerAnglesZXY(Real fYAngle, Real fPAngle, Real fRAngle); + void FromEulerAnglesZYX(Real fYAngle, Real fPAngle, Real fRAngle); + + // SLERP (spherical linear interpolation) without quaternions. Computes + // R(t) = R0*(Transpose(R0)*R1)^t. If Q is a rotation matrix with + // unit-length axis U and angle A, then Q^t is a rotation matrix with + // unit-length axis U and rotation angle t*A. + static Matrix3 Slerp(Real fT, const Matrix3 &rkR0, const Matrix3 &rkR1); + + // The matrix must be symmetric. Factor M = R * D * R^T where + // R = [u0|u1|u2] is a rotation matrix with columns u0, u1, and u2 and + // D = diag(d0,d1,d2) is a diagonal matrix whose diagonal entries are d0, + // d1, and d2. The eigenvector u[i] corresponds to eigenvector d[i]. + // The eigenvalues are ordered as d0 <= d1 <= d2. + void EigenDecomposition(Matrix3 &rkRot, Matrix3 &rkDiag) const; + + // Singular value decomposition, M = L*S*R, where L and R are orthogonal + // and S is a diagonal matrix whose diagonal entries are nonnegative. + void SingularValueDecomposition(Matrix3 &rkL, Matrix3 &rkS, + Matrix3 &rkR) const; + void SingularValueComposition(const Matrix3 &rkL, const Matrix3 &rkS, + const Matrix3 &rkR); + + // factor M = Q*D*U with orthogonal Q, diagonal D, upper triangular U + void QDUDecomposition(Matrix3 &rkQ, Matrix3 &rkD, Matrix3 &rkU) const; + + // special matrices + WML_ITEM static const Matrix3 ZERO; + WML_ITEM static const Matrix3 IDENTITY; + + protected: + // support for eigendecomposition + void Tridiagonalize(Real afDiag[3], Real afSubDiag[3]); + bool QLAlgorithm(Real afDiag[3], Real afSubDiag[3]); + + // support for singular value decomposition + static void Bidiagonalize(Matrix3 &rkA, Matrix3 &rkL, Matrix3 &rkR); + static void GolubKahanStep(Matrix3 &rkA, Matrix3 &rkL, Matrix3 &rkR); + }; + +#include "WmlMatrix3.inl" + + typedef Matrix3 Matrix3f; + typedef Matrix3 Matrix3d; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlMatrix3.inl b/src/editors/xrECore/WildMagic/WmlMatrix3.inl new file mode 100644 index 00000000000..f8dbc06faad --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix3.inl @@ -0,0 +1,1517 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +Matrix3::Matrix3() +{ + // the matrix is uninitialized +} +//---------------------------------------------------------------------------- +template +Matrix3::Matrix3(const Matrix3 &rkM) +{ + memcpy(Matrix3::m_afEntry, rkM.Matrix3::m_afEntry, 9 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Matrix3::Matrix3(const Matrix<3, Real> &rkM) +{ + memcpy(Matrix3::m_afEntry, (const Real *)rkM, 9 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Matrix3 &Matrix3::operator=(const Matrix3 &rkM) +{ + memcpy(Matrix3::m_afEntry, rkM.Matrix3::m_afEntry, 9 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Matrix3 &Matrix3::operator=(const Matrix<3, Real> &rkM) +{ + memcpy(Matrix3::m_afEntry, (const Real *)rkM, 9 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Matrix3::Matrix3(Real fM00, Real fM01, Real fM02, Real fM10, + Real fM11, Real fM12, Real fM20, Real fM21, Real fM22) +{ + Matrix3::m_afEntry[0] = fM00; + Matrix3::m_afEntry[1] = fM01; + Matrix3::m_afEntry[2] = fM02; + Matrix3::m_afEntry[3] = fM10; + Matrix3::m_afEntry[4] = fM11; + Matrix3::m_afEntry[5] = fM12; + Matrix3::m_afEntry[6] = fM20; + Matrix3::m_afEntry[7] = fM21; + Matrix3::m_afEntry[8] = fM22; +} +//---------------------------------------------------------------------------- +template +Matrix3::Matrix3(const Real afEntry[9], bool bRowMajor) +{ + if (bRowMajor) + { + memcpy(Matrix3::m_afEntry, afEntry, 9 * sizeof(Real)); + } + else + { + Matrix3::m_afEntry[0] = afEntry[0]; + Matrix3::m_afEntry[1] = afEntry[3]; + Matrix3::m_afEntry[2] = afEntry[6]; + Matrix3::m_afEntry[3] = afEntry[1]; + Matrix3::m_afEntry[4] = afEntry[4]; + Matrix3::m_afEntry[5] = afEntry[7]; + Matrix3::m_afEntry[6] = afEntry[2]; + Matrix3::m_afEntry[7] = afEntry[5]; + Matrix3::m_afEntry[8] = afEntry[8]; + } +} +//---------------------------------------------------------------------------- +template +Matrix3::Matrix3(const Vector3 &rkU, + const Vector3 &rkV, const Vector3 &rkW, bool bColumns) +{ + if (bColumns) + { + Matrix3::m_afEntry[0] = rkU[0]; + Matrix3::m_afEntry[1] = rkV[0]; + Matrix3::m_afEntry[2] = rkW[0]; + Matrix3::m_afEntry[3] = rkU[1]; + Matrix3::m_afEntry[4] = rkV[1]; + Matrix3::m_afEntry[5] = rkW[1]; + Matrix3::m_afEntry[6] = rkU[2]; + Matrix3::m_afEntry[7] = rkV[2]; + Matrix3::m_afEntry[8] = rkW[2]; + } + else + { + Matrix3::m_afEntry[0] = rkU[0]; + Matrix3::m_afEntry[1] = rkU[1]; + Matrix3::m_afEntry[2] = rkU[2]; + Matrix3::m_afEntry[3] = rkV[0]; + Matrix3::m_afEntry[4] = rkV[1]; + Matrix3::m_afEntry[5] = rkV[2]; + Matrix3::m_afEntry[6] = rkW[0]; + Matrix3::m_afEntry[7] = rkW[1]; + Matrix3::m_afEntry[8] = rkW[2]; + } +} +//---------------------------------------------------------------------------- +template +Matrix3::Matrix3(const Vector3 *akV, bool bColumns) +{ + if (bColumns) + { + Matrix3::m_afEntry[0] = akV[0][0]; + Matrix3::m_afEntry[1] = akV[1][0]; + Matrix3::m_afEntry[2] = akV[2][0]; + Matrix3::m_afEntry[3] = akV[0][1]; + Matrix3::m_afEntry[4] = akV[1][1]; + Matrix3::m_afEntry[5] = akV[2][1]; + Matrix3::m_afEntry[6] = akV[0][2]; + Matrix3::m_afEntry[7] = akV[1][2]; + Matrix3::m_afEntry[8] = akV[2][2]; + } + else + { + Matrix3::m_afEntry[0] = akV[0][0]; + Matrix3::m_afEntry[1] = akV[0][1]; + Matrix3::m_afEntry[2] = akV[0][2]; + Matrix3::m_afEntry[3] = akV[1][0]; + Matrix3::m_afEntry[4] = akV[1][1]; + Matrix3::m_afEntry[5] = akV[1][2]; + Matrix3::m_afEntry[6] = akV[2][0]; + Matrix3::m_afEntry[7] = akV[2][1]; + Matrix3::m_afEntry[8] = akV[2][2]; + } +} +//---------------------------------------------------------------------------- +template +Matrix3::Matrix3(const Vector3 &rkU, + const Vector3 &rkV) +{ + MakeTensorProduct(rkU, rkV); +} +//---------------------------------------------------------------------------- +template +void Matrix3::MakeTensorProduct(const Vector3 &rkU, + const Vector3 &rkV) +{ + Matrix3::m_afEntry[0] = rkU[0] * rkV[0]; + Matrix3::m_afEntry[1] = rkU[0] * rkV[1]; + Matrix3::m_afEntry[2] = rkU[0] * rkV[2]; + Matrix3::m_afEntry[3] = rkU[1] * rkV[0]; + Matrix3::m_afEntry[4] = rkU[1] * rkV[1]; + Matrix3::m_afEntry[5] = rkU[1] * rkV[2]; + Matrix3::m_afEntry[6] = rkU[2] * rkV[0]; + Matrix3::m_afEntry[7] = rkU[2] * rkV[1]; + Matrix3::m_afEntry[8] = rkU[2] * rkV[2]; +} +//---------------------------------------------------------------------------- +template +Matrix3::Matrix3(Real fM00, Real fM11, Real fM22) +{ + MakeDiagonal(fM00, fM11, fM22); +} +//---------------------------------------------------------------------------- +template +void Matrix3::MakeDiagonal(Real fM00, Real fM11, Real fM22) +{ + Matrix3::m_afEntry[0] = fM00; + Matrix3::m_afEntry[1] = (Real)0.0; + Matrix3::m_afEntry[2] = (Real)0.0; + Matrix3::m_afEntry[3] = (Real)0.0; + Matrix3::m_afEntry[4] = fM11; + Matrix3::m_afEntry[5] = (Real)0.0; + Matrix3::m_afEntry[6] = (Real)0.0; + Matrix3::m_afEntry[7] = (Real)0.0; + Matrix3::m_afEntry[8] = fM22; +} +//---------------------------------------------------------------------------- +template +Matrix3::Matrix3(const Vector3 &rkAxis, Real fAngle) +{ + FromAxisAngle(rkAxis, fAngle); +} +//---------------------------------------------------------------------------- +template +void Matrix3::FromAxisAngle(const Vector3 &rkAxis, Real fAngle) +{ + Real fCos = Math::Cos(fAngle); + Real fSin = Math::Sin(fAngle); + Real fOneMinusCos = ((Real)1.0) - fCos; + Real fX2 = rkAxis[0] * rkAxis[0]; + Real fY2 = rkAxis[1] * rkAxis[1]; + Real fZ2 = rkAxis[2] * rkAxis[2]; + Real fXYM = rkAxis[0] * rkAxis[1] * fOneMinusCos; + Real fXZM = rkAxis[0] * rkAxis[2] * fOneMinusCos; + Real fYZM = rkAxis[1] * rkAxis[2] * fOneMinusCos; + Real fXSin = rkAxis[0] * fSin; + Real fYSin = rkAxis[1] * fSin; + Real fZSin = rkAxis[2] * fSin; + + Matrix3::m_afEntry[0] = fX2 * fOneMinusCos + fCos; + Matrix3::m_afEntry[1] = fXYM - fZSin; + Matrix3::m_afEntry[2] = fXZM + fYSin; + Matrix3::m_afEntry[3] = fXYM + fZSin; + Matrix3::m_afEntry[4] = fY2 * fOneMinusCos + fCos; + Matrix3::m_afEntry[5] = fYZM - fXSin; + Matrix3::m_afEntry[6] = fXZM - fYSin; + Matrix3::m_afEntry[7] = fYZM + fXSin; + Matrix3::m_afEntry[8] = fZ2 * fOneMinusCos + fCos; +} +//---------------------------------------------------------------------------- +template +Matrix3 Matrix3::Inverse() const +{ + // Invert a 3x3 using cofactors. This is faster than using a generic + // Gaussian elimination because of the loop overhead of such a method. + + Matrix3 kInverse; + + kInverse[0][0] = Matrix3::m_afEntry[4] * Matrix3::m_afEntry[8] - Matrix3::m_afEntry[5] * Matrix3::m_afEntry[7]; + kInverse[0][1] = Matrix3::m_afEntry[2] * Matrix3::m_afEntry[7] - Matrix3::m_afEntry[1] * Matrix3::m_afEntry[8]; + kInverse[0][2] = Matrix3::m_afEntry[1] * Matrix3::m_afEntry[5] - Matrix3::m_afEntry[2] * Matrix3::m_afEntry[4]; + kInverse[1][0] = Matrix3::m_afEntry[5] * Matrix3::m_afEntry[6] - Matrix3::m_afEntry[3] * Matrix3::m_afEntry[8]; + kInverse[1][1] = Matrix3::m_afEntry[0] * Matrix3::m_afEntry[8] - Matrix3::m_afEntry[2] * Matrix3::m_afEntry[6]; + kInverse[1][2] = Matrix3::m_afEntry[2] * Matrix3::m_afEntry[3] - Matrix3::m_afEntry[0] * Matrix3::m_afEntry[5]; + kInverse[2][0] = Matrix3::m_afEntry[3] * Matrix3::m_afEntry[7] - Matrix3::m_afEntry[4] * Matrix3::m_afEntry[6]; + kInverse[2][1] = Matrix3::m_afEntry[1] * Matrix3::m_afEntry[6] - Matrix3::m_afEntry[0] * Matrix3::m_afEntry[7]; + kInverse[2][2] = Matrix3::m_afEntry[0] * Matrix3::m_afEntry[4] - Matrix3::m_afEntry[1] * Matrix3::m_afEntry[3]; + + Real fDet = Matrix3::m_afEntry[0] * kInverse[0][0] + Matrix3::m_afEntry[1] * kInverse[1][0] + + Matrix3::m_afEntry[2] * kInverse[2][0]; + + if (Math::FAbs(fDet) <= Math::EPSILON) + return Matrix3::ZERO; + + kInverse /= fDet; + return kInverse; +} +//---------------------------------------------------------------------------- +template +Matrix3 Matrix3::Adjoint() const +{ + Matrix3 kAdjoint; + + kAdjoint[0][0] = Matrix3::m_afEntry[4] * Matrix3::m_afEntry[8] - Matrix3::m_afEntry[5] * Matrix3::m_afEntry[7]; + kAdjoint[0][1] = Matrix3::m_afEntry[2] * Matrix3::m_afEntry[7] - Matrix3::m_afEntry[1] * Matrix3::m_afEntry[8]; + kAdjoint[0][2] = Matrix3::m_afEntry[1] * Matrix3::m_afEntry[5] - Matrix3::m_afEntry[2] * Matrix3::m_afEntry[4]; + kAdjoint[1][0] = Matrix3::m_afEntry[5] * Matrix3::m_afEntry[6] - Matrix3::m_afEntry[3] * Matrix3::m_afEntry[8]; + kAdjoint[1][1] = Matrix3::m_afEntry[0] * Matrix3::m_afEntry[8] - Matrix3::m_afEntry[2] * Matrix3::m_afEntry[6]; + kAdjoint[1][2] = Matrix3::m_afEntry[2] * Matrix3::m_afEntry[3] - Matrix3::m_afEntry[0] * Matrix3::m_afEntry[5]; + kAdjoint[2][0] = Matrix3::m_afEntry[3] * Matrix3::m_afEntry[7] - Matrix3::m_afEntry[4] * Matrix3::m_afEntry[6]; + kAdjoint[2][1] = Matrix3::m_afEntry[1] * Matrix3::m_afEntry[6] - Matrix3::m_afEntry[0] * Matrix3::m_afEntry[7]; + kAdjoint[2][2] = Matrix3::m_afEntry[0] * Matrix3::m_afEntry[4] - Matrix3::m_afEntry[1] * Matrix3::m_afEntry[3]; + + return kAdjoint; +} +//---------------------------------------------------------------------------- +template +Real Matrix3::Determinant() const +{ + Real fCo00 = Matrix3::m_afEntry[4] * Matrix3::m_afEntry[8] - Matrix3::m_afEntry[5] * Matrix3::m_afEntry[7]; + Real fCo10 = Matrix3::m_afEntry[5] * Matrix3::m_afEntry[6] - Matrix3::m_afEntry[3] * Matrix3::m_afEntry[8]; + Real fCo20 = Matrix3::m_afEntry[3] * Matrix3::m_afEntry[7] - Matrix3::m_afEntry[4] * Matrix3::m_afEntry[6]; + Real fDet = Matrix3::m_afEntry[0] * fCo00 + Matrix3::m_afEntry[1] * fCo10 + Matrix3::m_afEntry[2] * fCo20; + return fDet; +} +//---------------------------------------------------------------------------- +template +void Matrix3::ToAxisAngle(Vector3 &rkAxis, Real &rfAngle) const +{ + // Let (x,y,z) be the unit-length axis and let A be an angle of rotation. + // The rotation matrix is R = I + sin(A)*P + (1-cos(A))*P^2 where + // I is the identity and + // + // +- -+ + // P = | 0 -z +y | + // | +z 0 -x | + // | -y +x 0 | + // +- -+ + // + // If A > 0, R represents a counterclockwise rotation about the axis in + // the sense of looking from the tip of the axis vector towards the + // origin. Some algebra will show that + // + // cos(A) = (trace(R)-1)/2 and R - R^t = 2*sin(A)*P + // + // In the event that A = pi, R-R^t = 0 which prevents us from extracting + // the axis through P. Instead note that R = I+2*P^2 when A = pi, so + // P^2 = (R-I)/2. The diagonal entries of P^2 are x^2-1, y^2-1, and + // z^2-1. We can solve these for axis (x,y,z). Because the angle is pi, + // it does not matter which sign you choose on the square roots. + + Real fTrace = Matrix3::m_afEntry[0] + Matrix3::m_afEntry[4] + Matrix3::m_afEntry[8]; + Real fCos = ((Real)0.5) * (fTrace - ((Real)1.0)); + rfAngle = Math::ACos(fCos); // in [0,PI] + + if (rfAngle > (Real)0.0) + { + if (rfAngle < Math::_PI) + { + rkAxis[0] = Matrix3::m_afEntry[7] - Matrix3::m_afEntry[5]; + rkAxis[1] = Matrix3::m_afEntry[2] - Matrix3::m_afEntry[6]; + rkAxis[2] = Matrix3::m_afEntry[3] - Matrix3::m_afEntry[1]; + rkAxis.Normalize(); + } + else + { + // angle is PI + Real fHalfInverse; + if (Matrix3::m_afEntry[0] >= Matrix3::m_afEntry[4]) + { + // r00 >= r11 + if (Matrix3::m_afEntry[0] >= Matrix3::m_afEntry[8]) + { + // r00 is maximum diagonal term + rkAxis[0] = ((Real)0.5) * Math::Sqrt(Matrix3::m_afEntry[0] - + Matrix3::m_afEntry[4] - Matrix3::m_afEntry[8] + (Real)1.0); + fHalfInverse = ((Real)0.5) / rkAxis[0]; + rkAxis[1] = fHalfInverse * Matrix3::m_afEntry[1]; + rkAxis[2] = fHalfInverse * Matrix3::m_afEntry[2]; + } + else + { + // r22 is maximum diagonal term + rkAxis[2] = ((Real)0.5) * Math::Sqrt(Matrix3::m_afEntry[8] - + Matrix3::m_afEntry[0] - Matrix3::m_afEntry[4] + (Real)1.0); + fHalfInverse = ((Real)0.5) / rkAxis[2]; + rkAxis[0] = fHalfInverse * Matrix3::m_afEntry[2]; + rkAxis[1] = fHalfInverse * Matrix3::m_afEntry[5]; + } + } + else + { + // r11 > r00 + if (Matrix3::m_afEntry[4] >= Matrix3::m_afEntry[8]) + { + // r11 is maximum diagonal term + rkAxis[1] = ((Real)0.5) * Math::Sqrt(Matrix3::m_afEntry[4] - + Matrix3::m_afEntry[0] - Matrix3::m_afEntry[8] + (Real)1.0); + fHalfInverse = ((Real)0.5) / rkAxis[1]; + rkAxis[0] = fHalfInverse * Matrix3::m_afEntry[1]; + rkAxis[2] = fHalfInverse * Matrix3::m_afEntry[5]; + } + else + { + // r22 is maximum diagonal term + rkAxis[2] = ((Real)0.5) * Math::Sqrt(Matrix3::m_afEntry[8] - + Matrix3::m_afEntry[0] - Matrix3::m_afEntry[4] + (Real)1.0); + fHalfInverse = ((Real)0.5) / rkAxis[2]; + rkAxis[0] = fHalfInverse * Matrix3::m_afEntry[2]; + rkAxis[1] = fHalfInverse * Matrix3::m_afEntry[5]; + } + } + } + } + else + { + // The angle is 0 and the matrix is the identity. Any axis will + // work, so just use the x-axis. + rkAxis[0] = (Real)1.0; + rkAxis[1] = (Real)0.0; + rkAxis[2] = (Real)0.0; + } +} +//---------------------------------------------------------------------------- +template +void Matrix3::Orthonormalize() +{ + // Algorithm uses Gram-Schmidt orthogonalization. If 'this' matrix is + // M = [m0|m1|m2], then orthonormal output matrix is Q = [q0|q1|q2], + // + // q0 = m0/|m0| + // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| + // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| + // + // where |V| indicates length of vector V and A*B indicates dot + // product of vectors A and B. + + // compute q0 + Real fInvLength = Math::InvSqrt(Matrix3::m_afEntry[0] * Matrix3::m_afEntry[0] + + Matrix3::m_afEntry[3] * Matrix3::m_afEntry[3] + Matrix3::m_afEntry[6] * Matrix3::m_afEntry[6]); + + Matrix3::m_afEntry[0] *= fInvLength; + Matrix3::m_afEntry[3] *= fInvLength; + Matrix3::m_afEntry[6] *= fInvLength; + + // compute q1 + Real fDot0 = Matrix3::m_afEntry[0] * Matrix3::m_afEntry[1] + Matrix3::m_afEntry[3] * Matrix3::m_afEntry[4] + + Matrix3::m_afEntry[6] * Matrix3::m_afEntry[7]; + + Matrix3::m_afEntry[1] -= fDot0 * Matrix3::m_afEntry[0]; + Matrix3::m_afEntry[4] -= fDot0 * Matrix3::m_afEntry[3]; + Matrix3::m_afEntry[7] -= fDot0 * Matrix3::m_afEntry[6]; + + fInvLength = Math::InvSqrt(Matrix3::m_afEntry[1] * Matrix3::m_afEntry[1] + + Matrix3::m_afEntry[4] * Matrix3::m_afEntry[4] + Matrix3::m_afEntry[7] * Matrix3::m_afEntry[7]); + + Matrix3::m_afEntry[1] *= fInvLength; + Matrix3::m_afEntry[4] *= fInvLength; + Matrix3::m_afEntry[7] *= fInvLength; + + // compute q2 + Real fDot1 = Matrix3::m_afEntry[1] * Matrix3::m_afEntry[2] + Matrix3::m_afEntry[4] * Matrix3::m_afEntry[5] + + Matrix3::m_afEntry[7] * Matrix3::m_afEntry[8]; + + fDot0 = Matrix3::m_afEntry[0] * Matrix3::m_afEntry[2] + Matrix3::m_afEntry[3] * Matrix3::m_afEntry[5] + + Matrix3::m_afEntry[6] * Matrix3::m_afEntry[8]; + + Matrix3::m_afEntry[2] -= fDot0 * Matrix3::m_afEntry[0] + fDot1 * Matrix3::m_afEntry[1]; + Matrix3::m_afEntry[5] -= fDot0 * Matrix3::m_afEntry[3] + fDot1 * Matrix3::m_afEntry[4]; + Matrix3::m_afEntry[8] -= fDot0 * Matrix3::m_afEntry[6] + fDot1 * Matrix3::m_afEntry[7]; + + fInvLength = Math::InvSqrt(Matrix3::m_afEntry[2] * Matrix3::m_afEntry[2] + + Matrix3::m_afEntry[5] * Matrix3::m_afEntry[5] + Matrix3::m_afEntry[8] * Matrix3::m_afEntry[8]); + + Matrix3::m_afEntry[2] *= fInvLength; + Matrix3::m_afEntry[5] *= fInvLength; + Matrix3::m_afEntry[8] *= fInvLength; +} +//---------------------------------------------------------------------------- +template +bool Matrix3::ToEulerAnglesXYZ(Real &rfXAngle, Real &rfYAngle, + Real &rfZAngle) const +{ + // rot = cy*cz -cy*sz sy + // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx + // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy + + if (Matrix3::m_afEntry[2] < (Real)1.0) + { + if (Matrix3::m_afEntry[2] > -(Real)1.0) + { + rfXAngle = Math::ATan2(-Matrix3::m_afEntry[5], Matrix3::m_afEntry[8]); + rfYAngle = (Real)asin((double)Matrix3::m_afEntry[2]); + rfZAngle = Math::ATan2(-Matrix3::m_afEntry[1], Matrix3::m_afEntry[0]); + return true; + } + else + { + // WARNING. Not unique. XA - ZA = -atan2(r10,r11) + rfXAngle = -Math::ATan2(Matrix3::m_afEntry[3], Matrix3::m_afEntry[4]); + rfYAngle = -Math::HALF_PI; + rfZAngle = (Real)0.0; + return false; + } + } + else + { + // WARNING. Not unique. XAngle + ZAngle = atan2(r10,r11) + rfXAngle = Math::ATan2(Matrix3::m_afEntry[3], Matrix3::m_afEntry[4]); + rfYAngle = Math::HALF_PI; + rfZAngle = (Real)0.0; + return false; + } +} +//---------------------------------------------------------------------------- +template +bool Matrix3::ToEulerAnglesXZY(Real &rfXAngle, Real &rfZAngle, + Real &rfYAngle) const +{ + // rot = cy*cz -sz cz*sy + // sx*sy+cx*cy*sz cx*cz -cy*sx+cx*sy*sz + // -cx*sy+cy*sx*sz cz*sx cx*cy+sx*sy*sz + + if (Matrix3::m_afEntry[1] < (Real)1.0) + { + if (Matrix3::m_afEntry[1] > -(Real)1.0) + { + rfXAngle = Math::ATan2(Matrix3::m_afEntry[7], Matrix3::m_afEntry[4]); + rfZAngle = (Real)asin(-(double)Matrix3::m_afEntry[1]); + rfYAngle = Math::ATan2(Matrix3::m_afEntry[2], Matrix3::m_afEntry[0]); + return true; + } + else + { + // WARNING. Not unique. XA - YA = atan2(r20,r22) + rfXAngle = Math::ATan2(Matrix3::m_afEntry[6], Matrix3::m_afEntry[8]); + rfZAngle = Math::HALF_PI; + rfYAngle = (Real)0.0; + return false; + } + } + else + { + // WARNING. Not unique. XA + YA = atan2(-r20,r22) + rfXAngle = Math::ATan2(-Matrix3::m_afEntry[6], Matrix3::m_afEntry[8]); + rfZAngle = -Math::HALF_PI; + rfYAngle = (Real)0.0; + return false; + } +} +//---------------------------------------------------------------------------- +template +bool Matrix3::ToEulerAnglesYXZ(Real &rfYAngle, Real &rfXAngle, + Real &rfZAngle) const +{ + // rot = cy*cz+sx*sy*sz cz*sx*sy-cy*sz cx*sy + // cx*sz cx*cz -sx + // -cz*sy+cy*sx*sz cy*cz*sx+sy*sz cx*cy + + if (Matrix3::m_afEntry[5] < (Real)1.0) + { + if (Matrix3::m_afEntry[5] > -(Real)1.0) + { + rfYAngle = Math::ATan2(Matrix3::m_afEntry[2], Matrix3::m_afEntry[8]); + rfXAngle = (Real)asin(-(double)Matrix3::m_afEntry[5]); + rfZAngle = Math::ATan2(Matrix3::m_afEntry[3], Matrix3::m_afEntry[4]); + return true; + } + else + { + // WARNING. Not unique. YA - ZA = atan2(r01,r00) + rfYAngle = Math::ATan2(Matrix3::m_afEntry[1], Matrix3::m_afEntry[0]); + rfXAngle = Math::HALF_PI; + rfZAngle = (Real)0.0; + return false; + } + } + else + { + // WARNING. Not unique. YA + ZA = atan2(-r01,r00) + rfYAngle = Math::ATan2(-Matrix3::m_afEntry[1], Matrix3::m_afEntry[0]); + rfXAngle = -Math::HALF_PI; + rfZAngle = (Real)0.0; + return false; + } +} +//---------------------------------------------------------------------------- +template +bool Matrix3::ToEulerAnglesYZX(Real &rfYAngle, Real &rfZAngle, + Real &rfXAngle) const +{ + // rot = cy*cz sx*sy-cx*cy*sz cx*sy+cy*sx*sz + // sz cx*cz -cz*sx + // -cz*sy cy*sx+cx*sy*sz cx*cy-sx*sy*sz + + if (Matrix3::m_afEntry[3] < (Real)1.0) + { + if (Matrix3::m_afEntry[3] > -(Real)1.0) + { + rfYAngle = Math::ATan2(-Matrix3::m_afEntry[6], Matrix3::m_afEntry[0]); + rfZAngle = (Real)asin((double)Matrix3::m_afEntry[3]); + rfXAngle = Math::ATan2(-Matrix3::m_afEntry[5], Matrix3::m_afEntry[4]); + return true; + } + else + { + // WARNING. Not unique. YA - XA = -atan2(r21,r22); + rfYAngle = -Math::ATan2(Matrix3::m_afEntry[7], Matrix3::m_afEntry[8]); + rfZAngle = -Math::HALF_PI; + rfXAngle = (Real)0.0; + return false; + } + } + else + { + // WARNING. Not unique. YA + XA = atan2(r21,r22) + rfYAngle = Math::ATan2(Matrix3::m_afEntry[7], Matrix3::m_afEntry[8]); + rfZAngle = Math::HALF_PI; + rfXAngle = (Real)0.0; + return false; + } +} +//---------------------------------------------------------------------------- +template +bool Matrix3::ToEulerAnglesZXY(Real &rfZAngle, Real &rfXAngle, + Real &rfYAngle) const +{ + // rot = cy*cz-sx*sy*sz -cx*sz cz*sy+cy*sx*sz + // cz*sx*sy+cy*sz cx*cz -cy*cz*sx+sy*sz + // -cx*sy sx cx*cy + + if (Matrix3::m_afEntry[7] < (Real)1.0) + { + if (Matrix3::m_afEntry[7] > -(Real)1.0) + { + rfZAngle = Math::ATan2(-Matrix3::m_afEntry[1], Matrix3::m_afEntry[4]); + rfXAngle = (Real)asin((double)Matrix3::m_afEntry[7]); + rfYAngle = Math::ATan2(-Matrix3::m_afEntry[6], Matrix3::m_afEntry[8]); + return true; + } + else + { + // WARNING. Not unique. ZA - YA = -atan(r02,r00) + rfZAngle = -Math::ATan2(Matrix3::m_afEntry[2], Matrix3::m_afEntry[0]); + rfXAngle = -Math::HALF_PI; + rfYAngle = (Real)0.0; + return false; + } + } + else + { + // WARNING. Not unique. ZA + YA = atan2(r02,r00) + rfZAngle = Math::ATan2(Matrix3::m_afEntry[2], Matrix3::m_afEntry[0]); + rfXAngle = Math::HALF_PI; + rfYAngle = (Real)0.0; + return false; + } +} +//---------------------------------------------------------------------------- +template +bool Matrix3::ToEulerAnglesZYX(Real &rfZAngle, Real &rfYAngle, + Real &rfXAngle) const +{ + // rot = cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz + // cy*sz cx*cz+sx*sy*sz -cz*sx+cx*sy*sz + // -sy cy*sx cx*cy + + if (Matrix3::m_afEntry[6] < (Real)1.0) + { + if (Matrix3::m_afEntry[6] > -(Real)1.0) + { + rfZAngle = Math::ATan2(Matrix3::m_afEntry[3], Matrix3::m_afEntry[0]); + rfYAngle = (Real)asin(-(double)Matrix3::m_afEntry[6]); + rfXAngle = Math::ATan2(Matrix3::m_afEntry[7], Matrix3::m_afEntry[8]); + return true; + } + else + { + // WARNING. Not unique. ZA - XA = -atan2(r01,r02) + rfZAngle = -Math::ATan2(Matrix3::m_afEntry[1], Matrix3::m_afEntry[2]); + rfYAngle = Math::HALF_PI; + rfXAngle = (Real)0.0; + return false; + } + } + else + { + // WARNING. Not unique. ZA + XA = atan2(-r01,-r02) + rfZAngle = Math::ATan2(-Matrix3::m_afEntry[1], -Matrix3::m_afEntry[2]); + rfYAngle = -Math::HALF_PI; + rfXAngle = (Real)0.0; + return false; + } +} +//---------------------------------------------------------------------------- +template +void Matrix3::FromEulerAnglesXYZ(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kXMat( + (Real)1.0, (Real)0.0, (Real)0.0, + (Real)0.0, fCos, -fSin, + (Real)0.0, fSin, fCos); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kYMat( + fCos, (Real)0.0, fSin, + (Real)0.0, (Real)1.0, (Real)0.0, + -fSin, (Real)0.0, fCos); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kZMat( + fCos, -fSin, (Real)0.0, + fSin, fCos, (Real)0.0, + (Real)0.0, (Real)0.0, (Real)1.0); + + *this = kXMat * (kYMat * kZMat); +} +//---------------------------------------------------------------------------- +template +void Matrix3::FromEulerAnglesXZY(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kXMat( + (Real)1.0, (Real)0.0, (Real)0.0, + (Real)0.0, fCos, -fSin, + (Real)0.0, fSin, fCos); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kZMat( + fCos, -fSin, (Real)0.0, + fSin, fCos, (Real)0.0, + (Real)0.0, (Real)0.0, (Real)1.0); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kYMat( + fCos, (Real)0.0, fSin, + (Real)0.0, (Real)1.0, (Real)0.0, + -fSin, (Real)0.0, fCos); + + *this = kXMat * (kZMat * kYMat); +} +//---------------------------------------------------------------------------- +template +void Matrix3::FromEulerAnglesYXZ(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kYMat( + fCos, (Real)0.0, fSin, + (Real)0.0, (Real)1.0, (Real)0.0, + -fSin, (Real)0.0, fCos); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kXMat( + (Real)1.0, (Real)0.0, (Real)0.0, + (Real)0.0, fCos, -fSin, + (Real)0.0, fSin, fCos); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kZMat( + fCos, -fSin, (Real)0.0, + fSin, fCos, (Real)0.0, + (Real)0.0, (Real)0.0, (Real)1.0); + + *this = kYMat * (kXMat * kZMat); +} +//---------------------------------------------------------------------------- +template +void Matrix3::FromEulerAnglesYZX(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kYMat( + fCos, (Real)0.0, fSin, + (Real)0.0, (Real)1.0, (Real)0.0, + -fSin, (Real)0.0, fCos); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kZMat( + fCos, -fSin, (Real)0.0, + fSin, fCos, (Real)0.0, + (Real)0.0, (Real)0.0, (Real)1.0); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kXMat( + (Real)1.0, (Real)0.0, (Real)0.0, + (Real)0.0, fCos, -fSin, + (Real)0.0, fSin, fCos); + + *this = kYMat * (kZMat * kXMat); +} +//---------------------------------------------------------------------------- +template +void Matrix3::FromEulerAnglesZXY(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kZMat( + fCos, -fSin, (Real)0.0, + fSin, fCos, (Real)0.0, + (Real)0.0, (Real)0.0, (Real)1.0); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kXMat( + (Real)1.0, (Real)0.0, (Real)0.0, + (Real)0.0, fCos, -fSin, + (Real)0.0, fSin, fCos); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kYMat( + fCos, (Real)0.0, fSin, + (Real)0.0, (Real)1.0, (Real)0.0, + -fSin, (Real)0.0, fCos); + + *this = kZMat * (kXMat * kYMat); +} +//---------------------------------------------------------------------------- +template +void Matrix3::FromEulerAnglesZYX(Real fYAngle, Real fPAngle, + Real fRAngle) +{ + Real fCos, fSin; + + fCos = Math::Cos(fYAngle); + fSin = Math::Sin(fYAngle); + Matrix3 kZMat( + fCos, -fSin, (Real)0.0, + fSin, fCos, (Real)0.0, + (Real)0.0, (Real)0.0, (Real)1.0); + + fCos = Math::Cos(fPAngle); + fSin = Math::Sin(fPAngle); + Matrix3 kYMat( + fCos, (Real)0.0, fSin, + (Real)0.0, (Real)1.0, (Real)0.0, + -fSin, (Real)0.0, fCos); + + fCos = Math::Cos(fRAngle); + fSin = Math::Sin(fRAngle); + Matrix3 kXMat( + (Real)1.0, (Real)0.0, (Real)0.0, + (Real)0.0, fCos, -fSin, + (Real)0.0, fSin, fCos); + + *this = kZMat * (kYMat * kXMat); +} +//---------------------------------------------------------------------------- +template +Matrix3 Matrix3::Slerp(Real fT, const Matrix3 &rkR0, + const Matrix3 &rkR1) +{ + Vector3 kAxis; + Real fAngle; + Matrix3 kProd = rkR0.TransposeTimes(rkR1); + kProd.ToAxisAngle(kAxis, fAngle); + return rkR0 * Matrix3(kAxis, fT * fAngle); +} +//---------------------------------------------------------------------------- +template +void Matrix3::Tridiagonalize(Real afDiag[3], Real afSubDiag[3]) +{ + // Householder reduction T = Q^t M Q + // Input: + // mat, symmetric 3x3 matrix M + // Output: + // mat, orthogonal matrix Q (a reflection) + // diag, diagonal entries of T + // subd, subdiagonal entries of T (T is symmetric) + + Real fA = Matrix3::m_afEntry[0]; + Real fB = Matrix3::m_afEntry[1]; + Real fC = Matrix3::m_afEntry[2]; + Real fD = Matrix3::m_afEntry[4]; + Real fE = Matrix3::m_afEntry[5]; + Real fF = Matrix3::m_afEntry[8]; + + afDiag[0] = fA; + afSubDiag[2] = (Real)0.0; + if (Math::FAbs(fC) >= Math::EPSILON) + { + Real fLength = Math::Sqrt(fB * fB + fC * fC); + Real fInvLength = ((Real)1.0) / fLength; + fB *= fInvLength; + fC *= fInvLength; + Real fQ = ((Real)2.0) * fB * fE + fC * (fF - fD); + afDiag[1] = fD + fC * fQ; + afDiag[2] = fF - fC * fQ; + afSubDiag[0] = fLength; + afSubDiag[1] = fE - fB * fQ; + + Matrix3::m_afEntry[0] = (Real)1.0; + Matrix3::m_afEntry[1] = (Real)0.0; + Matrix3::m_afEntry[2] = (Real)0.0; + Matrix3::m_afEntry[3] = (Real)0.0; + Matrix3::m_afEntry[4] = fB; + Matrix3::m_afEntry[5] = fC; + Matrix3::m_afEntry[6] = (Real)0.0; + Matrix3::m_afEntry[7] = fC; + Matrix3::m_afEntry[8] = -fB; + } + else + { + afDiag[1] = fD; + afDiag[2] = fF; + afSubDiag[0] = fB; + afSubDiag[1] = fE; + + Matrix3::m_afEntry[0] = (Real)1.0; + Matrix3::m_afEntry[1] = (Real)0.0; + Matrix3::m_afEntry[2] = (Real)0.0; + Matrix3::m_afEntry[3] = (Real)0.0; + Matrix3::m_afEntry[4] = (Real)1.0; + Matrix3::m_afEntry[5] = (Real)0.0; + Matrix3::m_afEntry[6] = (Real)0.0; + Matrix3::m_afEntry[7] = (Real)0.0; + Matrix3::m_afEntry[8] = -(Real)1.0; + } +} +//---------------------------------------------------------------------------- +template +bool Matrix3::QLAlgorithm(Real afDiag[3], Real afSubDiag[3]) +{ + // QL iteration with implicit shifting to reduce matrix from tridiagonal + // to diagonal + + for (int i0 = 0; i0 < 3; i0++) + { + const int iMaxIter = 32; + int iIter; + for (iIter = 0; iIter < iMaxIter; iIter++) + { + int i1; + for (i1 = i0; i1 <= 1; i1++) + { + Real fSum = Math::FAbs(afDiag[i1]) + + Math::FAbs(afDiag[i1 + 1]); + if (Math::FAbs(afSubDiag[i1]) + fSum == fSum) + break; + } + if (i1 == i0) + break; + + Real fTmp0 = (afDiag[i0 + 1] - afDiag[i0]) / + (((Real)2.0) * afSubDiag[i0]); + Real fTmp1 = Math::Sqrt(fTmp0 * fTmp0 + (Real)1.0); + if (fTmp0 < (Real)0.0) + fTmp0 = afDiag[i1] - afDiag[i0] + afSubDiag[i0] / (fTmp0 - fTmp1); + else + fTmp0 = afDiag[i1] - afDiag[i0] + afSubDiag[i0] / (fTmp0 + fTmp1); + Real fSin = (Real)1.0; + Real fCos = (Real)1.0; + Real fTmp2 = (Real)0.0; + for (int i2 = i1 - 1; i2 >= i0; i2--) + { + Real fTmp3 = fSin * afSubDiag[i2]; + Real fTmp4 = fCos * afSubDiag[i2]; + if (Math::FAbs(fTmp3) >= Math::FAbs(fTmp0)) + { + fCos = fTmp0 / fTmp3; + fTmp1 = Math::Sqrt(fCos * fCos + (Real)1.0); + afSubDiag[i2 + 1] = fTmp3 * fTmp1; + fSin = ((Real)1.0) / fTmp1; + fCos *= fSin; + } + else + { + fSin = fTmp3 / fTmp0; + fTmp1 = Math::Sqrt(fSin * fSin + (Real)1.0); + afSubDiag[i2 + 1] = fTmp0 * fTmp1; + fCos = ((Real)1.0) / fTmp1; + fSin *= fCos; + } + fTmp0 = afDiag[i2 + 1] - fTmp2; + fTmp1 = (afDiag[i2] - fTmp0) * fSin + ((Real)2.0) * fTmp4 * fCos; + fTmp2 = fSin * fTmp1; + afDiag[i2 + 1] = fTmp0 + fTmp2; + fTmp0 = fCos * fTmp1 - fTmp4; + + for (int iRow = 0; iRow < 3; iRow++) + { + fTmp3 = Matrix3::m_afEntry[Matrix<3, Real>::I(iRow, i2 + 1)]; + Matrix3::m_afEntry[Matrix<3, Real>::I(iRow, i2 + 1)] = fSin * Matrix3::m_afEntry[Matrix<3, Real>::I(iRow, i2)] + + fCos * fTmp3; + Matrix3::m_afEntry[Matrix<3, Real>::I(iRow, i2)] = fCos * Matrix3::m_afEntry[Matrix<3, Real>::I(iRow, i2)] - + fSin * fTmp3; + } + } + afDiag[i0] -= fTmp2; + afSubDiag[i0] = fTmp0; + afSubDiag[i1] = (Real)0.0; + } + + if (iIter == iMaxIter) + { + // should not get here under normal circumstances + assert(false); + return false; + } + } + + return true; +} +//---------------------------------------------------------------------------- +template +void Matrix3::EigenDecomposition(Matrix3 &rkRot, Matrix3 &rkDiag) + const +{ + // Factor M = R*D*R^T. The columns of R are the eigenvectors. The + // diagonal entries of D are the corresponding eigenvalues. + Real afDiag[3], afSubDiag[3]; + rkRot = *this; + rkRot.Tridiagonalize(afDiag, afSubDiag); + rkRot.QLAlgorithm(afDiag, afSubDiag); + + // The Householder transformation is a reflection. Make the eigenvectors + // a right--handed system by changing sign on the last column. + rkRot[2][0] = -rkRot[2][0]; + rkRot[2][1] = -rkRot[2][1]; + rkRot[2][2] = -rkRot[2][2]; + + // (insertion) sort eigenvalues in increasing order, d0 <= d1 <= d2 + int i; + Real fSave; + + if (afDiag[1] < afDiag[0]) + { + // swap d0 and d1 + fSave = afDiag[0]; + afDiag[0] = afDiag[1]; + afDiag[1] = fSave; + + // swap V0 and V1 + for (i = 0; i < 3; i++) + { + fSave = rkRot[i][0]; + rkRot[i][0] = rkRot[i][1]; + rkRot[i][1] = fSave; + } + } + + if (afDiag[2] < afDiag[1]) + { + // swap d1 and d2 + fSave = afDiag[1]; + afDiag[1] = afDiag[2]; + afDiag[2] = fSave; + + // swap V1 and V2 + for (i = 0; i < 3; i++) + { + fSave = rkRot[i][1]; + rkRot[i][1] = rkRot[i][2]; + rkRot[i][2] = fSave; + } + } + + if (afDiag[1] < afDiag[0]) + { + // swap d0 and d1 + fSave = afDiag[0]; + afDiag[0] = afDiag[1]; + afDiag[1] = fSave; + + // swap V0 and V1 + for (i = 0; i < 3; i++) + { + fSave = rkRot[i][0]; + rkRot[i][0] = rkRot[i][1]; + rkRot[i][1] = fSave; + } + } + + rkDiag.MakeDiagonal(afDiag[0], afDiag[1], afDiag[2]); +} +//---------------------------------------------------------------------------- +template +void Matrix3::Bidiagonalize(Matrix3 &rkA, Matrix3 &rkL, Matrix3 &rkR) +{ + Real afV[3], afW[3]; + Real fLength, fSign, fT1, fInvT1, fT2; + bool bIdentity; + + // map first column to (*,0,0) + fLength = Math::Sqrt(rkA[0][0] * rkA[0][0] + rkA[1][0] * rkA[1][0] + + rkA[2][0] * rkA[2][0]); + if (fLength > (Real)0.0) + { + fSign = (rkA[0][0] > (Real)0.0 ? (Real)1.0 : -(Real)1.0); + fT1 = rkA[0][0] + fSign * fLength; + fInvT1 = ((Real)1.0) / fT1; + afV[1] = rkA[1][0] * fInvT1; + afV[2] = rkA[2][0] * fInvT1; + + fT2 = -((Real)2.0) / (((Real)1.0) + afV[1] * afV[1] + afV[2] * afV[2]); + afW[0] = fT2 * (rkA[0][0] + rkA[1][0] * afV[1] + rkA[2][0] * afV[2]); + afW[1] = fT2 * (rkA[0][1] + rkA[1][1] * afV[1] + rkA[2][1] * afV[2]); + afW[2] = fT2 * (rkA[0][2] + rkA[1][2] * afV[1] + rkA[2][2] * afV[2]); + rkA[0][0] += afW[0]; + rkA[0][1] += afW[1]; + rkA[0][2] += afW[2]; + rkA[1][1] += afV[1] * afW[1]; + rkA[1][2] += afV[1] * afW[2]; + rkA[2][1] += afV[2] * afW[1]; + rkA[2][2] += afV[2] * afW[2]; + + rkL[0][0] = ((Real)1.0) + fT2; + rkL[0][1] = fT2 * afV[1]; + rkL[1][0] = rkL[0][1]; + rkL[0][2] = fT2 * afV[2]; + rkL[2][0] = rkL[0][2]; + rkL[1][1] = ((Real)1.0) + fT2 * afV[1] * afV[1]; + rkL[1][2] = fT2 * afV[1] * afV[2]; + rkL[2][1] = rkL[1][2]; + rkL[2][2] = ((Real)1.0) + fT2 * afV[2] * afV[2]; + bIdentity = false; + } + else + { + rkL = Matrix3::IDENTITY; + bIdentity = true; + } + + // map first row to (*,*,0) + fLength = Math::Sqrt(rkA[0][1] * rkA[0][1] + rkA[0][2] * rkA[0][2]); + if (fLength > (Real)0.0) + { + fSign = (rkA[0][1] > (Real)0.0 ? (Real)1.0 : -(Real)1.0); + fT1 = rkA[0][1] + fSign * fLength; + afV[2] = rkA[0][2] / fT1; + + fT2 = -((Real)2.0) / (((Real)1.0) + afV[2] * afV[2]); + afW[0] = fT2 * (rkA[0][1] + rkA[0][2] * afV[2]); + afW[1] = fT2 * (rkA[1][1] + rkA[1][2] * afV[2]); + afW[2] = fT2 * (rkA[2][1] + rkA[2][2] * afV[2]); + rkA[0][1] += afW[0]; + rkA[1][1] += afW[1]; + rkA[1][2] += afW[1] * afV[2]; + rkA[2][1] += afW[2]; + rkA[2][2] += afW[2] * afV[2]; + + rkR[0][0] = (Real)1.0; + rkR[0][1] = (Real)0.0; + rkR[1][0] = (Real)0.0; + rkR[0][2] = (Real)0.0; + rkR[2][0] = (Real)0.0; + rkR[1][1] = ((Real)1.0) + fT2; + rkR[1][2] = fT2 * afV[2]; + rkR[2][1] = rkR[1][2]; + rkR[2][2] = ((Real)1.0) + fT2 * afV[2] * afV[2]; + } + else + { + rkR = Matrix3::IDENTITY; + } + + // map second column to (*,*,0) + fLength = Math::Sqrt(rkA[1][1] * rkA[1][1] + rkA[2][1] * rkA[2][1]); + if (fLength > (Real)0.0) + { + fSign = (rkA[1][1] > (Real)0.0 ? (Real)1.0 : -(Real)1.0); + fT1 = rkA[1][1] + fSign * fLength; + afV[2] = rkA[2][1] / fT1; + + fT2 = -((Real)2.0) / (((Real)1.0) + afV[2] * afV[2]); + afW[1] = fT2 * (rkA[1][1] + rkA[2][1] * afV[2]); + afW[2] = fT2 * (rkA[1][2] + rkA[2][2] * afV[2]); + rkA[1][1] += afW[1]; + rkA[1][2] += afW[2]; + rkA[2][2] += afV[2] * afW[2]; + + Real fA = ((Real)1.0) + fT2; + Real fB = fT2 * afV[2]; + Real fC = ((Real)1.0) + fB * afV[2]; + + if (bIdentity) + { + rkL[0][0] = (Real)1.0; + rkL[0][1] = (Real)0.0; + rkL[1][0] = (Real)0.0; + rkL[0][2] = (Real)0.0; + rkL[2][0] = (Real)0.0; + rkL[1][1] = fA; + rkL[1][2] = fB; + rkL[2][1] = fB; + rkL[2][2] = fC; + } + else + { + for (int iRow = 0; iRow < 3; iRow++) + { + Real fTmp0 = rkL[iRow][1]; + Real fTmp1 = rkL[iRow][2]; + rkL[iRow][1] = fA * fTmp0 + fB * fTmp1; + rkL[iRow][2] = fB * fTmp0 + fC * fTmp1; + } + } + } +} +//---------------------------------------------------------------------------- +template +void Matrix3::GolubKahanStep(Matrix3 &rkA, Matrix3 &rkL, Matrix3 &rkR) +{ + Real fT11 = rkA[0][1] * rkA[0][1] + rkA[1][1] * rkA[1][1]; + Real fT22 = rkA[1][2] * rkA[1][2] + rkA[2][2] * rkA[2][2]; + Real fT12 = rkA[1][1] * rkA[1][2]; + Real fTrace = fT11 + fT22; + Real fDiff = fT11 - fT22; + Real fDiscr = Math::Sqrt(fDiff * fDiff + ((Real)4.0) * fT12 * fT12); + Real fRoot1 = ((Real)0.5) * (fTrace + fDiscr); + Real fRoot2 = ((Real)0.5) * (fTrace - fDiscr); + + // adjust right + Real fY = rkA[0][0] - (Math::FAbs(fRoot1 - fT22) <= + Math::FAbs(fRoot2 - fT22) + ? fRoot1 + : fRoot2); + Real fZ = rkA[0][1]; + Real fInvLength = Math::InvSqrt(fY * fY + fZ * fZ); + Real fSin = fZ * fInvLength; + Real fCos = -fY * fInvLength; + + Real fTmp0 = rkA[0][0]; + Real fTmp1 = rkA[0][1]; + rkA[0][0] = fCos * fTmp0 - fSin * fTmp1; + rkA[0][1] = fSin * fTmp0 + fCos * fTmp1; + rkA[1][0] = -fSin * rkA[1][1]; + rkA[1][1] *= fCos; + + int iRow; + for (iRow = 0; iRow < 3; iRow++) + { + fTmp0 = rkR[0][iRow]; + fTmp1 = rkR[1][iRow]; + rkR[0][iRow] = fCos * fTmp0 - fSin * fTmp1; + rkR[1][iRow] = fSin * fTmp0 + fCos * fTmp1; + } + + // adjust left + fY = rkA[0][0]; + fZ = rkA[1][0]; + fInvLength = Math::InvSqrt(fY * fY + fZ * fZ); + fSin = fZ * fInvLength; + fCos = -fY * fInvLength; + + rkA[0][0] = fCos * rkA[0][0] - fSin * rkA[1][0]; + fTmp0 = rkA[0][1]; + fTmp1 = rkA[1][1]; + rkA[0][1] = fCos * fTmp0 - fSin * fTmp1; + rkA[1][1] = fSin * fTmp0 + fCos * fTmp1; + rkA[0][2] = -fSin * rkA[1][2]; + rkA[1][2] *= fCos; + + int iCol; + for (iCol = 0; iCol < 3; iCol++) + { + fTmp0 = rkL[iCol][0]; + fTmp1 = rkL[iCol][1]; + rkL[iCol][0] = fCos * fTmp0 - fSin * fTmp1; + rkL[iCol][1] = fSin * fTmp0 + fCos * fTmp1; + } + + // adjust right + fY = rkA[0][1]; + fZ = rkA[0][2]; + fInvLength = Math::InvSqrt(fY * fY + fZ * fZ); + fSin = fZ * fInvLength; + fCos = -fY * fInvLength; + + rkA[0][1] = fCos * rkA[0][1] - fSin * rkA[0][2]; + fTmp0 = rkA[1][1]; + fTmp1 = rkA[1][2]; + rkA[1][1] = fCos * fTmp0 - fSin * fTmp1; + rkA[1][2] = fSin * fTmp0 + fCos * fTmp1; + rkA[2][1] = -fSin * rkA[2][2]; + rkA[2][2] *= fCos; + + for (iRow = 0; iRow < 3; iRow++) + { + fTmp0 = rkR[1][iRow]; + fTmp1 = rkR[2][iRow]; + rkR[1][iRow] = fCos * fTmp0 - fSin * fTmp1; + rkR[2][iRow] = fSin * fTmp0 + fCos * fTmp1; + } + + // adjust left + fY = rkA[1][1]; + fZ = rkA[2][1]; + fInvLength = Math::InvSqrt(fY * fY + fZ * fZ); + fSin = fZ * fInvLength; + fCos = -fY * fInvLength; + + rkA[1][1] = fCos * rkA[1][1] - fSin * rkA[2][1]; + fTmp0 = rkA[1][2]; + fTmp1 = rkA[2][2]; + rkA[1][2] = fCos * fTmp0 - fSin * fTmp1; + rkA[2][2] = fSin * fTmp0 + fCos * fTmp1; + + for (iCol = 0; iCol < 3; iCol++) + { + fTmp0 = rkL[iCol][1]; + fTmp1 = rkL[iCol][2]; + rkL[iCol][1] = fCos * fTmp0 - fSin * fTmp1; + rkL[iCol][2] = fSin * fTmp0 + fCos * fTmp1; + } +} +//---------------------------------------------------------------------------- +template +void Matrix3::SingularValueDecomposition(Matrix3 &rkL, Matrix3 &rkS, + Matrix3 &rkR) const +{ + int iRow, iCol; + + Matrix3 kA = *this; + Bidiagonalize(kA, rkL, rkR); + rkS.MakeZero(); + + const int iMax = 32; + const Real fEpsilon = (Real)1e-04; + for (int i = 0; i < iMax; i++) + { + Real fTmp, fTmp0, fTmp1; + Real fSin0, fCos0, fTan0; + Real fSin1, fCos1, fTan1; + + bool bTest1 = (Math::FAbs(kA[0][1]) <= + fEpsilon * (Math::FAbs(kA[0][0]) + + Math::FAbs(kA[1][1]))); + bool bTest2 = (Math::FAbs(kA[1][2]) <= + fEpsilon * (Math::FAbs(kA[1][1]) + + Math::FAbs(kA[2][2]))); + if (bTest1) + { + if (bTest2) + { + rkS[0][0] = kA[0][0]; + rkS[1][1] = kA[1][1]; + rkS[2][2] = kA[2][2]; + break; + } + else + { + // 2x2 closed form factorization + fTmp = (kA[1][1] * kA[1][1] - kA[2][2] * kA[2][2] + + kA[1][2] * kA[1][2]) / + (kA[1][2] * kA[2][2]); + fTan0 = ((Real)0.5) * (fTmp + Math::Sqrt(fTmp * fTmp + + ((Real)4.0))); + fCos0 = Math::InvSqrt(((Real)1.0) + fTan0 * fTan0); + fSin0 = fTan0 * fCos0; + + for (iCol = 0; iCol < 3; iCol++) + { + fTmp0 = rkL[iCol][1]; + fTmp1 = rkL[iCol][2]; + rkL[iCol][1] = fCos0 * fTmp0 - fSin0 * fTmp1; + rkL[iCol][2] = fSin0 * fTmp0 + fCos0 * fTmp1; + } + + fTan1 = (kA[1][2] - kA[2][2] * fTan0) / kA[1][1]; + fCos1 = Math::InvSqrt(((Real)1.0) + fTan1 * fTan1); + fSin1 = -fTan1 * fCos1; + + for (iRow = 0; iRow < 3; iRow++) + { + fTmp0 = rkR[1][iRow]; + fTmp1 = rkR[2][iRow]; + rkR[1][iRow] = fCos1 * fTmp0 - fSin1 * fTmp1; + rkR[2][iRow] = fSin1 * fTmp0 + fCos1 * fTmp1; + } + + rkS[0][0] = kA[0][0]; + rkS[1][1] = fCos0 * fCos1 * kA[1][1] - + fSin1 * (fCos0 * kA[1][2] - fSin0 * kA[2][2]); + rkS[2][2] = fSin0 * fSin1 * kA[1][1] + + fCos1 * (fSin0 * kA[1][2] + fCos0 * kA[2][2]); + break; + } + } + else + { + if (bTest2) + { + // 2x2 closed form factorization + fTmp = (kA[0][0] * kA[0][0] + kA[1][1] * kA[1][1] - + kA[0][1] * kA[0][1]) / + (kA[0][1] * kA[1][1]); + fTan0 = ((Real)0.5) * (-fTmp + Math::Sqrt(fTmp * fTmp + + ((Real)4.0))); + fCos0 = Math::InvSqrt(((Real)1.0) + fTan0 * fTan0); + fSin0 = fTan0 * fCos0; + + for (iCol = 0; iCol < 3; iCol++) + { + fTmp0 = rkL[iCol][0]; + fTmp1 = rkL[iCol][1]; + rkL[iCol][0] = fCos0 * fTmp0 - fSin0 * fTmp1; + rkL[iCol][1] = fSin0 * fTmp0 + fCos0 * fTmp1; + } + + fTan1 = (kA[0][1] - kA[1][1] * fTan0) / kA[0][0]; + fCos1 = Math::InvSqrt(((Real)1.0) + fTan1 * fTan1); + fSin1 = -fTan1 * fCos1; + + for (iRow = 0; iRow < 3; iRow++) + { + fTmp0 = rkR[0][iRow]; + fTmp1 = rkR[1][iRow]; + rkR[0][iRow] = fCos1 * fTmp0 - fSin1 * fTmp1; + rkR[1][iRow] = fSin1 * fTmp0 + fCos1 * fTmp1; + } + + rkS[0][0] = fCos0 * fCos1 * kA[0][0] - + fSin1 * (fCos0 * kA[0][1] - fSin0 * kA[1][1]); + rkS[1][1] = fSin0 * fSin1 * kA[0][0] + + fCos1 * (fSin0 * kA[0][1] + fCos0 * kA[1][1]); + rkS[2][2] = kA[2][2]; + break; + } + else + { + GolubKahanStep(kA, rkL, rkR); + } + } + } + + // positize diagonal + for (iRow = 0; iRow < 3; iRow++) + { + if (rkS[iRow][iRow] < (Real)0.0) + { + rkS[iRow][iRow] = -rkS[iRow][iRow]; + for (iCol = 0; iCol < 3; iCol++) + rkR[iRow][iCol] = -rkR[iRow][iCol]; + } + } +} +//---------------------------------------------------------------------------- +template +void Matrix3::SingularValueComposition(const Matrix3 &rkL, + const Matrix3 &rkS, const Matrix3 &rkR) +{ + *this = rkL * (rkS * rkR); +} +//---------------------------------------------------------------------------- +template +void Matrix3::QDUDecomposition(Matrix3 &rkQ, Matrix3 &rkD, + Matrix3 &rkU) const +{ + // Factor M = QR = QDU where Q is orthogonal (rotation), D is diagonal + // (scaling), and U is upper triangular with ones on its diagonal + // (shear). Algorithm uses Gram-Schmidt orthogonalization (the QR + // algorithm). + // + // If M = [ m0 | m1 | m2 ] and Q = [ q0 | q1 | q2 ], then + // + // q0 = m0/|m0| + // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| + // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| + // + // where |V| indicates length of vector V and A*B indicates dot + // product of vectors A and B. The matrix R has entries + // + // r00 = q0*m0 r01 = q0*m1 r02 = q0*m2 + // r10 = 0 r11 = q1*m1 r12 = q1*m2 + // r20 = 0 r21 = 0 r22 = q2*m2 + // + // so D = diag(r00,r11,r22) and U has entries u01 = r01/r00, + // u02 = r02/r00, and u12 = r12/r11. + + // build orthogonal matrix Q + Real fInvLength = Math::InvSqrt(Matrix3::m_afEntry[0] * Matrix3::m_afEntry[0] + + Matrix3::m_afEntry[3] * Matrix3::m_afEntry[3] + Matrix3::m_afEntry[6] * Matrix3::m_afEntry[6]); + rkQ[0][0] = Matrix3::m_afEntry[0] * fInvLength; + rkQ[1][0] = Matrix3::m_afEntry[3] * fInvLength; + rkQ[2][0] = Matrix3::m_afEntry[6] * fInvLength; + + Real fDot = rkQ[0][0] * Matrix3::m_afEntry[1] + rkQ[1][0] * Matrix3::m_afEntry[4] + + rkQ[2][0] * Matrix3::m_afEntry[7]; + rkQ[0][1] = Matrix3::m_afEntry[1] - fDot * rkQ[0][0]; + rkQ[1][1] = Matrix3::m_afEntry[4] - fDot * rkQ[1][0]; + rkQ[2][1] = Matrix3::m_afEntry[7] - fDot * rkQ[2][0]; + fInvLength = Math::InvSqrt(rkQ[0][1] * rkQ[0][1] + + rkQ[1][1] * rkQ[1][1] + rkQ[2][1] * rkQ[2][1]); + rkQ[0][1] *= fInvLength; + rkQ[1][1] *= fInvLength; + rkQ[2][1] *= fInvLength; + + fDot = rkQ[0][0] * Matrix3::m_afEntry[2] + rkQ[1][0] * Matrix3::m_afEntry[5] + + rkQ[2][0] * Matrix3::m_afEntry[8]; + rkQ[0][2] = Matrix3::m_afEntry[2] - fDot * rkQ[0][0]; + rkQ[1][2] = Matrix3::m_afEntry[5] - fDot * rkQ[1][0]; + rkQ[2][2] = Matrix3::m_afEntry[8] - fDot * rkQ[2][0]; + fDot = rkQ[0][1] * Matrix3::m_afEntry[2] + rkQ[1][1] * Matrix3::m_afEntry[5] + + rkQ[2][1] * Matrix3::m_afEntry[8]; + rkQ[0][2] -= fDot * rkQ[0][1]; + rkQ[1][2] -= fDot * rkQ[1][1]; + rkQ[2][2] -= fDot * rkQ[2][1]; + fInvLength = Math::InvSqrt(rkQ[0][2] * rkQ[0][2] + + rkQ[1][2] * rkQ[1][2] + rkQ[2][2] * rkQ[2][2]); + rkQ[0][2] *= fInvLength; + rkQ[1][2] *= fInvLength; + rkQ[2][2] *= fInvLength; + + // guarantee that orthogonal matrix has determinant 1 (no reflections) + Real fDet = rkQ[0][0] * rkQ[1][1] * rkQ[2][2] + rkQ[0][1] * rkQ[1][2] * rkQ[2][0] + rkQ[0][2] * rkQ[1][0] * rkQ[2][1] - rkQ[0][2] * rkQ[1][1] * rkQ[2][0] - rkQ[0][1] * rkQ[1][0] * rkQ[2][2] - rkQ[0][0] * rkQ[1][2] * rkQ[2][1]; + + if (fDet < (Real)0.0) + { + for (int iRow = 0; iRow < 3; iRow++) + { + for (int iCol = 0; iCol < 3; iCol++) + rkQ[iRow][iCol] = -rkQ[iRow][iCol]; + } + } + + // build "right" matrix R + Matrix3 kR; + kR[0][0] = rkQ[0][0] * Matrix3::m_afEntry[0] + rkQ[1][0] * Matrix3::m_afEntry[3] + + rkQ[2][0] * Matrix3::m_afEntry[6]; + kR[0][1] = rkQ[0][0] * Matrix3::m_afEntry[1] + rkQ[1][0] * Matrix3::m_afEntry[4] + + rkQ[2][0] * Matrix3::m_afEntry[7]; + kR[1][1] = rkQ[0][1] * Matrix3::m_afEntry[1] + rkQ[1][1] * Matrix3::m_afEntry[4] + + rkQ[2][1] * Matrix3::m_afEntry[7]; + kR[0][2] = rkQ[0][0] * Matrix3::m_afEntry[2] + rkQ[1][0] * Matrix3::m_afEntry[5] + + rkQ[2][0] * Matrix3::m_afEntry[8]; + kR[1][2] = rkQ[0][1] * Matrix3::m_afEntry[2] + rkQ[1][1] * Matrix3::m_afEntry[5] + + rkQ[2][1] * Matrix3::m_afEntry[8]; + kR[2][2] = rkQ[0][2] * Matrix3::m_afEntry[2] + rkQ[1][2] * Matrix3::m_afEntry[5] + + rkQ[2][2] * Matrix3::m_afEntry[8]; + + // the scaling component + rkD.MakeDiagonal(kR[0][0], kR[1][1], kR[2][2]); + + // the shear component + Real fInvD0 = ((Real)1.0) / rkD[0][0]; + rkU[0][0] = (Real)1.0; + rkU[0][1] = kR[0][1] * fInvD0; + rkU[0][2] = kR[0][2] * fInvD0; + rkU[1][0] = (Real)0.0; + rkU[1][1] = (Real)1.0; + rkU[1][2] = kR[1][2] / rkD[1][1]; + rkU[2][0] = (Real)0.0; + rkU[2][1] = (Real)0.0; + rkU[2][2] = (Real)1.0; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlMatrix4.cpp b/src/editors/xrECore/WildMagic/WmlMatrix4.cpp new file mode 100644 index 00000000000..195213be271 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix4.cpp @@ -0,0 +1,38 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#include "WmlMatrix4.h" +using namespace Wml; + +template <> +const Matrix4 Matrix4::ZERO( + 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f); +template <> +const Matrix4 Matrix4::IDENTITY( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); + +template <> +const Matrix4 Matrix4::ZERO( + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0); +template <> +const Matrix4 Matrix4::IDENTITY( + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0); diff --git a/src/editors/xrECore/WildMagic/WmlMatrix4.h b/src/editors/xrECore/WildMagic/WmlMatrix4.h new file mode 100644 index 00000000000..5eac47aef87 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix4.h @@ -0,0 +1,64 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLMATRIX4_H +#define WMLMATRIX4_H + +#include "WmlMatrix.h" +#include "WmlVector4.h" + +namespace Wml +{ + + template + class Matrix4 : public Matrix<4, Real> + { + public: + // construction + Matrix4(); + Matrix4(const Matrix4 &rkM); + Matrix4(const Matrix<4, Real> &rkM); + + // input Mrc is in row r, column c. + Matrix4(Real fM00, Real fM01, Real fM02, Real fM03, + Real fM10, Real fM11, Real fM12, Real fM13, + Real fM20, Real fM21, Real fM22, Real fM23, + Real fM30, Real fM31, Real fM32, Real fM33); + + // Create a matrix from an array of numbers. The input array is + // interpreted based on the Boolean input as + // true: entry[0..15]={m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22, + // m23,m30,m31,m32,m33} [row major] + // false: entry[0..15]={m00,m10,m20,m30,m01,m11,m21,m31,m02,m12,m22, + // m32,m03,m13,m23,m33} [col major] + Matrix4(const Real afEntry[16], bool bRowMajor); + + // assignment + Matrix4 &operator=(const Matrix4 &rkM); + Matrix4 &operator=(const Matrix<4, Real> &rkM); + + // matrix operations + Matrix4 Inverse() const; + Matrix4 Adjoint() const; + Real Determinant() const; + + // special matrices + WML_ITEM static const Matrix4 ZERO; + WML_ITEM static const Matrix4 IDENTITY; + }; + +#include "WmlMatrix4.inl" + + typedef Matrix4 Matrix4f; + typedef Matrix4 Matrix4d; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlMatrix4.inl b/src/editors/xrECore/WildMagic/WmlMatrix4.inl new file mode 100644 index 00000000000..c7359606dfc --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMatrix4.inl @@ -0,0 +1,198 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +Matrix4::Matrix4() +{ + // the matrix is uninitialized +} +//---------------------------------------------------------------------------- +template +Matrix4::Matrix4(const Matrix4 &rkM) +{ + memcpy(Matrix4::m_afEntry, rkM.Matrix4::m_afEntry, 16 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Matrix4::Matrix4(const Matrix<4, Real> &rkM) +{ + memcpy(Matrix4::m_afEntry, (const Real *)rkM, 16 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Matrix4 &Matrix4::operator=(const Matrix4 &rkM) +{ + memcpy(Matrix4::m_afEntry, rkM.Matrix4::m_afEntry, 16 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Matrix4 &Matrix4::operator=(const Matrix<4, Real> &rkM) +{ + memcpy(Matrix4::m_afEntry, (const Real *)rkM, 16 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Matrix4::Matrix4(Real fM00, Real fM01, Real fM02, Real fM03, + Real fM10, Real fM11, Real fM12, Real fM13, Real fM20, Real fM21, + Real fM22, Real fM23, Real fM30, Real fM31, Real fM32, Real fM33) +{ + Matrix4::m_afEntry[0] = fM00; + Matrix4::m_afEntry[1] = fM01; + Matrix4::m_afEntry[2] = fM02; + Matrix4::m_afEntry[3] = fM03; + Matrix4::m_afEntry[4] = fM10; + Matrix4::m_afEntry[5] = fM11; + Matrix4::m_afEntry[6] = fM12; + Matrix4::m_afEntry[7] = fM13; + Matrix4::m_afEntry[8] = fM20; + Matrix4::m_afEntry[9] = fM21; + Matrix4::m_afEntry[10] = fM22; + Matrix4::m_afEntry[11] = fM23; + Matrix4::m_afEntry[12] = fM30; + Matrix4::m_afEntry[13] = fM31; + Matrix4::m_afEntry[14] = fM32; + Matrix4::m_afEntry[15] = fM33; +} +//---------------------------------------------------------------------------- +template +Matrix4::Matrix4(const Real afEntry[16], bool bRowMajor) +{ + if (bRowMajor) + { + memcpy(Matrix4::m_afEntry, afEntry, 16 * sizeof(Real)); + } + else + { + Matrix4::m_afEntry[0] = afEntry[0]; + Matrix4::m_afEntry[1] = afEntry[4]; + Matrix4::m_afEntry[2] = afEntry[8]; + Matrix4::m_afEntry[3] = afEntry[12]; + Matrix4::m_afEntry[4] = afEntry[1]; + Matrix4::m_afEntry[5] = afEntry[5]; + Matrix4::m_afEntry[6] = afEntry[9]; + Matrix4::m_afEntry[7] = afEntry[13]; + Matrix4::m_afEntry[8] = afEntry[2]; + Matrix4::m_afEntry[9] = afEntry[6]; + Matrix4::m_afEntry[10] = afEntry[10]; + Matrix4::m_afEntry[11] = afEntry[14]; + Matrix4::m_afEntry[12] = afEntry[3]; + Matrix4::m_afEntry[13] = afEntry[7]; + Matrix4::m_afEntry[14] = afEntry[11]; + Matrix4::m_afEntry[15] = afEntry[15]; + } +} +//---------------------------------------------------------------------------- +template +Matrix4 Matrix4::Inverse() const +{ + Real fA0 = Matrix4::m_afEntry[0] * Matrix4::m_afEntry[5] - Matrix4::m_afEntry[1] * Matrix4::m_afEntry[4]; + Real fA1 = Matrix4::m_afEntry[0] * Matrix4::m_afEntry[6] - Matrix4::m_afEntry[2] * Matrix4::m_afEntry[4]; + Real fA2 = Matrix4::m_afEntry[0] * Matrix4::m_afEntry[7] - Matrix4::m_afEntry[3] * Matrix4::m_afEntry[4]; + Real fA3 = Matrix4::m_afEntry[1] * Matrix4::m_afEntry[6] - Matrix4::m_afEntry[2] * Matrix4::m_afEntry[5]; + Real fA4 = Matrix4::m_afEntry[1] * Matrix4::m_afEntry[7] - Matrix4::m_afEntry[3] * Matrix4::m_afEntry[5]; + Real fA5 = Matrix4::m_afEntry[2] * Matrix4::m_afEntry[7] - Matrix4::m_afEntry[3] * Matrix4::m_afEntry[6]; + Real fB0 = Matrix4::m_afEntry[8] * Matrix4::m_afEntry[13] - Matrix4::m_afEntry[9] * Matrix4::m_afEntry[12]; + Real fB1 = Matrix4::m_afEntry[8] * Matrix4::m_afEntry[14] - Matrix4::m_afEntry[10] * Matrix4::m_afEntry[12]; + Real fB2 = Matrix4::m_afEntry[8] * Matrix4::m_afEntry[15] - Matrix4::m_afEntry[11] * Matrix4::m_afEntry[12]; + Real fB3 = Matrix4::m_afEntry[9] * Matrix4::m_afEntry[14] - Matrix4::m_afEntry[10] * Matrix4::m_afEntry[13]; + Real fB4 = Matrix4::m_afEntry[9] * Matrix4::m_afEntry[15] - Matrix4::m_afEntry[11] * Matrix4::m_afEntry[13]; + Real fB5 = Matrix4::m_afEntry[10] * Matrix4::m_afEntry[15] - Matrix4::m_afEntry[11] * Matrix4::m_afEntry[14]; + + Real fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0; + if (Math::FAbs(fDet) <= Math::EPSILON) + return Matrix4::ZERO; + + Matrix4 kInv; + kInv[0][0] = +Matrix4::m_afEntry[5] * fB5 - Matrix4::m_afEntry[6] * fB4 + Matrix4::m_afEntry[7] * fB3; + kInv[1][0] = -Matrix4::m_afEntry[4] * fB5 + Matrix4::m_afEntry[6] * fB2 - Matrix4::m_afEntry[7] * fB1; + kInv[2][0] = +Matrix4::m_afEntry[4] * fB4 - Matrix4::m_afEntry[5] * fB2 + Matrix4::m_afEntry[7] * fB0; + kInv[3][0] = -Matrix4::m_afEntry[4] * fB3 + Matrix4::m_afEntry[5] * fB1 - Matrix4::m_afEntry[6] * fB0; + kInv[0][1] = -Matrix4::m_afEntry[1] * fB5 + Matrix4::m_afEntry[2] * fB4 - Matrix4::m_afEntry[3] * fB3; + kInv[1][1] = +Matrix4::m_afEntry[0] * fB5 - Matrix4::m_afEntry[2] * fB2 + Matrix4::m_afEntry[3] * fB1; + kInv[2][1] = -Matrix4::m_afEntry[0] * fB4 + Matrix4::m_afEntry[1] * fB2 - Matrix4::m_afEntry[3] * fB0; + kInv[3][1] = +Matrix4::m_afEntry[0] * fB3 - Matrix4::m_afEntry[1] * fB1 + Matrix4::m_afEntry[2] * fB0; + kInv[0][2] = +Matrix4::m_afEntry[13] * fA5 - Matrix4::m_afEntry[14] * fA4 + Matrix4::m_afEntry[15] * fA3; + kInv[1][2] = -Matrix4::m_afEntry[12] * fA5 + Matrix4::m_afEntry[14] * fA2 - Matrix4::m_afEntry[15] * fA1; + kInv[2][2] = +Matrix4::m_afEntry[12] * fA4 - Matrix4::m_afEntry[13] * fA2 + Matrix4::m_afEntry[15] * fA0; + kInv[3][2] = -Matrix4::m_afEntry[12] * fA3 + Matrix4::m_afEntry[13] * fA1 - Matrix4::m_afEntry[14] * fA0; + kInv[0][3] = -Matrix4::m_afEntry[9] * fA5 + Matrix4::m_afEntry[10] * fA4 - Matrix4::m_afEntry[11] * fA3; + kInv[1][3] = +Matrix4::m_afEntry[8] * fA5 - Matrix4::m_afEntry[10] * fA2 + Matrix4::m_afEntry[11] * fA1; + kInv[2][3] = -Matrix4::m_afEntry[8] * fA4 + Matrix4::m_afEntry[9] * fA2 - Matrix4::m_afEntry[11] * fA0; + kInv[3][3] = +Matrix4::m_afEntry[8] * fA3 - Matrix4::m_afEntry[9] * fA1 + Matrix4::m_afEntry[10] * fA0; + + Real fInvDet = ((Real)1.0) / fDet; + for (int iRow = 0; iRow < 4; iRow++) + { + for (int iCol = 0; iCol < 4; iCol++) + kInv[iRow][iCol] *= fInvDet; + } + + return kInv; +} +//---------------------------------------------------------------------------- +template +Matrix4 Matrix4::Adjoint() const +{ + Real fA0 = Matrix4::m_afEntry[0] * Matrix4::m_afEntry[5] - Matrix4::m_afEntry[1] * Matrix4::m_afEntry[4]; + Real fA1 = Matrix4::m_afEntry[0] * Matrix4::m_afEntry[6] - Matrix4::m_afEntry[2] * Matrix4::m_afEntry[4]; + Real fA2 = Matrix4::m_afEntry[0] * Matrix4::m_afEntry[7] - Matrix4::m_afEntry[3] * Matrix4::m_afEntry[4]; + Real fA3 = Matrix4::m_afEntry[1] * Matrix4::m_afEntry[6] - Matrix4::m_afEntry[2] * Matrix4::m_afEntry[5]; + Real fA4 = Matrix4::m_afEntry[1] * Matrix4::m_afEntry[7] - Matrix4::m_afEntry[3] * Matrix4::m_afEntry[5]; + Real fA5 = Matrix4::m_afEntry[2] * Matrix4::m_afEntry[7] - Matrix4::m_afEntry[3] * Matrix4::m_afEntry[6]; + Real fB0 = Matrix4::m_afEntry[8] * Matrix4::m_afEntry[13] - Matrix4::m_afEntry[9] * Matrix4::m_afEntry[12]; + Real fB1 = Matrix4::m_afEntry[8] * Matrix4::m_afEntry[14] - Matrix4::m_afEntry[10] * Matrix4::m_afEntry[12]; + Real fB2 = Matrix4::m_afEntry[8] * Matrix4::m_afEntry[15] - Matrix4::m_afEntry[11] * Matrix4::m_afEntry[12]; + Real fB3 = Matrix4::m_afEntry[9] * Matrix4::m_afEntry[14] - Matrix4::m_afEntry[10] * Matrix4::m_afEntry[13]; + Real fB4 = Matrix4::m_afEntry[9] * Matrix4::m_afEntry[15] - Matrix4::m_afEntry[11] * Matrix4::m_afEntry[13]; + Real fB5 = Matrix4::m_afEntry[10] * Matrix4::m_afEntry[15] - Matrix4::m_afEntry[11] * Matrix4::m_afEntry[14]; + + Matrix4 kAdj; + kAdj[0][0] = +Matrix4::m_afEntry[5] * fB5 - Matrix4::m_afEntry[6] * fB4 + Matrix4::m_afEntry[7] * fB3; + kAdj[1][0] = -Matrix4::m_afEntry[4] * fB5 + Matrix4::m_afEntry[6] * fB2 - Matrix4::m_afEntry[7] * fB1; + kAdj[2][0] = +Matrix4::m_afEntry[4] * fB4 - Matrix4::m_afEntry[5] * fB2 + Matrix4::m_afEntry[7] * fB0; + kAdj[3][0] = -Matrix4::m_afEntry[4] * fB3 + Matrix4::m_afEntry[5] * fB1 - Matrix4::m_afEntry[6] * fB0; + kAdj[0][1] = -Matrix4::m_afEntry[1] * fB5 + Matrix4::m_afEntry[2] * fB4 - Matrix4::m_afEntry[3] * fB3; + kAdj[1][1] = +Matrix4::m_afEntry[0] * fB5 - Matrix4::m_afEntry[2] * fB2 + Matrix4::m_afEntry[3] * fB1; + kAdj[2][1] = -Matrix4::m_afEntry[0] * fB4 + Matrix4::m_afEntry[1] * fB2 - Matrix4::m_afEntry[3] * fB0; + kAdj[3][1] = +Matrix4::m_afEntry[0] * fB3 - Matrix4::m_afEntry[1] * fB1 + Matrix4::m_afEntry[2] * fB0; + kAdj[0][2] = +Matrix4::m_afEntry[13] * fA5 - Matrix4::m_afEntry[14] * fA4 + Matrix4::m_afEntry[15] * fA3; + kAdj[1][2] = -Matrix4::m_afEntry[12] * fA5 + Matrix4::m_afEntry[14] * fA2 - Matrix4::m_afEntry[15] * fA1; + kAdj[2][2] = +Matrix4::m_afEntry[12] * fA4 - Matrix4::m_afEntry[13] * fA2 + Matrix4::m_afEntry[15] * fA0; + kAdj[3][2] = -Matrix4::m_afEntry[12] * fA3 + Matrix4::m_afEntry[13] * fA1 - Matrix4::m_afEntry[14] * fA0; + kAdj[0][3] = -Matrix4::m_afEntry[9] * fA5 + Matrix4::m_afEntry[10] * fA4 - Matrix4::m_afEntry[11] * fA3; + kAdj[1][3] = +Matrix4::m_afEntry[8] * fA5 - Matrix4::m_afEntry[10] * fA2 + Matrix4::m_afEntry[11] * fA1; + kAdj[2][3] = -Matrix4::m_afEntry[8] * fA4 + Matrix4::m_afEntry[9] * fA2 - Matrix4::m_afEntry[11] * fA0; + kAdj[3][3] = +Matrix4::m_afEntry[8] * fA3 - Matrix4::m_afEntry[9] * fA1 + Matrix4::m_afEntry[10] * fA0; + + return kAdj; +} +//---------------------------------------------------------------------------- +template +Real Matrix4::Determinant() const +{ + Real fA0 = Matrix4::m_afEntry[0] * Matrix4::m_afEntry[5] - Matrix4::m_afEntry[1] * Matrix4::m_afEntry[4]; + Real fA1 = Matrix4::m_afEntry[0] * Matrix4::m_afEntry[6] - Matrix4::m_afEntry[2] * Matrix4::m_afEntry[4]; + Real fA2 = Matrix4::m_afEntry[0] * Matrix4::m_afEntry[7] - Matrix4::m_afEntry[3] * Matrix4::m_afEntry[4]; + Real fA3 = Matrix4::m_afEntry[1] * Matrix4::m_afEntry[6] - Matrix4::m_afEntry[2] * Matrix4::m_afEntry[5]; + Real fA4 = Matrix4::m_afEntry[1] * Matrix4::m_afEntry[7] - Matrix4::m_afEntry[3] * Matrix4::m_afEntry[5]; + Real fA5 = Matrix4::m_afEntry[2] * Matrix4::m_afEntry[7] - Matrix4::m_afEntry[3] * Matrix4::m_afEntry[6]; + Real fB0 = Matrix4::m_afEntry[8] * Matrix4::m_afEntry[13] - Matrix4::m_afEntry[9] * Matrix4::m_afEntry[12]; + Real fB1 = Matrix4::m_afEntry[8] * Matrix4::m_afEntry[14] - Matrix4::m_afEntry[10] * Matrix4::m_afEntry[12]; + Real fB2 = Matrix4::m_afEntry[8] * Matrix4::m_afEntry[15] - Matrix4::m_afEntry[11] * Matrix4::m_afEntry[12]; + Real fB3 = Matrix4::m_afEntry[9] * Matrix4::m_afEntry[14] - Matrix4::m_afEntry[10] * Matrix4::m_afEntry[13]; + Real fB4 = Matrix4::m_afEntry[9] * Matrix4::m_afEntry[15] - Matrix4::m_afEntry[11] * Matrix4::m_afEntry[13]; + Real fB5 = Matrix4::m_afEntry[10] * Matrix4::m_afEntry[15] - Matrix4::m_afEntry[11] * Matrix4::m_afEntry[14]; + Real fDet = fA0 * fB5 - fA1 * fB4 + fA2 * fB3 + fA3 * fB2 - fA4 * fB1 + fA5 * fB0; + return fDet; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlMinimize1.cpp b/src/editors/xrECore/WildMagic/WmlMinimize1.cpp new file mode 100644 index 00000000000..7bc2a5cca83 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMinimize1.cpp @@ -0,0 +1,315 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlMinimize1.h" +#include "WmlMath.h" +using namespace Wml; + +//---------------------------------------------------------------------------- +template +Minimize1::Minimize1(Function oFunction, int iMaxLevel, + int iMaxBracket, void *pvData) +{ + assert(oFunction); + m_oFunction = oFunction; + m_iMaxLevel = iMaxLevel; + m_iMaxBracket = iMaxBracket; + m_pvData = pvData; +} +//---------------------------------------------------------------------------- +template +int &Minimize1::MaxLevel() +{ + return m_iMaxLevel; +} +//---------------------------------------------------------------------------- +template +int &Minimize1::MaxBracket() +{ + return m_iMaxBracket; +} +//---------------------------------------------------------------------------- +template +void *&Minimize1::UserData() +{ + return m_pvData; +} +//---------------------------------------------------------------------------- +template +void Minimize1::GetMinimum(Real fT0, Real fT1, Real fTInitial, + Real &rfTMin, Real &rfFMin) +{ + assert(fT0 <= fTInitial && fTInitial <= fT1); + + m_fTMin = Math::MAX_REAL; + m_fFMin = Math::MAX_REAL; + + Real fF0 = m_oFunction(fT0, m_pvData); + Real fFInitial = m_oFunction(fTInitial, m_pvData); + Real fF1 = m_oFunction(fT1, m_pvData); + + GetMinimum(fT0, fF0, fTInitial, fFInitial, fT1, fF1, m_iMaxLevel); + + rfTMin = m_fTMin; + rfFMin = m_fFMin; +} +//---------------------------------------------------------------------------- +template +void Minimize1::GetMinimum(Real fT0, Real fF0, Real fTm, Real fFm, + Real fT1, Real fF1, int iLevel) +{ + if (fF0 < m_fFMin) + { + m_fTMin = fT0; + m_fFMin = fF0; + } + + if (fFm < m_fFMin) + { + m_fTMin = fTm; + m_fFMin = fFm; + } + + if (fF1 < m_fFMin) + { + m_fTMin = fT1; + m_fFMin = fF1; + } + + if (iLevel-- == 0) + return; + + if ((fT1 - fTm) * (fF0 - fFm) > (fTm - fT0) * (fFm - fF1)) + { + // quadratic fit has positive second derivative at midpoint + + if (fF1 > fF0) + { + if (fFm >= fF0) + { + // increasing, repeat on [t0,tm] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + } + else + { + // not monotonic, have a bracket + GetBracketedMinimum(fT0, fF0, fTm, fFm, fT1, fF1, iLevel); + } + } + else if (fF1 < fF0) + { + if (fFm >= fF1) + { + // decreasing, repeat on [tm,t1] + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + else + { + // not monotonic, have a bracket + GetBracketedMinimum(fT0, fF0, fTm, fFm, fT1, fF1, iLevel); + } + } + else + { + // constant, repeat on [t0,tm] and [tm,t1] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + } + else + { + // quadratic fit has nonpositive second derivative at midpoint + + if (fF1 > fF0) + { + // repeat on [t0,tm] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + } + else if (fF1 < fF0) + { + // repeat on [tm,t1] + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + else + { + // repeat on [t0,tm] and [tm,t1] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + } +} +//---------------------------------------------------------------------------- +template +void Minimize1::GetMinimum(Real fT0, Real fF0, Real fT1, Real fF1, + int iLevel) +{ + if (fF0 < m_fFMin) + { + m_fTMin = fT0; + m_fFMin = fF0; + } + + if (fF1 < m_fFMin) + { + m_fTMin = fT1; + m_fFMin = fF1; + } + + if (iLevel-- == 0) + return; + + Real fTm = ((Real)0.5) * (fT0 + fT1); + Real fFm = m_oFunction(fTm, m_pvData); + + if (fF0 - ((Real)2.0) * fFm + fF1 > (Real)0.0) + { + // quadratic fit has positive second derivative at midpoint + + if (fF1 > fF0) + { + if (fFm >= fF0) + { + // increasing, repeat on [t0,tm] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + } + else + { + // not monotonic, have a bracket + GetBracketedMinimum(fT0, fF0, fTm, fFm, fT1, fF1, iLevel); + } + } + else if (fF1 < fF0) + { + if (fFm >= fF1) + { + // decreasing, repeat on [tm,t1] + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + else + { + // not monotonic, have a bracket + GetBracketedMinimum(fT0, fF0, fTm, fFm, fT1, fF1, iLevel); + } + } + else + { + // constant, repeat on [t0,tm] and [tm,t1] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + } + else + { + // quadratic fit has nonpositive second derivative at midpoint + + if (fF1 > fF0) + { + // repeat on [t0,tm] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + } + else if (fF1 < fF0) + { + // repeat on [tm,t1] + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + else + { + // repeat on [t0,tm] and [tm,t1] + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + } +} +//---------------------------------------------------------------------------- +template +void Minimize1::GetBracketedMinimum(Real fT0, Real fF0, Real fTm, + Real fFm, Real fT1, Real fF1, int iLevel) +{ + for (int i = 0; i < m_iMaxBracket; i++) + { + // update minimum value + if (fFm < m_fFMin) + { + m_fTMin = fTm; + m_fFMin = fFm; + } + + // test for convergence + const Real fEps = (Real)1e-08, fTol = (Real)1e-04; + if (Math::FAbs(fT1 - fT0) <= ((Real)2.0) * fTol * + Math::FAbs(fTm) + + fEps) + { + break; + } + + // compute vertex of interpolating parabola + Real fDT0 = fT0 - fTm, fDT1 = fT1 - fTm; + Real fDF0 = fF0 - fFm, fDF1 = fF1 - fFm; + Real fTmp0 = fDT0 * fDF1, fTmp1 = fDT1 * fDF0; + Real fDenom = fTmp1 - fTmp0; + if (Math::FAbs(fDenom) < fEps) + return; + + Real fTv = fTm + ((Real)0.5) * (fDT1 * fTmp1 - fDT0 * fTmp0) / fDenom; + assert(fT0 <= fTv && fTv <= fT1); + Real fFv = m_oFunction(fTv, m_pvData); + + if (fTv < fTm) + { + if (fFv < fFm) + { + fT1 = fTm; + fF1 = fFm; + fTm = fTv; + fFm = fFv; + } + else + { + fT0 = fTv; + fF0 = fFv; + } + } + else if (fTv > fTm) + { + if (fFv < fFm) + { + fT0 = fTm; + fF0 = fFm; + fTm = fTv; + fFm = fFv; + } + else + { + fT1 = fTv; + fF1 = fFv; + } + } + else + { + // vertex of parabola is already at middle sample point + GetMinimum(fT0, fF0, fTm, fFm, iLevel); + GetMinimum(fTm, fFm, fT1, fF1, iLevel); + } + } +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// explicit instantiation +//---------------------------------------------------------------------------- +namespace Wml +{ + template class WML_ITEM Minimize1; + template class WML_ITEM Minimize1; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlMinimize1.h b/src/editors/xrECore/WildMagic/WmlMinimize1.h new file mode 100644 index 00000000000..9e751bd3ca2 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMinimize1.h @@ -0,0 +1,55 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLMINIMIZE1H +#define WMLMINIMIZE1H + +#include "WmlSystem.h" + +namespace Wml +{ + + template + class WML_ITEM Minimize1 + { + public: + typedef Real (*Function)(Real, void *); + + Minimize1(Function oFunction, int iMaxLevel, int iMaxBracket, + void *pvData = 0); + + int &MaxLevel(); + int &MaxBracket(); + void *&UserData(); + + void GetMinimum(Real fT0, Real fT1, Real fTInitial, Real &rfTMin, + Real &rfFMin); + + protected: + Function m_oFunction; + int m_iMaxLevel, m_iMaxBracket; + Real m_fTMin, m_fFMin; + void *m_pvData; + + void GetMinimum(Real fT0, Real fF0, Real fT1, Real fF1, int iLevel); + + void GetMinimum(Real fT0, Real fF0, Real fTm, Real fFm, Real fT1, + Real fF1, int iLevel); + + void GetBracketedMinimum(Real fT0, Real fF0, Real fTm, + Real fFm, Real fT1, Real fF1, int iLevel); + }; + + typedef Minimize1 Minimize1f; + typedef Minimize1 Minimize1d; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlMinimizeN.cpp b/src/editors/xrECore/WildMagic/WmlMinimizeN.cpp new file mode 100644 index 00000000000..4982182a8dd --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMinimizeN.cpp @@ -0,0 +1,209 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlMinimizeN.h" +#include "WmlMath.h" +using namespace Wml; + +//---------------------------------------------------------------------------- +template +MinimizeN::MinimizeN(int iDimensions, Function oFunction, + int iMaxLevel, int iMaxBracket, int iMaxIterations, void *pvData) + : m_kMinimizer(LineFunction, iMaxLevel, iMaxBracket) +{ + assert(iDimensions >= 1 && oFunction); + + m_iDimensions = iDimensions; + m_oFunction = oFunction; + m_iMaxIterations = iMaxIterations; + m_pvData = pvData; + + m_afTCurr = new Real[m_iDimensions]; + m_afTSave = new Real[m_iDimensions]; + m_afDirectionStorage = new Real[m_iDimensions * (m_iDimensions + 1)]; + m_aafDirection = new Real *[m_iDimensions + 1]; + for (int i = 0; i <= m_iDimensions; i++) + m_aafDirection[i] = &m_afDirectionStorage[i * m_iDimensions]; + m_afDConj = m_aafDirection[m_iDimensions]; + + m_afLineArg = new Real[m_iDimensions]; +} +//---------------------------------------------------------------------------- +template +MinimizeN::~MinimizeN() +{ + delete[] m_afTCurr; + delete[] m_afTSave; + delete[] m_afDirectionStorage; + delete[] m_aafDirection; + delete[] m_afLineArg; +} +//---------------------------------------------------------------------------- +template +int &MinimizeN::MaxLevel() +{ + return m_kMinimizer.MaxLevel(); +} +//---------------------------------------------------------------------------- +template +int &MinimizeN::MaxBracket() +{ + return m_kMinimizer.MaxBracket(); +} +//---------------------------------------------------------------------------- +template +void *&MinimizeN::UserData() +{ + return m_pvData; +} +//---------------------------------------------------------------------------- +template +void MinimizeN::GetMinimum(const Real *afT0, const Real *afT1, + const Real *afTInitial, Real *afTMin, Real &rfFMin) +{ + // for 1D function callback + m_kMinimizer.UserData() = this; + + // initial guess + int iQuantity = m_iDimensions * sizeof(Real); + m_fFCurr = m_oFunction(afTInitial, m_pvData); + memcpy(m_afTSave, afTInitial, iQuantity); + memcpy(m_afTCurr, afTInitial, iQuantity); + + // initialize direction set to the standard Euclidean basis + memset(m_afDirectionStorage, 0, iQuantity * (m_iDimensions + 1)); + int i; + for (i = 0; i < m_iDimensions; i++) + m_aafDirection[i][i] = (Real)1.0; + + Real fL0, fL1, fLMin; + for (int iIter = 0; iIter < m_iMaxIterations; iIter++) + { + // find minimum in each direction and update current location + for (i = 0; i < m_iDimensions; i++) + { + m_afDCurr = m_aafDirection[i]; + ComputeDomain(afT0, afT1, fL0, fL1); + m_kMinimizer.GetMinimum(fL0, fL1, (Real)0.0, fLMin, m_fFCurr); + for (int j = 0; j < m_iDimensions; j++) + m_afTCurr[j] += fLMin * m_afDCurr[j]; + } + + // estimate a unit-length conjugate direction + Real fLength = (Real)0.0; + for (i = 0; i < m_iDimensions; i++) + { + m_afDConj[i] = m_afTCurr[i] - m_afTSave[i]; + fLength += m_afDConj[i] * m_afDConj[i]; + } + + const Real fEpsilon = (Real)1e-06; + fLength = Math::Sqrt(fLength); + if (fLength < fEpsilon) + { + // New position did not change significantly from old one. + // Should there be a better convergence criterion here? + break; + } + + Real fInvLength = ((Real)1.0) / fLength; + for (i = 0; i < m_iDimensions; i++) + m_afDConj[i] *= fInvLength; + + // minimize in conjugate direction + m_afDCurr = m_afDConj; + ComputeDomain(afT0, afT1, fL0, fL1); + m_kMinimizer.GetMinimum(fL0, fL1, (Real)0.0, fLMin, m_fFCurr); + for (i = 0; i < m_iDimensions; i++) + m_afTCurr[i] += fLMin * m_afDCurr[i]; + + // cycle the directions and add conjugate direction to set + m_afDConj = m_aafDirection[0]; + for (i = 0; i < m_iDimensions; i++) + m_aafDirection[i] = m_aafDirection[i + 1]; + + // set parameters for next pass + memcpy(m_afTSave, m_afTCurr, iQuantity); + } + + memcpy(afTMin, m_afTCurr, iQuantity); + rfFMin = m_fFCurr; +} +//---------------------------------------------------------------------------- +template +void MinimizeN::ComputeDomain(const Real *afT0, const Real *afT1, + Real &rfL0, Real &rfL1) +{ + rfL0 = -Math::MAX_REAL; + rfL1 = +Math::MAX_REAL; + + for (int i = 0; i < m_iDimensions; i++) + { + Real fB0 = afT0[i] - m_afTCurr[i]; + Real fB1 = afT1[i] - m_afTCurr[i]; + Real fInv; + if (m_afDCurr[i] > (Real)0.0) + { + // valid t-interval is [B0,B1] + fInv = ((Real)1.0) / m_afDCurr[i]; + fB0 *= fInv; + if (fB0 > rfL0) + rfL0 = fB0; + fB1 *= fInv; + if (fB1 < rfL1) + rfL1 = fB1; + } + else if (m_afDCurr[i] < (Real)0.0) + { + // valid t-interval is [B1,B0] + fInv = ((Real)1.0) / m_afDCurr[i]; + fB0 *= fInv; + if (fB0 < rfL1) + rfL1 = fB0; + fB1 *= fInv; + if (fB1 > rfL0) + rfL0 = fB1; + } + } + + // correction if numerical errors lead to values nearly zero + if (rfL0 > (Real)0.0) + rfL0 = (Real)0.0; + if (rfL1 < (Real)0.0) + rfL1 = (Real)0.0; +} +//---------------------------------------------------------------------------- +template +Real MinimizeN::LineFunction(Real fT, void *pvData) +{ + MinimizeN *pkThis = (MinimizeN *)pvData; + + for (int i = 0; i < pkThis->m_iDimensions; i++) + { + pkThis->m_afLineArg[i] = pkThis->m_afTCurr[i] + + fT * pkThis->m_afDCurr[i]; + } + + Real fResult = pkThis->m_oFunction(pkThis->m_afLineArg, pkThis->m_pvData); + return fResult; +} +//---------------------------------------------------------------------------- + +//---------------------------------------------------------------------------- +// explicit instantiation +//---------------------------------------------------------------------------- +namespace Wml +{ + template class WML_ITEM MinimizeN; + template class WML_ITEM MinimizeN; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlMinimizeN.h b/src/editors/xrECore/WildMagic/WmlMinimizeN.h new file mode 100644 index 00000000000..7d6e7b1ff96 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlMinimizeN.h @@ -0,0 +1,64 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLMINIMIZENH +#define WMLMINIMIZENH + +#include "WmlMinimize1.h" + +namespace Wml +{ + + template + class WML_ITEM MinimizeN + { + public: + typedef Real (*Function)(const Real *, void *); + + MinimizeN(int iDimensions, Function oFunction, int iMaxLevel, + int iMaxBracket, int iMaxIterations, void *pvData = 0); + + ~MinimizeN(); + + int &MaxLevel(); + int &MaxBracket(); + void *&UserData(); + + // find minimum on Cartesian-product domain + void GetMinimum(const Real *afT0, const Real *afT1, + const Real *afTInitial, Real *afTMin, Real &rfFMin); + + protected: + int m_iDimensions; + Function m_oFunction; + int m_iMaxIterations; + void *m_pvData; + Minimize1 m_kMinimizer; + Real *m_afDirectionStorage; + Real **m_aafDirection; + Real *m_afDConj; + Real *m_afDCurr; + Real *m_afTSave; + Real *m_afTCurr; + Real m_fFCurr; + Real *m_afLineArg; + + void ComputeDomain(const Real *afT0, const Real *afT1, Real &rfL0, + Real &rfL1); + + static Real LineFunction(Real fT, void *pvData); + }; + + typedef MinimizeN MinimizeNf; + typedef MinimizeN MinimizeNd; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlQuaternion.cpp b/src/editors/xrECore/WildMagic/WmlQuaternion.cpp new file mode 100644 index 00000000000..2b49c5c1831 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlQuaternion.cpp @@ -0,0 +1,32 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlQuaternion.h" +using namespace Wml; + +template <> +const Quaternion + Quaternion::IDENTITY(1.0f, 0.0f, 0.0f, 0.0f); +template <> +const Quaternion + Quaternion::ZERO(0.0f, 0.0f, 0.0f, 0.0f); +template <> +int Quaternion::ms_iNext[3] = {1, 2, 0}; + +template <> +const Quaternion + Quaternion::IDENTITY(1.0, 0.0, 0.0, 0.0); +template <> +const Quaternion + Quaternion::ZERO(0.0, 0.0, 0.0, 0.0); +template <> +int Quaternion::ms_iNext[3] = {1, 2, 0}; diff --git a/src/editors/xrECore/WildMagic/WmlQuaternion.h b/src/editors/xrECore/WildMagic/WmlQuaternion.h new file mode 100644 index 00000000000..19e46cdf9c2 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlQuaternion.h @@ -0,0 +1,157 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLQUATERNIONH +#define WMLQUATERNIONH + +#include "WmlMatrix3.h" + +namespace Wml +{ + + template + class Quaternion + { + public: + // A quaternion is q = w + x*i + y*j + z*k where (w,x,y,z) is not + // necessarily a unit length vector in 4D. + + // construction + Quaternion(); // uninitialized + Quaternion(Real fW, Real fX, Real fY, Real fZ); + Quaternion(const Quaternion &rkQ); + + // quaternion for the input rotation matrix + Quaternion(const Matrix3 &rkRot); + + // quaternion for the rotation of the axis-angle pair + Quaternion(const Vector3 &rkAxis, Real fAngle); + + // quaternion for the rotation matrix with specified columns + Quaternion(const Vector3 akRotColumn[3]); + + // member access: 0 = w, 1 = x, 2 = y, 3 = z + operator const Real *() const; + operator Real *(); + Real operator[](int i) const; + Real &operator[](int i); + Real W() const; + Real &W(); + Real X() const; + Real &X(); + Real Y() const; + Real &Y(); + Real Z() const; + Real &Z(); + + // assignment and comparison + Quaternion &operator=(const Quaternion &rkQ); + bool operator==(const Quaternion &rkQ) const; + bool operator!=(const Quaternion &rkQ) const; + bool operator<(const Quaternion &rkQ) const; + bool operator<=(const Quaternion &rkQ) const; + bool operator>(const Quaternion &rkQ) const; + bool operator>=(const Quaternion &rkQ) const; + + // arithmetic operations + Quaternion operator+(const Quaternion &rkQ) const; + Quaternion operator-(const Quaternion &rkQ) const; + Quaternion operator*(const Quaternion &rkQ) const; + Quaternion operator*(Real fScalar) const; + Quaternion operator/(Real fScalar) const; + Quaternion operator-() const; + + // arithmetic updates + Quaternion &operator+=(const Quaternion &rkQ); + Quaternion &operator-=(const Quaternion &rkQ); + Quaternion &operator*=(Real fScalar); + Quaternion &operator/=(Real fScalar); + + // conversion between quaternions, matrices, and axis-angle + void FromRotationMatrix(const Matrix3 &rkRot); + void ToRotationMatrix(Matrix3 &rkRot) const; + void FromRotationMatrix(const Vector3 akRotColumn[3]); + void ToRotationMatrix(Vector3 akRotColumn[3]) const; + void FromAxisAngle(const Vector3 &rkAxis, Real fAngle); + void ToAxisAngle(Vector3 &rkAxis, Real &rfAngle) const; + + // functions of a quaternion + Real Dot(const Quaternion &rkQ) const; // dot product + Quaternion Inverse() const; // apply to non-zero quaternion + Quaternion Conjugate() const; + Quaternion Exp() const; // apply to quaternion with w = 0 + Quaternion Log() const; // apply to unit-length quaternion + + // rotation of a vector by a quaternion + Vector3 operator*(const Vector3 &rkVector) const; + + // spherical linear interpolation + static Quaternion Slerp(Real fT, const Quaternion &rkP, + const Quaternion &rkQ); + + static Quaternion SlerpExtraSpins(Real fT, const Quaternion &rkP, + const Quaternion &rkQ, int iExtraSpins); + + // intermediate terms for spherical quadratic interpolation + static Quaternion GetIntermediate(const Quaternion &rkQ0, + const Quaternion &rkQ1, const Quaternion &rkQ2); + + // spherical quadratic interpolation + static Quaternion Squad(Real fT, const Quaternion &rkQ0, + const Quaternion &rkA0, const Quaternion &rkA1, + const Quaternion &rkQ1); + + // Compute a quaternion that rotates unit-length vector V1 to unit-length + // vector V2. The rotation is about the axis perpendicular to both V1 and + // V2, with angle of that between V1 and V2. If V1 and V2 are parallel, + // any axis of rotation will do, such as the permutation (z2,x2,y2), where + // V2 = (x2,y2,z2). + static Quaternion Align(const Vector3 &rkV1, + const Vector3 &rkV2); + + // Decompose a quaternion into q = q_twist * q_no_twist, where q is 'this' + // quaternion. If V1 is the input axis and V2 is the rotation of V1 by + // q, q_no_twist represents the rotation about the axis perpendicular to + // V1 and V2 (see Quaternion::Align), and q_twist is a rotation about V1. + void DecomposeTwistTimesNoTwist(const Vector3 &rkAxis, + Quaternion &rkTwist, Quaternion &rkNoTwist); + + // Decompose a quaternion into q = q_no_twist * q_twist, where q is 'this' + // quaternion. If V1 is the input axis and V2 is the rotation of V1 by + // q, q_no_twist represents the rotation about the axis perpendicular to + // V1 and V2 (see Quaternion::Align), and q_twist is a rotation about V1. + void DecomposeNoTwistTimesTwist(const Vector3 &rkAxis, + Quaternion &rkTwist, Quaternion &rkNoTwist); + + // special values + WML_ITEM static const Quaternion IDENTITY; // the identity rotation + WML_ITEM static const Quaternion ZERO; + + protected: + // support for comparisons + int CompareArrays(const Quaternion &rkQ) const; + + // support for FromRotationMatrix + static int ms_iNext[3]; + + Real m_afTuple[4]; + }; + + template + Quaternion operator*(Real fScalar, const Quaternion &rkQ); + +#include "WmlQuaternion.inl" + + typedef Quaternion Quaternionf; + typedef Quaternion Quaterniond; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlQuaternion.inl b/src/editors/xrECore/WildMagic/WmlQuaternion.inl new file mode 100644 index 00000000000..ddc820b6007 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlQuaternion.inl @@ -0,0 +1,710 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +Quaternion::Quaternion() +{ + // the object is uninitialized +} +//---------------------------------------------------------------------------- +template +Quaternion::Quaternion(Real fW, Real fX, Real fY, Real fZ) +{ + m_afTuple[0] = fW; + m_afTuple[1] = fX; + m_afTuple[2] = fY; + m_afTuple[3] = fZ; +} +//---------------------------------------------------------------------------- +template +Quaternion::Quaternion(const Quaternion &rkQ) +{ + memcpy(m_afTuple, rkQ.m_afTuple, 4 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Quaternion::Quaternion(const Matrix3 &rkRot) +{ + FromRotationMatrix(rkRot); +} +//---------------------------------------------------------------------------- +template +Quaternion::Quaternion(const Vector3 &rkAxis, Real fAngle) +{ + FromAxisAngle(rkAxis, fAngle); +} +//---------------------------------------------------------------------------- +template +Quaternion::Quaternion(const Vector3 akRotColumn[3]) +{ + FromRotationMatrix(akRotColumn); +} +//---------------------------------------------------------------------------- +template +Quaternion::operator const Real *() const +{ + return m_afTuple; +} +//---------------------------------------------------------------------------- +template +Quaternion::operator Real *() +{ + return m_afTuple; +} +//---------------------------------------------------------------------------- +template +Real Quaternion::operator[](int i) const +{ + assert(0 <= i && i < 4); + return m_afTuple[i]; +} +//---------------------------------------------------------------------------- +template +Real &Quaternion::operator[](int i) +{ + assert(0 <= i && i < 4); + return m_afTuple[i]; +} +//---------------------------------------------------------------------------- +template +Real Quaternion::W() const +{ + return m_afTuple[0]; +} +//---------------------------------------------------------------------------- +template +Real &Quaternion::W() +{ + return m_afTuple[0]; +} +//---------------------------------------------------------------------------- +template +Real Quaternion::X() const +{ + return m_afTuple[1]; +} +//---------------------------------------------------------------------------- +template +Real &Quaternion::X() +{ + return m_afTuple[1]; +} +//---------------------------------------------------------------------------- +template +Real Quaternion::Y() const +{ + return m_afTuple[2]; +} +//---------------------------------------------------------------------------- +template +Real &Quaternion::Y() +{ + return m_afTuple[2]; +} +//---------------------------------------------------------------------------- +template +Real Quaternion::Z() const +{ + return m_afTuple[3]; +} +//---------------------------------------------------------------------------- +template +Real &Quaternion::Z() +{ + return m_afTuple[3]; +} +//---------------------------------------------------------------------------- +template +Quaternion &Quaternion::operator=(const Quaternion &rkQ) +{ + memcpy(m_afTuple, rkQ.m_afTuple, 4 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +bool Quaternion::operator==(const Quaternion &rkQ) const +{ + for (int i = 0; i < 4; i++) + { + if (m_afTuple[i] != rkQ.m_afTuple[i]) + return false; + } + return true; +} +//---------------------------------------------------------------------------- +template +bool Quaternion::operator!=(const Quaternion &rkQ) const +{ + return !operator==(rkQ); +} +//---------------------------------------------------------------------------- +template +int Quaternion::CompareArrays(const Quaternion &rkQ) const +{ + return memcmp(m_afTuple, rkQ.m_afTuple, 4 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +bool Quaternion::operator<(const Quaternion &rkQ) const +{ + return CompareArrays(rkQ) < 0; +} +//---------------------------------------------------------------------------- +template +bool Quaternion::operator<=(const Quaternion &rkQ) const +{ + return CompareArrays(rkQ) <= 0; +} +//---------------------------------------------------------------------------- +template +bool Quaternion::operator>(const Quaternion &rkQ) const +{ + return CompareArrays(rkQ) > 0; +} +//---------------------------------------------------------------------------- +template +bool Quaternion::operator>=(const Quaternion &rkQ) const +{ + return CompareArrays(rkQ) >= 0; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::operator+(const Quaternion &rkQ) const +{ + Quaternion kSum; + for (int i = 0; i < 4; i++) + kSum.m_afTuple[i] = m_afTuple[i] + rkQ.m_afTuple[i]; + return kSum; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::operator-(const Quaternion &rkQ) const +{ + Quaternion kDiff; + for (int i = 0; i < 4; i++) + kDiff.m_afTuple[i] = m_afTuple[i] - rkQ.m_afTuple[i]; + return kDiff; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::operator*(const Quaternion &rkQ) const +{ + // NOTE: Multiplication is not generally commutative, so in most + // cases p*q != q*p. + + Quaternion kProd; + + kProd.m_afTuple[0] = + m_afTuple[0] * rkQ.m_afTuple[0] - + m_afTuple[1] * rkQ.m_afTuple[1] - + m_afTuple[2] * rkQ.m_afTuple[2] - + m_afTuple[3] * rkQ.m_afTuple[3]; + + kProd.m_afTuple[1] = + m_afTuple[0] * rkQ.m_afTuple[1] + + m_afTuple[1] * rkQ.m_afTuple[0] + + m_afTuple[2] * rkQ.m_afTuple[3] - + m_afTuple[3] * rkQ.m_afTuple[2]; + + kProd.m_afTuple[2] = + m_afTuple[0] * rkQ.m_afTuple[2] + + m_afTuple[2] * rkQ.m_afTuple[0] + + m_afTuple[3] * rkQ.m_afTuple[1] - + m_afTuple[1] * rkQ.m_afTuple[3]; + + kProd.m_afTuple[3] = + m_afTuple[0] * rkQ.m_afTuple[3] + + m_afTuple[3] * rkQ.m_afTuple[0] + + m_afTuple[1] * rkQ.m_afTuple[2] - + m_afTuple[2] * rkQ.m_afTuple[1]; + + return kProd; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::operator*(Real fScalar) const +{ + Quaternion kProd; + for (int i = 0; i < 4; i++) + kProd.m_afTuple[i] = fScalar * m_afTuple[i]; + return kProd; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::operator/(Real fScalar) const +{ + Quaternion kQuot; + int i; + + if (fScalar != (Real)0.0) + { + Real fInvScalar = ((Real)1.0) / fScalar; + for (i = 0; i < 4; i++) + kQuot.m_afTuple[i] = fInvScalar * m_afTuple[i]; + } + else + { + for (i = 0; i < 4; i++) + kQuot.m_afTuple[i] = Math::MAX_REAL; + } + + return kQuot; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::operator-() const +{ + Quaternion kNeg; + for (int i = 0; i < 4; i++) + kNeg.m_afTuple[i] = -m_afTuple[i]; + return kNeg; +} +//---------------------------------------------------------------------------- +template +Quaternion operator*(Real fScalar, const Quaternion &rkQ) +{ + Quaternion kProd; + for (int i = 0; i < 4; i++) + kProd[i] = fScalar * rkQ[i]; + return kProd; +} +//---------------------------------------------------------------------------- +template +Quaternion &Quaternion::operator+=(const Quaternion &rkQ) +{ + for (int i = 0; i < 4; i++) + m_afTuple[i] += rkQ.m_afTuple[i]; + return *this; +} +//---------------------------------------------------------------------------- +template +Quaternion &Quaternion::operator-=(const Quaternion &rkQ) +{ + for (int i = 0; i < 4; i++) + m_afTuple[i] -= rkQ.m_afTuple[i]; + return *this; +} +//---------------------------------------------------------------------------- +template +Quaternion &Quaternion::operator*=(Real fScalar) +{ + for (int i = 0; i < 4; i++) + m_afTuple[i] *= fScalar; + return *this; +} +//---------------------------------------------------------------------------- +template +Quaternion &Quaternion::operator/=(Real fScalar) +{ + int i; + + if (fScalar != (Real)0.0) + { + Real fInvScalar = ((Real)1.0) / fScalar; + for (i = 0; i < 4; i++) + m_afTuple[i] *= fInvScalar; + } + else + { + for (i = 0; i < 4; i++) + m_afTuple[i] = Math::MAX_REAL; + } + + return *this; +} +//---------------------------------------------------------------------------- +template +void Quaternion::FromRotationMatrix(const Matrix3 &rkRot) +{ + // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes + // article "Quaternion Calculus and Fast Animation". + + Real fTrace = rkRot(0, 0) + rkRot(1, 1) + rkRot(2, 2); + Real fRoot; + + if (fTrace > (Real)0.0) + { + // |w| > 1/2, may as well choose w > 1/2 + fRoot = Math::Sqrt(fTrace + (Real)1.0); // 2w + m_afTuple[0] = ((Real)0.5) * fRoot; + fRoot = ((Real)0.5) / fRoot; // 1/(4w) + m_afTuple[1] = (rkRot(2, 1) - rkRot(1, 2)) * fRoot; + m_afTuple[2] = (rkRot(0, 2) - rkRot(2, 0)) * fRoot; + m_afTuple[3] = (rkRot(1, 0) - rkRot(0, 1)) * fRoot; + } + else + { + // |w| <= 1/2 + int i = 0; + if (rkRot(1, 1) > rkRot(0, 0)) + i = 1; + if (rkRot(2, 2) > rkRot(i, i)) + i = 2; + int j = ms_iNext[i]; + int k = ms_iNext[j]; + + fRoot = Math::Sqrt(rkRot(i, i) - rkRot(j, j) - rkRot(k, k) + (Real)1.0); + Real *apfQuat[3] = {&m_afTuple[1], &m_afTuple[2], &m_afTuple[3]}; + *apfQuat[i] = ((Real)0.5) * fRoot; + fRoot = ((Real)0.5) / fRoot; + m_afTuple[0] = (rkRot(k, j) - rkRot(j, k)) * fRoot; + *apfQuat[j] = (rkRot(j, i) + rkRot(i, j)) * fRoot; + *apfQuat[k] = (rkRot(k, i) + rkRot(i, k)) * fRoot; + } +} +//---------------------------------------------------------------------------- +template +void Quaternion::ToRotationMatrix(Matrix3 &rkRot) const +{ + Real fTx = ((Real)2.0) * m_afTuple[1]; + Real fTy = ((Real)2.0) * m_afTuple[2]; + Real fTz = ((Real)2.0) * m_afTuple[3]; + Real fTwx = fTx * m_afTuple[0]; + Real fTwy = fTy * m_afTuple[0]; + Real fTwz = fTz * m_afTuple[0]; + Real fTxx = fTx * m_afTuple[1]; + Real fTxy = fTy * m_afTuple[1]; + Real fTxz = fTz * m_afTuple[1]; + Real fTyy = fTy * m_afTuple[2]; + Real fTyz = fTz * m_afTuple[2]; + Real fTzz = fTz * m_afTuple[3]; + + rkRot(0, 0) = ((Real)1.0) - (fTyy + fTzz); + rkRot(0, 1) = fTxy - fTwz; + rkRot(0, 2) = fTxz + fTwy; + rkRot(1, 0) = fTxy + fTwz; + rkRot(1, 1) = ((Real)1.0) - (fTxx + fTzz); + rkRot(1, 2) = fTyz - fTwx; + rkRot(2, 0) = fTxz - fTwy; + rkRot(2, 1) = fTyz + fTwx; + rkRot(2, 2) = ((Real)1.0) - (fTxx + fTyy); +} +//---------------------------------------------------------------------------- +template +void Quaternion::FromRotationMatrix(const Vector3 akRotColumn[3]) +{ + Matrix3 kRot; + for (int iCol = 0; iCol < 3; iCol++) + { + kRot(0, iCol) = akRotColumn[iCol][0]; + kRot(1, iCol) = akRotColumn[iCol][1]; + kRot(2, iCol) = akRotColumn[iCol][2]; + } + FromRotationMatrix(kRot); +} +//---------------------------------------------------------------------------- +template +void Quaternion::ToRotationMatrix(Vector3 akRotColumn[3]) const +{ + Matrix3 kRot; + ToRotationMatrix(kRot); + for (int iCol = 0; iCol < 3; iCol++) + { + akRotColumn[iCol][0] = kRot(0, iCol); + akRotColumn[iCol][1] = kRot(1, iCol); + akRotColumn[iCol][2] = kRot(2, iCol); + } +} +//---------------------------------------------------------------------------- +template +void Quaternion::FromAxisAngle(const Vector3 &rkAxis, + Real fAngle) +{ + // assert: axis[] is unit length + // + // The quaternion representing the rotation is + // q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k) + + Real fHalfAngle = ((Real)0.5) * fAngle; + Real fSin = Math::Sin(fHalfAngle); + m_afTuple[0] = Math::Cos(fHalfAngle); + m_afTuple[1] = fSin * rkAxis[0]; + m_afTuple[2] = fSin * rkAxis[1]; + m_afTuple[3] = fSin * rkAxis[2]; +} +//---------------------------------------------------------------------------- +template +void Quaternion::ToAxisAngle(Vector3 &rkAxis, Real &rfAngle) + const +{ + // The quaternion representing the rotation is + // q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k) + + Real fSqrLength = m_afTuple[1] * m_afTuple[1] + m_afTuple[2] * m_afTuple[2] + m_afTuple[3] * m_afTuple[3]; + if (fSqrLength > Math::EPSILON) + { + rfAngle = ((Real)2.0) * Math::ACos(m_afTuple[0]); + Real fInvLength = Math::InvSqrt(fSqrLength); + rkAxis[0] = m_afTuple[1] * fInvLength; + rkAxis[1] = m_afTuple[2] * fInvLength; + rkAxis[2] = m_afTuple[3] * fInvLength; + } + else + { + // angle is 0 (mod 2*pi), so any axis will do + rfAngle = (Real)0.0; + rkAxis[0] = (Real)1.0; + rkAxis[1] = (Real)0.0; + rkAxis[2] = (Real)0.0; + } +} +//---------------------------------------------------------------------------- +template +Real Quaternion::Dot(const Quaternion &rkQ) const +{ + Real fDot = (Real)0.0; + for (int i = 0; i < 4; i++) + fDot += m_afTuple[i] * rkQ.m_afTuple[i]; + return fDot; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::Inverse() const +{ + Quaternion kInverse; + + Real fNorm = (Real)0.0; + int i; + for (i = 0; i < 4; i++) + fNorm += m_afTuple[i] * m_afTuple[i]; + + if (fNorm > (Real)0.0) + { + Real fInvNorm = ((Real)1.0) / fNorm; + kInverse.m_afTuple[0] = m_afTuple[0] * fInvNorm; + kInverse.m_afTuple[1] = -m_afTuple[1] * fInvNorm; + kInverse.m_afTuple[2] = -m_afTuple[2] * fInvNorm; + kInverse.m_afTuple[3] = -m_afTuple[3] * fInvNorm; + } + else + { + // return an invalid result to flag the error + for (i = 0; i < 4; i++) + kInverse.m_afTuple[i] = (Real)0.0; + } + + return kInverse; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::Conjugate() const +{ + // assert: 'this' is unit length + return Quaternion(m_afTuple[0], -m_afTuple[1], -m_afTuple[2], + -m_afTuple[3]); +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::Exp() const +{ + // If q = A*(x*i+y*j+z*k) where (x,y,z) is unit length, then + // exp(q) = cos(A)+sin(A)*(x*i+y*j+z*k). If sin(A) is near zero, + // use exp(q) = cos(A)+A*(x*i+y*j+z*k) since A/sin(A) has limit 1. + + Quaternion kResult; + + Real fAngle = Math::Sqrt(m_afTuple[1] * m_afTuple[1] + + m_afTuple[2] * m_afTuple[2] + m_afTuple[3] * m_afTuple[3]); + + Real fSin = Math::Sin(fAngle); + kResult.m_afTuple[0] = Math::Cos(fAngle); + + int i; + + if (Math::FAbs(fSin) >= Math::EPSILON) + { + Real fCoeff = fSin / fAngle; + for (i = 1; i <= 3; i++) + kResult.m_afTuple[i] = fCoeff * m_afTuple[i]; + } + else + { + for (i = 1; i <= 3; i++) + kResult.m_afTuple[i] = m_afTuple[i]; + } + + return kResult; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::Log() const +{ + // If q = cos(A)+sin(A)*(x*i+y*j+z*k) where (x,y,z) is unit length, then + // log(q) = A*(x*i+y*j+z*k). If sin(A) is near zero, use log(q) = + // sin(A)*(x*i+y*j+z*k) since sin(A)/A has limit 1. + + Quaternion kResult; + kResult.m_afTuple[0] = (Real)0.0; + + int i; + + if (Math::FAbs(m_afTuple[0]) < (Real)1.0) + { + Real fAngle = Math::ACos(m_afTuple[0]); + Real fSin = Math::Sin(fAngle); + if (Math::FAbs(fSin) >= Math::EPSILON) + { + Real fCoeff = fAngle / fSin; + for (i = 1; i <= 3; i++) + kResult.m_afTuple[i] = fCoeff * m_afTuple[i]; + return kResult; + } + } + + for (i = 1; i <= 3; i++) + kResult.m_afTuple[i] = m_afTuple[i]; + return kResult; +} +//---------------------------------------------------------------------------- +template +Vector3 Quaternion::operator*(const Vector3 &rkVector) + const +{ + // Given a vector u = (x0,y0,z0) and a unit length quaternion + // q = , the vector v = (x1,y1,z1) which represents the + // rotation of u by q is v = q*u*q^{-1} where * indicates quaternion + // multiplication and where u is treated as the quaternion <0,x0,y0,z0>. + // Note that q^{-1} = , so no real work is required to + // invert q. Now + // + // q*u*q^{-1} = q*<0,x0,y0,z0>*q^{-1} + // = q*(x0*i+y0*j+z0*k)*q^{-1} + // = x0*(q*i*q^{-1})+y0*(q*j*q^{-1})+z0*(q*k*q^{-1}) + // + // As 3-vectors, q*i*q^{-1}, q*j*q^{-1}, and 2*k*q^{-1} are the columns + // of the rotation matrix computed in Quaternion::ToRotationMatrix. + // The vector v is obtained as the product of that rotation matrix with + // vector u. As such, the quaternion representation of a rotation + // matrix requires less space than the matrix and more time to compute + // the rotated vector. Typical space-time tradeoff... + + Matrix3 kRot; + ToRotationMatrix(kRot); + return kRot * rkVector; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::Slerp(Real fT, const Quaternion &rkP, + const Quaternion &rkQ) +{ + Real fCos = rkP.Dot(rkQ); + Real fAngle = Math::ACos(fCos); + + if (Math::FAbs(fAngle) < Math::EPSILON) + return rkP; + + Real fSin = Math::Sin(fAngle); + Real fInvSin = ((Real)1.0) / fSin; + Real fCoeff0 = Math::Sin((((Real)1.0) - fT) * fAngle) * fInvSin; + Real fCoeff1 = Math::Sin(fT * fAngle) * fInvSin; + return fCoeff0 * rkP + fCoeff1 * rkQ; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::SlerpExtraSpins(Real fT, + const Quaternion &rkP, const Quaternion &rkQ, int iExtraSpins) +{ + Real fCos = rkP.Dot(rkQ); + Real fAngle = Math::ACos(fCos); + + if (Math::FAbs(fAngle) < Math::EPSILON) + return rkP; + + Real fSin = Math::Sin(fAngle); + Real fPhase = Math::_PI * iExtraSpins * fT; + Real fInvSin = ((Real)1.0) / fSin; + Real fCoeff0 = Math::Sin((((Real)1.0) - fT) * fAngle - fPhase) * fInvSin; + Real fCoeff1 = Math::Sin(fT * fAngle + fPhase) * fInvSin; + return fCoeff0 * rkP + fCoeff1 * rkQ; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::GetIntermediate(const Quaternion &rkQ0, + const Quaternion &rkQ1, const Quaternion &rkQ2) +{ + // assert: Q0, Q1, Q2 all unit-length + Quaternion kQ1Inv = rkQ1.Conjugate(); + Quaternion kP0 = kQ1Inv * rkQ0; + Quaternion kP2 = kQ1Inv * rkQ2; + Quaternion kArg = -((Real)0.25) * (kP0.Log() + kP2.Log()); + Quaternion kA = rkQ1 * kArg.Exp(); + return kA; +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::Squad(Real fT, const Quaternion &rkQ0, + const Quaternion &rkA0, const Quaternion &rkA1, const Quaternion &rkQ1) +{ + Real fSlerpT = ((Real)2.0) * fT * (((Real)1.0) - fT); + Quaternion kSlerpP = Slerp(fT, rkQ0, rkQ1); + Quaternion kSlerpQ = Slerp(fT, rkA0, rkA1); + return Slerp(fSlerpT, kSlerpP, kSlerpQ); +} +//---------------------------------------------------------------------------- +template +Quaternion Quaternion::Align(const Vector3 &rkV1, + const Vector3 &rkV2) +{ + // If V1 and V2 are not parallel, the axis of rotation is the unit-length + // vector U = Cross(V1,V2)/Length(Cross(V1,V2)). The angle of rotation, + // A, is the angle between V1 and V2. The quaternion for the rotation is + // q = cos(A/2) + sin(A/2)*(ux*i+uy*j+uz*k) where U = (ux,uy,uz). + // + // (1) Rather than extract A = acos(Dot(V1,V2)), multiply by 1/2, then + // compute sin(A/2) and cos(A/2), we reduce the computational costs by + // computing the bisector B = (V1+V2)/Length(V1+V2), so cos(A/2) = + // Dot(V1,B). + // + // (2) The rotation axis is U = Cross(V1,B)/Length(Cross(V1,B)), but + // Length(Cross(V1,B)) = Length(V1)*Length(B)*sin(A/2) = sin(A/2), in + // which case sin(A/2)*(ux*i+uy*j+uz*k) = (cx*i+cy*j+cz*k) where + // C = Cross(V1,B). + // + // If V1 and V2 are parallel, or nearly parallel as far as the floating + // point calculations are concerned, the calculation of B will produce + // the zero vector: Vector3::Normalize checks for closeness to zero and + // returns the zero vector accordingly. Thus, we test for parallelism + // by checking if cos(A/2) is zero. The test for exactly zero is usually + // not recommend for floating point arithmetic, but the implementation of + // Vector3::Normalize guarantees the comparison is robust. + + Vector3 kBisector = rkV1 + rkV2; + kBisector.Normalize(); + + Real fCosHalfAngle = rkV1.Dot(kBisector); + Vector3 kCross; + + if (fCosHalfAngle != (Real)0.0) + kCross = rkV1.Cross(kBisector); + else + kCross = rkV1.UnitCross(Vector3(rkV2.Z(), rkV2.X(), rkV2.Y())); + + return Quaternion(fCosHalfAngle, kCross.X(), kCross.Y(), kCross.Z()); +} +//---------------------------------------------------------------------------- +template +void Quaternion::DecomposeTwistTimesNoTwist( + const Vector3 &rkAxis, Quaternion &rkTwist, Quaternion &rkNoTwist) +{ + Vector3 kRotatedAxis = (*this) * rkAxis; + rkNoTwist = Align(rkAxis, kRotatedAxis); + rkTwist = (*this) * rkNoTwist.Conjugate(); +} +//---------------------------------------------------------------------------- +template +void Quaternion::DecomposeNoTwistTimesTwist( + const Vector3 &rkAxis, Quaternion &rkTwist, Quaternion &rkNoTwist) +{ + Vector3 kRotatedAxis = (*this) * rkAxis; + rkNoTwist = Align(rkAxis, kRotatedAxis); + rkTwist = rkNoTwist.Conjugate() * (*this); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlSystem.cpp b/src/editors/xrECore/WildMagic/WmlSystem.cpp new file mode 100644 index 00000000000..71bc8d303fa --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlSystem.cpp @@ -0,0 +1,71 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlSystem.h" +using namespace Wml; + +//---------------------------------------------------------------------------- +void Wml::System::SwapBytes(int iSize, void *pvValue) +{ + assert(iSize >= 1); + if (iSize == 1) + return; + + // size must be even + assert((iSize & 1) == 0); + + char *acBytes = (char *)pvValue; + for (int i0 = 0, i1 = iSize - 1; i0 < iSize / 2; i0++, i1--) + { + char cSave = acBytes[i0]; + acBytes[i0] = acBytes[i1]; + acBytes[i1] = cSave; + } +} +//---------------------------------------------------------------------------- +void Wml::System::SwapBytes(int iSize, int iQuantity, void *pvValue) +{ + assert(iSize >= 1); + if (iSize == 1) + return; + + // size must be even + assert((iSize & 1) == 0); + + char *acBytes = (char *)pvValue; + for (int i = 0; i < iQuantity; i++, acBytes += iSize) + { + for (int i0 = 0, i1 = iSize - 1; i0 < iSize / 2; i0++, i1--) + { + char cSave = acBytes[i0]; + acBytes[i0] = acBytes[i1]; + acBytes[i1] = cSave; + } + } +} +//---------------------------------------------------------------------------- +bool Wml::System::IsPowerOfTwo(int iValue) +{ + return (iValue != 0) && ((iValue & -iValue) == iValue); +} +//---------------------------------------------------------------------------- +bool Wml::System::FileExists(const char *acFilename) +{ + FILE *pkFile = fopen(acFilename, "r"); + if (pkFile) + { + fclose(pkFile); + return true; + } + return false; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlSystem.h b/src/editors/xrECore/WildMagic/WmlSystem.h new file mode 100644 index 00000000000..9815dcc3cf0 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlSystem.h @@ -0,0 +1,96 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLSYSTEMH +#define WMLSYSTEMH + +#ifndef WIN32 +#define WIN32 +#endif + +// Microsoft Windows +#if defined(WIN32) +#include "WmlWinSystem.h" + +// Macintosh OS X +#elif defined(__APPLE__) +#include "WmlMacSystem.h" + +// SGI IRIX +#elif defined(SGI_IRIX) +#include "WmlIrixSystem.h" + +// HP-UX +#elif defined(HP_UX) +#include "WmlHpuxSystem.h" + +// Sun SOLARIS +#elif defined(SUN_SOLARIS) +#include "WmlSolarisSystem.h" + +// Linux on a PC. Red Hat 8.x g++ has problems with specialized instantiation +// of static members in template classes *before* the class itself is +// explicitly instantiated. The problem is not consistent; for example, Math +// Vector*, and Matrix* classes compile fine, but not Integrate1 or +// BSplineRectangle. +#else +#include "WmlLnxSystem.h" + +#endif + +namespace Wml +{ + + class WML_ITEM System + { + public: + // little/big endian support + static void SwapBytes(int iSize, void *pvValue); + static void SwapBytes(int iSize, int iQuantity, void *pvValue); + static void EndianCopy(int iSize, const void *pvSrc, void *pvDst); + static void EndianCopy(int iSize, int iQuantity, const void *pvSrc, + void *pvDst); + + static unsigned int MakeRGB(unsigned char ucR, unsigned char ucG, + unsigned char ucB); + + static unsigned int MakeRGBA(unsigned char ucR, unsigned char ucG, + unsigned char ucB, unsigned char ucA); + + // time utilities + static double GetTime(); + + // TO DO. Pathname handling to access files in subdirectories. + static bool FileExists(const char *acFilename); + + // convenient utilities + static bool IsPowerOfTwo(int iValue); + }; + + // allocation and deallocation of 2D arrays + template + void Allocate2D(int iCols, int iRows, T **&raatArray); + template + void Deallocate2D(T **aatArray); + + // allocation and deallocation of 3D arrays + template + void Allocate3D(int iCols, int iRows, int iSlices, + T ***&raaatArray); + template + void Deallocate3D(int iRows, int iSlices, + T ***aaatArray); + +#include "WmlSystem.inl" +#include "WmlSystem.mcr" + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlSystem.inl b/src/editors/xrECore/WildMagic/WmlSystem.inl new file mode 100644 index 00000000000..9149f6cbed2 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlSystem.inl @@ -0,0 +1,51 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +void Allocate2D(int iCols, int iRows, T **&raatArray) +{ + raatArray = new T *[iRows]; + raatArray[0] = new T[iRows * iCols]; + for (int iRow = 1; iRow < iRows; iRow++) + raatArray[iRow] = &raatArray[0][iCols * iRow]; +} +//---------------------------------------------------------------------------- +template +void Deallocate2D(T **aatArray) +{ + delete[] aatArray[0]; + delete[] aatArray; +} +//---------------------------------------------------------------------------- +template +void Allocate3D(int iCols, int iRows, int iSlices, T ***&raaatArray) +{ + raaatArray = new T **[iSlices]; + for (int iSlice = 0; iSlice < iSlices; iSlice++) + { + raaatArray[iSlice] = new T *[iRows]; + for (int iRow = 0; iRow < iRows; iRow++) + raaatArray[iSlice][iRow] = new T[iCols]; + } +} +//---------------------------------------------------------------------------- +template +void Deallocate3D(int iRows, int iSlices, T ***aaatArray) +{ + for (int iSlice = 0; iSlice < iSlices; iSlice++) + { + for (int iRow = 0; iRow < iRows; iRow++) + delete[] aaatArray[iSlice][iRow]; + delete[] aaatArray[iSlice]; + } + delete[] aaatArray; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlSystem.mcr b/src/editors/xrECore/WildMagic/WmlSystem.mcr new file mode 100644 index 00000000000..ef468caaf1a --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlSystem.mcr @@ -0,0 +1,39 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLSYSTEM_MCR +#define WMLSYSTEM_MCR + +// Fast conversion from a IEEE 32-bit floating point number F in [0,1] to a +// a 32-bit integer I in [0,2^L-1]. +// +// fFloat = F +// iLog = L +// iInt = I + +#define WmlScaledFloatToInt(fFloat,iLog,iInt)\ +{ \ + int iShift = 150 - iLog - ((*(int*)(&fFloat) >> 23) & 0xFF); \ + if ( iShift < 24 ) \ + { \ + iInt = ((*(int*)(&fFloat) & 0x007FFFFF) | \ + 0x00800000) >> iShift; \ + if ( iInt == (1 << iLog) ) \ + { \ + iInt--; \ + } \ + } \ + else \ + { \ + iInt = 0; \ + } \ +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlVector.h b/src/editors/xrECore/WildMagic/WmlVector.h new file mode 100644 index 00000000000..dd64f0cca67 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector.h @@ -0,0 +1,78 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLVECTOR_H +#define WMLVECTOR_H + +#include "WmlMath.h" + +namespace Wml +{ + + template + class Vector + { + public: + // construction + Vector(); + Vector(const Real *afTuple); + Vector(const Vector &rkV); + + // coordinate access + operator const Real *() const; + operator Real *(); + Real operator[](int i) const; + Real &operator[](int i); + + // assignment + Vector &operator=(const Vector &rkV); + + // comparison + bool operator==(const Vector &rkV) const; + bool operator!=(const Vector &rkV) const; + bool operator<(const Vector &rkV) const; + bool operator<=(const Vector &rkV) const; + bool operator>(const Vector &rkV) const; + bool operator>=(const Vector &rkV) const; + + // arithmetic operations + Vector operator+(const Vector &rkV) const; + Vector operator-(const Vector &rkV) const; + Vector operator*(Real fScalar) const; + Vector operator/(Real fScalar) const; + Vector operator-() const; + + // arithmetic updates + Vector &operator+=(const Vector &rkV); + Vector &operator-=(const Vector &rkV); + Vector &operator*=(Real fScalar); + Vector &operator/=(Real fScalar); + + // vector operations + Real Length() const; + Real SquaredLength() const; + Real Dot(const Vector &rkV) const; + Real Normalize(); + + protected: + // support for comparisons + int CompareArrays(const Vector &rkV) const; + + Real m_afTuple[N]; + }; + + template + Vector operator*(Real fScalar, const Vector &rkV); + +#include "WmlVector.inl" + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlVector.inl b/src/editors/xrECore/WildMagic/WmlVector.inl new file mode 100644 index 00000000000..e3d9dd50017 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector.inl @@ -0,0 +1,264 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +Vector::Vector() +{ + // For efficiency in construction of large arrays of vectors, the + // default constructor does not initialize the vector. +} +//---------------------------------------------------------------------------- +template +Vector::Vector(const Real *afTuple) +{ + memcpy(Vector::m_afTuple, afTuple, N * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Vector::Vector(const Vector &rkV) +{ + memcpy(Vector::m_afTuple, rkV.Vector::m_afTuple, N * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Vector::operator const Real *() const +{ + return Vector::m_afTuple; +} +//---------------------------------------------------------------------------- +template +Vector::operator Real *() +{ + return Vector::m_afTuple; +} +//---------------------------------------------------------------------------- +template +Real Vector::operator[](int i) const +{ + assert(0 <= i && i < N); + return Vector::m_afTuple[i]; +} +//---------------------------------------------------------------------------- +template +Real &Vector::operator[](int i) +{ + assert(0 <= i && i < N); + return Vector::m_afTuple[i]; +} +//---------------------------------------------------------------------------- +template +Vector &Vector::operator=(const Vector &rkV) +{ + memcpy(Vector::m_afTuple, rkV.Vector::m_afTuple, N * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +bool Vector::operator==(const Vector &rkV) const +{ + return memcmp(Vector::m_afTuple, rkV.Vector::m_afTuple, N * sizeof(Real)) == 0; +} +//---------------------------------------------------------------------------- +template +bool Vector::operator!=(const Vector &rkV) const +{ + return memcmp(Vector::m_afTuple, rkV.Vector::m_afTuple, N * sizeof(Real)) != 0; +} +//---------------------------------------------------------------------------- +template +int Vector::CompareArrays(const Vector &rkV) const +{ + return memcmp(Vector::m_afTuple, rkV.Vector::m_afTuple, N * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +bool Vector::operator<(const Vector &rkV) const +{ + return CompareArrays(rkV) < 0; +} +//---------------------------------------------------------------------------- +template +bool Vector::operator<=(const Vector &rkV) const +{ + return CompareArrays(rkV) <= 0; +} +//---------------------------------------------------------------------------- +template +bool Vector::operator>(const Vector &rkV) const +{ + return CompareArrays(rkV) > 0; +} +//---------------------------------------------------------------------------- +template +bool Vector::operator>=(const Vector &rkV) const +{ + return CompareArrays(rkV) >= 0; +} +//---------------------------------------------------------------------------- +template +Vector Vector::operator+(const Vector &rkV) const +{ + Vector kSum; + for (int i = 0; i < N; i++) + kSum.Vector::m_afTuple[i] = Vector::m_afTuple[i] + rkV.Vector::m_afTuple[i]; + return kSum; +} +//---------------------------------------------------------------------------- +template +Vector Vector::operator-(const Vector &rkV) const +{ + Vector kDiff; + for (int i = 0; i < N; i++) + kDiff.Vector::m_afTuple[i] = Vector::m_afTuple[i] - rkV.Vector::m_afTuple[i]; + return kDiff; +} +//---------------------------------------------------------------------------- +template +Vector Vector::operator*(Real fScalar) const +{ + Vector kProd; + for (int i = 0; i < N; i++) + kProd.Vector::m_afTuple[i] = fScalar * Vector::m_afTuple[i]; + return kProd; +} +//---------------------------------------------------------------------------- +template +Vector Vector::operator/(Real fScalar) const +{ + Vector kQuot; + int i; + + if (fScalar != (Real)0.0) + { + Real fInvScalar = ((Real)1.0) / fScalar; + for (i = 0; i < N; i++) + kQuot.Vector::m_afTuple[i] = fInvScalar * Vector::m_afTuple[i]; + } + else + { + for (i = 0; i < N; i++) + kQuot.Vector::m_afTuple[i] = Math::MAX_REAL; + } + + return kQuot; +} +//---------------------------------------------------------------------------- +template +Vector Vector::operator-() const +{ + Vector kNeg; + for (int i = 0; i < N; i++) + kNeg.Vector::m_afTuple[i] = -Vector::m_afTuple[i]; + return kNeg; +} +//---------------------------------------------------------------------------- +template +Vector operator*(Real fScalar, const Vector &rkV) +{ + Vector kProd; + for (int i = 0; i < N; i++) + kProd[i] = fScalar * rkV[i]; + return kProd; +} +//---------------------------------------------------------------------------- +template +Vector &Vector::operator+=(const Vector &rkV) +{ + for (int i = 0; i < N; i++) + Vector::m_afTuple[i] += rkV.Vector::m_afTuple[i]; + return *this; +} +//---------------------------------------------------------------------------- +template +Vector &Vector::operator-=(const Vector &rkV) +{ + for (int i = 0; i < N; i++) + Vector::m_afTuple[i] -= rkV.Vector::m_afTuple[i]; + return *this; +} +//---------------------------------------------------------------------------- +template +Vector &Vector::operator*=(Real fScalar) +{ + for (int i = 0; i < N; i++) + Vector::m_afTuple[i] *= fScalar; + return *this; +} +//---------------------------------------------------------------------------- +template +Vector &Vector::operator/=(Real fScalar) +{ + int i; + + if (fScalar != (Real)0.0) + { + Real fInvScalar = ((Real)1.0) / fScalar; + for (i = 0; i < N; i++) + Vector::m_afTuple[i] *= fInvScalar; + } + else + { + for (i = 0; i < N; i++) + Vector::m_afTuple[i] = Math::MAX_REAL; + } + + return *this; +} +//---------------------------------------------------------------------------- +template +Real Vector::Length() const +{ + Real fSqrLen = (Real)0.0; + for (int i = 0; i < N; i++) + fSqrLen += Vector::m_afTuple[i] * Vector::m_afTuple[i]; + return Math::Sqrt(fSqrLen); +} +//---------------------------------------------------------------------------- +template +Real Vector::SquaredLength() const +{ + Real fSqrLen = (Real)0.0; + for (int i = 0; i < N; i++) + fSqrLen += Vector::m_afTuple[i] * Vector::m_afTuple[i]; + return fSqrLen; +} +//---------------------------------------------------------------------------- +template +Real Vector::Dot(const Vector &rkV) const +{ + Real fDot = (Real)0.0; + for (int i = 0; i < N; i++) + fDot += Vector::m_afTuple[i] * rkV.Vector::m_afTuple[i]; + return fDot; +} +//---------------------------------------------------------------------------- +template +Real Vector::Normalize() +{ + Real fLength = Length(); + int i; + + if (fLength > Math::EPSILON) + { + Real fInvLength = ((Real)1.0) / fLength; + for (i = 0; i < N; i++) + Vector::m_afTuple[i] *= fInvLength; + } + else + { + fLength = (Real)0.0; + for (i = 0; i < N; i++) + Vector::m_afTuple[i] = (Real)0.0; + } + + return fLength; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlVector2.cpp b/src/editors/xrECore/WildMagic/WmlVector2.cpp new file mode 100644 index 00000000000..6b6beee31b8 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector2.cpp @@ -0,0 +1,26 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#include "WmlVector2.h" +using namespace Wml; + +template <> +const Vector2 Vector2::ZERO(0.0f, 0.0f); +template <> +const Vector2 Vector2::UNIT_X(1.0f, 0.0f); +template <> +const Vector2 Vector2::UNIT_Y(0.0f, 1.0f); + +template <> +const Vector2 Vector2::ZERO(0.0, 0.0); +template <> +const Vector2 Vector2::UNIT_X(1.0, 0.0); +template <> +const Vector2 Vector2::UNIT_Y(0.0, 1.0); diff --git a/src/editors/xrECore/WildMagic/WmlVector2.h b/src/editors/xrECore/WildMagic/WmlVector2.h new file mode 100644 index 00000000000..22c36c0b80e --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector2.h @@ -0,0 +1,78 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLVECTOR2_H +#define WMLVECTOR2_H + +#include "WmlVector.h" + +namespace Wml +{ + + template + class Vector2 : public Vector<2, Real> + { + public: + // construction + Vector2(); + Vector2(Real fX, Real fY); + Vector2(const Vector2 &rkV); + Vector2(const Vector<2, Real> &rkV); + + // member access + Real X() const; + Real &X(); + Real Y() const; + Real &Y(); + + // assignment + Vector2 &operator=(const Vector2 &rkV); + Vector2 &operator=(const Vector<2, Real> &rkV); + + // returns (y,-x) + Vector2 Perp() const; + + // returns (y,-x)/sqrt(x*x+y*y) + Vector2 UnitPerp() const; + + // returns Cross((x,y,0),(V.x,V.y,0)) = x*V.y - y*V.x + Real Kross(const Vector2 &rkV) const; + + // NOTE. These exist to support template code that takes vectors of + // dimensions 2 or 3. In 2D, the input vector is ignored, but allows + // the correct signature matching in the template code. + Vector2 Cross(const Vector2 &rkV) const; + Vector2 UnitCross(const Vector2 &rkV) const; + + // Gram-Schmidt orthonormalization. Take linearly independent vectors U + // and V and compute an orthonormal set (unit length, mutually + // perpendicular). + static void Orthonormalize(Vector2 &rkU, Vector2 &rkV); + + // Input V must be initialized to a nonzero vector, output is {U,V}, an + // orthonormal basis. A hint is provided about whether or not V is + // already unit length. + static void GenerateOrthonormalBasis(Vector2 &rkU, Vector2 &rkV, + bool bUnitLengthV); + + // special vectors + WML_ITEM static const Vector2 ZERO; + WML_ITEM static const Vector2 UNIT_X; + WML_ITEM static const Vector2 UNIT_Y; + }; + +#include "WmlVector2.inl" + + typedef Vector2 Vector2f; + typedef Vector2 Vector2d; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlVector2.inl b/src/editors/xrECore/WildMagic/WmlVector2.inl new file mode 100644 index 00000000000..7465798c0c4 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector2.inl @@ -0,0 +1,139 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +Vector2::Vector2() +{ + // the vector is uninitialized +} +//---------------------------------------------------------------------------- +template +Vector2::Vector2(Real fX, Real fY) +{ + Vector2::m_afTuple[0] = fX; + Vector2::m_afTuple[1] = fY; +} +//---------------------------------------------------------------------------- +template +Vector2::Vector2(const Vector2 &rkV) +{ + memcpy(Vector2::m_afTuple, rkV.Vector2::m_afTuple, 2 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Vector2::Vector2(const Vector<2, Real> &rkV) +{ + memcpy(Vector2::m_afTuple, (const Real *)rkV, 2 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Vector2 &Vector2::operator=(const Vector2 &rkV) +{ + memcpy(Vector2::m_afTuple, rkV.Vector2::m_afTuple, 2 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Vector2 &Vector2::operator=(const Vector<2, Real> &rkV) +{ + memcpy(Vector2::m_afTuple, (const Real *)rkV, 2 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Real Vector2::X() const +{ + return Vector2::m_afTuple[0]; +} +//---------------------------------------------------------------------------- +template +Real &Vector2::X() +{ + return Vector2::m_afTuple[0]; +} +//---------------------------------------------------------------------------- +template +Real Vector2::Y() const +{ + return Vector2::m_afTuple[1]; +} +//---------------------------------------------------------------------------- +template +Real &Vector2::Y() +{ + return Vector2::m_afTuple[1]; +} +//---------------------------------------------------------------------------- +template +Vector2 Vector2::Perp() const +{ + return Vector2(Vector2::m_afTuple[1], -Vector2::m_afTuple[0]); +} +//---------------------------------------------------------------------------- +template +Vector2 Vector2::UnitPerp() const +{ + Vector2 kPerp(Vector2::m_afTuple[1], -Vector2::m_afTuple[0]); + kPerp.Normalize(); + return kPerp; +} +//---------------------------------------------------------------------------- +template +Real Vector2::Kross(const Vector2 &rkV) const +{ + return Vector2::m_afTuple[0] * rkV.Vector2::m_afTuple[1] - Vector2::m_afTuple[1] * rkV.Vector2::m_afTuple[0]; +} +//---------------------------------------------------------------------------- +template +Vector2 Vector2::Cross(const Vector2 &) const +{ + return Vector2(Vector2::m_afTuple[1], -Vector2::m_afTuple[0]); +} +//---------------------------------------------------------------------------- +template +Vector2 Vector2::UnitCross(const Vector2 &) const +{ + Vector2 kPerp(Vector2::m_afTuple[1], -Vector2::m_afTuple[0]); + kPerp.Normalize(); + return kPerp; +} +//---------------------------------------------------------------------------- +template +void Vector2::Orthonormalize(Vector2 &rkU, Vector2 &rkV) +{ + // If the input vectors are v0 and v1, then the Gram-Schmidt + // orthonormalization produces vectors u0 and u1 as follows, + // + // u0 = v0/|v0| + // u1 = (v1-(u0*v1)u0)/|v1-(u0*v1)u0| + // + // where |A| indicates length of vector A and A*B indicates dot + // product of vectors A and B. + + // compute u0 + rkU.Normalize(); + + // compute u1 + Real fDot0 = rkU.Dot(rkV); + rkV -= fDot0 * rkU; + rkV.Normalize(); +} +//---------------------------------------------------------------------------- +template +void Vector2::GenerateOrthonormalBasis(Vector2 &rkU, Vector2 &rkV, + bool bUnitLengthV) +{ + if (!bUnitLengthV) + rkV.Normalize(); + + rkU = rkV.Perp(); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlVector3.cpp b/src/editors/xrECore/WildMagic/WmlVector3.cpp new file mode 100644 index 00000000000..5a86d72952c --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector3.cpp @@ -0,0 +1,32 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlVector3.h" +using namespace Wml; + +template <> +const Vector3 Vector3::ZERO(0.0f, 0.0f, 0.0f); +template <> +const Vector3 Vector3::UNIT_X(1.0f, 0.0f, 0.0f); +template <> +const Vector3 Vector3::UNIT_Y(0.0f, 1.0f, 0.0f); +template <> +const Vector3 Vector3::UNIT_Z(0.0f, 0.0f, 1.0f); + +template <> +const Vector3 Vector3::ZERO(0.0, 0.0, 0.0); +template <> +const Vector3 Vector3::UNIT_X(1.0, 0.0, 0.0); +template <> +const Vector3 Vector3::UNIT_Y(0.0, 1.0, 0.0); +template <> +const Vector3 Vector3::UNIT_Z(0.0, 0.0, 1.0); diff --git a/src/editors/xrECore/WildMagic/WmlVector3.h b/src/editors/xrECore/WildMagic/WmlVector3.h new file mode 100644 index 00000000000..54ff86d8940 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector3.h @@ -0,0 +1,75 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLVECTOR3H +#define WMLVECTOR3H + +#include "WmlVector.h" + +namespace Wml +{ + + template + class Vector3 : public Vector<3, Real> + { + public: + // construction + Vector3(); + Vector3(Real fX, Real fY, Real fZ); + Vector3(const Vector3 &rkV); + Vector3(const Vector<3, Real> &rkV); + + // member access + Real X() const; + Real &X(); + Real Y() const; + Real &Y(); + Real Z() const; + Real &Z(); + + // assignment + Vector3 &operator=(const Vector3 &rkV); + Vector3 &operator=(const Vector<3, Real> &rkV); + + // The cross products are computed using the right-handed rule. Be aware + // that some graphics APIs use a left-handed rule. If you have to compute + // a cross product with these functions and send the result to the API + // that expects left-handed, you will need to change sign on the vector + // (replace each component value c by -c). + Vector3 Cross(const Vector3 &rkV) const; + Vector3 UnitCross(const Vector3 &rkV) const; + + // Gram-Schmidt orthonormalization. Take linearly independent vectors + // U, V, and W and compute an orthonormal set (unit length, mutually + // perpendicular). + static void Orthonormalize(Vector3 &rkU, Vector3 &rkV, Vector3 &rkW); + static void Orthonormalize(Vector3 akV[/*3*/]); + + // Input W must be initialized to a nonzero vector, output is {U,V,W}, + // an orthonormal basis. A hint is provided about whether or not W + // is already unit length. + static void GenerateOrthonormalBasis(Vector3 &rkU, Vector3 &rkV, + Vector3 &rkW, bool bUnitLengthW); + + // special vectors + WML_ITEM static const Vector3 ZERO; + WML_ITEM static const Vector3 UNIT_X; + WML_ITEM static const Vector3 UNIT_Y; + WML_ITEM static const Vector3 UNIT_Z; + }; + +#include "WmlVector3.inl" + + typedef Vector3 Vector3f; + typedef Vector3 Vector3d; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlVector3.inl b/src/editors/xrECore/WildMagic/WmlVector3.inl new file mode 100644 index 00000000000..75be337dc44 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector3.inl @@ -0,0 +1,173 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +Vector3::Vector3() +{ + // the vector is uninitialized +} +//---------------------------------------------------------------------------- +template +Vector3::Vector3(Real fX, Real fY, Real fZ) +{ + Vector3::m_afTuple[0] = fX; + Vector3::m_afTuple[1] = fY; + Vector3::m_afTuple[2] = fZ; +} +//---------------------------------------------------------------------------- +template +Vector3::Vector3(const Vector3 &rkV) +{ + memcpy(Vector3::m_afTuple, rkV.Vector3::m_afTuple, 3 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Vector3::Vector3(const Vector<3, Real> &rkV) +{ + memcpy(Vector3::m_afTuple, (const Real *)rkV, 3 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Vector3 &Vector3::operator=(const Vector3 &rkV) +{ + memcpy(Vector3::m_afTuple, rkV.Vector3::m_afTuple, 3 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Vector3 &Vector3::operator=(const Vector<3, Real> &rkV) +{ + memcpy(Vector3::m_afTuple, (const Real *)rkV, 3 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Real Vector3::X() const +{ + return Vector3::m_afTuple[0]; +} +//---------------------------------------------------------------------------- +template +Real &Vector3::X() +{ + return Vector3::m_afTuple[0]; +} +//---------------------------------------------------------------------------- +template +Real Vector3::Y() const +{ + return Vector3::m_afTuple[1]; +} +//---------------------------------------------------------------------------- +template +Real &Vector3::Y() +{ + return Vector3::m_afTuple[1]; +} +//---------------------------------------------------------------------------- +template +Real Vector3::Z() const +{ + return Vector3::m_afTuple[2]; +} +//---------------------------------------------------------------------------- +template +Real &Vector3::Z() +{ + return Vector3::m_afTuple[2]; +} +//---------------------------------------------------------------------------- +template +Vector3 Vector3::Cross(const Vector3 &rkV) const +{ + return Vector3( + Vector3::m_afTuple[1] * rkV.Vector3::m_afTuple[2] - Vector3::m_afTuple[2] * rkV.Vector3::m_afTuple[1], + Vector3::m_afTuple[2] * rkV.Vector3::m_afTuple[0] - Vector3::m_afTuple[0] * rkV.Vector3::m_afTuple[2], + Vector3::m_afTuple[0] * rkV.Vector3::m_afTuple[1] - Vector3::m_afTuple[1] * rkV.Vector3::m_afTuple[0]); +} +//---------------------------------------------------------------------------- +template +Vector3 Vector3::UnitCross(const Vector3 &rkV) const +{ + Vector3 kCross( + Vector3::m_afTuple[1] * rkV.Vector3::m_afTuple[2] - Vector3::m_afTuple[2] * rkV.Vector3::m_afTuple[1], + Vector3::m_afTuple[2] * rkV.Vector3::m_afTuple[0] - Vector3::m_afTuple[0] * rkV.Vector3::m_afTuple[2], + Vector3::m_afTuple[0] * rkV.Vector3::m_afTuple[1] - Vector3::m_afTuple[1] * rkV.Vector3::m_afTuple[0]); + kCross.Normalize(); + return kCross; +} +//---------------------------------------------------------------------------- +template +void Vector3::Orthonormalize(Vector3 &rkU, Vector3 &rkV, Vector3 &rkW) +{ + // If the input vectors are v0, v1, and v2, then the Gram-Schmidt + // orthonormalization produces vectors u0, u1, and u2 as follows, + // + // u0 = v0/|v0| + // u1 = (v1-(u0*v1)u0)/|v1-(u0*v1)u0| + // u2 = (v2-(u0*v2)u0-(u1*v2)u1)/|v2-(u0*v2)u0-(u1*v2)u1| + // + // where |A| indicates length of vector A and A*B indicates dot + // product of vectors A and B. + + // compute u0 + rkU.Normalize(); + + // compute u1 + Real fDot0 = rkU.Dot(rkV); + rkV -= fDot0 * rkU; + rkV.Normalize(); + + // compute u2 + Real fDot1 = rkV.Dot(rkW); + fDot0 = rkU.Dot(rkW); + rkW -= fDot0 * rkU + fDot1 * rkV; + rkW.Normalize(); +} +//---------------------------------------------------------------------------- +template +void Vector3::Orthonormalize(Vector3 akV[/*3*/]) +{ + Orthonormalize(akV[0], akV[1], akV[2]); +} +//---------------------------------------------------------------------------- +template +void Vector3::GenerateOrthonormalBasis(Vector3 &rkU, Vector3 &rkV, + Vector3 &rkW, bool bUnitLengthW) +{ + if (!bUnitLengthW) + rkW.Normalize(); + + Real fInvLength; + + if (Math::FAbs(rkW.Vector3::m_afTuple[0]) >= + Math::FAbs(rkW.Vector3::m_afTuple[1])) + { + // W.x or W.z is the largest magnitude component, swap them + fInvLength = Math::InvSqrt(rkW.Vector3::m_afTuple[0] * rkW.Vector3::m_afTuple[0] + + rkW.Vector3::m_afTuple[2] * rkW.Vector3::m_afTuple[2]); + rkU.Vector3::m_afTuple[0] = -rkW.Vector3::m_afTuple[2] * fInvLength; + rkU.Vector3::m_afTuple[1] = (Real)0.0; + rkU.Vector3::m_afTuple[2] = +rkW.Vector3::m_afTuple[0] * fInvLength; + } + else + { + // W.y or W.z is the largest magnitude component, swap them + fInvLength = Math::InvSqrt(rkW.Vector3::m_afTuple[1] * rkW.Vector3::m_afTuple[1] + + rkW.Vector3::m_afTuple[2] * rkW.Vector3::m_afTuple[2]); + rkU.Vector3::m_afTuple[0] = (Real)0.0; + rkU.Vector3::m_afTuple[1] = +rkW.Vector3::m_afTuple[2] * fInvLength; + rkU.Vector3::m_afTuple[2] = -rkW.Vector3::m_afTuple[1] * fInvLength; + } + + rkV = rkW.Cross(rkU); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlVector4.cpp b/src/editors/xrECore/WildMagic/WmlVector4.cpp new file mode 100644 index 00000000000..3650c29075b --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector4.cpp @@ -0,0 +1,34 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#include "WmlVector4.h" +using namespace Wml; + +template <> +const Vector4 Vector4::ZERO(0.0f, 0.0f, 0.0f, 0.0f); +template <> +const Vector4 Vector4::UNIT_X(1.0f, 0.0f, 0.0f, 0.0f); +template <> +const Vector4 Vector4::UNIT_Y(0.0f, 1.0f, 0.0f, 0.0f); +template <> +const Vector4 Vector4::UNIT_Z(0.0f, 0.0f, 1.0f, 0.0f); +template <> +const Vector4 Vector4::UNIT_W(0.0f, 0.0f, 0.0f, 1.0f); + +template <> +const Vector4 Vector4::ZERO(0.0, 0.0, 0.0, 0.0); +template <> +const Vector4 Vector4::UNIT_X(1.0, 0.0, 0.0, 0.0); +template <> +const Vector4 Vector4::UNIT_Y(0.0, 1.0, 0.0, 0.0); +template <> +const Vector4 Vector4::UNIT_Z(0.0, 0.0, 1.0, 0.0); +template <> +const Vector4 Vector4::UNIT_W(0.0, 0.0, 0.0, 1.0); diff --git a/src/editors/xrECore/WildMagic/WmlVector4.h b/src/editors/xrECore/WildMagic/WmlVector4.h new file mode 100644 index 00000000000..743d7833ea7 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector4.h @@ -0,0 +1,58 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLVECTOR4_H +#define WMLVECTOR4_H + +#include "WmlVector.h" + +namespace Wml +{ + + template + class Vector4 : public Vector<4, Real> + { + public: + // construction + Vector4(); + Vector4(Real fX, Real fY, Real fZ, Real fW); + Vector4(const Vector4 &rkV); + Vector4(const Vector<4, Real> &rkV); + + // member access + Real X() const; + Real &X(); + Real Y() const; + Real &Y(); + Real Z() const; + Real &Z(); + Real W() const; + Real &W(); + + // assignment + Vector4 &operator=(const Vector4 &rkV); + Vector4 &operator=(const Vector<4, Real> &rkV); + + // special vectors + WML_ITEM static const Vector4 ZERO; + WML_ITEM static const Vector4 UNIT_X; + WML_ITEM static const Vector4 UNIT_Y; + WML_ITEM static const Vector4 UNIT_Z; + WML_ITEM static const Vector4 UNIT_W; + }; + +#include "WmlVector4.inl" + + typedef Vector4 Vector4f; + typedef Vector4 Vector4d; + +} + +#endif diff --git a/src/editors/xrECore/WildMagic/WmlVector4.inl b/src/editors/xrECore/WildMagic/WmlVector4.inl new file mode 100644 index 00000000000..1d5dbb0e9fb --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlVector4.inl @@ -0,0 +1,100 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +//---------------------------------------------------------------------------- +template +Vector4::Vector4() +{ + // the vector is uninitialized +} +//---------------------------------------------------------------------------- +template +Vector4::Vector4(Real fX, Real fY, Real fZ, Real fW) +{ + Vector4::m_afTuple[0] = fX; + Vector4::m_afTuple[1] = fY; + Vector4::m_afTuple[2] = fZ; + Vector4::m_afTuple[3] = fW; +} +//---------------------------------------------------------------------------- +template +Vector4::Vector4(const Vector4 &rkV) +{ + memcpy(Vector4::m_afTuple, rkV.Vector4::m_afTuple, 4 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Vector4::Vector4(const Vector<4, Real> &rkV) +{ + memcpy(Vector4::m_afTuple, (const Real *)rkV, 4 * sizeof(Real)); +} +//---------------------------------------------------------------------------- +template +Vector4 &Vector4::operator=(const Vector4 &rkV) +{ + memcpy(Vector4::m_afTuple, rkV.Vector4::m_afTuple, 4 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Vector4 &Vector4::operator=(const Vector<4, Real> &rkV) +{ + memcpy(Vector4::m_afTuple, (const Real *)rkV, 4 * sizeof(Real)); + return *this; +} +//---------------------------------------------------------------------------- +template +Real Vector4::X() const +{ + return Vector4::m_afTuple[0]; +} +//---------------------------------------------------------------------------- +template +Real &Vector4::X() +{ + return Vector4::m_afTuple[0]; +} +//---------------------------------------------------------------------------- +template +Real Vector4::Y() const +{ + return Vector4::m_afTuple[1]; +} +//---------------------------------------------------------------------------- +template +Real &Vector4::Y() +{ + return Vector4::m_afTuple[1]; +} +//---------------------------------------------------------------------------- +template +Real Vector4::Z() const +{ + return Vector4::m_afTuple[2]; +} +//---------------------------------------------------------------------------- +template +Real &Vector4::Z() +{ + return Vector4::m_afTuple[2]; +} +//---------------------------------------------------------------------------- +template +Real Vector4::W() const +{ + return Vector4::m_afTuple[3]; +} +//---------------------------------------------------------------------------- +template +Real &Vector4::W() +{ + return Vector4::m_afTuple[3]; +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlWinSystem.cpp b/src/editors/xrECore/WildMagic/WmlWinSystem.cpp new file mode 100644 index 00000000000..2e2877b233a --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlWinSystem.cpp @@ -0,0 +1,49 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. +#include "stdafx.h" +#pragma hdrstop + +#include "WmlSystem.h" +using namespace Wml; + +//---------------------------------------------------------------------------- +void Wml::System::EndianCopy(int iSize, const void *pvSrc, void *pvDst) +{ + memcpy(pvDst, pvSrc, iSize); +} +//---------------------------------------------------------------------------- +void Wml::System::EndianCopy(int iSize, int iQuantity, const void *pvSrc, + void *pvDst) +{ + memcpy(pvDst, pvSrc, iSize * iQuantity); +} +//---------------------------------------------------------------------------- +unsigned int Wml::System::MakeRGB(unsigned char ucR, unsigned char ucG, + unsigned char ucB) +{ + return (ucR | (ucG << 8) | (ucB << 16) | (0xFF << 24)); +} +//---------------------------------------------------------------------------- +unsigned int Wml::System::MakeRGBA(unsigned char ucR, unsigned char ucG, + unsigned char ucB, unsigned char ucA) +{ + return (ucR | (ucG << 8) | (ucB << 16) | (ucA << 24)); +} +//---------------------------------------------------------------------------- +double Wml::System::GetTime() +{ + // 64-bit quantities + LARGE_INTEGER iFrequency, iCounter; + + QueryPerformanceFrequency(&iFrequency); + QueryPerformanceCounter(&iCounter); + return ((double)iCounter.QuadPart) / ((double)iFrequency.QuadPart); +} +//---------------------------------------------------------------------------- diff --git a/src/editors/xrECore/WildMagic/WmlWinSystem.h b/src/editors/xrECore/WildMagic/WmlWinSystem.h new file mode 100644 index 00000000000..a66c8fc7379 --- /dev/null +++ b/src/editors/xrECore/WildMagic/WmlWinSystem.h @@ -0,0 +1,79 @@ +// Magic Software, Inc. +// http://www.magic-software.com +// http://www.wild-magic.com +// Copyright (c) 2004. All Rights Reserved +// +// The Wild Magic Library (WML) source code is supplied under the terms of +// the license agreement http://www.magic-software.com/License/WildMagic.pdf +// and may not be copied or disclosed except in accordance with the terms of +// that agreement. + +#ifndef WMLWINSYSTEMH +#define WMLWINSYSTEMH + +// for a DLL library +#if defined(WML_DLL_EXPORT) +#define WML_ITEM __declspec(dllexport) + +// for a client of the DLL library +#elif defined(WML_DLL_IMPORT) +#define WML_ITEM __declspec(dllimport) + +// for a static library +#else +#define WML_ITEM + +#endif + +#if defined(_MSC_VER) + +// Microsoft Visual C++ specific pragmas. MSVC6 appears to be version 1200 +// and MSVC7 appears to be version 1300. +#if _MSC_VER < 1300 +#define WML_USING_VC6 +#else +#define WML_USING_VC7 +#endif + +#if defined(WML_USING_VC6) + +// Disable the warning about truncating the debug names to 255 characters. +// This warning shows up often with STL code in MSVC6, but not MSVC7. +#pragma warning(disable : 4786) + +// This warning is disabled because MSVC6 warns about not finding +// implementations for the pure virtual functions that occur in the template +// classes 'template ' when explicity instantiating the classe. +// NOTE: If you create your own template classes that will be explicitly +// instantiated, you should re-enable the warning to make sure that in fact +// all your member data and functions have been defined and implemented. +#pragma warning(disable : 4661) + +#endif + +// TO DO. What does this warning mean? +// warning C4251: class 'std::vector<_Ty,_Ax>' needs to have dll-interface +// to be used by clients of class 'foobar' +#pragma warning(disable : 4251) + +#endif + +// Specialized instantiation of static members in template classes before or +// after the class itself is instantiated is not a problem with Visual Studio +// .NET 2003 (VC 7.1), but VC 6 likes the specialized instantiation to occur +// after the class instantiation. +// #define WML_INSTANTIATE_BEFORE + +// common standard library headers +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif diff --git a/src/editors/xrECore/guid.cpp b/src/editors/xrECore/guid.cpp new file mode 100644 index 00000000000..ee536ced0f2 --- /dev/null +++ b/src/editors/xrECore/guid.cpp @@ -0,0 +1,3 @@ +#pragma hdrstop + +#define INITGUID \ No newline at end of file diff --git a/src/editors/xrECore/lwchunks.h b/src/editors/xrECore/lwchunks.h new file mode 100644 index 00000000000..98aae9da7b8 --- /dev/null +++ b/src/editors/xrECore/lwchunks.h @@ -0,0 +1,162 @@ +#ifndef LWCHUNKS_H +#define LWCHUNKS_H + +#ifndef LWID_ +#define LWID_(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d)) +#endif +/* chunk and subchunk IDs */ + +#define ID_FORM LWID_('F', 'O', 'R', 'M') +#define ID_LWO2 LWID_('L', 'W', 'O', '2') +#define ID_LWOB LWID_('L', 'W', 'O', 'B') + +/* top-level chunks */ +#define ID_LAYR LWID_('L', 'A', 'Y', 'R') +#define ID_TAGS LWID_('T', 'A', 'G', 'S') +#define ID_PNTS LWID_('P', 'N', 'T', 'S') +#define ID_BBOX LWID_('B', 'B', 'O', 'X') +#define ID_VMAP LWID_('V', 'M', 'A', 'P') +#define ID_VMAD LWID_('V', 'M', 'A', 'D') +#define ID_POLS LWID_('P', 'O', 'L', 'S') +#define ID_PTAG LWID_('P', 'T', 'A', 'G') +#define ID_ENVL LWID_('E', 'N', 'V', 'L') +#define ID_CLIP LWID_('C', 'L', 'I', 'P') +#define ID_SURF LWID_('S', 'U', 'R', 'F') +#define ID_DESC LWID_('D', 'E', 'S', 'C') +#define ID_TEXT LWID_('T', 'E', 'X', 'T') +#define ID_ICON LWID_('I', 'C', 'O', 'N') + +/* polygon types */ +#define ID_FACE LWID_('F', 'A', 'C', 'E') +#define ID_CURV LWID_('C', 'U', 'R', 'V') +#define ID_PTCH LWID_('P', 'T', 'C', 'H') +#define ID_MBAL LWID_('M', 'B', 'A', 'L') +#define ID_BONE LWID_('B', 'O', 'N', 'E') + +/* polygon tags */ +#define ID_SURF LWID_('S', 'U', 'R', 'F') +#define ID_PART LWID_('P', 'A', 'R', 'T') +#define ID_SMGP LWID_('S', 'M', 'G', 'P') + +/* envelopes */ +#define ID_PRE LWID_('P', 'R', 'E', ' ') +#define ID_POST LWID_('P', 'O', 'S', 'T') +#define ID_KEY LWID_('K', 'E', 'Y', ' ') +#define ID_SPAN LWID_('S', 'P', 'A', 'N') +#define ID_TCB LWID_('T', 'C', 'B', ' ') +#define ID_HERM LWID_('H', 'E', 'R', 'M') +#define ID_BEZI LWID_('B', 'E', 'Z', 'I') +#define ID_BEZ2 LWID_('B', 'E', 'Z', '2') +#define ID_LINE LWID_('L', 'I', 'N', 'E') +#define ID_STEP LWID_('S', 'T', 'E', 'P') + +/* clips */ +#define ID_STIL LWID_('S', 'T', 'I', 'L') +#define ID_ISEQ LWID_('I', 'S', 'E', 'Q') +#define ID_ANIM LWID_('A', 'N', 'I', 'M') +#define ID_XREF LWID_('X', 'R', 'E', 'F') +#define ID_STCC LWID_('S', 'T', 'C', 'C') +#define ID_TIME LWID_('T', 'I', 'M', 'E') +#define ID_CONT LWID_('C', 'O', 'N', 'T') +#define ID_BRIT LWID_('B', 'R', 'I', 'T') +#define ID_SATR LWID_('S', 'A', 'T', 'R') +#define ID_HUE LWID_('H', 'U', 'E', ' ') +#define ID_GAMM LWID_('G', 'A', 'M', 'M') +#define ID_NEGA LWID_('N', 'E', 'G', 'A') +#define ID_IFLT LWID_('I', 'F', 'L', 'T') +#define ID_PFLT LWID_('P', 'F', 'L', 'T') + +/* surfaces */ +#define ID_COLR LWID_('C', 'O', 'L', 'R') +#define ID_LUMI LWID_('L', 'U', 'M', 'I') +#define ID_DIFF LWID_('D', 'I', 'F', 'F') +#define ID_SPEC LWID_('S', 'P', 'E', 'C') +#define ID_GLOS LWID_('G', 'L', 'O', 'S') +#define ID_REFL LWID_('R', 'E', 'F', 'L') +#define ID_RFOP LWID_('R', 'F', 'O', 'P') +#define ID_RIMG LWID_('R', 'I', 'M', 'G') +#define ID_RSAN LWID_('R', 'S', 'A', 'N') +#define ID_TRAN LWID_('T', 'R', 'A', 'N') +#define ID_TROP LWID_('T', 'R', 'O', 'P') +#define ID_TIMG LWID_('T', 'I', 'M', 'G') +#define ID_RIND LWID_('R', 'I', 'N', 'D') +#define ID_TRNL LWID_('T', 'R', 'N', 'L') +#define ID_BUMP LWID_('B', 'U', 'M', 'P') +#define ID_SMAN LWID_('S', 'M', 'A', 'N') +#define ID_SIDE LWID_('S', 'I', 'D', 'E') +#define ID_CLRH LWID_('C', 'L', 'R', 'H') +#define ID_CLRF LWID_('C', 'L', 'R', 'F') +#define ID_ADTR LWID_('A', 'D', 'T', 'R') +#define ID_SHRP LWID_('S', 'H', 'R', 'P') +#define ID_LINE LWID_('L', 'I', 'N', 'E') +#define ID_LSIZ LWID_('L', 'S', 'I', 'Z') +#define ID_ALPH LWID_('A', 'L', 'P', 'H') +#define ID_AVAL LWID_('A', 'V', 'A', 'L') +#define ID_GVAL LWID_('G', 'V', 'A', 'L') +#define ID_BLOK LWID_('B', 'L', 'O', 'K') + +/* texture layer */ +#define ID_TYPE LWID_('T', 'Y', 'P', 'E') +#define ID_CHAN LWID_('C', 'H', 'A', 'N') +#define ID_NAME LWID_('N', 'A', 'M', 'E') +#define ID_ENAB LWID_('E', 'N', 'A', 'B') +#define ID_OPAC LWID_('O', 'P', 'A', 'C') +#define ID_FLAG LWID_('F', 'L', 'A', 'G') +#define ID_PROJ LWID_('P', 'R', 'O', 'J') +#define ID_STCK LWID_('S', 'T', 'C', 'K') +#define ID_TAMP LWID_('T', 'A', 'M', 'P') + +/* texture coordinates */ +#define ID_TMAP LWID_('T', 'M', 'A', 'P') +#define ID_AXIS LWID_('A', 'X', 'I', 'S') +#define ID_CNTR LWID_('C', 'N', 'T', 'R') +#define ID_SIZE LWID_('S', 'I', 'Z', 'E') +#define ID_ROTA LWID_('R', 'O', 'T', 'A') +#define ID_OREF LWID_('O', 'R', 'E', 'F') +#define ID_FALL LWID_('F', 'A', 'L', 'L') +#define ID_CSYS LWID_('C', 'S', 'Y', 'S') + +/* image map */ +#define ID_IMAP LWID_('I', 'M', 'A', 'P') +#define ID_IMAG LWID_('I', 'M', 'A', 'G') +#define ID_WRAP LWID_('W', 'R', 'A', 'P') +#define ID_WRPW LWID_('W', 'R', 'P', 'W') +#define ID_WRPH LWID_('W', 'R', 'P', 'H') +#define ID_VMAP LWID_('V', 'M', 'A', 'P') +#define ID_AAST LWID_('A', 'A', 'S', 'T') +#define ID_PIXB LWID_('P', 'I', 'X', 'B') + +/* procedural */ +#define ID_PROC LWID_('P', 'R', 'O', 'C') +#define ID_COLR LWID_('C', 'O', 'L', 'R') +#define ID_VALU LWID_('V', 'A', 'L', 'U') +#define ID_FUNC LWID_('F', 'U', 'N', 'C') +#define ID_FTPS LWID_('F', 'T', 'P', 'S') +#define ID_ITPS LWID_('I', 'T', 'P', 'S') +#define ID_ETPS LWID_('E', 'T', 'P', 'S') + +/* gradient */ +#define ID_GRAD LWID_('G', 'R', 'A', 'D') +#define ID_GRST LWID_('G', 'R', 'S', 'T') +#define ID_GREN LWID_('G', 'R', 'E', 'N') +#define ID_PNAM LWID_('P', 'N', 'A', 'M') +#define ID_INAM LWID_('I', 'N', 'A', 'M') +#define ID_GRPT LWID_('G', 'R', 'P', 'T') +#define ID_FKEY LWID_('F', 'K', 'E', 'Y') +#define ID_IKEY LWID_('I', 'K', 'E', 'Y') + +/* shader */ +#define ID_SHDR LWID_('S', 'H', 'D', 'R') +#define ID_DATA LWID_('D', 'A', 'T', 'A') + +/* vmap type */ +#define ID_PICK LWID_('P', 'I', 'C', 'K') +#define ID_WGHT LWID_('W', 'G', 'H', 'T') +#define ID_MNVW LWID_('M', 'N', 'V', 'W') +#define ID_TXUV LWID_('T', 'X', 'U', 'V') +#define ID_RGB LWID_('R', 'G', 'B', ' ') +#define ID_RGBA LWID_('R', 'G', 'B', 'A') +#define ID_MORF LWID_('M', 'O', 'R', 'F') +#define ID_SPOT LWID_('S', 'P', 'O', 'T') + +#endif diff --git a/src/editors/xrECore/stdafx.cpp b/src/editors/xrECore/stdafx.cpp new file mode 100644 index 00000000000..873c6e918e3 --- /dev/null +++ b/src/editors/xrECore/stdafx.cpp @@ -0,0 +1,5 @@ +#include "stdafx.h" + +// hack +IRender_Light::~IRender_Light() {} +IRender_Glow::~IRender_Glow() {} diff --git a/src/editors/xrECore/stdafx.h b/src/editors/xrECore/stdafx.h new file mode 100644 index 00000000000..8ca76e5158b --- /dev/null +++ b/src/editors/xrECore/stdafx.h @@ -0,0 +1,229 @@ +//---------------------------------------------------- +// file: stdafx.h +//---------------------------------------------------- +#pragma once + +#define smart_cast dynamic_cast +#define DIRECTINPUT_VERSION 0x0800 + +#define R_R1 1 +#define R_R2 2 +#define RENDER R_R1 + +// Std C++ headers + + + +// iseful macros +// MSC names for functions +#ifdef XRECORE_EXPORTS +#define ECORE_API __declspec(dllexport) +#define ENGINE_API __declspec(dllexport) +#else +#define ECORE_API __declspec(dllimport) +#define ENGINE_API __declspec(dllimport) +#endif + +#define DLL_API __declspec(dllimport) +#define PropertyGP(a, b) __declspec(property(get = a, put = b)) +#define THROW FATAL("THROW"); +#define THROW2(a) FATAL(a); +#define NO_XRC_STATS + +#define clMsg Msg + +// core + +#include "Common/Platform.hpp" +#include "..\..\xrCore\xrCore.h" + +#define time_t __time32_t +#include "..\xrEProps\stdafx.h" +#include "OgfDesc.h" + +#ifdef _EDITOR +class PropValue; +class PropItem; +DEFINE_VECTOR(PropItem *, PropItemVec, PropItemIt); + +class ListItem; +DEFINE_VECTOR(ListItem *, ListItemsVec, ListItemsIt); +#endif + +#define USE_DX9 1 + +#include "..\..\xrCDB\xrCDB.h" +#include "Include\xrApi\xrApi.h" +#include "..\..\xrSound\Sound.h" +#include "..\..\xrParticles\psystem.h" + +// DirectX headers +#include +#include "d3dx9.h" +#include "..\..\Layers\xrRenderDX9\CommonTypes.h" + +#include + +// some user components +#include "xrCore\Fmesh.hpp" +#include "Common\_d3d_extensions.h" + +DEFINE_VECTOR(xr_string, AStringVec, AStringIt); +DEFINE_VECTOR(xr_string *, LPAStringVec, LPAStringIt); + +#include "..\..\xrServerEntities\xrEProps.h" +#include "..\..\xrCore\Log.h" +#include "editor\engine.h" +#include "..\..\xrEngine\defines.h" + +#include "../../xrphysics/xrphysics.h" +#include "Layers/xrRender/FVF.h" + +struct str_pred +{ + IC bool operator()(LPCSTR x, LPCSTR y) const + { + return strcmp(x, y) < 0; + } +}; +struct astr_pred +{ + IC bool operator()(const xr_string &x, const xr_string &y) const + { + return x < y; + } +}; + +#ifdef _EDITOR + +DEFINE_VECTOR(u32, U32Vec, U32It); + +#include "editor\device.h" +#include "..\..\xrEngine\properties.h" +#include "editor\render.h" +DEFINE_VECTOR(FVF::L, FLvertexVec, FLvertexIt); +DEFINE_VECTOR(FVF::TL, FTLvertexVec, FTLvertexIt); +DEFINE_VECTOR(FVF::LIT, FLITvertexVec, FLITvertexIt); +DEFINE_VECTOR(shared_str, RStrVec, RStrVecIt); + +// TODO: remove me +DEFINE_VECTOR(bool, boolVec, boolIt); +DEFINE_VECTOR(BOOL, BOOLVec, BOOLIt); +DEFINE_VECTOR(BOOL*, LPBOOLVec, LPBOOLIt); +DEFINE_VECTOR(Frect, FrectVec, FrectIt); +DEFINE_VECTOR(Irect, IrectVec, IrectIt); +DEFINE_VECTOR(Fplane, PlaneVec, PlaneIt); +DEFINE_VECTOR(Fvector2, Fvector2Vec, Fvector2It); +DEFINE_VECTOR(Fvector, FvectorVec, FvectorIt); +DEFINE_VECTOR(Fvector*, LPFvectorVec, LPFvectorIt); +DEFINE_VECTOR(Fcolor, FcolorVec, FcolorIt); +DEFINE_VECTOR(Fcolor*, LPFcolorVec, LPFcolorIt); +DEFINE_VECTOR(LPSTR, LPSTRVec, LPSTRIt); +DEFINE_VECTOR(LPCSTR, LPCSTRVec, LPCSTRIt); +DEFINE_VECTOR(string64, string64Vec, string64It); +DEFINE_VECTOR(xr_string, SStringVec, SStringVecIt); + +DEFINE_VECTOR(s8, S8Vec, S8It); +DEFINE_VECTOR(s8*, LPS8Vec, LPS8It); +DEFINE_VECTOR(s16, S16Vec, S16It); +DEFINE_VECTOR(s16*, LPS16Vec, LPS16It); +DEFINE_VECTOR(s32, S32Vec, S32It); +DEFINE_VECTOR(s32*, LPS32Vec, LPS32It); +DEFINE_VECTOR(u8, U8Vec, U8It); +DEFINE_VECTOR(u8*, LPU8Vec, LPU8It); +DEFINE_VECTOR(u16, U16Vec, U16It); +DEFINE_VECTOR(u16*, LPU16Vec, LPU16It); +DEFINE_VECTOR(u32, U32Vec, U32It); +DEFINE_VECTOR(u32*, LPU32Vec, LPU32It); +DEFINE_VECTOR(float, FloatVec, FloatIt); +DEFINE_VECTOR(float*, LPFloatVec, LPFloatIt); +DEFINE_VECTOR(int, IntVec, IntIt); +DEFINE_VECTOR(int*, LPIntVec, LPIntIt); + +#include "Editor/EditorPreferences.h" +#endif + +#ifdef _LEVEL_EDITOR +#include "net_utils.h" +#endif + +#define INI_NAME(buf) \ + { \ + FS.update_path(buf, "$local_root$", EFS.ChangeFileExt(UI->EditorName(), ".ini").c_str()); \ + } +//#define INI_NAME(buf) {buf = buf+xr_string(Core.WorkingPath)+xr_string("\\")+EFS.ChangeFileExt(UI->EditorName(),".ini");} +#define DEFINE_INI(storage) \ + { \ + string_path buf; \ + INI_NAME(buf); \ + storage->IniFileName = buf; \ + } +#define NONE_CAPTION "" +#define MULTIPLESEL_CAPTION "" + +// path definition +#define _server_root_ "$server_root$" +#define _server_data_root_ "$server_data_root$" +#define _local_root_ "$local_root$" +#define _import_ "$import$" +#define _sounds_ "$sounds$" +#define _textures_ "$textures$" +#define _objects_ "$objects$" +#define _maps_ "$maps$" +#define _groups_ "$groups$" +#define _temp_ "$temp$" +#define _omotion_ "$omotion$" +#define _omotions_ "$omotions$" +#define _smotion_ "$smotion$" +#define _detail_objects_ "$detail_objects$" + +#define TEX_POINT_ATT "internal\\internal_light_attpoint" +#define TEX_SPOT_ATT "internal\\internal_light_attclip" + +#include "Layers/xrRender/ETextureParams.h" +#include "Layers/xrRender/ResourceManager.h" +#include "Editor/ImageManager.h" + +#include "xrEngine/Render.h" + +inline xr_string ChangeFileExt(const char *name, const char *e) +{ + string_path path; + xr_strcpy(path, name); + if (strrchr(path, '.')) + { + strrchr(path, '.')[0] = 0; + } + xr_string str; + str.append(path); + str.append(e); + return str; +} +inline xr_string ChangeFileExt(const xr_string &name, const char *e) +{ + string_path path; + xr_strcpy(path, name.c_str()); + if (strrchr(path, '.')) + { + strrchr(path, '.')[0] = 0; + } + xr_string str; + str.append(path); + str.append(e); + return str; +} +inline u32 TColor(u32 r) +{ + return r; +} +#ifdef XRECORE_EXPORTS +inline void not_implemented() +{ + if (IsDebuggerPresent()) + DebugBreak(); + else + { + R_ASSERT(0); + } +} +#endif diff --git a/src/editors/xrECore/tga.cpp b/src/editors/xrECore/tga.cpp new file mode 100644 index 00000000000..d4cb9f8285b --- /dev/null +++ b/src/editors/xrECore/tga.cpp @@ -0,0 +1,129 @@ +// file: targasaver.cpp +#include "stdafx.h" +#pragma hdrstop + +#include "tga.h" +/* +void tga_save (LPCSTR name, u32 w, u32 h, void* data, BOOL alpha ) +{ + // Save + TGAdesc tga; + tga.data = data; + tga.format = alpha?IMG_32B:IMG_24B; + tga.height = h; + tga.width = w; + tga.scanlenght=w*4; + + int hf = _open(name,O_CREAT | O_WRONLY | O_BINARY, S_IREAD | S_IWRITE); + tga.maketga (hf); + _close (hf); +} +*/ + +void TGAdesc::maketga(IWriter &fs) +{ + R_ASSERT(data); + R_ASSERT(width); + R_ASSERT(height); + + tgaHeader hdr; + ZeroMemory(&hdr, sizeof(hdr)); + hdr.tgaImgType = 2; + hdr.tgaImgSpec.tgaXSize = u16(width); + hdr.tgaImgSpec.tgaYSize = u16(height); + + if (format == IMG_24B) + { + hdr.tgaImgSpec.tgaDepth = 24; + hdr.tgaImgSpec.tgaImgDesc = 32; // flip + } + else + { + hdr.tgaImgSpec.tgaDepth = 32; + hdr.tgaImgSpec.tgaImgDesc = 0x0f | 32; // flip + } + + fs.w(&hdr, sizeof(hdr)); + + if (format == IMG_24B) + { + BYTE ab_buffer[4] = {0, 0, 0, 0}; + int real_sl = ((width * 3)) & 3; + int ab_size = real_sl ? 4 - real_sl : 0; + for (int j = 0; j < height; j++) + { + BYTE *p = (LPBYTE)data + scanlenght * j; + for (int i = 0; i < width; i++) + { + BYTE buffer[3] = {p[0], p[1], p[2]}; + fs.w(buffer, 3); + p += 4; + } + if (ab_size) + fs.w(ab_buffer, ab_size); + } + } + else + { + if (width * 4 == scanlenght) + fs.w(data, width * height * 4); + else + { + // bad pitch, it seems :( + for (int j = 0; j < height; j++) + { + BYTE *p = (LPBYTE)data + scanlenght * j; + for (int i = 0; i < width; i++) + { + BYTE buffer[4] = {p[0], p[1], p[2], p[3]}; + fs.w(buffer, 4); + p += 4; + } + } + } + } +} + +/* +void TGAdesc::maketga( int hf ){ + R_ASSERT(data); + R_ASSERT(width); + R_ASSERT(height); + + tgaHeader hdr; + ZeroMemory( &hdr, sizeof(hdr) ); + hdr.tgaImgType = 2; + hdr.tgaImgSpec.tgaXSize = u16(width); + hdr.tgaImgSpec.tgaYSize = u16(height); + + if( format == IMG_24B ){ + hdr.tgaImgSpec.tgaDepth = 24; + hdr.tgaImgSpec.tgaImgDesc = 32; // flip + } + else{ + hdr.tgaImgSpec.tgaDepth = 32; + hdr.tgaImgSpec.tgaImgDesc = 0x0f | 32; // flip + } + + _write(hf, &hdr, sizeof(hdr) ); + + if( format==IMG_24B ){ + BYTE ab_buffer[4]={0,0,0,0}; + int real_sl = ((width*3)) & 3; + int ab_size = real_sl ? 4-real_sl : 0 ; + for( int j=0; j + + + + + + {9187BE98-531A-4276-B78E-DBA3C8AB8447} + xrECore + xrECore + + + + + + + + + + + + + + + + stdafx.h + _EDITOR;XRECORE_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + $(xrExternals)libtheora\include;$(xrExternals)libogg\include;$(xrExternals)libvorbis\include;%(AdditionalIncludeDirectories) + + + vfw32.lib;%(AdditionalDependencies) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NotUsing + + + + Create + + + + + + + + + + NotUsing + + + + NotUsing + + + + + + + NotUsing + + + + NotUsing + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {15cbfeff-7965-41f5-b4e2-21e8795c9159} + + + {653f3841-3f26-49b9-afcf-091db4b67031} + + + {3a214e06-b95e-4d61-a291-1f8df2ec10fd} + + + {1daec516-e52c-4a3c-a4da-ae3553e6e0f8} + + + {65cbb9d0-fbc6-41a4-8316-f5e9b5d7fb33} + + + {ebf9b543-0830-4866-9b48-dc0740e87e8a} + + + {7885cf3c-ee04-4c67-9467-1fbf9a36b037} + + + {a19b1df2-82ec-4364-8bdf-85d13a1c89b5} + + + {a0f7d1fb-59a7-4717-a7e4-96f37e91998e} + + + {94a1c366-3d19-48e6-8170-4adc2e70df97} + + + {98d24a3d-7666-4c11-9d6e-b10393ce8cba} + + + {132c62de-de85-4978-9675-c78ed4da46f0} + + + {ccca7859-eb86-493e-9b53-c4235f45b3c5} + + + {dcc5b76d-be13-4d1f-be14-75d0fa678340} + + + {6d47afc7-0557-4bbf-8902-b248f3621419} + + + {7e28883c-db86-4ee8-813a-991ba20c68c9} + + + + + + \ No newline at end of file diff --git a/src/editors/xrECore/xrECore.vcxproj.filters b/src/editors/xrECore/xrECore.vcxproj.filters new file mode 100644 index 00000000000..ecaac95e9b3 --- /dev/null +++ b/src/editors/xrECore/xrECore.vcxproj.filters @@ -0,0 +1,699 @@ + + + + + {9c2f17dd-6257-4111-a7ba-e30888749500} + + + {2c3b3e17-20d1-4169-a616-a45ffb634a4b} + + + {c54c47ef-21d4-49ba-93fe-8107eaf5eef4} + + + {593c3986-0d03-46a3-af38-f8fdcf08f115} + + + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Editor + + + Editor + + + + Editor + + + Editor + + + Editor + + + Engine + + + Editor + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + Engine + + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + + + + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + WildMagic + + + Editor + + + Editor + + + Editor + + + Editor + + + Editor + + + + + + \ No newline at end of file diff --git a/src/editors/xrECore/xrECoreB.bpr b/src/editors/xrECore/xrECoreB.bpr new file mode 100644 index 00000000000..494b582044c --- /dev/null +++ b/src/editors/xrECore/xrECoreB.bpr @@ -0,0 +1,567 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[Version Info] +IncludeVerInfo=0 +AutoIncBuild=0 +MajorVer=1 +MinorVer=0 +Release=0 +Build=34 +Debug=0 +PreRelease=0 +Special=0 +Private=0 +DLL=0 +Locale=1058 +CodePage=1251 + +[Version Info Keys] +CompanyName= +FileDescription= +FileVersion=1.0.0.34 +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion=1.0.0.0 +Comments= + +[HistoryLists\hlIncludePath] +Count=17 +Item0=D:\Program Files\Borland\CBuilder6\Projects;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrCDB;..\..\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\include\freeimage;$(ETOOLS_DIR) +Item1=$(VC_INCLUDE);D:\Program Files\Borland\CBuilder6\Projects;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrCDB;..\..\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\include\freeimage;$(ETOOLS_DIR) +Item2=D:\Program Files\Borland\CBuilder6\Projects;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrEngine\xrRender_R1;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrCPU_Pipe;Engine\Blenders;..\..\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\include\freeimage;$(ETOOLS_DIR) +Item3=D:\Program Files\Borland\CBuilder6\Projects;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrEngine\xrRender_R1;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrCPU_Pipe;Engine\Blenders;..\..\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\include\freeimage;$(ETOOLS_DIR) +Item4=..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrEngine\xrRender_R1;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrCPU_Pipe;Engine\Blenders;..\..\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\include\freeimage;$(ETOOLS_DIR) +Item5=..\..\common\NvMender2003;D:\STALKER\sources\engine\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrEngine\xrRender_R1;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrCPU_Pipe;Engine\Blenders;..\..\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\include\freeimage;$(ETOOLS_DIR) +Item6=..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrEngine\xrRender_R1;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrCPU_Pipe;Engine\Blenders;..\..\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\include\freeimage;$(ETOOLS_DIR) +Item7=..\..\xrEngine\xrRender_R1;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrCPU_Pipe;Engine\Blenders;..\..\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\include\freeimage;$(ETOOLS_DIR) +Item8=..\..\xrEngine\xrRender_R1;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrCPU_Pipe;Engine\Blenders;..\..\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\include\freeimage +Item9=..\..\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrCPU_Pipe;Engine\Blenders;..\..\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\include\freeimage +Item10=I:\Program Files\Borland\CBuilder6\Projects;blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\freeimage +Item11=blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR);$(SDK_DIR)\freeimage +Item12=blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR) +Item13=..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR);$(MAGIC_SW_DIR) +Item14=..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR) +Item15=..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine\xrRender;..\..\xrEngine;$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR)\include +Item16=$(DXSDK_DIR)\Include;WildMagic;Editor;Engine;$(BCB)\include;$(BCB)\include\vcl;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code\Source;$(BCB)\Include\Mfc;$(CORE_DIR);..\xrEProps;$(XIPH_DIR)\include + +[HistoryLists\hlLibraryPath] +Count=26 +Item0=..\..\..\sdk\components\ElPack\Code;..\..\..\SDK\components\AlexMX;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrCPU_Pipe;WildMagic;Editor;Engine\blenders;..\..\xrCDB;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(BCB)\Lib\Psdk;$(OUT_LIB_DIR) +Item1=..\..\..\sdk\components\ElPack\Code;..\..\..\SDK\components\AlexMX;$(COMPONENTS)\ElPack\Code;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrCPU_Pipe;WildMagic;Editor;Engine\blenders;..\..\xrCDB;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(BCB)\Lib\Psdk;$(OUT_LIB_DIR) +Item2=..\..\..\SDK\components\AlexMX;$(COMPONENTS)\ElPack\Code;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrCPU_Pipe;WildMagic;Editor;Engine\blenders;..\..\xrCDB;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(BCB)\Lib\Psdk;$(OUT_LIB_DIR) +Item3=..\..\..\SDK\components\AlexMX;$(COMPONENTS)\ElPack\Code;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrCPU_Pipe;WildMagic;Editor;Engine\blenders;..\..\xrCDB;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(BCB)\Lib\Psdk +Item4=..\..\..\SDK\components\AlexMX;$(COMPONENTS)\ElPack\Code;$(COMPONENTS)\AlexMX;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrCPU_Pipe;WildMagic;Editor;Engine\blenders;..\..\xrCDB;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(BCB)\Lib\Psdk +Item5=$(COMPONENTS)\ElPack\Code;$(COMPONENTS)\AlexMX;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrCPU_Pipe;WildMagic;Editor;Engine\blenders;..\..\xrCDB;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(BCB)\Lib\Psdk +Item6=..\..\..\SDK\components\ElPack\Code;..\..\..\SDK\components\AlexMX;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;WildMagic;Editor;Engine\blenders;..\..\xrCDB;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(BCB)\Lib\Psdk +Item7=..\..\..\SDK\components\ElPack\Code;..\..\..\SDK\components\AlexMX;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(BCB)\Lib\Psdk;x:\stalker_addon\libraries;x:\libraries +Item8=..\..\..\SDK\components\ElPack\Code;..\..\..\SDK\components\AlexMX;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(BCB)\Lib\Psdk;x:\stalker_addon\libraries +Item9=..\..\..\SDK\components\ElPack\Code;..\..\..\SDK\components\AlexMX;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\stalker_addon\libraries +Item10=..\..\..\SDK\components\AlexMX;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\stalker_addon\libraries +Item11=..\..\..\SDK\components\AlexMX;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\libraries +Item12=..\..\..\SDK\components\AlexMX;..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\libraries +Item13=..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\libraries +Item14=..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\stalker_addon\libraries +Item15=..\..\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;$(XRAY_LIBS) +Item16=D:\Program Files\Borland\CBuilder6\Projects;..\..\common\NvMender2003;D:\STALKER\sources\engine\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;$(XRAY_LIBS) +Item17=..\..\common\NvMender2003;D:\STALKER\sources\engine\common\NvMender2003;..\..;..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;$(XRAY_LIBS) +Item18=..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;$(XRAY_LIBS) +Item19=..\..\Layers\xrRenderDX9;..\..\Layers\xrRender\blenders;E:\Program Files\Borland\CBuilder6\Projects;..\..\Layers\xrRender;..\..\Layers\xrRenderPC_R1;..\..\xrRender_R1;..\..\xrCPU_Pipe;..\..\xrRender;WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\stalker_addon\libraries +Item20=WildMagic;Editor;Engine\blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\stalker_addon\libraries +Item21=$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\stalker_addon\libraries +Item22=I:\Program Files\Borland\CBuilder6\Projects;blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;WildMagic;Editor;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\libraries +Item23=blenders;..\..\xrEngine\xrRender_R1;..\..\xrEngine\blenders;WildMagic;Editor;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\libraries +Item24=WildMagic;Editor;..\..\xrCDB;..\..\xrEngine\xrCPU_Pipe;Engine\Blenders;..\..\xrEngine\xrRender;..\..\xrEngine;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\libraries +Item25=Editor;WildMagic;Engine;$(BCB)\lib;$(BCB)\lib\obj;$(BCB)\Projects\Lib;$(COMPONENTS)\AlexMX;$(COMPONENTS)\ElPack\Code;$(BCB)\Lib\Psdk;x:\libraries + +[HistoryLists\hlDebugSourcePath] +Count=1 +Item0=$(BCB)\source\vcl + +[HistoryLists\hlConditionals] +Count=4 +Item0=_EDITOR;_ECOREB;XRCDB_EXPORTS;_DEBUG +Item1=_EDITOR;_ECOREB;XRCDB_EXPORTS +Item2=_EDITOR;_ECOREB;_DEBUG;XRCDB_EXPORTS +Item3=_EDITOR;_ECOREB;_DEBUG + +[HistoryLists\hlIntOutputDir] +Count=5 +Item0=x:\intermediate_ed\ecore +Item1=$(OUTPUT_INTERMEDIATE_DIR)\ecore +Item2=Intermediate +Item3=XRLC_Intermediate +Item4=xrLC_Options + +[HistoryLists\hlFinalOutputDir] +Count=3 +Item0=$(OUTPUT_BINARIES_DIR)\ +Item1=x:\stalker_addon\binaries\ +Item2=x:\binaries\ + +[HistoryLists\hIBPIOutputDir] +Count=5 +Item0=x:\stalker_addon\libraries +Item1=$(OUTPUT_LIBRARIES_DIR) +Item2=$(OUTPUT_LIBRARIES_DIR)\ +Item3=X:\libraries +Item4=X:\libraries\ + +[Debugging] +DebugSourceDirs=$(BCB)\source\vcl + +[Parameters] +RunParams=-wf x:\stalker_addon\resources -editor +Launcher= +UseLauncher=0 +DebugCWD= +HostApplication=x:\stalker_addon\binaries\ShaderEditor.exe +RemoteHost= +RemotePath= +RemoteLauncher= +RemoteCWD= +RemoteDebug=0 + +[Compiler] +ShowInfoMsgs=0 +LinkDebugVcl=0 +LinkCGLIB=0 + +[CORBA] +AddServerUnit=1 +AddClientUnit=1 +PrecompiledHeaders=1 + +[Language] +ActiveLang= +ProjectLang= +RootDir= + +[Linker] +LibPrefix= +LibSuffix= +LibVersion= + + \ No newline at end of file diff --git a/src/editors/xrECore/xrECoreB.dsk b/src/editors/xrECore/xrECoreB.dsk new file mode 100644 index 00000000000..e8395d6a100 --- /dev/null +++ b/src/editors/xrECore/xrECoreB.dsk @@ -0,0 +1,419 @@ +[Closed Files] +File_0=SourceModule,'P:\Editors\!.txt',0,1,62,35,75,0,0 +File_1=SourceModule,'P:\Editors\ECore\xrEProps.h',0,1,1,11,10,0,0 +File_2=SourceModule,'P:\Editors\ECore\stdafx.cpp',0,1,1,1,1,0,0 +File_3=SourceModule,'R:\SDK\DirectX9.0_beta3\include\d3dx9core.h',0,1,629,22,644,0,0 +File_4=SourceModule,'P:\Editors\LevelEditor\Edit\CustomObjectLE.cpp',0,1,203,23,219,0,0 +File_5=SourceModule,'P:\Editors\LevelEditor\Edit\GroupObject.cpp',0,1,143,23,158,0,0 +File_6=SourceModule,'P:\Editors\ECore\Editor\CustomObject.h',0,1,155,50,164,0,0 +File_7=SourceModule,'P:\Editors\LevelEditor\Edit\ELight.cpp',0,1,34,1,1,0,0 +File_8=SourceModule,'P:\Editors\LevelEditor\Edit\SpawnPoint.cpp',0,1,216,19,231,0,0 +File_9=SourceModule,'P:\Editors\LevelEditor\Edit\UI_SpawnTools.cpp',0,1,28,1,30,0,0 + +[Modules] +Module0=P:\Editors\ECore\xrECoreB.bpr +Count=1 +EditWindowCount=1 + +[P:\Editors\ECore\xrECoreB.bpr] +ModuleType=SourceModule +FormState=0 +FormOnTop=0 + +[C:\Rad\Borland\CBuilder6\Projects\ProjectGroup1.bpg] +FormState=0 +FormOnTop=0 + +[EditWindow0] +ViewCount=1 +CurrentView=0 +View0=0 +CodeExplorer=CodeExplorer@EditWindow0 +MessageView=MessageView@EditWindow0 +ClassHierarchy=ClassHierarchy@EditWindow0 +Create=1 +Visible=1 +State=0 +Left=230 +Top=101 +Width=1050 +Height=893 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=1042 +ClientHeight=866 +LeftPanelSize=0 +RightPanelSize=0 +BottomPanelSize=276 +BottomPanelClients=DockSite0 +BottomPanelData=0000040000000000120400000000000002140100000000000001000000001204000009000000446F636B5369746530FFFFFFFF + +[View0] +Module=P:\Editors\ECore\xrECoreB.bpf +CursorX=1 +CursorY=1 +TopLine=1 +LeftCol=1 + +[Watches] +Count=0 + +[Breakpoints] +Count=0 + +[AddressBreakpoints] +Count=0 + +[Main Window] +Create=1 +Visible=1 +State=2 +Left=0 +Top=0 +Width=1280 +Height=105 +MaxLeft=-1 +MaxTop=-1 +MaxWidth=1288 +MaxHeight=105 +ClientWidth=1280 +ClientHeight=78 + +[Components] +Create=1 +Visible=0 +State=0 +Left=264 +Top=229 +Width=351 +Height=490 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=343 +ClientHeight=466 + +[ProjectManager] +Create=1 +Visible=1 +State=0 +Left=0 +Top=0 +Width=1022 +Height=247 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=1022 +ClientHeight=247 +TBDockHeight=303 +LRDockWidth=438 +Dockable=1 + +[CPUWindow] +Create=1 +Visible=0 +State=0 +Left=606 +Top=335 +Width=533 +Height=353 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=525 +ClientHeight=326 +DumpPane=79 +DisassemblyPane=187 +RegisterPane=231 +FlagPane=64 + +[DebugLogView] +Create=1 +Visible=1 +State=0 +Left=0 +Top=0 +Width=1022 +Height=247 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=1022 +ClientHeight=247 +TBDockHeight=291 +LRDockWidth=417 +Dockable=1 + +[LocalVarsWindow] +Create=1 +Visible=0 +State=0 +Left=669 +Top=573 +Width=541 +Height=268 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=533 +ClientHeight=244 +TBDockHeight=273 +LRDockWidth=421 +Dockable=1 + +[ToDo List] +Create=1 +Visible=1 +State=0 +Left=0 +Top=0 +Width=1022 +Height=247 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=1022 +ClientHeight=247 +TBDockHeight=276 +LRDockWidth=310 +Dockable=1 +Column0Width=157 +Column1Width=30 +Column2Width=100 +Column3Width=70 +Column4Width=70 +SortOrder=4 +ShowHints=1 +ShowChecked=1 + +[WatchWindow] +Create=1 +Visible=0 +State=0 +Left=703 +Top=488 +Width=541 +Height=268 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=533 +ClientHeight=244 +TBDockHeight=149 +LRDockWidth=421 +Dockable=1 + +[CallStackWindow] +Create=1 +Visible=0 +State=0 +Left=383 +Top=379 +Width=481 +Height=297 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=473 +ClientHeight=273 +TBDockHeight=273 +LRDockWidth=294 +Dockable=1 + +[AlignmentPalette] +Create=1 +Visible=0 +State=0 +Left=200 +Top=107 +Width=156 +Height=82 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=150 +ClientHeight=60 + +[PropertyInspector] +Create=1 +Visible=1 +State=0 +Left=2 +Top=101 +Width=228 +Height=893 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=220 +ClientHeight=869 +TBDockHeight=869 +LRDockWidth=190 +Dockable=1 +SplitPos=103 +ArrangeBy=Name +SelectedItem= +ExpandedItems= +HiddenCategories= + +[BreakpointWindow] +Create=1 +Visible=1 +State=0 +Left=0 +Top=0 +Width=1022 +Height=247 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=1022 +ClientHeight=247 +TBDockHeight=134 +LRDockWidth=737 +Dockable=1 +Column0Width=100 +Column1Width=75 +Column2Width=200 +Column3Width=200 +Column4Width=75 +Column5Width=75 + +[ThreadStatusWindow] +Create=1 +Visible=0 +State=0 +Left=739 +Top=742 +Width=541 +Height=268 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=533 +ClientHeight=244 +TBDockHeight=152 +LRDockWidth=624 +Dockable=1 +Column0Width=145 +Column1Width=100 +Column2Width=115 +Column3Width=250 + +[ModuleWindow] +Create=1 +Visible=0 +State=0 +Left=481 +Top=422 +Width=638 +Height=355 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=630 +ClientHeight=331 +TBDockHeight=355 +LRDockWidth=638 +Dockable=1 +Column0Width=125 +Column1Width=100 +Column2Width=155 +EntryPointPane=225 +CompUnitPane=104 + +[ObjectTree] +Create=1 +Visible=0 +State=0 +Left=294 +Top=216 +Width=445 +Height=471 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=437 +ClientHeight=447 +TBDockHeight=356 +LRDockWidth=190 +Dockable=1 + +[CodeguardLog] +Create=1 +Visible=1 +State=0 +Left=0 +Top=0 +Width=1022 +Height=247 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=1022 +ClientHeight=247 +TBDockHeight=190 +LRDockWidth=448 +Dockable=1 + +[ClassHierarchy@EditWindow0] +Create=1 +Visible=0 +State=0 +Left=218 +Top=113 +Width=403 +Height=284 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=395 +ClientHeight=260 +TBDockHeight=284 +LRDockWidth=403 +Dockable=1 +TreeWidth=121 +Col1Width=120 +Col2Width=120 + +[CodeExplorer@EditWindow0] +Create=1 +Visible=0 +State=0 +Left=685 +Top=309 +Width=178 +Height=788 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=170 +ClientHeight=764 +TBDockHeight=576 +LRDockWidth=170 +Dockable=1 +ClassViewDisplayMode=0 + +[MessageView@EditWindow0] +Create=1 +Visible=1 +State=0 +Left=0 +Top=0 +Width=1022 +Height=247 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=1022 +ClientHeight=247 +TBDockHeight=276 +LRDockWidth=443 +Dockable=1 + +[DockHosts] +DockHostCount=1 + +[DockSite0] +DockSiteType=1 +Create=1 +Visible=1 +State=0 +Left=12 +Top=0 +Width=1030 +Height=276 +MaxLeft=-1 +MaxTop=-1 +ClientWidth=1030 +ClientHeight=276 +TBDockHeight=276 +LRDockWidth=283 +Dockable=1 +TabPosition=0 +ActiveTab=Project Manager +TabDockClients=ToDo List,BreakpointWindow,MessageView@EditWindow0,ProjectManager,CodeguardLog,DebugLogView + diff --git a/src/editors/xrEProps/FolderLib.cpp b/src/editors/xrEProps/FolderLib.cpp new file mode 100644 index 00000000000..fd4f341c7b2 --- /dev/null +++ b/src/editors/xrEProps/FolderLib.cpp @@ -0,0 +1 @@ +#include "stdafx.h" diff --git a/src/editors/xrEProps/FolderLib.h b/src/editors/xrEProps/FolderLib.h new file mode 100644 index 00000000000..8874225c5a3 --- /dev/null +++ b/src/editors/xrEProps/FolderLib.h @@ -0,0 +1,463 @@ +#pragma once +template +class FolderHelper +{ +public: + enum EFolderNodeType + { + FNT_Root, + FNT_Folder, + FNT_Object + }; + struct Node + { + Node() : Object(nullptr), Type(FNT_Root), Selected(false) {} + ~Node() {} + bool Selected; + EFolderNodeType Type; + shared_str Name; + shared_str Path; + xr_vector Nodes; + mutable C *Object; + IC bool IsObject() { return Type == FNT_Object; } + IC bool IsFolder() { return Type == FNT_Folder || Type == FNT_Root; } + }; + FolderHelper() {} + inline ~FolderHelper() {} + inline Node *SelectObject(Node *N, const char *path) + { + VERIFY(N); + VERIFY(N->IsFolder()); + if (strchr(path, '\\')) + { + string_path name; + xr_strcpy(name, path); + strchr(name, '\\')[0] = 0; + N = FindFolder(N, name); + VERIFY(N); + N->Selected = true; + return SelectObject(N, strchr(path, '\\') + 1); + } + for (Node &node : N->Nodes) + { + if (FolderAsItem) + { + if (node.Name == path && node.Object) + { + node.Selected = true; + return &node; + } + } + else + { + if (node.Name == path && node.IsObject()) + { + node.Selected = true; + return &node; + } + } + } + VERIFY(false); + return nullptr; + } + inline Node *FindObject(Node *N, const char *path) + { + if (N == nullptr) + return nullptr; + if (!N->IsFolder()) + return nullptr; + if (strchr(path, '\\')) + { + string_path name; + xr_strcpy(name, path); + strrchr(name, '\\')[0] = 0; + path = strrchr(path, '\\') + 1; + N = FindFolder(N, name); + if (N == nullptr) + return nullptr; + } + for (Node &node : N->Nodes) + { + if (node.Name == path && node.IsObject()) + return &node; + } + return nullptr; + } + + inline Node *Find(Node *N, const char *path) + { + if (N == nullptr) + return nullptr; + + if (!N->IsFolder()) + return nullptr; + + if (strchr(path, '\\')) + { + string_path name; + xr_strcpy(name, path); + strrchr(name, '\\')[0] = 0; + path = strrchr(path, '\\') + 1; + N = FindFolder(N, name); + + if (!N) + return nullptr; + } + + for (Node &node : N->Nodes) + { + if (node.Name == path) + return &node; + } + + return nullptr; + } + + inline Node *FindFolder(Node *N, const char *path) + { + if (!N) + return nullptr; + + if (!N->IsFolder()) + return nullptr; + + if (strchr(path, '\\')) + { + string_path name; + xr_strcpy(name, path); + strchr(name, '\\')[0] = 0; + return FindFolder(FindFolder(N, name), strchr(path, '\\') + 1); + } + + for (Node &node : N->Nodes) + { + if (node.Name == path && node.IsFolder()) + return &node; + } + + return nullptr; + } + + inline Node *AppendFolder(Node *N, const char *path) + { + if (!N) + return nullptr; + + if (strchr(path, '\\')) + { + string_path name; + xr_strcpy(name, path); + strchr(name, '\\')[0] = 0; + + Node *NextNode = FindFolder(N, name); + if (NextNode) + return AppendFolder(NextNode, strchr(path, '\\') + 1); + + return AppendFolder(AppendFolder(N, name), strchr(path, '\\') + 1); + } + + for (Node &node : N->Nodes) + { + if (node.Name == path) + { + if constexpr (FolderAsItem) + { + node.Type = FNT_Folder; + return &node; + } + else + { + if (node.IsFolder()) + return &node; + // return nullptr; + } + } + } + Node NewNode; + NewNode.Type = FNT_Folder; + NewNode.Name = path; + if (N->Path.size() == 0) + { + if (N->Name.size()) + NewNode.Path = N->Name; + else + NewNode.Path = ""; + } + else + NewNode.Path.printf("%s\\%s", N->Path.c_str(), N->Name.c_str()); + + N->Nodes.push_back(NewNode); + return &N->Nodes.back(); + } + + inline Node *AppendObject(Node *N, const char *path) + { + if (!N) + return nullptr; + + if (strchr(path, '\\')) + { + string_path name; + xr_strcpy(name, path); + + char *slash = strchr(name, '\\'); + *slash = '\0'; + + Node *NextNode = FindFolder(N, name); + if (NextNode) + return AppendObject(NextNode, strchr(path, '\\') + 1); + + return AppendObject(AppendFolder(N, name), strchr(path, '\\') + 1); + } + + for (Node &node : N->Nodes) + { + if (node.Name == path) + { + if constexpr (FolderAsItem) + { + if (node.IsObject()) + return &node; + return nullptr; + } + else + return &node; + } + } + + Node NewNode; + NewNode.Type = FNT_Object; + NewNode.Name = path; + + if (N->Path.size() == 0) + { + if (N->Name.size()) + NewNode.Path = N->Name; + else + NewNode.Path = ""; + } + else + NewNode.Path.printf("%s\\%s", N->Path.c_str(), N->Name.c_str()); + + N->Nodes.push_back(NewNode); + return &N->Nodes.back(); + } + + inline void Remove(Node *N, Node *Object, bool use_event = false) + { + Node *F = Object->Path.size() == 0 ? N : FindFolder(N, Object->Path.c_str()); + R_ASSERT(F); + string_path path; + if (use_event) + { + RemoveNode(Object); + GetFullPath(Object, path); + EventRemoveNode(Object, path); + } + R_ASSERT(RemoveNodeFromN(F, Object)); + } + inline bool Move(Node *N, Node *Object, const char *new_path) + { + { + Node *ObjectNew = nullptr; + bool IsFolder = false; + + string_path old_path; + GetFullPath(Object, old_path); + + if (Object->IsFolder()) + { + IsFolder = true; + ObjectNew = AppendFolder(N, new_path); + } + else + + { + ObjectNew = AppendObject(N, new_path); + } + if (IsFolder) + { + Object = FindFolder(N, old_path); + } + else + + { + Object = FindObject(N, old_path); + } + if (ObjectNew == Object) + return false; + if (!ObjectNew) + return false; + + SwapData(ObjectNew, Object); + Remove(N, Object); + if (IsFolder) + { + ObjectNew = FindFolder(N, new_path); + } + else + { + ObjectNew = FindObject(N, new_path); + } + R_ASSERT(ObjectNew); + EventRenameNode(ObjectNew, old_path, new_path); + RebuildPath(ObjectNew); + ObjectNew->Selected = true; + } + return true; + } + + virtual void DrawNode(Node *N) + { + if (N->Type == FNT_Root) + { + for (Node &node : N->Nodes) + { + if (node.IsFolder() && IsDrawFolder(&node)) + { + DrawNode(&node); + } + } + for (Node &node : N->Nodes) + { + if (!node.IsFolder()) + { + DrawNode(&node); + } + } + } + else if (N->IsFolder()) + { + if (N->Selected) + ImGui::SetNextItemOpen(true); + + ImGui::AlignTextToFramePadding(); + ImGuiTreeNodeFlags FolderFlags = ImGuiTreeNodeFlags_OpenOnArrow; + + if (IsFolderBullet(N)) + FolderFlags |= ImGuiTreeNodeFlags_Bullet; + + if (IsFolderSelected(N)) + FolderFlags |= ImGuiTreeNodeFlags_Selected; + + if (ImGui::TreeNodeEx(N->Name.c_str(), FolderFlags)) + { + DrawAfterFolderNode(true, N); + if (ImGui::IsItemClicked() && N->Object) + IsItemClicked(N); + for (Node &node : N->Nodes) + { + if (node.IsFolder() && IsDrawFolder(&node)) + { + DrawNode(&node); + } + } + for (Node &node : N->Nodes) + { + if (!node.IsFolder()) + { + DrawNode(&node); + } + } + ImGui::TreePop(); + } + else + { + DrawAfterFolderNode(false, N); + if (ImGui::IsItemClicked() && N->Object) + IsItemClicked(N); + } + if (N->Selected) + N->Selected = false; + } + else if (N->IsObject()) + { + DrawItem(N); + if (N->Selected) + N->Selected = false; + } + } + virtual void DrawAfterFolderNode(bool is_open = false, Node *Node = 0) {} + virtual bool IsFolderBullet(Node *Node) { return false; } + virtual bool IsFolderSelected(Node *Node) { return false; } + virtual void EventRenameNode(Node *Node, const char *old_path, const char *new_path) {} + virtual void EventRemoveNode(Node *Node, const char *path) {} + inline void GetFullPath(Node *Object, string_path &full_path) + { + if (Object->Path.c_str() && Object->Path.c_str()[0]) + xr_strcpy(full_path, Object->Path.c_str()); + else + full_path[0] = 0; + + if (full_path[0]) + xr_strcat(full_path, "\\"); + xr_strcat(full_path, Object->Name.c_str()); + } + virtual void IsItemClicked(Node *Node) {} + virtual bool IsDrawFolder(Node *Node) = 0; + virtual void DrawItem(Node *Node) = 0; + +private: + inline void SwapData(Node *Dst, Node *Src) + { + std::swap(Dst->Type, Src->Type); + std::swap(Dst->Object, Src->Object); + Dst->Nodes.swap(Src->Nodes); + } + inline void RebuildPath(Node *N) + { + for (Node &n : N->Nodes) + { + + string_path old_path, new_path; + GetFullPath(&n, old_path); + + if (N->Path.size() == 0) + { + if (N->Name.size()) + { + n.Path = N->Name; + } + else + { + + n.Path = ""; + } + } + else + { + + n.Path.printf("%s\\%s", N->Path.c_str(), N->Name.c_str()); + } + GetFullPath(&n, new_path); + + EventRenameNode(&n, old_path, new_path); + RebuildPath(&n); + } + } + + inline void RemoveNode(Node *Object) + { + for (Node &n : Object->Nodes) + { + string_path path; + RemoveNode(&n); + GetFullPath(&n, path); + EventRemoveNode(&n, path); + } + Object->Nodes.clear(); + } + + inline bool RemoveNodeFromN(Node *N, Node *Object) + { + for (auto b = N->Nodes.begin(), e = N->Nodes.end(); b != e; b++) + { + if (&(*b) == Object) + { + N->Nodes.erase(b); + return true; + } + } + return false; + } +}; diff --git a/src/editors/xrEProps/ItemListHelper.cpp b/src/editors/xrEProps/ItemListHelper.cpp new file mode 100644 index 00000000000..624953f8084 --- /dev/null +++ b/src/editors/xrEProps/ItemListHelper.cpp @@ -0,0 +1,68 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "ItemListHelper.h" +//--------------------------------------------------------------------------- +//--------------------------------------------------------------------------- +CListHelper LHelper_impl; +XREPROPS_API IListHelper& LHelper() { return LHelper_impl; } +//--------------------------------------------------------------------------- + +ListItem *CListHelper::FindItem(ListItemsVec &items, LPCSTR key) +{ + for (auto it = items.begin(); it != items.end(); it++) + if ((*it)->key == key) + return *it; + return 0; +} + +ListItem *CListHelper::CreateItem(ListItemsVec &items, LPCSTR key, int type, u32 item_flags, void *object) +{ + ListItem *item = xr_new(type); + item->SetName(key); + item->m_Object = object; + item->m_Flags.set(item_flags, TRUE); + items.push_back(item); + return item; +} + +bool CListHelper::NameAfterEdit(ListItem *sender, LPCSTR value, shared_str &N) +{ + if (strstr(N.c_str(), "\\")) + { + N = value; + return false; + } + xr_strlwr(N); + if (!N.size()) + { + N = value; + return false; + } + int cnt = _GetItemCount(N.c_str(), '\\'); + if (cnt > 1) + { + N = value; + return false; + } + + for (ListItem *item : sender->Parent->GetItems()) + { + const char *name = strrchr(item->Key(), '\\'); + if (!name) + name = item->Key(); + else + name++; + if ((item != sender) && (N == name)) + { + // елемент с таким именем уже существует + N = value; + return false; + } + } + string2048 tmp; + _ReplaceItem(value, _GetItemCount(value, '\\') - 1, N.c_str(), tmp, '\\'); + N = tmp; + return true; +} +//--------------------------------------------------------------------------- diff --git a/src/editors/xrEProps/ItemListHelper.h b/src/editors/xrEProps/ItemListHelper.h new file mode 100644 index 00000000000..bf63c10f194 --- /dev/null +++ b/src/editors/xrEProps/ItemListHelper.h @@ -0,0 +1,17 @@ +//--------------------------------------------------------------------------- +#ifndef ItemListHelperH +#define ItemListHelperH + +//--------------------------------------------------------------------------- +class CListHelper : public IListHelper +{ + //------------------------------------------------------------------------------ +public: + virtual ListItem *FindItem(ListItemsVec &items, LPCSTR key); + virtual bool NameAfterEdit(ListItem *sender, LPCSTR value, shared_str &edit_val); + +public: + virtual ListItem *CreateItem(ListItemsVec &items, LPCSTR key, int type, u32 item_flags = 0, void *object = 0); +}; +//--------------------------------------------------------------------------- +#endif diff --git a/src/editors/xrEProps/PropertiesListHelper.cpp b/src/editors/xrEProps/PropertiesListHelper.cpp new file mode 100644 index 00000000000..762d4c4d68d --- /dev/null +++ b/src/editors/xrEProps/PropertiesListHelper.cpp @@ -0,0 +1,358 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "../../xrServerEntities/PropertiesListHelper.h" +//#include "ChoseForm.h" +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +CPropHelper PHelper_impl; +XREPROPS_API IPropHelper& PHelper() { return PHelper_impl; } +//--------------------------------------------------------------------------- +PropItem *CPropHelper::CreateItem(PropItemVec &items, const shared_str &key, EPropType type, u32 item_flags) +{ + PropItem *item = FindItem(items, key, type); + if (!item) + { + item = xr_new(type); + item->SetName(key); + item->m_Flags.set(item_flags, TRUE); + items.push_back(item); + } + return item; +} +PropValue *CPropHelper::AppendValue(PropItemVec &items, const shared_str &key, PropValue *val, EPropType type, u32 item_flags) +{ + PropItem *item = CreateItem(items, key, type, item_flags); + val->m_Owner = item; + item->AppendValue(val); + return val; +} +PropItem *CPropHelper::FindItem(PropItemVec &items, shared_str key, EPropType type) +{ + if (type != PROP_UNDEF) + { + for (PropItemIt it = items.begin(); it != items.end(); it++) + if (((*it)->type == type) && ((*it)->key == key)) + return *it; + } + else + { + for (PropItemIt it = items.begin(); it != items.end(); it++) + if ((*it)->key == key) + return *it; + } + return 0; +} +//--------------------------------------------------------------------------- + +CaptionValue *CPropHelper::CreateCaption(PropItemVec &items, shared_str key, shared_str val) +{ + return (CaptionValue *)AppendValue(items, key, xr_new(val), PROP_CAPTION); +} +CanvasValue *CPropHelper::CreateCanvas(PropItemVec &items, shared_str key, shared_str val, int height) +{ + return (CanvasValue *)AppendValue(items, key, xr_new(val, height), PROP_CANVAS); +} +ButtonValue *CPropHelper::CreateButton(PropItemVec &items, shared_str key, shared_str val, u32 flags, ButtonValue::TOnBtnClick onClick) +{ + PropValue *PV = AppendValue(items, key, xr_new(val, flags), PROP_BUTTON); + ButtonValue *BV = dynamic_cast(PV); + BV->OnBtnClickEvent = onClick; + return BV; + // return (ButtonValue*) AppendValue (items,key,xr_new(val,flags),PROP_BUTTON); +} +S8Value *CPropHelper::CreateS8(PropItemVec &items, shared_str key, s8 *val, s8 mn, s8 mx, s8 inc) +{ + return (S8Value *)AppendValue(items, key, xr_new(val, mn, mx, inc, 0), PROP_NUMERIC); +} +S16Value *CPropHelper::CreateS16(PropItemVec &items, shared_str key, s16 *val, s16 mn, s16 mx, s16 inc) +{ + return (S16Value *)AppendValue(items, key, xr_new(val, mn, mx, inc, 0), PROP_NUMERIC); +} +S32Value *CPropHelper::CreateS32(PropItemVec &items, shared_str key, s32 *val, s32 mn, s32 mx, s32 inc) +{ + return (S32Value *)AppendValue(items, key, xr_new(val, mn, mx, inc, 0), PROP_NUMERIC); +} +U8Value *CPropHelper::CreateU8(PropItemVec &items, shared_str key, u8 *val, u8 mn, u8 mx, u8 inc) +{ + return (U8Value *)AppendValue(items, key, xr_new(val, mn, mx, inc, 0), PROP_NUMERIC); +} +U16Value *CPropHelper::CreateU16(PropItemVec &items, shared_str key, u16 *val, u16 mn, u16 mx, u16 inc) +{ + return (U16Value *)AppendValue(items, key, xr_new(val, mn, mx, inc, 0), PROP_NUMERIC); +} +U32Value *CPropHelper::CreateU32(PropItemVec &items, shared_str key, u32 *val, u32 mn, u32 mx, u32 inc) +{ + return (U32Value *)AppendValue(items, key, xr_new(val, mn, mx, inc, 0), PROP_NUMERIC); +} +FloatValue *CPropHelper::CreateFloat(PropItemVec &items, shared_str key, float *val, float mn, float mx, float inc, int decim) +{ + return (FloatValue *)AppendValue(items, key, xr_new(val, mn, mx, inc, decim), PROP_NUMERIC); +} +BOOLValue *CPropHelper::CreateBOOL(PropItemVec &items, shared_str key, BOOL *val) +{ + return (BOOLValue *)AppendValue(items, key, xr_new(val), PROP_BOOLEAN); +} +VectorValue *CPropHelper::CreateVector(PropItemVec &items, shared_str key, Fvector *val, float mn, float mx, float inc, int decim) +{ + return (VectorValue *)AppendValue(items, key, xr_new(val, mn, mx, inc, decim), PROP_VECTOR); +} +Flag8Value *CPropHelper::CreateFlag8(PropItemVec &items, shared_str key, Flags8 *val, u8 mask, LPCSTR c0, LPCSTR c1, u32 flags) +{ + return (Flag8Value *)AppendValue(items, key, xr_new(val, mask, c0, c1, flags), PROP_FLAG); +} +Flag16Value *CPropHelper::CreateFlag16(PropItemVec &items, shared_str key, Flags16 *val, u16 mask, LPCSTR c0, LPCSTR c1, u32 flags) +{ + return (Flag16Value *)AppendValue(items, key, xr_new(val, mask, c0, c1, flags), PROP_FLAG); +} +Flag32Value *CPropHelper::CreateFlag32(PropItemVec &items, shared_str key, Flags32 *val, u32 mask, LPCSTR c0, LPCSTR c1, u32 flags) +{ + return (Flag32Value *)AppendValue(items, key, xr_new(val, mask, c0, c1, flags), PROP_FLAG); +} +Token8Value *CPropHelper::CreateToken8(PropItemVec &items, shared_str key, u8 *val, xr_token *token) +{ + return (Token8Value *)AppendValue(items, key, xr_new(val, token), PROP_TOKEN); +} +Token16Value *CPropHelper::CreateToken16(PropItemVec &items, shared_str key, u16 *val, xr_token *token) +{ + return (Token16Value *)AppendValue(items, key, xr_new(val, token), PROP_TOKEN); +} +Token32Value *CPropHelper::CreateToken32(PropItemVec &items, shared_str key, u32 *val, xr_token *token) +{ + return (Token32Value *)AppendValue(items, key, xr_new(val, token), PROP_TOKEN); +} +RToken8Value *CPropHelper::CreateRToken8(PropItemVec &items, shared_str key, u8 *val, xr_rtoken *token, u32 t_cnt) +{ + return (RToken8Value *)AppendValue(items, key, xr_new(val, token, t_cnt), PROP_RTOKEN); +} +RToken16Value *CPropHelper::CreateRToken16(PropItemVec &items, shared_str key, u16 *val, xr_rtoken *token, u32 t_cnt) +{ + return (RToken16Value *)AppendValue(items, key, xr_new(val, token, t_cnt), PROP_RTOKEN); +} +RToken32Value *CPropHelper::CreateRToken32(PropItemVec &items, shared_str key, u32 *val, xr_rtoken *token, u32 t_cnt) +{ + return (RToken32Value *)AppendValue(items, key, xr_new(val, token, t_cnt), PROP_RTOKEN); +} +TokenValueSH *CPropHelper::CreateTokenSH(PropItemVec &items, shared_str key, u32 *val, const TokenValueSH::Item *lst, u32 cnt) +{ + return (TokenValueSH *)AppendValue(items, key, xr_new(val, lst, cnt), PROP_SH_TOKEN); +} +RListValue *CPropHelper::CreateRList(PropItemVec &items, shared_str key, shared_str *val, shared_str *lst, u32 cnt) +{ + return (RListValue *)AppendValue(items, key, xr_new(val, lst, cnt), PROP_RLIST); +} +U32Value *CPropHelper::CreateColor(PropItemVec &items, shared_str key, u32 *val) +{ + return (U32Value *)AppendValue(items, key, xr_new(val, 0x00000000, 0xffffffff, 1, 0), PROP_COLOR); +} +ColorValue *CPropHelper::CreateFColor(PropItemVec &items, shared_str key, Fcolor *val) +{ + return (ColorValue *)AppendValue(items, key, xr_new(val), PROP_FCOLOR); +} +VectorValue *CPropHelper::CreateVColor(PropItemVec &items, shared_str key, Fvector *val) +{ + return (VectorValue *)AppendValue(items, key, xr_new(val, 0.f, 1.f, 0.f, 0), PROP_VCOLOR); +} +RTextValue *CPropHelper::CreateRText(PropItemVec &items, shared_str key, shared_str *val) +{ + return (RTextValue *)AppendValue(items, key, xr_new(val), PROP_RTEXT); +} +STextValue *CPropHelper::CreateSText(PropItemVec &items, shared_str key, xr_string *val) +{ + return (STextValue *)AppendValue(items, key, xr_new(val), PROP_STEXT); +} +WaveValue *CPropHelper::CreateWave(PropItemVec &items, shared_str key, WaveForm *val) +{ + return (WaveValue *)AppendValue(items, key, xr_new(val), PROP_WAVE); +} +FloatValue *CPropHelper::CreateTime(PropItemVec &items, shared_str key, float *val, float mn, float mx) +{ + return (FloatValue *)AppendValue(items, key, xr_new(val, mn, mx, 0.f, 0), PROP_TIME); +} +ShortcutValue *CPropHelper::CreateShortcut(PropItemVec &items, shared_str key, xr_shortcut *val) +{ + return (ShortcutValue *)AppendValue(items, key, xr_new(val), PROP_SHORTCUT); +} + +GameTypeValue *CPropHelper::CreateGameType(PropItemVec &items, shared_str key, GameTypeChooser *val) +{ + return (GameTypeValue *)AppendValue(items, key, xr_new(val), PROP_GAMETYPE); +} + +//--------------------------------------------------------------------------- +ChooseValue *CPropHelper::CreateChoose(PropItemVec &items, shared_str key, shared_str *val, u32 mode, LPCSTR path, void *fill_param, u32 sub_item_count, u32 choose_flags) +{ + ChooseValue *cv = (ChooseValue *)AppendValue(items, key, xr_new(val, mode, path, fill_param, sub_item_count, choose_flags), PROP_CHOOSE); + SChooseEvents *E = UIChooseForm::GetEvents(mode); + /*if (E&&!E->on_thm.empty()){ + cv->Owner()->m_Flags.set(PropItem::flDrawThumbnail,TRUE); + // cv->OnDrawThumbnailEvent = E->on_thm; + }*/ + return cv; +} +//--------------------------------------------------------------------------- +// obsolette +//--------------------------------------------------------------------------- +CTextValue *CPropHelper::CreateCText(PropItemVec &items, shared_str key, LPSTR val, u32 sz) +{ + return (CTextValue *)AppendValue(items, key, xr_new(val, sz), PROP_CTEXT); +} +CTextValue *CPropHelper::CreateTexture(PropItemVec &items, shared_str key, LPSTR val, u32 sz) +{ + return (CTextValue *)AppendValue(items, key, xr_new(val, sz), PROP_TEXTURE2); +} +CListValue *CPropHelper::CreateCList(PropItemVec &items, shared_str key, LPSTR val, u32 sz, xr_string *lst, u32 cnt) +{ + return (CListValue *)AppendValue(items, key, xr_new(val, sz, lst, cnt), PROP_CLIST); +} +CTextValue *CPropHelper::CreateCName(PropItemVec &items, shared_str key, LPSTR val, u32 sz, ListItem *owner) +{ + CTextValue *V = (CTextValue *)CreateCText(items, key, val, sz); + V->OnAfterEditEvent.bind(this, &CPropHelper::CNameAfterEdit); + V->OnBeforeEditEvent.bind(this, &CPropHelper::CNameBeforeEdit); + V->Owner()->OnDrawTextEvent.bind(this, &CPropHelper::CNameDraw); + V->tag = (size_t)owner; + VERIFY(owner); + if (V->Owner()->m_Flags.is(PropItem::flMixed)) + V->Owner()->m_Flags.set(PropItem::flDisabled, TRUE); + return V; +} +//--------------------------------------------------------------------------- + +FloatValue *CPropHelper::CreateAngle(PropItemVec &items, shared_str key, float *val, float mn, float mx, float inc, int decim) +{ + FloatValue *V = (FloatValue *)AppendValue(items, key, xr_new(val, mn, mx, inc, decim), PROP_NUMERIC); + V->OnAfterEditEvent.bind(this, &CPropHelper::floatRDOnAfterEdit); + V->OnBeforeEditEvent.bind(this, &CPropHelper::floatRDOnBeforeEdit); + V->Owner()->OnDrawTextEvent.bind(this, &CPropHelper::floatRDOnDraw); + return V; +} +VectorValue *CPropHelper::CreateAngle3(PropItemVec &items, shared_str key, Fvector *val, float mn, float mx, float inc, int decim) +{ + VectorValue *V = (VectorValue *)AppendValue(items, key, xr_new(val, mn, mx, inc, decim), PROP_VECTOR); + V->OnAfterEditEvent.bind(this, &CPropHelper::FvectorRDOnAfterEdit); + V->OnBeforeEditEvent.bind(this, &CPropHelper::FvectorRDOnBeforeEdit); + V->Owner()->OnDrawTextEvent.bind(this, &CPropHelper::FvectorRDOnDraw); + return V; +} +RTextValue *CPropHelper::CreateName(PropItemVec &items, shared_str key, shared_str *val, ListItem *owner) +{ + RTextValue *V = (RTextValue *)CreateRText(items, key, val); + V->OnAfterEditEvent.bind(this, &CPropHelper::NameAfterEdit); + V->OnBeforeEditEvent.bind(this, &CPropHelper::NameBeforeEdit); + V->Owner()->OnDrawTextEvent.bind(this, &CPropHelper::NameDraw); + V->tag = (size_t)owner; + VERIFY(owner); + if (V->Owner()->m_Flags.is(PropItem::flMixed)) + V->Owner()->m_Flags.set(PropItem::flDisabled, TRUE); + return V; +} +RTextValue *CPropHelper::CreateNameCB(PropItemVec &items, shared_str key, shared_str *val, TOnDrawTextEvent draw, RTextValue::TOnBeforeEditEvent before, RTextValue::TOnAfterEditEvent after) +{ + RTextValue *V = (RTextValue *)CreateRText(items, key, val); + V->OnAfterEditEvent = after; + V->OnBeforeEditEvent = before; + V->Owner()->OnDrawTextEvent = draw; + if (V->Owner()->m_Flags.is(PropItem::flMixed)) + V->Owner()->m_Flags.set(PropItem::flDisabled, TRUE); + return V; +} +//--------------------------------------------------------------------------- + +void CPropHelper::FvectorRDOnBeforeEdit(PropValue *sender, Fvector &edit_val) +{ + edit_val.set(rad2deg(edit_val.x), rad2deg(edit_val.y), rad2deg(edit_val.z)); + VectorValue *V = dynamic_cast(sender); + R_ASSERT(V); + V->lim_mn.set(rad2deg(V->lim_mn.x), rad2deg(V->lim_mn.y), rad2deg(V->lim_mn.z)); + V->lim_mx.set(rad2deg(V->lim_mx.x), rad2deg(V->lim_mx.y), rad2deg(V->lim_mx.z)); +} +void CPropHelper::FvectorRDOnDraw(PropValue *sender, xr_string &draw_val) +{ + VectorValue *V = dynamic_cast(sender); + VERIFY(V); + Fvector val; + val.set(rad2deg(V->value->x), rad2deg(V->value->y), rad2deg(V->value->z)); + draw_sprintf(draw_val, val, V->dec); +} +bool CPropHelper::FvectorRDOnAfterEdit(PropValue *sender, Fvector &edit_val) +{ + edit_val.set(deg2rad(edit_val.x), deg2rad(edit_val.y), deg2rad(edit_val.z)); + VectorValue *V = dynamic_cast(sender); + R_ASSERT(V); + V->lim_mn.set(deg2rad(V->lim_mn.x), deg2rad(V->lim_mn.y), deg2rad(V->lim_mn.z)); + V->lim_mx.set(deg2rad(V->lim_mx.x), deg2rad(V->lim_mx.y), deg2rad(V->lim_mx.z)); + return true; +} +//------------------------------------------------------------------------------ + +void CPropHelper::floatRDOnBeforeEdit(PropValue *sender, float &edit_val) +{ + edit_val = rad2deg(edit_val); + FloatValue *V = dynamic_cast(sender); + R_ASSERT(V); + V->lim_mn = rad2deg(V->lim_mn); + V->lim_mx = rad2deg(V->lim_mx); +} +void CPropHelper::floatRDOnDraw(PropValue *sender, xr_string &draw_val) +{ + FloatValue *V = dynamic_cast(sender); + VERIFY(V); + float val; + val = rad2deg(*V->value); + draw_sprintf(draw_val, val, V->dec); +} +bool CPropHelper::floatRDOnAfterEdit(PropValue *sender, float &edit_val) +{ + edit_val = deg2rad(edit_val); + FloatValue *V = dynamic_cast(sender); + R_ASSERT(V); + V->lim_mn = deg2rad(V->lim_mn); + V->lim_mx = deg2rad(V->lim_mx); + return true; +} +//------------------------------------------------------------------------------ + +void CPropHelper::NameBeforeEdit(PropValue *sender, shared_str &edit_val) +{ + int cnt = _GetItemCount(edit_val.c_str(), '\\'); + edit_val = _SetPos(edit_val.c_str(), cnt - 1, '\\'); +} +void CPropHelper::NameDraw(PropValue *sender, xr_string &draw_val) +{ + RTextValue *V = dynamic_cast(sender); + VERIFY(V); + int cnt = _GetItemCount(V->value->c_str(), '\\'); + draw_val = _SetPos(V->value->c_str(), cnt - 1, '\\'); +} +bool CPropHelper::NameAfterEdit(PropValue *sender, shared_str &edit_val) +{ + RTextValue *V = dynamic_cast(sender); + VERIFY(V); + ListItem *L = (ListItem *)sender->tag; + return LHelper().NameAfterEdit(L, V->GetValue().c_str(), edit_val); +} +void CPropHelper::CNameDraw(PropValue *sender, xr_string &draw_val) +{ + CTextValue *V = dynamic_cast(sender); + VERIFY(V); + int cnt = _GetItemCount(V->value, '\\'); + draw_val = _SetPos(V->value, cnt - 1, '\\'); +} +void CPropHelper::CNameBeforeEdit(PropValue *sender, xr_string &edit_val) +{ + int cnt = _GetItemCount(edit_val.c_str(), '\\'); + edit_val = _SetPos(edit_val.c_str(), cnt - 1, '\\'); +} +bool CPropHelper::CNameAfterEdit(PropValue *sender, xr_string &edit_val) +{ + CTextValue *V = dynamic_cast(sender); + VERIFY(V); + ListItem *L = (ListItem *)sender->tag; + shared_str tmp = edit_val.c_str(); + bool accepted = LHelper().NameAfterEdit(L, V->GetValue(), tmp); + edit_val = tmp.c_str(); + return accepted; +} +//--------------------------------------------------------------------------- diff --git a/src/editors/xrEProps/PropertiesListTypes.cpp b/src/editors/xrEProps/PropertiesListTypes.cpp new file mode 100644 index 00000000000..25921d7ca08 --- /dev/null +++ b/src/editors/xrEProps/PropertiesListTypes.cpp @@ -0,0 +1,191 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "../../xrServerEntities/PropertiesListTypes.h" +//------------------------------------------------------------------------------ + +xr_string ShortcutValue::GetDrawText(TOnDrawTextEvent) +{ + xr_string txt; // = ToStr(MxShortCutToText(value->hotkey)).c_str(); + if (value->key == 0) + { + txt.append("none"); + return txt; + } + if (value->ext.test(xr_shortcut::flCtrl)) + { + txt.append("Ctrl+"); + } + if (value->ext.test(xr_shortcut::flShift)) + { + txt.append("Shift+"); + } + if (value->ext.test(xr_shortcut::flAlt)) + { + txt.append("Alt+"); + } + if (value->key >= 'A' && value->key <= 'Z') + { + txt.append(1, (char)value->key); + } + else if (value->key >= '0' && value->key <= '9') + { + txt.append(1, (char)value->key); + } + else + { + switch (value->key) + { + case VK_ADD: + txt.append("Numpad+"); + break; + case VK_SUBTRACT: + txt.append("Numpad-"); + break; + case VK_MULTIPLY: + txt.append("Numpad*"); + break; + case VK_DIVIDE: + txt.append("Numpad/"); + break; + case VK_OEM_PLUS: + txt.append("+"); + break; + case VK_OEM_MINUS: + txt.append("-"); + break; + case VK_OEM_1: + txt.append(";:"); + break; + case VK_OEM_COMMA: + txt.append(","); + break; + case VK_OEM_PERIOD: + txt.append("."); + break; + case VK_OEM_2: + txt.append("/?"); + break; + case VK_OEM_4: + txt.append("{["); + break; + case VK_OEM_5: + txt.append("\\|"); + break; + case VK_OEM_6: + txt.append("]}"); + break; + case VK_OEM_7: + txt.append("\"\'"); + break; + case VK_SPACE: + txt.append("Space"); + break; + case VK_CANCEL: + txt.append("Scroll Lock"); + break; + case VK_RETURN: + txt.append("Enter"); + break; + //////////////////////////// + case VK_LEFT: + txt.append("Left"); + break; + case VK_RIGHT: + txt.append("Right"); + break; + case VK_UP: + txt.append("Up"); + break; + case VK_DOWN: + txt.append("Down"); + break; + case VK_NUMPAD0: + txt.append("Numpad0"); + break; + case VK_NUMPAD1: + txt.append("Numpad1"); + break; + case VK_NUMPAD2: + txt.append("Numpad2"); + break; + case VK_NUMPAD3: + txt.append("Numpad3"); + break; + case VK_NUMPAD4: + txt.append("Numpad4"); + break; + case VK_NUMPAD5: + txt.append("Numpad5"); + break; + case VK_NUMPAD6: + txt.append("Numpad6"); + break; + case VK_NUMPAD7: + txt.append("Numpad7"); + break; + case VK_NUMPAD8: + txt.append("Numpad8"); + break; + case VK_NUMPAD9: + txt.append("Numpad9"); + break; + case VK_F1: + txt.append("F1"); + break; + case VK_F2: + txt.append("F2"); + break; + case VK_F3: + txt.append("F3"); + break; + case VK_F4: + txt.append("F4"); + break; + case VK_F5: + txt.append("F5"); + break; + case VK_F6: + txt.append("F6"); + break; + case VK_F7: + txt.append("F7"); + break; + case VK_F8: + txt.append("F8"); + break; + case VK_F9: + txt.append("F9"); + break; + case VK_F10: + txt.append("F10"); + break; + case VK_F11: + txt.append("F11"); + break; + case VK_F12: + txt.append("F12"); + break; + case VK_DELETE: + txt.append("Delete"); + break; + + default: + VERIFY(0); + break; + } + } + return txt; +} + +xr_string GameTypeValue::GetDrawText(TOnDrawTextEvent) +{ + string512 str; + xr_sprintf(str, sizeof(str), "%s%s%s%s%s", + GetValue().MatchType(eGameIDSingle) ? "Single " : "", + GetValue().MatchType(eGameIDDeathmatch) ? "DM " : "", + GetValue().MatchType(eGameIDTeamDeathmatch) ? "TDM " : "", + GetValue().MatchType(eGameIDArtefactHunt) ? "AH " : "", + GetValue().MatchType(eGameIDCaptureTheArtefact) ? "CTA" : ""); + return xr_string(str); +} diff --git a/src/editors/xrEProps/Tree/Base/UITreeItem.cpp b/src/editors/xrEProps/Tree/Base/UITreeItem.cpp new file mode 100644 index 00000000000..39b749bc774 --- /dev/null +++ b/src/editors/xrEProps/Tree/Base/UITreeItem.cpp @@ -0,0 +1,77 @@ +#include "stdafx.h" + +UITreeItem::UITreeItem(shared_str NewName):Name(NewName) +{ + Owner = nullptr; +} + +UITreeItem::~UITreeItem() +{ + for (UITreeItem* Item : Items) + xr_delete(Item); +} + +UITreeItem* UITreeItem::AppendItem(const char* Path, char PathChar ) +{ + VERIFY(Path && *Path); + + if (PathChar&&strchr(Path, PathChar)) + { + string_path Name; + xr_strcpy(Name, Path); + strchr(Name, PathChar)[0] = 0; + UITreeItem* Item = FindItem(Name); + + if (!Item) + { + Items.push_back(CreateItem(Name)); + Item = Items.back(); + Item->Owner = this; + } + + return Item->AppendItem(strchr(Path, PathChar) + 1); + } + else + { + UITreeItem* Item = FindItem(Path); + + if (!Item) + { + Items.push_back(CreateItem(Path)); + Item = Items.back(); + Item->Owner = this; + } + + return Item; + } +} + +UITreeItem* UITreeItem::FindItem(const char* Path, char PathChar ) +{ + if (PathChar&&strchr(Path, PathChar)) + { + string_path Name; + xr_strcpy(Name, Path); + strchr(Name, PathChar)[0] = 0; + + if (UITreeItem* Item = FindItem(Name)) + return Item->FindItem(strchr(Path, PathChar) + 1); + } + else + { + shared_str FName = Path; + + for (UITreeItem* Item : Items) + { + if (Item->Name == FName) + return Item; + } + } + + return nullptr; +} + +UITreeItem* UITreeItem::CreateItem(shared_str Name) +{ + return xr_new(Name); +} diff --git a/src/editors/xrEProps/Tree/Base/UITreeItem.h b/src/editors/xrEProps/Tree/Base/UITreeItem.h new file mode 100644 index 00000000000..ce58e4ab893 --- /dev/null +++ b/src/editors/xrEProps/Tree/Base/UITreeItem.h @@ -0,0 +1,16 @@ +#pragma once + +class XREPROPS_API UITreeItem +{ +public: + UITreeItem(shared_str Name); + virtual ~UITreeItem(); + + UITreeItem* AppendItem(const char* Path,char PathChar = '\\'); + UITreeItem* FindItem(const char* Path, char PathChar = '\\'); + xr_vector Items; + UITreeItem* Owner; + shared_str Name; +protected: + virtual UITreeItem* CreateItem(shared_str Name); +}; diff --git a/src/editors/xrEProps/Tree/Choose/UIChooseForm.cpp b/src/editors/xrEProps/Tree/Choose/UIChooseForm.cpp new file mode 100644 index 00000000000..1c8db67ccbd --- /dev/null +++ b/src/editors/xrEProps/Tree/Choose/UIChooseForm.cpp @@ -0,0 +1,487 @@ +#include "stdafx.h" + +UIChooseForm::EventsMap UIChooseForm::m_Events; +UIChooseForm *UIChooseForm::Form = 0; + +ImTextureID UIChooseForm::NullTexture = nullptr; + +void UIChooseForm::UpdateSelected(UIChooseFormItem *NewSelected) +{ + m_SelectedItem = NewSelected; + + if (!m_SelectedItem) + return; + + PropItemVec Vec; + + if (E.on_sel) + { + E.on_sel(m_SelectedItem->Object, Vec); + m_Props->AssignItems(Vec); + } + + if (E.flags.test(SChooseEvents::flClearTexture)) + { + if (m_Texture) + m_Texture->Release(); + + m_Texture = 0; + } + + if (!E.on_get_texture.empty()) + E.on_get_texture(m_SelectedItem->Object->name.c_str(), m_Texture); +} + +void UIChooseForm::FillItems(u32 choose_id) +{ + m_SelectedItems.clear(); + m_RootItem = UIChooseFormItem(""); + m_RootItem.Form = this; + + m_ChooseID = choose_id; + int Index = 0; + + for (auto &i : m_Items) + { + xr_string Name = i.name.c_str(); + xr_string RealName; + + if (strrchr(i.name.c_str(), '\\')) + RealName = strrchr(i.name.c_str(), '\\') + 1; + else + RealName = i.name.c_str(); + + UIChooseFormItem *Item = static_cast(m_RootItem.AppendItem(Name.c_str())); + Item->Object = &i; + Item->Text = RealName.c_str(); + Item->Index = Index++; + } + + if (m_Flags.is(cfAllowNone) && !m_Flags.is(cfMultiSelect)) + { + m_ItemNone.name = NONE_CAPTION; + xr_string Name = m_ItemNone.name.c_str(); + UIChooseFormItem *Item = static_cast(m_RootItem.AppendItem(Name.c_str())); + Item->Object = &m_ItemNone; + Item->Text = NONE_CAPTION; + Item->Index = Index++; + } + + m_RootItem.Sort(); +} + +void UIChooseForm::CheckFavorite() +{ + m_RootItem.CheckFavorited(); + m_SelectedItems.clear(); + m_RootItem.FillFavorited(m_SelectedItems); +} + +UIChooseForm::UIChooseForm() : m_Texture(nullptr), m_SelectedItem(nullptr), m_RootItem(""), m_SelectedList(-1) +{ + m_Props = xr_new(); +} + +UIChooseForm::~UIChooseForm() +{ + if (m_Texture) + m_Texture->Release(); + + if (!E.on_close.empty()) + E.on_close(); + + xr_delete(m_Props); +} + +void UIChooseForm::Draw() +{ + if (m_SelectedItem && E.flags.test(SChooseEvents::flAnimated)) + { + if (!E.on_get_texture.empty()) + E.on_get_texture(m_SelectedItem->Object->name.c_str(), m_Texture); + } + + ImGui::Columns(2); + { + { + ImGui::Text("Find:"); + ImGui::SameLine(); + m_Filter.Draw("##Find", -1); + + if (ImGui::BeginChild("Left", ImVec2(0, 0), false)) + { + static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersH | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollX | ImGuiTableFlags_SizingFixedFit; + + if (ImGui::BeginTable("objects", 1, flags)) + { + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableHeadersRow(); + + m_RootItem.DrawRoot(); + ImGui::EndTable(); + } + } + + ImGui::EndChild(); + } + + ImGui::NextColumn(); + + { + ImGui::BeginChild("Right", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), false); + { + if (NullTexture || m_Texture) + { + if (m_Texture) + ImGui::Image(m_Texture, ImVec2(192, 192)); + else + ImGui::Image(NullTexture, ImVec2(192, 192)); + } + else + ImGui::InvisibleButton("Image", ImVec2(192, 192)); + + // ImGui::Image + ImGui::Separator(); + + if (!m_SelectedItem) + { + ImGui::Text("Name:"); + ImGui::Text("Hit:"); + } + else + { + ImGui::Text("Name:%s", m_SelectedItem->Object->name.c_str()); + ImGui::Text("Hit:%s", m_SelectedItem->Object->hint.c_str()); + } + + ImGui::Separator(); + } + + if (!E.on_sel.empty() && !m_Flags.is(cfMultiSelect)) + { + if (m_SelectedItem) + { + if (ImGui::BeginChild("Props", ImVec2(0, 0))) + m_Props->Draw(); + + ImGui::EndChild(); + } + } + + else if (m_Flags.is(cfMultiSelect)) + { + if (ImGui::Button("Up")) + { + if (m_SelectedList > 0) + { + std::swap(m_SelectedItems[m_SelectedList - 1], m_SelectedItems[m_SelectedList]); + m_SelectedList = -(m_SelectedList - 1) - 2; + } + } + + ImGui::SameLine(); + + if (ImGui::Button("Down")) + { + if (m_SelectedItems.size() > 1 && m_SelectedList < m_SelectedItems.size() - 1) + { + std::swap(m_SelectedItems[m_SelectedList], m_SelectedItems[m_SelectedList + 1]); + m_SelectedList = -(m_SelectedList + 1) - 2; + } + } + + ImGui::SameLine(); + + if (ImGui::Button("Del")) + { + if (m_SelectedItems.size() && m_SelectedList >= 0) + { + m_SelectedItems.erase(m_SelectedItems.begin() + m_SelectedList); + m_SelectedList = -1; + } + + m_RootItem.CheckFavorited(m_SelectedItems); + CheckFavorite(); + } + + ImGui::SameLine(); + + if (ImGui::Button("Clear List")) + { + m_SelectedItems.clear(); + m_RootItem.CheckFavorited(m_SelectedItems); + CheckFavorite(); + m_SelectedList = -1; /* if (E.flags.test(SChooseEvents::flClearTexture) ){ if (m_Texture)m_Texture->Release(); m_Texture = 0; } */ + ImGui::SameLine(); + } + + if (ImGui::BeginChild("List", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_AlwaysVerticalScrollbar)) + { + int i = 0; + + int HereY = -m_SelectedList - 2; + + if (HereY >= 0) + m_SelectedList = HereY; + + for (auto &item : m_SelectedItems) + { + if (HereY == i) + ImGui::SetScrollHereY(); + + if (ImGui::Selectable(item->name.c_str(), m_SelectedList == i)) + m_SelectedList = i; + + i++; + } + } + + ImGui::EndChild(); + } + + ImGui::EndChild(); + + ImGui::BeginDisabled(!m_Flags.is(cfMultiSelect) && !GetSelectedItem()); + + if (ImGui::Button("Ok", ImVec2(100, 0))) + { + if (!m_Flags.is(cfMultiSelect)) + { + VERIFY(m_SelectedItems.size() == 0); + m_SelectedItems.push_back(GetSelectedItem()); + } + + m_Result = R_Ok; + bOpen = false; + } + + ImGui::EndDisabled(); + ImGui::SameLine(0); + + if (ImGui::Button("Cancel", ImVec2(100, 0))) + { + m_Result = R_Cancel; + bOpen = false; + } + } + } +} + +void UIChooseForm::SetNullTexture(ImTextureID Texture) +{ + NullTexture = Texture; +} + +void UIChooseForm::Update() +{ + if (Form && !Form->IsClosed()) + { + ImGui::SetNextWindowSize(ImVec2(400, 500), ImGuiCond_::ImGuiCond_FirstUseEver); + + if (ImGui::BeginPopupModal("ChooseForm", nullptr, 0, true)) + { + Form->Draw(); + ImGui::EndPopup(); + } + } +} + +bool UIChooseForm::IsActive() +{ + return Form; +} + +bool UIChooseForm::GetResult(bool &change, shared_str &result) +{ + if (!Form) + return false; + + if (!Form->bOpen) + { + if (Form->m_Result == R_Ok) + { + if (!Form->m_Flags.test(cfMultiSelect)) + VERIFY(Form->GetSelectedItem()); + + xr_string resultTemp; + int i = 0; + + for (auto &item : Form->m_SelectedItems) + { + if (i != 0) + resultTemp.append(","); + + resultTemp.append(item->name.c_str()); + i++; + } + + result = resultTemp.c_str(); + change = true; + xr_delete(Form); + return true; + } + + change = false; + xr_delete(Form); + return true; + } + + return false; +} + +SChooseItem *UIChooseForm::GetSelectedItem() +{ + if (m_Flags.test(cfMultiSelect)) + { + if (m_SelectedItems.size()) + return m_SelectedItems.back(); + + return nullptr; + } + + if (m_SelectedItem) + return m_SelectedItem->Object; + + return nullptr; +} + +bool UIChooseForm::GetResult(bool& change, xr_string& result) +{ + if (Form->bOpen) + return false; + + if (Form->m_Result == R_Ok) + { + int i = 0; + + for (auto& item : Form->m_SelectedItems) + { + if (i != 0) + result.append(","); + + result.append(item->name.c_str()); + i++; + } + + change = true; + xr_delete(Form); + return true; + } + + change = false; + xr_delete(Form); + return true; +} + +bool UIChooseForm::GetResult(bool& change, xr_vector& result) +{ + if (Form->bOpen) + return false; + + if (Form->m_Result == R_Ok) + { + int i = 0; + + for (auto& item : Form->m_SelectedItems) + { + result.push_back(item->name.c_str()); + i++; + } + + change = true; + xr_delete(Form); + return true; + } + + change = false; + xr_delete(Form); + return true; +} + +void UIChooseForm::SelectItem(u32 choose_ID, int sel_cnt, LPCSTR init_name, TOnChooseFillItems item_fill, void *fill_param, TOnChooseSelectItem item_select, ChooseItemVec *items, u32 mask) +{ + VERIFY(!Form); + + Form = xr_new(); + Form->m_Flags.assign(mask); + Form->m_Flags.set(cfMultiSelect, sel_cnt > 1); + + // fill items + if (items) + { + VERIFY2(item_fill.empty(), "ChooseForm: Duplicate source."); + Form->m_Items = *items; + Form->E.Set("Select Item", 0, item_select, 0, 0, 0); + } + else if (!item_fill.empty()) + { + // custom + Form->E.Set("Select Item", item_fill, item_select, 0, 0, 0); + } + else + { + SChooseEvents *e = GetEvents(choose_ID); + VERIFY2(e, "Can't find choose event."); + Form->E = *e; + } + + // set & fill + Form->m_Title = Form->E.caption.c_str(); + + if (!Form->E.on_fill.empty()) + Form->E.on_fill(Form->m_Items, fill_param); + + Form->FillItems(choose_ID); + + if (sel_cnt > 1) + { + int cnt = _GetItemCount(init_name); + xr_string result; + + for (int i = 0; i < cnt; i++) + { + _GetItem(init_name, i, result); + + if (auto *Item = Form->m_RootItem.FindItem(result.c_str())) + ((UIChooseFormItem*)Item)->bSelected = true; + } + + Form->m_RootItem.SelectedToFavorite(true); + Form->CheckFavorite(); + } + else + { + if (sel_cnt <= 1 && init_name && init_name[0]) + { + if (auto Item = Form->m_RootItem.FindItem(init_name)) + { + ((UIChooseFormItem*)Item)->bSelected = true; + Form->UpdateSelected((UIChooseFormItem*)Item); + Form->m_RootItem.OpenParentItems(init_name); + } + } + } +} + +void UIChooseForm::AppendEvents(u32 choose_ID, LPCSTR caption, TOnChooseFillItems on_fill, TOnChooseSelectItem on_sel, TGetTexture on_thm, TOnChooseClose on_close, u32 flags) +{ + EventsMapIt it = m_Events.find(choose_ID); + VERIFY(it == m_Events.end()); + m_Events.insert(std::make_pair(choose_ID, SChooseEvents(caption, on_fill, on_sel, on_thm, on_close, flags))); +} + +void UIChooseForm::ClearEvents() +{ + NullTexture->Release(); + m_Events.clear(); +} + +SChooseEvents *UIChooseForm::GetEvents(u32 choose_ID) +{ + EventsMapIt it = m_Events.find(choose_ID); + + if (it != m_Events.end()) + return &it->second; + else + return nullptr; +} diff --git a/src/editors/xrEProps/Tree/Choose/UIChooseForm.h b/src/editors/xrEProps/Tree/Choose/UIChooseForm.h new file mode 100644 index 00000000000..64966cf2926 --- /dev/null +++ b/src/editors/xrEProps/Tree/Choose/UIChooseForm.h @@ -0,0 +1,57 @@ +#pragma once + +class XREPROPS_API UIChooseForm : public xrUI +{ + friend class UIChooseFormItem; + + void UpdateSelected(UIChooseFormItem* NewSelected); + UIChooseFormItem m_RootItem; + + ImTextureID m_Texture; + ImGuiTextFilter m_Filter; + UIPropertiesForm* m_Props; + Flags32 m_Flags; + xr_string m_Title; + xr_vectorm_SelectedItems; + s32 m_SelectedList; + SChooseItem* GetSelectedItem(); + UIChooseFormItem* m_SelectedItem; + SChooseItem m_ItemNone; + ChooseItemVec m_Items; + u32 m_ChooseID; + void FillItems(u32 choose_id); + void CheckFavorite(); + +protected: + DEFINE_MAP(u32, SChooseEvents, EventsMap, EventsMapIt); + static EventsMap m_Events; +private: + SChooseEvents E; + static UIChooseForm *Form; + static ImTextureID NullTexture; + +public: + enum Result + { + R_Ok, + R_Cancel + }; + +private: + Result m_Result; + +public: + UIChooseForm(); + virtual ~UIChooseForm(); + virtual void Draw(); + static void SetNullTexture(ImTextureID Texture); + static void Update(); + static bool IsActive(); + static bool GetResult(bool &change, shared_str &result); + static bool GetResult(bool &change, xr_string &result); + static bool GetResult(bool &change, xr_vector &result); + static void SelectItem(u32 choose_ID, int sel_cnt = 1, LPCSTR init_name = 0, TOnChooseFillItems item_fill = 0, void *fill_param = 0, TOnChooseSelectItem item_select = 0, ChooseItemVec *items = 0, u32 flags = cfAllowNone); + static void AppendEvents(u32 choose_ID, LPCSTR caption, TOnChooseFillItems on_fill, TOnChooseSelectItem on_sel, TGetTexture on_thm, TOnChooseClose on_close, u32 flags); + static void ClearEvents(); + static SChooseEvents *GetEvents(u32 choose_ID); +}; diff --git a/src/editors/xrEProps/Tree/Choose/UIChooseFormItem.cpp b/src/editors/xrEProps/Tree/Choose/UIChooseFormItem.cpp new file mode 100644 index 00000000000..7ad7e4a5be9 --- /dev/null +++ b/src/editors/xrEProps/Tree/Choose/UIChooseFormItem.cpp @@ -0,0 +1,293 @@ +#include "stdafx.h" + +UIChooseFormItem::UIChooseFormItem(shared_str Name) : Object(nullptr), UITreeItem(Name) +{ + bIsFavorite = false; + m_bIsMixed = false; + bSelected = false; + Index = -1; + m_bOpenByDefault = false; +} + +void UIChooseFormItem::Draw() +{ + if (!CheckFilter()) + return; + + ImGui::PushID(this); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + + if (Object) + { + ImGuiTreeNodeFlags Flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; + + if (Form->m_SelectedItem == this || bSelected) + Flags |= ImGuiTreeNodeFlags_Selected; + + if (Form->m_Flags.test(cfMultiSelect)) + { + if (ImGui::Checkbox("##checkbox", &bIsFavorite)) + { + if (bSelected) + { + Form->m_RootItem.SelectedToFavorite(bIsFavorite); + } + else + { + Form->m_RootItem.ClearSelection(); + Form->m_SelectedItem = this; + bSelected = true; + } + Form->CheckFavorite(); + } + + ImGui::SameLine(0, 0); + } + + ImGui::TreeNodeEx(Text.c_str(), Flags); + + if (ImGui::IsItemClicked()) + { + if (Form->m_Flags.test(cfMultiSelect)) + { + if (ImGui::GetIO().KeyShift) + { + if (Form->m_SelectedItem) + { + Form->m_RootItem.Selected(Index, Form->m_SelectedItem->Index); + } + bSelected = true; + } + else if (ImGui::GetIO().KeyCtrl) + { + bSelected = true; + Form->UpdateSelected(this); + } + else + { + Form->m_RootItem.ClearSelection(); + Form->m_SelectedItem = this; + bSelected = true; + Form->UpdateSelected(this); + } + } + else + { + Form->m_RootItem.ClearSelection(); + Form->m_SelectedItem = this; + bSelected = true; + Form->UpdateSelected(this); + } + } + } + else + { + ImGuiTreeNodeFlags Flags = ImGuiTreeNodeFlags_OpenOnArrow; + + if (m_bOpenByDefault) + Flags |= ImGuiTreeNodeFlags_DefaultOpen; + + if (Form->m_Flags.test(cfMultiSelect)) + { + ImGui::PushItemFlag(ImGuiItemFlags_MixedValue, m_bIsMixed); + bool CheckChange = ImGui::Checkbox("##checkbox", &bIsFavorite); + ImGui::PopItemFlag(); + + if (CheckChange) + { + Form->m_RootItem.ClearSelection(); + Form->m_SelectedItem = nullptr; + bSelected = false; + SetFavorite(bIsFavorite); + Form->CheckFavorite(); + } + + ImGui::SameLine(0, 0); + } + + if (ImGui::TreeNodeEx(Name.c_str(), Flags)) + { + for (UITreeItem *Item : Items) + ((UIChooseFormItem *)Item)->Draw(); + + ImGui::TreePop(); + } + } + + ImGui::PopID(); +} + +void UIChooseFormItem::DrawRoot() +{ + for (UITreeItem *Item : Items) + ((UIChooseFormItem *)Item)->Draw(); +} + +void UIChooseFormItem::Sort() +{ + for (UITreeItem *Item : Items) + { + std::sort(Items.begin(), Items.end(), [](UITreeItem *Right, UITreeItem *Left) -> bool + { + UIChooseFormItem* pRight = ((UIChooseFormItem*)Right); + UIChooseFormItem* pLeft = ((UIChooseFormItem*)Left); + + if(pRight->Object&& !pLeft->Object) + return false; + + if (!pRight->Object && pLeft->Object) + return true; + + return xr_strcmp(pRight->Name.c_str(), pLeft->Name.c_str()) < 0; }); + } + + for (UITreeItem *Item : Items) + ((UIChooseFormItem *)Item)->Sort(); +} + +void UIChooseFormItem::CheckFavorited() +{ + if (Items.size() == 0) + return; + + if (!Form->m_Flags.test(cfMultiSelect)) + return; + + m_bIsMixed = false; + bool bIsLastFavorited = ((UIChooseFormItem *)Items.front())->bIsFavorite; + + for (UITreeItem *Item : Items) + { + ((UIChooseFormItem *)Item)->CheckFavorited(); + m_bIsMixed |= ((UIChooseFormItem *)Item)->m_bIsMixed; + + if (bIsLastFavorited != ((UIChooseFormItem *)Item)->bIsFavorite) + { + bIsLastFavorited = false; + m_bIsMixed = true; + } + } + + bIsFavorite = bIsLastFavorited; +} + +void UIChooseFormItem::SetFavorite(bool bFavorited) +{ + if (!Form->m_Flags.test(cfMultiSelect)) + return; + + bIsFavorite = bFavorited; + m_bIsMixed = false; + + for (UITreeItem *Item : Items) + ((UIChooseFormItem *)Item)->SetFavorite(bFavorited); +} + +void UIChooseFormItem::FillFavorited(xr_vector &Favorited) +{ + if (!Form->m_Flags.test(cfMultiSelect)) + return; + + if (Object && bIsFavorite) + Favorited.push_back(Object); + + for (UITreeItem *Item : Items) + ((UIChooseFormItem *)Item)->FillFavorited(Favorited); +} + +void UIChooseFormItem::CheckFavorited(xr_vector &Favorited) +{ + if (!Form->m_Flags.test(cfMultiSelect)) + return; + + if (Object) + bIsFavorite = std::find_if(Favorited.begin(), Favorited.end(), [&](SChooseItem *I) + { return Object == I; }) != Favorited.end(); + + for (UITreeItem *Item : Items) + ((UIChooseFormItem *)Item)->CheckFavorited(Favorited); +} + +void UIChooseFormItem::ClearSelection() +{ + bSelected = false; + + for (UITreeItem *Item : Items) + ((UIChooseFormItem *)Item)->ClearSelection(); +} + +void UIChooseFormItem::Selected(int Start, int End) +{ + for (UITreeItem *Item : Items) + ((UIChooseFormItem *)Item)->Selected(Start, End); + + if (!Object) + return; + + if (!CheckFilter()) + return; + + if (Start > End) + std::swap(Start, End); + + bSelected = Index >= Start && Index <= End; +} + +void UIChooseFormItem::SelectedToFavorite(bool Favorite) +{ + if (!Form->m_Flags.test(cfMultiSelect)) + return; + + for (UITreeItem *Item : Items) + ((UIChooseFormItem *)Item)->SelectedToFavorite(Favorite); + + if (bSelected) + SetFavorite(Favorite); +} + +bool UIChooseFormItem::CheckFilter() +{ + if (!Form->m_Filter.InputBuf[0]) + return true; + + if (Object) + { + if (Form->m_Filter.PassFilter(Object->name.c_str())) + return true; + } + else + { + bool bTest = false; + + for (UITreeItem *Item : Items) + bTest |= ((UIChooseFormItem *)Item)->CheckFilter(); + + return bTest; + } + + return false; +} + +UITreeItem *UIChooseFormItem::CreateItem(shared_str Name) +{ + auto Item = xr_new(Name); + Item->Form = Form; + return Item; +} + +void UIChooseFormItem::OpenParentItems(const char* path, char delimiter) +{ + if (!delimiter || !strchr(path, delimiter)) // not a folder + return; + + string_path itemName; + xr_strcpy(itemName, path); + strchr(itemName, delimiter)[0] = '\0'; + + if (UIChooseFormItem* Item = dynamic_cast(FindItem(itemName))) + { + Item->m_bOpenByDefault = true; + Item->OpenParentItems(strchr(path, delimiter) + 1); + } +} diff --git a/src/editors/xrEProps/Tree/Choose/UIChooseFormItem.h b/src/editors/xrEProps/Tree/Choose/UIChooseFormItem.h new file mode 100644 index 00000000000..22b8b6f0338 --- /dev/null +++ b/src/editors/xrEProps/Tree/Choose/UIChooseFormItem.h @@ -0,0 +1,33 @@ +#pragma once + +class UIChooseFormItem :public UITreeItem +{ +public: + UIChooseFormItem(shared_str Name); + virtual ~UIChooseFormItem() = default; + + bool bIsFavorite; + + class UIChooseForm* Form; + int Index; + SChooseItem* Object; + shared_str Text; + bool bSelected; + bool m_bOpenByDefault; + void Draw(); + void DrawRoot(); + void Sort(); + void CheckFavorited(); + void SetFavorite(bool bFavorite); + void FillFavorited(xr_vector< SChooseItem*>& selected); + void CheckFavorited(xr_vector< SChooseItem*>& selected); + void ClearSelection(); + void Selected(int Start, int End); + void SelectedToFavorite(bool Favorite); + void OpenParentItems(const char* path, char delimiter = '\\'); + +protected: + bool CheckFilter(); + virtual UITreeItem* CreateItem(shared_str Name); + bool m_bIsMixed; +}; diff --git a/src/editors/xrEProps/Tree/Properties/UIPropertiesForm.cpp b/src/editors/xrEProps/Tree/Properties/UIPropertiesForm.cpp new file mode 100644 index 00000000000..53b7903e70e --- /dev/null +++ b/src/editors/xrEProps/Tree/Properties/UIPropertiesForm.cpp @@ -0,0 +1,403 @@ +#include "stdafx.h" + +UIPropertiesForm::UIPropertiesForm() : m_Root("", this) +{ + m_bModified = false; + m_EditChooseValue = nullptr; + m_EditShortcutValue = nullptr; + m_EditTextureValue = nullptr; + m_EditTextValueData = nullptr; + m_EditTextValueInitial = nullptr; + m_Flags.zero(); +} + +UIPropertiesForm::~UIPropertiesForm() +{ + if (m_EditTextValueData) + xr_delete(m_EditTextValueData); + ClearProperties(); +} + +void UIPropertiesForm::Draw() +{ + { + if (m_EditChooseValue) + { + shared_str result; + bool is_result; + if (UIChooseForm::GetResult(is_result, result)) + { + if (is_result) + { + if (m_EditChooseValue->AfterEdit(result)) + if (m_EditChooseValue->ApplyValue(result)) + { + Modified(); + } + } + m_EditChooseValue = nullptr; + } + + UIChooseForm::Update(); + } + if (m_EditTextureValue) + { + shared_str result; + bool is_result; + if (UIChooseForm::GetResult(is_result, result)) + { + if (is_result) + { + if (result.c_str() == nullptr) + { + xr_string result_as_str = "$null"; + if (m_EditTextureValue->AfterEdit(result_as_str)) + if (m_EditTextureValue->ApplyValue(result_as_str.c_str())) + { + Modified(); + } + } + else + { + xr_string result_as_str = result.c_str(); + if (m_EditTextureValue->AfterEdit(result_as_str)) + if (m_EditTextureValue->ApplyValue(result_as_str.c_str())) + { + Modified(); + } + } + } + m_EditTextureValue = nullptr; + } + UIChooseForm::Update(); + } + if (m_EditShortcutValue) + { + xr_shortcut result; + bool ok; + if (UIKeyPressForm::GetResult(ok, result)) + { + if (ok) + { + if (m_EditShortcutValue->AfterEdit(result)) + if (m_EditShortcutValue->ApplyValue(result)) + { + Modified(); + } + } + m_EditShortcutValue = nullptr; + } + } + } + + static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody; + const float TEXT_BASE_WIDTH = ImGui::CalcTextSize("A").x; + + if (ImGui::BeginTable("3ways", 2, flags)) + { + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide); + ImGui::TableSetupColumn("Prop", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 6.0f); + ImGui::TableHeadersRow(); + m_Root.DrawRoot(); + ImGui::EndTable(); + } +} + +void UIPropertiesForm::AssignItems(PropItemVec &items) +{ + m_Items = items; + + for (PropItem *item : items) + { + item->m_Owner = this; + UIPropertiesItem* Item = static_cast(m_Root.AppendItem(item->Key())); + VERIFY(Item); + Item->PItem = item; + } +} + +PropItem *UIPropertiesForm::FindItemOfName(shared_str name) +{ + for (PropItem *I : m_Items) + { + const char *key = I->Key(); + if (strrchr(key, '\\')) + { + key = strrchr(key, '\\') + 1; + } + if (name == key) + { + return I; + } + } + return nullptr; +} + +void UIPropertiesForm::ClearProperties() +{ + VERIFY(!m_EditChooseValue); + + for (PropItem *I : m_Items) + xr_delete(I); + + m_Root = UIPropertiesItem("", this); + m_Items.clear(); +} + +PropItem *UIPropertiesForm::FindItem(const char *name) +{ + if (UIPropertiesItem* Item = static_cast(m_Root.FindItem(name))) + return Item->PItem; + + return nullptr; +} + +void UIPropertiesForm::DrawEditText() +{ + if (ImGui::BeginPopupContextItem("EditText", 0)) + { + R_ASSERT(m_EditTextValueData); + ImGui::BeginGroup(); + + if (ImGui::Button("Ok")) + { + auto OnOkSuccessful = [&]() + { + xr_delete(m_EditTextValueData); + xr_delete(m_EditTextValueInitial); + Modified(); + ImGui::CloseCurrentPopup(); + }; + + auto OnOkFailed = [&]() + { + if (!m_EditTextValueData || !m_EditTextValueInitial) + return; + + // TSMP: close window on ok when nothing changed + if (!xr_strcmp(m_EditTextValueData, m_EditTextValueInitial)) + OnOkSuccessful(); + }; + + if (dynamic_cast(m_EditTextValue->GetFrontValue())) + { + xr_string out = m_EditTextValueData; + + if (m_EditTextValue->AfterEdit(out)) + { + if (m_EditTextValue->ApplyValue(out.c_str())) + OnOkSuccessful(); + } + } + else if (dynamic_cast(m_EditTextValue->GetFrontValue())) + { + shared_str out = m_EditTextValueData; + + if (m_EditTextValue->AfterEdit(out)) + { + if (m_EditTextValue->ApplyValue(out)) + OnOkSuccessful(); + } + } + else if (dynamic_cast(m_EditTextValue->GetFrontValue())) + { + xr_string out = m_EditTextValueData; + + if (m_EditTextValue->AfterEdit(out)) + { + if (m_EditTextValue->ApplyValue(out)) + OnOkSuccessful(); + } + } + else + R_ASSERT(false); + + OnOkFailed(); + } + + ImGui::SameLine(0); + + if (ImGui::Button("Cancel")) + { + xr_delete(m_EditTextValueData); + xr_delete(m_EditTextValueInitial); + ImGui::CloseCurrentPopup(); + } + + ImGui::SameLine(0); + + if (ImGui::Button("Apply")) + { + auto OnApplySuccessful = [&]() + { + const char* newText = m_EditTextValueData; + xr_delete(m_EditTextValueInitial); + m_EditTextValueInitial = xr_strdup(newText ? newText : ""); + Modified(); + }; + + if (dynamic_cast(m_EditTextValue->GetFrontValue())) + { + xr_string out = m_EditTextValueData; + + if (m_EditTextValue->AfterEdit(out)) + { + if (m_EditTextValue->ApplyValue(out.c_str())) + OnApplySuccessful(); + } + } + else if (dynamic_cast(m_EditTextValue->GetFrontValue())) + { + shared_str out = m_EditTextValueData; + + if (m_EditTextValue->AfterEdit(out)) + { + if (m_EditTextValue->ApplyValue(out)) + OnApplySuccessful(); + } + } + else if (dynamic_cast(m_EditTextValue->GetFrontValue())) + { + xr_string out = m_EditTextValueData; + + if (m_EditTextValue->AfterEdit(out)) + { + if (m_EditTextValue->ApplyValue(out)) + OnApplySuccessful(); + } + } + else + R_ASSERT(false); + } + + ImGui::SameLine(150); + + if (ImGui::Button("Load")) + { + xr_string fn; + + if (EFS.GetOpenName(0, "$import$", fn, false, NULL, 2)) + { + xr_string buf; + IReader *F = FS.r_open(fn.c_str()); + F->r_stringZ(buf); + xr_delete(m_EditTextValueData); + m_EditTextValueData = xr_strdup(buf.c_str()); + m_EditTextValueDataSize = xr_strlen(m_EditTextValueData) + 1; + FS.r_close(F); + } + } + + ImGui::SameLine(0); + + if (ImGui::Button("Save")) + { + xr_string fn; + + if (EFS.GetSaveName("$import$", fn, NULL, 2)) + { + CMemoryWriter F; + F.w_stringZ(m_EditTextValueData); + + if (!F.save_to(fn.c_str())) + Log("!Can't save text file:", fn.c_str()); + } + } + + ImGui::SameLine(0); + + if (ImGui::Button("Clear")) + m_EditTextValueData[0] = '\0'; + + ImGui::EndGroup(); + + if (m_EditTextValueData) + { + ImGui::InputTextMultiline("##text", m_EditTextValueData, m_EditTextValueDataSize, ImVec2(500, 200), + ImGuiInputTextFlags_CallbackResize, [](ImGuiInputTextCallbackData* data) -> int + { + return reinterpret_cast(data->UserData)->DrawEditText_Callback(data); + }, this + ); + } + + ImGui::EndPopup(); + } +} + +int UIPropertiesForm::DrawEditText_Callback(ImGuiInputTextCallbackData *data) +{ + m_EditTextValueData = (char *)xr_realloc(m_EditTextValueData, data->BufSize); + m_EditTextValueDataSize = data->BufSize; + data->Buf = m_EditTextValueData; + return 0; +} + +void UIPropertiesForm::DrawEditGameType() +{ + if (ImGui::BeginPopupContextItem("EditGameType", 0)) + { + R_ASSERT(m_EditGameTypeValue); + + bool test = false; + { + ImGui::BeginGroup(); + { + bool cheked = m_EditGameTypeChooser.MatchType(eGameIDSingle); + if (ImGui::Checkbox("Single", &cheked)) + { + m_EditGameTypeChooser.m_GameType.set(eGameIDSingle, cheked); + } + } + { + bool cheked = m_EditGameTypeChooser.MatchType(eGameIDDeathmatch); + if (ImGui::Checkbox("DM", &cheked)) + { + m_EditGameTypeChooser.m_GameType.set(eGameIDDeathmatch, cheked); + } + } + { + bool cheked = m_EditGameTypeChooser.MatchType(eGameIDTeamDeathmatch); + if (ImGui::Checkbox("TDM", &cheked)) + { + m_EditGameTypeChooser.m_GameType.set(eGameIDTeamDeathmatch, cheked); + } + } + { + bool cheked = m_EditGameTypeChooser.MatchType(eGameIDArtefactHunt); + if (ImGui::Checkbox("ArtefactHunt", &cheked)) + { + m_EditGameTypeChooser.m_GameType.set(eGameIDArtefactHunt, cheked); + } + } + { + bool cheked = m_EditGameTypeChooser.MatchType(eGameIDCaptureTheArtefact); + if (ImGui::Checkbox("CTA", &cheked)) + { + m_EditGameTypeChooser.m_GameType.set(eGameIDCaptureTheArtefact, cheked); + } + } + ImGui::EndGroup(); + ImGui::SameLine(); + } + { + ImGui::BeginGroup(); + if (ImGui::Button("Ok", ImVec2(ImGui::GetFrameHeight() * 6, 0))) + { + if (m_EditGameTypeValue->AfterEdit(m_EditGameTypeChooser)) + if (m_EditGameTypeValue->ApplyValue(m_EditGameTypeChooser)) + { + Modified(); + } + ImGui::CloseCurrentPopup(); + } + if (ImGui::Button("Cancel", ImVec2(ImGui::GetFrameHeight() * 6, 0))) + { + m_EditGameTypeValue = nullptr; + ImGui::CloseCurrentPopup(); + } + ImGui::EndGroup(); + } + ImGui::EndPopup(); + } +} diff --git a/src/editors/xrEProps/Tree/Properties/UIPropertiesForm.h b/src/editors/xrEProps/Tree/Properties/UIPropertiesForm.h new file mode 100644 index 00000000000..0a6a6c98125 --- /dev/null +++ b/src/editors/xrEProps/Tree/Properties/UIPropertiesForm.h @@ -0,0 +1,63 @@ +#pragma once + +class XREPROPS_API UIPropertiesForm : public xrUI +{ + friend class UIPropertiesItem; + +public: + void SetModifiedEvent(TOnModifiedEvent modif = 0) { OnModifiedEvent = modif; } + + UIPropertiesForm(); + ~UIPropertiesForm() override; + + void Draw() override; + void AssignItems(PropItemVec &items); + PropItem *FindItem(const char *path); + PropItem *FindItemOfName(shared_str name); + void ClearProperties(); + void SetReadOnly(bool enable) { m_Flags.set(plReadOnly, enable); } + bool IsModified() const { return m_bModified; } + bool Empty() const { return m_Items.empty(); } + + enum + { + plReadOnly = (1 << 0), + }; + + Flags32 m_Flags; + + bool IsReadOnly() const { return m_Flags.is(plReadOnly); } + +private: + PropItemVec m_Items; + PropItem *m_EditChooseValue; + PropItem *m_EditTextureValue; + PropItem *m_EditShortcutValue; + + TOnModifiedEvent OnModifiedEvent; + + PropItem *m_EditTextValue; + + char* m_EditTextValueData; + char* m_EditTextValueInitial; + int m_EditTextValueDataSize; + bool m_bModified; + + void DrawEditText(); + int DrawEditText_Callback(ImGuiInputTextCallbackData *data); + + GameTypeChooser m_EditGameTypeChooser; + PropItem *m_EditGameTypeValue; + + void DrawEditGameType(); + + void Modified() + { + m_bModified = true; + + if (!OnModifiedEvent.empty()) + OnModifiedEvent(); + } + + UIPropertiesItem m_Root; +}; diff --git a/src/editors/xrEProps/Tree/Properties/UIPropertiesItem_DrawProp.cpp b/src/editors/xrEProps/Tree/Properties/UIPropertiesItem_DrawProp.cpp new file mode 100644 index 00000000000..e6e52f5bcb7 --- /dev/null +++ b/src/editors/xrEProps/Tree/Properties/UIPropertiesItem_DrawProp.cpp @@ -0,0 +1,590 @@ +#include "stdafx.h" + +#define TSTRING_COUNT 10 +const LPCSTR TEXTUREString[TSTRING_COUNT] = {"Custom...", "$null", "$base0", "$base1", "$base2", "$base3", "$base4", "$base5", "$base6", "$base7"}; + +template +inline bool DrawNumeric(PropItem *item, bool &change, bool read_only) +{ + change = false; + NumericValue *V = dynamic_cast *>(item->GetFrontValue()); + if (!V) + return false; + int data = 0; + { + T value = *V->value; + item->BeforeEdit, T>(value); + data = static_cast(value); + } + + change = ImGui::InputInt("##value", &data, read_only ? ImGuiInputTextFlags_ReadOnly : 0); + + if (change) + { + T temp = static_cast(data); + + if (V->lim_mn > temp) + temp = V->lim_mn; + if (V->lim_mx < temp) + temp = V->lim_mx; + + if (item->AfterEdit, T>(temp) && !read_only) + change = item->ApplyValue, T>(temp); + } + + return true; +} + +template <> +inline bool DrawNumeric(PropItem *item, bool &change, bool read_only) +{ + change = false; + NumericValue *V = dynamic_cast *>(item->GetFrontValue()); + if (!V) + return false; + float temp = *V->value; + item->BeforeEdit, float>(temp); + change = ImGui::InputFloat("##value", &temp, 0.01, 0.1, V->dec, read_only ? ImGuiInputTextFlags_ReadOnly : 0); + if (change) + { + if (!isinf(V->lim_mn) && V->lim_mn > temp) + temp = V->lim_mn; + if (!isinf(V->lim_mx) && V->lim_mx < temp) + temp = V->lim_mx; + if (item->AfterEdit, float>(temp) && !read_only) + { + change = item->ApplyValue, float>(temp); + } + } + return true; +} + +template +BOOL TokenOnEdit(PropItem *prop, bool &change) +{ + TokenValue *V = dynamic_cast *>(prop->GetFrontValue()); + if (!V) + return FALSE; + T edit_value = V->GetValue(); + prop->BeforeEdit, T>(edit_value); + int index = 0; + xr_token *token_list = V->token; + int cnt = 0; + for (; token_list[cnt].name; cnt++) + { + if (token_list[cnt].id == edit_value) + { + index = cnt; + } + } + if (ImGui::Combo( + "##value", &index, [](void *data, int idx, const char **out_text) -> bool + {*out_text = reinterpret_cast(data)[idx].name;return true; }, + reinterpret_cast(token_list), cnt)) + { + T new_val = token_list[index].id; + if (prop->AfterEdit, T>(new_val)) + change = prop->ApplyValue, T>(new_val); + } + return TRUE; +} + +template +BOOL RTokenOnEdit(PropItem *prop, bool &change) +{ + RTokenValue *V = dynamic_cast *>(prop->GetFrontValue()); + if (!V) + return FALSE; + T edit_value = V->GetValue(); + prop->BeforeEdit, T>(edit_value); + int index = 0; + + xr_rtoken *token_list = V->token; + for (int cnt = 0; V->token_count > cnt; cnt++) + { + if (token_list[cnt].id == edit_value) + { + index = cnt; + } + } + if (ImGui::Combo( + "##value", &index, [](void *data, int idx, const char **out_text) -> bool + {*out_text = reinterpret_cast(data)[idx].name.c_str(); return true; }, + reinterpret_cast(token_list), V->token_count)) + { + T new_val = token_list[index].id; + if (prop->AfterEdit, T>(new_val)) + change = prop->ApplyValue, T>(new_val); + } + return TRUE; +} + +template +BOOL FlagOnEdit(PropItem *prop, bool &change) +{ + FlagValue<_flags> *V = dynamic_cast> *>(prop->GetFrontValue()); + if (!V) + return FALSE; + _flags new_val = V->GetValue(); + + prop->BeforeEdit>, _flags>(new_val); + u32 u = new_val.get(); + + if (ImGui::CheckboxFlags("##value", &u, V->mask)) + { + new_val.assign(u); + if (prop->AfterEdit>, _flags>(new_val)) + change = prop->ApplyValue>, _flags>(new_val); + } + return TRUE; +} + +void UIPropertiesItem::DrawProp() +{ + PropItem* node = PItem; + + auto Modified = [&]() + { + PropertiesFrom->Modified(); + }; + + auto DrawTextProperty = [&](const char* text) + { + string128 Str; + xr_string Source = PItem->GetDrawText(); + strncpy_s(Str, Source.c_str(), sizeof(string128) - 4); + + if (Source.size() > 128 && strrchr(Str, '\n')) + strrchr(Str, '\n')[0] = '\0'; + + xr_strcat(Str, "..."); + ImGui::Button(Str, ImVec2(-1, 0)); + + if (ImGui::OpenPopupOnItemClick2("EditText", 0)) + { + if (PropertiesFrom->m_EditTextValueData) + xr_delete(PropertiesFrom->m_EditTextValueData); + + if (PropertiesFrom->m_EditTextValueInitial) + xr_delete(PropertiesFrom->m_EditTextValueInitial); + + PropertiesFrom->m_EditTextValueData = xr_strdup(text ? text : ""); + PropertiesFrom->m_EditTextValueInitial = xr_strdup(text ? text : ""); + PropertiesFrom->m_EditTextValueDataSize = xr_strlen(PropertiesFrom->m_EditTextValueData) + 1; + } + + PropertiesFrom->m_EditTextValue = node; + PropertiesFrom->DrawEditText(); + }; + + EPropType type = PItem->Type(); + + switch (type) + { + case PROP_NUMERIC: + { + bool change = false; + bool ro = PropertiesFrom->IsReadOnly(); + + if (!DrawNumeric(node, change, ro)) + if (!DrawNumeric(node, change, ro)) + if (!DrawNumeric(node, change, ro)) + if (!DrawNumeric(node, change, ro)) + if (!DrawNumeric(node, change, ro)) + if (!DrawNumeric(node, change, ro)) + if (!DrawNumeric(node, change, ro)) + R_ASSERT(false); + if (change) + Modified(); + } + break; + + case PROP_SHORTCUT: + { + ShortcutValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + + if (ImGui::Button(V->GetDrawText(0).c_str(), ImVec2(-30, 0))) + { + UIKeyPressForm::Show(); + PropertiesFrom->m_EditShortcutValue = node; + } + ImGui::SameLine(); + + if (ImGui::Button("X", ImVec2(-1, 0))) + { + xr_shortcut val; + if (V->ApplyValue(val)) + Modified(); + } + } + break; + + case PROP_BOOLEAN: + { + BOOLValue *V = dynamic_cast(node->GetFrontValue()); + VERIFY(V); + BOOL new_val_as_BOOL = V->GetValue(); + node->BeforeEdit(new_val_as_BOOL); + bool new_val = new_val_as_BOOL; + + if (ImGui::Checkbox("##value", &new_val)) + { + new_val_as_BOOL = new_val; + + if (node->AfterEdit(new_val_as_BOOL)) + { + if (node->ApplyValue(new_val_as_BOOL)) + Modified(); + } + } + } + break; + + case PROP_FLAG: + { + bool change = false; + + if (!FlagOnEdit(node, change)) + if (!FlagOnEdit(node, change)) + if (!FlagOnEdit(node, change)) + R_ASSERT(false); + + if (change) + Modified(); + } + break; + + case PROP_VECTOR: + { + VectorValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + Fvector edit_val = V->GetValue(); + + node->BeforeEdit(edit_val); + float vector[3] = { edit_val.x, edit_val.y, edit_val.z }; + + if (ImGui::InputFloat3("##value", vector, V->dec)) + { + for (int i = 0; i < 3; i++) + { + if (V->lim_mn[i] > vector[i]) + { + vector[i] = V->lim_mn[i]; + } + else if (V->lim_mx[i] < vector[i]) + { + vector[i] = V->lim_mx[i]; + } + edit_val[i] = vector[i]; + } + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val)) + Modified(); + } + } + } + break; + + case PROP_COLOR: + { + U32Value *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + u32 edit_val = V->GetValue(); + + node->BeforeEdit(edit_val); + u32 a = color_get_A(edit_val); + float color[3] = { color_get_B(edit_val) / 255.f, color_get_G(edit_val) / 255.f, color_get_R(edit_val) / 255.f }; + + if (ImGui::ColorEdit3("##value", color)) + { + edit_val = color_rgba_f(color[2], color[1], color[0], 1.f); + edit_val = subst_alpha(edit_val, a); + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val)) + Modified(); + } + } + } + break; + + case PROP_FCOLOR: + { + ColorValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + Fcolor edit_val = V->GetValue(); + + node->BeforeEdit(edit_val); + float a = edit_val.a; + float color[3] = { edit_val.r, edit_val.g, edit_val.b }; + + if (ImGui::ColorEdit3("##value", color)) + { + edit_val.r = color[0]; + edit_val.g = color[1]; + edit_val.b = color[2]; + edit_val.a = a; + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val)) + Modified(); + } + } + } + break; + + case PROP_VCOLOR: + { + VectorValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + Fvector edit_val = V->GetValue(); + + node->BeforeEdit(edit_val); + float color[3] = { edit_val[0], edit_val[0], edit_val[0] }; + + if (ImGui::ColorEdit3("##value", color)) + { + edit_val[0] = color[0]; + edit_val[0] = color[1]; + edit_val[0] = color[2]; + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val)) + Modified(); + } + } + } + break; + + case PROP_CHOOSE: + { + xr_string text = node->GetDrawText().c_str(); + + if (!text[0]) + text = ""; + + if (ImGui::Button(text.c_str(), ImVec2(-1, 0))) + { + PropItem *prop = node; + ChooseValue *V = dynamic_cast(prop->GetFrontValue()); + VERIFY(V); + shared_str edit_val = V->GetValue(); + + if (!edit_val.size()) + edit_val = V->m_StartPath; + + prop->BeforeEdit(edit_val); + ChooseItemVec items; + + if (!V->OnChooseFillEvent.empty()) + { + V->m_Items = &items; + V->OnChooseFillEvent(V); + } + + UIChooseForm::SelectItem(V->m_ChooseID, V->subitem, edit_val.c_str(), 0, V->m_FillParam, 0, items.size() ? &items : 0, V->m_ChooseFlags); + PropertiesFrom->m_EditChooseValue = prop; + +#pragma TODO("TSMP: не надо ли тут тоже Modified() ?") + } + } + break; + + case PROP_TOKEN: + { + bool change = false; + if (!TokenOnEdit(node, change)) + if (!TokenOnEdit(node, change)) + if (!TokenOnEdit(node, change)) + R_ASSERT(false); + + if (change) + Modified(); + } + break; + + case PROP_RTOKEN: + { + bool change = false; + if (!RTokenOnEdit(node, change)) + if (!RTokenOnEdit(node, change)) + if (!RTokenOnEdit(node, change)) + R_ASSERT(false); + + if (change) + Modified(); + } + break; + + case PROP_SH_TOKEN: + { + TokenValueSH *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + u32 edit_value = V->GetValue(); + node->BeforeEdit(edit_value); + int index = edit_value; + const char *InTokens[256]; + int i = 0; + + for (; i < V->cnt; i++) + InTokens[i] = V->items[i].str; + + if (ImGui::Combo("##value", &index, InTokens, i)) + { + u32 new_val = index; + if (node->AfterEdit(new_val)) + if (node->ApplyValue(new_val)) + Modified(); + } + } + break; + + case PROP_TEXTURE2: + { + CTextValue *T = dynamic_cast(node->GetFrontValue()); + R_ASSERT(T); + xr_string edit_val = T->GetValue(); + node->BeforeEdit(edit_val); + int index = 0; + int cnt = TSTRING_COUNT; + LPCSTR List[TSTRING_COUNT + 1] = {TEXTUREString[0], TEXTUREString[1], TEXTUREString[2], TEXTUREString[3], TEXTUREString[4], TEXTUREString[5], TEXTUREString[6], TEXTUREString[7], TEXTUREString[8], TEXTUREString[9], 0}; + + if (edit_val == List[1]) + index = 1; + else if (edit_val == List[2]) + index = 2; + else if (!edit_val.empty()) + { + List[3] = edit_val.c_str(); + index = 3; + cnt = 4; + } + else + index = 1; + + if (ImGui::Combo("##value", &index, List, cnt)) + { + if (index == 0) + { + UIChooseForm::SelectItem(smTexture, 8, edit_val.c_str(), 0, 0, 0, 0, 0); + PropertiesFrom->m_EditTextureValue = node; + } + else + { + edit_val = List[index]; + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val.c_str())) + Modified(); + } + } + } + } + break; + + case PROP_CLIST: + { + CListValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + LPCSTR edit_value = V->value; + int index = 0; + int i = 0; + + for (; i < V->item_count; i++) + { + if (V->items[i] == edit_value) + index = i; + } + + if (ImGui::Combo( + "##value", &index, [](void *data, int idx, const char **out_text) -> bool + {*out_text = reinterpret_cast(data)[idx].c_str(); return true; }, + reinterpret_cast(V->items), i)) + { + if (node->AfterEdit(V->items[index])) + if (node->ApplyValue(V->items[index].c_str())) + Modified(); + } + } + break; + + case PROP_RLIST: + { + RListValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + LPCSTR edit_value = V->value ? V->value->c_str() : 0; + int index = 0; + int i = 0; + + for (; i < V->item_count; i++) + { + if (V->items[i] == edit_value) + index = i; + } + + if (ImGui::Combo( + "##value", &index, [](void *data, int idx, const char **out_text) -> bool + {*out_text = reinterpret_cast(data)[idx].c_str(); return true; }, + reinterpret_cast(V->items), i)) + { + if (node->AfterEdit(V->items[index])) + if (node->ApplyValue(V->items[index])) + Modified(); + } + } + break; + + case PROP_CTEXT: + { + CTextValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + DrawTextProperty(V->GetValue()); + } + break; + + case PROP_RTEXT: + { + RTextValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + DrawTextProperty(V->GetValue().c_str()); + } + break; + + case PROP_STEXT: + { + STextValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + DrawTextProperty(V->GetValue().c_str()); + } + break; + + case PROP_GAMETYPE: + { + GameTypeValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + ImGui::Text(node->GetDrawText().c_str()); + + if (ImGui::OpenPopupOnItemClick2("EditGameType", 0)) + { + PropertiesFrom->m_EditGameTypeChooser = V->GetValue(); + node->BeforeEdit(PropertiesFrom->m_EditGameTypeChooser); + PropertiesFrom->m_EditGameTypeValue = node; + } + + PropertiesFrom->DrawEditGameType(); + } + break; + + default: + // not_implemented(); + ImGui::Text(""); + break; + } +} diff --git a/src/editors/xrEProps/Tree/Properties/UIPropertiesItem_Mixed.cpp b/src/editors/xrEProps/Tree/Properties/UIPropertiesItem_Mixed.cpp new file mode 100644 index 00000000000..4b28d7c7e97 --- /dev/null +++ b/src/editors/xrEProps/Tree/Properties/UIPropertiesItem_Mixed.cpp @@ -0,0 +1,357 @@ +#include "stdafx.h" + +template +inline bool MixedNumeric(PropItem *item, bool &change) +{ + change = false; + NumericValue *V = dynamic_cast *>(item->GetFrontValue()); + if (!V) + return false; + T value = *V->value; + item->BeforeEdit, T>(value); + + if (item->AfterEdit, T>(value)) + { + change = item->ApplyValue, T>(value); + } + return true; +} + +template +BOOL MixedFlag(PropItem *prop, bool &change) +{ + FlagValue<_flags> *V = dynamic_cast> *>(prop->GetFrontValue()); + if (!V) + return FALSE; + _flags new_val = V->GetValue(); + + prop->BeforeEdit>, _flags>(new_val); + if (prop->AfterEdit>, _flags>(new_val)) + change = prop->ApplyValue>, _flags>(new_val); + return TRUE; +} + +template +BOOL MixedToken(PropItem *prop, bool &change) +{ + TokenValue *V = dynamic_cast *>(prop->GetFrontValue()); + if (!V) + return FALSE; + T edit_value = V->GetValue(); + prop->BeforeEdit, T>(edit_value); + if (prop->AfterEdit, T>(edit_value)) + change = prop->ApplyValue, T>(edit_value); + return TRUE; +} + +template +BOOL MixedRToken(PropItem *prop, bool &change) +{ + RTokenValue *V = dynamic_cast *>(prop->GetFrontValue()); + if (!V) + return FALSE; + T edit_value = V->GetValue(); + prop->BeforeEdit, T>(edit_value); + if (prop->AfterEdit, T>(edit_value)) + change = prop->ApplyValue, T>(edit_value); + return TRUE; +} + +void UIPropertiesItem::RemoveMixed() +{ + PropItem* node = PItem; + EPropType type = node->Type(); + bool change = false; + + auto Modified = [&]() + { + PropertiesFrom->Modified(); + }; + + switch (type) + { + case PROP_SHORTCUT: + { + ShortcutValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + xr_shortcut val = *V->value; + + if (V->ApplyValue(val)) + change = true; + } + break; + + case PROP_CHOOSE: + { + ChooseValue *V = dynamic_cast(node->GetFrontValue()); + VERIFY(V); + shared_str edit_val = V->GetValue(); + + if (!edit_val.size()) + edit_val = V->m_StartPath; + + node->BeforeEdit(edit_val); + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val)) + change = true; + } + } + break; + + case PROP_NUMERIC: + { + if (!MixedNumeric(node, change)) + if (!MixedNumeric(node, change)) + if (!MixedNumeric(node, change)) + if (!MixedNumeric(node, change)) + if (!MixedNumeric(node, change)) + if (!MixedNumeric(node, change)) + if (!MixedNumeric(node, change)) + R_ASSERT(false); + } + break; + + case PROP_BOOLEAN: + { + BOOLValue *V = dynamic_cast(node->GetFrontValue()); + VERIFY(V); + BOOL val = V->GetValue(); + node->BeforeEdit(val); + + if (node->AfterEdit(val)) + { + if (node->ApplyValue(val)) + change = true; + } + } + break; + + case PROP_FLAG: + { + if (!MixedFlag(node, change)) + if (!MixedFlag(node, change)) + if (!MixedFlag(node, change)) + R_ASSERT(false); + } + break; + + case PROP_VECTOR: + { + VectorValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + Fvector edit_val = V->GetValue(); + node->BeforeEdit(edit_val); + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val)) + change = true; + } + } + break; + + case PROP_TOKEN: + { + if (!MixedToken(node, change)) + if (!MixedToken(node, change)) + if (!MixedToken(node, change)) + R_ASSERT(false); + } + break; + + case PROP_RTOKEN: + { + if (!MixedRToken(node, change)) + if (!MixedRToken(node, change)) + if (!MixedRToken(node, change)) + R_ASSERT(false); + } + break; + + case PROP_RLIST: + { + RListValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + LPCSTR edit_value = V->value ? V->value->c_str() : nullptr; + int index = 0; + const char *InTokens[256]; + + for (int i = 0; i < V->item_count; i++) + { + if (V->items[i] == edit_value) + index = i; + } + + if (node->AfterEdit(V->items[index])) + if (node->ApplyValue(V->items[index])) + change = true; + } + break; + + case PROP_COLOR: + { + U32Value *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + u32 edit_val = V->GetValue(); + node->BeforeEdit(edit_val); + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val)) + change = true; + } + } + break; + + case PROP_FCOLOR: + { + ColorValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + Fcolor edit_val = V->GetValue(); + node->BeforeEdit(edit_val); + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val)) + change = true; + } + } + break; + + case PROP_VCOLOR: + { + VectorValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + Fvector edit_val = V->GetValue(); + node->BeforeEdit(edit_val); + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val)) + change = true; + } + } + break; + + case PROP_RTEXT: + case PROP_STEXT: + case PROP_CTEXT: + { + if (CTextValue* V1 = dynamic_cast(node->GetFrontValue())) + { + xr_string out = V1->GetValue(); + if (node->AfterEdit(out)) + { + if (node->ApplyValue(out.c_str())) + change = true; + } + } + else if (RTextValue* V2 = dynamic_cast(node->GetFrontValue())) + { + shared_str out = V2->GetValue(); + if (node->AfterEdit(out)) + { + if (node->ApplyValue(out)) + change = true; + } + } + else if (STextValue* V3 = dynamic_cast(node->GetFrontValue())) + { + xr_string out = V3->GetValue(); + if (node->AfterEdit(out)) + { + if (node->ApplyValue(out)) + change = true; + } + } + else + R_ASSERT(false); + } + break; + + case PROP_CLIST: + { + CListValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + LPCSTR edit_value = V->value; + int index = 0; + + for (int i = 0; i < V->item_count; i++) + { + if (V->items[i] == edit_value) + index = i; + } + + if (node->AfterEdit(V->items[index])) + { + if (node->ApplyValue(V->items[index].c_str())) + change = true; + } + } + break; + + case PROP_SH_TOKEN: + { + TokenValueSH *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + u32 edit_value = V->GetValue(); + node->BeforeEdit(edit_value); + + if (node->AfterEdit(edit_value)) + { + if (node->ApplyValue(edit_value)) + change = true; + } + } + break; + + case PROP_TEXTURE2: + { + CTextValue *T = dynamic_cast(node->GetFrontValue()); + R_ASSERT(T); + xr_string edit_val = T->GetValue(); + node->BeforeEdit(edit_val); + + if (node->AfterEdit(edit_val)) + { + if (node->ApplyValue(edit_val.c_str())) + change = true; + } + } + break; + + case PROP_GAMETYPE: + { + GameTypeValue *V = dynamic_cast(node->GetFrontValue()); + R_ASSERT(V); + ImGui::Text(node->GetDrawText().c_str()); + auto value = V->GetValue(); + node->BeforeEdit(value); + + if (node->AfterEdit(value)) + { + if (node->ApplyValue(value)) + change = true; + } + } + break; + + default: + return; + break; + } + +#pragma TODO("TSMP: ") + + if (change) + { + Modified(); + } + else + { + Modified(); + PItem->m_Flags.set(PropItem::flIgnoreMixed, 1); + } +} diff --git a/src/editors/xrEProps/Tree/Properties/UiPropertiesItem.cpp b/src/editors/xrEProps/Tree/Properties/UiPropertiesItem.cpp new file mode 100644 index 00000000000..80e4a84b638 --- /dev/null +++ b/src/editors/xrEProps/Tree/Properties/UiPropertiesItem.cpp @@ -0,0 +1,173 @@ +#include "stdafx.h" + +UIPropertiesItem::UIPropertiesItem(shared_str Name, UIPropertiesForm* propertiesFrom) : UITreeItem(Name), PropertiesFrom(propertiesFrom) +{ + PItem = nullptr; +} + +void UIPropertiesItem::Draw() +{ + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + + if (PItem && PItem->m_Flags.test(PropItem::flShowCB)) + { + if (ImGui::CheckboxFlags("##value", &PItem->m_Flags.flags, PropItem::flCBChecked)) + { + PItem->OnChange(); + PropertiesFrom->Modified(); + } + + ImGui::SameLine(0, 2); + } + + if (Items.size()) + { + ImGuiTreeNodeFlags FloderFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_DefaultOpen; + bool open = ImGui::TreeNodeEx(Name.c_str(), FloderFlags); + ImGui::TableNextColumn(); + DrawItem(); + + if (open) + { + for (UITreeItem* Item : Items) + static_cast(Item)->Draw(); + + ImGui::TreePop(); + } + } + else + { + ImGui::TreeNodeEx(Name.c_str(), ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::TableNextColumn(); + DrawItem(); + } +} + +void UIPropertiesItem::DrawRoot() +{ + VERIFY(!PItem); + + for (UITreeItem* Item : Items) + static_cast(Item)->Draw(); +} + +void UIPropertiesItem::DrawItem() +{ + if (!PItem) + return; + + EPropType type = PItem->Type(); + + switch (type) + { + case PROP_CANVAS: + { + if (PItem->m_Flags.test(PropItem::flMixed)) + { + ImGui::TextDisabled(PItem->GetDrawText().c_str()); + + } + else + { + ImGui::PushItemWidth(-1); + CanvasValue* val = dynamic_cast(PItem->GetFrontValue()); R_ASSERT(val); + if (!val->OnDrawCanvasEvent.empty()) + val->OnDrawCanvasEvent(val); + } + } + break; + + case PROP_BUTTON: + if (PItem->m_Flags.test(PropItem::flMixed)) + ImGui::TextDisabled(PItem->GetDrawText().c_str()); + else + { + ImGui::PushID(Name.c_str()); + bool bRes = false; + bool bSafe = false; + ButtonValue* V = dynamic_cast(PItem->GetFrontValue()); + R_ASSERT(V); + + if (!V->value.empty()) + { + ImGui::PushItemWidth(-1); + float size = float(ImGui::CalcItemWidth()); + float dx = floorf(size / float(V->value.size())); + float offset = size - (dx * V->value.size()); + V->btn_num = V->value.size(); + + for (RStringVecIt it = V->value.begin(); it != V->value.end(); it++) + { + int k = it - V->value.begin(); + + if (ImGui::Button(it->c_str(), ImVec2(dx + offset, 0))) + { + V->btn_num = k; + bRes |= V->OnBtnClick(bSafe); + } + + offset = 0; + ImGui::SameLine(0, 2); + } + } + else + ImGui::Text(""); + + ImGui::PopID(); + } + break; + + case PROP_WAVE: + case PROP_UNDEF: + break; + + case PROP_CAPTION: + ImGui::TextDisabled(PItem->GetDrawText().c_str()); + break; + + default: + ImGui::PushID(Name.c_str()); + + if (PropertiesFrom->IsReadOnly()) + { + if (type == PROP_BOOLEAN) + { + FlagValueCustom* V = dynamic_cast(PItem->GetFrontValue()); VERIFY(V); + ImGui::TextDisabled(V->GetValueEx() ? "true" : "false"); + } + else + ImGui::TextDisabled(PItem->GetDrawText().c_str()); + } + else if (PItem->m_Flags.test(PropItem::flMixed) && !PItem->m_Flags.test(PropItem::flIgnoreMixed)) + { + if (ImGui::Button("(Mixed)", ImVec2(-1, 0))) + RemoveMixed(); + } + else + { + if (PItem->m_Flags.test(PropItem::flDisabled)) + { + if (type == PROP_FLAG) + { + FlagValueCustom* V = dynamic_cast(PItem->GetFrontValue()); VERIFY(V); + ImGui::TextDisabled(V->GetValueEx() ? "true" : "false"); + } + else + ImGui::TextDisabled(PItem->GetDrawText().c_str()); + } + else + { + ImGui::PushItemWidth(-1); + DrawProp(); + } + } + ImGui::PopID(); + break; + } +} + +UITreeItem* UIPropertiesItem::CreateItem(shared_str Name) +{ + return xr_new(Name, PropertiesFrom); +} diff --git a/src/editors/xrEProps/Tree/Properties/UiPropertiesItem.h b/src/editors/xrEProps/Tree/Properties/UiPropertiesItem.h new file mode 100644 index 00000000000..a019107abdc --- /dev/null +++ b/src/editors/xrEProps/Tree/Properties/UiPropertiesItem.h @@ -0,0 +1,22 @@ +#pragma once + +class UIPropertiesForm; + +class XREPROPS_API UIPropertiesItem : public UITreeItem +{ +public: + UIPropertiesItem(shared_str Name, UIPropertiesForm* PropertiesFrom); + virtual ~UIPropertiesItem() = default; + PropItem* PItem; + UIPropertiesForm* PropertiesFrom; + void Draw(); + void DrawRoot(); + void DrawItem(); + void DrawProp(); + +protected: + virtual UITreeItem* CreateItem(shared_str Name); + +private: + void RemoveMixed(); +}; diff --git a/src/editors/xrEProps/UIItemListForm.cpp b/src/editors/xrEProps/UIItemListForm.cpp new file mode 100644 index 00000000000..ed6eff7c62a --- /dev/null +++ b/src/editors/xrEProps/UIItemListForm.cpp @@ -0,0 +1,549 @@ +#include "stdafx.h" + +UIItemListForm::UIItemListForm() +{ + m_Flags.zero(); + m_UseMenuEdit = false; +} + +UIItemListForm::~UIItemListForm() +{ + ClearList(); +} + +void UIItemListForm::Draw() +{ + + m_UseMenuEdit = false; + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 1)); + DrawMenuEdit(); + DrawNode(&m_GeneralNode); + ImGui::PopStyleVar(2); + if (!m_UseMenuEdit) + { + m_edit_node = nullptr; + } +} + +void UIItemListForm::ClearList() +{ + m_GeneralNode = Node(); + + ClearSelectedItems(); + for (ListItem *item : m_Items) + { + xr_delete(item); + } + m_Items.clear(); +} + +void UIItemListForm::RemoveSelectItem() +{ + if (!m_SelectedItems.size() || m_Flags.test(fMultiSelect)) + return; + for (auto b = m_Items.begin(), e = m_Items.end(); b != e; b++) + { + if (*b == m_SelectedItems.back()) + { + m_Items.erase(b); + break; + } + } + m_GeneralNode = Node(); + for (ListItem *item : m_Items) + { + Node *N = AppendObject(&m_GeneralNode, item->Key()); + VERIFY(N); + N->Object = item; + } +} + +void UIItemListForm::ClearSelected() +{ + ClearSelectedItems(); + if (!OnItemFocusedEvent.empty()) + OnItemFocusedEvent(0); + if (m_Flags.test(fMultiSelect)) + { + if (!OnItemsFocusedEvent.empty()) + OnItemsFocusedEvent(m_SelectedItems); + } +} + +void UIItemListForm::SelectItem(const char *name) +{ + if (name == nullptr) + return; + Node *N = SelectObject(&m_GeneralNode, name); + if (m_Flags.test(fMultiSelect)) + { + ClearSelectedItems(); + N->Object->selected = true; + if (N) + m_SelectedItems.push_back(N->Object); + if (!OnItemFocusedEvent.empty()) + OnItemFocusedEvent(N->Object); + if (!OnItemsFocusedEvent.empty()) + OnItemsFocusedEvent(m_SelectedItems); + } + else + { + ClearSelectedItems(); + if (N) + m_SelectedItems.push_back(N->Object); + if (!OnItemFocusedEvent.empty()) + OnItemFocusedEvent(N->Object); + } +} + +bool UIItemListForm::GetSelected(RStringVec &items) const +{ + for (ListItem *prop : m_SelectedItems) + { + items.push_back(prop->key); + } + return true; +} +int UIItemListForm::GetSelected(LPCSTR pref, ListItemsVec &items, bool bOnlyObject) +{ + for (ListItem *prop : m_SelectedItems) + { + if (prop && (!bOnlyObject || (bOnlyObject && prop->m_Object))) + { + xr_string key = *prop->key; + if (pref) + { + if (0 == key.find(pref)) + items.push_back(prop); + } + else + items.push_back(prop); + } + } + return items.size(); +} +void UIItemListForm::AssignItems(ListItemsVec &items, const char *name_selection, bool clear_Folder, bool save_selected) +{ + RStringVec selection_items; + if (save_selected) + GetSelected(selection_items); + ClearList(); + m_Items = items; + + if (!clear_Folder) + { + ClearObject(&m_GeneralNode); + } + else + { + m_GeneralNode = Node(); + } + + for (ListItem *item : m_Items) + { + item->Parent = this; + Node *N = AppendObject(&m_GeneralNode, item->Key()); + VERIFY(N); + N->Object = item; + } + if (name_selection) + { + Node *N = SelectObject(&m_GeneralNode, name_selection); + ClearSelectedItems(); + if (m_Flags.test(fMultiSelect)) + { + N->Object->selected = true; + } + if (N) + m_SelectedItems.push_back(N->Object); + } + if (save_selected) + { + for (shared_str &name : selection_items) + { + Node *N = Find(&m_GeneralNode, name.c_str()); + if (N) + { + if (m_Flags.test(fMultiSelect)) + { + N->Object->selected = true; + } + m_SelectedItems.push_back(N->Object); + } + } + } +} + +void UIItemListForm::DrawMenuEdit() +{ + if (ImGui::BeginPopupContextItem("MenuEdit")) + { + ImGui::PopStyleVar(2); + m_UseMenuEdit = true; + + if (!OnItemCreateEvent.empty()) + { + if (ImGui::MenuItem("Create")) + { + for (int i = 0; i < 256; i++) + { + string4096 name; + if (i == 0) + xr_strcpy(name, "new"); + else + xr_sprintf(name, "new_%d", i); + + Node *N = m_edit_node == 0 ? &m_GeneralNode : m_edit_node; + string_path path; + path[0] = 0; + if (N->Path.c_str() && N->Path.c_str()[0]) + { + xr_strcpy(path, N->Path.c_str()); + } + if (N->IsFolder() && N->Name.c_str() && N->Name.c_str()[0]) + { + if (path[0]) + xr_strcat(path, "\\"); + xr_strcat(path, N->Name.c_str()); + } + if (path[0]) + xr_strcat(path, "\\"); + xr_strcat(path, name); + if (!Find(&m_GeneralNode, path)) + { + OnItemCreateEvent(path); + ImGui::CloseCurrentPopup(); + m_edit_node = nullptr; + break; + } + } + } + } + if (!OnItemCloneEvent.empty() && m_edit_node && m_edit_node->IsObject()) + { + if (ImGui::MenuItem("Clone")) + { + string_path parent_path; + parent_path[0] = 0; + Node *N = m_edit_node == 0 ? &m_GeneralNode : m_edit_node; + GetFullPath(N, parent_path); + for (int i = 0; i < 256; i++) + { + string4096 name; + if (i == 0) + xr_sprintf(name, "%s_clone", m_edit_node->Name.c_str()); + else + xr_sprintf(name, "%s_clone_%d", m_edit_node->Name.c_str(), i); + + Node *N = m_edit_node == 0 ? &m_GeneralNode : m_edit_node; + string_path path; + path[0] = 0; + if (N->Path.c_str() && N->Path.c_str()[0]) + { + xr_strcpy(path, N->Path.c_str()); + } + if (m_edit_node->IsFolder()) + { + if (path[0]) + xr_strcat(path, "\\"); + xr_strcat(path, m_edit_node->Name.c_str()); + } + if (path[0]) + xr_strcat(path, "\\"); + xr_strcat(path, name); + if (!Find(&m_GeneralNode, path)) + { + + OnItemCloneEvent(parent_path, path); + ImGui::CloseCurrentPopup(); + m_edit_node = nullptr; + break; + } + } + } + if (!OnItemCreateEvent.empty() || !OnItemCloneEvent.empty()) + { + ImGui::Separator(); + } + } + + if (ImGui::MenuItem("Create Folder")) + { + Node *N = m_edit_node == 0 ? &m_GeneralNode : m_edit_node; + for (int i = 0; i < 256; i++) + { + string4096 full_path, name; + if (i == 0) + xr_strcpy(name, "new_Folder"); + else + xr_sprintf(name, "new_Folder_%d", i); + + if (N->Path.c_str() && N->Path.c_str()[0]) + xr_strcpy(full_path, N->Path.c_str()); + else + full_path[0] = 0; + if (N->IsFolder() && N->Name.c_str() && N->Name.c_str()[0]) + { + if (full_path[0]) + xr_strcat(full_path, "\\"); + xr_strcat(full_path, N->Name.c_str()); + } + if (full_path[0]) + xr_strcat(full_path, "\\"); + xr_strcat(full_path, name); + + if (!FindFolder(&m_GeneralNode, full_path) && AppendFolder(&m_GeneralNode, full_path)) + { + ImGui::CloseCurrentPopup(); + m_edit_node = nullptr; + break; + } + } + } + if (m_edit_node && m_edit_node != &m_GeneralNode) + { + ImGui::Separator(); + if (ImGui::BeginMenu("Rename")) + { + ImGui::InputText("New Name", m_edit_name, sizeof(m_edit_name)); + if (ImGui::Button("Ok")) + { + string4096 full_path; + if (m_edit_node->Path.c_str() && m_edit_node->Path.c_str()[0]) + xr_strcpy(full_path, m_edit_node->Path.c_str()); + else + full_path[0] = 0; + + if (full_path[0]) + xr_strcat(full_path, "\\"); + xr_strcat(full_path, m_edit_name); + if (Move(&m_GeneralNode, m_edit_node, full_path)) + { + ImGui::CloseCurrentPopup(); + m_edit_node = nullptr; + } + } + ImGui::SameLine(); + if (ImGui::Button("Cancel")) + { + ImGui::CloseCurrentPopup(); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Move")) + { + ImGui::InputText("New Path", m_edit_path, sizeof(m_edit_path)); + if (ImGui::Button("Ok")) + { + string4096 full_path; + xr_strcpy(full_path, m_edit_path); + if (m_edit_path[0]) + xr_strcat(full_path, "\\"); + xr_strcat(full_path, m_edit_node->Name.c_str()); + if (Move(&m_GeneralNode, m_edit_node, full_path)) + { + ImGui::CloseCurrentPopup(); + m_edit_node = nullptr; + } + } + ImGui::SameLine(); + if (ImGui::Button("Cancel")) + { + ImGui::CloseCurrentPopup(); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Delete")) + { + Remove(&m_GeneralNode, m_edit_node, true); + ImGui::CloseCurrentPopup(); + m_edit_node = nullptr; + } + } + + ImGui::EndPopup(); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 1)); + } +} + +void UIItemListForm::DrawAfterFolderNode(bool is_open, Node *Node) +{ + if (m_Flags.is(fMenuEdit)) + { + if (ImGui::OpenPopupOnItemClick2("MenuEdit", 1)) + { + m_UseMenuEdit = true; + m_edit_node = Node; + xr_strcpy(m_edit_path, Node->Path.c_str()); + xr_strcpy(m_edit_name, Node->Name.c_str()); + } + } + if (is_open && m_Flags.is(fMenuEdit)) + { + DrawMenuEdit(); + } +} + +void UIItemListForm::DrawItem(Node *Node) +{ + if (!Node->Object->Visible()) + return; + ImGuiTreeNodeFlags Flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; + if (m_Flags.test(fMultiSelect)) + { + if (Node->Object && Node->Object->selected) + Flags |= ImGuiTreeNodeFlags_Bullet; + if (m_SelectedItems.size() && m_SelectedItems.back() == Node->Object) + Flags |= ImGuiTreeNodeFlags_Selected; + } + else + { + if (m_SelectedItems.size() && m_SelectedItems.back() == Node->Object) + Flags |= ImGuiTreeNodeFlags_Selected; + } + if (m_edit_node == Node) + Flags |= ImGuiTreeNodeFlags_Selected; + ImGui::TreeNodeEx(Node->Name.c_str(), Flags); + + if (m_Flags.is(fMenuEdit)) + { + if (ImGui::OpenPopupOnItemClick2("MenuEdit", 1)) + { + m_UseMenuEdit = true; + m_edit_node = Node; + xr_strcpy(m_edit_path, Node->Path.c_str()); + xr_strcpy(m_edit_name, Node->Name.c_str()); + } + } + + if (ImGui::IsItemClicked()) + { + if (m_Flags.test(fMultiSelect)) + { + if (!ImGui::GetIO().KeyCtrl) + { + ClearSelectedItems(); + } + if (Node->Object->selected) + { + Node->Object->selected = false; + auto p = std::find_if(m_SelectedItems.begin(), m_SelectedItems.end(), [&Node](ListItem *a) + { return a == Node->Object; }); + VERIFY(p != m_SelectedItems.end()); + m_SelectedItems.erase(p); + } + else + { + Node->Object->selected = true; + m_SelectedItems.push_back(Node->Object); + if (!OnItemFocusedEvent.empty()) + OnItemFocusedEvent(Node->Object); + if (!OnItemsFocusedEvent.empty()) + OnItemsFocusedEvent(m_SelectedItems); + } + } + else + { + ClearSelectedItems(); + m_SelectedItems.push_back(Node->Object); + if (!OnItemFocusedEvent.empty()) + OnItemFocusedEvent(Node->Object); + } + } +} + +bool UIItemListForm::IsDrawFolder(Node *node) +{ + + if (node->Object) + return node->Object->Visible(); + bool result = m_Flags.test(fMenuEdit); + ; + for (Node &N : node->Nodes) + { + result = result | IsDrawFolder(&N); + } + return result; +} + +void UIItemListForm::IsItemClicked(Node *Node) +{ + ClearSelectedItems(); + Node->Object->selected = true; + m_SelectedItems.push_back(Node->Object); + if (!OnItemFocusedEvent.empty()) + OnItemFocusedEvent(Node->Object); + if (m_Flags.test(fMultiSelect)) + { + if (!OnItemsFocusedEvent.empty()) + OnItemsFocusedEvent(m_SelectedItems); + } +} + +bool UIItemListForm::IsFolderBullet(Node *Node) +{ + return false; +} + +bool UIItemListForm::IsFolderSelected(Node *Node) +{ + if (m_Flags.test(fMultiSelect)) + { + return Node->Object->selected; + } + else if (m_SelectedItems.size() && m_SelectedItems.back() == Node->Object) + { + return true; + } + return Node == m_edit_node; +} + +void UIItemListForm::EventRenameNode(Node *Node, const char *old_path, const char *new_path) +{ + EItemType type = TYPE_FOLDER; + if (Node->IsObject()) + { + type = TYPE_OBJECT; + Node->Object->key = new_path; + } + if (!OnItemRenameEvent.empty()) + OnItemRenameEvent(old_path, new_path, type); +} + +void UIItemListForm::EventRemoveNode(Node *Node, const char *path) +{ + EItemType type = TYPE_FOLDER; + if (Node->IsObject()) + { + type = TYPE_OBJECT; + } + if (!OnItemRemoveEvent.empty()) + OnItemRemoveEvent(path, type); +} + +void UIItemListForm::ClearSelectedItems() +{ + for (auto ptr : m_SelectedItems) + { + ptr->selected = false; + } + m_SelectedItems.clear(); +} + +void UIItemListForm::ClearObject(Node *N) +{ + for (int i = N->Nodes.size() - 1; i >= 0; i--) + { + if (N->Nodes[i].IsObject()) + { + N->Nodes.erase(N->Nodes.begin() + i); + } + else + { + ClearObject(&N->Nodes[i]); + } + } +} diff --git a/src/editors/xrEProps/UIItemListForm.h b/src/editors/xrEProps/UIItemListForm.h new file mode 100644 index 00000000000..3d72849dc20 --- /dev/null +++ b/src/editors/xrEProps/UIItemListForm.h @@ -0,0 +1,67 @@ +#pragma once +class XREPROPS_API UIItemListForm : public xrUI, private FolderHelper +{ + TOnILItemsFocused OnItemsFocusedEvent; + TOnILItemFocused OnItemFocusedEvent; + TOnItemRemove OnItemRemoveEvent; + TOnItemRename OnItemRenameEvent; + TOnItemCreate OnItemCreateEvent; + TOnItemClone OnItemCloneEvent; + +public: + UIItemListForm(); + virtual ~UIItemListForm(); + +public: + virtual void Draw(); + void ClearList(); + void RemoveSelectItem(); + void ClearSelected(); + void SelectItem(const char *name); + void AssignItems(ListItemsVec &items, const char *name_selection = nullptr, bool clear_Folder = true, bool save_selected = false); + IC const ListItemsVec &GetItems() const { return m_Items; } + bool GetSelected(RStringVec &items) const; + int GetSelected(LPCSTR pref, ListItemsVec &items, bool bOnlyObject); + +public: + enum + { + fMenuEdit = (1 << 0), + fMultiSelect = (1 << 1), + }; + Flags32 m_Flags; + +private: + void DrawMenuEdit(); + string4096 m_edit_name; + string4096 m_edit_path; + Node *m_edit_node; + +public: + IC void SetOnItemsFocusedEvent(TOnILItemsFocused e) { OnItemsFocusedEvent = e; } + IC void SetOnItemFocusedEvent(TOnILItemFocused e) { OnItemFocusedEvent = e; } + IC void SetOnItemRemoveEvent(TOnItemRemove e) { OnItemRemoveEvent = e; } + IC void SetOnItemRenameEvent(TOnItemRename e) { OnItemRenameEvent = e; } + IC void SetOnItemCreaetEvent(TOnItemCreate e) { OnItemCreateEvent = e; } + IC void SetOnItemCloneEvent(TOnItemClone e) { OnItemCloneEvent = e; } + +private: + virtual void DrawAfterFolderNode(bool is_open, Node *Node = 0); + virtual void DrawItem(Node *Node); + virtual bool IsDrawFolder(Node *Node); + virtual void IsItemClicked(Node *Node); + virtual bool IsFolderBullet(Node *Node); + virtual bool IsFolderSelected(Node *Node); + +private: + virtual void EventRenameNode(Node *Node, const char *old_path, const char *new_path); + virtual void EventRemoveNode(Node *Node, const char *path); + +public: + Node m_GeneralNode; + ListItemsVec m_Items; + ListItemsVec m_SelectedItems; + void ClearSelectedItems(); + bool m_UseMenuEdit; + void ClearObject(Node *Node); +}; diff --git a/src/editors/xrEProps/UIKeyPressForm.cpp b/src/editors/xrEProps/UIKeyPressForm.cpp new file mode 100644 index 00000000000..afa0968d2d4 --- /dev/null +++ b/src/editors/xrEProps/UIKeyPressForm.cpp @@ -0,0 +1,81 @@ +#include "stdafx.h" +UIKeyPressForm *UIKeyPressForm::Form = nullptr; +UIKeyPressForm::UIKeyPressForm() +{ + m_Ok = true; +} + +UIKeyPressForm::~UIKeyPressForm() +{ +} + +void UIKeyPressForm::Draw() +{ + if (!ImGui::BeginPopupModal("PressKey", 0, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove, true)) + { + ImGui::EndPopup(); + return; + } + if (!bOpen) + { + ImGui::CloseCurrentPopup(); + return; + } + if (fmod(m_TimeGlobal * 1000, 1000.f) > 500.f) + { + ImGui::TextColored(ImVec4(1, 0, 0, 1), "PRESS ANY KEY!!!"); + } + else + { + ImGui::Text("PRESS ANY KEY!!!"); + } + if (ImGui::Button("Cancel", ImVec2(-1, 0))) + { + m_Ok = false; + bOpen = false; + } + ImGui::EndPopup(); + /*else + { + ; + ImGui::CloseCurrentPopup(); + }*/ +} + +void UIKeyPressForm::Update(float timeGlobal) +{ + if (Form) + { + Form->m_TimeGlobal = timeGlobal; + Form->Draw(); + } +} + +void UIKeyPressForm::Show() +{ + VERIFY(!Form); + Form = xr_new(); +} + +bool UIKeyPressForm::SetResult(const xr_shortcut &result) +{ + if (Form && !Form->IsClosed()) + { + Form->m_Resutl = result; + Form->bOpen = false; + return true; + } + return false; +} + +bool UIKeyPressForm::GetResult(bool &Ok, xr_shortcut &result) +{ + if (Form && Form->IsClosed()) + { + Ok = Form->m_Ok; + result = Form->m_Resutl; + xr_delete(Form); + return true; + } + return false; +} diff --git a/src/editors/xrEProps/UIKeyPressForm.h b/src/editors/xrEProps/UIKeyPressForm.h new file mode 100644 index 00000000000..f89377e1a58 --- /dev/null +++ b/src/editors/xrEProps/UIKeyPressForm.h @@ -0,0 +1,20 @@ +#pragma once +class XREPROPS_API UIKeyPressForm : public xrUI +{ +public: + UIKeyPressForm(); + virtual ~UIKeyPressForm(); + virtual void Draw(); + +public: + static void Update(float timeGlobal); + static void Show(); + static bool SetResult(const xr_shortcut &result); + static bool GetResult(bool &Ok, xr_shortcut &result); + +private: + xr_shortcut m_Resutl; + float m_TimeGlobal; + static UIKeyPressForm *Form; + bool m_Ok; +}; \ No newline at end of file diff --git a/src/editors/xrEProps/UINumericVectorForm.cpp b/src/editors/xrEProps/UINumericVectorForm.cpp new file mode 100644 index 00000000000..6e138c83aa9 --- /dev/null +++ b/src/editors/xrEProps/UINumericVectorForm.cpp @@ -0,0 +1,75 @@ +#include "stdafx.h" + +UINumericVectorForm::UINumericVectorForm(const char *title, Fvector *data, Fvector *Reset, int decimal, Fvector *Min, Fvector *Max) +{ + m_Title = title; + m_Out = data; + m_Max = Max; + m_Min = Min; + m_Reset = Reset; + m_Edit = *m_Out; + m_Decimal = decimal; +} + +UINumericVectorForm::~UINumericVectorForm() +{ +} + +void UINumericVectorForm::Draw() +{ + ImGui::Begin(m_Title.c_str(), 0, ImGuiWindowFlags_::ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings); + ImGui::BeginGroup(); + ImGui::InputFloat("X", &m_Edit.x, 0.01, 0.1, m_Decimal); + ImGui::SameLine(0); + if (ImGui::Button("Ok")) + CLBOk(); + ImGui::EndGroup(); + ImGui::BeginGroup(); + ImGui::InputFloat("Y", &m_Edit.y, 0.01, 0.1, m_Decimal); + ImGui::SameLine(0); + if (ImGui::Button("Cancek")) + CLBCancel(); + ImGui::EndGroup(); + ImGui::BeginGroup(); + ImGui::InputFloat("Z", &m_Edit.z, 0.01, 0.1, m_Decimal); + ImGui::SameLine(0); + if (m_Reset) + if (ImGui::Button("Reset")) + CLBReset(); + ImGui::EndGroup(); + ImGui::End(); + if (m_Max) + { + if (m_Max->x < m_Edit.x) + m_Edit.x = m_Max->x; + if (m_Max->y < m_Edit.y) + m_Edit.y = m_Max->y; + if (m_Max->z < m_Edit.z) + m_Edit.z = m_Max->z; + } + if (m_Min) + { + if (m_Min->x > m_Edit.x) + m_Edit.x = m_Min->x; + if (m_Min->y > m_Edit.y) + m_Edit.y = m_Min->y; + if (m_Min->z > m_Edit.z) + m_Edit.z = m_Min->z; + } +} + +void UINumericVectorForm::CLBOk() +{ + *m_Out = m_Edit; + bOpen = false; +} + +void UINumericVectorForm::CLBCancel() +{ + bOpen = false; +} + +void UINumericVectorForm::CLBReset() +{ + m_Edit = *m_Reset; +} diff --git a/src/editors/xrEProps/UINumericVectorForm.h b/src/editors/xrEProps/UINumericVectorForm.h new file mode 100644 index 00000000000..a030c443b7c --- /dev/null +++ b/src/editors/xrEProps/UINumericVectorForm.h @@ -0,0 +1,20 @@ +#pragma once +class XREPROPS_API UINumericVectorForm : public xrUI +{ +public: + UINumericVectorForm(const char *title, Fvector *data, Fvector *Reset = 0, int decimal = 0, Fvector *Min = 0, Fvector *Max = 0); + virtual ~UINumericVectorForm(); + virtual void Draw(); + +private: + void CLBOk(); + void CLBCancel(); + void CLBReset(); + Fvector m_Edit; + xr_string m_Title; + Fvector *m_Reset; + Fvector *m_Out; + Fvector *m_Min; + Fvector *m_Max; + int m_Decimal; +}; diff --git a/src/editors/xrEProps/UITextForm.cpp b/src/editors/xrEProps/UITextForm.cpp new file mode 100644 index 00000000000..ec33fb040b9 --- /dev/null +++ b/src/editors/xrEProps/UITextForm.cpp @@ -0,0 +1,92 @@ +#include "stdafx.h" +UITextForm *UITextForm::Form = nullptr; +UITextForm::UITextForm(const char *text) : m_Text(text) +{ + m_Ok = false; + xr_strcpy(m_EditText, m_Text.c_str()); +} + +UITextForm::~UITextForm() +{ +} + +void UITextForm::Draw() +{ + ImGui::BeginGroup(); + if (ImGui::Button("Ok")) + CLBOk(); + ImGui::SameLine(0); + if (ImGui::Button("Cancel")) + CLBCancel(); + ImGui::SameLine(150); + + if (ImGui::Button("Load")) + CLBLoad(); + ImGui::SameLine(0); + if (ImGui::Button("Save")) + CLBSave(); + ImGui::SameLine(0); + if (ImGui::Button("Clear")) + CLBClear(); + + ImGui::EndGroup(); + ImGui::InputTextMultiline("", m_EditText, sizeof(m_EditText), ImVec2(500, 200)); +} + +void UITextForm::RunEditor(const char *str) +{ + VERIFY(!Form); + Form = xr_new(str); +} + +void UITextForm::Update() +{ + if (Form && !Form->IsClosed()) + { + if (ImGui::BeginPopupModal("TextEditor", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoResize)) + { + Form->Draw(); + ImGui::EndPopup(); + } + } +} + +bool UITextForm::GetResult(bool &change, xr_string &result) +{ + if (Form->IsClosed()) + { + change = Form->m_Ok; + result = Form->m_Text; + xr_delete(Form); + return true; + } + + return false; +} + +void UITextForm::CLBOk() +{ + m_Text = m_EditText; + bOpen = false; + m_Ok = true; +} + +void UITextForm::CLBCancel() +{ + bOpen = false; +} + +void UITextForm::CLBLoad() +{ + R_ASSERT(0); +} + +void UITextForm::CLBSave() +{ + R_ASSERT(0); +} + +void UITextForm::CLBClear() +{ + m_EditText[0] = 0; +} diff --git a/src/editors/xrEProps/UITextForm.h b/src/editors/xrEProps/UITextForm.h new file mode 100644 index 00000000000..3d89ff0d226 --- /dev/null +++ b/src/editors/xrEProps/UITextForm.h @@ -0,0 +1,26 @@ +#pragma once +class XREPROPS_API UITextForm : public xrUI +{ +public: + UITextForm(const char *str); + virtual ~UITextForm(); + virtual void Draw(); + static void RunEditor(const char *str); + static void Update(); + static bool GetResult(bool &change, xr_string &result); + +private: + void CLBOk(); + void CLBCancel(); + + void CLBLoad(); + void CLBSave(); + void CLBClear(); + +private: + bool m_Ok; + xr_string m_Text; + string4096 m_EditText; + + static UITextForm *Form; +}; diff --git a/src/editors/xrEProps/stdafx.cpp b/src/editors/xrEProps/stdafx.cpp new file mode 100644 index 00000000000..1577c4e3bcb --- /dev/null +++ b/src/editors/xrEProps/stdafx.cpp @@ -0,0 +1 @@ +#include "stdafx.h" \ No newline at end of file diff --git a/src/editors/xrEProps/stdafx.h b/src/editors/xrEProps/stdafx.h new file mode 100644 index 00000000000..57dad3c68d7 --- /dev/null +++ b/src/editors/xrEProps/stdafx.h @@ -0,0 +1,37 @@ +#pragma once +#ifdef XREPROPS_EXPORTS +#define smart_cast dynamic_cast +#define XREPROPS_API __declspec(dllexport) +#else +#define XREPROPS_API __declspec(dllimport) +#endif + +#include +#include "Common/FSMacros.hpp" +#include "Common/Platform.hpp" +#include "..\..\xrCore\xrCore.h" +#ifdef XREPROPS_EXPORTS +inline void not_implemented() +{ + if (IsDebuggerPresent()) + DebugBreak(); + else + R_ASSERT(0); +} +#endif + +#include "..\xrEUI\stdafx.h" +#include "..\..\xrServerEntities\gametype_chooser.h" +#include "..\..\xrServerEntities\xrEProps.h" +#include "..\..\xrCore\ChooseTypes.H" +#include "FolderLib.h" +#include "Tree\Base\UITreeItem.h" +#include "ItemListHelper.h" +#include "UITextForm.h" +#include "UINumericVectorForm.h" +#include "Tree\Properties\UIPropertiesItem.h" +#include "Tree\Properties\UIPropertiesForm.h" +#include "UIItemListForm.h" +#include "Tree\Choose\UIChooseFormItem.h" +#include "Tree\Choose\UIChooseForm.h" +#include "UIKeyPressForm.h" diff --git a/src/editors/xrEProps/xrEProps.vcxproj b/src/editors/xrEProps/xrEProps.vcxproj new file mode 100644 index 00000000000..c98e654c01d --- /dev/null +++ b/src/editors/xrEProps/xrEProps.vcxproj @@ -0,0 +1,77 @@ + + + + + + + {6D47AFC7-0557-4BBF-8902-B248F3621419} + xrEProps + xrEProps + + + + + + + + + + + + + + + + stdafx.h + XREPROPS_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + + + + + + + + + Create + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {a0f7d1fb-59a7-4717-a7e4-96f37e91998e} + + + {7e28883c-db86-4ee8-813a-991ba20c68c9} + + + + + + \ No newline at end of file diff --git a/src/editors/xrEProps/xrEProps.vcxproj.filters b/src/editors/xrEProps/xrEProps.vcxproj.filters new file mode 100644 index 00000000000..b9af0b0c099 --- /dev/null +++ b/src/editors/xrEProps/xrEProps.vcxproj.filters @@ -0,0 +1,120 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {1ed51885-0799-4071-ae4b-df1eae541f8b} + + + {46ad08be-8860-4e32-ab21-23d51c8ccb56} + + + {195fe88c-3b69-456c-b129-41385cf1459e} + + + {ed887730-9b8c-4e31-8094-8b984aedcfbd} + + + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Tree\Base + + + Tree\Properties + + + Tree\Properties + + + Tree\Properties + + + Tree\Properties + + + Tree\Choose + + + Tree\Choose + + + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Tree\Base + + + Tree\Properties + + + Tree\Properties + + + Tree\Choose + + + Tree\Choose + + + + + + \ No newline at end of file diff --git a/src/editors/xrEUI/imconfig.h b/src/editors/xrEUI/imconfig.h new file mode 100644 index 00000000000..ffa93738c09 --- /dev/null +++ b/src/editors/xrEUI/imconfig.h @@ -0,0 +1,108 @@ +//----------------------------------------------------------------------------- +// COMPILE-TIME OPTIONS FOR DEAR IMGUI +// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. +// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. +//----------------------------------------------------------------------------- +// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/branch with your modifications to imconfig.h) +// B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h" +// If you do so you need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include +// the imgui*.cpp files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. +// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. +// Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using. +//----------------------------------------------------------------------------- + +#pragma once +//---- Define assertion handler. Defaults to calling assert(). +// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. +//#define IM_ASSERT(_EXPR) MyAssert(_EXPR) +//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts + +//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows +// Using dear imgui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. +//#define IMGUI_API __declspec( dllexport ) +//#define IMGUI_API __declspec( dllimport ) + +//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names. +//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +//---- Disable all of Dear ImGui or don't implement standard windows. +// It is very strongly recommended to NOT disable the demo windows during development. Please read comments in imgui_demo.cpp. +//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. +//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended. +//#define IMGUI_DISABLE_METRICS_WINDOW // Disable debug/metrics window: ShowMetricsWindow() will be empty. + +//---- Don't implement some functions to reduce linkage requirements. +//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. +//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow. +//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime). +//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). +//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) +//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. +//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. +//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). + +//---- Include imgui_user.h at the end of imgui.h as a convenience +//#define IMGUI_INCLUDE_IMGUI_USER_H + +//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) +//#define IMGUI_USE_BGRA_PACKED_COLOR + +//---- Use 32-bit for ImWchar (default is 16-bit) to support full unicode code points. +//#define IMGUI_USE_WCHAR32 + +//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version +// By default the embedded implementations are declared static and not available outside of imgui cpp files. +//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" +//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" +//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION + +//---- Unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined, use the much faster STB sprintf library implementation of vsnprintf instead of the one from the default C library. +// Note that stb_sprintf.h is meant to be provided by the user and available in the include path at compile time. Also, the compatibility checks of the arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by STB sprintf. +// #define IMGUI_USE_STB_SPRINTF + +//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. +// This will be inlined as part of ImVec2 and ImVec4 class declarations. +/* +#define IM_VEC2_CLASS_EXTRA \ + ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ + operator MyVec2() const { return MyVec2(x,y); } + +#define IM_VEC4_CLASS_EXTRA \ + ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ + operator MyVec4() const { return MyVec4(x,y,z,w); } +*/ + +//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. +// Your renderer back-end will need to support it (most example renderer back-ends support both 16/32-bit indices). +// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. +// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. +//#define ImDrawIdx unsigned int + +//---- Override ImDrawCallback signature (will need to modify renderer back-ends accordingly) +// struct ImDrawList; +// struct ImDrawCmd; +// typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); +//#define ImDrawCallback MyImDrawCallback + +//---- Debug Tools: Macro to break in Debugger +// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) +//#define IM_DEBUG_BREAK IM_ASSERT(0) +//#define IM_DEBUG_BREAK __debugbreak() + +//---- Debug Tools: Have the Item Picker break in the ItemAdd() function instead of ItemHoverable(), +// (which comes earlier in the code, will catch a few extra items, allow picking items other than Hovered one.) +// This adds a small runtime cost which is why it is not enabled by default. +//#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX + +//---- Debug Tools: Enable slower asserts +//#define IMGUI_DEBUG_PARANOID + +//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. +/* +namespace ImGui +{ + void MyFunction(const char* name, const MyMatrix44& v); +} +*/ +#include "stdafx.h" diff --git a/src/editors/xrEUI/imgui.cpp b/src/editors/xrEUI/imgui.cpp new file mode 100644 index 00000000000..d3e431cc643 --- /dev/null +++ b/src/editors/xrEUI/imgui.cpp @@ -0,0 +1,19756 @@ +// dear imgui, 1.88 WIP +// (main code and documentation) + +// Help: +// - Read FAQ at http://dearimgui.org/faq +// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. +// Read imgui.cpp for details, links and comments. + +// Resources: +// - FAQ http://dearimgui.org/faq +// - Homepage & latest https://github.com/ocornut/imgui +// - Releases & changelog https://github.com/ocornut/imgui/releases +// - Gallery https://github.com/ocornut/imgui/issues/5243 (please post your screenshots/video there!) +// - Wiki https://github.com/ocornut/imgui/wiki (lots of good stuff there) +// - Glossary https://github.com/ocornut/imgui/wiki/Glossary +// - Issues & support https://github.com/ocornut/imgui/issues + +// Getting Started? +// - For first-time users having issues compiling/linking/running or issues loading fonts: +// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. + +// Developed by Omar Cornut and every direct or indirect contributors to the GitHub. +// See LICENSE.txt for copyright and licensing details (standard MIT License). +// This library is free but needs your support to sustain development and maintenance. +// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com". +// Individuals: you can support continued development via donations. See docs/README or web page. + +// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library. +// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without +// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't +// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you +// to a better solution or official support for them. + +/* + +Index of this file: + +DOCUMENTATION + +- MISSION STATEMENT +- END-USER GUIDE +- PROGRAMMER GUIDE + - READ FIRST + - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI + - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE + - HOW A SIMPLE APPLICATION MAY LOOK LIKE + - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE + - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS +- API BREAKING CHANGES (read me when you update!) +- FREQUENTLY ASKED QUESTIONS (FAQ) + - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer) + +CODE +(search for "[SECTION]" in the code to find them) + +// [SECTION] INCLUDES +// [SECTION] FORWARD DECLARATIONS +// [SECTION] CONTEXT AND MEMORY ALLOCATORS +// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) +// [SECTION] MISC HELPERS/UTILITIES (Geometry functions) +// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) +// [SECTION] MISC HELPERS/UTILITIES (File functions) +// [SECTION] MISC HELPERS/UTILITIES (ImText* functions) +// [SECTION] MISC HELPERS/UTILITIES (Color functions) +// [SECTION] ImGuiStorage +// [SECTION] ImGuiTextFilter +// [SECTION] ImGuiTextBuffer +// [SECTION] ImGuiListClipper +// [SECTION] STYLING +// [SECTION] RENDER HELPERS +// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) +// [SECTION] INPUTS +// [SECTION] ERROR CHECKING +// [SECTION] LAYOUT +// [SECTION] SCROLLING +// [SECTION] TOOLTIPS +// [SECTION] POPUPS +// [SECTION] KEYBOARD/GAMEPAD NAVIGATION +// [SECTION] DRAG AND DROP +// [SECTION] LOGGING/CAPTURING +// [SECTION] SETTINGS +// [SECTION] VIEWPORTS, PLATFORM WINDOWS +// [SECTION] DOCKING +// [SECTION] PLATFORM DEPENDENT HELPERS +// [SECTION] METRICS/DEBUGGER WINDOW +// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL) + +*/ + +//----------------------------------------------------------------------------- +// DOCUMENTATION +//----------------------------------------------------------------------------- + +/* + + MISSION STATEMENT + ================= + + - Easy to use to create code-driven and data-driven tools. + - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools. + - Easy to hack and improve. + - Minimize setup and maintenance. + - Minimize state storage on user side. + - Minimize state synchronization. + - Portable, minimize dependencies, run on target (consoles, phones, etc.). + - Efficient runtime and memory consumption. + + Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes: + + - Doesn't look fancy, doesn't animate. + - Limited layout features, intricate layouts are typically crafted in code. + + + END-USER GUIDE + ============== + + - Double-click on title bar to collapse window. + - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin(). + - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents). + - Click and drag on any empty space to move window. + - TAB/SHIFT+TAB to cycle through keyboard editable fields. + - CTRL+Click on a slider or drag box to input value as text. + - Use mouse wheel to scroll. + - Text editor: + - Hold SHIFT or use mouse to select text. + - CTRL+Left/Right to word jump. + - CTRL+Shift+Left/Right to select words. + - CTRL+A our Double-Click to select all. + - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/ + - CTRL+Z,CTRL+Y to undo/redo. + - ESCAPE to revert text to its original value. + - Controls are automatically adjusted for OSX to match standard OSX text editing operations. + - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard. + - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://dearimgui.org/controls_sheets + + + PROGRAMMER GUIDE + ================ + + READ FIRST + ---------- + - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki) + - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or + destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs. + - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features. + - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build. + - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori). + You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki. + - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances. + For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI, + where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches. + - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right. + - This codebase is also optimized to yield decent performances with typical "Debug" builds settings. + - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected). + If you get an assert, read the messages and comments around the assert. + - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace. + - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types. + See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that. + However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase. + - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!). + + + HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI + ---------------------------------------------- + - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h) + - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master". + - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file. + - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes. + If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed + from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will + likely be a comment about it. Please report any issue to the GitHub page! + - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file. + - Try to keep your copy of Dear ImGui reasonably up to date. + + + GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE + --------------------------------------------------------------- + - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library. + - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder. + - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system. + It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL). + - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types. + - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. + - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide. + Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" + phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render(). + - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code. + - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder. + + + HOW A SIMPLE APPLICATION MAY LOOK LIKE + -------------------------------------- + EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder). + The sub-folders in examples/ contain examples applications following this structure. + + // Application init: create a dear imgui context, setup some options, load fonts + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls. + // TODO: Fill optional fields of the io structure later. + // TODO: Load TTF/OTF fonts if you don't want to use the default font. + + // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp) + ImGui_ImplWin32_Init(hwnd); + ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); + + // Application main loop + while (true) + { + // Feed inputs to dear imgui, start new frame + ImGui_ImplDX11_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); + + // Any application code here + ImGui::Text("Hello, world!"); + + // Render dear imgui into screen + ImGui::Render(); + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + g_pSwapChain->Present(1, 0); + } + + // Shutdown + ImGui_ImplDX11_Shutdown(); + ImGui_ImplWin32_Shutdown(); + ImGui::DestroyContext(); + + EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE + + // Application init: create a dear imgui context, setup some options, load fonts + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls. + // TODO: Fill optional fields of the io structure later. + // TODO: Load TTF/OTF fonts if you don't want to use the default font. + + // Build and load the texture atlas into a texture + // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer) + int width, height; + unsigned char* pixels = NULL; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + + // At this point you've got the texture data and you need to upload that to your graphic system: + // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'. + // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID. + MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32) + io.Fonts->SetTexID((void*)texture); + + // Application main loop + while (true) + { + // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc. + // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends) + io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds) + io.DisplaySize.x = 1920.0f; // set the current display width + io.DisplaySize.y = 1280.0f; // set the current display height here + io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position + io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states + io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states + + // Call NewFrame(), after this point you can use ImGui::* functions anytime + // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere) + ImGui::NewFrame(); + + // Most of your application code here + ImGui::Text("Hello, world!"); + MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); + MyGameRender(); // may use any Dear ImGui functions as well! + + // Render dear imgui, swap buffers + // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code) + ImGui::EndFrame(); + ImGui::Render(); + ImDrawData* draw_data = ImGui::GetDrawData(); + MyImGuiRenderFunction(draw_data); + SwapBuffers(); + } + + // Shutdown + ImGui::DestroyContext(); + + To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application, + you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! + Please read the FAQ and example applications for details about this! + + + HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE + --------------------------------------------- + The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function. + + void void MyImGuiRenderFunction(ImDrawData* draw_data) + { + // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled + // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering. + // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize + // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize + // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color. + ImVec2 clip_off = draw_data->DisplayPos; + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui + const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) + { + pcmd->UserCallback(cmd_list, pcmd); + } + else + { + // Project scissor/clipping rectangles into framebuffer space + ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); + ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + + // We are using scissoring to clip some objects. All low-level graphics API should support it. + // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches + // (some elements visible outside their bounds) but you can fix that once everything else works! + // - Clipping coordinates are provided in imgui coordinates space: + // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size + // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values. + // - In the interest of supporting multi-viewport applications (see 'docking' branch on github), + // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space. + // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min) + MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y); + + // The texture for the draw call is specified by pcmd->GetTexID(). + // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization. + MyEngineBindTexture((MyTexture*)pcmd->GetTexID()); + + // Render 'pcmd->ElemCount/3' indexed triangles. + // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices. + MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset); + } + } + } + } + + + USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS + ------------------------------------------ + - The gamepad/keyboard navigation is fairly functional and keeps being improved. + - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse! + - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787 + - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable. + - Keyboard: + - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. + - Internally: NewFrame() will automatically fill io.NavInputs[] based on backend's io.AddKeyEvent() calls. + - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), + the io.WantCaptureKeyboard flag will be set. For more advanced uses, you may want to read from: + - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set. + - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used). + - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions. + Please reach out if you think the game vs navigation input sharing could be improved. + - Gamepad: + - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. + - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys. + For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly. + Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.). + - Internally: NewFrame() will automatically fill io.NavInputs[] based on backend's io.AddKeyEvent() + io.AddKeyAnalogEvent() calls. + - BEFORE 1.87, BACKENDS USED TO WRITE DIRECTLY TO io.NavInputs[]. This is going to be obsoleted in the future. Please call io functions instead! + - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://dearimgui.org/controls_sheets + - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing, + with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved. + - Mouse: + - PS4/PS5 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback. + - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard. + - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag. + Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements. + When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved. + When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that. + (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse moving back and forth!) + (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want + to set a boolean to ignore your other external mouse positions until the external source is moved again.) + + + API BREAKING CHANGES + ==================== + + Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix. + Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code. + When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. + You can read releases logs https://github.com/ocornut/imgui/releases for more details. + +(Docking/Viewport Branch) + - 2022/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that: + - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore. + you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos) + - likewise io.MousePos and GetMousePos() will use OS coordinates. + If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos. + + - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary. + - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO. + - 2022/01/20 (1.87) - inputs: reworded gamepad IO. + - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values. + - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used). + - 2022/01/17 (1.87) - inputs: reworked mouse IO. + - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent() + - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent() + - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent() + - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only] + note: for all calls to IO new functions, the Dear ImGui context should be bound/current. + - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details. + - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX) + - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX) + - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes). + - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiKey_ModXXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiKey_ModXXX values.* + - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert. + - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper. + - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum. + - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'. + - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019) + - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen() + - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x + - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing()); + - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect + - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex + - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings + - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function. + - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful. + - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019): + - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList() + - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder + - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID(). + - if you are using official backends from the source tree: you have nothing to do. + - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID(). + - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags. + - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft + - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight + - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc. + flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API. + breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners": + - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use) + - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use) + - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use) + - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f. + this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok. + the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts. + legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise). + - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018): + - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY() + - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing. + - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future. + - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'. + - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed. + - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete). + - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete). + - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete). + - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags. + - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags. + - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API. + - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018): + - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit(). + - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg + - ImGuiInputTextCallback -> use ImGuiTextEditCallback + - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData + - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete). + - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added! + - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API. + - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures + - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/. + - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018): + - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend + - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) + - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) + - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT + - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT + - removed redirecting functions names that were marked obsolete in 1.61 (May 2018): + - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision. + - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter. + - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed). + - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently). + - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. + - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory. + - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result. + - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now! + - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar(). + replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). + worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions: + - if you omitted the 'power' parameter (likely!), you are not affected. + - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct. + - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. + see https://github.com/ocornut/imgui/issues/3361 for all details. + kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used. + for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`. + - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime. + - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. + - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79] + - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. + - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). + - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more. + - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead. + - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value. + - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017): + - ShowTestWindow() -> use ShowDemoWindow() + - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow) + - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) + - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f) + - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing() + - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg + - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding + - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap + - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS + - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API. + - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it). + - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert. + - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency. + - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency. + - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017): + - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed + - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) + - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding() + - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f) + - ImFont::Glyph -> use ImFontGlyph + - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function. + if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix. + The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay). + If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you. + - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete). + - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete). + - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71. + - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have + overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering. + This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows. + Please reach out if you are affected. + - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). + - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c). + - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now. + - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete). + - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). + - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete). + - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value! + - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). + - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! + - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete). + - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects. + - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags. + - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files. + - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete). + - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h. + If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths. + - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427) + - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp. + NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED. + Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions. + - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent). + - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete). + - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly). + - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature. + - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency. + - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time. + - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete). + - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.). + old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports. + when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call. + in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function. + - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set. + - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details. + - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more. + If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format. + To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code. + If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them. + - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format", + consistent with other functions. Kept redirection functions (will obsolete). + - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value. + - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch). + - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now. + - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically. + - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums. + - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment. + - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display. + - 2018/02/07 (1.60) - reorganized context handling to be more explicit, + - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END. + - removed Shutdown() function, as DestroyContext() serve this purpose. + - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance. + - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts. + - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts. + - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths. + - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete). + - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete). + - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData. + - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side. + - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete). + - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags + - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame. + - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set. + - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete). + - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete). + - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete). + - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete). + - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete). + - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed. + - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up. + Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions. + - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency. + - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg. + - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding. + - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); + - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency. + - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it. + - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details. + removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting. + IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly) + IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow) + IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior] + - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead! + - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete). + - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete). + - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete). + - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)". + - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)! + - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete). + - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete). + - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency. + - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix. + - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type. + - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely. + - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete). + - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete). + - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton(). + - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu. + - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options. + - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))' + - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse + - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset. + - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity. + - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild(). + - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it. + - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc. + - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal. + - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. + If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. + This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color: + ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); } + If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. + - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). + - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. + - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). + - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. + - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337). + - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) + - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). + - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. + - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. + - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. + - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. + - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. + GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. + GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! + - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize + - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. + - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason + - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. + you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. + - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. + this necessary change will break your rendering function! the fix should be very easy. sorry for that :( + - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. + - the signature of the io.RenderDrawListsFn handler has changed! + old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) + new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). + parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount' + ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new. + ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'. + - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer. + - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! + - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade! + - 2015/07/10 (1.43) - changed SameLine() parameters from int to float. + - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete). + - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount. + - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence + - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry! + - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). + - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). + - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. + - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. + - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). + - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50. + - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API + - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. + - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. + - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50. + - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing + - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50. + - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) + - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50. + - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. + - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. + - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior + - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() + - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) + - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. + - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. + - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. + - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..]; + - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier); + you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation. + - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID() + - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) + - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets + - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) + - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) + - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility + - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() + - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) + - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) + - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() + - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn + - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) + - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite + - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes + + + FREQUENTLY ASKED QUESTIONS (FAQ) + ================================ + + Read all answers online: + https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url) + Read all answers locally (with a text editor or ideally a Markdown viewer): + docs/FAQ.md + Some answers are copied down here to facilitate searching in code. + + Q&A: Basics + =========== + + Q: Where is the documentation? + A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++. + - Run the examples/ and explore them. + - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function. + - The demo covers most features of Dear ImGui, so you can read the code and see its output. + - See documentation and comments at the top of imgui.cpp + effectively imgui.h. + - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the + examples/ folder to explain how to integrate Dear ImGui with your own engine/application. + - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links. + - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful. + - Your programming IDE is your friend, find the type or function declaration to find comments + associated with it. + + Q: What is this library called? + Q: Which version should I get? + >> This library is called "Dear ImGui", please don't call it "ImGui" :) + >> See https://www.dearimgui.org/faq for details. + + Q&A: Integration + ================ + + Q: How to get started? + A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt. + + Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application? + A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! + >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this. + + Q. How can I enable keyboard controls? + Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display) + Q: I integrated Dear ImGui in my engine and little squares are showing instead of text... + Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around... + Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries... + >> See https://www.dearimgui.org/faq + + Q&A: Usage + ---------- + + Q: About the ID Stack system.. + - Why is my widget not reacting when I click on it? + - How can I have widgets with an empty label? + - How can I have multiple widgets with the same label? + - How can I have multiple windows with the same label? + Q: How can I display an image? What is ImTextureID, how does it works? + Q: How can I use my own math types instead of ImVec2/ImVec4? + Q: How can I interact with standard C++ types (such as std::string and std::vector)? + Q: How can I display custom shapes? (using low-level ImDrawList API) + >> See https://www.dearimgui.org/faq + + Q&A: Fonts, Text + ================ + + Q: How should I handle DPI in my application? + Q: How can I load a different font than the default? + Q: How can I easily use icons in my application? + Q: How can I load multiple fonts? + Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? + >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md + + Q&A: Concerns + ============= + + Q: Who uses Dear ImGui? + Q: Can you create elaborate/serious tools with Dear ImGui? + Q: Can you reskin the look of Dear ImGui? + Q: Why using C++ (as opposed to C)? + >> See https://www.dearimgui.org/faq + + Q&A: Community + ============== + + Q: How can I help? + A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui! + We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts. + This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project. + - Individuals: you can support continued development via PayPal donations. See README. + - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt + and see how you want to help and can help! + - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc. + You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers. + But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions. + - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately). + +*/ + +//------------------------------------------------------------------------- +// [SECTION] INCLUDES +//------------------------------------------------------------------------- + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif +#include "imgui_internal.h" + +// System includes +#include // toupper +#include // vsnprintf, sscanf, printf +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled +#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) +#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS +#endif + +// [Windows] OS specific includes (optional) +#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) +#define IMGUI_DISABLE_WIN32_FUNCTIONS +#endif +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#ifndef __MINGW32__ +#include // _wfopen, OpenClipboard +#else +#include +#endif +#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions +#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS +#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS +#endif +#endif + +// [Apple] OS specific includes +#if defined(__APPLE__) +#include +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning(disable : 4127) // condition expression is constant +#pragma warning(disable : 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later +#pragma warning(disable : 5054) // operator '|': deprecated between enumerations of different types +#endif +#pragma warning(disable : 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). +#pragma warning(disable : 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). +#pragma warning(disable : 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int' +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#elif defined(__GNUC__) +// We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association. +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked +#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif + +// Debug options +#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL +#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window +#define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower) + +// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. +static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in +static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear + +// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend) +static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow(). +static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time. +static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved. + +// Docking +static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport. +static const float DOCKING_SPLITTER_SIZE = 2.0f; + +//------------------------------------------------------------------------- +// [SECTION] FORWARD DECLARATIONS +//------------------------------------------------------------------------- + +static void SetCurrentWindow(ImGuiWindow *window); +static void FindHoveredWindow(); +static ImGuiWindow *CreateNewWindow(const char *name, ImGuiWindowFlags flags); +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow *window); + +static void AddDrawListToDrawData(ImVector *out_list, ImDrawList *draw_list); +static void AddWindowToSortBuffer(ImVector *out_sorted_windows, ImGuiWindow *window); + +// Settings +static void WindowSettingsHandler_ClearAll(ImGuiContext *, ImGuiSettingsHandler *); +static void *WindowSettingsHandler_ReadOpen(ImGuiContext *, ImGuiSettingsHandler *, const char *name); +static void WindowSettingsHandler_ReadLine(ImGuiContext *, ImGuiSettingsHandler *, void *entry, const char *line); +static void WindowSettingsHandler_ApplyAll(ImGuiContext *, ImGuiSettingsHandler *); +static void WindowSettingsHandler_WriteAll(ImGuiContext *, ImGuiSettingsHandler *, ImGuiTextBuffer *buf); + +// Platform Dependents default implementation for IO functions +static const char *GetClipboardTextFn_DefaultImpl(void *user_data); +static void SetClipboardTextFn_DefaultImpl(void *user_data, const char *text); +static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport *viewport, ImGuiPlatformImeData *data); + +namespace ImGui +{ + // Navigation + static void NavUpdate(); + static void NavUpdateWindowing(); + static void NavUpdateWindowingOverlay(); + static void NavUpdateCancelRequest(); + static void NavUpdateCreateMoveRequest(); + static void NavUpdateCreateTabbingRequest(); + static float NavUpdatePageUpPageDown(); + static inline void NavUpdateAnyRequestFlag(); + static void NavUpdateCreateWrappingRequest(); + static void NavEndFrame(); + static bool NavScoreItem(ImGuiNavItemData *result); + static void NavApplyItemToResult(ImGuiNavItemData *result); + static void NavProcessItem(); + static void NavProcessItemForTabbingRequest(ImGuiID id); + static ImVec2 NavCalcPreferredRefPos(); + static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow *nav_window); + static ImGuiWindow *NavRestoreLastChildNavWindow(ImGuiWindow *window); + static void NavRestoreLayer(ImGuiNavLayer layer); + static void NavRestoreHighlightAfterMove(); + static int FindWindowFocusIndex(ImGuiWindow *window); + + // Error Checking and Debug Tools + static void ErrorCheckNewFrameSanityChecks(); + static void ErrorCheckEndFrameSanityChecks(); + static void UpdateDebugToolItemPicker(); + static void UpdateDebugToolStackQueries(); + + // Misc + static void UpdateSettings(); + static void UpdateKeyboardInputs(); + static void UpdateMouseInputs(); + static void UpdateMouseWheel(); + static bool UpdateWindowManualResize(ImGuiWindow *window, const ImVec2 &size_auto_fit, int *border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect &visibility_rect); + static void RenderWindowOuterBorders(ImGuiWindow *window); + static void RenderWindowDecorations(ImGuiWindow *window, const ImRect &title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size); + static void RenderWindowTitleBarContents(ImGuiWindow *window, const ImRect &title_bar_rect, const char *name, bool *p_open); + static void RenderDimmedBackgroundBehindWindow(ImGuiWindow *window, ImU32 col); + static void RenderDimmedBackgrounds(); + static ImGuiWindow *FindBlockingModal(ImGuiWindow *window); + + // Viewports + const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter. + static ImGuiViewportP *AddUpdateViewport(ImGuiWindow *window, ImGuiID id, const ImVec2 &platform_pos, const ImVec2 &size, ImGuiViewportFlags flags); + static void DestroyViewport(ImGuiViewportP *viewport); + static void UpdateViewportsNewFrame(); + static void UpdateViewportsEndFrame(); + static void WindowSelectViewport(ImGuiWindow *window); + static void WindowSyncOwnedViewport(ImGuiWindow *window, ImGuiWindow *parent_window_in_stack); + static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow *window, ImGuiViewportP *host_viewport); + static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow *window); + static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow *window); + static int FindPlatformMonitorForPos(const ImVec2 &pos); + static int FindPlatformMonitorForRect(const ImRect &r); + static void UpdateViewportPlatformMonitor(ImGuiViewportP *viewport); + +} + +//----------------------------------------------------------------------------- +// [SECTION] CONTEXT AND MEMORY ALLOCATORS +//----------------------------------------------------------------------------- + +// DLL users: +// - Heaps and globals are not shared across DLL boundaries! +// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from. +// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL). +// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. +// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in). + +// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL. +// - ImGui::CreateContext() will automatically set this pointer if it is NULL. +// Change to a different context by calling ImGui::SetCurrentContext(). +// - Important: Dear ImGui functions are not thread-safe because of this pointer. +// If you want thread-safety to allow N threads to access N different contexts: +// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h: +// struct ImGuiContext; +// extern thread_local ImGuiContext* MyImGuiTLS; +// #define GImGui MyImGuiTLS +// And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword. +// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 +// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace. +// - DLL users: read comments above. +#ifndef GImGui +ImGuiContext *GImGui = NULL; +#endif + +// Memory Allocator functions. Use SetAllocatorFunctions() to change them. +// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction. +// - DLL users: read comments above. +#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS +static void *MallocWrapper(size_t size, void *user_data) +{ + IM_UNUSED(user_data); + return malloc(size); +} +static void FreeWrapper(void *ptr, void *user_data) +{ + IM_UNUSED(user_data); + free(ptr); +} +#else +static void *MallocWrapper(size_t size, void *user_data) +{ + IM_UNUSED(user_data); + IM_UNUSED(size); + IM_ASSERT(0); + return NULL; +} +static void FreeWrapper(void *ptr, void *user_data) +{ + IM_UNUSED(user_data); + IM_UNUSED(ptr); + IM_ASSERT(0); +} +#endif +static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper; +static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper; +static void *GImAllocatorUserData = NULL; + +//----------------------------------------------------------------------------- +// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) +//----------------------------------------------------------------------------- + +ImGuiStyle::ImGuiStyle() +{ + Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui. + DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. + WindowPadding = ImVec2(8, 8); // Padding within a window + WindowRounding = 0.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. + WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested. + WindowMinSize = ImVec2(32, 32); // Minimum window size + WindowTitleAlign = ImVec2(0.0f, 0.5f); // Alignment for title bar text + WindowMenuButtonPosition = ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left. + ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows + ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested. + PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows + PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested. + FramePadding = ImVec2(4, 3); // Padding within a framed rectangle (used by most widgets) + FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). + FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested. + ItemSpacing = ImVec2(8, 4); // Horizontal and vertical spacing between widgets/lines + ItemInnerSpacing = ImVec2(4, 4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + CellPadding = ImVec2(4, 2); // Padding within a table cell + TouchExtraPadding = ImVec2(0, 0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). + ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar + GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar + GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. + TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. + TabBorderSize = 0.0f; // Thickness of border around tabs. + TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. + ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. + ButtonTextAlign = ImVec2(0.5f, 0.5f); // Alignment of button text when button is larger than text. + SelectableTextAlign = ImVec2(0.0f, 0.0f); // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. + DisplayWindowPadding = ImVec2(19, 19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows. + DisplaySafeAreaPadding = ImVec2(3, 3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. + MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. + AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). + AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). + CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + + // Default theme + ImGui::StyleColorsDark(this); +} + +// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you. +// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times. +void ImGuiStyle::ScaleAllSizes(float scale_factor) +{ + WindowPadding = ImFloor(WindowPadding * scale_factor); + WindowRounding = ImFloor(WindowRounding * scale_factor); + WindowMinSize = ImFloor(WindowMinSize * scale_factor); + ChildRounding = ImFloor(ChildRounding * scale_factor); + PopupRounding = ImFloor(PopupRounding * scale_factor); + FramePadding = ImFloor(FramePadding * scale_factor); + FrameRounding = ImFloor(FrameRounding * scale_factor); + ItemSpacing = ImFloor(ItemSpacing * scale_factor); + ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor); + CellPadding = ImFloor(CellPadding * scale_factor); + TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor); + IndentSpacing = ImFloor(IndentSpacing * scale_factor); + ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor); + ScrollbarSize = ImFloor(ScrollbarSize * scale_factor); + ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor); + GrabMinSize = ImFloor(GrabMinSize * scale_factor); + GrabRounding = ImFloor(GrabRounding * scale_factor); + LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor); + TabRounding = ImFloor(TabRounding * scale_factor); + TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX; + DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor); + DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor); + MouseCursorScale = ImFloor(MouseCursorScale * scale_factor); +} + +ImGuiIO::ImGuiIO() +{ + // Most fields are initialized with zero + memset(this, 0, sizeof(*this)); + IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); + + // Settings + ConfigFlags = ImGuiConfigFlags_None; + BackendFlags = ImGuiBackendFlags_None; + DisplaySize = ImVec2(-1.0f, -1.0f); + DeltaTime = 1.0f / 60.0f; + IniSavingRate = 5.0f; + IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables). + LogFilename = "imgui_log.txt"; + MouseDoubleClickTime = 0.30f; + MouseDoubleClickMaxDist = 6.0f; +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + for (int i = 0; i < ImGuiKey_COUNT; i++) + KeyMap[i] = -1; +#endif + KeyRepeatDelay = 0.275f; + KeyRepeatRate = 0.050f; + UserData = NULL; + + Fonts = NULL; + FontGlobalScale = 1.0f; + FontDefault = NULL; + FontAllowUserScaling = false; + DisplayFramebufferScale = ImVec2(1.0f, 1.0f); + + // Docking options (when ImGuiConfigFlags_DockingEnable is set) + ConfigDockingNoSplit = false; + ConfigDockingWithShift = false; + ConfigDockingAlwaysTabBar = false; + ConfigDockingTransparentPayload = false; + + // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) + ConfigViewportsNoAutoMerge = false; + ConfigViewportsNoTaskBarIcon = false; + ConfigViewportsNoDecoration = true; + ConfigViewportsNoDefaultParent = false; + + // Miscellaneous options + MouseDrawCursor = false; +#ifdef __APPLE__ + ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag +#else + ConfigMacOSXBehaviors = false; +#endif + ConfigInputTrickleEventQueue = true; + ConfigInputTextCursorBlink = true; + ConfigWindowsResizeFromEdges = true; + ConfigWindowsMoveFromTitleBarOnly = false; + ConfigMemoryCompactTimer = 60.0f; + + // Platform Functions + BackendPlatformName = BackendRendererName = NULL; + BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL; + GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations + SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; + ClipboardUserData = NULL; + SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl; + + // Input (NB: we already have memset zero the entire structure!) + MousePos = ImVec2(-FLT_MAX, -FLT_MAX); + MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX); + MouseDragThreshold = 6.0f; + for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) + MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; + for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) + { + KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; + } + for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) + NavInputsDownDuration[i] = -1.0f; + BackendUsingLegacyKeyArrays = (ImS8)-1; + BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong +} + +// Pass in translated ASCII characters for text input. +// - with glfw you can get those from the callback set in glfwSetCharCallback() +// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message +// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API +void ImGuiIO::AddInputCharacter(unsigned int c) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(&g.IO == this && "Can only add events to current context."); + if (c == 0) + return; + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_Text; + e.Source = ImGuiInputSource_Keyboard; + e.Text.Char = c; + g.InputEventsQueue.push_back(e); +} + +// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so +// we should save the high surrogate. +void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c) +{ + if (c == 0 && InputQueueSurrogate == 0) + return; + + if ((c & 0xFC00) == 0xD800) // High surrogate, must save + { + if (InputQueueSurrogate != 0) + AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID); + InputQueueSurrogate = c; + return; + } + + ImWchar cp = c; + if (InputQueueSurrogate != 0) + { + if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate + { + AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID); + } + else + { +#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF + cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar +#else + cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000); +#endif + } + + InputQueueSurrogate = 0; + } + AddInputCharacter((unsigned)cp); +} + +void ImGuiIO::AddInputCharactersUTF8(const char *utf8_chars) +{ + while (*utf8_chars != 0) + { + unsigned int c = 0; + utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL); + if (c != 0) + AddInputCharacter(c); + } +} + +void ImGuiIO::ClearInputCharacters() +{ + InputQueueCharacters.resize(0); +} + +void ImGuiIO::ClearInputKeys() +{ +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + memset(KeysDown, 0, sizeof(KeysDown)); +#endif + for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++) + { + KeysData[n].Down = false; + KeysData[n].DownDuration = -1.0f; + KeysData[n].DownDurationPrev = -1.0f; + } + KeyCtrl = KeyShift = KeyAlt = KeySuper = false; + KeyMods = ImGuiModFlags_None; + for (int n = 0; n < IM_ARRAYSIZE(NavInputsDownDuration); n++) + NavInputsDownDuration[n] = NavInputsDownDurationPrev[n] = -1.0f; +} + +// Queue a new key down/up event. +// - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character) +// - bool down: Is the key down? use false to signify a key release. +// - float analog_value: 0.0f..1.0f +void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value) +{ + // if (e->Down) { IMGUI_DEBUG_LOG("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); } + if (key == ImGuiKey_None) + return; + ImGuiContext &g = *GImGui; + IM_ASSERT(&g.IO == this && "Can only add events to current context."); + IM_ASSERT(ImGui::IsNamedKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API. + + // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data. +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!"); + if (BackendUsingLegacyKeyArrays == -1) + for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++) + IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!"); + BackendUsingLegacyKeyArrays = 0; +#endif + if (ImGui::IsGamepadKey(key)) + BackendUsingLegacyNavInputArray = false; + + // Partial filter of duplicates (not strictly needed, but makes data neater in particular for key mods and gamepad values which are most commonly spmamed) + ImGuiKeyData *key_data = ImGui::GetKeyData(key); + if (key_data->Down == down && key_data->AnalogValue == analog_value) + { + bool found = false; + for (int n = g.InputEventsQueue.Size - 1; n >= 0 && !found; n--) + if (g.InputEventsQueue[n].Type == ImGuiInputEventType_Key && g.InputEventsQueue[n].Key.Key == key) + found = true; + if (!found) + return; + } + + // Add event + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_Key; + e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard; + e.Key.Key = key; + e.Key.Down = down; + e.Key.AnalogValue = analog_value; + g.InputEventsQueue.push_back(e); +} + +void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down) +{ + AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f); +} + +// [Optional] Call after AddKeyEvent(). +// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices. +// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this. +void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index) +{ + if (key == ImGuiKey_None) + return; + IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512 + IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey(native_legacy_index)); // >= 0 && <= 511 + IM_UNUSED(native_keycode); // Yet unused + IM_UNUSED(native_scancode); // Yet unused + + // Build native->imgui map so old user code can still call key functions with native 0..511 values. +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode; + if (!ImGui::IsLegacyKey(legacy_key)) + return; + KeyMap[legacy_key] = key; + KeyMap[key] = legacy_key; +#else + IM_UNUSED(key); + IM_UNUSED(native_legacy_index); +#endif +} + +// Queue a mouse move event +void ImGuiIO::AddMousePosEvent(float x, float y) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(&g.IO == this && "Can only add events to current context."); + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_MousePos; + e.Source = ImGuiInputSource_Mouse; + e.MousePos.PosX = x; + e.MousePos.PosY = y; + g.InputEventsQueue.push_back(e); +} + +void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(&g.IO == this && "Can only add events to current context."); + IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT); + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_MouseButton; + e.Source = ImGuiInputSource_Mouse; + e.MouseButton.Button = mouse_button; + e.MouseButton.Down = down; + g.InputEventsQueue.push_back(e); +} + +// Queue a mouse wheel event (most mouse/API will only have a Y component) +void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(&g.IO == this && "Can only add events to current context."); + if (wheel_x == 0.0f && wheel_y == 0.0f) + return; + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_MouseWheel; + e.Source = ImGuiInputSource_Mouse; + e.MouseWheel.WheelX = wheel_x; + e.MouseWheel.WheelY = wheel_y; + g.InputEventsQueue.push_back(e); +} + +void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(&g.IO == this && "Can only add events to current context."); + IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport); + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_MouseViewport; + e.Source = ImGuiInputSource_Mouse; + e.MouseViewport.HoveredViewportID = viewport_id; + g.InputEventsQueue.push_back(e); +} + +void ImGuiIO::AddFocusEvent(bool focused) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(&g.IO == this && "Can only add events to current context."); + + ImGuiInputEvent e; + e.Type = ImGuiInputEventType_Focus; + e.AppFocused.Focused = focused; + g.InputEventsQueue.push_back(e); +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (Geometry functions) +//----------------------------------------------------------------------------- + +ImVec2 ImBezierCubicClosestPoint(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, const ImVec2 &p, int num_segments) +{ + IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau() + ImVec2 p_last = p1; + ImVec2 p_closest; + float p_closest_dist2 = FLT_MAX; + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + { + ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step); + ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p); + float dist2 = ImLengthSqr(p - p_line); + if (dist2 < p_closest_dist2) + { + p_closest = p_line; + p_closest_dist2 = dist2; + } + p_last = p_current; + } + return p_closest; +} + +// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp +static void ImBezierCubicClosestPointCasteljauStep(const ImVec2 &p, ImVec2 &p_closest, ImVec2 &p_last, float &p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) +{ + float dx = x4 - x1; + float dy = y4 - y1; + float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); + float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); + d2 = (d2 >= 0) ? d2 : -d2; + d3 = (d3 >= 0) ? d3 : -d3; + if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy)) + { + ImVec2 p_current(x4, y4); + ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p); + float dist2 = ImLengthSqr(p - p_line); + if (dist2 < p_closest_dist2) + { + p_closest = p_line; + p_closest_dist2 = dist2; + } + p_last = p_current; + } + else if (level < 10) + { + float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f; + float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f; + float x34 = (x3 + x4) * 0.5f, y34 = (y3 + y4) * 0.5f; + float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f; + float x234 = (x23 + x34) * 0.5f, y234 = (y23 + y34) * 0.5f; + float x1234 = (x123 + x234) * 0.5f, y1234 = (y123 + y234) * 0.5f; + ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1); + ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1); + } +} + +// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol +// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically. +ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, const ImVec2 &p, float tess_tol) +{ + IM_ASSERT(tess_tol > 0.0f); + ImVec2 p_last = p1; + ImVec2 p_closest; + float p_closest_dist2 = FLT_MAX; + ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0); + return p_closest; +} + +ImVec2 ImLineClosestPoint(const ImVec2 &a, const ImVec2 &b, const ImVec2 &p) +{ + ImVec2 ap = p - a; + ImVec2 ab_dir = b - a; + float dot = ap.x * ab_dir.x + ap.y * ab_dir.y; + if (dot < 0.0f) + return a; + float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y; + if (dot > ab_len_sqr) + return b; + return a + ab_dir * dot / ab_len_sqr; +} + +bool ImTriangleContainsPoint(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &p) +{ + bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; + bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; + bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; + return ((b1 == b2) && (b2 == b3)); +} + +void ImTriangleBarycentricCoords(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &p, float &out_u, float &out_v, float &out_w) +{ + ImVec2 v0 = b - a; + ImVec2 v1 = c - a; + ImVec2 v2 = p - a; + const float denom = v0.x * v1.y - v1.x * v0.y; + out_v = (v2.x * v1.y - v1.x * v2.y) / denom; + out_w = (v0.x * v2.y - v2.x * v0.y) / denom; + out_u = 1.0f - out_v - out_w; +} + +ImVec2 ImTriangleClosestPoint(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &p) +{ + ImVec2 proj_ab = ImLineClosestPoint(a, b, p); + ImVec2 proj_bc = ImLineClosestPoint(b, c, p); + ImVec2 proj_ca = ImLineClosestPoint(c, a, p); + float dist2_ab = ImLengthSqr(p - proj_ab); + float dist2_bc = ImLengthSqr(p - proj_bc); + float dist2_ca = ImLengthSqr(p - proj_ca); + float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca)); + if (m == dist2_ab) + return proj_ab; + if (m == dist2_bc) + return proj_bc; + return proj_ca; +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) +//----------------------------------------------------------------------------- + +// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more. +int ImStricmp(const char *str1, const char *str2) +{ + int d; + while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) + { + str1++; + str2++; + } + return d; +} + +int ImStrnicmp(const char *str1, const char *str2, size_t count) +{ + int d = 0; + while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) + { + str1++; + str2++; + count--; + } + return d; +} + +void ImStrncpy(char *dst, const char *src, size_t count) +{ + if (count < 1) + return; + if (count > 1) + strncpy(dst, src, count - 1); + dst[count - 1] = 0; +} + +char *ImStrdup(const char *str) +{ + size_t len = strlen(str); + void *buf = IM_ALLOC(len + 1); + return (char *)memcpy(buf, (const void *)str, len + 1); +} + +char *ImStrdupcpy(char *dst, size_t *p_dst_size, const char *src) +{ + size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1; + size_t src_size = strlen(src) + 1; + if (dst_buf_size < src_size) + { + IM_FREE(dst); + dst = (char *)IM_ALLOC(src_size); + if (p_dst_size) + *p_dst_size = src_size; + } + return (char *)memcpy(dst, (const void *)src, src_size); +} + +const char *ImStrchrRange(const char *str, const char *str_end, char c) +{ + const char *p = (const char *)memchr(str, (int)c, str_end - str); + return p; +} + +int ImStrlenW(const ImWchar *str) +{ + // return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit + int n = 0; + while (*str++) + n++; + return n; +} + +// Find end-of-line. Return pointer will point to either first \n, either str_end. +const char *ImStreolRange(const char *str, const char *str_end) +{ + const char *p = (const char *)memchr(str, '\n', str_end - str); + return p ? p : str_end; +} + +const ImWchar *ImStrbolW(const ImWchar *buf_mid_line, const ImWchar *buf_begin) // find beginning-of-line +{ + while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') + buf_mid_line--; + return buf_mid_line; +} + +const char *ImStristr(const char *haystack, const char *haystack_end, const char *needle, const char *needle_end) +{ + if (!needle_end) + needle_end = needle + strlen(needle); + + const char un0 = (char)toupper(*needle); + while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) + { + if (toupper(*haystack) == un0) + { + const char *b = needle + 1; + for (const char *a = haystack + 1; b < needle_end; a++, b++) + if (toupper(*a) != toupper(*b)) + break; + if (b == needle_end) + return haystack; + } + haystack++; + } + return NULL; +} + +// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. +void ImStrTrimBlanks(char *buf) +{ + char *p = buf; + while (p[0] == ' ' || p[0] == '\t') // Leading blanks + p++; + char *p_start = p; + while (*p != 0) // Find end of string + p++; + while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks + p--; + if (p_start != buf) // Copy memory if we had leading blanks + memmove(buf, p_start, p - p_start); + buf[p - p_start] = 0; // Zero terminate +} + +const char *ImStrSkipBlank(const char *str) +{ + while (str[0] == ' ' || str[0] == '\t') + str++; + return str; +} + +// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size). +// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm. +// B) When buf==NULL vsnprintf() will return the output size. +#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS + +// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h) +// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS +// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are +// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.) +#ifdef IMGUI_USE_STB_SPRINTF +#define STB_SPRINTF_IMPLEMENTATION +#ifdef IMGUI_STB_SPRINTF_FILENAME +#include IMGUI_STB_SPRINTF_FILENAME +#else +#include "stb_sprintf.h" +#endif +#endif + +#if defined(_MSC_VER) && !defined(vsnprintf) +#define vsnprintf _vsnprintf +#endif + +int ImFormatString(char *buf, size_t buf_size, const char *fmt, ...) +{ + va_list args; + va_start(args, fmt); +#ifdef IMGUI_USE_STB_SPRINTF + int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args); +#else + int w = vsnprintf(buf, buf_size, fmt, args); +#endif + va_end(args); + if (buf == NULL) + return w; + if (w == -1 || w >= (int)buf_size) + w = (int)buf_size - 1; + buf[w] = 0; + return w; +} + +int ImFormatStringV(char *buf, size_t buf_size, const char *fmt, va_list args) +{ +#ifdef IMGUI_USE_STB_SPRINTF + int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args); +#else + int w = vsnprintf(buf, buf_size, fmt, args); +#endif + if (buf == NULL) + return w; + if (w == -1 || w >= (int)buf_size) + w = (int)buf_size - 1; + buf[w] = 0; + return w; +} +#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS + +// CRC32 needs a 1KB lookup table (not cache friendly) +// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily: +// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe. +static const ImU32 GCrc32LookupTable[256] = + { + 0x00000000, + 0x77073096, + 0xEE0E612C, + 0x990951BA, + 0x076DC419, + 0x706AF48F, + 0xE963A535, + 0x9E6495A3, + 0x0EDB8832, + 0x79DCB8A4, + 0xE0D5E91E, + 0x97D2D988, + 0x09B64C2B, + 0x7EB17CBD, + 0xE7B82D07, + 0x90BF1D91, + 0x1DB71064, + 0x6AB020F2, + 0xF3B97148, + 0x84BE41DE, + 0x1ADAD47D, + 0x6DDDE4EB, + 0xF4D4B551, + 0x83D385C7, + 0x136C9856, + 0x646BA8C0, + 0xFD62F97A, + 0x8A65C9EC, + 0x14015C4F, + 0x63066CD9, + 0xFA0F3D63, + 0x8D080DF5, + 0x3B6E20C8, + 0x4C69105E, + 0xD56041E4, + 0xA2677172, + 0x3C03E4D1, + 0x4B04D447, + 0xD20D85FD, + 0xA50AB56B, + 0x35B5A8FA, + 0x42B2986C, + 0xDBBBC9D6, + 0xACBCF940, + 0x32D86CE3, + 0x45DF5C75, + 0xDCD60DCF, + 0xABD13D59, + 0x26D930AC, + 0x51DE003A, + 0xC8D75180, + 0xBFD06116, + 0x21B4F4B5, + 0x56B3C423, + 0xCFBA9599, + 0xB8BDA50F, + 0x2802B89E, + 0x5F058808, + 0xC60CD9B2, + 0xB10BE924, + 0x2F6F7C87, + 0x58684C11, + 0xC1611DAB, + 0xB6662D3D, + 0x76DC4190, + 0x01DB7106, + 0x98D220BC, + 0xEFD5102A, + 0x71B18589, + 0x06B6B51F, + 0x9FBFE4A5, + 0xE8B8D433, + 0x7807C9A2, + 0x0F00F934, + 0x9609A88E, + 0xE10E9818, + 0x7F6A0DBB, + 0x086D3D2D, + 0x91646C97, + 0xE6635C01, + 0x6B6B51F4, + 0x1C6C6162, + 0x856530D8, + 0xF262004E, + 0x6C0695ED, + 0x1B01A57B, + 0x8208F4C1, + 0xF50FC457, + 0x65B0D9C6, + 0x12B7E950, + 0x8BBEB8EA, + 0xFCB9887C, + 0x62DD1DDF, + 0x15DA2D49, + 0x8CD37CF3, + 0xFBD44C65, + 0x4DB26158, + 0x3AB551CE, + 0xA3BC0074, + 0xD4BB30E2, + 0x4ADFA541, + 0x3DD895D7, + 0xA4D1C46D, + 0xD3D6F4FB, + 0x4369E96A, + 0x346ED9FC, + 0xAD678846, + 0xDA60B8D0, + 0x44042D73, + 0x33031DE5, + 0xAA0A4C5F, + 0xDD0D7CC9, + 0x5005713C, + 0x270241AA, + 0xBE0B1010, + 0xC90C2086, + 0x5768B525, + 0x206F85B3, + 0xB966D409, + 0xCE61E49F, + 0x5EDEF90E, + 0x29D9C998, + 0xB0D09822, + 0xC7D7A8B4, + 0x59B33D17, + 0x2EB40D81, + 0xB7BD5C3B, + 0xC0BA6CAD, + 0xEDB88320, + 0x9ABFB3B6, + 0x03B6E20C, + 0x74B1D29A, + 0xEAD54739, + 0x9DD277AF, + 0x04DB2615, + 0x73DC1683, + 0xE3630B12, + 0x94643B84, + 0x0D6D6A3E, + 0x7A6A5AA8, + 0xE40ECF0B, + 0x9309FF9D, + 0x0A00AE27, + 0x7D079EB1, + 0xF00F9344, + 0x8708A3D2, + 0x1E01F268, + 0x6906C2FE, + 0xF762575D, + 0x806567CB, + 0x196C3671, + 0x6E6B06E7, + 0xFED41B76, + 0x89D32BE0, + 0x10DA7A5A, + 0x67DD4ACC, + 0xF9B9DF6F, + 0x8EBEEFF9, + 0x17B7BE43, + 0x60B08ED5, + 0xD6D6A3E8, + 0xA1D1937E, + 0x38D8C2C4, + 0x4FDFF252, + 0xD1BB67F1, + 0xA6BC5767, + 0x3FB506DD, + 0x48B2364B, + 0xD80D2BDA, + 0xAF0A1B4C, + 0x36034AF6, + 0x41047A60, + 0xDF60EFC3, + 0xA867DF55, + 0x316E8EEF, + 0x4669BE79, + 0xCB61B38C, + 0xBC66831A, + 0x256FD2A0, + 0x5268E236, + 0xCC0C7795, + 0xBB0B4703, + 0x220216B9, + 0x5505262F, + 0xC5BA3BBE, + 0xB2BD0B28, + 0x2BB45A92, + 0x5CB36A04, + 0xC2D7FFA7, + 0xB5D0CF31, + 0x2CD99E8B, + 0x5BDEAE1D, + 0x9B64C2B0, + 0xEC63F226, + 0x756AA39C, + 0x026D930A, + 0x9C0906A9, + 0xEB0E363F, + 0x72076785, + 0x05005713, + 0x95BF4A82, + 0xE2B87A14, + 0x7BB12BAE, + 0x0CB61B38, + 0x92D28E9B, + 0xE5D5BE0D, + 0x7CDCEFB7, + 0x0BDBDF21, + 0x86D3D2D4, + 0xF1D4E242, + 0x68DDB3F8, + 0x1FDA836E, + 0x81BE16CD, + 0xF6B9265B, + 0x6FB077E1, + 0x18B74777, + 0x88085AE6, + 0xFF0F6A70, + 0x66063BCA, + 0x11010B5C, + 0x8F659EFF, + 0xF862AE69, + 0x616BFFD3, + 0x166CCF45, + 0xA00AE278, + 0xD70DD2EE, + 0x4E048354, + 0x3903B3C2, + 0xA7672661, + 0xD06016F7, + 0x4969474D, + 0x3E6E77DB, + 0xAED16A4A, + 0xD9D65ADC, + 0x40DF0B66, + 0x37D83BF0, + 0xA9BCAE53, + 0xDEBB9EC5, + 0x47B2CF7F, + 0x30B5FFE9, + 0xBDBDF21C, + 0xCABAC28A, + 0x53B39330, + 0x24B4A3A6, + 0xBAD03605, + 0xCDD70693, + 0x54DE5729, + 0x23D967BF, + 0xB3667A2E, + 0xC4614AB8, + 0x5D681B02, + 0x2A6F2B94, + 0xB40BBE37, + 0xC30C8EA1, + 0x5A05DF1B, + 0x2D02EF8D, +}; + +// Known size hash +// It is ok to call ImHashData on a string with known length but the ### operator won't be supported. +// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. +ImGuiID ImHashData(const void *data_p, size_t data_size, ImU32 seed) +{ + ImU32 crc = ~seed; + const unsigned char *data = (const unsigned char *)data_p; + const ImU32 *crc32_lut = GCrc32LookupTable; + while (data_size-- != 0) + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++]; + return ~crc; +} + +// Zero-terminated string hash, with support for ### to reset back to seed value +// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. +// Because this syntax is rarely used we are optimizing for the common case. +// - If we reach ### in the string we discard the hash so far and reset to the seed. +// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build) +// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. +ImGuiID ImHashStr(const char *data_p, size_t data_size, ImU32 seed) +{ + seed = ~seed; + ImU32 crc = seed; + const unsigned char *data = (const unsigned char *)data_p; + const ImU32 *crc32_lut = GCrc32LookupTable; + if (data_size != 0) + { + while (data_size-- != 0) + { + unsigned char c = *data++; + if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#') + crc = seed; + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; + } + } + else + { + while (unsigned char c = *data++) + { + if (c == '#' && data[0] == '#' && data[1] == '#') + crc = seed; + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; + } + } + return ~crc; +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (File functions) +//----------------------------------------------------------------------------- + +// Default file functions +#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS + +ImFileHandle ImFileOpen(const char *filename, const char *mode) +{ +#if 0 // defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__) + // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. + // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32! + const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0); + const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0); + ImVector buf; + buf.resize(filename_wsize + mode_wsize); + ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t *)&buf[0], filename_wsize); + ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t *)&buf[filename_wsize], mode_wsize); + return ::_wfopen((const wchar_t *)&buf[0], (const wchar_t *)&buf[filename_wsize]); +#else + return fopen(filename, mode); +#endif +} + +// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way. +bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; } +ImU64 ImFileGetSize(ImFileHandle f) +{ + long off = 0, sz = 0; + return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; +} +ImU64 ImFileRead(void *data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); } +ImU64 ImFileWrite(const void *data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); } +#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS + +// Helper: Load file content into memory +// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree() +// This can't really be used with "rt" because fseek size won't match read size. +void *ImFileLoadToMemory(const char *filename, const char *mode, size_t *out_file_size, int padding_bytes) +{ + IM_ASSERT(filename && mode); + if (out_file_size) + *out_file_size = 0; + + ImFileHandle f; + if ((f = ImFileOpen(filename, mode)) == NULL) + return NULL; + + size_t file_size = (size_t)ImFileGetSize(f); + if (file_size == (size_t)-1) + { + ImFileClose(f); + return NULL; + } + + void *file_data = IM_ALLOC(file_size + padding_bytes); + if (file_data == NULL) + { + ImFileClose(f); + return NULL; + } + if (ImFileRead(file_data, 1, file_size, f) != file_size) + { + ImFileClose(f); + IM_FREE(file_data); + return NULL; + } + if (padding_bytes > 0) + memset((void *)(((char *)file_data) + file_size), 0, (size_t)padding_bytes); + + ImFileClose(f); + if (out_file_size) + *out_file_size = file_size; + + return file_data; +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (ImText* functions) +//----------------------------------------------------------------------------- + +// Convert UTF-8 to 32-bit character, process single character input. +// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8). +// We handle UTF-8 decoding error by skipping forward. +int ImTextCharFromUtf8(unsigned int *out_char, const char *in_text, const char *in_text_end) +{ + static const char lengths[32] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0}; + static const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07}; + static const uint32_t mins[] = {0x400000, 0, 0x80, 0x800, 0x10000}; + static const int shiftc[] = {0, 18, 12, 6, 0}; + static const int shifte[] = {0, 6, 4, 2, 0}; + int len = lengths[*(const unsigned char *)in_text >> 3]; + int wanted = len + !len; + + if (in_text_end == NULL) + in_text_end = in_text + wanted; // Max length, nulls will be taken into account. + + // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here, + // so it is fast even with excessive branching. + unsigned char s[4]; + s[0] = in_text + 0 < in_text_end ? in_text[0] : 0; + s[1] = in_text + 1 < in_text_end ? in_text[1] : 0; + s[2] = in_text + 2 < in_text_end ? in_text[2] : 0; + s[3] = in_text + 3 < in_text_end ? in_text[3] : 0; + + // Assume a four-byte character and load four bytes. Unused bits are shifted out. + *out_char = (uint32_t)(s[0] & masks[len]) << 18; + *out_char |= (uint32_t)(s[1] & 0x3f) << 12; + *out_char |= (uint32_t)(s[2] & 0x3f) << 6; + *out_char |= (uint32_t)(s[3] & 0x3f) << 0; + *out_char >>= shiftc[len]; + + // Accumulate the various error conditions. + int e = 0; + e = (*out_char < mins[len]) << 6; // non-canonical encoding + e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half? + e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range? + e |= (s[1] & 0xc0) >> 2; + e |= (s[2] & 0xc0) >> 4; + e |= (s[3]) >> 6; + e ^= 0x2a; // top two bits of each tail byte correct? + e >>= shifte[len]; + + if (e) + { + // No bytes are consumed when *in_text == 0 || in_text == in_text_end. + // One byte is consumed in case of invalid first byte of in_text. + // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes. + // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s. + wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]); + *out_char = IM_UNICODE_CODEPOINT_INVALID; + } + + return wanted; +} + +int ImTextStrFromUtf8(ImWchar *buf, int buf_size, const char *in_text, const char *in_text_end, const char **in_text_remaining) +{ + ImWchar *buf_out = buf; + ImWchar *buf_end = buf + buf_size; + while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + *buf_out++ = (ImWchar)c; + } + *buf_out = 0; + if (in_text_remaining) + *in_text_remaining = in_text; + return (int)(buf_out - buf); +} + +int ImTextCountCharsFromUtf8(const char *in_text, const char *in_text_end) +{ + int char_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + char_count++; + } + return char_count; +} + +// Based on stb_to_utf8() from github.com/nothings/stb/ +static inline int ImTextCharToUtf8_inline(char *buf, int buf_size, unsigned int c) +{ + if (c < 0x80) + { + buf[0] = (char)c; + return 1; + } + if (c < 0x800) + { + if (buf_size < 2) + return 0; + buf[0] = (char)(0xc0 + (c >> 6)); + buf[1] = (char)(0x80 + (c & 0x3f)); + return 2; + } + if (c < 0x10000) + { + if (buf_size < 3) + return 0; + buf[0] = (char)(0xe0 + (c >> 12)); + buf[1] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[2] = (char)(0x80 + ((c)&0x3f)); + return 3; + } + if (c <= 0x10FFFF) + { + if (buf_size < 4) + return 0; + buf[0] = (char)(0xf0 + (c >> 18)); + buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); + buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[3] = (char)(0x80 + ((c)&0x3f)); + return 4; + } + // Invalid code point, the max unicode is 0x10FFFF + return 0; +} + +const char *ImTextCharToUtf8(char out_buf[5], unsigned int c) +{ + int count = ImTextCharToUtf8_inline(out_buf, 5, c); + out_buf[count] = 0; + return out_buf; +} + +// Not optimal but we very rarely use this function. +int ImTextCountUtf8BytesFromChar(const char *in_text, const char *in_text_end) +{ + unsigned int unused = 0; + return ImTextCharFromUtf8(&unused, in_text, in_text_end); +} + +static inline int ImTextCountUtf8BytesFromChar(unsigned int c) +{ + if (c < 0x80) + return 1; + if (c < 0x800) + return 2; + if (c < 0x10000) + return 3; + if (c <= 0x10FFFF) + return 4; + return 3; +} + +int ImTextStrToUtf8(char *out_buf, int out_buf_size, const ImWchar *in_text, const ImWchar *in_text_end) +{ + char *buf_p = out_buf; + const char *buf_end = out_buf + out_buf_size; + while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + *buf_p++ = (char)c; + else + buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c); + } + *buf_p = 0; + return (int)(buf_p - out_buf); +} + +int ImTextCountUtf8BytesFromStr(const ImWchar *in_text, const ImWchar *in_text_end) +{ + int bytes_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + bytes_count++; + else + bytes_count += ImTextCountUtf8BytesFromChar(c); + } + return bytes_count; +} + +//----------------------------------------------------------------------------- +// [SECTION] MISC HELPERS/UTILITIES (Color functions) +// Note: The Convert functions are early design which are not consistent with other API. +//----------------------------------------------------------------------------- + +IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b) +{ + float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f; + int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t); + int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t); + int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t); + return IM_COL32(r, g, b, 0xFF); +} + +ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) +{ + float s = 1.0f / 255.0f; + return ImVec4( + ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_B_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_A_SHIFT) & 0xFF) * s); +} + +ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4 &in) +{ + ImU32 out; + out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT; + return out; +} + +// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 +// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv +void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float &out_h, float &out_s, float &out_v) +{ + float K = 0.f; + if (g < b) + { + ImSwap(g, b); + K = -1.f; + } + if (r < g) + { + ImSwap(r, g); + K = -2.f / 6.f - K; + } + + const float chroma = r - (g < b ? g : b); + out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f)); + out_s = chroma / (r + 1e-20f); + out_v = r; +} + +// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 +// also http://en.wikipedia.org/wiki/HSL_and_HSV +void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float &out_r, float &out_g, float &out_b) +{ + if (s == 0.0f) + { + // gray + out_r = out_g = out_b = v; + return; + } + + h = ImFmod(h, 1.0f) / (60.0f / 360.0f); + int i = (int)h; + float f = h - (float)i; + float p = v * (1.0f - s); + float q = v * (1.0f - s * f); + float t = v * (1.0f - s * (1.0f - f)); + + switch (i) + { + case 0: + out_r = v; + out_g = t; + out_b = p; + break; + case 1: + out_r = q; + out_g = v; + out_b = p; + break; + case 2: + out_r = p; + out_g = v; + out_b = t; + break; + case 3: + out_r = p; + out_g = q; + out_b = v; + break; + case 4: + out_r = t; + out_g = p; + out_b = v; + break; + case 5: + default: + out_r = v; + out_g = p; + out_b = q; + break; + } +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiStorage +// Helper: Key->value storage +//----------------------------------------------------------------------------- + +// std::lower_bound but without the bullshit +static ImGuiStorage::ImGuiStoragePair *LowerBound(ImVector &data, ImGuiID key) +{ + ImGuiStorage::ImGuiStoragePair *first = data.Data; + ImGuiStorage::ImGuiStoragePair *last = data.Data + data.Size; + size_t count = (size_t)(last - first); + while (count > 0) + { + size_t count2 = count >> 1; + ImGuiStorage::ImGuiStoragePair *mid = first + count2; + if (mid->key < key) + { + first = ++mid; + count -= count2 + 1; + } + else + { + count = count2; + } + } + return first; +} + +// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. +void ImGuiStorage::BuildSortByKey() +{ + struct StaticFunc + { + static int IMGUI_CDECL PairComparerByID(const void *lhs, const void *rhs) + { + // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that. + if (((const ImGuiStoragePair *)lhs)->key > ((const ImGuiStoragePair *)rhs)->key) + return +1; + if (((const ImGuiStoragePair *)lhs)->key < ((const ImGuiStoragePair *)rhs)->key) + return -1; + return 0; + } + }; + ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID); +} + +int ImGuiStorage::GetInt(ImGuiID key, int default_val) const +{ + ImGuiStoragePair *it = LowerBound(const_cast &>(Data), key); + if (it == Data.end() || it->key != key) + return default_val; + return it->val_i; +} + +bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const +{ + return GetInt(key, default_val ? 1 : 0) != 0; +} + +float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const +{ + ImGuiStoragePair *it = LowerBound(const_cast &>(Data), key); + if (it == Data.end() || it->key != key) + return default_val; + return it->val_f; +} + +void *ImGuiStorage::GetVoidPtr(ImGuiID key) const +{ + ImGuiStoragePair *it = LowerBound(const_cast &>(Data), key); + if (it == Data.end() || it->key != key) + return NULL; + return it->val_p; +} + +// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. +int *ImGuiStorage::GetIntRef(ImGuiID key, int default_val) +{ + ImGuiStoragePair *it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, ImGuiStoragePair(key, default_val)); + return &it->val_i; +} + +bool *ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) +{ + return (bool *)GetIntRef(key, default_val ? 1 : 0); +} + +float *ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) +{ + ImGuiStoragePair *it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, ImGuiStoragePair(key, default_val)); + return &it->val_f; +} + +void **ImGuiStorage::GetVoidPtrRef(ImGuiID key, void *default_val) +{ + ImGuiStoragePair *it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, ImGuiStoragePair(key, default_val)); + return &it->val_p; +} + +// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) +void ImGuiStorage::SetInt(ImGuiID key, int val) +{ + ImGuiStoragePair *it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, ImGuiStoragePair(key, val)); + return; + } + it->val_i = val; +} + +void ImGuiStorage::SetBool(ImGuiID key, bool val) +{ + SetInt(key, val ? 1 : 0); +} + +void ImGuiStorage::SetFloat(ImGuiID key, float val) +{ + ImGuiStoragePair *it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, ImGuiStoragePair(key, val)); + return; + } + it->val_f = val; +} + +void ImGuiStorage::SetVoidPtr(ImGuiID key, void *val) +{ + ImGuiStoragePair *it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, ImGuiStoragePair(key, val)); + return; + } + it->val_p = val; +} + +void ImGuiStorage::SetAllInt(int v) +{ + for (int i = 0; i < Data.Size; i++) + Data[i].val_i = v; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiTextFilter +//----------------------------------------------------------------------------- + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +ImGuiTextFilter::ImGuiTextFilter(const char *default_filter) //-V1077 +{ + InputBuf[0] = 0; + CountGrep = 0; + if (default_filter) + { + ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); + Build(); + } +} + +bool ImGuiTextFilter::Draw(const char *label, float width) +{ + if (width != 0.0f) + ImGui::SetNextItemWidth(width); + bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); + if (value_changed) + Build(); + return value_changed; +} + +void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector *out) const +{ + out->resize(0); + const char *wb = b; + const char *we = wb; + while (we < e) + { + if (*we == separator) + { + out->push_back(ImGuiTextRange(wb, we)); + wb = we + 1; + } + we++; + } + if (wb != we) + out->push_back(ImGuiTextRange(wb, we)); +} + +void ImGuiTextFilter::Build() +{ + Filters.resize(0); + ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf)); + input_range.split(',', &Filters); + + CountGrep = 0; + for (int i = 0; i != Filters.Size; i++) + { + ImGuiTextRange &f = Filters[i]; + while (f.b < f.e && ImCharIsBlankA(f.b[0])) + f.b++; + while (f.e > f.b && ImCharIsBlankA(f.e[-1])) + f.e--; + if (f.empty()) + continue; + if (Filters[i].b[0] != '-') + CountGrep += 1; + } +} + +bool ImGuiTextFilter::PassFilter(const char *text, const char *text_end) const +{ + if (Filters.empty()) + return true; + + if (text == NULL) + text = ""; + + for (int i = 0; i != Filters.Size; i++) + { + const ImGuiTextRange &f = Filters[i]; + if (f.empty()) + continue; + if (f.b[0] == '-') + { + // Subtract + if (ImStristr(text, text_end, f.b + 1, f.e) != NULL) + return false; + } + else + { + // Grep + if (ImStristr(text, text_end, f.b, f.e) != NULL) + return true; + } + } + + // Implicit * grep + if (CountGrep == 0) + return true; + + return false; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiTextBuffer +//----------------------------------------------------------------------------- + +// On some platform vsnprintf() takes va_list by reference and modifies it. +// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. +#ifndef va_copy +#if defined(__GNUC__) || defined(__clang__) +#define va_copy(dest, src) __builtin_va_copy(dest, src) +#else +#define va_copy(dest, src) (dest = src) +#endif +#endif + +char ImGuiTextBuffer::EmptyString[1] = {0}; + +void ImGuiTextBuffer::append(const char *str, const char *str_end) +{ + int len = str_end ? (int)(str_end - str) : (int)strlen(str); + + // Add zero-terminator the first time + const int write_off = (Buf.Size != 0) ? Buf.Size : 1; + const int needed_sz = write_off + len; + if (write_off + len >= Buf.Capacity) + { + int new_capacity = Buf.Capacity * 2; + Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); + } + + Buf.resize(needed_sz); + memcpy(&Buf[write_off - 1], str, (size_t)len); + Buf[write_off - 1 + len] = 0; +} + +void ImGuiTextBuffer::appendf(const char *fmt, ...) +{ + va_list args; + va_start(args, fmt); + appendfv(fmt, args); + va_end(args); +} + +// Helper: Text buffer for logging/accumulating text +void ImGuiTextBuffer::appendfv(const char *fmt, va_list args) +{ + va_list args_copy; + va_copy(args_copy, args); + + int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. + if (len <= 0) + { + va_end(args_copy); + return; + } + + // Add zero-terminator the first time + const int write_off = (Buf.Size != 0) ? Buf.Size : 1; + const int needed_sz = write_off + len; + if (write_off + len >= Buf.Capacity) + { + int new_capacity = Buf.Capacity * 2; + Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); + } + + Buf.resize(needed_sz); + ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy); + va_end(args_copy); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiListClipper +// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed +// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO) +//----------------------------------------------------------------------------- + +// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell. +// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous. +static bool GetSkipItemForListClipping() +{ + ImGuiContext &g = *GImGui; + return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems); +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +// Legacy helper to calculate coarse clipping of large list of evenly sized items. +// This legacy API is not ideal because it assume we will return a single contiguous rectangle. +// Prefer using ImGuiListClipper which can returns non-contiguous ranges. +void ImGui::CalcListClipping(int items_count, float items_height, int *out_items_display_start, int *out_items_display_end) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (g.LogEnabled) + { + // If logging is active, do not perform any clipping + *out_items_display_start = 0; + *out_items_display_end = items_count; + return; + } + if (GetSkipItemForListClipping()) + { + *out_items_display_start = *out_items_display_end = 0; + return; + } + + // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect + // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly. + ImRect rect = window->ClipRect; + if (g.NavMoveScoringItems) + rect.Add(g.NavScoringNoClipRect); + if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId) + rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel + + const ImVec2 pos = window->DC.CursorPos; + int start = (int)((rect.Min.y - pos.y) / items_height); + int end = (int)((rect.Max.y - pos.y) / items_height); + + // When performing a navigation request, ensure we have one item extra in the direction we are moving to + // FIXME: Verify this works with tabbing + const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); + if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) + start--; + if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) + end++; + + start = ImClamp(start, 0, items_count); + end = ImClamp(end + 1, start, items_count); + *out_items_display_start = start; + *out_items_display_end = end; +} +#endif + +static void ImGuiListClipper_SortAndFuseRanges(ImVector &ranges, int offset = 0) +{ + if (ranges.Size - offset <= 1) + return; + + // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries) + for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end) + for (int i = offset; i < sort_end + offset; ++i) + if (ranges[i].Min > ranges[i + 1].Min) + ImSwap(ranges[i], ranges[i + 1]); + + // Now fuse ranges together as much as possible. + for (int i = 1 + offset; i < ranges.Size; i++) + { + IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert); + if (ranges[i - 1].Max < ranges[i].Min) + continue; + ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min); + ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max); + ranges.erase(ranges.Data + i); + i--; + } +} + +static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height) +{ + // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. + // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. + // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek? + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + float off_y = pos_y - window->DC.CursorPos.y; + window->DC.CursorPos.y = pos_y; + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y); + window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. + window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. + if (ImGuiOldColumns *columns = window->DC.CurrentColumns) + columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly + if (ImGuiTable *table = g.CurrentTable) + { + if (table->IsInsideRow) + ImGui::TableEndRow(table); + table->RowPosY2 = window->DC.CursorPos.y; + const int row_increase = (int)((off_y / line_height) + 0.5f); + // table->CurrentRow += row_increase; // Can't do without fixing TableEndRow() + table->RowBgColorCounter += row_increase; + } +} + +static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper *clipper, int item_n) +{ + // StartPosY starts from ItemsFrozen hence the subtraction + // Perform the add and multiply with double to allow seeking through larger ranges + ImGuiListClipperData *data = (ImGuiListClipperData *)clipper->TempData; + float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight); + ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight); +} + +ImGuiListClipper::ImGuiListClipper() +{ + memset(this, 0, sizeof(*this)); + ItemsCount = -1; +} + +ImGuiListClipper::~ImGuiListClipper() +{ + End(); +} + +// Use case A: Begin() called from constructor with items_height<0, then called again from Step() in StepNo 1 +// Use case B: Begin() called from constructor with items_height>0 +// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. +void ImGuiListClipper::Begin(int items_count, float items_height) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + if (ImGuiTable *table = g.CurrentTable) + if (table->IsInsideRow) + ImGui::TableEndRow(table); + + StartPosY = window->DC.CursorPos.y; + ItemsHeight = items_height; + ItemsCount = items_count; + DisplayStart = -1; + DisplayEnd = 0; + + // Acquire temporary buffer + if (++g.ClipperTempDataStacked > g.ClipperTempData.Size) + g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData()); + ImGuiListClipperData *data = &g.ClipperTempData[g.ClipperTempDataStacked - 1]; + data->Reset(this); + data->LossynessOffset = window->DC.CursorStartPosLossyness.y; + TempData = data; +} + +void ImGuiListClipper::End() +{ + ImGuiContext &g = *GImGui; + if (ImGuiListClipperData *data = (ImGuiListClipperData *)TempData) + { + // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user. + if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0) + ImGuiListClipper_SeekCursorForItem(this, ItemsCount); + + // Restore temporary buffer and fix back pointers which may be invalidated when nesting + IM_ASSERT(data->ListClipper == this); + data->StepNo = data->Ranges.Size; + if (--g.ClipperTempDataStacked > 0) + { + data = &g.ClipperTempData[g.ClipperTempDataStacked - 1]; + data->ListClipper->TempData = data; + } + TempData = NULL; + } + ItemsCount = -1; +} + +void ImGuiListClipper::ForceDisplayRangeByIndices(int item_min, int item_max) +{ + ImGuiListClipperData *data = (ImGuiListClipperData *)TempData; + IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet. + IM_ASSERT(item_min <= item_max); + if (item_min < item_max) + data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_min, item_max)); +} + +bool ImGuiListClipper::Step() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + ImGuiListClipperData *data = (ImGuiListClipperData *)TempData; + IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?"); + + ImGuiTable *table = g.CurrentTable; + if (table && table->IsInsideRow) + ImGui::TableEndRow(table); + + // No items + if (ItemsCount == 0 || GetSkipItemForListClipping()) + return (void)End(), false; + + // While we are in frozen row state, keep displaying items one by one, unclipped + // FIXME: Could be stored as a table-agnostic state. + if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows) + { + DisplayStart = data->ItemsFrozen; + DisplayEnd = data->ItemsFrozen + 1; + if (DisplayStart >= ItemsCount) + return (void)End(), false; + data->ItemsFrozen++; + return true; + } + + // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height) + bool calc_clipping = false; + if (data->StepNo == 0) + { + StartPosY = window->DC.CursorPos.y; + if (ItemsHeight <= 0.0f) + { + // Submit the first item (or range) so we can measure its height (generally the first range is 0..1) + data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1)); + DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen); + DisplayEnd = ImMin(data->Ranges[0].Max, ItemsCount); + if (DisplayStart == DisplayEnd) + return (void)End(), false; + data->StepNo = 1; + return true; + } + calc_clipping = true; // If on the first step with known item height, calculate clipping. + } + + // Step 1: Let the clipper infer height from first range + if (ItemsHeight <= 0.0f) + { + IM_ASSERT(data->StepNo == 1); + if (table) + IM_ASSERT(table->RowPosY1 == StartPosY && table->RowPosY2 == window->DC.CursorPos.y); + + ItemsHeight = (window->DC.CursorPos.y - StartPosY) / (float)(DisplayEnd - DisplayStart); + bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y); + if (affected_by_floating_point_precision) + ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries. + + IM_ASSERT(ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!"); + calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards. + } + + // Step 0 or 1: Calculate the actual ranges of visible elements. + const int already_submitted = DisplayEnd; + if (calc_clipping) + { + if (g.LogEnabled) + { + // If logging is active, do not perform any clipping + data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, ItemsCount)); + } + else + { + // Add range selected to be included for navigation + const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); + if (is_nav_request) + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0)); + if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1) + data->Ranges.push_back(ImGuiListClipperRange::FromIndices(ItemsCount - 1, ItemsCount)); + + // Add focused/active item + ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]); + if (g.NavId != 0 && window->NavLastIds[0] == g.NavId) + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0)); + + // Add visible range + const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0; + const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0; + data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max)); + } + + // Convert position ranges to item index ranges + // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping. + // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list, + // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted. + for (int i = 0; i < data->Ranges.Size; i++) + if (data->Ranges[i].PosToIndexConvert) + { + int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / ItemsHeight); + int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / ItemsHeight) + 0.999999f); + data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, ItemsCount - 1); + data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, ItemsCount); + data->Ranges[i].PosToIndexConvert = false; + } + ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo); + } + + // Step 0+ (if item height is given in advance) or 1+: Display the next range in line. + if (data->StepNo < data->Ranges.Size) + { + DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted); + DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, ItemsCount); + if (DisplayStart > already_submitted) //-V1051 + ImGuiListClipper_SeekCursorForItem(this, DisplayStart); + data->StepNo++; + return true; + } + + // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), + // Advance the cursor to the end of the list and then returns 'false' to end the loop. + if (ItemsCount < INT_MAX) + ImGuiListClipper_SeekCursorForItem(this, ItemsCount); + + End(); + return false; +} + +//----------------------------------------------------------------------------- +// [SECTION] STYLING +//----------------------------------------------------------------------------- + +ImGuiStyle &ImGui::GetStyle() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); + return GImGui->Style; +} + +ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) +{ + ImGuiStyle &style = GImGui->Style; + ImVec4 c = style.Colors[idx]; + c.w *= style.Alpha * alpha_mul; + return ColorConvertFloat4ToU32(c); +} + +ImU32 ImGui::GetColorU32(const ImVec4 &col) +{ + ImGuiStyle &style = GImGui->Style; + ImVec4 c = col; + c.w *= style.Alpha; + return ColorConvertFloat4ToU32(c); +} + +const ImVec4 &ImGui::GetStyleColorVec4(ImGuiCol idx) +{ + ImGuiStyle &style = GImGui->Style; + return style.Colors[idx]; +} + +ImU32 ImGui::GetColorU32(ImU32 col) +{ + ImGuiStyle &style = GImGui->Style; + if (style.Alpha >= 1.0f) + return col; + ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; + a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range. + return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); +} + +// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32 +void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col) +{ + ImGuiContext &g = *GImGui; + ImGuiColorMod backup; + backup.Col = idx; + backup.BackupValue = g.Style.Colors[idx]; + g.ColorStack.push_back(backup); + g.Style.Colors[idx] = ColorConvertU32ToFloat4(col); +} + +void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4 &col) +{ + ImGuiContext &g = *GImGui; + ImGuiColorMod backup; + backup.Col = idx; + backup.BackupValue = g.Style.Colors[idx]; + g.ColorStack.push_back(backup); + g.Style.Colors[idx] = col; +} + +void ImGui::PopStyleColor(int count) +{ + ImGuiContext &g = *GImGui; + while (count > 0) + { + ImGuiColorMod &backup = g.ColorStack.back(); + g.Style.Colors[backup.Col] = backup.BackupValue; + g.ColorStack.pop_back(); + count--; + } +} + +struct ImGuiStyleVarInfo +{ + ImGuiDataType Type; + ImU32 Count; + ImU32 Offset; + void *GetVarPtr(ImGuiStyle *style) const { return (void *)((unsigned char *)style + Offset); } +}; + +static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] = + { + ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive}; + +static const ImGuiStyleVarInfo GStyleVarInfo[] = + { + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha)}, // ImGuiStyleVar_Alpha + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha)}, // ImGuiStyleVar_DisabledAlpha + {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding)}, // ImGuiStyleVar_WindowPadding + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding)}, // ImGuiStyleVar_WindowRounding + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize)}, // ImGuiStyleVar_WindowBorderSize + {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize)}, // ImGuiStyleVar_WindowMinSize + {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign)}, // ImGuiStyleVar_WindowTitleAlign + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding)}, // ImGuiStyleVar_ChildRounding + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize)}, // ImGuiStyleVar_ChildBorderSize + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding)}, // ImGuiStyleVar_PopupRounding + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize)}, // ImGuiStyleVar_PopupBorderSize + {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding)}, // ImGuiStyleVar_FramePadding + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding)}, // ImGuiStyleVar_FrameRounding + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize)}, // ImGuiStyleVar_FrameBorderSize + {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing)}, // ImGuiStyleVar_ItemSpacing + {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing)}, // ImGuiStyleVar_ItemInnerSpacing + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing)}, // ImGuiStyleVar_IndentSpacing + {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding)}, // ImGuiStyleVar_CellPadding + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize)}, // ImGuiStyleVar_ScrollbarSize + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding)}, // ImGuiStyleVar_ScrollbarRounding + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize)}, // ImGuiStyleVar_GrabMinSize + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding)}, // ImGuiStyleVar_GrabRounding + {ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding)}, // ImGuiStyleVar_TabRounding + {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign)}, // ImGuiStyleVar_ButtonTextAlign + {ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign)}, // ImGuiStyleVar_SelectableTextAlign +}; + +static const ImGuiStyleVarInfo *GetStyleVarInfo(ImGuiStyleVar idx) +{ + IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT); + IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT); + return &GStyleVarInfo[idx]; +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) +{ + const ImGuiStyleVarInfo *var_info = GetStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) + { + ImGuiContext &g = *GImGui; + float *pvar = (float *)var_info->GetVarPtr(&g.Style); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!"); +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2 &val) +{ + const ImGuiStyleVarInfo *var_info = GetStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2) + { + ImGuiContext &g = *GImGui; + ImVec2 *pvar = (ImVec2 *)var_info->GetVarPtr(&g.Style); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!"); +} + +void ImGui::PopStyleVar(int count) +{ + ImGuiContext &g = *GImGui; + while (count > 0) + { + // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it. + ImGuiStyleMod &backup = g.StyleVarStack.back(); + const ImGuiStyleVarInfo *info = GetStyleVarInfo(backup.VarIdx); + void *data = info->GetVarPtr(&g.Style); + if (info->Type == ImGuiDataType_Float && info->Count == 1) + { + ((float *)data)[0] = backup.BackupFloat[0]; + } + else if (info->Type == ImGuiDataType_Float && info->Count == 2) + { + ((float *)data)[0] = backup.BackupFloat[0]; + ((float *)data)[1] = backup.BackupFloat[1]; + } + g.StyleVarStack.pop_back(); + count--; + } +} + +const char *ImGui::GetStyleColorName(ImGuiCol idx) +{ + // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; + switch (idx) + { + case ImGuiCol_Text: + return "Text"; + case ImGuiCol_TextDisabled: + return "TextDisabled"; + case ImGuiCol_WindowBg: + return "WindowBg"; + case ImGuiCol_ChildBg: + return "ChildBg"; + case ImGuiCol_PopupBg: + return "PopupBg"; + case ImGuiCol_Border: + return "Border"; + case ImGuiCol_BorderShadow: + return "BorderShadow"; + case ImGuiCol_FrameBg: + return "FrameBg"; + case ImGuiCol_FrameBgHovered: + return "FrameBgHovered"; + case ImGuiCol_FrameBgActive: + return "FrameBgActive"; + case ImGuiCol_TitleBg: + return "TitleBg"; + case ImGuiCol_TitleBgActive: + return "TitleBgActive"; + case ImGuiCol_TitleBgCollapsed: + return "TitleBgCollapsed"; + case ImGuiCol_MenuBarBg: + return "MenuBarBg"; + case ImGuiCol_ScrollbarBg: + return "ScrollbarBg"; + case ImGuiCol_ScrollbarGrab: + return "ScrollbarGrab"; + case ImGuiCol_ScrollbarGrabHovered: + return "ScrollbarGrabHovered"; + case ImGuiCol_ScrollbarGrabActive: + return "ScrollbarGrabActive"; + case ImGuiCol_CheckMark: + return "CheckMark"; + case ImGuiCol_SliderGrab: + return "SliderGrab"; + case ImGuiCol_SliderGrabActive: + return "SliderGrabActive"; + case ImGuiCol_Button: + return "Button"; + case ImGuiCol_ButtonHovered: + return "ButtonHovered"; + case ImGuiCol_ButtonActive: + return "ButtonActive"; + case ImGuiCol_Header: + return "Header"; + case ImGuiCol_HeaderHovered: + return "HeaderHovered"; + case ImGuiCol_HeaderActive: + return "HeaderActive"; + case ImGuiCol_Separator: + return "Separator"; + case ImGuiCol_SeparatorHovered: + return "SeparatorHovered"; + case ImGuiCol_SeparatorActive: + return "SeparatorActive"; + case ImGuiCol_ResizeGrip: + return "ResizeGrip"; + case ImGuiCol_ResizeGripHovered: + return "ResizeGripHovered"; + case ImGuiCol_ResizeGripActive: + return "ResizeGripActive"; + case ImGuiCol_Tab: + return "Tab"; + case ImGuiCol_TabHovered: + return "TabHovered"; + case ImGuiCol_TabActive: + return "TabActive"; + case ImGuiCol_TabUnfocused: + return "TabUnfocused"; + case ImGuiCol_TabUnfocusedActive: + return "TabUnfocusedActive"; + case ImGuiCol_DockingPreview: + return "DockingPreview"; + case ImGuiCol_DockingEmptyBg: + return "DockingEmptyBg"; + case ImGuiCol_PlotLines: + return "PlotLines"; + case ImGuiCol_PlotLinesHovered: + return "PlotLinesHovered"; + case ImGuiCol_PlotHistogram: + return "PlotHistogram"; + case ImGuiCol_PlotHistogramHovered: + return "PlotHistogramHovered"; + case ImGuiCol_TableHeaderBg: + return "TableHeaderBg"; + case ImGuiCol_TableBorderStrong: + return "TableBorderStrong"; + case ImGuiCol_TableBorderLight: + return "TableBorderLight"; + case ImGuiCol_TableRowBg: + return "TableRowBg"; + case ImGuiCol_TableRowBgAlt: + return "TableRowBgAlt"; + case ImGuiCol_TextSelectedBg: + return "TextSelectedBg"; + case ImGuiCol_DragDropTarget: + return "DragDropTarget"; + case ImGuiCol_NavHighlight: + return "NavHighlight"; + case ImGuiCol_NavWindowingHighlight: + return "NavWindowingHighlight"; + case ImGuiCol_NavWindowingDimBg: + return "NavWindowingDimBg"; + case ImGuiCol_ModalWindowDimBg: + return "ModalWindowDimBg"; + } + IM_ASSERT(0); + return "Unknown"; +} + +//----------------------------------------------------------------------------- +// [SECTION] RENDER HELPERS +// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change, +// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context. +// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context. +//----------------------------------------------------------------------------- + +const char *ImGui::FindRenderedTextEnd(const char *text, const char *text_end) +{ + const char *text_display_end = text; + if (!text_end) + text_end = (const char *)-1; + + while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) + text_display_end++; + return text_display_end; +} + +// Internal ImGui functions to render text +// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() +void ImGui::RenderText(ImVec2 pos, const char *text, const char *text_end, bool hide_text_after_hash) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + // Hide anything after a '##' string + const char *text_display_end; + if (hide_text_after_hash) + { + text_display_end = FindRenderedTextEnd(text, text_end); + } + else + { + if (!text_end) + text_end = text + strlen(text); // FIXME-OPT + text_display_end = text_end; + } + + if (text != text_display_end) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_display_end); + } +} + +void ImGui::RenderTextWrapped(ImVec2 pos, const char *text, const char *text_end, float wrap_width) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + if (!text_end) + text_end = text + strlen(text); // FIXME-OPT + + if (text != text_end) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_end); + } +} + +// Default clip_rect uses (pos_min,pos_max) +// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) +void ImGui::RenderTextClippedEx(ImDrawList *draw_list, const ImVec2 &pos_min, const ImVec2 &pos_max, const char *text, const char *text_display_end, const ImVec2 *text_size_if_known, const ImVec2 &align, const ImRect *clip_rect) +{ + // Perform CPU side clipping for single clipped element to avoid using scissor state + ImVec2 pos = pos_min; + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); + + const ImVec2 *clip_min = clip_rect ? &clip_rect->Min : &pos_min; + const ImVec2 *clip_max = clip_rect ? &clip_rect->Max : &pos_max; + bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); + if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min + need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); + + // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. + if (align.x > 0.0f) + pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); + if (align.y > 0.0f) + pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); + + // Render + if (need_clipping) + { + ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); + draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); + } + else + { + draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); + } +} + +void ImGui::RenderTextClipped(const ImVec2 &pos_min, const ImVec2 &pos_max, const char *text, const char *text_end, const ImVec2 *text_size_if_known, const ImVec2 &align, const ImRect *clip_rect) +{ + // Hide anything after a '##' string + const char *text_display_end = FindRenderedTextEnd(text, text_end); + const int text_len = (int)(text_display_end - text); + if (text_len == 0) + return; + + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect); + if (g.LogEnabled) + LogRenderedText(&pos_min, text, text_display_end); +} + +// Another overly complex function until we reorganize everything into a nice all-in-one helper. +// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display. +// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move. +void ImGui::RenderTextEllipsis(ImDrawList *draw_list, const ImVec2 &pos_min, const ImVec2 &pos_max, float clip_max_x, float ellipsis_max_x, const char *text, const char *text_end_full, const ImVec2 *text_size_if_known) +{ + ImGuiContext &g = *GImGui; + if (text_end_full == NULL) + text_end_full = FindRenderedTextEnd(text); + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f); + + // draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255)); + // draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255)); + // draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255)); + // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels. + if (text_size.x > pos_max.x - pos_min.x) + { + // Hello wo... + // | | | + // min max ellipsis_max + // <-> this is generally some padding value + + const ImFont *font = draw_list->_Data->Font; + const float font_size = draw_list->_Data->FontSize; + const char *text_end_ellipsis = NULL; + + ImWchar ellipsis_char = font->EllipsisChar; + int ellipsis_char_count = 1; + if (ellipsis_char == (ImWchar)-1) + { + ellipsis_char = font->DotChar; + ellipsis_char_count = 3; + } + const ImFontGlyph *glyph = font->FindGlyph(ellipsis_char); + + float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side + float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis + + if (ellipsis_char_count > 1) + { + // Full ellipsis size without free spacing after it. + const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize); + ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots; + ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots; + } + + // We can now claim the space between pos_max.x and ellipsis_max.x + const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f); + float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x; + if (text == text_end_ellipsis && text_end_ellipsis < text_end_full) + { + // Always display at least 1 character if there's no room for character + ellipsis + text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full); + text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x; + } + while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1])) + { + // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text) + text_end_ellipsis--; + text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte + } + + // Render text, render ellipsis + RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f)); + float ellipsis_x = pos_min.x + text_size_clipped_x; + if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x) + for (int i = 0; i < ellipsis_char_count; i++) + { + font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char); + ellipsis_x += ellipsis_glyph_width; + } + } + else + { + RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f)); + } + + if (g.LogEnabled) + LogRenderedText(&pos_min, text, text_end_full); +} + +// Render a rectangle shaped with optional rounding and borders +void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); + const float border_size = g.Style.FrameBorderSize; + if (border && border_size > 0.0f) + { + window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size); + window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size); + } +} + +void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + const float border_size = g.Style.FrameBorderSize; + if (border_size > 0.0f) + { + window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size); + window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size); + } +} + +void ImGui::RenderNavHighlight(const ImRect &bb, ImGuiID id, ImGuiNavHighlightFlags flags) +{ + ImGuiContext &g = *GImGui; + if (id != g.NavId) + return; + if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw)) + return; + ImGuiWindow *window = g.CurrentWindow; + if (window->DC.NavHideHighlightOneFrame) + return; + + float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding; + ImRect display_rect = bb; + display_rect.ClipWith(window->ClipRect); + if (flags & ImGuiNavHighlightFlags_TypeDefault) + { + const float THICKNESS = 2.0f; + const float DISTANCE = 3.0f + THICKNESS * 0.5f; + display_rect.Expand(ImVec2(DISTANCE, DISTANCE)); + bool fully_visible = window->ClipRect.Contains(display_rect); + if (!fully_visible) + window->DrawList->PushClipRect(display_rect.Min, display_rect.Max); + window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS); + if (!fully_visible) + window->DrawList->PopClipRect(); + } + if (flags & ImGuiNavHighlightFlags_TypeThin) + { + window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f); + } +} + +void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT); + ImFontAtlas *font_atlas = g.DrawListSharedData.Font->ContainerAtlas; + for (int n = 0; n < g.Viewports.Size; n++) + { + // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor. + ImVec2 offset, size, uv[4]; + if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2])) + continue; + ImGuiViewportP *viewport = g.Viewports[n]; + const ImVec2 pos = base_pos - offset; + const float scale = base_scale * viewport->DpiScale; + if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale))) + continue; + ImDrawList *draw_list = GetForegroundDrawList(viewport); + ImTextureID tex_id = font_atlas->TexID; + draw_list->PushTextureID(tex_id); + draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border); + draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill); + draw_list->PopTextureID(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) +//----------------------------------------------------------------------------- + +// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods +ImGuiWindow::ImGuiWindow(ImGuiContext *context, const char *name) : DrawListInst(NULL) +{ + memset(this, 0, sizeof(*this)); + Name = ImStrdup(name); + NameBufLen = (int)strlen(name) + 1; + ID = ImHashStr(name); + IDStack.push_back(ID); + ViewportAllowPlatformMonitorExtend = -1; + ViewportPos = ImVec2(FLT_MAX, FLT_MAX); + MoveId = GetID("#MOVE"); + TabId = GetID("#TAB"); + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); + AutoFitFramesX = AutoFitFramesY = -1; + AutoPosLastDirection = ImGuiDir_None; + SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; + SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); + LastFrameActive = -1; + LastFrameJustFocused = -1; + LastTimeActive = -1.0f; + FontWindowScale = FontDpiScale = 1.0f; + SettingsOffset = -1; + DockOrder = -1; + DrawList = &DrawListInst; + DrawList->_Data = &context->DrawListSharedData; + DrawList->_OwnerName = Name; + IM_PLACEMENT_NEW(&WindowClass) + ImGuiWindowClass(); +} + +ImGuiWindow::~ImGuiWindow() +{ + IM_ASSERT(DrawList == &DrawListInst); + IM_DELETE(Name); + ColumnsStorage.clear_destruct(); +} + +ImGuiID ImGuiWindow::GetID(const char *str, const char *str_end) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); + ImGuiContext &g = *GImGui; + if (g.DebugHookIdInfo == id) + ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end); + return id; +} + +ImGuiID ImGuiWindow::GetID(const void *ptr) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHashData(&ptr, sizeof(void *), seed); + ImGuiContext &g = *GImGui; + if (g.DebugHookIdInfo == id) + ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL); + return id; +} + +ImGuiID ImGuiWindow::GetID(int n) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHashData(&n, sizeof(n), seed); + ImGuiContext &g = *GImGui; + if (g.DebugHookIdInfo == id) + ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void *)(intptr_t)n, NULL); + return id; +} + +// This is only used in rare/specific situations to manufacture an ID out of nowhere. +ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect &r_abs) +{ + ImGuiID seed = IDStack.back(); + ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs); + ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed); + return id; +} + +static void SetCurrentWindow(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + g.CurrentWindow = window; + g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL; + if (window) + g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); +} + +void ImGui::GcCompactTransientMiscBuffers() +{ + ImGuiContext &g = *GImGui; + g.ItemFlagsStack.clear(); + g.GroupStack.clear(); + TableGcCompactSettings(); +} + +// Free up/compact internal window buffers, we can use this when a window becomes unused. +// Not freed: +// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data) +// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost. +void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow *window) +{ + window->MemoryCompacted = true; + window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity; + window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity; + window->IDStack.clear(); + window->DrawList->_ClearFreeMemory(); + window->DC.ChildWindows.clear(); + window->DC.ItemWidthStack.clear(); + window->DC.TextWrapPosStack.clear(); +} + +void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow *window) +{ + // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening. + // The other buffers tends to amortize much faster. + window->MemoryCompacted = false; + window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity); + window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity); + window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0; +} + +void ImGui::SetActiveID(ImGuiID id, ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + g.ActiveIdIsJustActivated = (g.ActiveId != id); + if (g.ActiveIdIsJustActivated) + { + g.ActiveIdTimer = 0.0f; + g.ActiveIdHasBeenPressedBefore = false; + g.ActiveIdHasBeenEditedBefore = false; + g.ActiveIdMouseButton = -1; + if (id != 0) + { + g.LastActiveId = id; + g.LastActiveIdTimer = 0.0f; + } + } + g.ActiveId = id; + g.ActiveIdAllowOverlap = false; + g.ActiveIdNoClearOnFocusLoss = false; + g.ActiveIdWindow = window; + g.ActiveIdHasBeenEditedThisFrame = false; + if (id) + { + g.ActiveIdIsAlive = id; + g.ActiveIdSource = (g.NavActivateId == id || g.NavActivateInputId == id || g.NavJustMovedToId == id) ? (ImGuiInputSource)ImGuiInputSource_Nav : ImGuiInputSource_Mouse; + } + + // Clear declaration of inputs claimed by the widget + // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet) + g.ActiveIdUsingMouseWheel = false; + g.ActiveIdUsingNavDirMask = 0x00; + g.ActiveIdUsingNavInputMask = 0x00; + g.ActiveIdUsingKeyInputMask.ClearAllBits(); +} + +void ImGui::ClearActiveID() +{ + SetActiveID(0, NULL); // g.ActiveId = 0; +} + +void ImGui::SetHoveredID(ImGuiID id) +{ + ImGuiContext &g = *GImGui; + g.HoveredId = id; + g.HoveredIdAllowOverlap = false; + g.HoveredIdUsingMouseWheel = false; + if (id != 0 && g.HoveredIdPreviousFrame != id) + g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f; +} + +ImGuiID ImGui::GetHoveredID() +{ + ImGuiContext &g = *GImGui; + return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame; +} + +// This is called by ItemAdd(). +// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID(). +void ImGui::KeepAliveID(ImGuiID id) +{ + ImGuiContext &g = *GImGui; + if (g.ActiveId == id) + g.ActiveIdIsAlive = id; + if (g.ActiveIdPreviousFrame == id) + g.ActiveIdPreviousFrameIsAlive = true; +} + +void ImGui::MarkItemEdited(ImGuiID id) +{ + // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit(). + // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data. + ImGuiContext &g = *GImGui; + IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive); + IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out. + // IM_ASSERT(g.CurrentWindow->DC.LastItemId == id); + g.ActiveIdHasBeenEditedThisFrame = true; + g.ActiveIdHasBeenEditedBefore = true; + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited; +} + +static inline bool IsWindowContentHoverable(ImGuiWindow *window, ImGuiHoveredFlags flags) +{ + // An active popup disable hovering on other windows (apart from its own children) + // FIXME-OPT: This could be cached/stored within the window. + ImGuiContext &g = *GImGui; + if (g.NavWindow) + if (ImGuiWindow *focused_root_window = g.NavWindow->RootWindowDockTree) + if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree) + { + // For the purpose of those flags we differentiate "standard popup" from "modal popup" + // NB: The order of those two tests is important because Modal windows are also Popups. + if (focused_root_window->Flags & ImGuiWindowFlags_Modal) + return false; + if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + return false; + } + + // Filter by viewport + if (window->Viewport != g.MouseViewport) + if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree) + return false; + + return true; +} + +// This is roughly matching the behavior of internal-facing ItemHoverable() +// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() +// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId +bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride)) + { + if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled)) + return false; + if (!IsItemFocused()) + return false; + } + else + { + // Test for bounding box overlap, as updated as ItemAdd() + ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags; + if (!(status_flags & ImGuiItemStatusFlags_HoveredRect)) + return false; + IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0); // Flags not supported by this function + + // Test if we are hovering the right window (our window could be behind another window) + // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851) + // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable + // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was + // the test that has been running for a long while. + if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0) + if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0) + return false; + + // Test if another item is active (e.g. being dragged) + if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0) + if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap) + if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId) + return false; + + // Test if interactions on this window are blocked by an active popup or modal. + // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here. + if (!IsWindowContentHoverable(window, flags)) + return false; + + // Test if the item is disabled + if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled)) + return false; + + // Special handling for calling after Begin() which represent the title bar or tab. + // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin) + // will never be overwritten so we need to detect the case. + if (g.LastItemData.ID == window->MoveId && window->WriteAccessed) + return false; + } + + return true; +} + +// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered(). +bool ImGui::ItemHoverable(const ImRect &bb, ImGuiID id) +{ + ImGuiContext &g = *GImGui; + if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap) + return false; + + ImGuiWindow *window = g.CurrentWindow; + if (g.HoveredWindow != window) + return false; + if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) + return false; + if (!IsMouseHoveringRect(bb.Min, bb.Max)) + return false; + if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None)) + { + g.HoveredIdDisabled = true; + return false; + } + + // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level + // hover test in widgets code. We could also decide to split this function is two. + if (id != 0) + SetHoveredID(id); + + // When disabled we'll return false but still set HoveredId + ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags); + if (item_flags & ImGuiItemFlags_Disabled) + { + // Release active id if turning disabled + if (g.ActiveId == id) + ClearActiveID(); + g.HoveredIdDisabled = true; + return false; + } + + if (id != 0) + { + // [DEBUG] Item Picker tool! + // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making + // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered + // items if we perform the test in ItemAdd(), but that would incur a small runtime cost. + // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd(). + if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id) + GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255)); + if (g.DebugItemPickerBreakId == id) + IM_DEBUG_BREAK(); + } + + if (g.NavDisableMouseHover) + return false; + + return true; +} + +bool ImGui::IsClippedEx(const ImRect &bb, ImGuiID id) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (!bb.Overlaps(window->ClipRect)) + if (id == 0 || (id != g.ActiveId && id != g.NavId)) + if (!g.LogEnabled) + return true; + return false; +} + +// This is also inlined in ItemAdd() +// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect! +void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect &item_rect) +{ + ImGuiContext &g = *GImGui; + g.LastItemData.ID = item_id; + g.LastItemData.InFlags = in_flags; + g.LastItemData.StatusFlags = item_flags; + g.LastItemData.Rect = item_rect; +} + +float ImGui::CalcWrapWidthForPos(const ImVec2 &pos, float wrap_pos_x) +{ + if (wrap_pos_x < 0.0f) + return 0.0f; + + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (wrap_pos_x == 0.0f) + { + // We could decide to setup a default wrapping max point for auto-resizing windows, + // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function? + // if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) + // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x); + // else + wrap_pos_x = window->WorkRect.Max.x; + } + else if (wrap_pos_x > 0.0f) + { + wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space + } + + return ImMax(wrap_pos_x - pos.x, 1.0f); +} + +// IM_ALLOC() == ImGui::MemAlloc() +void *ImGui::MemAlloc(size_t size) +{ + if (ImGuiContext *ctx = GImGui) + ctx->IO.MetricsActiveAllocations++; + return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData); +} + +// IM_FREE() == ImGui::MemFree() +void ImGui::MemFree(void *ptr) +{ + if (ptr) + if (ImGuiContext *ctx = GImGui) + ctx->IO.MetricsActiveAllocations--; + return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData); +} + +const char *ImGui::GetClipboardText() +{ + ImGuiContext &g = *GImGui; + return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : ""; +} + +void ImGui::SetClipboardText(const char *text) +{ + ImGuiContext &g = *GImGui; + if (g.IO.SetClipboardTextFn) + g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text); +} + +const char *ImGui::GetVersion() +{ + return IMGUI_VERSION; +} + +// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself +// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module +ImGuiContext *ImGui::GetCurrentContext() +{ + return GImGui; +} + +void ImGui::SetCurrentContext(ImGuiContext *ctx) +{ +#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC + IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this. +#else + GImGui = ctx; +#endif +} + +void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void *user_data) +{ + GImAllocatorAllocFunc = alloc_func; + GImAllocatorFreeFunc = free_func; + GImAllocatorUserData = user_data; +} + +// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space) +void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc *p_alloc_func, ImGuiMemFreeFunc *p_free_func, void **p_user_data) +{ + *p_alloc_func = GImAllocatorAllocFunc; + *p_free_func = GImAllocatorFreeFunc; + *p_user_data = GImAllocatorUserData; +} + +ImGuiContext *ImGui::CreateContext(ImFontAtlas *shared_font_atlas) +{ + ImGuiContext *prev_ctx = GetCurrentContext(); + ImGuiContext *ctx = IM_NEW(ImGuiContext)(shared_font_atlas); + SetCurrentContext(ctx); + Initialize(); + if (prev_ctx != NULL) + SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one. + return ctx; +} + +void ImGui::DestroyContext(ImGuiContext *ctx) +{ + ImGuiContext *prev_ctx = GetCurrentContext(); + if (ctx == NULL) //-V1051 + ctx = prev_ctx; + SetCurrentContext(ctx); + Shutdown(); + SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL); + IM_DELETE(ctx); +} + +// No specific ordering/dependency support, will see as needed +ImGuiID ImGui::AddContextHook(ImGuiContext *ctx, const ImGuiContextHook *hook) +{ + ImGuiContext &g = *ctx; + IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_); + g.Hooks.push_back(*hook); + g.Hooks.back().HookId = ++g.HookIdNext; + return g.HookIdNext; +} + +// Deferred removal, avoiding issue with changing vector while iterating it +void ImGui::RemoveContextHook(ImGuiContext *ctx, ImGuiID hook_id) +{ + ImGuiContext &g = *ctx; + IM_ASSERT(hook_id != 0); + for (int n = 0; n < g.Hooks.Size; n++) + if (g.Hooks[n].HookId == hook_id) + g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_; +} + +// Call context hooks (used by e.g. test engine) +// We assume a small number of hooks so all stored in same array +void ImGui::CallContextHooks(ImGuiContext *ctx, ImGuiContextHookType hook_type) +{ + ImGuiContext &g = *ctx; + for (int n = 0; n < g.Hooks.Size; n++) + if (g.Hooks[n].Type == hook_type) + g.Hooks[n].Callback(&g, &g.Hooks[n]); +} + +ImGuiIO &ImGui::GetIO() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); + return GImGui->IO; +} + +ImGuiPlatformIO &ImGui::GetPlatformIO() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?"); + return GImGui->PlatformIO; +} + +// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() +ImDrawData *ImGui::GetDrawData() +{ + ImGuiContext &g = *GImGui; + ImGuiViewportP *viewport = g.Viewports[0]; + return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL; +} + +double ImGui::GetTime() +{ + return GImGui->Time; +} + +int ImGui::GetFrameCount() +{ + return GImGui->FrameCount; +} + +static ImDrawList *GetViewportDrawList(ImGuiViewportP *viewport, size_t drawlist_no, const char *drawlist_name) +{ + // Create the draw list on demand, because they are not frequently used for all viewports + ImGuiContext &g = *GImGui; + IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists)); + ImDrawList *draw_list = viewport->DrawLists[drawlist_no]; + if (draw_list == NULL) + { + draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData); + draw_list->_OwnerName = drawlist_name; + viewport->DrawLists[drawlist_no] = draw_list; + } + + // Our ImDrawList system requires that there is always a command + if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount) + { + draw_list->_ResetForNewFrame(); + draw_list->PushTextureID(g.IO.Fonts->TexID); + draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false); + viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount; + } + return draw_list; +} + +ImDrawList *ImGui::GetBackgroundDrawList(ImGuiViewport *viewport) +{ + return GetViewportDrawList((ImGuiViewportP *)viewport, 0, "##Background"); +} + +ImDrawList *ImGui::GetBackgroundDrawList() +{ + ImGuiContext &g = *GImGui; + return GetBackgroundDrawList(g.CurrentWindow->Viewport); +} + +ImDrawList *ImGui::GetForegroundDrawList(ImGuiViewport *viewport) +{ + return GetViewportDrawList((ImGuiViewportP *)viewport, 1, "##Foreground"); +} + +ImDrawList *ImGui::GetForegroundDrawList() +{ + ImGuiContext &g = *GImGui; + return GetForegroundDrawList(g.CurrentWindow->Viewport); +} + +ImDrawListSharedData *ImGui::GetDrawListSharedData() +{ + return &GImGui->DrawListSharedData; +} + +void ImGui::StartMouseMovingWindow(ImGuiWindow *window) +{ + // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows. + // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward. + // This is because we want ActiveId to be set even when the window is not permitted to move. + ImGuiContext &g = *GImGui; + FocusWindow(window); + SetActiveID(window->MoveId, window); + g.NavDisableHighlight = true; + g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos; + g.ActiveIdNoClearOnFocusLoss = true; + SetActiveIdUsingNavAndKeys(); + + bool can_move_window = true; + if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove)) + can_move_window = false; + if (ImGuiDockNode *node = window->DockNodeAsHost) + if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove)) + can_move_window = false; + if (can_move_window) + g.MovingWindow = window; +} + +// We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them. +// - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node. +// - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window. +void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow *window, ImGuiDockNode *node, bool undock_floating_node) +{ + ImGuiContext &g = *GImGui; + bool can_undock_node = false; + if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0) + { + // Can undock if: + // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy) + // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows) + ImGuiDockNode *root_node = DockNodeGetRootNode(node); + if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that. + if (undock_floating_node || root_node->IsDockSpace()) + can_undock_node = true; + } + + const bool clicked = IsMouseClicked(0); + const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f); + if (can_undock_node && dragging) + DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame + else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window) + StartMouseMovingWindow(window); +} + +// Handle mouse moving window +// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing() +// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId. +// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs, +// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other. +void ImGui::UpdateMouseMovingWindowNewFrame() +{ + ImGuiContext &g = *GImGui; + if (g.MovingWindow != NULL) + { + // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window). + // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency. + KeepAliveID(g.ActiveId); + IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree); + ImGuiWindow *moving_window = g.MovingWindow->RootWindowDockTree; + + // When a window stop being submitted while being dragged, it may will its viewport until next Begin() + const bool window_disappared = ((!moving_window->WasActive && !moving_window->Active) || moving_window->Viewport == NULL); + if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared) + { + ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset; + if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y) + { + MarkIniSettingsDirty(moving_window); + SetWindowPos(moving_window, pos, ImGuiCond_Always); + if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window. + { + moving_window->Viewport->Pos = pos; + moving_window->Viewport->UpdateWorkRect(); + } + } + FocusWindow(g.MovingWindow); + } + else + { + if (!window_disappared) + { + // Try to merge the window back into the main viewport. + // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports) + if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) + UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport); + + // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button. + if (!IsDragDropPayloadBeingAccepted()) + g.MouseViewport = moving_window->Viewport; + + // Clear the NoInput window flag set by the Viewport system + moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL. + } + + g.MovingWindow = NULL; + ClearActiveID(); + } + } + else + { + // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others. + if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId) + { + KeepAliveID(g.ActiveId); + if (!g.IO.MouseDown[0]) + ClearActiveID(); + } + } +} + +// Initiate moving window when clicking on empty space or title bar. +// Handle left-click and right-click focus. +void ImGui::UpdateMouseMovingWindowEndFrame() +{ + ImGuiContext &g = *GImGui; + if (g.ActiveId != 0 || g.HoveredId != 0) + return; + + // Unless we just made a window/popup appear + if (g.NavWindow && g.NavWindow->Appearing) + return; + + // Click on empty space to focus window and start moving + // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!) + if (g.IO.MouseClicked[0]) + { + // Handle the edge case of a popup being closed while clicking in its empty space. + // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. + ImGuiWindow *root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; + const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel); + + if (root_window != NULL && !is_closed_popup) + { + StartMouseMovingWindow(g.HoveredWindow); //-V595 + + // Cancel moving if clicked outside of title bar + if (g.IO.ConfigWindowsMoveFromTitleBarOnly) + if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive) + if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) + g.MovingWindow = NULL; + + // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already) + if (g.HoveredIdDisabled) + g.MovingWindow = NULL; + } + else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) + { + // Clicking on void disable focus + FocusWindow(NULL); + } + } + + // With right mouse button we close popups without changing focus based on where the mouse is aimed + // Instead, focus will be restored to the window under the bottom-most closed popup. + // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger) + if (g.IO.MouseClicked[1]) + { + // Find the top-most window between HoveredWindow and the top-most Modal Window. + // This is where we can trim the popup stack. + ImGuiWindow *modal = GetTopMostPopupModal(); + bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal)); + ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true); + } +} + +// This is called during NewFrame()->UpdateViewportsNewFrame() only. +// Need to keep in sync with SetWindowPos() +static void TranslateWindow(ImGuiWindow *window, const ImVec2 &delta) +{ + window->Pos += delta; + window->ClipRect.Translate(delta); + window->OuterRectClipped.Translate(delta); + window->InnerRect.Translate(delta); + window->DC.CursorPos += delta; + window->DC.CursorStartPos += delta; + window->DC.CursorMaxPos += delta; + window->DC.IdealMaxPos += delta; +} + +static void ScaleWindow(ImGuiWindow *window, float scale) +{ + ImVec2 origin = window->Viewport->Pos; + window->Pos = ImFloor((window->Pos - origin) * scale + origin); + window->Size = ImFloor(window->Size * scale); + window->SizeFull = ImFloor(window->SizeFull * scale); + window->ContentSize = ImFloor(window->ContentSize * scale); +} + +static bool IsWindowActiveAndVisible(ImGuiWindow *window) +{ + return (window->Active) && (!window->Hidden); +} + +static void ImGui::UpdateKeyboardInputs() +{ + ImGuiContext &g = *GImGui; + ImGuiIO &io = g.IO; + + // Import legacy keys or verify they are not used +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + if (io.BackendUsingLegacyKeyArrays == 0) + { + // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally. + for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++) + IM_ASSERT((io.KeysDown[n] == false || IsKeyDown(n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!"); + } + else + { + if (g.FrameCount == 0) + for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++) + IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!"); + + // Build reverse KeyMap (Named -> Legacy) + for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++) + if (io.KeyMap[n] != -1) + { + IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n])); + io.KeyMap[io.KeyMap[n]] = n; + } + + // Import legacy keys into new ones + for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++) + if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1) + { + const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n); + IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key)); + io.KeysData[key].Down = io.KeysDown[n]; + if (key != n) + io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends + io.BackendUsingLegacyKeyArrays = 1; + } + if (io.BackendUsingLegacyKeyArrays == 1) + { + io.KeysData[ImGuiKey_ModCtrl].Down = io.KeyCtrl; + io.KeysData[ImGuiKey_ModShift].Down = io.KeyShift; + io.KeysData[ImGuiKey_ModAlt].Down = io.KeyAlt; + io.KeysData[ImGuiKey_ModSuper].Down = io.KeySuper; + } + } +#endif + + // Synchronize io.KeyMods with individual modifiers io.KeyXXX bools + io.KeyMods = GetMergedModFlags(); + + // Clear gamepad data if disabled + if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0) + for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++) + { + io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false; + io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f; + } + + // Update keys + for (int i = 0; i < IM_ARRAYSIZE(io.KeysData); i++) + { + ImGuiKeyData *key_data = &io.KeysData[i]; + key_data->DownDurationPrev = key_data->DownDuration; + key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f; + } +} + +static void ImGui::UpdateMouseInputs() +{ + ImGuiContext &g = *GImGui; + ImGuiIO &io = g.IO; + + // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well) + if (IsMousePosValid(&io.MousePos)) + io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos); + + // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta + if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev)) + io.MouseDelta = io.MousePos - io.MousePosPrev; + else + io.MouseDelta = ImVec2(0.0f, 0.0f); + + // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true. + if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f) + g.NavDisableMouseHover = false; + + io.MousePosPrev = io.MousePos; + for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) + { + io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f; + io.MouseClickedCount[i] = 0; // Will be filled below + io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f; + io.MouseDownDurationPrev[i] = io.MouseDownDuration[i]; + io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f; + if (io.MouseClicked[i]) + { + bool is_repeated_click = false; + if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime) + { + ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); + if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist) + is_repeated_click = true; + } + if (is_repeated_click) + io.MouseClickedLastCount[i]++; + else + io.MouseClickedLastCount[i] = 1; + io.MouseClickedTime[i] = g.Time; + io.MouseClickedPos[i] = io.MousePos; + io.MouseClickedCount[i] = io.MouseClickedLastCount[i]; + io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f); + io.MouseDragMaxDistanceSqr[i] = 0.0f; + } + else if (io.MouseDown[i]) + { + // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold + ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); + io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos)); + io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x); + io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y); + } + + // We provide io.MouseDoubleClicked[] as a legacy service + io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2); + + // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation + if (io.MouseClicked[i]) + g.NavDisableMouseHover = false; + } +} + +static void StartLockWheelingWindow(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + if (g.WheelingWindow == window) + return; + g.WheelingWindow = window; + g.WheelingWindowRefMousePos = g.IO.MousePos; + g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER; +} + +void ImGui::UpdateMouseWheel() +{ + ImGuiContext &g = *GImGui; + + // Reset the locked window if we move the mouse or after the timer elapses + if (g.WheelingWindow != NULL) + { + g.WheelingWindowTimer -= g.IO.DeltaTime; + if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold) + g.WheelingWindowTimer = 0.0f; + if (g.WheelingWindowTimer <= 0.0f) + { + g.WheelingWindow = NULL; + g.WheelingWindowTimer = 0.0f; + } + } + + float wheel_x = g.IO.MouseWheelH; + float wheel_y = g.IO.MouseWheel; + if (wheel_x == 0.0f && wheel_y == 0.0f) + return; + + if ((g.ActiveId != 0 && g.ActiveIdUsingMouseWheel) || (g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrameUsingMouseWheel)) + return; + + ImGuiWindow *window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow; + if (!window || window->Collapsed) + return; + + // Zoom / Scale window + // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. + if (wheel_y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling) + { + StartLockWheelingWindow(window); + const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); + const float scale = new_font_scale / window->FontWindowScale; + window->FontWindowScale = new_font_scale; + if (window == window->RootWindow) + { + const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; + SetWindowPos(window, window->Pos + offset, 0); + window->Size = ImFloor(window->Size * scale); + window->SizeFull = ImFloor(window->SizeFull * scale); + } + return; + } + + // Mouse wheel scrolling + // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent + if (g.IO.KeyCtrl) + return; + + // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead + // (we avoid doing it on OSX as it the OS input layer handles this already) + const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors; + if (swap_axis) + { + wheel_x = wheel_y; + wheel_y = 0.0f; + } + + // Vertical Mouse Wheel scrolling + if (wheel_y != 0.0f) + { + StartLockWheelingWindow(window); + while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)))) + window = window->ParentWindow; + if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)) + { + float max_step = window->InnerRect.GetHeight() * 0.67f; + float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step)); + SetScrollY(window, window->Scroll.y - wheel_y * scroll_step); + } + } + + // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held + if (wheel_x != 0.0f) + { + StartLockWheelingWindow(window); + while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)))) + window = window->ParentWindow; + if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)) + { + float max_step = window->InnerRect.GetWidth() * 0.67f; + float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step)); + SetScrollX(window, window->Scroll.x - wheel_x * scroll_step); + } + } +} + +// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app) +void ImGui::UpdateHoveredWindowAndCaptureFlags() +{ + ImGuiContext &g = *GImGui; + ImGuiIO &io = g.IO; + g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING)); + + // Find the window hovered by mouse: + // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow. + // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame. + // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. + bool clear_hovered_windows = false; + FindHoveredWindow(); + IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport); + + // Modal windows prevents mouse from hovering behind them. + ImGuiWindow *modal_window = GetTopMostPopupModal(); + if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ? + clear_hovered_windows = true; + + // Disabled mouse? + if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) + clear_hovered_windows = true; + + // We track click ownership. When clicked outside of a window the click is owned by the application and + // won't report hovering nor request capture even while dragging over our windows afterward. + const bool has_open_popup = (g.OpenPopupStack.Size > 0); + const bool has_open_modal = (modal_window != NULL); + int mouse_earliest_down = -1; + bool mouse_any_down = false; + for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) + { + if (io.MouseClicked[i]) + { + io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup; + io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal; + } + mouse_any_down |= io.MouseDown[i]; + if (io.MouseDown[i]) + if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down]) + mouse_earliest_down = i; + } + const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down]; + const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down]; + + // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. + // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) + const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0; + if (!mouse_avail && !mouse_dragging_extern_payload) + clear_hovered_windows = true; + + if (clear_hovered_windows) + g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL; + + // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app) + // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag + if (g.WantCaptureMouseNextFrame != -1) + { + io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0); + } + else + { + io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup; + io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal; + } + + // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app) + if (g.WantCaptureKeyboardNextFrame != -1) + io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0); + else + io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL); + if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)) + io.WantCaptureKeyboard = true; + + // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible + io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; +} + +// [Internal] Do not use directly (can read io.KeyMods instead) +ImGuiModFlags ImGui::GetMergedModFlags() +{ + ImGuiContext &g = *GImGui; + ImGuiModFlags key_mods = ImGuiModFlags_None; + if (g.IO.KeyCtrl) + { + key_mods |= ImGuiModFlags_Ctrl; + } + if (g.IO.KeyShift) + { + key_mods |= ImGuiModFlags_Shift; + } + if (g.IO.KeyAlt) + { + key_mods |= ImGuiModFlags_Alt; + } + if (g.IO.KeySuper) + { + key_mods |= ImGuiModFlags_Super; + } + return key_mods; +} + +void ImGui::NewFrame() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); + ImGuiContext &g = *GImGui; + + // Remove pending delete hooks before frame start. + // This deferred removal avoid issues of removal while iterating the hook vector + for (int n = g.Hooks.Size - 1; n >= 0; n--) + if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_) + g.Hooks.erase(&g.Hooks[n]); + + CallContextHooks(&g, ImGuiContextHookType_NewFramePre); + + // Check and assert for various common IO and Configuration mistakes + g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame; + ErrorCheckNewFrameSanityChecks(); + g.ConfigFlagsCurrFrame = g.IO.ConfigFlags; + + // Load settings on first frame, save settings when modified (after a delay) + UpdateSettings(); + + g.Time += g.IO.DeltaTime; + g.WithinFrameScope = true; + g.FrameCount += 1; + g.TooltipOverrideCount = 0; + g.WindowsActiveCount = 0; + g.MenusIdSubmittedThisFrame.resize(0); + + // Calculate frame-rate for the user, as a purely luxurious feature + g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; + g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; + g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); + g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame)); + g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX; + + UpdateViewportsNewFrame(); + + // Setup current font and draw list shared data + // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! + g.IO.Fonts->Locked = true; + SetCurrentFont(GetDefaultFont()); + IM_ASSERT(g.Font->IsLoaded()); + ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); + for (int n = 0; n < g.Viewports.Size; n++) + virtual_space.Add(g.Viewports[n]->GetMainRect()); + g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4(); + g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; + g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError); + g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; + if (g.Style.AntiAliasedLines) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; + if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex; + if (g.Style.AntiAliasedFill) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; + if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; + + // Mark rendering data as invalid to prevent user who may have a handle on it to use it. + for (int n = 0; n < g.Viewports.Size; n++) + { + ImGuiViewportP *viewport = g.Viewports[n]; + viewport->DrawData = NULL; + viewport->DrawDataP.Clear(); + } + + // Drag and drop keep the source ID alive so even if the source disappear our state is consistent + if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId) + KeepAliveID(g.DragDropPayload.SourceId); + + // Update HoveredId data + if (!g.HoveredIdPreviousFrame) + g.HoveredIdTimer = 0.0f; + if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId)) + g.HoveredIdNotActiveTimer = 0.0f; + if (g.HoveredId) + g.HoveredIdTimer += g.IO.DeltaTime; + if (g.HoveredId && g.ActiveId != g.HoveredId) + g.HoveredIdNotActiveTimer += g.IO.DeltaTime; + g.HoveredIdPreviousFrame = g.HoveredId; + g.HoveredIdPreviousFrameUsingMouseWheel = g.HoveredIdUsingMouseWheel; + g.HoveredId = 0; + g.HoveredIdAllowOverlap = false; + g.HoveredIdUsingMouseWheel = false; + g.HoveredIdDisabled = false; + + // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore) + if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) + ClearActiveID(); + if (g.ActiveId) + g.ActiveIdTimer += g.IO.DeltaTime; + g.LastActiveIdTimer += g.IO.DeltaTime; + g.ActiveIdPreviousFrame = g.ActiveId; + g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow; + g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore; + g.ActiveIdIsAlive = 0; + g.ActiveIdHasBeenEditedThisFrame = false; + g.ActiveIdPreviousFrameIsAlive = false; + g.ActiveIdIsJustActivated = false; + if (g.TempInputId != 0 && g.ActiveId != g.TempInputId) + g.TempInputId = 0; + if (g.ActiveId == 0) + { + g.ActiveIdUsingNavDirMask = 0x00; + g.ActiveIdUsingNavInputMask = 0x00; + g.ActiveIdUsingKeyInputMask.ClearAllBits(); + } + + // Drag and drop + g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr; + g.DragDropAcceptIdCurr = 0; + g.DragDropAcceptIdCurrRectSurface = FLT_MAX; + g.DragDropWithinSource = false; + g.DragDropWithinTarget = false; + g.DragDropHoldJustPressedId = 0; + + // Close popups on focus lost (currently wip/opt-in) + // if (g.IO.AppFocusLost) + // ClosePopupsExceptModals(); + + // Process input queue (trickle as many events as possible) + g.InputEventsTrail.resize(0); + UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue); + + // Update keyboard input state + UpdateKeyboardInputs(); + + // IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl)); + // IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift)); + // IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt)); + // IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper)); + + // Update gamepad/keyboard navigation + NavUpdate(); + + // Update mouse input state + UpdateMouseInputs(); + + // Undocking + // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame) + DockContextNewFrameUpdateUndocking(&g); + + // Find hovered window + // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame) + UpdateHoveredWindowAndCaptureFlags(); + + // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) + UpdateMouseMovingWindowNewFrame(); + + // Background darkening/whitening + if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f)) + g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f); + else + g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f); + + g.MouseCursor = ImGuiMouseCursor_Arrow; + g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1; + + // Platform IME data: reset for the frame + g.PlatformImeDataPrev = g.PlatformImeData; + g.PlatformImeData.WantVisible = false; + + // Mouse wheel scrolling, scale + UpdateMouseWheel(); + + // Mark all windows as not visible and compact unused memory. + IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size); + const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer; + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow *window = g.Windows[i]; + window->WasActive = window->Active; + window->BeginCount = 0; + window->Active = false; + window->WriteAccessed = false; + + // Garbage collect transient buffers of recently unused windows + if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time) + GcCompactTransientWindowBuffers(window); + } + + // Garbage collect transient buffers of recently unused tables + for (int i = 0; i < g.TablesLastTimeActive.Size; i++) + if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time) + TableGcCompactTransientBuffers(g.Tables.GetByIndex(i)); + for (int i = 0; i < g.TablesTempData.Size; i++) + if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time) + TableGcCompactTransientBuffers(&g.TablesTempData[i]); + if (g.GcCompactAll) + GcCompactTransientMiscBuffers(); + g.GcCompactAll = false; + + // Closing the focused window restore focus to the first active root window in descending z-order + if (g.NavWindow && !g.NavWindow->WasActive) + FocusTopMostWindowUnderOne(NULL, NULL); + + // No window should be open at the beginning of the frame. + // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. + g.CurrentWindowStack.resize(0); + g.BeginPopupStack.resize(0); + g.ItemFlagsStack.resize(0); + g.ItemFlagsStack.push_back(ImGuiItemFlags_None); + g.GroupStack.resize(0); + + // Docking + DockContextNewFrameUpdateDocking(&g); + + // [DEBUG] Update debug features + UpdateDebugToolItemPicker(); + UpdateDebugToolStackQueries(); + + // Create implicit/fallback window - which we will only render it if the user has added something to it. + // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. + // This fallback is particularly important as it avoid ImGui:: calls from crashing. + g.WithinFrameScopeWithImplicitWindow = true; + SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver); + Begin("Debug##Default"); + IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true); + + CallContextHooks(&g, ImGuiContextHookType_NewFramePost); +} + +void ImGui::Initialize() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(!g.Initialized && !g.SettingsLoaded); + + // Add .ini handle for ImGuiWindow type + { + ImGuiSettingsHandler ini_handler; + ini_handler.TypeName = "Window"; + ini_handler.TypeHash = ImHashStr("Window"); + ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll; + ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen; + ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll; + ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll; + AddSettingsHandler(&ini_handler); + } + + // Add .ini handle for ImGuiTable type + TableSettingsAddSettingsHandler(); + + // Create default viewport + ImGuiViewportP *viewport = IM_NEW(ImGuiViewportP)(); + viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID; + viewport->Idx = 0; + viewport->PlatformWindowCreated = true; + viewport->Flags = ImGuiViewportFlags_OwnedByApp; + g.Viewports.push_back(viewport); + g.PlatformIO.Viewports.push_back(g.Viewports[0]); + +#ifdef IMGUI_HAS_DOCK + // Initialize Docking + DockContextInitialize(&g); +#endif + + g.Initialized = true; +} + +// This function is merely here to free heap allocations. +void ImGui::Shutdown() +{ + // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) + ImGuiContext &g = *GImGui; + if (g.IO.Fonts && g.FontAtlasOwnedByContext) + { + g.IO.Fonts->Locked = false; + IM_DELETE(g.IO.Fonts); + } + g.IO.Fonts = NULL; + + // Cleanup of other data are conditional on actually having initialized Dear ImGui. + if (!g.Initialized) + return; + + // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file) + if (g.SettingsLoaded && g.IO.IniFilename != NULL) + SaveIniSettingsToDisk(g.IO.IniFilename); + + // Destroy platform windows + DestroyPlatformWindows(); + + // Shutdown extensions + DockContextShutdown(&g); + + CallContextHooks(&g, ImGuiContextHookType_Shutdown); + + // Clear everything else + g.Windows.clear_delete(); + g.WindowsFocusOrder.clear(); + g.WindowsTempSortBuffer.clear(); + g.CurrentWindow = NULL; + g.CurrentWindowStack.clear(); + g.WindowsById.Clear(); + g.NavWindow = NULL; + g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL; + g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL; + g.MovingWindow = NULL; + g.ColorStack.clear(); + g.StyleVarStack.clear(); + g.FontStack.clear(); + g.OpenPopupStack.clear(); + g.BeginPopupStack.clear(); + + g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL; + g.Viewports.clear_delete(); + + g.TabBars.Clear(); + g.CurrentTabBarStack.clear(); + g.ShrinkWidthBuffer.clear(); + + g.ClipperTempData.clear_destruct(); + + g.Tables.Clear(); + g.TablesTempData.clear_destruct(); + g.DrawChannelsTempMergeBuffer.clear(); + + g.ClipboardHandlerData.clear(); + g.MenusIdSubmittedThisFrame.clear(); + g.InputTextState.ClearFreeMemory(); + + g.SettingsWindows.clear(); + g.SettingsHandlers.clear(); + + if (g.LogFile) + { +#ifndef IMGUI_DISABLE_TTY_FUNCTIONS + if (g.LogFile != stdout) +#endif + ImFileClose(g.LogFile); + g.LogFile = NULL; + } + g.LogBuffer.clear(); + + g.Initialized = false; +} + +// FIXME: Add a more explicit sort order in the window structure. +static int IMGUI_CDECL ChildWindowComparer(const void *lhs, const void *rhs) +{ + const ImGuiWindow *const a = *(const ImGuiWindow *const *)lhs; + const ImGuiWindow *const b = *(const ImGuiWindow *const *)rhs; + if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) + return d; + if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) + return d; + return (a->BeginOrderWithinParent - b->BeginOrderWithinParent); +} + +static void AddWindowToSortBuffer(ImVector *out_sorted_windows, ImGuiWindow *window) +{ + out_sorted_windows->push_back(window); + if (window->Active) + { + int count = window->DC.ChildWindows.Size; + ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow *), ChildWindowComparer); + for (int i = 0; i < count; i++) + { + ImGuiWindow *child = window->DC.ChildWindows[i]; + if (child->Active) + AddWindowToSortBuffer(out_sorted_windows, child); + } + } +} + +static void AddDrawListToDrawData(ImVector *out_list, ImDrawList *draw_list) +{ + if (draw_list->CmdBuffer.Size == 0) + return; + if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL) + return; + + // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. + // May trigger for you if you are using PrimXXX functions incorrectly. + IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); + IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); + if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset)) + IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); + + // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window) + // If this assert triggers because you are drawing lots of stuff manually: + // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds. + // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents. + // - If you want large meshes with more than 64K vertices, you can either: + // (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'. + // Most example backends already support this from 1.71. Pre-1.71 backends won't. + // Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them. + // (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h. + // Most example backends already support this. For example, the OpenGL example code detect index size at compile-time: + // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); + // Your own engine or render API may use different parameters or function calls to specify index sizes. + // 2 and 4 bytes indices are generally supported by most graphics API. + // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching + // the 64K limit to split your draw commands in multiple draw lists. + if (sizeof(ImDrawIdx) == 2) + IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above"); + + out_list->push_back(draw_list); +} + +static void AddWindowToDrawData(ImGuiWindow *window, int layer) +{ + ImGuiContext &g = *GImGui; + ImGuiViewportP *viewport = window->Viewport; + g.IO.MetricsRenderWindows++; + if (window->Flags & ImGuiWindowFlags_DockNodeHost) + window->DrawList->ChannelsMerge(); + AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList); + for (int i = 0; i < window->DC.ChildWindows.Size; i++) + { + ImGuiWindow *child = window->DC.ChildWindows[i]; + if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active + AddWindowToDrawData(child, layer); + } +} + +static inline int GetWindowDisplayLayer(ImGuiWindow *window) +{ + return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0; +} + +// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu) +static inline void AddRootWindowToDrawData(ImGuiWindow *window) +{ + AddWindowToDrawData(window, GetWindowDisplayLayer(window)); +} + +void ImDrawDataBuilder::FlattenIntoSingleLayer() +{ + int n = Layers[0].Size; + int size = n; + for (int i = 1; i < IM_ARRAYSIZE(Layers); i++) + size += Layers[i].Size; + Layers[0].resize(size); + for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++) + { + ImVector &layer = Layers[layer_n]; + if (layer.empty()) + continue; + memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList *)); + n += layer.Size; + layer.resize(0); + } +} + +static void SetupViewportDrawData(ImGuiViewportP *viewport, ImVector *draw_lists) +{ + // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode, + // and to allow applications/backends to easily skip rendering. + // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure. + // This is because the work has been done already, and its wasted! We should fix that and add optimizations for + // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline. + const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_Minimized) != 0; + + ImGuiIO &io = ImGui::GetIO(); + ImDrawData *draw_data = &viewport->DrawDataP; + viewport->DrawData = draw_data; // Make publicly accessible + draw_data->Valid = true; + draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL; + draw_data->CmdListsCount = draw_lists->Size; + draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0; + draw_data->DisplayPos = viewport->Pos; + draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size; + draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis? + draw_data->OwnerViewport = viewport; + for (int n = 0; n < draw_lists->Size; n++) + { + ImDrawList *draw_list = draw_lists->Data[n]; + draw_list->_PopUnusedDrawCmd(); + draw_data->TotalVtxCount += draw_list->VtxBuffer.Size; + draw_data->TotalIdxCount += draw_list->IdxBuffer.Size; + } +} + +// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. +// - When using this function it is sane to ensure that float are perfectly rounded to integer values, +// so that e.g. (int)(max.x-min.x) in user's render produce correct result. +// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect(): +// some frequently called functions which to modify both channels and clipping simultaneously tend to use the +// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds. +void ImGui::PushClipRect(const ImVec2 &clip_rect_min, const ImVec2 &clip_rect_max, bool intersect_with_current_clip_rect) +{ + ImGuiWindow *window = GetCurrentWindow(); + window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} + +void ImGui::PopClipRect() +{ + ImGuiWindow *window = GetCurrentWindow(); + window->DrawList->PopClipRect(); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} + +static ImGuiWindow *FindFrontMostVisibleChildWindow(ImGuiWindow *window) +{ + for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--) + if (IsWindowActiveAndVisible(window->DC.ChildWindows[n])) + return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]); + return window; +} + +static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow *window, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + ImGuiViewportP *viewport = window->Viewport; + ImRect viewport_rect = viewport->GetMainRect(); + + // Draw behind window by moving the draw command at the FRONT of the draw list + { + // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows, + // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing. + // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order. + ImDrawList *draw_list = window->RootWindowDockTree->DrawList; + if (draw_list->CmdBuffer.Size == 0) + draw_list->AddDrawCmd(); + draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged + draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col); + ImDrawCmd cmd = draw_list->CmdBuffer.back(); + IM_ASSERT(cmd.ElemCount == 6); + draw_list->CmdBuffer.pop_back(); + draw_list->CmdBuffer.push_front(cmd); + draw_list->PopClipRect(); + draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command. + } + + // Draw over sibling docking nodes in a same docking tree + if (window->RootWindow->DockIsActive) + { + ImDrawList *draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList; + if (draw_list->CmdBuffer.Size == 0) + draw_list->AddDrawCmd(); + draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false); + RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f); // window->RootWindowDockTree->WindowRounding); + draw_list->PopClipRect(); + } +} + +ImGuiWindow *ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow *parent_window) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *bottom_most_visible_window = parent_window; + for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--) + { + ImGuiWindow *window = g.Windows[i]; + if (window->Flags & ImGuiWindowFlags_ChildWindow) + continue; + if (!IsWindowWithinBeginStackOf(window, parent_window)) + break; + if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window)) + bottom_most_visible_window = window; + } + return bottom_most_visible_window; +} + +static void ImGui::RenderDimmedBackgrounds() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *modal_window = GetTopMostAndVisiblePopupModal(); + if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f) + return; + const bool dim_bg_for_modal = (modal_window != NULL); + const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active); + if (!dim_bg_for_modal && !dim_bg_for_window_list) + return; + + ImGuiViewport *viewports_already_dimmed[2] = {NULL, NULL}; + if (dim_bg_for_modal) + { + // Draw dimming behind modal or a begin stack child, whichever comes first in draw order. + ImGuiWindow *dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window); + RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio)); + viewports_already_dimmed[0] = modal_window->Viewport; + } + else if (dim_bg_for_window_list) + { + // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window + RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio)); + if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport) + RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio)); + viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport; + viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL; + + // Draw border around CTRL+Tab target window + ImGuiWindow *window = g.NavWindowingTargetAnim; + ImGuiViewport *viewport = window->Viewport; + float distance = g.FontSize; + ImRect bb = window->Rect(); + bb.Expand(distance); + if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y) + bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward + if (window->DrawList->CmdBuffer.Size == 0) + window->DrawList->AddDrawCmd(); + window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size); + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f); + window->DrawList->PopClipRect(); + } + + // Draw dimming background on _other_ viewports than the ones our windows are in + for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++) + { + ImGuiViewportP *viewport = g.Viewports[viewport_n]; + if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1]) + continue; + if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window)) + continue; + ImDrawList *draw_list = GetForegroundDrawList(viewport); + const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio); + draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col); + } +} + +// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. +void ImGui::EndFrame() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.Initialized); + + // Don't process EndFrame() multiple times. + if (g.FrameCountEnded == g.FrameCount) + return; + IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?"); + + CallContextHooks(&g, ImGuiContextHookType_EndFramePre); + + ErrorCheckEndFrameSanityChecks(); + + // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) + if (g.IO.SetPlatformImeDataFn && memcmp(&g.PlatformImeData, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0) + { + ImGuiViewport *viewport = FindViewportByID(g.PlatformImeViewport); + g.IO.SetPlatformImeDataFn(viewport ? viewport : GetMainViewport(), &g.PlatformImeData); + } + + // Hide implicit/fallback "Debug" window if it hasn't been used + g.WithinFrameScopeWithImplicitWindow = false; + if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed) + g.CurrentWindow->Active = false; + End(); + + // Update navigation: CTRL+Tab, wrap-around requests + NavEndFrame(); + + // Update docking + DockContextEndFrame(&g); + + SetCurrentViewport(NULL, NULL); + + // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted) + if (g.DragDropActive) + { + bool is_delivered = g.DragDropPayload.Delivery; + bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton)); + if (is_delivered || is_elapsed) + ClearDragDrop(); + } + + // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing. + if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) + { + g.DragDropWithinSource = true; + SetTooltip("..."); + g.DragDropWithinSource = false; + } + + // End frame + g.WithinFrameScope = false; + g.FrameCountEnded = g.FrameCount; + + // Initiate moving window + handle left-click and right-click focus + UpdateMouseMovingWindowEndFrame(); + + // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) + UpdateViewportsEndFrame(); + + // Sort the window list so that all child windows are after their parent + // We cannot do that on FocusWindow() because children may not exist yet + g.WindowsTempSortBuffer.resize(0); + g.WindowsTempSortBuffer.reserve(g.Windows.Size); + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow *window = g.Windows[i]; + if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it + continue; + AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window); + } + + // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong. + IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size); + g.Windows.swap(g.WindowsTempSortBuffer); + g.IO.MetricsActiveWindows = g.WindowsActiveCount; + + // Unlock font atlas + g.IO.Fonts->Locked = false; + + // Clear Input data for next frame + g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f; + g.IO.InputQueueCharacters.resize(0); + memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs)); + + CallContextHooks(&g, ImGuiContextHookType_EndFramePost); +} + +// Prepare the data for rendering so you can call GetDrawData() +// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all: +// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend) +void ImGui::Render() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.Initialized); + + if (g.FrameCountEnded != g.FrameCount) + EndFrame(); + const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount); + g.FrameCountRendered = g.FrameCount; + g.IO.MetricsRenderWindows = 0; + + CallContextHooks(&g, ImGuiContextHookType_RenderPre); + + // Add background ImDrawList (for each active viewport) + for (int n = 0; n != g.Viewports.Size; n++) + { + ImGuiViewportP *viewport = g.Viewports[n]; + viewport->DrawDataBuilder.Clear(); + if (viewport->DrawLists[0] != NULL) + AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport)); + } + + // Add ImDrawList to render + ImGuiWindow *windows_to_render_top_most[2]; + windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL; + windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL); + for (int n = 0; n != g.Windows.Size; n++) + { + ImGuiWindow *window = g.Windows[n]; + IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'" + if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1]) + AddRootWindowToDrawData(window); + } + for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++) + if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window + AddRootWindowToDrawData(windows_to_render_top_most[n]); + + // Draw modal/window whitening backgrounds + if (first_render_of_frame) + RenderDimmedBackgrounds(); + + // Draw software mouse cursor if requested by io.MouseDrawCursor flag + if (g.IO.MouseDrawCursor && first_render_of_frame && g.MouseCursor != ImGuiMouseCursor_None) + RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48)); + + // Setup ImDrawData structures for end-user + g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0; + for (int n = 0; n < g.Viewports.Size; n++) + { + ImGuiViewportP *viewport = g.Viewports[n]; + viewport->DrawDataBuilder.FlattenIntoSingleLayer(); + + // Add foreground ImDrawList (for each active viewport) + if (viewport->DrawLists[1] != NULL) + AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport)); + + SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]); + ImDrawData *draw_data = viewport->DrawData; + g.IO.MetricsRenderVertices += draw_data->TotalVtxCount; + g.IO.MetricsRenderIndices += draw_data->TotalIdxCount; + } + + CallContextHooks(&g, ImGuiContextHookType_RenderPost); +} + +// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. +// CalcTextSize("") should return ImVec2(0.0f, g.FontSize) +ImVec2 ImGui::CalcTextSize(const char *text, const char *text_end, bool hide_text_after_double_hash, float wrap_width) +{ + ImGuiContext &g = *GImGui; + + const char *text_display_end; + if (hide_text_after_double_hash) + text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string + else + text_display_end = text_end; + + ImFont *font = g.Font; + const float font_size = g.FontSize; + if (text == text_display_end) + return ImVec2(0.0f, font_size); + ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); + + // Round + // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out. + // FIXME: Investigate using ceilf or e.g. + // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c + // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html + text_size.x = IM_FLOOR(text_size.x + 0.99999f); + + return text_size; +} + +// Find window given position, search front-to-back +// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically +// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is +// called, aka before the next Begin(). Moving window isn't affected. +static void FindHoveredWindow() +{ + ImGuiContext &g = *GImGui; + + // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame) + ImGuiViewportP *moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL; + if (g.MovingWindow) + g.MovingWindow->Viewport = g.MouseViewport; + + ImGuiWindow *hovered_window = NULL; + ImGuiWindow *hovered_window_ignoring_moving_window = NULL; + if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs)) + hovered_window = g.MovingWindow; + + ImVec2 padding_regular = g.Style.TouchExtraPadding; + ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular; + for (int i = g.Windows.Size - 1; i >= 0; i--) + { + ImGuiWindow *window = g.Windows[i]; + IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer. + if (!window->Active || window->Hidden) + continue; + if (window->Flags & ImGuiWindowFlags_NoMouseInputs) + continue; + IM_ASSERT(window->Viewport); + if (window->Viewport != g.MouseViewport) + continue; + + // Using the clipped AABB, a child window will typically be clipped by its parent (not always) + ImRect bb(window->OuterRectClipped); + if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) + bb.Expand(padding_regular); + else + bb.Expand(padding_for_resize); + if (!bb.Contains(g.IO.MousePos)) + continue; + + // Support for one rectangular hole in any given window + // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512) + if (window->HitTestHoleSize.x != 0) + { + ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y); + ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y); + if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos)) + continue; + } + + if (hovered_window == NULL) + hovered_window = window; + IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer. + if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)) + hovered_window_ignoring_moving_window = window; + if (hovered_window && hovered_window_ignoring_moving_window) + break; + } + + g.HoveredWindow = hovered_window; + g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window; + + if (g.MovingWindow) + g.MovingWindow->Viewport = moving_window_viewport; +} + +bool ImGui::IsItemActive() +{ + ImGuiContext &g = *GImGui; + if (g.ActiveId) + return g.ActiveId == g.LastItemData.ID; + return false; +} + +bool ImGui::IsItemActivated() +{ + ImGuiContext &g = *GImGui; + if (g.ActiveId) + if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID) + return true; + return false; +} + +bool ImGui::IsItemDeactivated() +{ + ImGuiContext &g = *GImGui; + if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated) + return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0; + return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID); +} + +bool ImGui::IsItemDeactivatedAfterEdit() +{ + ImGuiContext &g = *GImGui; + return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore)); +} + +// == GetItemID() == GetFocusID() +bool ImGui::IsItemFocused() +{ + ImGuiContext &g = *GImGui; + if (g.NavId != g.LastItemData.ID || g.NavId == 0) + return false; + + // Special handling for the dummy item after Begin() which represent the title bar or tab. + // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. + ImGuiWindow *window = g.CurrentWindow; + if (g.LastItemData.ID == window->ID && window->WriteAccessed) + return false; + + return true; +} + +// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()! +// Most widgets have specific reactions based on mouse-up/down state, mouse position etc. +bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button) +{ + return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None); +} + +bool ImGui::IsItemToggledOpen() +{ + ImGuiContext &g = *GImGui; + return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false; +} + +bool ImGui::IsItemToggledSelection() +{ + ImGuiContext &g = *GImGui; + return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false; +} + +bool ImGui::IsAnyItemHovered() +{ + ImGuiContext &g = *GImGui; + return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0; +} + +bool ImGui::IsAnyItemActive() +{ + ImGuiContext &g = *GImGui; + return g.ActiveId != 0; +} + +bool ImGui::IsAnyItemFocused() +{ + ImGuiContext &g = *GImGui; + return g.NavId != 0 && !g.NavDisableHighlight; +} + +bool ImGui::IsItemVisible() +{ + ImGuiContext &g = *GImGui; + return g.CurrentWindow->ClipRect.Overlaps(g.LastItemData.Rect); +} + +bool ImGui::IsItemEdited() +{ + ImGuiContext &g = *GImGui; + return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0; +} + +// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. +// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework. +void ImGui::SetItemAllowOverlap() +{ + ImGuiContext &g = *GImGui; + ImGuiID id = g.LastItemData.ID; + if (g.HoveredId == id) + g.HoveredIdAllowOverlap = true; + if (g.ActiveId == id) + g.ActiveIdAllowOverlap = true; +} + +void ImGui::SetItemUsingMouseWheel() +{ + ImGuiContext &g = *GImGui; + ImGuiID id = g.LastItemData.ID; + if (g.HoveredId == id) + g.HoveredIdUsingMouseWheel = true; + if (g.ActiveId == id) + g.ActiveIdUsingMouseWheel = true; +} + +void ImGui::SetActiveIdUsingNavAndKeys() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.ActiveId != 0); + g.ActiveIdUsingNavDirMask = ~(ImU32)0; + g.ActiveIdUsingNavInputMask = ~(ImU32)0; + g.ActiveIdUsingKeyInputMask.SetAllBits(); + NavMoveRequestCancel(); +} + +ImVec2 ImGui::GetItemRectMin() +{ + ImGuiContext &g = *GImGui; + return g.LastItemData.Rect.Min; +} + +ImVec2 ImGui::GetItemRectMax() +{ + ImGuiContext &g = *GImGui; + return g.LastItemData.Rect.Max; +} + +ImVec2 ImGui::GetItemRectSize() +{ + ImGuiContext &g = *GImGui; + return g.LastItemData.Rect.GetSize(); +} + +bool ImGui::BeginChildEx(const char *name, ImGuiID id, const ImVec2 &size_arg, bool border, ImGuiWindowFlags flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *parent_window = g.CurrentWindow; + + flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking; + flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag + + // Size + const ImVec2 content_avail = GetContentRegionAvail(); + ImVec2 size = ImFloor(size_arg); + const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00); + if (size.x <= 0.0f) + size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues) + if (size.y <= 0.0f) + size.y = ImMax(content_avail.y + size.y, 4.0f); + SetNextWindowSize(size); + + // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value. + if (name) + ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%s_%08X", parent_window->Name, name, id); + else + ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%08X", parent_window->Name, id); + + const float backup_border_size = g.Style.ChildBorderSize; + if (!border) + g.Style.ChildBorderSize = 0.0f; + bool ret = Begin(g.TempBuffer, NULL, flags); + g.Style.ChildBorderSize = backup_border_size; + + ImGuiWindow *child_window = g.CurrentWindow; + child_window->ChildId = id; + child_window->AutoFitChildAxises = (ImS8)auto_fit_axises; + + // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually. + // While this is not really documented/defined, it seems that the expected thing to do. + if (child_window->BeginCount == 1) + parent_window->DC.CursorPos = child_window->Pos; + + // Process navigation-in immediately so NavInit can run on first frame + if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll)) + { + FocusWindow(child_window); + NavInitWindow(child_window, false); + SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item + g.ActiveIdSource = ImGuiInputSource_Nav; + } + return ret; +} + +bool ImGui::BeginChild(const char *str_id, const ImVec2 &size_arg, bool border, ImGuiWindowFlags extra_flags) +{ + ImGuiWindow *window = GetCurrentWindow(); + return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags); +} + +bool ImGui::BeginChild(ImGuiID id, const ImVec2 &size_arg, bool border, ImGuiWindowFlags extra_flags) +{ + IM_ASSERT(id != 0); + return BeginChildEx(NULL, id, size_arg, border, extra_flags); +} + +void ImGui::EndChild() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + IM_ASSERT(g.WithinEndChild == false); + IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls + + g.WithinEndChild = true; + if (window->BeginCount > 1) + { + End(); + } + else + { + ImVec2 sz = window->Size; + if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f + sz.x = ImMax(4.0f, sz.x); + if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y)) + sz.y = ImMax(4.0f, sz.y); + End(); + + ImGuiWindow *parent_window = g.CurrentWindow; + ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz); + ItemSize(sz); + if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened)) + { + ItemAdd(bb, window->ChildId); + RenderNavHighlight(bb, window->ChildId); + + // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying) + if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow) + RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin); + } + else + { + // Not navigable into + ItemAdd(bb, 0); + } + if (g.HoveredWindow == window) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; + } + g.WithinEndChild = false; + g.LogLinePosY = -FLT_MAX; // To enforce a carriage return +} + +// Helper to create a child window / scrolling region that looks like a normal widget frame. +bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2 &size, ImGuiWindowFlags extra_flags) +{ + ImGuiContext &g = *GImGui; + const ImGuiStyle &style = g.Style; + PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]); + PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); + PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); + PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); + bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); + PopStyleVar(3); + PopStyleColor(); + return ret; +} + +void ImGui::EndChildFrame() +{ + EndChild(); +} + +static void SetWindowConditionAllowFlags(ImGuiWindow *window, ImGuiCond flags, bool enabled) +{ + window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags); + window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags); + window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags); + window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags); +} + +ImGuiWindow *ImGui::FindWindowByID(ImGuiID id) +{ + ImGuiContext &g = *GImGui; + return (ImGuiWindow *)g.WindowsById.GetVoidPtr(id); +} + +ImGuiWindow *ImGui::FindWindowByName(const char *name) +{ + ImGuiID id = ImHashStr(name); + return FindWindowByID(id); +} + +static void ApplyWindowSettings(ImGuiWindow *window, ImGuiWindowSettings *settings) +{ + const ImGuiViewport *main_viewport = ImGui::GetMainViewport(); + window->ViewportPos = main_viewport->Pos; + if (settings->ViewportId) + { + window->ViewportId = settings->ViewportId; + window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y); + } + window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y)); + if (settings->Size.x > 0 && settings->Size.y > 0) + window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y)); + window->Collapsed = settings->Collapsed; + window->DockId = settings->DockId; + window->DockOrder = settings->DockOrder; +} + +static void UpdateWindowInFocusOrderList(ImGuiWindow *window, bool just_created, ImGuiWindowFlags new_flags) +{ + ImGuiContext &g = *GImGui; + + const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0; + const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild; + if ((just_created || child_flag_changed) && !new_is_explicit_child) + { + IM_ASSERT(!g.WindowsFocusOrder.contains(window)); + g.WindowsFocusOrder.push_back(window); + window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1); + } + else if (!just_created && child_flag_changed && new_is_explicit_child) + { + IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window); + for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++) + g.WindowsFocusOrder[n]->FocusOrder--; + g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder); + window->FocusOrder = -1; + } + window->IsExplicitChild = new_is_explicit_child; +} + +static ImGuiWindow *CreateNewWindow(const char *name, ImGuiWindowFlags flags) +{ + ImGuiContext &g = *GImGui; + // IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags); + + // Create window the first time + ImGuiWindow *window = IM_NEW(ImGuiWindow)(&g, name); + window->Flags = flags; + g.WindowsById.SetVoidPtr(window->ID, window); + + // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. + const ImGuiViewport *main_viewport = ImGui::GetMainViewport(); + window->Pos = main_viewport->Pos + ImVec2(60, 60); + window->ViewportPos = main_viewport->Pos; + + // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + if (ImGuiWindowSettings *settings = ImGui::FindWindowSettings(window->ID)) + { + // Retrieve settings from .ini file + window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); + SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); + ApplyWindowSettings(window, settings); + } + window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values + + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) + { + window->AutoFitFramesX = window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = false; + } + else + { + if (window->Size.x <= 0.0f) + window->AutoFitFramesX = 2; + if (window->Size.y <= 0.0f) + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); + } + + if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) + g.Windows.push_front(window); // Quite slow but rare and only once + else + g.Windows.push_back(window); + UpdateWindowInFocusOrderList(window, true, window->Flags); + + return window; +} + +static ImGuiWindow *GetWindowForTitleDisplay(ImGuiWindow *window) +{ + return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window; +} + +static ImGuiWindow *GetWindowForTitleAndMenuHeight(ImGuiWindow *window) +{ + return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window; +} + +static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow *window, const ImVec2 &size_desired) +{ + ImGuiContext &g = *GImGui; + ImVec2 new_size = size_desired; + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) + { + // Using -1,-1 on either X/Y axis to preserve the current size. + ImRect cr = g.NextWindowData.SizeConstraintRect; + new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; + new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; + if (g.NextWindowData.SizeCallback) + { + ImGuiSizeCallbackData data; + data.UserData = g.NextWindowData.SizeCallbackUserData; + data.Pos = window->Pos; + data.CurrentSize = window->SizeFull; + data.DesiredSize = new_size; + g.NextWindowData.SizeCallback(&data); + new_size = data.DesiredSize; + } + new_size.x = IM_FLOOR(new_size.x); + new_size.y = IM_FLOOR(new_size.y); + } + + // Minimum size + if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) + { + ImGuiWindow *window_for_height = GetWindowForTitleAndMenuHeight(window); + const float decoration_up_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight(); + new_size = ImMax(new_size, g.Style.WindowMinSize); + new_size.y = ImMax(new_size.y, decoration_up_height + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows + } + return new_size; +} + +static void CalcWindowContentSizes(ImGuiWindow *window, ImVec2 *content_size_current, ImVec2 *content_size_ideal) +{ + bool preserve_old_content_sizes = false; + if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + preserve_old_content_sizes = true; + else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0) + preserve_old_content_sizes = true; + if (preserve_old_content_sizes) + { + *content_size_current = window->ContentSize; + *content_size_ideal = window->ContentSizeIdeal; + return; + } + + content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); + content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); + content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x); + content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y); +} + +static ImVec2 CalcWindowAutoFitSize(ImGuiWindow *window, const ImVec2 &size_contents) +{ + ImGuiContext &g = *GImGui; + ImGuiStyle &style = g.Style; + const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); + ImVec2 size_pad = window->WindowPadding * 2.0f; + ImVec2 size_desired = size_contents + size_pad + ImVec2(0.0f, decoration_up_height); + if (window->Flags & ImGuiWindowFlags_Tooltip) + { + // Tooltip always resize + return size_desired; + } + else + { + // Maximum window size is determined by the viewport size or monitor size + const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0; + const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0; + ImVec2 size_min = style.WindowMinSize; + if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) + size_min = ImMin(size_min, ImVec2(4.0f, 4.0f)); + + // FIXME-VIEWPORT-WORKAREA: May want to use GetWorkSize() instead of Size depending on the type of windows? + ImVec2 avail_size = window->Viewport->Size; + if (window->ViewportOwned) + avail_size = ImVec2(FLT_MAX, FLT_MAX); + const int monitor_idx = window->ViewportAllowPlatformMonitorExtend; + if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size) + avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize; + ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f)); + + // When the window cannot fit all contents (either because of constraints, either because screen is too small), + // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. + ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit); + bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - 0.0f < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar); + bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_up_height < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar); + if (will_have_scrollbar_x) + size_auto_fit.y += style.ScrollbarSize; + if (will_have_scrollbar_y) + size_auto_fit.x += style.ScrollbarSize; + return size_auto_fit; + } +} + +ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow *window) +{ + ImVec2 size_contents_current; + ImVec2 size_contents_ideal; + CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal); + ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal); + ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit); + return size_final; +} + +static ImGuiCol GetWindowBgColorIdx(ImGuiWindow *window) +{ + if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) + return ImGuiCol_PopupBg; + if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive) + return ImGuiCol_ChildBg; + return ImGuiCol_WindowBg; +} + +static void CalcResizePosSizeFromAnyCorner(ImGuiWindow *window, const ImVec2 &corner_target, const ImVec2 &corner_norm, ImVec2 *out_pos, ImVec2 *out_size) +{ + ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left + ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right + ImVec2 size_expected = pos_max - pos_min; + ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected); + *out_pos = pos_min; + if (corner_norm.x == 0.0f) + out_pos->x -= (size_constrained.x - size_expected.x); + if (corner_norm.y == 0.0f) + out_pos->y -= (size_constrained.y - size_expected.y); + *out_size = size_constrained; +} + +// Data for resizing from corner +struct ImGuiResizeGripDef +{ + ImVec2 CornerPosN; + ImVec2 InnerDir; + int AngleMin12, AngleMax12; +}; +static const ImGuiResizeGripDef resize_grip_def[4] = + { + {ImVec2(1, 1), ImVec2(-1, -1), 0, 3}, // Lower-right + {ImVec2(0, 1), ImVec2(+1, -1), 3, 6}, // Lower-left + {ImVec2(0, 0), ImVec2(+1, +1), 6, 9}, // Upper-left (Unused) + {ImVec2(1, 0), ImVec2(-1, +1), 9, 12} // Upper-right (Unused) +}; + +// Data for resizing from borders +struct ImGuiResizeBorderDef +{ + ImVec2 InnerDir; + ImVec2 SegmentN1, SegmentN2; + float OuterAngle; +}; +static const ImGuiResizeBorderDef resize_border_def[4] = + { + {ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f}, // Left + {ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f}, // Right + {ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f}, // Up + {ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f} // Down +}; + +static ImRect GetResizeBorderRect(ImGuiWindow *window, int border_n, float perp_padding, float thickness) +{ + ImRect rect = window->Rect(); + if (thickness == 0.0f) + rect.Max -= ImVec2(1, 1); + if (border_n == ImGuiDir_Left) + { + return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); + } + if (border_n == ImGuiDir_Right) + { + return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); + } + if (border_n == ImGuiDir_Up) + { + return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); + } + if (border_n == ImGuiDir_Down) + { + return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); + } + IM_ASSERT(0); + return ImRect(); +} + +// 0..3: corners (Lower-right, Lower-left, Unused, Unused) +ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow *window, int n) +{ + IM_ASSERT(n >= 0 && n < 4); + ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID; + id = ImHashStr("#RESIZE", 0, id); + id = ImHashData(&n, sizeof(int), id); + return id; +} + +// Borders (Left, Right, Up, Down) +ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow *window, ImGuiDir dir) +{ + IM_ASSERT(dir >= 0 && dir < 4); + int n = (int)dir + 4; + ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID; + id = ImHashStr("#RESIZE", 0, id); + id = ImHashData(&n, sizeof(int), id); + return id; +} + +// Handle resize for: Resize Grips, Borders, Gamepad +// Return true when using auto-fit (double click on resize grip) +static bool ImGui::UpdateWindowManualResize(ImGuiWindow *window, const ImVec2 &size_auto_fit, int *border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect &visibility_rect) +{ + ImGuiContext &g = *GImGui; + ImGuiWindowFlags flags = window->Flags; + + if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) + return false; + if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window. + return false; + + bool ret_auto_fit = false; + const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0; + const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); + const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f); + const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f; + + ImVec2 pos_target(FLT_MAX, FLT_MAX); + ImVec2 size_target(FLT_MAX, FLT_MAX); + + // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time). + // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits. + // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it. + // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow. + // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold). + // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. + const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration); + if (clip_with_viewport_rect) + window->ClipRect = window->Viewport->GetMainRect(); + + // Resize grips and borders are on layer 1 + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + + // Manual resize grips + PushID("#RESIZE"); + for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) + { + const ImGuiResizeGripDef &def = resize_grip_def[resize_grip_n]; + const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN); + + // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window + bool hovered, held; + ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size); + if (resize_rect.Min.x > resize_rect.Max.x) + ImSwap(resize_rect.Min.x, resize_rect.Max.x); + if (resize_rect.Min.y > resize_rect.Max.y) + ImSwap(resize_rect.Min.y, resize_rect.Max.y); + ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID() + KeepAliveID(resize_grip_id); + ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); + // GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)); + if (hovered || held) + g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE; + + if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0) + { + // Manual auto-fit when double-clicking + size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit); + ret_auto_fit = true; + ClearActiveID(); + } + else if (held) + { + // Resize from any of the four corners + // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position + ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX); + ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip + corner_target = ImClamp(corner_target, clamp_min, clamp_max); + CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target); + } + + // Only lower-left grip is visible before hovering/activating + if (resize_grip_n == 0 || held || hovered) + resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered + : ImGuiCol_ResizeGrip); + } + for (int border_n = 0; border_n < resize_border_count; border_n++) + { + const ImGuiResizeBorderDef &def = resize_border_def[border_n]; + const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; + + bool hovered, held; + ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING); + ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID() + KeepAliveID(border_id); + ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); + // GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)); + if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held) + { + g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS; + if (held) + *border_held = border_n; + } + if (held) + { + ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max(border_n == ImGuiDir_Left ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? visibility_rect.Max.y : +FLT_MAX); + ImVec2 border_target = window->Pos; + border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; + border_target = ImClamp(border_target, clamp_min, clamp_max); + CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target); + } + } + PopID(); + + // Restore nav layer + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + + // Navigation resize (keyboard/gamepad) + if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window) + { + ImVec2 nav_resize_delta; + if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift) + nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_RawKeyboard, ImGuiNavReadMode_Down); + if (g.NavInputSource == ImGuiInputSource_Gamepad) + nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiNavReadMode_Down); + if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f) + { + const float NAV_RESIZE_SPEED = 600.0f; + nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); + nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size); + g.NavWindowingToggleLayer = false; + g.NavDisableMouseHover = true; + resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); + // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck. + size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta); + } + } + + // Apply back modified position/size to window + if (size_target.x != FLT_MAX) + { + window->SizeFull = size_target; + MarkIniSettingsDirty(window); + } + if (pos_target.x != FLT_MAX) + { + window->Pos = ImFloor(pos_target); + MarkIniSettingsDirty(window); + } + + window->Size = window->SizeFull; + return ret_auto_fit; +} + +static inline void ClampWindowRect(ImGuiWindow *window, const ImRect &visibility_rect) +{ + ImGuiContext &g = *GImGui; + ImVec2 size_for_clamping = window->Size; + if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost)) + size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here. + window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max); +} + +static void ImGui::RenderWindowOuterBorders(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + float rounding = window->WindowRounding; + float border_size = window->WindowBorderSize; + if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground)) + window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size); + + int border_held = window->ResizeBorderHeld; + if (border_held != -1) + { + const ImGuiResizeBorderDef &def = resize_border_def[border_held]; + ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f); + window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle); + window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f); + window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual + } + if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) + { + float y = window->Pos.y + window->TitleBarHeight() - 1; + window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize); + } +} + +// Draw background and borders +// Draw and handle scrollbars +void ImGui::RenderWindowDecorations(ImGuiWindow *window, const ImRect &title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size) +{ + ImGuiContext &g = *GImGui; + ImGuiStyle &style = g.Style; + ImGuiWindowFlags flags = window->Flags; + + // Ensure that ScrollBar doesn't read last frame's SkipItems + IM_ASSERT(window->BeginCount == 0); + window->SkipItems = false; + + // Draw window + handle manual resize + // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame. + const float window_rounding = window->WindowRounding; + const float window_border_size = window->WindowBorderSize; + if (window->Collapsed) + { + // Title bar only + float backup_border_size = style.FrameBorderSize; + g.Style.FrameBorderSize = window->WindowBorderSize; + ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed); + RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding); + g.Style.FrameBorderSize = backup_border_size; + } + else + { + // Window background + if (!(flags & ImGuiWindowFlags_NoBackground)) + { + bool is_docking_transparent_payload = false; + if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload) + if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow **)g.DragDropPayload.Data == window) + is_docking_transparent_payload = true; + + ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window)); + if (window->ViewportOwned) + { + // No alpha + bg_col = (bg_col | IM_COL32_A_MASK); + if (is_docking_transparent_payload) + window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; + } + else + { + // Adjust alpha. For docking + bool override_alpha = false; + float alpha = 1.0f; + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha) + { + alpha = g.NextWindowData.BgAlphaVal; + override_alpha = true; + } + if (is_docking_transparent_payload) + { + alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override? + override_alpha = true; + } + if (override_alpha) + bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); + } + + // Render, for docked windows and host windows we ensure bg goes before decorations + ImDrawList *bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList; + if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost)) + bg_draw_list->ChannelsSetCurrent(0); + if (window->DockIsActive) + window->DockNode->LastBgColor = bg_col; + + bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom); + + if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost)) + bg_draw_list->ChannelsSetCurrent(1); + } + if (window->DockIsActive) + window->DockNode->IsBgDrawnThisFrame = true; + + // Title bar + // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag, + // in order for their pos/size to be matching their undocking state.) + if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) + { + ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); + window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop); + } + + // Menu bar + if (flags & ImGuiWindowFlags_MenuBar) + { + ImRect menu_bar_rect = window->MenuBarRect(); + menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. + window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop); + if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) + window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); + } + + // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock + ImGuiDockNode *node = window->DockNode; + if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar()) + { + float unhide_sz_draw = ImFloor(g.FontSize * 0.70f); + float unhide_sz_hit = ImFloor(g.FontSize * 0.55f); + ImVec2 p = node->Pos; + ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit)); + ImGuiID unhide_id = window->GetID("#UNHIDE"); + KeepAliveID(unhide_id); + bool hovered, held; + if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren)) + node->WantHiddenTabBarToggle = true; + else if (held && IsMouseDragging(0)) + StartMouseMovingWindowOrNode(window, node, true); + + // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size.. + ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered + : ImGuiCol_Button); + window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col); + } + + // Scrollbars + if (window->ScrollbarX) + Scrollbar(ImGuiAxis_X); + if (window->ScrollbarY) + Scrollbar(ImGuiAxis_Y); + + // Render resize grips (after their input handling so we don't have a frame of latency) + if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize)) + { + for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) + { + const ImGuiResizeGripDef &grip = resize_grip_def[resize_grip_n]; + const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN); + window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size))); + window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size))); + window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12); + window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]); + } + } + + // Borders (for dock node host they will be rendered over after the tab bar) + if (handle_borders_and_resize_grips && !window->DockNodeAsHost) + RenderWindowOuterBorders(window); + } +} + +// Render title text, collapse button, close button +// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. +void ImGui::RenderWindowTitleBarContents(ImGuiWindow *window, const ImRect &title_bar_rect, const char *name, bool *p_open) +{ + ImGuiContext &g = *GImGui; + ImGuiStyle &style = g.Style; + ImGuiWindowFlags flags = window->Flags; + + const bool has_close_button = (p_open != NULL); + const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None); + + // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) + // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref? + const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags; + g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + + // Layout buttons + // FIXME: Would be nice to generalize the subtleties expressed here into reusable code. + float pad_l = style.FramePadding.x; + float pad_r = style.FramePadding.x; + float button_sz = g.FontSize; + ImVec2 close_button_pos; + ImVec2 collapse_button_pos; + if (has_close_button) + { + pad_r += button_sz; + close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y); + } + if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right) + { + pad_r += button_sz; + collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y); + } + if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left) + { + collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y); + pad_l += button_sz; + } + + // Collapse button (submitting first so it gets priority when choosing a navigation init fallback) + if (has_collapse_button) + if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL)) + window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function + + // Close button + if (has_close_button) + if (CloseButton(window->GetID("#CLOSE"), close_button_pos)) + *p_open = false; + + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + g.CurrentItemFlags = item_flags_backup; + + // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) + // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. + const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f; + const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f); + + // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, + // while uncentered title text will still reach edges correctly. + if (pad_l > style.FramePadding.x) + pad_l += g.Style.ItemInnerSpacing.x; + if (pad_r > style.FramePadding.x) + pad_r += g.Style.ItemInnerSpacing.x; + if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f) + { + float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center + float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x); + pad_l = ImMax(pad_l, pad_extend * centerness); + pad_r = ImMax(pad_r, pad_extend * centerness); + } + + ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y); + ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y); + if (flags & ImGuiWindowFlags_UnsavedDocument) + { + ImVec2 marker_pos; + marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x); + marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f; + if (marker_pos.x > layout_r.Min.x) + { + RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text)); + clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f)); + } + } + // if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG] + // if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG] + RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r); +} + +void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow *window, ImGuiWindowFlags flags, ImGuiWindow *parent_window) +{ + window->ParentWindow = parent_window; + window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window; + if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) + { + window->RootWindowDockTree = parent_window->RootWindowDockTree; + if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost)) + window->RootWindow = parent_window->RootWindow; + } + if (parent_window && (flags & ImGuiWindowFlags_Popup)) + window->RootWindowPopupTree = parent_window->RootWindowPopupTree; + if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) + window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight; + while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened) + { + IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL); + window->RootWindowForNav = window->RootWindowForNav->ParentWindow; + } +} + +// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing) +// should be positioned behind that modal window, unless the window was created inside the modal begin-stack. +// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent. +// - Window // FindBlockingModal() returns Modal1 +// - Window // .. returns Modal1 +// - Modal1 // .. returns Modal2 +// - Window // .. returns Modal2 +// - Window // .. returns Modal2 +// - Modal2 // .. returns Modal2 +static ImGuiWindow *ImGui::FindBlockingModal(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + if (g.OpenPopupStack.Size <= 0) + return NULL; + + // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal. + for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--) + { + ImGuiWindow *popup_window = g.OpenPopupStack.Data[i].Window; + if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal)) + continue; + if (!popup_window->Active && !popup_window->WasActive) // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows. + continue; + if (IsWindowWithinBeginStackOf(window, popup_window)) // Window is rendered over last modal, no render order change needed. + break; + for (ImGuiWindow *parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow) + if (IsWindowWithinBeginStackOf(window, parent)) + return popup_window; // Place window above its begin stack parent. + } + return NULL; +} + +// Push a new Dear ImGui window to add widgets to. +// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. +// - Begin/End can be called multiple times during the frame with the same window name to append content. +// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). +// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. +// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. +// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. +bool ImGui::Begin(const char *name, bool *p_open, ImGuiWindowFlags flags) +{ + ImGuiContext &g = *GImGui; + const ImGuiStyle &style = g.Style; + IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required + IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame() + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet + + // Find or create + ImGuiWindow *window = FindWindowByName(name); + const bool window_just_created = (window == NULL); + if (window_just_created) + window = CreateNewWindow(name, flags); + else + UpdateWindowInFocusOrderList(window, window_just_created, flags); + + // Automatically disable manual moving/resizing when NoInputs is set + if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs) + flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; + + if (flags & ImGuiWindowFlags_NavFlattened) + IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow); + + const int current_frame = g.FrameCount; + const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); + window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow); + + // Update the Appearing flag (note: the BeginDocked() path may also set this to true later) + bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupData &popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; + window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed + window_just_activated_by_user |= (window != popup_ref.Window); + } + + // Update Flags, LastFrameActive, BeginOrderXXX fields + const bool window_was_appearing = window->Appearing; + if (first_begin_of_the_frame) + { + window->Appearing = window_just_activated_by_user; + if (window->Appearing) + SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); + + window->FlagsPreviousFrame = window->Flags; + window->Flags = (ImGuiWindowFlags)flags; + window->LastFrameActive = current_frame; + window->LastTimeActive = (float)g.Time; + window->BeginOrderWithinParent = 0; + window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++); + } + else + { + flags = window->Flags; + } + + // Docking + // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1) + IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock) + SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond); + if (first_begin_of_the_frame) + { + bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL); + bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window); + bool dock_node_was_visible = window->DockNodeIsVisible; + bool dock_tab_was_visible = window->DockTabIsVisible; + if (has_dock_node || new_auto_dock_node) + { + BeginDocked(window, p_open); + flags = window->Flags; + if (window->DockIsActive) + { + IM_ASSERT(window->DockNode != NULL); + g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints + } + + // Amend the Appearing flag + if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing) + { + window->Appearing = true; + SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); + } + } + else + { + window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false; + } + } + + // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack + ImGuiWindow *parent_window_in_stack = window->DockIsActive ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL + : g.CurrentWindowStack.back().Window; + ImGuiWindow *parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow; + IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); + + // We allow window memory to be compacted so recreate the base stack when needed. + if (window->IDStack.Size == 0) + window->IDStack.push_back(window->ID); + + // Add to stack + // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow() + g.CurrentWindow = window; + ImGuiWindowStackData window_stack_data; + window_stack_data.Window = window; + window_stack_data.ParentLastItemDataBackup = g.LastItemData; + window_stack_data.StackSizesOnBegin.SetToCurrentState(); + g.CurrentWindowStack.push_back(window_stack_data); + g.CurrentWindow = NULL; + if (flags & ImGuiWindowFlags_ChildMenu) + g.BeginMenuCount++; + + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupData &popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; + popup_ref.Window = window; + g.BeginPopupStack.push_back(popup_ref); + window->PopupId = popup_ref.PopupId; + } + + // Update ->RootWindow and others pointers (before any possible call to FocusWindow) + if (first_begin_of_the_frame) + { + UpdateWindowParentAndRootLinks(window, flags, parent_window); + window->ParentWindowInBeginStack = parent_window_in_stack; + } + + // Process SetNextWindow***() calls + // (FIXME: Consider splitting the HasXXX flags into X/Y components + bool window_pos_set_by_api = false; + bool window_size_x_set_by_api = false, window_size_y_set_by_api = false; + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) + { + window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0; + if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f) + { + // May be processed on the next frame if this is our first frame and we are measuring size + // FIXME: Look into removing the branch so everything can go through this same code path for consistency. + window->SetWindowPosVal = g.NextWindowData.PosVal; + window->SetWindowPosPivot = g.NextWindowData.PosPivotVal; + window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + } + else + { + SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond); + } + } + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) + { + window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f); + window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f); + SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond); + } + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll) + { + if (g.NextWindowData.ScrollVal.x >= 0.0f) + { + window->ScrollTarget.x = g.NextWindowData.ScrollVal.x; + window->ScrollTargetCenterRatio.x = 0.0f; + } + if (g.NextWindowData.ScrollVal.y >= 0.0f) + { + window->ScrollTarget.y = g.NextWindowData.ScrollVal.y; + window->ScrollTargetCenterRatio.y = 0.0f; + } + } + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize) + window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal; + else if (first_begin_of_the_frame) + window->ContentSizeExplicit = ImVec2(0.0f, 0.0f); + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass) + window->WindowClass = g.NextWindowData.WindowClass; + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed) + SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus) + FocusWindow(window); + if (window->Appearing) + SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false); + + // When reusing window again multiple times a frame, just append content (don't need to setup again) + if (first_begin_of_the_frame) + { + // Initialize + const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) + const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0); + window->Active = true; + window->HasCloseButton = (p_open != NULL); + window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX); + window->IDStack.resize(1); + window->DrawList->_ResetForNewFrame(); + window->DC.CurrentTableIdx = -1; + if (flags & ImGuiWindowFlags_DockNodeHost) + { + window->DrawList->ChannelsSplit(2); + window->DrawList->ChannelsSetCurrent(1); // Render decorations on channel 1 as we will render the backgrounds manually later + } + + // Restore buffer capacity when woken from a compacted state, to avoid + if (window->MemoryCompacted) + GcAwakeTransientWindowBuffers(window); + + // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged). + // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere. + bool window_title_visible_elsewhere = false; + if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive)) + window_title_visible_elsewhere = true; + else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB + window_title_visible_elsewhere = true; + if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0) + { + size_t buf_len = (size_t)window->NameBufLen; + window->Name = ImStrdupcpy(window->Name, &buf_len, name); + window->NameBufLen = (int)buf_len; + } + + // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS + + // Update contents size from last frame for auto-fitting (or use explicit size) + CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal); + + // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors + // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because + // it has a single usage before this code block and may be set below before it is finally checked. + if (window->HiddenFramesCanSkipItems > 0) + window->HiddenFramesCanSkipItems--; + if (window->HiddenFramesCannotSkipItems > 0) + window->HiddenFramesCannotSkipItems--; + if (window->HiddenFramesForRenderOnly > 0) + window->HiddenFramesForRenderOnly--; + + // Hide new windows for one frame until they calculate their size + if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api)) + window->HiddenFramesCannotSkipItems = 1; + + // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows) + // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size. + if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0) + { + window->HiddenFramesCannotSkipItems = 1; + if (flags & ImGuiWindowFlags_AlwaysAutoResize) + { + if (!window_size_x_set_by_api) + window->Size.x = window->SizeFull.x = 0.f; + if (!window_size_y_set_by_api) + window->Size.y = window->SizeFull.y = 0.f; + window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f); + } + } + + // SELECT VIEWPORT + // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes. + + WindowSelectViewport(window); + SetCurrentViewport(window, window->Viewport); + window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f; + SetCurrentWindow(window); + flags = window->Flags; + + // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies) + // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style. + + if (flags & ImGuiWindowFlags_ChildWindow) + window->WindowBorderSize = style.ChildBorderSize; + else + window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize; + if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f) + window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f); + else + window->WindowPadding = style.WindowPadding; + + // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size. + window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); + window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; + + // Collapse window by double-clicking on title bar + // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing + if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive) + { + // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar. + ImRect title_bar_rect = window->TitleBarRect(); + if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2) + window->WantCollapseToggle = true; + if (window->WantCollapseToggle) + { + window->Collapsed = !window->Collapsed; + MarkIniSettingsDirty(window); + } + } + else + { + window->Collapsed = false; + } + window->WantCollapseToggle = false; + + // SIZE + + // Calculate auto-fit size, handle automatic resize + const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal); + bool use_current_size_for_scrollbar_x = window_just_created; + bool use_current_size_for_scrollbar_y = window_just_created; + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) + { + // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. + if (!window_size_x_set_by_api) + { + window->SizeFull.x = size_auto_fit.x; + use_current_size_for_scrollbar_x = true; + } + if (!window_size_y_set_by_api) + { + window->SizeFull.y = size_auto_fit.y; + use_current_size_for_scrollbar_y = true; + } + } + else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) + { + // Auto-fit may only grow window during the first few frames + // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. + if (!window_size_x_set_by_api && window->AutoFitFramesX > 0) + { + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + use_current_size_for_scrollbar_x = true; + } + if (!window_size_y_set_by_api && window->AutoFitFramesY > 0) + { + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + use_current_size_for_scrollbar_y = true; + } + if (!window->Collapsed) + MarkIniSettingsDirty(window); + } + + // Apply minimum/maximum window size constraints and final size + window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull); + window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull; + + // Decoration size + const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); + + // POSITION + + // Popup latch its initial position, will position itself when it appears next frame + if (window_just_activated_by_user) + { + window->AutoPosLastDirection = ImGuiDir_None; + if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos() + window->Pos = g.BeginPopupStack.back().OpenPopupPos; + } + + // Position child window + if (flags & ImGuiWindowFlags_ChildWindow) + { + IM_ASSERT(parent_window && parent_window->Active); + window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size; + parent_window->DC.ChildWindows.push_back(window); + if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip) + window->Pos = parent_window->DC.CursorPos; + } + + const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0); + if (window_pos_with_pivot) + SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering) + else if ((flags & ImGuiWindowFlags_ChildMenu) != 0) + window->Pos = FindBestWindowPosForPopup(window); + else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize) + window->Pos = FindBestWindowPosForPopup(window); + else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip) + window->Pos = FindBestWindowPosForPopup(window); + + // Late create viewport if we don't fit within our current host viewport. + if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized)) + if (!window->Viewport->GetMainRect().Contains(window->Rect())) + { + // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport) + // ImGuiViewport* old_viewport = window->Viewport; + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); + + // FIXME-DPI + // IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong + SetCurrentViewport(window, window->Viewport); + window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f; + SetCurrentWindow(window); + } + + if (window->ViewportOwned) + WindowSyncOwnedViewport(window, parent_window_in_stack); + + // Calculate the range of allowed position for that window (to be movable and visible past safe area padding) + // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect. + ImRect viewport_rect(window->Viewport->GetMainRect()); + ImRect viewport_work_rect(window->Viewport->GetWorkRect()); + ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding); + + // Clamp position/size so window stays visible within its viewport or monitor + // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + // FIXME: Similar to code in GetWindowAllowedExtentRect() + if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + { + if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f) + { + ClampWindowRect(window, visibility_rect); + } + else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0) + { + // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport. + const ImGuiPlatformMonitor *monitor = GetViewportPlatformMonitor(window->Viewport); + visibility_rect.Min = monitor->WorkPos + visibility_padding; + visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding; + ClampWindowRect(window, visibility_rect); + } + } + window->Pos = ImFloor(window->Pos); + + // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) + // Large values tend to lead to variety of artifacts and are not recommended. + if (window->ViewportOwned || window->DockIsActive) + window->WindowRounding = 0.0f; + else + window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding + : style.WindowRounding; + + // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts. + // if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar)) + // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f); + + // Apply window focus (new and reactivated windows are moved to front) + bool want_focus = false; + if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) + { + if (flags & ImGuiWindowFlags_Popup) + want_focus = true; + else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip)) + want_focus = true; + + ImGuiWindow *modal = GetTopMostPopupModal(); + if (modal != NULL && !IsWindowWithinBeginStackOf(window, modal)) + { + // Avoid focusing a window that is created outside of active modal. This will prevent active modal from being closed. + // Since window is not focused it would reappear at the same display position like the last time it was visible. + // In case of completely new windows it would go to the top (over current modal), but input to such window would still be blocked by modal. + // Position window behind a modal that is not a begin-parent of this window. + want_focus = false; + if (window == window->RootWindow) + { + ImGuiWindow *blocking_modal = FindBlockingModal(window); + IM_ASSERT(blocking_modal != NULL); + BringWindowToDisplayBehind(window, blocking_modal); + } + } + } + + // [Test Engine] Register whole window in the item system +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (g.TestEngineHookItems) + { + IM_ASSERT(window->IDStack.Size == 1); + window->IDStack.Size = 0; + IMGUI_TEST_ENGINE_ITEM_ADD(window->Rect(), window->ID); + IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0); + window->IDStack.Size = 1; + } +#endif + + // Decide if we are going to handle borders and resize grips + const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive); + + // Handle manual resize: Resize Grips, Borders, Gamepad + int border_held = -1; + ImU32 resize_grip_col[4] = {}; + const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. + const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); + if (handle_borders_and_resize_grips && !window->Collapsed) + if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) + use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true; + window->ResizeBorderHeld = (signed char)border_held; + + // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either) + if (window->ViewportOwned) + { + if (!window->Viewport->PlatformRequestMove) + window->Viewport->Pos = window->Pos; + if (!window->Viewport->PlatformRequestResize) + window->Viewport->Size = window->Size; + window->Viewport->UpdateWorkRect(); + viewport_rect = window->Viewport->GetMainRect(); + } + + // Save last known viewport position within the window itself (so it can be saved in .ini file and restored) + window->ViewportPos = window->Viewport->Pos; + + // SCROLLBAR VISIBILITY + + // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). + if (!window->Collapsed) + { + // When reading the current size we need to read it after size constraints have been applied. + // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again. + ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height); + ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes; + ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f; + float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x; + float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y; + // bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons? + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + if (window->ScrollbarX && !window->ScrollbarY) + window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar); + window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); + } + + // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING) + // Update various regions. Variables they depends on should be set above in this function. + // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame. + + // Outer rectangle + // Not affected by window border size. Used by: + // - FindHoveredWindow() (w/ extra padding when border resize is enabled) + // - Begin() initial clipping rect for drawing window background and borders. + // - Begin() clipping whole child + const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; + const ImRect outer_rect = window->Rect(); + const ImRect title_bar_rect = window->TitleBarRect(); + window->OuterRectClipped = outer_rect; + if (window->DockIsActive) + window->OuterRectClipped.Min.y += window->TitleBarHeight(); + window->OuterRectClipped.ClipWith(host_rect); + + // Inner rectangle + // Not affected by window border size. Used by: + // - InnerClipRect + // - ScrollToRectEx() + // - NavUpdatePageUpPageDown() + // - Scrollbar() + window->InnerRect.Min.x = window->Pos.x; + window->InnerRect.Min.y = window->Pos.y + decoration_up_height; + window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x; + window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y; + + // Inner clipping rectangle. + // Will extend a little bit outside the normal work region. + // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. + // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. + // Affected by window/frame border size. Used by: + // - Begin() initial clip rect + float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); + window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize)); + window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size); + window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize)); + window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize); + window->InnerClipRect.ClipWithFull(host_rect); + + // Default item width. Make it proportional to window size if window manually resizes + if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) + window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f); + else + window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f); + + // SCROLLING + + // Lock down maximum scrolling + // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate + // for right/bottom aligned items without creating a scrollbar. + window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth()); + window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight()); + + // Apply scrolling + window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window); + window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + + // DRAWING + + // Setup draw list and outer clipping rectangle + IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0); + window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); + PushClipRect(host_rect.Min, host_rect.Max, false); + + // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71) + // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order. + // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493) + const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible; + if (is_undocked_or_docked_visible) + { + bool render_decorations_in_parent = false; + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) + { + // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here) + // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs + ImGuiWindow *previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL; + bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false; + bool parent_is_empty = parent_window->DrawList->VtxBuffer.Size > 0; + if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_is_empty && !previous_child_overlapping) + render_decorations_in_parent = true; + } + if (render_decorations_in_parent) + window->DrawList = parent_window->DrawList; + + // Handle title bar, scrollbar, resize grips and resize borders + const ImGuiWindow *window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; + const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode))); + RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size); + + if (render_decorations_in_parent) + window->DrawList = &window->DrawListInst; + } + + // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING) + + // Work rectangle. + // Affected by window padding and border size. Used by: + // - Columns() for right-most edge + // - TreeNode(), CollapsingHeader() for right-most edge + // - BeginTabBar() for right-most edge + const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar); + const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar); + const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x)); + const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y)); + window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize)); + window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize)); + window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x; + window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y; + window->ParentWorkRect = window->WorkRect; + + // [LEGACY] Content Region + // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. + // Used by: + // - Mouse wheel scrolling + many other things + window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; + window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height; + window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x)); + window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y)); + + // Setup drawing context + // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) + window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x; + window->DC.GroupOffset.x = 0.0f; + window->DC.ColumnsOffset.x = 0.0f; + + // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount. + // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64. + double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DC.ColumnsOffset.x; + double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + decoration_up_height; + window->DC.CursorStartPos = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y); + window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y)); + window->DC.CursorPos = window->DC.CursorStartPos; + window->DC.CursorPosPrevLine = window->DC.CursorPos; + window->DC.CursorMaxPos = window->DC.CursorStartPos; + window->DC.IdealMaxPos = window->DC.CursorStartPos; + window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; + window->DC.IsSameLine = false; + + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext; + window->DC.NavHideHighlightOneFrame = false; + window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f); + + window->DC.MenuBarAppending = false; + window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user); + window->DC.TreeDepth = 0; + window->DC.TreeJumpToParentOnPopMask = 0x00; + window->DC.ChildWindows.resize(0); + window->DC.StateStorage = &window->StateStorage; + window->DC.CurrentColumns = NULL; + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; + + window->DC.ItemWidth = window->ItemWidthDefault; + window->DC.TextWrapPos = -1.0f; // disabled + window->DC.ItemWidthStack.resize(0); + window->DC.TextWrapPosStack.resize(0); + + if (window->AutoFitFramesX > 0) + window->AutoFitFramesX--; + if (window->AutoFitFramesY > 0) + window->AutoFitFramesY--; + + // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) + if (want_focus) + { + FocusWindow(window); + NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls + } + + // Close requested by platform window + if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport()) + { + if (!window->DockIsActive || window->DockTabIsVisible) + { + window->Viewport->PlatformRequestClose = false; + g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. + IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' PlatformRequestClose\n", window->Name); + *p_open = false; + } + } + + // Title bar + if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) + RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open); + + // Clear hit test shape every frame + window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0; + + // Pressing CTRL+C while holding on a window copy its content to the clipboard + // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. + // Maybe we can support CTRL+C on every element? + /* + //if (g.NavWindow == window && g.ActiveId == 0) + if (g.ActiveId == window->MoveId) + if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C)) + LogToClipboard(); + */ + + if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) + { + // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source. + // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it. + if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift)) + if ((window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0) + BeginDockableDragDropSource(window); + + // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead. + if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking)) + if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window) + if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost)) + BeginDockableDragDropTarget(window); + } + + // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). + // This is useful to allow creating context menus on title bar only, etc. + if (window->DockIsActive) + SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect); + else + SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect); + + // [Test Engine] Register title bar / tab + if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) + IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.Rect, g.LastItemData.ID); + } + else + { + // Append + SetCurrentViewport(window, window->Viewport); + SetCurrentWindow(window); + } + + // Pull/inherit current state + window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : window->GetID("#FOCUSSCOPE"); // Inherit from parent only // -V595 + + if (!(flags & ImGuiWindowFlags_DockNodeHost)) + PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); + + // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) + window->WriteAccessed = false; + window->BeginCount++; + g.NextWindowData.ClearFlags(); + + // Update visibility + if (first_begin_of_the_frame) + { + // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. + // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. + // This is analogous to regular windows being hidden from one frame. + // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed. + if (window->DockIsActive && !window->DockTabIsVisible) + { + if (window->LastFrameJustFocused == g.FrameCount) + window->HiddenFramesCannotSkipItems = 1; + else + window->HiddenFramesCanSkipItems = 1; + } + + if (flags & ImGuiWindowFlags_ChildWindow) + { + // Child window can be out of sight and have "negative" clip windows. + // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). + IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive)); + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow?? + { + const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); + if (!g.LogEnabled && !nav_request) + if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) + window->HiddenFramesCanSkipItems = 1; + } + + // Hide along with parent or if parent is collapsed + if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0)) + window->HiddenFramesCanSkipItems = 1; + if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0)) + window->HiddenFramesCannotSkipItems = 1; + } + + // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) + if (style.Alpha <= 0.0f) + window->HiddenFramesCanSkipItems = 1; + + // Update the Hidden flag + bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0); + window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0); + + // Disable inputs for requested number of frames + if (window->DisableInputsFrames > 0) + { + window->DisableInputsFrames--; + window->Flags |= ImGuiWindowFlags_NoInputs; + } + + // Update the SkipItems flag, used to early out of all items functions (no layout required) + bool skip_items = false; + if (window->Collapsed || !window->Active || hidden_regular) + if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0) + skip_items = true; + window->SkipItems = skip_items; + + // Only clear NavLayersActiveMaskNext when marked as visible, so a CTRL+Tab back can use a safe value. + if (!window->SkipItems) + window->DC.NavLayersActiveMaskNext = 0x00; + + // Sanity check: there are two spots which can set Appearing = true + // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false + // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert. + if (window->SkipItems && !window->Appearing) + IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177 + } + + return !window->SkipItems; +} + +void ImGui::End() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + // Error checking: verify that user hasn't called End() too many times! + if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow) + { + IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!"); + return; + } + IM_ASSERT(g.CurrentWindowStack.Size > 0); + + // Error checking: verify that user doesn't directly call End() on a child window. + if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive) + IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!"); + + // Close anything that is open + if (window->DC.CurrentColumns) + EndColumns(); + if (!(window->Flags & ImGuiWindowFlags_DockNodeHost)) // Pop inner window clip rectangle + PopClipRect(); + + // Stop logging + if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging + LogFinish(); + + // Docking: report contents sizes to parent to allow for auto-resize + if (window->DockNode && window->DockTabIsVisible) + if (ImGuiWindow *host_window = window->DockNode->HostWindow) // FIXME-DOCK + host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding; + + // Pop from window stack + g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup; + if (window->Flags & ImGuiWindowFlags_ChildMenu) + g.BeginMenuCount--; + if (window->Flags & ImGuiWindowFlags_Popup) + g.BeginPopupStack.pop_back(); + g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithCurrentState(); + g.CurrentWindowStack.pop_back(); + SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window); + if (g.CurrentWindow) + SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport); +} + +void ImGui::BringWindowToFocusFront(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(window == window->RootWindow); + + const int cur_order = window->FocusOrder; + IM_ASSERT(g.WindowsFocusOrder[cur_order] == window); + if (g.WindowsFocusOrder.back() == window) + return; + + const int new_order = g.WindowsFocusOrder.Size - 1; + for (int n = cur_order; n < new_order; n++) + { + g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1]; + g.WindowsFocusOrder[n]->FocusOrder--; + IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n); + } + g.WindowsFocusOrder[new_order] = window; + window->FocusOrder = (short)new_order; +} + +void ImGui::BringWindowToDisplayFront(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *current_front_window = g.Windows.back(); + if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better) + return; + for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window + if (g.Windows[i] == window) + { + memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow *)); + g.Windows[g.Windows.Size - 1] = window; + break; + } +} + +void ImGui::BringWindowToDisplayBack(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + if (g.Windows[0] == window) + return; + for (int i = 0; i < g.Windows.Size; i++) + if (g.Windows[i] == window) + { + memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow *)); + g.Windows[0] = window; + break; + } +} + +void ImGui::BringWindowToDisplayBehind(ImGuiWindow *window, ImGuiWindow *behind_window) +{ + IM_ASSERT(window != NULL && behind_window != NULL); + ImGuiContext &g = *GImGui; + window = window->RootWindow; + behind_window = behind_window->RootWindow; + int pos_wnd = FindWindowDisplayIndex(window); + int pos_beh = FindWindowDisplayIndex(behind_window); + if (pos_wnd < pos_beh) + { + size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow *); + memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes); + g.Windows[pos_beh - 1] = window; + } + else + { + size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow *); + memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes); + g.Windows[pos_beh] = window; + } +} + +int ImGui::FindWindowDisplayIndex(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + return g.Windows.index_from_ptr(g.Windows.find(window)); +} + +// Moving window to front of display and set focus (which happens to be back of our sorted list) +void ImGui::FocusWindow(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + + if (g.NavWindow != window) + { + g.NavWindow = window; + if (window && g.NavDisableMouseHover) + g.NavMousePosDirty = true; + g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId + g.NavFocusScopeId = 0; + g.NavIdIsAlive = false; + g.NavLayer = ImGuiNavLayer_Main; + g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false; + NavUpdateAnyRequestFlag(); + // IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL); + } + + // Close popups if any + ClosePopupsOverWindow(window, false); + + // Move the root window to the top of the pile + IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL); + ImGuiWindow *focus_front_window = window ? window->RootWindow : NULL; + ImGuiWindow *display_front_window = window ? window->RootWindowDockTree : NULL; + ImGuiDockNode *dock_node = window ? window->DockNode : NULL; + bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow); + + // Steal active widgets. Some of the cases it triggers includes: + // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. + // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) + // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window. + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) + if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host) + ClearActiveID(); + + // Passing NULL allow to disable keyboard focus + if (!window) + return; + window->LastFrameJustFocused = g.FrameCount; + + // Select in dock node + if (dock_node && dock_node->TabBar) + dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId; + + // Bring to front + BringWindowToFocusFront(focus_front_window); + if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) + BringWindowToDisplayFront(display_front_window); +} + +void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow *under_this_window, ImGuiWindow *ignore_window) +{ + ImGuiContext &g = *GImGui; + int start_idx = g.WindowsFocusOrder.Size - 1; + if (under_this_window != NULL) + { + // Aim at root window behind us, if we are in a child window that's our own root (see #4640) + int offset = -1; + while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow) + { + under_this_window = under_this_window->ParentWindow; + offset = 0; + } + start_idx = FindWindowFocusIndex(under_this_window) + offset; + } + for (int i = start_idx; i >= 0; i--) + { + // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user. + ImGuiWindow *window = g.WindowsFocusOrder[i]; + IM_ASSERT(window == window->RootWindow); + if (window != ignore_window && window->WasActive) + if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) + { + // FIXME-DOCK: This is failing (lagging by one frame) for docked windows. + // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B. + // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update) + // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself? + ImGuiWindow *focus_window = NavRestoreLastChildNavWindow(window); + FocusWindow(focus_window); + return; + } + } + FocusWindow(NULL); +} + +// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only. +void ImGui::SetCurrentFont(ImFont *font) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(font->Scale > 0.0f); + g.Font = font; + g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); + g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; + + ImFontAtlas *atlas = g.Font->ContainerAtlas; + g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; + g.DrawListSharedData.TexUvLines = atlas->TexUvLines; + g.DrawListSharedData.Font = g.Font; + g.DrawListSharedData.FontSize = g.FontSize; +} + +void ImGui::PushFont(ImFont *font) +{ + ImGuiContext &g = *GImGui; + if (!font) + font = GetDefaultFont(); + SetCurrentFont(font); + g.FontStack.push_back(font); + g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); +} + +void ImGui::PopFont() +{ + ImGuiContext &g = *GImGui; + g.CurrentWindow->DrawList->PopTextureID(); + g.FontStack.pop_back(); + SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back()); +} + +void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) +{ + ImGuiContext &g = *GImGui; + ImGuiItemFlags item_flags = g.CurrentItemFlags; + IM_ASSERT(item_flags == g.ItemFlagsStack.back()); + if (enabled) + item_flags |= option; + else + item_flags &= ~option; + g.CurrentItemFlags = item_flags; + g.ItemFlagsStack.push_back(item_flags); +} + +void ImGui::PopItemFlag() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack. + g.ItemFlagsStack.pop_back(); + g.CurrentItemFlags = g.ItemFlagsStack.back(); +} + +// BeginDisabled()/EndDisabled() +// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) +// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently. +// - Feedback welcome at https://github.com/ocornut/imgui/issues/211 +// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it. +// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag() +void ImGui::BeginDisabled(bool disabled) +{ + ImGuiContext &g = *GImGui; + bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0; + if (!was_disabled && disabled) + { + g.DisabledAlphaBackup = g.Style.Alpha; + g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha); + } + if (was_disabled || disabled) + g.CurrentItemFlags |= ImGuiItemFlags_Disabled; + g.ItemFlagsStack.push_back(g.CurrentItemFlags); + g.DisabledStackSize++; +} + +void ImGui::EndDisabled() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.DisabledStackSize > 0); + g.DisabledStackSize--; + bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0; + // PopItemFlag(); + g.ItemFlagsStack.pop_back(); + g.CurrentItemFlags = g.ItemFlagsStack.back(); + if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0) + g.Style.Alpha = g.DisabledAlphaBackup; // PopStyleVar(); +} + +// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system. +void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) +{ + PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus); +} + +void ImGui::PopAllowKeyboardFocus() +{ + PopItemFlag(); +} + +void ImGui::PushButtonRepeat(bool repeat) +{ + PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); +} + +void ImGui::PopButtonRepeat() +{ + PopItemFlag(); +} + +void ImGui::PushTextWrapPos(float wrap_pos_x) +{ + ImGuiWindow *window = GetCurrentWindow(); + window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos); + window->DC.TextWrapPos = wrap_pos_x; +} + +void ImGui::PopTextWrapPos() +{ + ImGuiWindow *window = GetCurrentWindow(); + window->DC.TextWrapPos = window->DC.TextWrapPosStack.back(); + window->DC.TextWrapPosStack.pop_back(); +} + +static ImGuiWindow *GetCombinedRootWindow(ImGuiWindow *window, bool popup_hierarchy, bool dock_hierarchy) +{ + ImGuiWindow *last_window = NULL; + while (last_window != window) + { + last_window = window; + window = window->RootWindow; + if (popup_hierarchy) + window = window->RootWindowPopupTree; + if (dock_hierarchy) + window = window->RootWindowDockTree; + } + return window; +} + +bool ImGui::IsWindowChildOf(ImGuiWindow *window, ImGuiWindow *potential_parent, bool popup_hierarchy, bool dock_hierarchy) +{ + ImGuiWindow *window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy); + if (window_root == potential_parent) + return true; + while (window != NULL) + { + if (window == potential_parent) + return true; + if (window == window_root) // end of chain + return false; + window = window->ParentWindow; + } + return false; +} + +bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow *window, ImGuiWindow *potential_parent) +{ + if (window->RootWindow == potential_parent) + return true; + while (window != NULL) + { + if (window == potential_parent) + return true; + window = window->ParentWindowInBeginStack; + } + return false; +} + +bool ImGui::IsWindowAbove(ImGuiWindow *potential_above, ImGuiWindow *potential_below) +{ + ImGuiContext &g = *GImGui; + + // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array + const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below); + if (display_layer_delta != 0) + return display_layer_delta > 0; + + for (int i = g.Windows.Size - 1; i >= 0; i--) + { + ImGuiWindow *candidate_window = g.Windows[i]; + if (candidate_window == potential_above) + return true; + if (candidate_window == potential_below) + return false; + } + return false; +} + +bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) +{ + IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0); // Flags not supported by this function + ImGuiContext &g = *GImGui; + ImGuiWindow *ref_window = g.HoveredWindow; + ImGuiWindow *cur_window = g.CurrentWindow; + if (ref_window == NULL) + return false; + + if ((flags & ImGuiHoveredFlags_AnyWindow) == 0) + { + IM_ASSERT(cur_window); // Not inside a Begin()/End() + const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0; + const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0; + if (flags & ImGuiHoveredFlags_RootWindow) + cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy); + + bool result; + if (flags & ImGuiHoveredFlags_ChildWindows) + result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy); + else + result = (ref_window == cur_window); + if (!result) + return false; + } + + if (!IsWindowContentHoverable(ref_window, flags)) + return false; + if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId) + return false; + return true; +} + +bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *ref_window = g.NavWindow; + ImGuiWindow *cur_window = g.CurrentWindow; + + if (ref_window == NULL) + return false; + if (flags & ImGuiFocusedFlags_AnyWindow) + return true; + + IM_ASSERT(cur_window); // Not inside a Begin()/End() + const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0; + const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0; + if (flags & ImGuiHoveredFlags_RootWindow) + cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy); + + if (flags & ImGuiHoveredFlags_ChildWindows) + return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy); + else + return (ref_window == cur_window); +} + +ImGuiID ImGui::GetWindowDockID() +{ + ImGuiContext &g = *GImGui; + return g.CurrentWindow->DockId; +} + +bool ImGui::IsWindowDocked() +{ + ImGuiContext &g = *GImGui; + return g.CurrentWindow->DockIsActive; +} + +// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) +// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically. +// If you want a window to never be focused, you may use the e.g. NoInputs flag. +bool ImGui::IsWindowNavFocusable(ImGuiWindow *window) +{ + return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus); +} + +float ImGui::GetWindowWidth() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->Size.x; +} + +float ImGui::GetWindowHeight() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->Size.y; +} + +ImVec2 ImGui::GetWindowPos() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + return window->Pos; +} + +void ImGui::SetWindowPos(ImGuiWindow *window, const ImVec2 &pos, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowPosAllowFlags & cond) == 0) + return; + + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX); + + // Set + const ImVec2 old_pos = window->Pos; + window->Pos = ImFloor(pos); + ImVec2 offset = window->Pos - old_pos; + // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here. + window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected. + window->DC.IdealMaxPos += offset; + window->DC.CursorStartPos += offset; +} + +void ImGui::SetWindowPos(const ImVec2 &pos, ImGuiCond cond) +{ + ImGuiWindow *window = GetCurrentWindowRead(); + SetWindowPos(window, pos, cond); +} + +void ImGui::SetWindowPos(const char *name, const ImVec2 &pos, ImGuiCond cond) +{ + if (ImGuiWindow *window = FindWindowByName(name)) + SetWindowPos(window, pos, cond); +} + +ImVec2 ImGui::GetWindowSize() +{ + ImGuiWindow *window = GetCurrentWindowRead(); + return window->Size; +} + +void ImGui::SetWindowSize(ImGuiWindow *window, const ImVec2 &size, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) + return; + + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + + // Set + if (size.x > 0.0f) + { + window->AutoFitFramesX = 0; + window->SizeFull.x = IM_FLOOR(size.x); + } + else + { + window->AutoFitFramesX = 2; + window->AutoFitOnlyGrows = false; + } + if (size.y > 0.0f) + { + window->AutoFitFramesY = 0; + window->SizeFull.y = IM_FLOOR(size.y); + } + else + { + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = false; + } +} + +void ImGui::SetWindowSize(const ImVec2 &size, ImGuiCond cond) +{ + SetWindowSize(GImGui->CurrentWindow, size, cond); +} + +void ImGui::SetWindowSize(const char *name, const ImVec2 &size, ImGuiCond cond) +{ + if (ImGuiWindow *window = FindWindowByName(name)) + SetWindowSize(window, size, cond); +} + +void ImGui::SetWindowCollapsed(ImGuiWindow *window, bool collapsed, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) + return; + window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + + // Set + window->Collapsed = collapsed; +} + +void ImGui::SetWindowHitTestHole(ImGuiWindow *window, const ImVec2 &pos, const ImVec2 &size) +{ + IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters + window->HitTestHoleSize = ImVec2ih(size); + window->HitTestHoleOffset = ImVec2ih(pos - window->Pos); +} + +void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond) +{ + SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); +} + +bool ImGui::IsWindowCollapsed() +{ + ImGuiWindow *window = GetCurrentWindowRead(); + return window->Collapsed; +} + +bool ImGui::IsWindowAppearing() +{ + ImGuiWindow *window = GetCurrentWindowRead(); + return window->Appearing; +} + +void ImGui::SetWindowCollapsed(const char *name, bool collapsed, ImGuiCond cond) +{ + if (ImGuiWindow *window = FindWindowByName(name)) + SetWindowCollapsed(window, collapsed, cond); +} + +void ImGui::SetWindowFocus() +{ + FocusWindow(GImGui->CurrentWindow); +} + +void ImGui::SetWindowFocus(const char *name) +{ + if (name) + { + if (ImGuiWindow *window = FindWindowByName(name)) + FocusWindow(window); + } + else + { + FocusWindow(NULL); + } +} + +void ImGui::SetNextWindowPos(const ImVec2 &pos, ImGuiCond cond, const ImVec2 &pivot) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos; + g.NextWindowData.PosVal = pos; + g.NextWindowData.PosPivotVal = pivot; + g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always; + g.NextWindowData.PosUndock = true; +} + +void ImGui::SetNextWindowSize(const ImVec2 &size, ImGuiCond cond) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize; + g.NextWindowData.SizeVal = size; + g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always; +} + +void ImGui::SetNextWindowSizeConstraints(const ImVec2 &size_min, const ImVec2 &size_max, ImGuiSizeCallback custom_callback, void *custom_callback_user_data) +{ + ImGuiContext &g = *GImGui; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint; + g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max); + g.NextWindowData.SizeCallback = custom_callback; + g.NextWindowData.SizeCallbackUserData = custom_callback_user_data; +} + +// Content size = inner scrollable rectangle, padded with WindowPadding. +// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item. +void ImGui::SetNextWindowContentSize(const ImVec2 &size) +{ + ImGuiContext &g = *GImGui; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize; + g.NextWindowData.ContentSizeVal = ImFloor(size); +} + +void ImGui::SetNextWindowScroll(const ImVec2 &scroll) +{ + ImGuiContext &g = *GImGui; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll; + g.NextWindowData.ScrollVal = scroll; +} + +void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed; + g.NextWindowData.CollapsedVal = collapsed; + g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always; +} + +void ImGui::SetNextWindowFocus() +{ + ImGuiContext &g = *GImGui; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus; +} + +void ImGui::SetNextWindowBgAlpha(float alpha) +{ + ImGuiContext &g = *GImGui; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha; + g.NextWindowData.BgAlphaVal = alpha; +} + +void ImGui::SetNextWindowViewport(ImGuiID id) +{ + ImGuiContext &g = *GImGui; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport; + g.NextWindowData.ViewportId = id; +} + +void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond) +{ + ImGuiContext &g = *GImGui; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock; + g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always; + g.NextWindowData.DockId = id; +} + +void ImGui::SetNextWindowClass(const ImGuiWindowClass *window_class) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass; + g.NextWindowData.WindowClass = *window_class; +} + +ImDrawList *ImGui::GetWindowDrawList() +{ + ImGuiWindow *window = GetCurrentWindow(); + return window->DrawList; +} + +float ImGui::GetWindowDpiScale() +{ + ImGuiContext &g = *GImGui; + return g.CurrentDpiScale; +} + +ImGuiViewport *ImGui::GetWindowViewport() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport); + return g.CurrentViewport; +} + +ImFont *ImGui::GetFont() +{ + return GImGui->Font; +} + +float ImGui::GetFontSize() +{ + return GImGui->FontSize; +} + +ImVec2 ImGui::GetFontTexUvWhitePixel() +{ + return GImGui->DrawListSharedData.TexUvWhitePixel; +} + +void ImGui::SetWindowFontScale(float scale) +{ + IM_ASSERT(scale > 0.0f); + ImGuiContext &g = *GImGui; + ImGuiWindow *window = GetCurrentWindow(); + window->FontWindowScale = scale; + g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); +} + +void ImGui::ActivateItem(ImGuiID id) +{ + ImGuiContext &g = *GImGui; + g.NavNextActivateId = id; + g.NavNextActivateFlags = ImGuiActivateFlags_None; +} + +void ImGui::PushFocusScope(ImGuiID id) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + g.FocusScopeStack.push_back(window->DC.NavFocusScopeIdCurrent); + window->DC.NavFocusScopeIdCurrent = id; +} + +void ImGui::PopFocusScope() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ? + window->DC.NavFocusScopeIdCurrent = g.FocusScopeStack.back(); + g.FocusScopeStack.pop_back(); +} + +void ImGui::SetKeyboardFocusHere(int offset) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + IM_ASSERT(offset >= -1); // -1 is allowed but not below + g.NavWindow = window; + ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY; + NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable. + if (offset == -1) + { + NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal); + } + else + { + g.NavTabbingDir = 1; + g.NavTabbingCounter = offset + 1; + } +} + +void ImGui::SetItemDefaultFocus() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (!window->Appearing) + return; + if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent) + return; + + g.NavInitRequest = false; + g.NavInitResultId = g.LastItemData.ID; + g.NavInitResultRectRel = WindowRectAbsToRel(window, g.LastItemData.Rect); + NavUpdateAnyRequestFlag(); + + // Scroll could be done in NavInitRequestApplyResult() via a opt-in flag (we however don't want regular init requests to scroll) + if (!IsItemVisible()) + ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None); +} + +void ImGui::SetStateStorage(ImGuiStorage *tree) +{ + ImGuiWindow *window = GImGui->CurrentWindow; + window->DC.StateStorage = tree ? tree : &window->StateStorage; +} + +ImGuiStorage *ImGui::GetStateStorage() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->DC.StateStorage; +} + +void ImGui::PushID(const char *str_id) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + ImGuiID id = window->GetID(str_id); + window->IDStack.push_back(id); +} + +void ImGui::PushID(const char *str_id_begin, const char *str_id_end) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + ImGuiID id = window->GetID(str_id_begin, str_id_end); + window->IDStack.push_back(id); +} + +void ImGui::PushID(const void *ptr_id) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + ImGuiID id = window->GetID(ptr_id); + window->IDStack.push_back(id); +} + +void ImGui::PushID(int int_id) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + ImGuiID id = window->GetID(int_id); + window->IDStack.push_back(id); +} + +// Push a given id value ignoring the ID stack as a seed. +void ImGui::PushOverrideID(ImGuiID id) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (g.DebugHookIdInfo == id) + DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL); + window->IDStack.push_back(id); +} + +// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call +// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level. +// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more) +ImGuiID ImGui::GetIDWithSeed(const char *str, const char *str_end, ImGuiID seed) +{ + ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); + ImGuiContext &g = *GImGui; + if (g.DebugHookIdInfo == id) + DebugHookIdInfo(id, ImGuiDataType_String, str, str_end); + return id; +} + +void ImGui::PopID() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window? + window->IDStack.pop_back(); +} + +ImGuiID ImGui::GetID(const char *str_id) +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->GetID(str_id); +} + +ImGuiID ImGui::GetID(const char *str_id_begin, const char *str_id_end) +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->GetID(str_id_begin, str_id_end); +} + +ImGuiID ImGui::GetID(const void *ptr_id) +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->GetID(ptr_id); +} + +bool ImGui::IsRectVisible(const ImVec2 &size) +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); +} + +bool ImGui::IsRectVisible(const ImVec2 &rect_min, const ImVec2 &rect_max) +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); +} + +//----------------------------------------------------------------------------- +// [SECTION] INPUTS +//----------------------------------------------------------------------------- + +// Test if mouse cursor is hovering given rectangle +// NB- Rectangle is clipped by our current clip setting +// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) +bool ImGui::IsMouseHoveringRect(const ImVec2 &r_min, const ImVec2 &r_max, bool clip) +{ + ImGuiContext &g = *GImGui; + + // Clip + ImRect rect_clipped(r_min, r_max); + if (clip) + rect_clipped.ClipWith(g.CurrentWindow->ClipRect); + + // Expand for touch input + const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); + if (!rect_for_touch.Contains(g.IO.MousePos)) + return false; + if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped)) + return false; + return true; +} + +ImGuiKeyData *ImGui::GetKeyData(ImGuiKey key) +{ + ImGuiContext &g = *GImGui; + int index; +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END); + if (IsLegacyKey(key)) + index = (g.IO.KeyMap[key] != -1) ? g.IO.KeyMap[key] : key; // Remap native->imgui or imgui->native + else + index = key; +#else + IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code."); + index = key - ImGuiKey_NamedKey_BEGIN; +#endif + return &g.IO.KeysData[index]; +} + +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO +int ImGui::GetKeyIndex(ImGuiKey key) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(IsNamedKey(key)); + const ImGuiKeyData *key_data = GetKeyData(key); + return (int)(key_data - g.IO.KeysData); +} +#endif + +// Those names a provided for debugging purpose and are not meant to be saved persistently not compared. +static const char *const GKeyNames[] = + { + "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown", + "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape", + "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu", + "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", + "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", + "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket", + "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen", + "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6", + "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply", + "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual", + "GamepadStart", "GamepadBack", "GamepadFaceUp", "GamepadFaceDown", "GamepadFaceLeft", "GamepadFaceRight", + "GamepadDpadUp", "GamepadDpadDown", "GamepadDpadLeft", "GamepadDpadRight", + "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3", + "GamepadLStickUp", "GamepadLStickDown", "GamepadLStickLeft", "GamepadLStickRight", + "GamepadRStickUp", "GamepadRStickDown", "GamepadRStickLeft", "GamepadRStickRight", + "ModCtrl", "ModShift", "ModAlt", "ModSuper"}; +IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames)); + +const char *ImGui::GetKeyName(ImGuiKey key) +{ +#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO + IM_ASSERT((IsNamedKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code."); +#else + if (IsLegacyKey(key)) + { + ImGuiIO &io = GetIO(); + if (io.KeyMap[key] == -1) + return "N/A"; + IM_ASSERT(IsNamedKey((ImGuiKey)io.KeyMap[key])); + key = (ImGuiKey)io.KeyMap[key]; + } +#endif + if (key == ImGuiKey_None) + return "None"; + if (!IsNamedKey(key)) + return "Unknown"; + + return GKeyNames[key - ImGuiKey_NamedKey_BEGIN]; +} + +// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime) +// t1 = current time (e.g.: g.Time) +// An event is triggered at: +// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N +int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate) +{ + if (t1 == 0.0f) + return 1; + if (t0 >= t1) + return 0; + if (repeat_rate <= 0.0f) + return (t0 < repeat_delay) && (t1 >= repeat_delay); + const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate); + const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate); + const int count = count_t1 - count_t0; + return count; +} + +int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate) +{ + ImGuiContext &g = *GImGui; + const ImGuiKeyData *key_data = GetKeyData(key); + const float t = key_data->DownDuration; + return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate); +} + +// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes. +// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87) +bool ImGui::IsKeyDown(ImGuiKey key) +{ + const ImGuiKeyData *key_data = GetKeyData(key); + if (!key_data->Down) + return false; + return true; +} + +bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat) +{ + ImGuiContext &g = *GImGui; + const ImGuiKeyData *key_data = GetKeyData(key); + const float t = key_data->DownDuration; + if (t < 0.0f) + return false; + const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && GetKeyPressedAmount(key, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0); + if (!pressed) + return false; + return true; +} + +bool ImGui::IsKeyReleased(ImGuiKey key) +{ + const ImGuiKeyData *key_data = GetKeyData(key); + if (key_data->DownDurationPrev < 0.0f || key_data->Down) + return false; + return true; +} + +bool ImGui::IsMouseDown(ImGuiMouseButton button) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseDown[button]; +} + +bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + const float t = g.IO.MouseDownDuration[button]; + if (t == 0.0f) + return true; + if (repeat && t > g.IO.KeyRepeatDelay) + return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0; + return false; +} + +bool ImGui::IsMouseReleased(ImGuiMouseButton button) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseReleased[button]; +} + +bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseClickedCount[button] == 2; +} + +int ImGui::GetMouseClickedCount(ImGuiMouseButton button) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseClickedCount[button]; +} + +// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame. +// [Internal] This doesn't test if the button is pressed +bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (lock_threshold < 0.0f) + lock_threshold = g.IO.MouseDragThreshold; + return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; +} + +bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (!g.IO.MouseDown[button]) + return false; + return IsMouseDragPastThreshold(button, lock_threshold); +} + +ImVec2 ImGui::GetMousePos() +{ + ImGuiContext &g = *GImGui; + return g.IO.MousePos; +} + +// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! +ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() +{ + ImGuiContext &g = *GImGui; + if (g.BeginPopupStack.Size > 0) + return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos; + return g.IO.MousePos; +} + +// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position. +bool ImGui::IsMousePosValid(const ImVec2 *mouse_pos) +{ + // The assert is only to silence a false-positive in XCode Static Analysis. + // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions). + IM_ASSERT(GImGui != NULL); + const float MOUSE_INVALID = -256000.0f; + ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos; + return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID; +} + +// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. +bool ImGui::IsAnyMouseDown() +{ + ImGuiContext &g = *GImGui; + for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++) + if (g.IO.MouseDown[n]) + return true; + return false; +} + +// Return the delta from the initial clicking position while the mouse button is clicked or was just released. +// This is locked and return 0.0f until the mouse moves past a distance threshold at least once. +// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window. +ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (lock_threshold < 0.0f) + lock_threshold = g.IO.MouseDragThreshold; + if (g.IO.MouseDown[button] || g.IO.MouseReleased[button]) + if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) + if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button])) + return g.IO.MousePos - g.IO.MouseClickedPos[button]; + return ImVec2(0.0f, 0.0f); +} + +void ImGui::ResetMouseDragDelta(ImGuiMouseButton button) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr + g.IO.MouseClickedPos[button] = g.IO.MousePos; +} + +ImGuiMouseCursor ImGui::GetMouseCursor() +{ + ImGuiContext &g = *GImGui; + return g.MouseCursor; +} + +void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) +{ + ImGuiContext &g = *GImGui; + g.MouseCursor = cursor_type; +} + +void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard) +{ + ImGuiContext &g = *GImGui; + g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0; +} + +void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse) +{ + ImGuiContext &g = *GImGui; + g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0; +} + +static const char *GetInputSourceName(ImGuiInputSource source) +{ + const char *input_source_names[] = {"None", "Mouse", "Keyboard", "Gamepad", "Nav", "Clipboard"}; + IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT); + return input_source_names[source]; +} + +/*static void DebugLogInputEvent(const char* prefix, const ImGuiInputEvent* e) +{ + if (e->Type == ImGuiInputEventType_MousePos) { IMGUI_DEBUG_LOG("%s: MousePos (%.1f %.1f)\n", prefix, e->MousePos.PosX, e->MousePos.PosY); return; } + if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG("%s: MouseButton %d %s\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up"); return; } + if (e->Type == ImGuiInputEventType_MouseWheel) { IMGUI_DEBUG_LOG("%s: MouseWheel (%.1f %.1f)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY); return; } + if (e->Type == ImGuiInputEventType_Key) { IMGUI_DEBUG_LOG("%s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; } + if (e->Type == ImGuiInputEventType_Text) { IMGUI_DEBUG_LOG("%s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; } + if (e->Type == ImGuiInputEventType_Focus) { IMGUI_DEBUG_LOG("%s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; } +}*/ + +// Process input queue +// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'. +// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost) +// - trickle_fast_inputs = true : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87) +void ImGui::UpdateInputEvents(bool trickle_fast_inputs) +{ + ImGuiContext &g = *GImGui; + ImGuiIO &io = g.IO; + + // Only trickle chars<>key when working with InputText() + // FIXME: InputText() could parse event trail? + // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters) + const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1); + + bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false; + int mouse_button_changed = 0x00; + ImBitArray key_changed_mask; + + int event_n = 0; + for (; event_n < g.InputEventsQueue.Size; event_n++) + { + const ImGuiInputEvent *e = &g.InputEventsQueue[event_n]; + if (e->Type == ImGuiInputEventType_MousePos) + { + ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY); + if (IsMousePosValid(&event_pos)) + event_pos = ImVec2(ImFloorSigned(event_pos.x), ImFloorSigned(event_pos.y)); // Apply same flooring as UpdateMouseInputs() + if (io.MousePos.x != event_pos.x || io.MousePos.y != event_pos.y) + { + // Trickling Rule: Stop processing queued events if we already handled a mouse button change + if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted)) + break; + io.MousePos = event_pos; + mouse_moved = true; + } + } + else if (e->Type == ImGuiInputEventType_MouseButton) + { + const ImGuiMouseButton button = e->MouseButton.Button; + IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT); + if (io.MouseDown[button] != e->MouseButton.Down) + { + // Trickling Rule: Stop processing queued events if we got multiple action on the same button + if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled)) + break; + io.MouseDown[button] = e->MouseButton.Down; + mouse_button_changed |= (1 << button); + } + } + else if (e->Type == ImGuiInputEventType_MouseWheel) + { + if (e->MouseWheel.WheelX != 0.0f || e->MouseWheel.WheelY != 0.0f) + { + // Trickling Rule: Stop processing queued events if we got multiple action on the event + if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0)) + break; + io.MouseWheelH += e->MouseWheel.WheelX; + io.MouseWheel += e->MouseWheel.WheelY; + mouse_wheeled = true; + } + } + else if (e->Type == ImGuiInputEventType_MouseViewport) + { + io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID; + } + else if (e->Type == ImGuiInputEventType_Key) + { + ImGuiKey key = e->Key.Key; + IM_ASSERT(key != ImGuiKey_None); + const int keydata_index = (key - ImGuiKey_KeysData_OFFSET); + ImGuiKeyData *keydata = &io.KeysData[keydata_index]; + if (keydata->Down != e->Key.Down || keydata->AnalogValue != e->Key.AnalogValue) + { + // Trickling Rule: Stop processing queued events if we got multiple action on the same button + if (trickle_fast_inputs && keydata->Down != e->Key.Down && (key_changed_mask.TestBit(keydata_index) || text_inputted || mouse_button_changed != 0)) + break; + keydata->Down = e->Key.Down; + keydata->AnalogValue = e->Key.AnalogValue; + key_changed = true; + key_changed_mask.SetBit(keydata_index); + + if (key == ImGuiKey_ModCtrl || key == ImGuiKey_ModShift || key == ImGuiKey_ModAlt || key == ImGuiKey_ModSuper) + { + if (key == ImGuiKey_ModCtrl) + { + io.KeyCtrl = keydata->Down; + } + if (key == ImGuiKey_ModShift) + { + io.KeyShift = keydata->Down; + } + if (key == ImGuiKey_ModAlt) + { + io.KeyAlt = keydata->Down; + } + if (key == ImGuiKey_ModSuper) + { + io.KeySuper = keydata->Down; + } + io.KeyMods = GetMergedModFlags(); + } + + // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + io.KeysDown[key] = keydata->Down; + if (io.KeyMap[key] != -1) + io.KeysDown[io.KeyMap[key]] = keydata->Down; +#endif + } + } + else if (e->Type == ImGuiInputEventType_Text) + { + // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with + if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled)) + break; + unsigned int c = e->Text.Char; + io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID); + if (trickle_interleaved_keys_and_text) + text_inputted = true; + } + else if (e->Type == ImGuiInputEventType_Focus) + { + // We intentionally overwrite this and process lower, in order to give a chance + // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame. + io.AppFocusLost = !e->AppFocused.Focused; + } + else + { + IM_ASSERT(0 && "Unknown event!"); + } + } + + // Record trail (for domain-specific applications wanting to access a precise trail) + // if (event_n != 0) IMGUI_DEBUG_LOG("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n); + for (int n = 0; n < event_n; n++) + g.InputEventsTrail.push_back(g.InputEventsQueue[n]); + + // [DEBUG] + /*if (event_n != 0) + for (int n = 0; n < g.InputEventsQueue.Size; n++) + DebugLogInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);*/ + + // Remaining events will be processed on the next frame + if (event_n == g.InputEventsQueue.Size) + g.InputEventsQueue.resize(0); + else + g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n); + + // Clear buttons state when focus is lost + // (this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle) + if (g.IO.AppFocusLost) + { + g.IO.ClearInputKeys(); + g.IO.AppFocusLost = false; + } +} + +//----------------------------------------------------------------------------- +// [SECTION] ERROR CHECKING +//----------------------------------------------------------------------------- + +// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui. +// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit +// If this triggers you have an issue: +// - Most commonly: mismatched headers and compiled code version. +// - Or: mismatched configuration #define, compilation settings, packing pragma etc. +// The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui, +// which is way it is required you put them in your imconfig file (and not just before including imgui.h). +// Otherwise it is possible that different compilation units would see different structure layout +bool ImGui::DebugCheckVersionAndDataLayout(const char *version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx) +{ + bool error = false; + if (strcmp(version, IMGUI_VERSION) != 0) + { + error = true; + IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); + } + if (sz_io != sizeof(ImGuiIO)) + { + error = true; + IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); + } + if (sz_style != sizeof(ImGuiStyle)) + { + error = true; + IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); + } + if (sz_vec2 != sizeof(ImVec2)) + { + error = true; + IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); + } + if (sz_vec4 != sizeof(ImVec4)) + { + error = true; + IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); + } + if (sz_vert != sizeof(ImDrawVert)) + { + error = true; + IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); + } + if (sz_idx != sizeof(ImDrawIdx)) + { + error = true; + IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); + } + return !error; +} + +static void ImGui::ErrorCheckNewFrameSanityChecks() +{ + ImGuiContext &g = *GImGui; + + // Check user IM_ASSERT macro + // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined! + // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block. + // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.) + // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong! + // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct! + if (true) + IM_ASSERT(1); + else + IM_ASSERT(0); + + // Check user data + // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument) + IM_ASSERT(g.Initialized); + IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!"); + IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); + IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!"); + IM_ASSERT(g.IO.Fonts->IsBuilt() && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()"); + IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); + IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f && "Invalid style setting!"); + IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations + IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting."); + IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right); + IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right); +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++) + IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)"); + + // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP) + if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1) + IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation."); +#endif + + // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly. + if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors)) + g.IO.ConfigWindowsResizeFromEdges = false; + + // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data. + if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0) + IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); + if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0) + IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); + + // Perform simple checks: multi-viewport and platform windows support + if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports)) + { + IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference."); + IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?"); + IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?"); + IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport."); + if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) + IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!"); + } + else + { + // Disable feature, our backends do not support it + g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable; + } + + // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs + for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++) + { + ImGuiPlatformMonitor &mon = g.PlatformIO.Monitors[monitor_n]; + IM_UNUSED(mon); + IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly."); + IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them."); + IM_ASSERT(mon.DpiScale != 0.0f); + } + } +} + +static void ImGui::ErrorCheckEndFrameSanityChecks() +{ + ImGuiContext &g = *GImGui; + + // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame() + // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame(). + // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will + // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs. + // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0), + // while still correctly asserting on mid-frame key press events. + const ImGuiModFlags key_mods = GetMergedModFlags(); + IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); + IM_UNUSED(key_mods); + + // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame(). + // ErrorCheckEndFrameRecover(); + + // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you + // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API). + if (g.CurrentWindowStack.Size != 1) + { + if (g.CurrentWindowStack.Size > 1) + { + IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?"); + while (g.CurrentWindowStack.Size > 1) + End(); + } + else + { + IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?"); + } + } + + IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!"); +} + +// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls. +// Must be called during or before EndFrame(). +// This is generally flawed as we are not necessarily End/Popping things in the right order. +// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet. +// FIXME: Can't recover from interleaved BeginTabBar/Begin +void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void *user_data) +{ + // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations" + ImGuiContext &g = *GImGui; + while (g.CurrentWindowStack.Size > 0) //-V1044 + { + ErrorCheckEndWindowRecover(log_callback, user_data); + ImGuiWindow *window = g.CurrentWindow; + if (g.CurrentWindowStack.Size == 1) + { + IM_ASSERT(window->IsFallbackWindow); + break; + } + if (window->Flags & ImGuiWindowFlags_ChildWindow) + { + if (log_callback) + log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name); + EndChild(); + } + else + { + if (log_callback) + log_callback(user_data, "Recovered from missing End() for '%s'", window->Name); + End(); + } + } +} + +// Must be called before End()/EndChild() +void ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void *user_data) +{ + ImGuiContext &g = *GImGui; + while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow)) + { + if (log_callback) + log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name); + EndTable(); + } + + ImGuiWindow *window = g.CurrentWindow; + ImGuiStackSizes *stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin; + IM_ASSERT(window != NULL); + while (g.CurrentTabBar != NULL) //-V1044 + { + if (log_callback) + log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name); + EndTabBar(); + } + while (window->DC.TreeDepth > 0) + { + if (log_callback) + log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name); + TreePop(); + } + while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044 + { + if (log_callback) + log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name); + EndGroup(); + } + while (window->IDStack.Size > 1) + { + if (log_callback) + log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name); + PopID(); + } + while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044 + { + if (log_callback) + log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name); + EndDisabled(); + } + while (g.ColorStack.Size > stack_sizes->SizeOfColorStack) + { + if (log_callback) + log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col)); + PopStyleColor(); + } + while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044 + { + if (log_callback) + log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name); + PopItemFlag(); + } + while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044 + { + if (log_callback) + log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name); + PopStyleVar(); + } + while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack) //-V1044 + { + if (log_callback) + log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name); + PopFocusScope(); + } +} + +// Save current stack sizes for later compare +void ImGuiStackSizes::SetToCurrentState() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + SizeOfIDStack = (short)window->IDStack.Size; + SizeOfColorStack = (short)g.ColorStack.Size; + SizeOfStyleVarStack = (short)g.StyleVarStack.Size; + SizeOfFontStack = (short)g.FontStack.Size; + SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size; + SizeOfGroupStack = (short)g.GroupStack.Size; + SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size; + SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size; + SizeOfDisabledStack = (short)g.DisabledStackSize; +} + +// Compare to detect usage errors +void ImGuiStackSizes::CompareWithCurrentState() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + IM_UNUSED(window); + + // Window stacks + // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) + IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!"); + + // Global stacks + // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them. + IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!"); + IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!"); + IM_ASSERT(SizeOfDisabledStack == g.DisabledStackSize && "BeginDisabled/EndDisabled Mismatch!"); + IM_ASSERT(SizeOfItemFlagsStack >= g.ItemFlagsStack.Size && "PushItemFlag/PopItemFlag Mismatch!"); + IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!"); + IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!"); + IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!"); + IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!"); +} + +//----------------------------------------------------------------------------- +// [SECTION] LAYOUT +//----------------------------------------------------------------------------- +// - ItemSize() +// - ItemAdd() +// - SameLine() +// - GetCursorScreenPos() +// - SetCursorScreenPos() +// - GetCursorPos(), GetCursorPosX(), GetCursorPosY() +// - SetCursorPos(), SetCursorPosX(), SetCursorPosY() +// - GetCursorStartPos() +// - Indent() +// - Unindent() +// - SetNextItemWidth() +// - PushItemWidth() +// - PushMultiItemsWidths() +// - PopItemWidth() +// - CalcItemWidth() +// - CalcItemSize() +// - GetTextLineHeight() +// - GetTextLineHeightWithSpacing() +// - GetFrameHeight() +// - GetFrameHeightWithSpacing() +// - GetContentRegionMax() +// - GetContentRegionMaxAbs() [Internal] +// - GetContentRegionAvail(), +// - GetWindowContentRegionMin(), GetWindowContentRegionMax() +// - BeginGroup() +// - EndGroup() +// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns. +//----------------------------------------------------------------------------- + +// Advance cursor given item size for layout. +// Register minimum needed size so it can extend the bounding box used for auto-fit calculation. +// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different. +void ImGui::ItemSize(const ImVec2 &size, float text_baseline_y) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (window->SkipItems) + return; + + // We increase the height in this function to accommodate for baseline offset. + // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor, + // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect. + const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f; + + const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y; + const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/ window->DC.CursorPos.y - line_y1 /*, 0.0f)*/ + size.y + offset_to_match_baseline_y); + + // Always align ourselves on pixel boundaries + // if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG] + window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x; + window->DC.CursorPosPrevLine.y = line_y1; + window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line + window->DC.CursorPos.y = IM_FLOOR(line_y1 + line_height + g.Style.ItemSpacing.y); // Next line + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y); + // if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG] + + window->DC.PrevLineSize.y = line_height; + window->DC.CurrLineSize.y = 0.0f; + window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y); + window->DC.CurrLineTextBaseOffset = 0.0f; + window->DC.IsSameLine = false; + + // Horizontal layout mode + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + SameLine(); +} + +// Declare item bounding box for clipping and interaction. +// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface +// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction. +bool ImGui::ItemAdd(const ImRect &bb, ImGuiID id, const ImRect *nav_bb_arg, ImGuiItemFlags extra_flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + // Set item data + // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set) + g.LastItemData.ID = id; + g.LastItemData.Rect = bb; + g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb; + g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags; + g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None; + + // Directional navigation processing + if (id != 0) + { + KeepAliveID(id); + + // Runs prior to clipping early-out + // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget + // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests + // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of + // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. + // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able + // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick). + // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null. + // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere. + window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent); + if (g.NavId == id || g.NavAnyRequest) + if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) + if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened)) + NavProcessItem(); + + // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something". + // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something". + // READ THE FAQ: https://dearimgui.org/faq + IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!"); + + // [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd() +#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX + if (id == g.DebugItemPickerBreakId) + { + IM_DEBUG_BREAK(); + g.DebugItemPickerBreakId = 0; + } +#endif + } + g.NextItemData.Flags = ImGuiNextItemDataFlags_None; + +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (id != 0) + IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id); +#endif + + // Clipping test + const bool is_clipped = IsClippedEx(bb, id); + if (is_clipped) + return false; + // if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG] + + // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them) + if (IsMouseHoveringRect(bb.Min, bb.Max)) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect; + return true; +} + +// Gets back to previous line and continue with horizontal layout +// offset_from_start_x == 0 : follow right after previous item +// offset_from_start_x != 0 : align to specified x position (relative to window/group left) +// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 +// spacing_w >= 0 : enforce spacing amount +void ImGui::SameLine(float offset_from_start_x, float spacing_w) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (window->SkipItems) + return; + + if (offset_from_start_x != 0.0f) + { + if (spacing_w < 0.0f) + spacing_w = 0.0f; + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; + } + else + { + if (spacing_w < 0.0f) + spacing_w = g.Style.ItemSpacing.x; + window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; + } + window->DC.CurrLineSize = window->DC.PrevLineSize; + window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; + window->DC.IsSameLine = true; +} + +ImVec2 ImGui::GetCursorScreenPos() +{ + ImGuiWindow *window = GetCurrentWindowRead(); + return window->DC.CursorPos; +} + +void ImGui::SetCursorScreenPos(const ImVec2 &pos) +{ + ImGuiWindow *window = GetCurrentWindow(); + window->DC.CursorPos = pos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); +} + +// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. +// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. +ImVec2 ImGui::GetCursorPos() +{ + ImGuiWindow *window = GetCurrentWindowRead(); + return window->DC.CursorPos - window->Pos + window->Scroll; +} + +float ImGui::GetCursorPosX() +{ + ImGuiWindow *window = GetCurrentWindowRead(); + return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; +} + +float ImGui::GetCursorPosY() +{ + ImGuiWindow *window = GetCurrentWindowRead(); + return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; +} + +void ImGui::SetCursorPos(const ImVec2 &local_pos) +{ + ImGuiWindow *window = GetCurrentWindow(); + window->DC.CursorPos = window->Pos - window->Scroll + local_pos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); +} + +void ImGui::SetCursorPosX(float x) +{ + ImGuiWindow *window = GetCurrentWindow(); + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); +} + +void ImGui::SetCursorPosY(float y) +{ + ImGuiWindow *window = GetCurrentWindow(); + window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); +} + +ImVec2 ImGui::GetCursorStartPos() +{ + ImGuiWindow *window = GetCurrentWindowRead(); + return window->DC.CursorStartPos - window->Pos; +} + +void ImGui::Indent(float indent_w) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = GetCurrentWindow(); + window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; +} + +void ImGui::Unindent(float indent_w) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = GetCurrentWindow(); + window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; +} + +// Affect large frame+labels widgets only. +void ImGui::SetNextItemWidth(float item_width) +{ + ImGuiContext &g = *GImGui; + g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth; + g.NextItemData.Width = item_width; +} + +// FIXME: Remove the == 0.0f behavior? +void ImGui::PushItemWidth(float item_width) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width + window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); + g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; +} + +void ImGui::PushMultiItemsWidths(int components, float w_full) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + const ImGuiStyle &style = g.Style; + const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components)); + const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1))); + window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width + window->DC.ItemWidthStack.push_back(w_item_last); + for (int i = 0; i < components - 2; i++) + window->DC.ItemWidthStack.push_back(w_item_one); + window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one; + g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; +} + +void ImGui::PopItemWidth() +{ + ImGuiWindow *window = GetCurrentWindow(); + window->DC.ItemWidth = window->DC.ItemWidthStack.back(); + window->DC.ItemWidthStack.pop_back(); +} + +// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(). +// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags() +float ImGui::CalcItemWidth() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + float w; + if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth) + w = g.NextItemData.Width; + else + w = window->DC.ItemWidth; + if (w < 0.0f) + { + float region_max_x = GetContentRegionMaxAbs().x; + w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w); + } + w = IM_FLOOR(w); + return w; +} + +// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth(). +// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. +// Note that only CalcItemWidth() is publicly exposed. +// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) +ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + ImVec2 region_max; + if (size.x < 0.0f || size.y < 0.0f) + region_max = GetContentRegionMaxAbs(); + + if (size.x == 0.0f) + size.x = default_w; + else if (size.x < 0.0f) + size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x); + + if (size.y == 0.0f) + size.y = default_h; + else if (size.y < 0.0f) + size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y); + + return size; +} + +float ImGui::GetTextLineHeight() +{ + ImGuiContext &g = *GImGui; + return g.FontSize; +} + +float ImGui::GetTextLineHeightWithSpacing() +{ + ImGuiContext &g = *GImGui; + return g.FontSize + g.Style.ItemSpacing.y; +} + +float ImGui::GetFrameHeight() +{ + ImGuiContext &g = *GImGui; + return g.FontSize + g.Style.FramePadding.y * 2.0f; +} + +float ImGui::GetFrameHeightWithSpacing() +{ + ImGuiContext &g = *GImGui; + return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; +} + +// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience! + +// FIXME: This is in window space (not screen space!). +ImVec2 ImGui::GetContentRegionMax() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + ImVec2 mx = window->ContentRegionRect.Max - window->Pos; + if (window->DC.CurrentColumns || g.CurrentTable) + mx.x = window->WorkRect.Max.x - window->Pos.x; + return mx; +} + +// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features. +ImVec2 ImGui::GetContentRegionMaxAbs() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + ImVec2 mx = window->ContentRegionRect.Max; + if (window->DC.CurrentColumns || g.CurrentTable) + mx.x = window->WorkRect.Max.x; + return mx; +} + +ImVec2 ImGui::GetContentRegionAvail() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return GetContentRegionMaxAbs() - window->DC.CursorPos; +} + +// In window space (not screen space!) +ImVec2 ImGui::GetWindowContentRegionMin() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->ContentRegionRect.Min - window->Pos; +} + +ImVec2 ImGui::GetWindowContentRegionMax() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->ContentRegionRect.Max - window->Pos; +} + +// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) +// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated. +// FIXME-OPT: Could we safely early out on ->SkipItems? +void ImGui::BeginGroup() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + g.GroupStack.resize(g.GroupStack.Size + 1); + ImGuiGroupData &group_data = g.GroupStack.back(); + group_data.WindowID = window->ID; + group_data.BackupCursorPos = window->DC.CursorPos; + group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; + group_data.BackupIndent = window->DC.Indent; + group_data.BackupGroupOffset = window->DC.GroupOffset; + group_data.BackupCurrLineSize = window->DC.CurrLineSize; + group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset; + group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive; + group_data.BackupHoveredIdIsAlive = g.HoveredId != 0; + group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive; + group_data.EmitItem = true; + + window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x; + window->DC.Indent = window->DC.GroupOffset; + window->DC.CursorMaxPos = window->DC.CursorPos; + window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + if (g.LogEnabled) + g.LogLinePosY = -FLT_MAX; // To enforce a carriage return +} + +void ImGui::EndGroup() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls + + ImGuiGroupData &group_data = g.GroupStack.back(); + IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window? + + ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos)); + + window->DC.CursorPos = group_data.BackupCursorPos; + window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); + window->DC.Indent = group_data.BackupIndent; + window->DC.GroupOffset = group_data.BackupGroupOffset; + window->DC.CurrLineSize = group_data.BackupCurrLineSize; + window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset; + if (g.LogEnabled) + g.LogLinePosY = -FLT_MAX; // To enforce a carriage return + + if (!group_data.EmitItem) + { + g.GroupStack.pop_back(); + return; + } + + window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. + ItemSize(group_bb.GetSize()); + ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop); + + // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group. + // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets. + // Also if you grep for LastItemId you'll notice it is only used in that context. + // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.) + const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId; + const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true); + if (group_contains_curr_active_id) + g.LastItemData.ID = g.ActiveId; + else if (group_contains_prev_active_id) + g.LastItemData.ID = g.ActiveIdPreviousFrame; + g.LastItemData.Rect = group_bb; + + // Forward Hovered flag + const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0; + if (group_contains_curr_hovered_id) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; + + // Forward Edited flag + if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited; + + // Forward Deactivated flag + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated; + if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated; + + g.GroupStack.pop_back(); + // window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug] +} + +//----------------------------------------------------------------------------- +// [SECTION] SCROLLING +//----------------------------------------------------------------------------- + +// Helper to snap on edges when aiming at an item very close to the edge, +// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling. +// When we refactor the scrolling API this may be configurable with a flag? +// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default. +static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio) +{ + if (target <= snap_min + snap_threshold) + return ImLerp(snap_min, target, center_ratio); + if (target >= snap_max - snap_threshold) + return ImLerp(target, snap_max, center_ratio); + return target; +} + +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow *window) +{ + ImVec2 scroll = window->Scroll; + if (window->ScrollTarget.x < FLT_MAX) + { + float decoration_total_width = window->ScrollbarSizes.x; + float center_x_ratio = window->ScrollTargetCenterRatio.x; + float scroll_target_x = window->ScrollTarget.x; + if (window->ScrollTargetEdgeSnapDist.x > 0.0f) + { + float snap_x_min = 0.0f; + float snap_x_max = window->ScrollMax.x + window->SizeFull.x - decoration_total_width; + scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio); + } + scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - decoration_total_width); + } + if (window->ScrollTarget.y < FLT_MAX) + { + float decoration_total_height = window->TitleBarHeight() + window->MenuBarHeight() + window->ScrollbarSizes.y; + float center_y_ratio = window->ScrollTargetCenterRatio.y; + float scroll_target_y = window->ScrollTarget.y; + if (window->ScrollTargetEdgeSnapDist.y > 0.0f) + { + float snap_y_min = 0.0f; + float snap_y_max = window->ScrollMax.y + window->SizeFull.y - decoration_total_height; + scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio); + } + scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - decoration_total_height); + } + scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f)); + scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f)); + if (!window->Collapsed && !window->SkipItems) + { + scroll.x = ImMin(scroll.x, window->ScrollMax.x); + scroll.y = ImMin(scroll.y, window->ScrollMax.y); + } + return scroll; +} + +void ImGui::ScrollToItem(ImGuiScrollFlags flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + ScrollToRectEx(window, g.LastItemData.NavRect, flags); +} + +void ImGui::ScrollToRect(ImGuiWindow *window, const ImRect &item_rect, ImGuiScrollFlags flags) +{ + ScrollToRectEx(window, item_rect, flags); +} + +// Scroll to keep newly navigated item fully into view +ImVec2 ImGui::ScrollToRectEx(ImGuiWindow *window, const ImRect &item_rect, ImGuiScrollFlags flags) +{ + ImGuiContext &g = *GImGui; + ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)); + // GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] + + // Check that only one behavior is selected per axis + IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_)); + IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_)); + + // Defaults + ImGuiScrollFlags in_flags = flags; + if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX) + flags |= ImGuiScrollFlags_KeepVisibleEdgeX; + if ((flags & ImGuiScrollFlags_MaskY_) == 0) + flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY; + + const bool fully_visible_x = item_rect.Min.x >= window_rect.Min.x && item_rect.Max.x <= window_rect.Max.x; + const bool fully_visible_y = item_rect.Min.y >= window_rect.Min.y && item_rect.Max.y <= window_rect.Max.y; + const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= window_rect.GetWidth(); + const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= window_rect.GetHeight(); + + if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x) + { + if (item_rect.Min.x < window_rect.Min.x || !can_be_fully_visible_x) + SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f); + else if (item_rect.Max.x >= window_rect.Max.x) + SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f); + } + else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX)) + { + float target_x = can_be_fully_visible_x ? ImFloor((item_rect.Min.x + item_rect.Max.x - window->InnerRect.GetWidth()) * 0.5f) : item_rect.Min.x; + SetScrollFromPosX(window, target_x - window->Pos.x, 0.0f); + } + + if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y) + { + if (item_rect.Min.y < window_rect.Min.y || !can_be_fully_visible_y) + SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f); + else if (item_rect.Max.y >= window_rect.Max.y) + SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f); + } + else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY)) + { + float target_y = can_be_fully_visible_y ? ImFloor((item_rect.Min.y + item_rect.Max.y - window->InnerRect.GetHeight()) * 0.5f) : item_rect.Min.y; + SetScrollFromPosY(window, target_y - window->Pos.y, 0.0f); + } + + ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window); + ImVec2 delta_scroll = next_scroll - window->Scroll; + + // Also scroll parent window to keep us into view if necessary + if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow)) + { + // FIXME-SCROLL: May be an option? + if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0) + in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX; + if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0) + in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY; + delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags); + } + + return delta_scroll; +} + +float ImGui::GetScrollX() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->Scroll.x; +} + +float ImGui::GetScrollY() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->Scroll.y; +} + +float ImGui::GetScrollMaxX() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->ScrollMax.x; +} + +float ImGui::GetScrollMaxY() +{ + ImGuiWindow *window = GImGui->CurrentWindow; + return window->ScrollMax.y; +} + +void ImGui::SetScrollX(ImGuiWindow *window, float scroll_x) +{ + window->ScrollTarget.x = scroll_x; + window->ScrollTargetCenterRatio.x = 0.0f; + window->ScrollTargetEdgeSnapDist.x = 0.0f; +} + +void ImGui::SetScrollY(ImGuiWindow *window, float scroll_y) +{ + window->ScrollTarget.y = scroll_y; + window->ScrollTargetCenterRatio.y = 0.0f; + window->ScrollTargetEdgeSnapDist.y = 0.0f; +} + +void ImGui::SetScrollX(float scroll_x) +{ + ImGuiContext &g = *GImGui; + SetScrollX(g.CurrentWindow, scroll_x); +} + +void ImGui::SetScrollY(float scroll_y) +{ + ImGuiContext &g = *GImGui; + SetScrollY(g.CurrentWindow, scroll_y); +} + +// Note that a local position will vary depending on initial scroll value, +// This is a little bit confusing so bear with us: +// - local_pos = (absolution_pos - window->Pos) +// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window, +// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area. +// - They mostly exists because of legacy API. +// Following the rules above, when trying to work with scrolling code, consider that: +// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect! +// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense +// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size +void ImGui::SetScrollFromPosX(ImGuiWindow *window, float local_x, float center_x_ratio) +{ + IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); + window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset + window->ScrollTargetCenterRatio.x = center_x_ratio; + window->ScrollTargetEdgeSnapDist.x = 0.0f; +} + +void ImGui::SetScrollFromPosY(ImGuiWindow *window, float local_y, float center_y_ratio) +{ + IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); + const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect; + local_y -= decoration_up_height; + window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset + window->ScrollTargetCenterRatio.y = center_y_ratio; + window->ScrollTargetEdgeSnapDist.y = 0.0f; +} + +void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) +{ + ImGuiContext &g = *GImGui; + SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio); +} + +void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) +{ + ImGuiContext &g = *GImGui; + SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio); +} + +// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. +void ImGui::SetScrollHereX(float center_x_ratio) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x); + float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio); + SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos + + // Tweak: snap on edges when aiming at an item very close to the edge + window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x); +} + +// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. +void ImGui::SetScrollHereY(float center_y_ratio) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y); + float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio); + SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos + + // Tweak: snap on edges when aiming at an item very close to the edge + window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y); +} + +//----------------------------------------------------------------------------- +// [SECTION] TOOLTIPS +//----------------------------------------------------------------------------- + +void ImGui::BeginTooltip() +{ + BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None); +} + +void ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags) +{ + ImGuiContext &g = *GImGui; + + if (g.DragDropWithinSource || g.DragDropWithinTarget) + { + // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor) + // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor. + // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do. + // ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; + ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale); + SetNextWindowPos(tooltip_pos); + SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f); + // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :( + tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip; + } + + char window_name[16]; + ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount); + if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip) + if (ImGuiWindow *window = FindWindowByName(window_name)) + if (window->Active) + { + // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. + window->Hidden = true; + window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary? + ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount); + } + ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking; + Begin(window_name, NULL, flags | extra_window_flags); +} + +void ImGui::EndTooltip() +{ + IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls + End(); +} + +void ImGui::SetTooltipV(const char *fmt, va_list args) +{ + BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None); + TextV(fmt, args); + EndTooltip(); +} + +void ImGui::SetTooltip(const char *fmt, ...) +{ + va_list args; + va_start(args, fmt); + SetTooltipV(fmt, args); + va_end(args); +} + +//----------------------------------------------------------------------------- +// [SECTION] POPUPS +//----------------------------------------------------------------------------- + +// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel +bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext &g = *GImGui; + if (popup_flags & ImGuiPopupFlags_AnyPopupId) + { + // Return true if any popup is open at the current BeginPopup() level of the popup stack + // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level. + IM_ASSERT(id == 0); + if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) + return g.OpenPopupStack.Size > 0; + else + return g.OpenPopupStack.Size > g.BeginPopupStack.Size; + } + else + { + if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) + { + // Return true if the popup is open anywhere in the popup stack + for (int n = 0; n < g.OpenPopupStack.Size; n++) + if (g.OpenPopupStack[n].PopupId == id) + return true; + return false; + } + else + { + // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query) + return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; + } + } +} + +bool ImGui::IsPopupOpen(const char *str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext &g = *GImGui; + ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id); + if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0) + IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally + return IsPopupOpen(id, popup_flags); +} + +ImGuiWindow *ImGui::GetTopMostPopupModal() +{ + ImGuiContext &g = *GImGui; + for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--) + if (ImGuiWindow *popup = g.OpenPopupStack.Data[n].Window) + if (popup->Flags & ImGuiWindowFlags_Modal) + return popup; + return NULL; +} + +ImGuiWindow *ImGui::GetTopMostAndVisiblePopupModal() +{ + ImGuiContext &g = *GImGui; + for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--) + if (ImGuiWindow *popup = g.OpenPopupStack.Data[n].Window) + if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup)) + return popup; + return NULL; +} + +void ImGui::OpenPopup(const char *str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext &g = *GImGui; + OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags); +} + +void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags) +{ + OpenPopupEx(id, popup_flags); +} + +// Mark popup as open (toggle toward open state). +// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. +// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). +// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) +void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *parent_window = g.CurrentWindow; + const int current_stack_size = g.BeginPopupStack.Size; + + if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup) + if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId)) + return; + + ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. + popup_ref.PopupId = id; + popup_ref.Window = NULL; + popup_ref.SourceWindow = g.NavWindow; + popup_ref.OpenFrameCount = g.FrameCount; + popup_ref.OpenParentId = parent_window->IDStack.back(); + popup_ref.OpenPopupPos = NavCalcPreferredRefPos(); + popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos; + + IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id); + if (g.OpenPopupStack.Size < current_stack_size + 1) + { + g.OpenPopupStack.push_back(popup_ref); + } + else + { + // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui + // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing + // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand. + if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) + { + g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount; + } + else + { + // Close child popups if any, then flag popup for open/reopen + ClosePopupToLevel(current_stack_size, false); + g.OpenPopupStack.push_back(popup_ref); + } + + // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow(). + // This is equivalent to what ClosePopupToLevel() does. + // if (g.OpenPopupStack[current_stack_size].PopupId == id) + // FocusWindow(parent_window); + } +} + +// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. +// This function closes any popups that are over 'ref_window'. +void ImGui::ClosePopupsOverWindow(ImGuiWindow *ref_window, bool restore_focus_to_window_under_popup) +{ + ImGuiContext &g = *GImGui; + if (g.OpenPopupStack.Size == 0) + return; + + // Don't close our own child popup windows. + int popup_count_to_keep = 0; + if (ref_window) + { + // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow) + for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++) + { + ImGuiPopupData &popup = g.OpenPopupStack[popup_count_to_keep]; + if (!popup.Window) + continue; + IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); + if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) + continue; + + // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow) + // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3: + // Window -> Popup1 -> Popup2 -> Popup3 + // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree! + // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child + bool ref_window_is_descendent_of_popup = false; + for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++) + if (ImGuiWindow *popup_window = g.OpenPopupStack[n].Window) + // if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE + if (IsWindowWithinBeginStackOf(ref_window, popup_window)) + { + ref_window_is_descendent_of_popup = true; + break; + } + if (!ref_window_is_descendent_of_popup) + break; + } + } + if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below + { + IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep); + ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup); + } +} + +void ImGui::ClosePopupsExceptModals() +{ + ImGuiContext &g = *GImGui; + + int popup_count_to_keep; + for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--) + { + ImGuiWindow *window = g.OpenPopupStack[popup_count_to_keep - 1].Window; + if (!window || window->Flags & ImGuiWindowFlags_Modal) + break; + } + if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below + ClosePopupToLevel(popup_count_to_keep, true); +} + +void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup) +{ + ImGuiContext &g = *GImGui; + IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup); + IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); + + // Trim open popup stack + ImGuiWindow *focus_window = g.OpenPopupStack[remaining].SourceWindow; + ImGuiWindow *popup_window = g.OpenPopupStack[remaining].Window; + g.OpenPopupStack.resize(remaining); + + if (restore_focus_to_window_under_popup) + { + if (focus_window && !focus_window->WasActive && popup_window) + { + // Fallback + FocusTopMostWindowUnderOne(popup_window, NULL); + } + else + { + if (g.NavLayer == ImGuiNavLayer_Main && focus_window) + focus_window = NavRestoreLastChildNavWindow(focus_window); + FocusWindow(focus_window); + } + } +} + +// Close the popup we have begin-ed into. +void ImGui::CloseCurrentPopup() +{ + ImGuiContext &g = *GImGui; + int popup_idx = g.BeginPopupStack.Size - 1; + if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId) + return; + + // Closing a menu closes its top-most parent popup (unless a modal) + while (popup_idx > 0) + { + ImGuiWindow *popup_window = g.OpenPopupStack[popup_idx].Window; + ImGuiWindow *parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window; + bool close_parent = false; + if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu)) + if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar)) + close_parent = true; + if (!close_parent) + break; + popup_idx--; + } + IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx); + ClosePopupToLevel(popup_idx, true); + + // A common pattern is to close a popup when selecting a menu item/selectable that will open another window. + // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window. + // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic. + if (ImGuiWindow *window = g.NavWindow) + window->DC.NavHideHighlightOneFrame = true; +} + +// Attention! BeginPopup() adds default flags which BeginPopupEx()! +bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) +{ + ImGuiContext &g = *GImGui; + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) + { + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + return false; + } + + char name[20]; + if (flags & ImGuiWindowFlags_ChildMenu) + ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth + else + ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame + + flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking; + bool is_open = Begin(name, NULL, flags); + if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) + EndPopup(); + + return is_open; +} + +bool ImGui::BeginPopup(const char *str_id, ImGuiWindowFlags flags) +{ + ImGuiContext &g = *GImGui; + if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance + { + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + return false; + } + flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings; + ImGuiID id = g.CurrentWindow->GetID(str_id); + return BeginPopupEx(id, flags); +} + +// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup. +// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here. +bool ImGui::BeginPopupModal(const char *name, bool *p_open, ImGuiWindowFlags flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + const ImGuiID id = window->GetID(name); + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) + { + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + return false; + } + + // Center modal windows by default for increased visibility + // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves) + // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. + if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) + { + const ImGuiViewport *viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport? + SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); + } + + flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking; + const bool is_open = Begin(name, p_open, flags); + if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + { + EndPopup(); + if (is_open) + ClosePopupToLevel(g.BeginPopupStack.Size, true); + return false; + } + return is_open; +} + +void ImGui::EndPopup() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls + IM_ASSERT(g.BeginPopupStack.Size > 0); + + // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests) + if (g.NavWindow == window) + NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY); + + // Child-popups don't need to be laid out + IM_ASSERT(g.WithinEndChild == false); + if (window->Flags & ImGuiWindowFlags_ChildWindow) + g.WithinEndChild = true; + End(); + g.WithinEndChild = false; +} + +// Helper to open a popup if mouse button is released over the item +// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup() +void ImGui::OpenPopupOnItemClick(const char *str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); + if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + { + ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) + OpenPopupEx(id, popup_flags); + } +} + +// This is a helper to handle the simplest case of associating one named popup to one given widget. +// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id. +// - To create a popup with a specific identifier, pass it in str_id. +// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call. +// - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id. +// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). +// This is essentially the same as: +// id = str_id ? GetID(str_id) : GetItemID(); +// OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight); +// return BeginPopup(id); +// Which is essentially the same as: +// id = str_id ? GetID(str_id) : GetItemID(); +// if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) +// OpenPopup(id); +// return BeginPopup(id); +// The main difference being that this is tweaked to avoid computing the ID twice. +bool ImGui::BeginPopupContextItem(const char *str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (window->SkipItems) + return false; + ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); + if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + OpenPopupEx(id, popup_flags); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); +} + +bool ImGui::BeginPopupContextWindow(const char *str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (!str_id) + str_id = "window_context"; + ImGuiID id = window->GetID(str_id); + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); + if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered()) + OpenPopupEx(id, popup_flags); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); +} + +bool ImGui::BeginPopupContextVoid(const char *str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (!str_id) + str_id = "void_context"; + ImGuiID id = window->GetID(str_id); + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); + if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) + if (GetTopMostPopupModal() == NULL) + OpenPopupEx(id, popup_flags); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); +} + +// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) +// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it. +// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor +// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport. +// this allows us to have tooltips/popups displayed out of the parent viewport.) +ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2 &ref_pos, const ImVec2 &size, ImGuiDir *last_dir, const ImRect &r_outer, const ImRect &r_avoid, ImGuiPopupPositionPolicy policy) +{ + ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size); + // GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255)); + // GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255)); + + // Combo Box policy (we want a connecting edge) + if (policy == ImGuiPopupPositionPolicy_ComboBox) + { + const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = {ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up}; + for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) + { + const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; + if (n != -1 && dir == *last_dir) // Already tried this direction? + continue; + ImVec2 pos; + if (dir == ImGuiDir_Down) + pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default) + if (dir == ImGuiDir_Right) + pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right + if (dir == ImGuiDir_Left) + pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left + if (dir == ImGuiDir_Up) + pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left + if (!r_outer.Contains(ImRect(pos, pos + size))) + continue; + *last_dir = dir; + return pos; + } + } + + // Tooltip and Default popup policy + // (Always first try the direction we used on the last frame, if any) + if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default) + { + const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = {ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left}; + for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) + { + const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; + if (n != -1 && dir == *last_dir) // Already tried this direction? + continue; + + const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); + const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); + + // If there not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width) + if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right)) + continue; + if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down)) + continue; + + ImVec2 pos; + pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x + : base_pos_clamped.x; + pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y + : base_pos_clamped.y; + + // Clamp top-left corner of popup + pos.x = ImMax(pos.x, r_outer.Min.x); + pos.y = ImMax(pos.y, r_outer.Min.y); + + *last_dir = dir; + return pos; + } + } + + // Fallback when not enough room: + *last_dir = ImGuiDir_None; + + // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. + if (policy == ImGuiPopupPositionPolicy_Tooltip) + return ref_pos + ImVec2(2, 2); + + // Otherwise try to keep within display + ImVec2 pos = ref_pos; + pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); + pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); + return pos; +} + +// Note that this is used for popups, which can overlap the non work-area of individual viewports. +ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + ImRect r_screen; + if (window->ViewportAllowPlatformMonitorExtend >= 0) + { + // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here) + const ImGuiPlatformMonitor &monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend]; + r_screen.Min = monitor.WorkPos; + r_screen.Max = monitor.WorkPos + monitor.WorkSize; + } + else + { + // Use the full viewport area (not work area) for popups + r_screen = window->Viewport->GetMainRect(); + } + ImVec2 padding = g.Style.DisplaySafeAreaPadding; + r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f)); + return r_screen; +} + +ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + + ImRect r_outer = GetPopupAllowedExtentRect(window); + if (window->Flags & ImGuiWindowFlags_ChildMenu) + { + // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds. + // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. + ImGuiWindow *parent_window = window->ParentWindow; + float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x). + ImRect r_avoid; + if (parent_window->DC.MenuBarAppending) + r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field + else + r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX); + return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default); + } + if (window->Flags & ImGuiWindowFlags_Popup) + { + return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here + } + if (window->Flags & ImGuiWindowFlags_Tooltip) + { + // Position tooltip (always follows mouse) + float sc = g.Style.MouseCursorScale; + ImVec2 ref_pos = NavCalcPreferredRefPos(); + ImRect r_avoid; + if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)) + r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8); + else + r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important. + return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip); + } + IM_ASSERT(0); + return window->Pos; +} + +//----------------------------------------------------------------------------- +// [SECTION] KEYBOARD/GAMEPAD NAVIGATION +//----------------------------------------------------------------------------- + +// FIXME-NAV: The existence of SetNavID vs SetFocusID properly needs to be clarified/reworked. +// In our terminology those should be interchangeable. Those two functions are merely a legacy artifact, so at minimum naming should be clarified. +void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect &rect_rel) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.NavWindow != NULL); + IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu); + g.NavId = id; + g.NavLayer = nav_layer; + g.NavFocusScopeId = focus_scope_id; + g.NavWindow->NavLastIds[nav_layer] = id; + g.NavWindow->NavRectRel[nav_layer] = rect_rel; +} + +void ImGui::SetFocusID(ImGuiID id, ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(id != 0); + + // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid. + // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text) + const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent; + if (g.NavWindow != window) + g.NavInitRequest = false; + g.NavWindow = window; + g.NavId = id; + g.NavLayer = nav_layer; + g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent; + window->NavLastIds[nav_layer] = id; + if (g.LastItemData.ID == id) + window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect); + + if (g.ActiveIdSource == ImGuiInputSource_Nav) + g.NavDisableMouseHover = true; + else + g.NavDisableHighlight = true; +} + +ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy) +{ + if (ImFabs(dx) > ImFabs(dy)) + return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left; + return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up; +} + +static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1) +{ + if (a1 < b0) + return a1 - b0; + if (b1 < a0) + return a0 - b1; + return 0.0f; +} + +static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect &r, const ImRect &clip_rect) +{ + if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) + { + r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y); + r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y); + } + else // FIXME: PageUp/PageDown are leaving move_dir == None + { + r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x); + r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x); + } +} + +// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057 +static bool ImGui::NavScoreItem(ImGuiNavItemData *result) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + if (g.NavLayer != window->DC.NavLayerCurrent) + return false; + + // FIXME: Those are not good variables names + ImRect cand = g.LastItemData.NavRect; // Current item nav rectangle + const ImRect curr = g.NavScoringRect; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width) + g.NavScoringDebugCount++; + + // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring + if (window->ParentWindow == g.NavWindow) + { + IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened); + if (!window->ClipRect.Overlaps(cand)) + return false; + cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window + } + + // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items) + // For example, this ensure that items in one column are not reached when moving vertically from items in another column. + NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect); + + // Compute distance between boxes + // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed. + float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x); + float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items + if (dby != 0.0f && dbx != 0.0f) + dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f); + float dist_box = ImFabs(dbx) + ImFabs(dby); + + // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) + float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x); + float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y); + float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee) + + // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance + ImGuiDir quadrant; + float dax = 0.0f, day = 0.0f, dist_axial = 0.0f; + if (dbx != 0.0f || dby != 0.0f) + { + // For non-overlapping boxes, use distance between boxes + dax = dbx; + day = dby; + dist_axial = dist_box; + quadrant = ImGetDirQuadrantFromDelta(dbx, dby); + } + else if (dcx != 0.0f || dcy != 0.0f) + { + // For overlapping boxes with different centers, use distance between centers + dax = dcx; + day = dcy; + dist_axial = dist_center; + quadrant = ImGetDirQuadrantFromDelta(dcx, dcy); + } + else + { + // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter) + quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right; + } + +#if IMGUI_DEBUG_NAV_SCORING + char buf[128]; + if (IsMouseHoveringRect(cand.Min, cand.Max)) + { + ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]); + ImDrawList *draw_list = GetForegroundDrawList(window); + draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100)); + draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200)); + draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 150)); + draw_list->AddText(cand.Max, ~0U, buf); + } + else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate. + { + if (quadrant == g.NavMoveDir) + { + ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center); + ImDrawList *draw_list = GetForegroundDrawList(window); + draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200)); + draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf); + } + } +#endif + + // Is it in the quadrant we're interesting in moving to? + bool new_best = false; + const ImGuiDir move_dir = g.NavMoveDir; + if (quadrant == move_dir) + { + // Does it beat the current best candidate? + if (dist_box < result->DistBox) + { + result->DistBox = dist_box; + result->DistCenter = dist_center; + return true; + } + if (dist_box == result->DistBox) + { + // Try using distance between center points to break ties + if (dist_center < result->DistCenter) + { + result->DistCenter = dist_center; + new_best = true; + } + else if (dist_center == result->DistCenter) + { + // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items + // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index), + // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis. + if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance + new_best = true; + } + } + } + + // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches + // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness) + // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too. + // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward. + // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option? + if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match + if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) + if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f)) + { + result->DistAxial = dist_axial; + new_best = true; + } + + return new_best; +} + +static void ImGui::NavApplyItemToResult(ImGuiNavItemData *result) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + result->Window = window; + result->ID = g.LastItemData.ID; + result->FocusScopeId = window->DC.NavFocusScopeIdCurrent; + result->InFlags = g.LastItemData.InFlags; + result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect); +} + +// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above) +// This is called after LastItemData is set. +static void ImGui::NavProcessItem() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + const ImGuiID id = g.LastItemData.ID; + const ImRect nav_bb = g.LastItemData.NavRect; + const ImGuiItemFlags item_flags = g.LastItemData.InFlags; + + // Process Init Request + if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0) + { + // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback + const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0; + if (candidate_for_nav_default_focus || g.NavInitResultId == 0) + { + g.NavInitResultId = id; + g.NavInitResultRectRel = WindowRectAbsToRel(window, nav_bb); + } + if (candidate_for_nav_default_focus) + { + g.NavInitRequest = false; // Found a match, clear request + NavUpdateAnyRequestFlag(); + } + } + + // Process Move Request (scoring for navigation) + // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy) + if (g.NavMoveScoringItems) + { + const bool is_tab_stop = (item_flags & ImGuiItemFlags_Inputable) && (item_flags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0; + const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0; + if (is_tabbing) + { + if (is_tab_stop || (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi)) + NavProcessItemForTabbingRequest(id); + } + else if ((g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav))) + { + ImGuiNavItemData *result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; + if (!is_tabbing) + { + if (NavScoreItem(result)) + NavApplyItemToResult(result); + + // Features like PageUp/PageDown need to maintain a separate score for the visible set of items. + const float VISIBLE_RATIO = 0.70f; + if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb)) + if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO) + if (NavScoreItem(&g.NavMoveResultLocalVisible)) + NavApplyItemToResult(&g.NavMoveResultLocalVisible); + } + } + } + + // Update window-relative bounding box of navigated item + if (g.NavId == id) + { + g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window. + g.NavLayer = window->DC.NavLayerCurrent; + g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent; + g.NavIdIsAlive = true; + window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position) + } +} + +// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest(). +// Note that SetKeyboardFocusHere() API calls are considered tabbing requests! +// - Case 1: no nav/active id: set result to first eligible item, stop storing. +// - Case 2: tab forward: on ref id set counter, on counter elapse store result +// - Case 3: tab forward wrap: set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request +// - Case 4: tab backward: store all results, on ref id pick prev, stop storing +// - Case 5: tab backward wrap: store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested +void ImGui::NavProcessItemForTabbingRequest(ImGuiID id) +{ + ImGuiContext &g = *GImGui; + + // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows) + ImGuiNavItemData *result = &g.NavMoveResultLocal; + if (g.NavTabbingDir == +1) + { + // Tab Forward or SetKeyboardFocusHere() with >= 0 + if (g.NavTabbingResultFirst.ID == 0) + NavApplyItemToResult(&g.NavTabbingResultFirst); + if (--g.NavTabbingCounter == 0) + NavMoveRequestResolveWithLastItem(result); + else if (g.NavId == id) + g.NavTabbingCounter = 1; + } + else if (g.NavTabbingDir == -1) + { + // Tab Backward + if (g.NavId == id) + { + if (result->ID) + { + g.NavMoveScoringItems = false; + NavUpdateAnyRequestFlag(); + } + } + else + { + NavApplyItemToResult(result); + } + } + else if (g.NavTabbingDir == 0) + { + // Tab Init + if (g.NavTabbingResultFirst.ID == 0) + NavMoveRequestResolveWithLastItem(&g.NavTabbingResultFirst); + } +} + +bool ImGui::NavMoveRequestButNoResultYet() +{ + ImGuiContext &g = *GImGui; + return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0; +} + +// FIXME: ScoringRect is not set +void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.NavWindow != NULL); + + if (move_flags & ImGuiNavMoveFlags_Tabbing) + move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId; + + g.NavMoveSubmitted = g.NavMoveScoringItems = true; + g.NavMoveDir = move_dir; + g.NavMoveDirForDebug = move_dir; + g.NavMoveClipDir = clip_dir; + g.NavMoveFlags = move_flags; + g.NavMoveScrollFlags = scroll_flags; + g.NavMoveForwardToNextFrame = false; + g.NavMoveKeyMods = g.IO.KeyMods; + g.NavTabbingCounter = 0; + g.NavMoveResultLocal.Clear(); + g.NavMoveResultLocalVisible.Clear(); + g.NavMoveResultOther.Clear(); + NavUpdateAnyRequestFlag(); +} + +void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData *result) +{ + ImGuiContext &g = *GImGui; + g.NavMoveScoringItems = false; // Ensure request doesn't need more processing + NavApplyItemToResult(result); + NavUpdateAnyRequestFlag(); +} + +void ImGui::NavMoveRequestCancel() +{ + ImGuiContext &g = *GImGui; + g.NavMoveSubmitted = g.NavMoveScoringItems = false; + NavUpdateAnyRequestFlag(); +} + +// Forward will reuse the move request again on the next frame (generally with modifications done to it) +void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.NavMoveForwardToNextFrame == false); + NavMoveRequestCancel(); + g.NavMoveForwardToNextFrame = true; + g.NavMoveDir = move_dir; + g.NavMoveClipDir = clip_dir; + g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded; + g.NavMoveScrollFlags = scroll_flags; +} + +// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire +// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final. +void ImGui::NavMoveRequestTryWrapping(ImGuiWindow *window, ImGuiNavMoveFlags wrap_flags) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(wrap_flags != 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY + // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test + if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main) + g.NavMoveFlags |= wrap_flags; +} + +// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0). +// This way we could find the last focused window among our children. It would be much less confusing this way? +static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow *nav_window) +{ + ImGuiWindow *parent = nav_window; + while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) + parent = parent->ParentWindow; + if (parent && parent != nav_window) + parent->NavLastChildNavWindow = nav_window; +} + +// Restore the last focused child. +// Call when we are expected to land on the Main Layer (0) after FocusWindow() +static ImGuiWindow *ImGui::NavRestoreLastChildNavWindow(ImGuiWindow *window) +{ + if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive) + return window->NavLastChildNavWindow; + if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar) + if (ImGuiTabItem *tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar)) + return tab->Window; + return window; +} + +void ImGui::NavRestoreLayer(ImGuiNavLayer layer) +{ + ImGuiContext &g = *GImGui; + if (layer == ImGuiNavLayer_Main) + g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow); + ImGuiWindow *window = g.NavWindow; + if (window->NavLastIds[layer] != 0) + { + SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]); + } + else + { + g.NavLayer = layer; + NavInitWindow(window, true); + } +} + +void ImGui::NavRestoreHighlightAfterMove() +{ + ImGuiContext &g = *GImGui; + g.NavDisableHighlight = false; + g.NavDisableMouseHover = g.NavMousePosDirty = true; +} + +static inline void ImGui::NavUpdateAnyRequestFlag() +{ + ImGuiContext &g = *GImGui; + g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL); + if (g.NavAnyRequest) + IM_ASSERT(g.NavWindow != NULL); +} + +// This needs to be called before we submit any widget (aka in or before Begin) +void ImGui::NavInitWindow(ImGuiWindow *window, bool force_reinit) +{ + // FIXME: ChildWindow test here is wrong for docking + ImGuiContext &g = *GImGui; + IM_ASSERT(window == g.NavWindow); + + if (window->Flags & ImGuiWindowFlags_NoNavInputs) + { + g.NavId = g.NavFocusScopeId = 0; + return; + } + + bool init_for_nav = false; + if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit) + init_for_nav = true; + IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer); + if (init_for_nav) + { + SetNavID(0, g.NavLayer, 0, ImRect()); + g.NavInitRequest = true; + g.NavInitRequestFromMove = false; + g.NavInitResultId = 0; + g.NavInitResultRectRel = ImRect(); + NavUpdateAnyRequestFlag(); + } + else + { + g.NavId = window->NavLastIds[0]; + g.NavFocusScopeId = 0; + } +} + +static ImVec2 ImGui::NavCalcPreferredRefPos() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.NavWindow; + if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window) + { + // Mouse (we need a fallback in case the mouse becomes invalid after being used) + // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard. + // In theory we could move that +1.0f offset in OpenPopupEx() + ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos; + return ImVec2(p.x + 1.0f, p.y); + } + else + { + // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item + // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?) + ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]); + if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX)) + { + ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window); + rect_rel.Translate(window->Scroll - next_scroll); + } + ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight())); + ImGuiViewport *viewport = window->Viewport; + return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta. + } +} + +const char *ImGui::GetNavInputName(ImGuiNavInput n) +{ + static const char *names[] = + { + "Activate", "Cancel", "Input", "Menu", "DpadLeft", "DpadRight", "DpadUp", "DpadDown", "LStickLeft", "LStickRight", "LStickUp", "LStickDown", + "FocusPrev", "FocusNext", "TweakSlow", "TweakFast", "KeyLeft", "KeyRight", "KeyUp", "KeyDown"}; + IM_ASSERT(IM_ARRAYSIZE(names) == ImGuiNavInput_COUNT); + IM_ASSERT(n >= 0 && n < ImGuiNavInput_COUNT); + return names[n]; +} + +float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiNavReadMode mode) +{ + ImGuiContext &g = *GImGui; + if (mode == ImGuiNavReadMode_Down) + return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user) + + const float t = g.IO.NavInputsDownDuration[n]; + if (t < 0.0f && mode == ImGuiNavReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input. + return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f); + if (t < 0.0f) + return 0.0f; + if (mode == ImGuiNavReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input. + return (t == 0.0f) ? 1.0f : 0.0f; + if (mode == ImGuiNavReadMode_Repeat) + return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f); + if (mode == ImGuiNavReadMode_RepeatSlow) + return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f); + if (mode == ImGuiNavReadMode_RepeatFast) + return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f); + return 0.0f; +} + +ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiNavReadMode mode, float slow_factor, float fast_factor) +{ + ImVec2 delta(0.0f, 0.0f); + if (dir_sources & ImGuiNavDirSourceFlags_RawKeyboard) + delta += ImVec2((float)IsKeyDown(ImGuiKey_RightArrow) - (float)IsKeyDown(ImGuiKey_LeftArrow), (float)IsKeyDown(ImGuiKey_DownArrow) - (float)IsKeyDown(ImGuiKey_UpArrow)); + if (dir_sources & ImGuiNavDirSourceFlags_Keyboard) + delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode)); + if (dir_sources & ImGuiNavDirSourceFlags_PadDPad) + delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode)); + if (dir_sources & ImGuiNavDirSourceFlags_PadLStick) + delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode)); + if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow)) + delta *= slow_factor; + if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast)) + delta *= fast_factor; + return delta; +} + +static void ImGui::NavUpdate() +{ + ImGuiContext &g = *GImGui; + ImGuiIO &io = g.IO; + + io.WantSetMousePos = false; + // if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG("NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest); + + // Update Gamepad->Nav inputs mapping + // Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard) + const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; + if (nav_gamepad_active && g.IO.BackendUsingLegacyNavInputArray == false) + { + for (int n = 0; n < ImGuiNavInput_COUNT; n++) + IM_ASSERT(io.NavInputs[n] == 0.0f && "Backend needs to either only use io.AddKeyEvent()/io.AddKeyAnalogEvent(), either only fill legacy io.NavInputs[]. Not both!"); +#define NAV_MAP_KEY(_KEY, _NAV_INPUT, _ACTIVATE_NAV) \ + do \ + { \ + io.NavInputs[_NAV_INPUT] = io.KeysData[_KEY - ImGuiKey_KeysData_OFFSET].AnalogValue; \ + if (_ACTIVATE_NAV && io.NavInputs[_NAV_INPUT] > 0.0f) \ + { \ + g.NavInputSource = ImGuiInputSource_Gamepad; \ + } \ + } while (0) + NAV_MAP_KEY(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate, true); + NAV_MAP_KEY(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel, true); + NAV_MAP_KEY(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu, true); + NAV_MAP_KEY(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input, true); + NAV_MAP_KEY(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft, true); + NAV_MAP_KEY(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight, true); + NAV_MAP_KEY(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp, true); + NAV_MAP_KEY(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown, true); + NAV_MAP_KEY(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, false); + NAV_MAP_KEY(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, false); + NAV_MAP_KEY(ImGuiKey_GamepadL1, ImGuiNavInput_TweakSlow, false); + NAV_MAP_KEY(ImGuiKey_GamepadR1, ImGuiNavInput_TweakFast, false); + NAV_MAP_KEY(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft, false); + NAV_MAP_KEY(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight, false); + NAV_MAP_KEY(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp, false); + NAV_MAP_KEY(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown, false); +#undef NAV_MAP_KEY + } + + // Update Keyboard->Nav inputs mapping + const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + if (nav_keyboard_active) + { +#define NAV_MAP_KEY(_KEY, _NAV_INPUT) \ + do \ + { \ + if (IsKeyDown(_KEY)) \ + { \ + io.NavInputs[_NAV_INPUT] = 1.0f; \ + g.NavInputSource = ImGuiInputSource_Keyboard; \ + } \ + } while (0) + NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate); + NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input); + NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel); + NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_); + NAV_MAP_KEY(ImGuiKey_RightArrow, ImGuiNavInput_KeyRight_); + NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_); + NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_); + if (io.KeyCtrl) + io.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; + if (io.KeyShift) + io.NavInputs[ImGuiNavInput_TweakFast] = 1.0f; +#undef NAV_MAP_KEY + } + memcpy(io.NavInputsDownDurationPrev, io.NavInputsDownDuration, sizeof(io.NavInputsDownDuration)); + for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) + io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f; + + // Process navigation init request (select first/default focus) + if (g.NavInitResultId != 0) + NavInitRequestApplyResult(); + g.NavInitRequest = false; + g.NavInitRequestFromMove = false; + g.NavInitResultId = 0; + g.NavJustMovedToId = 0; + + // Process navigation move request + if (g.NavMoveSubmitted) + NavMoveRequestApplyResult(); + g.NavTabbingCounter = 0; + g.NavMoveSubmitted = g.NavMoveScoringItems = false; + + // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling) + bool set_mouse_pos = false; + if (g.NavMousePosDirty && g.NavIdIsAlive) + if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow) + set_mouse_pos = true; + g.NavMousePosDirty = false; + IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu); + + // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0 + if (g.NavWindow) + NavSaveLastChildNavWindowIntoParent(g.NavWindow); + if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main) + g.NavWindow->NavLastChildNavWindow = NULL; + + // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.) + NavUpdateWindowing(); + + // Set output flags for user application + io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs); + io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL); + + // Process NavCancel input (to close a popup, get back to parent, clear focus) + NavUpdateCancelRequest(); + + // Process manual activation request + g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavActivateInputId = 0; + g.NavActivateFlags = ImGuiActivateFlags_None; + if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) + { + bool activate_down = IsNavInputDown(ImGuiNavInput_Activate); + bool input_down = IsNavInputDown(ImGuiNavInput_Input); + bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiNavReadMode_Pressed); + bool input_pressed = input_down && IsNavInputTest(ImGuiNavInput_Input, ImGuiNavReadMode_Pressed); + if (g.ActiveId == 0 && activate_pressed) + { + g.NavActivateId = g.NavId; + g.NavActivateFlags = ImGuiActivateFlags_PreferTweak; + } + if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed) + { + g.NavActivateInputId = g.NavId; + g.NavActivateFlags = ImGuiActivateFlags_PreferInput; + } + if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down) + g.NavActivateDownId = g.NavId; + if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed) + g.NavActivatePressedId = g.NavId; + } + if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) + g.NavDisableHighlight = true; + if (g.NavActivateId != 0) + IM_ASSERT(g.NavActivateDownId == g.NavActivateId); + + // Process programmatic activation request + // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others) + if (g.NavNextActivateId != 0) + { + if (g.NavNextActivateFlags & ImGuiActivateFlags_PreferInput) + g.NavActivateInputId = g.NavNextActivateId; + else + g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId; + g.NavActivateFlags = g.NavNextActivateFlags; + } + g.NavNextActivateId = 0; + + // Process move requests + NavUpdateCreateMoveRequest(); + if (g.NavMoveDir == ImGuiDir_None) + NavUpdateCreateTabbingRequest(); + NavUpdateAnyRequestFlag(); + g.NavIdIsAlive = false; + + // Scrolling + if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget) + { + // *Fallback* manual-scroll with Nav directional keys when window has no navigable item + ImGuiWindow *window = g.NavWindow; + const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported. + const ImGuiDir move_dir = g.NavMoveDir; + if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && move_dir != ImGuiDir_None) + { + if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) + SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed)); + if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) + SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed)); + } + + // *Normal* Manual scroll with NavScrollXXX keys + // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. + ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiNavReadMode_Down, 1.0f / 10.0f, 10.0f); + if (scroll_dir.x != 0.0f && window->ScrollbarX) + SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); + if (scroll_dir.y != 0.0f) + SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed)); + } + + // Always prioritize mouse highlight if navigation is disabled + if (!nav_keyboard_active && !nav_gamepad_active) + { + g.NavDisableHighlight = true; + g.NavDisableMouseHover = set_mouse_pos = false; + } + + // Update mouse position if requested + // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied) + if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos)) + { + io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos(); + io.WantSetMousePos = true; + // IMGUI_DEBUG_LOG("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y); + } + + // [DEBUG] + g.NavScoringDebugCount = 0; +#if IMGUI_DEBUG_NAV_RECTS + if (g.NavWindow) + { + ImDrawList *draw_list = GetForegroundDrawList(g.NavWindow); + if (1) + { + for (int layer = 0; layer < 2; layer++) + { + ImRect r = WindowRectRelToAbs(g.NavWindow, g.NavWindow->NavRectRel[layer]); + draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); + } + } // [DEBUG] + if (1) + { + ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255, 0, 255, 255) : IM_COL32(255, 0, 0, 255); + ImVec2 p = NavCalcPreferredRefPos(); + char buf[32]; + ImFormatString(buf, 32, "%d", g.NavLayer); + draw_list->AddCircleFilled(p, 3.0f, col); + draw_list->AddText(NULL, 13.0f, p + ImVec2(8, -4), col, buf); + } + } +#endif +} + +void ImGui::NavInitRequestApplyResult() +{ + // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void) + ImGuiContext &g = *GImGui; + if (!g.NavWindow) + return; + + // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) + // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently. + IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name); + SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel); + g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result + if (g.NavInitRequestFromMove) + NavRestoreHighlightAfterMove(); +} + +void ImGui::NavUpdateCreateMoveRequest() +{ + ImGuiContext &g = *GImGui; + ImGuiIO &io = g.IO; + ImGuiWindow *window = g.NavWindow; + + if (g.NavMoveForwardToNextFrame && window != NULL) + { + // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window) + // (preserve most state, which were already set by the NavMoveRequestForward() function) + IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None); + IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded); + IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir); + } + else + { + // Initiate directional inputs request + g.NavMoveDir = ImGuiDir_None; + g.NavMoveFlags = ImGuiNavMoveFlags_None; + g.NavMoveScrollFlags = ImGuiScrollFlags_None; + if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs)) + { + const ImGuiNavReadMode read_mode = ImGuiNavReadMode_Repeat; + if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) + { + g.NavMoveDir = ImGuiDir_Left; + } + if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) + { + g.NavMoveDir = ImGuiDir_Right; + } + if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) + { + g.NavMoveDir = ImGuiDir_Up; + } + if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) + { + g.NavMoveDir = ImGuiDir_Down; + } + } + g.NavMoveClipDir = g.NavMoveDir; + g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); + } + + // Update PageUp/PageDown/Home/End scroll + // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag? + const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + float scoring_rect_offset_y = 0.0f; + if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active) + scoring_rect_offset_y = NavUpdatePageUpPageDown(); + if (scoring_rect_offset_y != 0.0f) + { + g.NavScoringNoClipRect = window->InnerRect; + g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y); + } + + // [DEBUG] Always send a request +#if IMGUI_DEBUG_NAV_SCORING + if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C)) + g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3); + if (io.KeyCtrl && g.NavMoveDir == ImGuiDir_None) + { + g.NavMoveDir = g.NavMoveDirForDebug; + g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult; + } +#endif + + // Submit + g.NavMoveForwardToNextFrame = false; + if (g.NavMoveDir != ImGuiDir_None) + NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); + + // Moving with no reference triggers a init request (will be used as a fallback if the direction fails to find a match) + if (g.NavMoveSubmitted && g.NavId == 0) + { + IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer); + g.NavInitRequest = g.NavInitRequestFromMove = true; + g.NavInitResultId = 0; + g.NavDisableHighlight = false; + } + + // When using gamepad, we project the reference nav bounding box into window visible area. + // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative + // (can't focus a visible object like we can with the mouse). + if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL) // && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded)) + { + bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0; + bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0; + ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1))); + if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer])) + { + IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n"); + float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f); + float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item + inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX; + inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX; + inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX; + inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX; + window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel); + g.NavId = g.NavFocusScopeId = 0; + } + } + + // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) + ImRect scoring_rect; + if (window != NULL) + { + ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0); + scoring_rect = WindowRectRelToAbs(window, nav_rect_rel); + scoring_rect.TranslateY(scoring_rect_offset_y); + scoring_rect.Min.x = ImMin(scoring_rect.Min.x + 1.0f, scoring_rect.Max.x); + scoring_rect.Max.x = scoring_rect.Min.x; + IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem(). + // GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG] + // if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG] + } + g.NavScoringRect = scoring_rect; + g.NavScoringNoClipRect.Add(scoring_rect); +} + +void ImGui::NavUpdateCreateTabbingRequest() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.NavWindow; + IM_ASSERT(g.NavMoveDir == ImGuiDir_None); + if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs)) + return; + + const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, true) && !IsActiveIdUsingKey(ImGuiKey_Tab) && !g.IO.KeyCtrl && !g.IO.KeyAlt; + if (!tab_pressed) + return; + + // Initiate tabbing request + // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!) + // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests. + // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping. + //// FIXME: We use (g.ActiveId == 0) but (g.NavDisableHighlight == false) might be righter once we can tab through anything + g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 + : +1; + ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY; + ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down; + NavMoveRequestSubmit(ImGuiDir_None, clip_dir, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable. + g.NavTabbingResultFirst.Clear(); + g.NavTabbingCounter = -1; +} + +// Apply result from previous frame navigation directional move request. Always called from NavUpdate() +void ImGui::NavMoveRequestApplyResult() +{ + ImGuiContext &g = *GImGui; +#if IMGUI_DEBUG_NAV_SCORING + if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times + return; +#endif + + // Select which result to use + ImGuiNavItemData *result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther + : NULL; + + // Tabbing forward wrap + if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) + if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID) + result = &g.NavTabbingResultFirst; + + // In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result) + if (result == NULL) + { + if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) + g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight; + if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0) + NavRestoreHighlightAfterMove(); + return; + } + + // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page. + if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) + if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId) + result = &g.NavMoveResultLocalVisible; + + // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules. + if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow) + if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter)) + result = &g.NavMoveResultOther; + IM_ASSERT(g.NavWindow && result->Window); + + // Scroll to keep newly navigated item fully into view. + if (g.NavLayer == ImGuiNavLayer_Main) + { + if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY) + { + // FIXME: Should remove this + float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f; + SetScrollY(result->Window, scroll_target); + } + else + { + ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel); + ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags); + } + } + + g.NavWindow = result->Window; + if (g.ActiveId != result->ID) + ClearActiveID(); + if (g.NavId != result->ID) + { + // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId) + g.NavJustMovedToId = result->ID; + g.NavJustMovedToFocusScopeId = result->FocusScopeId; + g.NavJustMovedToKeyMods = g.NavMoveKeyMods; + } + + // Focus + IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name); + SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel); + + // Tabbing: Activates Inputable or Focus non-Inputable + if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable)) + { + g.NavNextActivateId = result->ID; + g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState; + g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight; + } + + // Activate + if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate) + { + g.NavNextActivateId = result->ID; + g.NavNextActivateFlags = ImGuiActivateFlags_None; + } + + // Enable nav highlight + if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0) + NavRestoreHighlightAfterMove(); +} + +// Process NavCancel input (to close a popup, get back to parent, clear focus) +// FIXME: In order to support e.g. Escape to clear a selection we'll need: +// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it. +// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept +static void ImGui::NavUpdateCancelRequest() +{ + ImGuiContext &g = *GImGui; + if (!IsNavInputTest(ImGuiNavInput_Cancel, ImGuiNavReadMode_Pressed)) + return; + + IMGUI_DEBUG_LOG_NAV("[nav] ImGuiNavInput_Cancel\n"); + if (g.ActiveId != 0) + { + if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel)) + ClearActiveID(); + } + else if (g.NavLayer != ImGuiNavLayer_Main) + { + // Leave the "menu" layer + NavRestoreLayer(ImGuiNavLayer_Main); + NavRestoreHighlightAfterMove(); + } + else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow) + { + // Exit child window + ImGuiWindow *child_window = g.NavWindow; + ImGuiWindow *parent_window = g.NavWindow->ParentWindow; + IM_ASSERT(child_window->ChildId != 0); + ImRect child_rect = child_window->Rect(); + FocusWindow(parent_window); + SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect)); + NavRestoreHighlightAfterMove(); + } + else if (g.OpenPopupStack.Size > 0) + { + // Close open popup/menu + if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal)) + ClosePopupToLevel(g.OpenPopupStack.Size - 1, true); + } + else + { + // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were + if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow))) + g.NavWindow->NavLastIds[0] = 0; + g.NavId = g.NavFocusScopeId = 0; + } +} + +// Handle PageUp/PageDown/Home/End keys +// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request +// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference +// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid? +static float ImGui::NavUpdatePageUpPageDown() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.NavWindow; + if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL) + return 0.0f; + + const bool page_up_held = IsKeyDown(ImGuiKey_PageUp) && !IsActiveIdUsingKey(ImGuiKey_PageUp); + const bool page_down_held = IsKeyDown(ImGuiKey_PageDown) && !IsActiveIdUsingKey(ImGuiKey_PageDown); + const bool home_pressed = IsKeyPressed(ImGuiKey_Home) && !IsActiveIdUsingKey(ImGuiKey_Home); + const bool end_pressed = IsKeyPressed(ImGuiKey_End) && !IsActiveIdUsingKey(ImGuiKey_End); + if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out + return 0.0f; + + if (g.NavLayer != ImGuiNavLayer_Main) + NavRestoreLayer(ImGuiNavLayer_Main); + + if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll) + { + // Fallback manual-scroll when window has no navigable item + if (IsKeyPressed(ImGuiKey_PageUp, true)) + SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight()); + else if (IsKeyPressed(ImGuiKey_PageDown, true)) + SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight()); + else if (home_pressed) + SetScrollY(window, 0.0f); + else if (end_pressed) + SetScrollY(window, window->ScrollMax.y); + } + else + { + ImRect &nav_rect_rel = window->NavRectRel[g.NavLayer]; + const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); + float nav_scoring_rect_offset_y = 0.0f; + if (IsKeyPressed(ImGuiKey_PageUp, true)) + { + nav_scoring_rect_offset_y = -page_offset_y; + g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item) + g.NavMoveClipDir = ImGuiDir_Up; + g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; + } + else if (IsKeyPressed(ImGuiKey_PageDown, true)) + { + nav_scoring_rect_offset_y = +page_offset_y; + g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item) + g.NavMoveClipDir = ImGuiDir_Down; + g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; + } + else if (home_pressed) + { + // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y + // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result. + // Preserve current horizontal position if we have any. + nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f; + if (nav_rect_rel.IsInverted()) + nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f; + g.NavMoveDir = ImGuiDir_Down; + g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY; + // FIXME-NAV: MoveClipDir left to _None, intentional? + } + else if (end_pressed) + { + nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y; + if (nav_rect_rel.IsInverted()) + nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f; + g.NavMoveDir = ImGuiDir_Up; + g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY; + // FIXME-NAV: MoveClipDir left to _None, intentional? + } + return nav_scoring_rect_offset_y; + } + return 0.0f; +} + +static void ImGui::NavEndFrame() +{ + ImGuiContext &g = *GImGui; + + // Show CTRL+TAB list window + if (g.NavWindowingTarget != NULL) + NavUpdateWindowingOverlay(); + + // Perform wrap-around in menus + // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly. + // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame. + const ImGuiNavMoveFlags wanted_flags = ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY; + if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & wanted_flags) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0) + NavUpdateCreateWrappingRequest(); +} + +static void ImGui::NavUpdateCreateWrappingRequest() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.NavWindow; + + bool do_forward = false; + ImRect bb_rel = window->NavRectRel[g.NavLayer]; + ImGuiDir clip_dir = g.NavMoveDir; + const ImGuiNavMoveFlags move_flags = g.NavMoveFlags; + if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) + { + bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x; + if (move_flags & ImGuiNavMoveFlags_WrapX) + { + bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row + clip_dir = ImGuiDir_Up; + } + do_forward = true; + } + if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) + { + bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x; + if (move_flags & ImGuiNavMoveFlags_WrapX) + { + bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row + clip_dir = ImGuiDir_Down; + } + do_forward = true; + } + if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) + { + bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y; + if (move_flags & ImGuiNavMoveFlags_WrapY) + { + bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column + clip_dir = ImGuiDir_Left; + } + do_forward = true; + } + if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) + { + bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y; + if (move_flags & ImGuiNavMoveFlags_WrapY) + { + bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column + clip_dir = ImGuiDir_Right; + } + do_forward = true; + } + if (!do_forward) + return; + window->NavRectRel[g.NavLayer] = bb_rel; + NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags); +} + +static int ImGui::FindWindowFocusIndex(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + IM_UNUSED(g); + int order = window->FocusOrder; + IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking) + IM_ASSERT(g.WindowsFocusOrder[order] == window); + return order; +} + +static ImGuiWindow *FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N) +{ + ImGuiContext &g = *GImGui; + for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir) + if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i])) + return g.WindowsFocusOrder[i]; + return NULL; +} + +static void NavUpdateWindowingHighlightWindow(int focus_change_dir) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.NavWindowingTarget); + if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal) + return; + + const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget); + ImGuiWindow *window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir); + if (!window_target) + window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir); + if (window_target) // Don't reset windowing target if there's a single window in the list + g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target; + g.NavWindowingToggleLayer = false; +} + +// Windowing management mode +// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer) +// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer) +static void ImGui::NavUpdateWindowing() +{ + ImGuiContext &g = *GImGui; + ImGuiIO &io = g.IO; + + ImGuiWindow *apply_focus_window = NULL; + bool apply_toggle_layer = false; + + ImGuiWindow *modal_window = GetTopMostPopupModal(); + bool allow_windowing = (modal_window == NULL); + if (!allow_windowing) + g.NavWindowingTarget = NULL; + + // Fade out + if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL) + { + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f); + if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f) + g.NavWindowingTargetAnim = NULL; + } + + // Start CTRL+Tab or Square+L/R window selection + const bool start_windowing_with_gamepad = allow_windowing && !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiNavReadMode_Pressed); + const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && io.KeyCtrl && IsKeyPressed(ImGuiKey_Tab); + if (start_windowing_with_gamepad || start_windowing_with_keyboard) + if (ImGuiWindow *window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) + { + g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; + g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f; + g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer + g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad; + } + + // Gamepad update + g.NavWindowingTimer += io.DeltaTime; + if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad) + { + // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); + + // Select window to focus + const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiNavReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiNavReadMode_RepeatSlow); + if (focus_change_dir != 0) + { + NavUpdateWindowingHighlightWindow(focus_change_dir); + g.NavWindowingHighlightAlpha = 1.0f; + } + + // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most) + if (!IsNavInputDown(ImGuiNavInput_Menu)) + { + g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. + if (g.NavWindowingToggleLayer && g.NavWindow) + apply_toggle_layer = true; + else if (!g.NavWindowingToggleLayer) + apply_focus_window = g.NavWindowingTarget; + g.NavWindowingTarget = NULL; + } + } + + // Keyboard: Focus + if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard) + { + // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f + if (IsKeyPressed(ImGuiKey_Tab, true)) + NavUpdateWindowingHighlightWindow(io.KeyShift ? +1 : -1); + if (!io.KeyCtrl) + apply_focus_window = g.NavWindowingTarget; + } + + // Keyboard: Press and Release ALT to toggle menu layer + // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer. + // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway. + const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + if (nav_keyboard_active && IsKeyPressed(ImGuiKey_ModAlt)) + { + g.NavWindowingToggleLayer = true; + g.NavInputSource = ImGuiInputSource_Keyboard; + } + if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard) + { + // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370) + // We cancel toggling nav layer when other modifiers are pressed. (See #4439) + if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper) + g.NavWindowingToggleLayer = false; + + // Apply layer toggle on release + // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss. + if (IsKeyReleased(ImGuiKey_ModAlt) && g.NavWindowingToggleLayer) + if (g.ActiveId == 0 || g.ActiveIdAllowOverlap) + if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev)) + apply_toggle_layer = true; + if (!IsKeyDown(ImGuiKey_ModAlt)) + g.NavWindowingToggleLayer = false; + } + + // Move window + if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove)) + { + ImVec2 move_delta; + if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift) + move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_RawKeyboard, ImGuiNavReadMode_Down); + if (g.NavInputSource == ImGuiInputSource_Gamepad) + move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiNavReadMode_Down); + if (move_delta.x != 0.0f || move_delta.y != 0.0f) + { + const float NAV_MOVE_SPEED = 800.0f; + const float move_speed = ImFloor(NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y)); // FIXME: Doesn't handle variable framerate very well + ImGuiWindow *moving_window = g.NavWindowingTarget->RootWindowDockTree; + SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always); + MarkIniSettingsDirty(moving_window); + g.NavDisableMouseHover = true; + } + } + + // Apply final focus + if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)) + { + ImGuiViewport *previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL; + ClearActiveID(); + NavRestoreHighlightAfterMove(); + apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window); + ClosePopupsOverWindow(apply_focus_window, false); + FocusWindow(apply_focus_window); + if (apply_focus_window->NavLastIds[0] == 0) + NavInitWindow(apply_focus_window, false); + + // If the window has ONLY a menu layer (no main layer), select it directly + // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame, + // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since + // the target window as already been previewed once. + // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases, + // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask* + // won't be valid. + if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu)) + g.NavLayer = ImGuiNavLayer_Menu; + + // Request OS level focus + if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus) + g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport); + } + if (apply_focus_window) + g.NavWindowingTarget = NULL; + + // Apply menu/layer toggle + if (apply_toggle_layer && g.NavWindow) + { + ClearActiveID(); + + // Move to parent menu if necessary + ImGuiWindow *new_nav_window = g.NavWindow; + while (new_nav_window->ParentWindow && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) + new_nav_window = new_nav_window->ParentWindow; + if (new_nav_window != g.NavWindow) + { + ImGuiWindow *old_nav_window = g.NavWindow; + FocusWindow(new_nav_window); + new_nav_window->NavLastChildNavWindow = old_nav_window; + } + + // Toggle layer + const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main; + if (new_nav_layer != g.NavLayer) + { + // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?) + const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL); + if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id) + g.NavWindow->NavLastIds[new_nav_layer] = 0; + NavRestoreLayer(new_nav_layer); + NavRestoreHighlightAfterMove(); + } + } +} + +// Window has already passed the IsWindowNavFocusable() +static const char *GetFallbackWindowNameForWindowingList(ImGuiWindow *window) +{ + if (window->Flags & ImGuiWindowFlags_Popup) + return "(Popup)"; + if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0) + return "(Main menu bar)"; + if (window->DockNodeAsHost) + return "(Dock node)"; + return "(Untitled)"; +} + +// Overlay displayed when using CTRL+TAB. Called by EndFrame(). +void ImGui::NavUpdateWindowingOverlay() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.NavWindowingTarget != NULL); + + if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY) + return; + + if (g.NavWindowingListWindow == NULL) + g.NavWindowingListWindow = FindWindowByName("###NavWindowingList"); + const ImGuiViewport *viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport(); + SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); + SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); + Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings); + for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--) + { + ImGuiWindow *window = g.WindowsFocusOrder[n]; + IM_ASSERT(window != NULL); // Fix static analyzers + if (!IsWindowNavFocusable(window)) + continue; + const char *label = window->Name; + if (label == FindRenderedTextEnd(label)) + label = GetFallbackWindowNameForWindowingList(window); + Selectable(label, g.NavWindowingTarget == window); + } + End(); + PopStyleVar(); +} + +//----------------------------------------------------------------------------- +// [SECTION] DRAG AND DROP +//----------------------------------------------------------------------------- + +void ImGui::ClearDragDrop() +{ + ImGuiContext &g = *GImGui; + g.DragDropActive = false; + g.DragDropPayload.Clear(); + g.DragDropAcceptFlags = ImGuiDragDropFlags_None; + g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0; + g.DragDropAcceptIdCurrRectSurface = FLT_MAX; + g.DragDropAcceptFrameCount = -1; + + g.DragDropPayloadBufHeap.clear(); + memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); +} + +// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource() +// If the item has an identifier: +// - This assume/require the item to be activated (typically via ButtonBehavior). +// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button. +// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag. +// If the item has no identifier: +// - Currently always assume left mouse button. +bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button, + // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic). + ImGuiMouseButton mouse_button = ImGuiMouseButton_Left; + + bool source_drag_active = false; + ImGuiID source_id = 0; + ImGuiID source_parent_id = 0; + if (!(flags & ImGuiDragDropFlags_SourceExtern)) + { + source_id = g.LastItemData.ID; + if (source_id != 0) + { + // Common path: items with ID + if (g.ActiveId != source_id) + return false; + if (g.ActiveIdMouseButton != -1) + mouse_button = g.ActiveIdMouseButton; + if (g.IO.MouseDown[mouse_button] == false || window->SkipItems) + return false; + g.ActiveIdAllowOverlap = false; + } + else + { + // Uncommon path: items without ID + if (g.IO.MouseDown[mouse_button] == false || window->SkipItems) + return false; + if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window)) + return false; + + // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to: + // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag. + if (!(flags & ImGuiDragDropFlags_SourceAllowNullID)) + { + IM_ASSERT(0); + return false; + } + + // Magic fallback to handle items with no assigned ID, e.g. Text(), Image() + // We build a throwaway ID based on current ID stack + relative AABB of items in window. + // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled. + // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive. + // Rely on keeping other window->LastItemXXX fields intact. + source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect); + KeepAliveID(source_id); + bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id); + if (is_hovered && g.IO.MouseClicked[mouse_button]) + { + SetActiveID(source_id, window); + FocusWindow(window); + } + if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker. + g.ActiveIdAllowOverlap = is_hovered; + } + if (g.ActiveId != source_id) + return false; + source_parent_id = window->IDStack.back(); + source_drag_active = IsMouseDragging(mouse_button); + + // Disable navigation and key inputs while dragging + cancel existing request if any + SetActiveIdUsingNavAndKeys(); + } + else + { + window = NULL; + source_id = ImHashStr("#SourceExtern"); + source_drag_active = true; + } + + if (source_drag_active) + { + if (!g.DragDropActive) + { + IM_ASSERT(source_id != 0); + ClearDragDrop(); + ImGuiPayload &payload = g.DragDropPayload; + payload.SourceId = source_id; + payload.SourceParentId = source_parent_id; + g.DragDropActive = true; + g.DragDropSourceFlags = flags; + g.DragDropMouseButton = mouse_button; + if (payload.SourceId == g.ActiveId) + g.ActiveIdNoClearOnFocusLoss = true; + } + g.DragDropSourceFrameCount = g.FrameCount; + g.DragDropWithinSource = true; + + if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) + { + // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit) + // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents. + BeginTooltip(); + if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip)) + { + ImGuiWindow *tooltip_window = g.CurrentWindow; + tooltip_window->Hidden = tooltip_window->SkipItems = true; + tooltip_window->HiddenFramesCanSkipItems = 1; + } + } + + if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern)) + g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect; + + return true; + } + return false; +} + +void ImGui::EndDragDropSource() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.DragDropActive); + IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?"); + + if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) + EndTooltip(); + + // Discard the drag if have not called SetDragDropPayload() + if (g.DragDropPayload.DataFrameCount == -1) + ClearDragDrop(); + g.DragDropWithinSource = false; +} + +// Use 'cond' to choose to submit payload on drag start or every frame +bool ImGui::SetDragDropPayload(const char *type, const void *data, size_t data_size, ImGuiCond cond) +{ + ImGuiContext &g = *GImGui; + ImGuiPayload &payload = g.DragDropPayload; + if (cond == 0) + cond = ImGuiCond_Always; + + IM_ASSERT(type != NULL); + IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long"); + IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0)); + IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once); + IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource() + + if (cond == ImGuiCond_Always || payload.DataFrameCount == -1) + { + // Copy payload + ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType)); + g.DragDropPayloadBufHeap.resize(0); + if (data_size > sizeof(g.DragDropPayloadBufLocal)) + { + // Store in heap + g.DragDropPayloadBufHeap.resize((int)data_size); + payload.Data = g.DragDropPayloadBufHeap.Data; + memcpy(payload.Data, data, data_size); + } + else if (data_size > 0) + { + // Store locally + memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); + payload.Data = g.DragDropPayloadBufLocal; + memcpy(payload.Data, data, data_size); + } + else + { + payload.Data = NULL; + } + payload.DataSize = (int)data_size; + } + payload.DataFrameCount = g.FrameCount; + + // Return whether the payload has been accepted + return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1); +} + +bool ImGui::BeginDragDropTargetCustom(const ImRect &bb, ImGuiID id) +{ + ImGuiContext &g = *GImGui; + if (!g.DragDropActive) + return false; + + ImGuiWindow *window = g.CurrentWindow; + ImGuiWindow *hovered_window = g.HoveredWindowUnderMovingWindow; + if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree) + return false; + IM_ASSERT(id != 0); + if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId)) + return false; + if (window->SkipItems) + return false; + + IM_ASSERT(g.DragDropWithinTarget == false); + g.DragDropTargetRect = bb; + g.DragDropTargetId = id; + g.DragDropWithinTarget = true; + return true; +} + +// We don't use BeginDragDropTargetCustom() and duplicate its code because: +// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them. +// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can. +// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case) +bool ImGui::BeginDragDropTarget() +{ + ImGuiContext &g = *GImGui; + if (!g.DragDropActive) + return false; + + ImGuiWindow *window = g.CurrentWindow; + if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect)) + return false; + ImGuiWindow *hovered_window = g.HoveredWindowUnderMovingWindow; + if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems) + return false; + + const ImRect &display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect; + ImGuiID id = g.LastItemData.ID; + if (id == 0) + { + id = window->GetIDFromRectangle(display_rect); + KeepAliveID(id); + } + if (g.DragDropPayload.SourceId == id) + return false; + + IM_ASSERT(g.DragDropWithinTarget == false); + g.DragDropTargetRect = display_rect; + g.DragDropTargetId = id; + g.DragDropWithinTarget = true; + return true; +} + +bool ImGui::IsDragDropPayloadBeingAccepted() +{ + ImGuiContext &g = *GImGui; + return g.DragDropActive && g.DragDropAcceptIdPrev != 0; +} + +const ImGuiPayload *ImGui::AcceptDragDropPayload(const char *type, ImGuiDragDropFlags flags) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + ImGuiPayload &payload = g.DragDropPayload; + IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ? + IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ? + if (type != NULL && !payload.IsDataType(type)) + return NULL; + + // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints. + // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function! + const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId); + ImRect r = g.DragDropTargetRect; + float r_surface = r.GetWidth() * r.GetHeight(); + if (r_surface <= g.DragDropAcceptIdCurrRectSurface) + { + g.DragDropAcceptFlags = flags; + g.DragDropAcceptIdCurr = g.DragDropTargetId; + g.DragDropAcceptIdCurrRectSurface = r_surface; + } + + // Render default drop visuals + // FIXME-DRAGDROP: Settle on a proper default visuals for drop target. + payload.Preview = was_accepted_previously; + flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame) + if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview) + window->DrawList->AddRect(r.Min - ImVec2(3.5f, 3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f); + + g.DragDropAcceptFrameCount = g.FrameCount; + payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased() + if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery)) + return NULL; + + return &payload; +} + +const ImGuiPayload *ImGui::GetDragDropPayload() +{ + ImGuiContext &g = *GImGui; + return g.DragDropActive ? &g.DragDropPayload : NULL; +} + +// We don't really use/need this now, but added it for the sake of consistency and because we might need it later. +void ImGui::EndDragDropTarget() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.DragDropActive); + IM_ASSERT(g.DragDropWithinTarget); + g.DragDropWithinTarget = false; +} + +//----------------------------------------------------------------------------- +// [SECTION] LOGGING/CAPTURING +//----------------------------------------------------------------------------- +// All text output from the interface can be captured into tty/file/clipboard. +// By default, tree nodes are automatically opened during logging. +//----------------------------------------------------------------------------- + +// Pass text data straight to log (without being displayed) +static inline void LogTextV(ImGuiContext &g, const char *fmt, va_list args) +{ + if (g.LogFile) + { + g.LogBuffer.Buf.resize(0); + g.LogBuffer.appendfv(fmt, args); + ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile); + } + else + { + g.LogBuffer.appendfv(fmt, args); + } +} + +void ImGui::LogText(const char *fmt, ...) +{ + ImGuiContext &g = *GImGui; + if (!g.LogEnabled) + return; + + va_list args; + va_start(args, fmt); + LogTextV(g, fmt, args); + va_end(args); +} + +void ImGui::LogTextV(const char *fmt, va_list args) +{ + ImGuiContext &g = *GImGui; + if (!g.LogEnabled) + return; + + LogTextV(g, fmt, args); +} + +// Internal version that takes a position to decide on newline placement and pad items according to their depth. +// We split text into individual lines to add current tree level padding +// FIXME: This code is a little complicated perhaps, considering simplifying the whole system. +void ImGui::LogRenderedText(const ImVec2 *ref_pos, const char *text, const char *text_end) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + const char *prefix = g.LogNextPrefix; + const char *suffix = g.LogNextSuffix; + g.LogNextPrefix = g.LogNextSuffix = NULL; + + if (!text_end) + text_end = FindRenderedTextEnd(text, text_end); + + const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1); + if (ref_pos) + g.LogLinePosY = ref_pos->y; + if (log_new_line) + { + LogText(IM_NEWLINE); + g.LogLineFirstItem = true; + } + + if (prefix) + LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here. + + // Re-adjust padding if we have popped out of our starting depth + if (g.LogDepthRef > window->DC.TreeDepth) + g.LogDepthRef = window->DC.TreeDepth; + const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef); + + const char *text_remaining = text; + for (;;) + { + // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry. + // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured. + const char *line_start = text_remaining; + const char *line_end = ImStreolRange(line_start, text_end); + const bool is_last_line = (line_end == text_end); + if (line_start != line_end || !is_last_line) + { + const int line_length = (int)(line_end - line_start); + const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1; + LogText("%*s%.*s", indentation, "", line_length, line_start); + g.LogLineFirstItem = false; + if (*line_end == '\n') + { + LogText(IM_NEWLINE); + g.LogLineFirstItem = true; + } + } + if (is_last_line) + break; + text_remaining = line_end + 1; + } + + if (suffix) + LogRenderedText(ref_pos, suffix, suffix + strlen(suffix)); +} + +// Start logging/capturing text output +void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + IM_ASSERT(g.LogEnabled == false); + IM_ASSERT(g.LogFile == NULL); + IM_ASSERT(g.LogBuffer.empty()); + g.LogEnabled = true; + g.LogType = type; + g.LogNextPrefix = g.LogNextSuffix = NULL; + g.LogDepthRef = window->DC.TreeDepth; + g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); + g.LogLinePosY = FLT_MAX; + g.LogLineFirstItem = true; +} + +// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText) +void ImGui::LogSetNextTextDecoration(const char *prefix, const char *suffix) +{ + ImGuiContext &g = *GImGui; + g.LogNextPrefix = prefix; + g.LogNextSuffix = suffix; +} + +void ImGui::LogToTTY(int auto_open_depth) +{ + ImGuiContext &g = *GImGui; + if (g.LogEnabled) + return; + IM_UNUSED(auto_open_depth); +#ifndef IMGUI_DISABLE_TTY_FUNCTIONS + LogBegin(ImGuiLogType_TTY, auto_open_depth); + g.LogFile = stdout; +#endif +} + +// Start logging/capturing text output to given file +void ImGui::LogToFile(int auto_open_depth, const char *filename) +{ + ImGuiContext &g = *GImGui; + if (g.LogEnabled) + return; + + // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still + // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE. + // By opening the file in binary mode "ab" we have consistent output everywhere. + if (!filename) + filename = g.IO.LogFilename; + if (!filename || !filename[0]) + return; + ImFileHandle f = ImFileOpen(filename, "ab"); + if (!f) + { + IM_ASSERT(0); + return; + } + + LogBegin(ImGuiLogType_File, auto_open_depth); + g.LogFile = f; +} + +// Start logging/capturing text output to clipboard +void ImGui::LogToClipboard(int auto_open_depth) +{ + ImGuiContext &g = *GImGui; + if (g.LogEnabled) + return; + LogBegin(ImGuiLogType_Clipboard, auto_open_depth); +} + +void ImGui::LogToBuffer(int auto_open_depth) +{ + ImGuiContext &g = *GImGui; + if (g.LogEnabled) + return; + LogBegin(ImGuiLogType_Buffer, auto_open_depth); +} + +void ImGui::LogFinish() +{ + ImGuiContext &g = *GImGui; + if (!g.LogEnabled) + return; + + LogText(IM_NEWLINE); + switch (g.LogType) + { + case ImGuiLogType_TTY: +#ifndef IMGUI_DISABLE_TTY_FUNCTIONS + fflush(g.LogFile); +#endif + break; + case ImGuiLogType_File: + ImFileClose(g.LogFile); + break; + case ImGuiLogType_Buffer: + break; + case ImGuiLogType_Clipboard: + if (!g.LogBuffer.empty()) + SetClipboardText(g.LogBuffer.begin()); + break; + case ImGuiLogType_None: + IM_ASSERT(0); + break; + } + + g.LogEnabled = false; + g.LogType = ImGuiLogType_None; + g.LogFile = NULL; + g.LogBuffer.clear(); +} + +// Helper to display logging buttons +// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!) +void ImGui::LogButtons() +{ + ImGuiContext &g = *GImGui; + + PushID("LogButtons"); +#ifndef IMGUI_DISABLE_TTY_FUNCTIONS + const bool log_to_tty = Button("Log To TTY"); + SameLine(); +#else + const bool log_to_tty = false; +#endif + const bool log_to_file = Button("Log To File"); + SameLine(); + const bool log_to_clipboard = Button("Log To Clipboard"); + SameLine(); + PushAllowKeyboardFocus(false); + SetNextItemWidth(80.0f); + SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL); + PopAllowKeyboardFocus(); + PopID(); + + // Start logging at the end of the function so that the buttons don't appear in the log + if (log_to_tty) + LogToTTY(); + if (log_to_file) + LogToFile(); + if (log_to_clipboard) + LogToClipboard(); +} + +//----------------------------------------------------------------------------- +// [SECTION] SETTINGS +//----------------------------------------------------------------------------- +// - UpdateSettings() [Internal] +// - MarkIniSettingsDirty() [Internal] +// - CreateNewWindowSettings() [Internal] +// - FindWindowSettings() [Internal] +// - FindOrCreateWindowSettings() [Internal] +// - FindSettingsHandler() [Internal] +// - ClearIniSettings() [Internal] +// - LoadIniSettingsFromDisk() +// - LoadIniSettingsFromMemory() +// - SaveIniSettingsToDisk() +// - SaveIniSettingsToMemory() +// - WindowSettingsHandler_***() [Internal] +//----------------------------------------------------------------------------- + +// Called by NewFrame() +void ImGui::UpdateSettings() +{ + // Load settings on first frame (if not explicitly loaded manually before) + ImGuiContext &g = *GImGui; + if (!g.SettingsLoaded) + { + IM_ASSERT(g.SettingsWindows.empty()); + if (g.IO.IniFilename) + LoadIniSettingsFromDisk(g.IO.IniFilename); + g.SettingsLoaded = true; + } + + // Save settings (with a delay after the last modification, so we don't spam disk too much) + if (g.SettingsDirtyTimer > 0.0f) + { + g.SettingsDirtyTimer -= g.IO.DeltaTime; + if (g.SettingsDirtyTimer <= 0.0f) + { + if (g.IO.IniFilename != NULL) + SaveIniSettingsToDisk(g.IO.IniFilename); + else + g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. + g.SettingsDirtyTimer = 0.0f; + } + } +} + +void ImGui::MarkIniSettingsDirty() +{ + ImGuiContext &g = *GImGui; + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +void ImGui::MarkIniSettingsDirty(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +ImGuiWindowSettings *ImGui::CreateNewWindowSettings(const char *name) +{ + ImGuiContext &g = *GImGui; + +#if !IMGUI_DEBUG_INI_SETTINGS + // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() + // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier. + if (const char *p = strstr(name, "###")) + name = p; +#endif + const size_t name_len = strlen(name); + + // Allocate chunk + const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1; + ImGuiWindowSettings *settings = g.SettingsWindows.alloc_chunk(chunk_size); + IM_PLACEMENT_NEW(settings) + ImGuiWindowSettings(); + settings->ID = ImHashStr(name, name_len); + memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator + + return settings; +} + +ImGuiWindowSettings *ImGui::FindWindowSettings(ImGuiID id) +{ + ImGuiContext &g = *GImGui; + for (ImGuiWindowSettings *settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->ID == id) + return settings; + return NULL; +} + +ImGuiWindowSettings *ImGui::FindOrCreateWindowSettings(const char *name) +{ + if (ImGuiWindowSettings *settings = FindWindowSettings(ImHashStr(name))) + return settings; + return CreateNewWindowSettings(name); +} + +void ImGui::AddSettingsHandler(const ImGuiSettingsHandler *handler) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL); + g.SettingsHandlers.push_back(*handler); +} + +void ImGui::RemoveSettingsHandler(const char *type_name) +{ + ImGuiContext &g = *GImGui; + if (ImGuiSettingsHandler *handler = FindSettingsHandler(type_name)) + g.SettingsHandlers.erase(handler); +} + +ImGuiSettingsHandler *ImGui::FindSettingsHandler(const char *type_name) +{ + ImGuiContext &g = *GImGui; + const ImGuiID type_hash = ImHashStr(type_name); + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].TypeHash == type_hash) + return &g.SettingsHandlers[handler_n]; + return NULL; +} + +void ImGui::ClearIniSettings() +{ + ImGuiContext &g = *GImGui; + g.SettingsIniData.clear(); + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ClearAllFn) + g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]); +} + +void ImGui::LoadIniSettingsFromDisk(const char *ini_filename) +{ + size_t file_data_size = 0; + char *file_data = (char *)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); + if (!file_data) + return; + if (file_data_size > 0) + LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); + IM_FREE(file_data); +} + +// Zero-tolerance, no error reporting, cheap .ini parsing +void ImGui::LoadIniSettingsFromMemory(const char *ini_data, size_t ini_size) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.Initialized); + // IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()"); + // IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0); + + // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). + // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. + if (ini_size == 0) + ini_size = strlen(ini_data); + g.SettingsIniData.Buf.resize((int)ini_size + 1); + char *const buf = g.SettingsIniData.Buf.Data; + char *const buf_end = buf + ini_size; + memcpy(buf, ini_data, ini_size); + buf_end[0] = 0; + + // Call pre-read handlers + // Some types will clear their data (e.g. dock information) some types will allow merge/override (window) + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ReadInitFn) + g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]); + + void *entry_data = NULL; + ImGuiSettingsHandler *entry_handler = NULL; + + char *line_end = NULL; + for (char *line = buf; line < buf_end; line = line_end + 1) + { + // Skip new lines markers, then find end of the line + while (*line == '\n' || *line == '\r') + line++; + line_end = line; + while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') + line_end++; + line_end[0] = 0; + if (line[0] == ';') + continue; + if (line[0] == '[' && line_end > line && line_end[-1] == ']') + { + // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. + line_end[-1] = 0; + const char *name_end = line_end - 1; + const char *type_start = line + 1; + char *type_end = (char *)(void *)ImStrchrRange(type_start, name_end, ']'); + const char *name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; + if (!type_end || !name_start) + continue; + *type_end = 0; // Overwrite first ']' + name_start++; // Skip second '[' + entry_handler = FindSettingsHandler(type_start); + entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL; + } + else if (entry_handler != NULL && entry_data != NULL) + { + // Let type handler parse the line + entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); + } + } + g.SettingsLoaded = true; + + // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary) + memcpy(buf, ini_data, ini_size); + + // Call post-read handlers + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ApplyAllFn) + g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]); +} + +void ImGui::SaveIniSettingsToDisk(const char *ini_filename) +{ + ImGuiContext &g = *GImGui; + g.SettingsDirtyTimer = 0.0f; + if (!ini_filename) + return; + + size_t ini_data_size = 0; + const char *ini_data = SaveIniSettingsToMemory(&ini_data_size); + ImFileHandle f = ImFileOpen(ini_filename, "wt"); + if (!f) + return; + ImFileWrite(ini_data, sizeof(char), ini_data_size, f); + ImFileClose(f); +} + +// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer +const char *ImGui::SaveIniSettingsToMemory(size_t *out_size) +{ + ImGuiContext &g = *GImGui; + g.SettingsDirtyTimer = 0.0f; + g.SettingsIniData.Buf.resize(0); + g.SettingsIniData.Buf.push_back(0); + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + { + ImGuiSettingsHandler *handler = &g.SettingsHandlers[handler_n]; + handler->WriteAllFn(&g, handler, &g.SettingsIniData); + } + if (out_size) + *out_size = (size_t)g.SettingsIniData.size(); + return g.SettingsIniData.c_str(); +} + +static void WindowSettingsHandler_ClearAll(ImGuiContext *ctx, ImGuiSettingsHandler *) +{ + ImGuiContext &g = *ctx; + for (int i = 0; i != g.Windows.Size; i++) + g.Windows[i]->SettingsOffset = -1; + g.SettingsWindows.clear(); +} + +static void *WindowSettingsHandler_ReadOpen(ImGuiContext *, ImGuiSettingsHandler *, const char *name) +{ + ImGuiWindowSettings *settings = ImGui::FindOrCreateWindowSettings(name); + ImGuiID id = settings->ID; + *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry + settings->ID = id; + settings->WantApply = true; + return (void *)settings; +} + +static void WindowSettingsHandler_ReadLine(ImGuiContext *, ImGuiSettingsHandler *, void *entry, const char *line) +{ + ImGuiWindowSettings *settings = (ImGuiWindowSettings *)entry; + int x, y; + int i; + ImU32 u1; + if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) + { + settings->Pos = ImVec2ih((short)x, (short)y); + } + else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) + { + settings->Size = ImVec2ih((short)x, (short)y); + } + else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) + { + settings->ViewportId = u1; + } + else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2) + { + settings->ViewportPos = ImVec2ih((short)x, (short)y); + } + else if (sscanf(line, "Collapsed=%d", &i) == 1) + { + settings->Collapsed = (i != 0); + } + else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) + { + settings->DockId = u1; + settings->DockOrder = (short)i; + } + else if (sscanf(line, "DockId=0x%X", &u1) == 1) + { + settings->DockId = u1; + settings->DockOrder = -1; + } + else if (sscanf(line, "ClassId=0x%X", &u1) == 1) + { + settings->ClassId = u1; + } +} + +// Apply to existing windows (if any) +static void WindowSettingsHandler_ApplyAll(ImGuiContext *ctx, ImGuiSettingsHandler *) +{ + ImGuiContext &g = *ctx; + for (ImGuiWindowSettings *settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->WantApply) + { + if (ImGuiWindow *window = ImGui::FindWindowByID(settings->ID)) + ApplyWindowSettings(window, settings); + settings->WantApply = false; + } +} + +static void WindowSettingsHandler_WriteAll(ImGuiContext *ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf) +{ + // Gather data from windows that were active during this session + // (if a window wasn't opened in this session we preserve its settings) + ImGuiContext &g = *ctx; + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow *window = g.Windows[i]; + if (window->Flags & ImGuiWindowFlags_NoSavedSettings) + continue; + + ImGuiWindowSettings *settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID); + if (!settings) + { + settings = ImGui::CreateNewWindowSettings(window->Name); + window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); + } + IM_ASSERT(settings->ID == window->ID); + settings->Pos = ImVec2ih(window->Pos - window->ViewportPos); + settings->Size = ImVec2ih(window->SizeFull); + settings->ViewportId = window->ViewportId; + settings->ViewportPos = ImVec2ih(window->ViewportPos); + IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId); + settings->DockId = window->DockId; + settings->ClassId = window->WindowClass.ClassId; + settings->DockOrder = window->DockOrder; + settings->Collapsed = window->Collapsed; + } + + // Write to text buffer + buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve + for (ImGuiWindowSettings *settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + { + const char *settings_name = settings->GetName(); + buf->appendf("[%s][%s]\n", handler->TypeName, settings_name); + if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID) + { + buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y); + buf->appendf("ViewportId=0x%08X\n", settings->ViewportId); + } + if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID) + buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y); + if (settings->Size.x != 0 || settings->Size.y != 0) + buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y); + buf->appendf("Collapsed=%d\n", settings->Collapsed); + if (settings->DockId != 0) + { + // buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier. + if (settings->DockOrder == -1) + buf->appendf("DockId=0x%08X\n", settings->DockId); + else + buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder); + if (settings->ClassId != 0) + buf->appendf("ClassId=0x%08X\n", settings->ClassId); + } + buf->append("\n"); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] VIEWPORTS, PLATFORM WINDOWS +//----------------------------------------------------------------------------- +// - GetMainViewport() +// - FindViewportByID() +// - FindViewportByPlatformHandle() +// - SetCurrentViewport() [Internal] +// - SetWindowViewport() [Internal] +// - GetWindowAlwaysWantOwnViewport() [Internal] +// - UpdateTryMergeWindowIntoHostViewport() [Internal] +// - UpdateTryMergeWindowIntoHostViewports() [Internal] +// - TranslateWindowsInViewport() [Internal] +// - ScaleWindowsInViewport() [Internal] +// - FindHoveredViewportFromPlatformWindowStack() [Internal] +// - UpdateViewportsNewFrame() [Internal] +// - UpdateViewportsEndFrame() [Internal] +// - AddUpdateViewport() [Internal] +// - WindowSelectViewport() [Internal] +// - WindowSyncOwnedViewport() [Internal] +// - UpdatePlatformWindows() +// - RenderPlatformWindowsDefault() +// - FindPlatformMonitorForPos() [Internal] +// - FindPlatformMonitorForRect() [Internal] +// - UpdateViewportPlatformMonitor() [Internal] +// - DestroyPlatformWindow() [Internal] +// - DestroyPlatformWindows() +//----------------------------------------------------------------------------- + +ImGuiViewport *ImGui::GetMainViewport() +{ + ImGuiContext &g = *GImGui; + return g.Viewports[0]; +} + +// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236) +ImGuiViewport *ImGui::FindViewportByID(ImGuiID id) +{ + ImGuiContext &g = *GImGui; + for (int n = 0; n < g.Viewports.Size; n++) + if (g.Viewports[n]->ID == id) + return g.Viewports[n]; + return NULL; +} + +ImGuiViewport *ImGui::FindViewportByPlatformHandle(void *platform_handle) +{ + ImGuiContext &g = *GImGui; + for (int i = 0; i != g.Viewports.Size; i++) + if (g.Viewports[i]->PlatformHandle == platform_handle) + return g.Viewports[i]; + return NULL; +} + +void ImGui::SetCurrentViewport(ImGuiWindow *current_window, ImGuiViewportP *viewport) +{ + ImGuiContext &g = *GImGui; + (void)current_window; + + if (viewport) + viewport->LastFrameActive = g.FrameCount; + if (g.CurrentViewport == viewport) + return; + g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f; + g.CurrentViewport = viewport; + // IMGUI_DEBUG_LOG_VIEWPORT("SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0); + + // Notify platform layer of viewport changes + // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI + if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport) + g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport); +} + +void ImGui::SetWindowViewport(ImGuiWindow *window, ImGuiViewportP *viewport) +{ + // Abandon viewport + if (window->ViewportOwned && window->Viewport->Window == window) + window->Viewport->Size = ImVec2(0.0f, 0.0f); + + window->Viewport = viewport; + window->ViewportId = viewport->ID; + window->ViewportOwned = (viewport->Window == window); +} + +static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow *window) +{ + // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own. + ImGuiContext &g = *GImGui; + if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge)) + if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) + if (!window->DockIsActive) + if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0) + if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0) + return true; + return false; +} + +static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow *window, ImGuiViewportP *viewport) +{ + ImGuiContext &g = *GImGui; + if (window->Viewport == viewport) + return false; + if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0) + return false; + if ((viewport->Flags & ImGuiViewportFlags_Minimized) != 0) + return false; + if (!viewport->GetMainRect().Contains(window->Rect())) + return false; + if (GetWindowAlwaysWantOwnViewport(window)) + return false; + + // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could.. + for (int n = 0; n < g.Windows.Size; n++) + { + ImGuiWindow *window_behind = g.Windows[n]; + if (window_behind == window) + break; + if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow)) + if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect())) + return false; + } + + // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child) + ImGuiViewportP *old_viewport = window->Viewport; + if (window->ViewportOwned) + for (int n = 0; n < g.Windows.Size; n++) + if (g.Windows[n]->Viewport == old_viewport) + SetWindowViewport(g.Windows[n], viewport); + SetWindowViewport(window, viewport); + BringWindowToDisplayFront(window); + + return true; +} + +// FIXME: handle 0 to N host viewports +static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]); +} + +// Translate Dear ImGui windows when a Host Viewport has been moved +// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) +void ImGui::TranslateWindowsInViewport(ImGuiViewportP *viewport, const ImVec2 &old_pos, const ImVec2 &new_pos) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows)); + + // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently + // translate imgui windows from OS-window-local to absolute coordinates or vice-versa. + // 2) If it's not going to fit into the new size, keep it at same absolute position. + // One problem with this is that most Win32 applications doesn't update their render while dragging, + // and so the window will appear to teleport when releasing the mouse. + const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable); + ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size); + ImVec2 delta_pos = new_pos - old_pos; + for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT + if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect()))) + TranslateWindow(g.Windows[window_n], delta_pos); +} + +// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) +void ImGui::ScaleWindowsInViewport(ImGuiViewportP *viewport, float scale) +{ + ImGuiContext &g = *GImGui; + if (viewport->Window) + { + ScaleWindow(viewport->Window, scale); + } + else + { + for (int i = 0; i != g.Windows.Size; i++) + if (g.Windows[i]->Viewport == viewport) + ScaleWindow(g.Windows[i], scale); + } +} + +// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves. +// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. +// B) It requires Platform_GetWindowFocus to be implemented by backend. +ImGuiViewportP *ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2 &mouse_platform_pos) +{ + ImGuiContext &g = *GImGui; + ImGuiViewportP *best_candidate = NULL; + for (int n = 0; n < g.Viewports.Size; n++) + { + ImGuiViewportP *viewport = g.Viewports[n]; + if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetMainRect().Contains(mouse_platform_pos)) + if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount) + best_candidate = viewport; + } + return best_candidate; +} + +// Update viewports and monitor infos +// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info. +static void ImGui::UpdateViewportsNewFrame() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size); + + // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport) + const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0; + if (viewports_enabled) + { + for (int n = 0; n < g.Viewports.Size; n++) + { + ImGuiViewportP *viewport = g.Viewports[n]; + const bool platform_funcs_available = viewport->PlatformWindowCreated; + if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available) + { + bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport); + if (minimized) + viewport->Flags |= ImGuiViewportFlags_Minimized; + else + viewport->Flags &= ~ImGuiViewportFlags_Minimized; + } + } + } + + // Create/update main viewport with current platform position. + // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent. + ImGuiViewportP *main_viewport = g.Viewports[0]; + IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID); + IM_ASSERT(main_viewport->Window == NULL); + ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f); + ImVec2 main_viewport_size = g.IO.DisplaySize; + if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_Minimized)) + { + main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path) + main_viewport_size = main_viewport->Size; + } + AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows); + + g.CurrentDpiScale = 0.0f; + g.CurrentViewport = NULL; + g.MouseViewport = NULL; + for (int n = 0; n < g.Viewports.Size; n++) + { + ImGuiViewportP *viewport = g.Viewports[n]; + viewport->Idx = n; + + // Erase unused viewports + if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2) + { + DestroyViewport(viewport); + n--; + continue; + } + + const bool platform_funcs_available = viewport->PlatformWindowCreated; + if (viewports_enabled) + { + // Update Position and Size (from Platform Window to ImGui) if requested. + // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities. + if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available) + { + // Viewport->WorkPos and WorkSize will be updated below + if (viewport->PlatformRequestMove) + viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport); + if (viewport->PlatformRequestResize) + viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport); + } + } + + // Update/copy monitor info + UpdateViewportPlatformMonitor(viewport); + + // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again. + viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin; + viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax; + viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f); + viewport->UpdateWorkRect(); + + // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back. + viewport->Alpha = 1.0f; + + // Translate Dear ImGui windows when a Host Viewport has been moved + // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) + const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos; + if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f)) + TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos); + + // Update DPI scale + float new_dpi_scale; + if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available) + new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport); + else if (viewport->PlatformMonitor != -1) + new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; + else + new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f; + if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale) + { + float scale_factor = new_dpi_scale / viewport->DpiScale; + if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) + ScaleWindowsInViewport(viewport, scale_factor); + // if (viewport == GetMainViewport()) + // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor); + + // Scale our window moving pivot so that the window will rescale roughly around the mouse position. + // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border. + // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.) + // if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport) + // g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor); + } + viewport->DpiScale = new_dpi_scale; + } + + // Update fallback monitor + if (g.PlatformIO.Monitors.Size == 0) + { + ImGuiPlatformMonitor *monitor = &g.FallbackMonitor; + monitor->MainPos = main_viewport->Pos; + monitor->MainSize = main_viewport->Size; + monitor->WorkPos = main_viewport->WorkPos; + monitor->WorkSize = main_viewport->WorkSize; + monitor->DpiScale = main_viewport->DpiScale; + } + + if (!viewports_enabled) + { + g.MouseViewport = main_viewport; + return; + } + + // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport. + // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set. + ImGuiViewportP *viewport_hovered = NULL; + if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) + { + viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP *)FindViewportByID(g.IO.MouseHoveredViewport) : NULL; + if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) + viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback. + } + else + { + // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search: + // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. + // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order. + // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO) + viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); + } + if (viewport_hovered != NULL) + g.MouseLastHoveredViewport = viewport_hovered; + else if (g.MouseLastHoveredViewport == NULL) + g.MouseLastHoveredViewport = g.Viewports[0]; + + // Update mouse reference viewport + // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode) + // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details) + if (g.MovingWindow && g.MovingWindow->Viewport) + g.MouseViewport = g.MovingWindow->Viewport; + else + g.MouseViewport = g.MouseLastHoveredViewport; + + // When dragging something, always refer to the last hovered viewport. + // - when releasing a moving window we will revert to aiming behind (at viewport_hovered) + // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info) + // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release. + // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that. + const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive; + if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL) + viewport_hovered = g.MouseLastHoveredViewport; + if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown()) + if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) + g.MouseViewport = viewport_hovered; + + IM_ASSERT(g.MouseViewport != NULL); +} + +// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) +static void ImGui::UpdateViewportsEndFrame() +{ + ImGuiContext &g = *GImGui; + g.PlatformIO.Viewports.resize(0); + for (int i = 0; i < g.Viewports.Size; i++) + { + ImGuiViewportP *viewport = g.Viewports[i]; + viewport->LastPos = viewport->Pos; + if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f) + if (i > 0) // Always include main viewport in the list + continue; + if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)) + continue; + if (i > 0) + IM_ASSERT(viewport->Window != NULL); + g.PlatformIO.Viewports.push_back(viewport); + } + g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called +} + +// FIXME: We should ideally refactor the system to call this every frame (we currently don't) +ImGuiViewportP *ImGui::AddUpdateViewport(ImGuiWindow *window, ImGuiID id, const ImVec2 &pos, const ImVec2 &size, ImGuiViewportFlags flags) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(id != 0); + + flags |= ImGuiViewportFlags_IsPlatformWindow; + if (window != NULL) + { + if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window) + flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing; + if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) + flags |= ImGuiViewportFlags_NoInputs; + if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing) + flags |= ImGuiViewportFlags_NoFocusOnAppearing; + } + + ImGuiViewportP *viewport = (ImGuiViewportP *)FindViewportByID(id); + if (viewport) + { + // Always update for main viewport as we are already pulling correct platform pos/size (see #4900) + if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID) + viewport->Pos = pos; + if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID) + viewport->Size = size; + viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags + } + else + { + // New viewport + viewport = IM_NEW(ImGuiViewportP)(); + viewport->ID = id; + viewport->Idx = g.Viewports.Size; + viewport->Pos = viewport->LastPos = pos; + viewport->Size = size; + viewport->Flags = flags; + UpdateViewportPlatformMonitor(viewport); + g.Viewports.push_back(viewport); + IMGUI_DEBUG_LOG_VIEWPORT("Add Viewport %08X (%s)\n", id, window->Name); + + // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport. + // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame + g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x); + g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y); + g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x); + g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y); + + // Store initial DpiScale before the OS platform window creation, based on expected monitor data. + // This is so we can select an appropriate font size on the first frame of our window lifetime + if (viewport->PlatformMonitor != -1) + viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; + } + + viewport->Window = window; + viewport->LastFrameActive = g.FrameCount; + viewport->UpdateWorkRect(); + IM_ASSERT(window == NULL || viewport->ID == window->ID); + + if (window != NULL) + window->ViewportOwned = true; + + return viewport; +} + +static void ImGui::DestroyViewport(ImGuiViewportP *viewport) +{ + // Clear references to this viewport in windows (window->ViewportId becomes the master data) + ImGuiContext &g = *GImGui; + for (int window_n = 0; window_n < g.Windows.Size; window_n++) + { + ImGuiWindow *window = g.Windows[window_n]; + if (window->Viewport != viewport) + continue; + window->Viewport = NULL; + window->ViewportOwned = false; + } + if (viewport == g.MouseLastHoveredViewport) + g.MouseLastHoveredViewport = NULL; + + // Destroy + IMGUI_DEBUG_LOG_VIEWPORT("Delete Viewport %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); + DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here. + IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false); + IM_ASSERT(g.Viewports[viewport->Idx] == viewport); + g.Viewports.erase(g.Viewports.Data + viewport->Idx); + IM_DELETE(viewport); +} + +// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. +static void ImGui::WindowSelectViewport(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + ImGuiWindowFlags flags = window->Flags; + window->ViewportAllowPlatformMonitorExtend = -1; + + // Restore main viewport if multi-viewport is not supported by the backend + ImGuiViewportP *main_viewport = (ImGuiViewportP *)(void *)GetMainViewport(); + if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) + { + SetWindowViewport(window, main_viewport); + return; + } + window->ViewportOwned = false; + + // Appearing popups reset their viewport so they can inherit again + if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing) + { + window->Viewport = NULL; + window->ViewportId = 0; + } + + if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0) + { + // By default inherit from parent window + if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive)) + window->Viewport = window->ParentWindow->Viewport; + + // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file + if (window->Viewport == NULL && window->ViewportId != 0) + { + window->Viewport = (ImGuiViewportP *)FindViewportByID(window->ViewportId); + if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX) + window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None); + } + } + + bool lock_viewport = false; + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) + { + // Code explicitly request a viewport + window->Viewport = (ImGuiViewportP *)FindViewportByID(g.NextWindowData.ViewportId); + window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet. + lock_viewport = true; + } + else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu)) + { + // Always inherit viewport from parent window + if (window->DockNode && window->DockNode->HostWindow) + IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport); + window->Viewport = window->ParentWindow->Viewport; + } + else if (window->DockNode && window->DockNode->HostWindow) + { + // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame + window->Viewport = window->DockNode->HostWindow->Viewport; + } + else if (flags & ImGuiWindowFlags_Tooltip) + { + window->Viewport = g.MouseViewport; + } + else if (GetWindowAlwaysWantOwnViewport(window)) + { + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); + } + else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid()) + { + if (window->Viewport != NULL && window->Viewport->Window == window) + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); + } + else + { + // Merge into host viewport? + // We cannot test window->ViewportOwned as it set lower in the function. + // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212) + bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap)); + if (try_to_merge_into_host_viewport) + UpdateTryMergeWindowIntoHostViewports(window); + } + + // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport + if (window->Viewport == NULL) + if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport)) + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); + + // Mark window as allowed to protrude outside of its viewport and into the current monitor + if (!lock_viewport) + { + if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) + { + // We need to take account of the possibility that mouse may become invalid. + // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds. + ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos; + bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow); + bool mouse_valid = IsMousePosValid(&mouse_ref); + if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid)) + window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos()); + else + window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; + } + else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL) + { + // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code. + const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true; + if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible) + { + // Steal/transfer ownership + IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name); + window->Viewport->Window = window; + window->Viewport->ID = window->ID; + window->Viewport->LastNameHash = 0; + } + else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge? + { + // New viewport + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); + } + } + else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0) + { + // Regular (non-child, non-popup) windows by default are also allowed to protrude + // Child windows are kept contained within their parent. + window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; + } + } + + // Update flags + window->ViewportOwned = (window == window->Viewport->Window); + window->ViewportId = window->Viewport->ID; + + // If the OS window has a title bar, hide our imgui title bar + // if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration)) + // window->Flags |= ImGuiWindowFlags_NoTitleBar; +} + +void ImGui::WindowSyncOwnedViewport(ImGuiWindow *window, ImGuiWindow *parent_window_in_stack) +{ + ImGuiContext &g = *GImGui; + + bool viewport_rect_changed = false; + + // Synchronize window --> viewport in most situations + // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM + if (window->Viewport->PlatformRequestMove) + { + window->Pos = window->Viewport->Pos; + MarkIniSettingsDirty(window); + } + else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0) + { + viewport_rect_changed = true; + window->Viewport->Pos = window->Pos; + } + + if (window->Viewport->PlatformRequestResize) + { + window->Size = window->SizeFull = window->Viewport->Size; + MarkIniSettingsDirty(window); + } + else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0) + { + viewport_rect_changed = true; + window->Viewport->Size = window->Size; + } + window->Viewport->UpdateWorkRect(); + + // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame() + // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect. + if (viewport_rect_changed) + UpdateViewportPlatformMonitor(window->Viewport); + + // Update common viewport flags + const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear; + ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear; + ImGuiWindowFlags window_flags = window->Flags; + const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0; + const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0; + if (window_flags & ImGuiWindowFlags_Tooltip) + viewport_flags |= ImGuiViewportFlags_TopMost; + if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal) + viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon; + if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window) + viewport_flags |= ImGuiViewportFlags_NoDecoration; + + // Not correct to set modal as topmost because: + // - Because other popups can be stacked above a modal (e.g. combo box in a modal) + // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost" + // if (flags & ImGuiWindowFlags_Modal) + // viewport_flags |= ImGuiViewportFlags_TopMost; + + // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them + // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration). + // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app, + // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere. + if (is_short_lived_floating_window && !is_modal) + viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick; + + // We can overwrite viewport flags using ImGuiWindowClass (advanced users) + if (window->WindowClass.ViewportFlagsOverrideSet) + viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet; + if (window->WindowClass.ViewportFlagsOverrideClear) + viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear; + + // We can also tell the backend that clearing the platform window won't be necessary, + // as our window background is filling the viewport and we have disabled BgAlpha. + // FIXME: Work on support for per-viewport transparency (#2766) + if (!(window_flags & ImGuiWindowFlags_NoBackground)) + viewport_flags |= ImGuiViewportFlags_NoRendererClear; + + window->Viewport->Flags = viewport_flags; + + // Update parent viewport ID + // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport()) + if (window->WindowClass.ParentViewportId != (ImGuiID)-1) + window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId; + else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive)) + window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID; + else + window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID; +} + +// Called by user at the end of the main loop, after EndFrame() +// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api. +void ImGui::UpdatePlatformWindows() +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?"); + IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount); + g.FrameCountPlatformEnded = g.FrameCount; + if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) + return; + + // Create/resize/destroy platform windows to match each active viewport. + // Skip the main viewport (index 0), which is always fully handled by the application! + for (int i = 1; i < g.Viewports.Size; i++) + { + ImGuiViewportP *viewport = g.Viewports[i]; + + // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window + // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame) + bool destroy_platform_window = false; + destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1); + destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)); + if (destroy_platform_window) + { + DestroyPlatformWindow(viewport); + continue; + } + + // New windows that appears directly in a new viewport won't always have a size on their first frame + if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0) + continue; + + // Create window + bool is_new_platform_window = (viewport->PlatformWindowCreated == false); + if (is_new_platform_window) + { + IMGUI_DEBUG_LOG_VIEWPORT("Create Platform Window %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); + g.PlatformIO.Platform_CreateWindow(viewport); + if (g.PlatformIO.Renderer_CreateWindow != NULL) + g.PlatformIO.Renderer_CreateWindow(viewport); + viewport->LastNameHash = 0; + viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?) + viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it. + viewport->PlatformWindowCreated = true; + } + + // Apply Position and Size (from ImGui to Platform/Renderer backends) + if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove) + g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos); + if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize) + g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size); + if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize) + g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size); + viewport->LastPlatformPos = viewport->Pos; + viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size; + + // Update title bar (if it changed) + if (ImGuiWindow *window_for_title = GetWindowForTitleDisplay(viewport->Window)) + { + const char *title_begin = window_for_title->Name; + char *title_end = (char *)(intptr_t)FindRenderedTextEnd(title_begin); + const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin); + if (viewport->LastNameHash != title_hash) + { + char title_end_backup_c = *title_end; + *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain. + g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin); + *title_end = title_end_backup_c; + viewport->LastNameHash = title_hash; + } + } + + // Update alpha (if it changed) + if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha) + g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha); + viewport->LastAlpha = viewport->Alpha; + + // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed. + if (g.PlatformIO.Platform_UpdateWindow) + g.PlatformIO.Platform_UpdateWindow(viewport); + + if (is_new_platform_window) + { + // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late) + if (g.FrameCount < 3) + viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing; + + // Show window + g.PlatformIO.Platform_ShowWindow(viewport); + + // Even without focus, we assume the window becomes front-most. + // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available. + if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount) + viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount; + } + + // Clear request flags + viewport->ClearRequestFlags(); + } + + // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport. + // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored. + // FIXME-VIEWPORT: We should use this information to also set dear imgui-side focus, allowing us to handle os-level alt+tab. + if (g.PlatformIO.Platform_GetWindowFocus != NULL) + { + ImGuiViewportP *focused_viewport = NULL; + for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++) + { + ImGuiViewportP *viewport = g.Viewports[n]; + if (viewport->PlatformWindowCreated) + if (g.PlatformIO.Platform_GetWindowFocus(viewport)) + focused_viewport = viewport; + } + + // Store a tag so we can infer z-order easily from all our windows + // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag + // will keep the front most stamp instead of losing it back to their parent viewport. + if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID) + { + if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount) + focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount; + g.PlatformLastFocusedViewportId = focused_viewport->ID; + } + } +} + +// This is a default/basic function for performing the rendering/swap of multiple Platform Windows. +// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves. +// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself: +// +// ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); +// for (int i = 1; i < platform_io.Viewports.Size; i++) +// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0) +// MyRenderFunction(platform_io.Viewports[i], my_args); +// for (int i = 1; i < platform_io.Viewports.Size; i++) +// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0) +// MySwapBufferFunction(platform_io.Viewports[i], my_args); +// +void ImGui::RenderPlatformWindowsDefault(void *platform_render_arg, void *renderer_render_arg) +{ + // Skip the main viewport (index 0), which is always fully handled by the application! + ImGuiPlatformIO &platform_io = ImGui::GetPlatformIO(); + for (int i = 1; i < platform_io.Viewports.Size; i++) + { + ImGuiViewport *viewport = platform_io.Viewports[i]; + if (viewport->Flags & ImGuiViewportFlags_Minimized) + continue; + if (platform_io.Platform_RenderWindow) + platform_io.Platform_RenderWindow(viewport, platform_render_arg); + if (platform_io.Renderer_RenderWindow) + platform_io.Renderer_RenderWindow(viewport, renderer_render_arg); + } + for (int i = 1; i < platform_io.Viewports.Size; i++) + { + ImGuiViewport *viewport = platform_io.Viewports[i]; + if (viewport->Flags & ImGuiViewportFlags_Minimized) + continue; + if (platform_io.Platform_SwapBuffers) + platform_io.Platform_SwapBuffers(viewport, platform_render_arg); + if (platform_io.Renderer_SwapBuffers) + platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg); + } +} + +static int ImGui::FindPlatformMonitorForPos(const ImVec2 &pos) +{ + ImGuiContext &g = *GImGui; + for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++) + { + const ImGuiPlatformMonitor &monitor = g.PlatformIO.Monitors[monitor_n]; + if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos)) + return monitor_n; + } + return -1; +} + +// Search for the monitor with the largest intersection area with the given rectangle +// We generally try to avoid searching loops but the monitor count should be very small here +// FIXME-OPT: We could test the last monitor used for that viewport first, and early +static int ImGui::FindPlatformMonitorForRect(const ImRect &rect) +{ + ImGuiContext &g = *GImGui; + + const int monitor_count = g.PlatformIO.Monitors.Size; + if (monitor_count <= 1) + return monitor_count - 1; + + // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position. + // This is necessary for tooltips which always resize down to zero at first. + const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f); + int best_monitor_n = -1; + float best_monitor_surface = 0.001f; + + for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++) + { + const ImGuiPlatformMonitor &monitor = g.PlatformIO.Monitors[monitor_n]; + const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize); + if (monitor_rect.Contains(rect)) + return monitor_n; + ImRect overlapping_rect = rect; + overlapping_rect.ClipWithFull(monitor_rect); + float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight(); + if (overlapping_surface < best_monitor_surface) + continue; + best_monitor_surface = overlapping_surface; + best_monitor_n = monitor_n; + } + return best_monitor_n; +} + +// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor) +static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP *viewport) +{ + viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect()); +} + +// Return value is always != NULL, but don't hold on it across frames. +const ImGuiPlatformMonitor *ImGui::GetViewportPlatformMonitor(ImGuiViewport *viewport_p) +{ + ImGuiContext &g = *GImGui; + ImGuiViewportP *viewport = (ImGuiViewportP *)(void *)viewport_p; + int monitor_idx = viewport->PlatformMonitor; + if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size) + return &g.PlatformIO.Monitors[monitor_idx]; + return &g.FallbackMonitor; +} + +void ImGui::DestroyPlatformWindow(ImGuiViewportP *viewport) +{ + ImGuiContext &g = *GImGui; + if (viewport->PlatformWindowCreated) + { + if (g.PlatformIO.Renderer_DestroyWindow) + g.PlatformIO.Renderer_DestroyWindow(viewport); + if (g.PlatformIO.Platform_DestroyWindow) + g.PlatformIO.Platform_DestroyWindow(viewport); + IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL); + + // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize() + // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public. + if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID) + viewport->PlatformWindowCreated = false; + } + else + { + IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL); + } + viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL; + viewport->ClearRequestFlags(); +} + +void ImGui::DestroyPlatformWindows() +{ + // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend + // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData. + // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling + // code to operator a consistent manner. + // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without + // crashing if it doesn't have data stored. + ImGuiContext &g = *GImGui; + for (int i = 0; i < g.Viewports.Size; i++) + DestroyPlatformWindow(g.Viewports[i]); +} + +//----------------------------------------------------------------------------- +// [SECTION] DOCKING +//----------------------------------------------------------------------------- +// Docking: Internal Types +// Docking: Forward Declarations +// Docking: ImGuiDockContext +// Docking: ImGuiDockContext Docking/Undocking functions +// Docking: ImGuiDockNode +// Docking: ImGuiDockNode Tree manipulation functions +// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) +// Docking: Builder Functions +// Docking: Begin/End Support Functions (called from Begin/End) +// Docking: Settings +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Typical Docking call flow: (root level is generally public API): +//----------------------------------------------------------------------------- +// - NewFrame() new dear imgui frame +// | DockContextNewFrameUpdateUndocking() - process queued undocking requests +// | - DockContextProcessUndockWindow() - process one window undocking request +// | - DockContextProcessUndockNode() - process one whole node undocking request +// | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes +// | - update g.HoveredDockNode - [debug] update node hovered by mouse +// | - DockContextProcessDock() - process one docking request +// | - DockNodeUpdate() +// | - DockNodeUpdateForRootNode() +// | - DockNodeUpdateFlagsAndCollapse() +// | - DockNodeFindInfo() +// | - destroy unused node or tab bar +// | - create dock node host window +// | - Begin() etc. +// | - DockNodeStartMouseMovingWindow() +// | - DockNodeTreeUpdatePosSize() +// | - DockNodeTreeUpdateSplitter() +// | - draw node background +// | - DockNodeUpdateTabBar() - create/update tab bar for a docking node +// | - DockNodeAddTabBar() +// | - DockNodeUpdateWindowMenu() +// | - DockNodeCalcTabBarLayout() +// | - BeginTabBarEx() +// | - TabItemEx() calls +// | - EndTabBar() +// | - BeginDockableDragDropTarget() +// | - DockNodeUpdate() - recurse into child nodes... +//----------------------------------------------------------------------------- +// - DockSpace() user submit a dockspace into a window +// | Begin(Child) - create a child window +// | DockNodeUpdate() - call main dock node update function +// | End(Child) +// | ItemSize() +//----------------------------------------------------------------------------- +// - Begin() +// | BeginDocked() +// | BeginDockableDragDropSource() +// | BeginDockableDragDropTarget() +// | - DockNodePreviewDockRender() +//----------------------------------------------------------------------------- +// - EndFrame() +// | DockContextEndFrame() +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Docking: Internal Types +//----------------------------------------------------------------------------- +// - ImGuiDockRequestType +// - ImGuiDockRequest +// - ImGuiDockPreviewData +// - ImGuiDockNodeSettings +// - ImGuiDockContext +//----------------------------------------------------------------------------- + +enum ImGuiDockRequestType +{ + ImGuiDockRequestType_None = 0, + ImGuiDockRequestType_Dock, + ImGuiDockRequestType_Undock, + ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload +}; + +struct ImGuiDockRequest +{ + ImGuiDockRequestType Type; + ImGuiWindow *DockTargetWindow; // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL) + ImGuiDockNode *DockTargetNode; // Destination/Target Node to dock into + ImGuiWindow *DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional] + ImGuiDir DockSplitDir; + float DockSplitRatio; + bool DockSplitOuter; + ImGuiWindow *UndockTargetWindow; + ImGuiDockNode *UndockTargetNode; + + ImGuiDockRequest() + { + Type = ImGuiDockRequestType_None; + DockTargetWindow = DockPayload = UndockTargetWindow = NULL; + DockTargetNode = UndockTargetNode = NULL; + DockSplitDir = ImGuiDir_None; + DockSplitRatio = 0.5f; + DockSplitOuter = false; + } +}; + +struct ImGuiDockPreviewData +{ + ImGuiDockNode FutureNode; + bool IsDropAllowed; + bool IsCenterAvailable; + bool IsSidesAvailable; // Hold your breath, grammar freaks.. + bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window) + ImGuiDockNode *SplitNode; + ImGuiDir SplitDir; + float SplitRatio; + ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects() + + ImGuiDockPreviewData() : FutureNode(0) + { + IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; + SplitNode = NULL; + SplitDir = ImGuiDir_None; + SplitRatio = 0.f; + for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) + DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); + } +}; + +// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes) +struct ImGuiDockNodeSettings +{ + ImGuiID ID; + ImGuiID ParentNodeId; + ImGuiID ParentWindowId; + ImGuiID SelectedTabId; + signed char SplitAxis; + char Depth; + ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_) + ImVec2ih Pos; + ImVec2ih Size; + ImVec2ih SizeRef; + ImGuiDockNodeSettings() + { + memset(this, 0, sizeof(*this)); + SplitAxis = ImGuiAxis_None; + } +}; + +//----------------------------------------------------------------------------- +// Docking: Forward Declarations +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // ImGuiDockContext + static ImGuiDockNode *DockContextAddNode(ImGuiContext *ctx, ImGuiID id); + static void DockContextRemoveNode(ImGuiContext *ctx, ImGuiDockNode *node, bool merge_sibling_into_parent_node); + static void DockContextQueueNotifyRemovedNode(ImGuiContext *ctx, ImGuiDockNode *node); + static void DockContextProcessDock(ImGuiContext *ctx, ImGuiDockRequest *req); + static void DockContextProcessUndockWindow(ImGuiContext *ctx, ImGuiWindow *window, bool clear_persistent_docking_ref = true); + static void DockContextProcessUndockNode(ImGuiContext *ctx, ImGuiDockNode *node); + static void DockContextPruneUnusedSettingsNodes(ImGuiContext *ctx); + static ImGuiDockNode *DockContextFindNodeByID(ImGuiContext *ctx, ImGuiID id); + static ImGuiDockNode *DockContextBindNodeToWindow(ImGuiContext *ctx, ImGuiWindow *window); + static void DockContextBuildNodesFromSettings(ImGuiContext *ctx, ImGuiDockNodeSettings *node_settings_array, int node_settings_count); + static void DockContextBuildAddWindowsToNodes(ImGuiContext *ctx, ImGuiID root_id); // Use root_id==0 to add all + + // ImGuiDockNode + static void DockNodeAddWindow(ImGuiDockNode *node, ImGuiWindow *window, bool add_to_tab_bar); + static void DockNodeMoveWindows(ImGuiDockNode *dst_node, ImGuiDockNode *src_node); + static void DockNodeMoveChildNodes(ImGuiDockNode *dst_node, ImGuiDockNode *src_node); + static ImGuiWindow *DockNodeFindWindowByID(ImGuiDockNode *node, ImGuiID id); + static void DockNodeApplyPosSizeToWindows(ImGuiDockNode *node); + static void DockNodeRemoveWindow(ImGuiDockNode *node, ImGuiWindow *window, ImGuiID save_dock_id); + static void DockNodeHideHostWindow(ImGuiDockNode *node); + static void DockNodeUpdate(ImGuiDockNode *node); + static void DockNodeUpdateForRootNode(ImGuiDockNode *node); + static void DockNodeUpdateFlagsAndCollapse(ImGuiDockNode *node); + static void DockNodeUpdateHasCentralNodeChild(ImGuiDockNode *node); + static void DockNodeUpdateTabBar(ImGuiDockNode *node, ImGuiWindow *host_window); + static void DockNodeAddTabBar(ImGuiDockNode *node); + static void DockNodeRemoveTabBar(ImGuiDockNode *node); + static ImGuiID DockNodeUpdateWindowMenu(ImGuiDockNode *node, ImGuiTabBar *tab_bar); + static void DockNodeUpdateVisibleFlag(ImGuiDockNode *node); + static void DockNodeStartMouseMovingWindow(ImGuiDockNode *node, ImGuiWindow *window); + static bool DockNodeIsDropAllowed(ImGuiWindow *host_window, ImGuiWindow *payload_window); + static void DockNodePreviewDockSetup(ImGuiWindow *host_window, ImGuiDockNode *host_node, ImGuiWindow *payload_window, ImGuiDockPreviewData *preview_data, bool is_explicit_target, bool is_outer_docking); + static void DockNodePreviewDockRender(ImGuiWindow *host_window, ImGuiDockNode *host_node, ImGuiWindow *payload_window, const ImGuiDockPreviewData *preview_data); + static void DockNodeCalcTabBarLayout(const ImGuiDockNode *node, ImRect *out_title_rect, ImRect *out_tab_bar_rect, ImVec2 *out_window_menu_button_pos, ImVec2 *out_close_button_pos); + static void DockNodeCalcSplitRects(ImVec2 &pos_old, ImVec2 &size_old, ImVec2 &pos_new, ImVec2 &size_new, ImGuiDir dir, ImVec2 size_new_desired); + static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect &parent, ImGuiDir dir, ImRect &out_draw, bool outer_docking, ImVec2 *test_mouse_pos); + static const char *DockNodeGetHostWindowTitle(ImGuiDockNode *node, char *buf, int buf_size) + { + ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); + return buf; + } + static int DockNodeGetTabOrder(ImGuiWindow *window); + + // ImGuiDockNode tree manipulations + static void DockNodeTreeSplit(ImGuiContext *ctx, ImGuiDockNode *parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode *new_node); + static void DockNodeTreeMerge(ImGuiContext *ctx, ImGuiDockNode *parent_node, ImGuiDockNode *merge_lead_child); + static void DockNodeTreeUpdatePosSize(ImGuiDockNode *node, ImVec2 pos, ImVec2 size, ImGuiDockNode *only_write_to_single_node = NULL); + static void DockNodeTreeUpdateSplitter(ImGuiDockNode *node); + static ImGuiDockNode *DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode *node, ImVec2 pos); + static ImGuiDockNode *DockNodeTreeFindFallbackLeafNode(ImGuiDockNode *node); + + // Settings + static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id); + static void DockSettingsRemoveNodeReferences(ImGuiID *node_ids, int node_ids_count); + static ImGuiDockNodeSettings *DockSettingsFindNodeSettings(ImGuiContext *ctx, ImGuiID node_id); + static void DockSettingsHandler_ClearAll(ImGuiContext *, ImGuiSettingsHandler *); + static void DockSettingsHandler_ApplyAll(ImGuiContext *, ImGuiSettingsHandler *); + static void *DockSettingsHandler_ReadOpen(ImGuiContext *, ImGuiSettingsHandler *, const char *name); + static void DockSettingsHandler_ReadLine(ImGuiContext *, ImGuiSettingsHandler *, void *entry, const char *line); + static void DockSettingsHandler_WriteAll(ImGuiContext *imgui_ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf); +} + +//----------------------------------------------------------------------------- +// Docking: ImGuiDockContext +//----------------------------------------------------------------------------- +// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings, +// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active. +// At boot time only, we run a simple GC to remove nodes that have no references. +// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures), +// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does). +// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data. +//----------------------------------------------------------------------------- +// - DockContextInitialize() +// - DockContextShutdown() +// - DockContextClearNodes() +// - DockContextRebuildNodes() +// - DockContextNewFrameUpdateUndocking() +// - DockContextNewFrameUpdateDocking() +// - DockContextEndFrame() +// - DockContextFindNodeByID() +// - DockContextBindNodeToWindow() +// - DockContextGenNodeID() +// - DockContextAddNode() +// - DockContextRemoveNode() +// - ImGuiDockContextPruneNodeData +// - DockContextPruneUnusedSettingsNodes() +// - DockContextBuildNodesFromSettings() +// - DockContextBuildAddWindowsToNodes() +//----------------------------------------------------------------------------- + +void ImGui::DockContextInitialize(ImGuiContext *ctx) +{ + ImGuiContext &g = *ctx; + + // Add .ini handle for persistent docking data + ImGuiSettingsHandler ini_handler; + ini_handler.TypeName = "Docking"; + ini_handler.TypeHash = ImHashStr("Docking"); + ini_handler.ClearAllFn = DockSettingsHandler_ClearAll; + ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read + ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen; + ini_handler.ReadLineFn = DockSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll; + ini_handler.WriteAllFn = DockSettingsHandler_WriteAll; + g.SettingsHandlers.push_back(ini_handler); +} + +void ImGui::DockContextShutdown(ImGuiContext *ctx) +{ + ImGuiDockContext *dc = &ctx->DockContext; + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode *node = (ImGuiDockNode *)dc->Nodes.Data[n].val_p) + IM_DELETE(node); +} + +void ImGui::DockContextClearNodes(ImGuiContext *ctx, ImGuiID root_id, bool clear_settings_refs) +{ + IM_UNUSED(ctx); + IM_ASSERT(ctx == GImGui); + DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs); + DockBuilderRemoveNodeChildNodes(root_id); +} + +// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch +// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!) +void ImGui::DockContextRebuildNodes(ImGuiContext *ctx) +{ + IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n"); + ImGuiDockContext *dc = &ctx->DockContext; + SaveIniSettingsToMemory(); + ImGuiID root_id = 0; // Rebuild all + DockContextClearNodes(ctx, root_id, false); + DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); + DockContextBuildAddWindowsToNodes(ctx, root_id); +} + +// Docking context update function, called by NewFrame() +void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext *ctx) +{ + ImGuiContext &g = *ctx; + ImGuiDockContext *dc = &ctx->DockContext; + if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) + { + if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0) + DockContextClearNodes(ctx, 0, true); + return; + } + + // Setting NoSplit at runtime merges all nodes + if (g.IO.ConfigDockingNoSplit) + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode *node = (ImGuiDockNode *)dc->Nodes.Data[n].val_p) + if (node->IsRootNode() && node->IsSplitNode()) + { + DockBuilderRemoveNodeChildNodes(node->ID); + // dc->WantFullRebuild = true; + } + + // Process full rebuild +#if 0 + if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C))) + dc->WantFullRebuild = true; +#endif + if (dc->WantFullRebuild) + { + DockContextRebuildNodes(ctx); + dc->WantFullRebuild = false; + } + + // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame) + for (int n = 0; n < dc->Requests.Size; n++) + { + ImGuiDockRequest *req = &dc->Requests[n]; + if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow) + DockContextProcessUndockWindow(ctx, req->UndockTargetWindow); + else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode) + DockContextProcessUndockNode(ctx, req->UndockTargetNode); + } +} + +// Docking context update function, called by NewFrame() +void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext *ctx) +{ + ImGuiContext &g = *ctx; + ImGuiDockContext *dc = &ctx->DockContext; + if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) + return; + + // [DEBUG] Store hovered dock node. + // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut. + // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering. + g.HoveredDockNode = NULL; + if (ImGuiWindow *hovered_window = g.HoveredWindowUnderMovingWindow) + { + if (hovered_window->DockNodeAsHost) + g.HoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos); + else if (hovered_window->RootWindow->DockNode) + g.HoveredDockNode = hovered_window->RootWindow->DockNode; + } + + // Process Docking requests + for (int n = 0; n < dc->Requests.Size; n++) + if (dc->Requests[n].Type == ImGuiDockRequestType_Dock) + DockContextProcessDock(ctx, &dc->Requests[n]); + dc->Requests.resize(0); + + // Create windows for each automatic docking nodes + // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high) + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode *node = (ImGuiDockNode *)dc->Nodes.Data[n].val_p) + if (node->IsFloatingNode()) + DockNodeUpdate(node); +} + +void ImGui::DockContextEndFrame(ImGuiContext *ctx) +{ + // Draw backgrounds of node missing their window + ImGuiContext &g = *ctx; + ImGuiDockContext *dc = &g.DockContext; + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode *node = (ImGuiDockNode *)dc->Nodes.Data[n].val_p) + if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame) + { + ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size); + ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), DOCKING_SPLITTER_SIZE); + node->HostWindow->DrawList->ChannelsSetCurrent(0); + node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags); + } +} + +static ImGuiDockNode *ImGui::DockContextFindNodeByID(ImGuiContext *ctx, ImGuiID id) +{ + return (ImGuiDockNode *)ctx->DockContext.Nodes.GetVoidPtr(id); +} + +ImGuiID ImGui::DockContextGenNodeID(ImGuiContext *ctx) +{ + // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used) + // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0 + // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted. + ImGuiID id = 0x0001; + while (DockContextFindNodeByID(ctx, id) != NULL) + id++; + return id; +} + +static ImGuiDockNode *ImGui::DockContextAddNode(ImGuiContext *ctx, ImGuiID id) +{ + // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window. + if (id == 0) + id = DockContextGenNodeID(ctx); + else + IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL); + + // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings! + IMGUI_DEBUG_LOG_DOCKING("DockContextAddNode 0x%08X\n", id); + ImGuiDockNode *node = IM_NEW(ImGuiDockNode)(id); + ctx->DockContext.Nodes.SetVoidPtr(node->ID, node); + return node; +} + +static void ImGui::DockContextRemoveNode(ImGuiContext *ctx, ImGuiDockNode *node, bool merge_sibling_into_parent_node) +{ + ImGuiContext &g = *ctx; + ImGuiDockContext *dc = &ctx->DockContext; + + IMGUI_DEBUG_LOG_DOCKING("DockContextRemoveNode 0x%08X\n", node->ID); + IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node); + IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL); + IM_ASSERT(node->Windows.Size == 0); + + if (node->HostWindow) + node->HostWindow->DockNodeAsHost = NULL; + + ImGuiDockNode *parent_node = node->ParentNode; + const bool merge = (merge_sibling_into_parent_node && parent_node != NULL); + if (merge) + { + IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node); + ImGuiDockNode *sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]); + DockNodeTreeMerge(&g, parent_node, sibling_node); + } + else + { + for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++) + if (parent_node->ChildNodes[n] == node) + node->ParentNode->ChildNodes[n] = NULL; + dc->Nodes.SetVoidPtr(node->ID, NULL); + IM_DELETE(node); + } +} + +static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void *lhs, const void *rhs) +{ + const ImGuiDockNode *a = *(const ImGuiDockNode *const *)lhs; + const ImGuiDockNode *b = *(const ImGuiDockNode *const *)rhs; + return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a); +} + +// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here. +struct ImGuiDockContextPruneNodeData +{ + int CountWindows, CountChildWindows, CountChildNodes; + ImGuiID RootId; + ImGuiDockContextPruneNodeData() + { + CountWindows = CountChildWindows = CountChildNodes = 0; + RootId = 0; + } +}; + +// Garbage collect unused nodes (run once at init time) +static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext *ctx) +{ + ImGuiContext &g = *ctx; + ImGuiDockContext *dc = &ctx->DockContext; + IM_ASSERT(g.Windows.Size == 0); + + ImPool pool; + pool.Reserve(dc->NodesSettings.Size); + + // Count child nodes and compute RootID + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) + { + ImGuiDockNodeSettings *settings = &dc->NodesSettings[settings_n]; + ImGuiDockContextPruneNodeData *parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0; + pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID; + if (settings->ParentNodeId) + pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++; + } + + // Count reference to dock ids from dockspaces + // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes() + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) + { + ImGuiDockNodeSettings *settings = &dc->NodesSettings[settings_n]; + if (settings->ParentWindowId != 0) + if (ImGuiWindowSettings *window_settings = FindWindowSettings(settings->ParentWindowId)) + if (window_settings->DockId) + if (ImGuiDockContextPruneNodeData *data = pool.GetByKey(window_settings->DockId)) + data->CountChildNodes++; + } + + // Count reference to dock ids from window settings + // We guard against the possibility of an invalid .ini file (RootID may point to a missing node) + for (ImGuiWindowSettings *settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (ImGuiID dock_id = settings->DockId) + if (ImGuiDockContextPruneNodeData *data = pool.GetByKey(dock_id)) + { + data->CountWindows++; + if (ImGuiDockContextPruneNodeData *data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId)) + data_root->CountChildWindows++; + } + + // Prune + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) + { + ImGuiDockNodeSettings *settings = &dc->NodesSettings[settings_n]; + ImGuiDockContextPruneNodeData *data = pool.GetByKey(settings->ID); + if (data->CountWindows > 1) + continue; + ImGuiDockContextPruneNodeData *data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId); + + bool remove = false; + remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window + remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window + remove |= (data_root->CountChildWindows == 0); + if (remove) + { + IMGUI_DEBUG_LOG_DOCKING("DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID); + DockSettingsRemoveNodeReferences(&settings->ID, 1); + settings->ID = 0; + } + } +} + +static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext *ctx, ImGuiDockNodeSettings *node_settings_array, int node_settings_count) +{ + // Build nodes + for (int node_n = 0; node_n < node_settings_count; node_n++) + { + ImGuiDockNodeSettings *settings = &node_settings_array[node_n]; + if (settings->ID == 0) + continue; + ImGuiDockNode *node = DockContextAddNode(ctx, settings->ID); + node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL; + node->Pos = ImVec2(settings->Pos.x, settings->Pos.y); + node->Size = ImVec2(settings->Size.x, settings->Size.y); + node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y); + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode; + if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL) + node->ParentNode->ChildNodes[0] = node; + else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL) + node->ParentNode->ChildNodes[1] = node; + node->SelectedTabId = settings->SelectedTabId; + node->SplitAxis = (ImGuiAxis)settings->SplitAxis; + node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_); + + // Bind host window immediately if it already exist (in case of a rebuild) + // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set. + char host_window_title[20]; + ImGuiDockNode *root_node = DockNodeGetRootNode(node); + node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title))); + } +} + +void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext *ctx, ImGuiID root_id) +{ + // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame) + ImGuiContext &g = *ctx; + for (int n = 0; n < g.Windows.Size; n++) + { + ImGuiWindow *window = g.Windows[n]; + if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1) + continue; + if (window->DockNode != NULL) + continue; + + ImGuiDockNode *node = DockContextFindNodeByID(ctx, window->DockId); + IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings() + if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id) + DockNodeAddWindow(node, window, true); + } +} + +//----------------------------------------------------------------------------- +// Docking: ImGuiDockContext Docking/Undocking functions +//----------------------------------------------------------------------------- +// - DockContextQueueDock() +// - DockContextQueueUndockWindow() +// - DockContextQueueUndockNode() +// - DockContextQueueNotifyRemovedNode() +// - DockContextProcessDock() +// - DockContextProcessUndockWindow() +// - DockContextProcessUndockNode() +// - DockContextCalcDropPosForDocking() +//----------------------------------------------------------------------------- + +void ImGui::DockContextQueueDock(ImGuiContext *ctx, ImGuiWindow *target, ImGuiDockNode *target_node, ImGuiWindow *payload, ImGuiDir split_dir, float split_ratio, bool split_outer) +{ + IM_ASSERT(target != payload); + ImGuiDockRequest req; + req.Type = ImGuiDockRequestType_Dock; + req.DockTargetWindow = target; + req.DockTargetNode = target_node; + req.DockPayload = payload; + req.DockSplitDir = split_dir; + req.DockSplitRatio = split_ratio; + req.DockSplitOuter = split_outer; + ctx->DockContext.Requests.push_back(req); +} + +void ImGui::DockContextQueueUndockWindow(ImGuiContext *ctx, ImGuiWindow *window) +{ + ImGuiDockRequest req; + req.Type = ImGuiDockRequestType_Undock; + req.UndockTargetWindow = window; + ctx->DockContext.Requests.push_back(req); +} + +void ImGui::DockContextQueueUndockNode(ImGuiContext *ctx, ImGuiDockNode *node) +{ + ImGuiDockRequest req; + req.Type = ImGuiDockRequestType_Undock; + req.UndockTargetNode = node; + ctx->DockContext.Requests.push_back(req); +} + +void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext *ctx, ImGuiDockNode *node) +{ + ImGuiDockContext *dc = &ctx->DockContext; + for (int n = 0; n < dc->Requests.Size; n++) + if (dc->Requests[n].DockTargetNode == node) + dc->Requests[n].Type = ImGuiDockRequestType_None; +} + +void ImGui::DockContextProcessDock(ImGuiContext *ctx, ImGuiDockRequest *req) +{ + IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL)); + IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL); + + ImGuiContext &g = *ctx; + IM_UNUSED(g); + + ImGuiWindow *payload_window = req->DockPayload; // Optional + ImGuiWindow *target_window = req->DockTargetWindow; + ImGuiDockNode *node = req->DockTargetNode; + if (payload_window) + IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window ? payload_window->Name : "NULL", req->DockSplitDir); + else + IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir); + + // Decide which Tab will be selected at the end of the operation + ImGuiID next_selected_id = 0; + ImGuiDockNode *payload_node = NULL; + if (payload_window) + { + payload_node = payload_window->DockNodeAsHost; + payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later. + if (payload_node && payload_node->IsLeafNode()) + next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId; + if (payload_node == NULL) + next_selected_id = payload_window->TabId; + } + + // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well + // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==. + if (node) + IM_ASSERT(node->LastFrameAlive <= g.FrameCount); + if (node && target_window && node == target_window->DockNodeAsHost) + IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode()); + + // Create new node and add existing window to it + if (node == NULL) + { + node = DockContextAddNode(ctx, 0); + node->Pos = target_window->Pos; + node->Size = target_window->Size; + if (target_window->DockNodeAsHost == NULL) + { + DockNodeAddWindow(node, target_window, true); + node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted; + target_window->DockIsActive = true; + } + } + + ImGuiDir split_dir = req->DockSplitDir; + if (split_dir != ImGuiDir_None) + { + // Split into two, one side will be our payload node unless we are dropping a loose window + const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; + const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side + const float split_ratio = req->DockSplitRatio; + DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here! + ImGuiDockNode *new_node = node->ChildNodes[split_inheritor_child_idx ^ 1]; + new_node->HostWindow = node->HostWindow; + node = new_node; + } + node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar); + + if (node != payload_node) + { + // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!) + if (node->Windows.Size > 0 && node->TabBar == NULL) + { + DockNodeAddTabBar(node); + for (int n = 0; n < node->Windows.Size; n++) + TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]); + } + + if (payload_node != NULL) + { + // Transfer full payload node (with 1+ child windows or child nodes) + if (payload_node->IsSplitNode()) + { + if (node->Windows.Size > 0) + { + // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node. + // In this situation, we move the windows of the target node into the currently visible node of the payload. + // This allows us to preserve some of the underlying dock tree settings nicely. + IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted. + ImGuiDockNode *visible_node = payload_node->OnlyNodeWithWindows; + if (visible_node->TabBar) + IM_ASSERT(visible_node->TabBar->Tabs.Size > 0); + DockNodeMoveWindows(node, visible_node); + DockNodeMoveWindows(visible_node, node); + DockSettingsRenameNodeReferences(node->ID, visible_node->ID); + } + if (node->IsCentralNode()) + { + // Central node property needs to be moved to a leaf node, pick the last focused one. + // FIXME-DOCK: If we had to transfer other flags here, what would the policy be? + ImGuiDockNode *last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId); + IM_ASSERT(last_focused_node != NULL); + ImGuiDockNode *last_focused_root_node = DockNodeGetRootNode(last_focused_node); + IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node)); + last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode); + node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode); + last_focused_root_node->CentralNode = last_focused_node; + } + + IM_ASSERT(node->Windows.Size == 0); + DockNodeMoveChildNodes(node, payload_node); + } + else + { + const ImGuiID payload_dock_id = payload_node->ID; + DockNodeMoveWindows(node, payload_node); + DockSettingsRenameNodeReferences(payload_dock_id, node->ID); + } + DockContextRemoveNode(ctx, payload_node, true); + } + else if (payload_window) + { + // Transfer single window + const ImGuiID payload_dock_id = payload_window->DockId; + node->VisibleWindow = payload_window; + DockNodeAddWindow(node, payload_window, true); + if (payload_dock_id != 0) + DockSettingsRenameNodeReferences(payload_dock_id, node->ID); + } + } + else + { + // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar + node->WantHiddenTabBarUpdate = true; + } + + // Update selection immediately + if (ImGuiTabBar *tab_bar = node->TabBar) + tab_bar->NextSelectedTabId = next_selected_id; + MarkIniSettingsDirty(); +} + +// Problem: +// Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more +// than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic +// with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be +// due to missing ImGuiBackendFlags_HasMouseCursors backend flag). +// Solution: +// When undocking a window we currently force its maximum size to 90% of the host viewport or monitor. +// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch). +static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2 &size, ImGuiViewport *ref_viewport) +{ + if (ref_viewport == NULL) + return size; + + ImGuiContext &g = *GImGui; + ImVec2 max_size = ImFloor(ref_viewport->WorkSize * 0.90f); + if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) + { + const ImGuiPlatformMonitor *monitor = ImGui::GetViewportPlatformMonitor(ref_viewport); + max_size = ImFloor(monitor->WorkSize * 0.90f); + } + return ImMin(size, max_size); +} + +void ImGui::DockContextProcessUndockWindow(ImGuiContext *ctx, ImGuiWindow *window, bool clear_persistent_docking_ref) +{ + IMGUI_DEBUG_LOG_DOCKING("DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref); + IM_UNUSED(ctx); + if (window->DockNode) + DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId); + else + window->DockId = 0; + window->Collapsed = false; + window->DockIsActive = false; + window->DockNodeIsVisible = window->DockTabIsVisible = false; + window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport); + + MarkIniSettingsDirty(); +} + +void ImGui::DockContextProcessUndockNode(ImGuiContext *ctx, ImGuiDockNode *node) +{ + IMGUI_DEBUG_LOG_DOCKING("DockContextProcessUndockNode node %08X\n", node->ID); + IM_ASSERT(node->IsLeafNode()); + IM_ASSERT(node->Windows.Size >= 1); + + if (node->IsRootNode() || node->IsCentralNode()) + { + // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload. + ImGuiDockNode *new_node = DockContextAddNode(ctx, 0); + new_node->Pos = node->Pos; + new_node->Size = node->Size; + new_node->SizeRef = node->SizeRef; + DockNodeMoveWindows(new_node, node); + DockSettingsRenameNodeReferences(node->ID, new_node->ID); + for (int n = 0; n < new_node->Windows.Size; n++) + { + ImGuiWindow *window = new_node->Windows[n]; + window->Flags &= ~ImGuiWindowFlags_ChildWindow; + if (window->ParentWindow) + window->ParentWindow->DC.ChildWindows.find_erase(window); + UpdateWindowParentAndRootLinks(window, window->Flags, NULL); + } + node = new_node; + } + else + { + // Otherwise extract our node and merge our sibling back into the parent node. + IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); + int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1; + node->ParentNode->ChildNodes[index_in_parent] = NULL; + DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]); + node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport + node->ParentNode = NULL; + } + node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode; + node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport); + node->WantMouseMove = true; + MarkIniSettingsDirty(); +} + +// This is mostly used for automation. +bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow *target, ImGuiDockNode *target_node, ImGuiWindow *payload, ImGuiDir split_dir, bool split_outer, ImVec2 *out_pos) +{ + // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects + // (which would be functionally identical) we only show the outer one. Reflect this here. + if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None) + split_outer = true; + ImGuiDockPreviewData split_data; + DockNodePreviewDockSetup(target, target_node, payload, &split_data, false, split_outer); + if (split_data.DropRectsDraw[split_dir + 1].IsInverted()) + return false; + *out_pos = split_data.DropRectsDraw[split_dir + 1].GetCenter(); + return true; +} + +//----------------------------------------------------------------------------- +// Docking: ImGuiDockNode +//----------------------------------------------------------------------------- +// - DockNodeGetTabOrder() +// - DockNodeAddWindow() +// - DockNodeRemoveWindow() +// - DockNodeMoveChildNodes() +// - DockNodeMoveWindows() +// - DockNodeApplyPosSizeToWindows() +// - DockNodeHideHostWindow() +// - ImGuiDockNodeFindInfoResults +// - DockNodeFindInfo() +// - DockNodeFindWindowByID() +// - DockNodeUpdateFlagsAndCollapse() +// - DockNodeUpdateHasCentralNodeFlag() +// - DockNodeUpdateVisibleFlag() +// - DockNodeStartMouseMovingWindow() +// - DockNodeUpdate() +// - DockNodeUpdateWindowMenu() +// - DockNodeBeginAmendTabBar() +// - DockNodeEndAmendTabBar() +// - DockNodeUpdateTabBar() +// - DockNodeAddTabBar() +// - DockNodeRemoveTabBar() +// - DockNodeIsDropAllowedOne() +// - DockNodeIsDropAllowed() +// - DockNodeCalcTabBarLayout() +// - DockNodeCalcSplitRects() +// - DockNodeCalcDropRectsAndTestMousePos() +// - DockNodePreviewDockSetup() +// - DockNodePreviewDockRender() +//----------------------------------------------------------------------------- + +ImGuiDockNode::ImGuiDockNode(ImGuiID id) +{ + ID = id; + SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None; + ParentNode = ChildNodes[0] = ChildNodes[1] = NULL; + TabBar = NULL; + SplitAxis = ImGuiAxis_None; + + State = ImGuiDockNodeState_Unknown; + LastBgColor = IM_COL32_WHITE; + HostWindow = VisibleWindow = NULL; + CentralNode = OnlyNodeWithWindows = NULL; + CountNodeWithWindows = 0; + LastFrameAlive = LastFrameActive = LastFrameFocused = -1; + LastFocusedNodeId = 0; + SelectedTabId = 0; + WantCloseTabId = 0; + AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode; + AuthorityForViewport = ImGuiDataAuthority_Auto; + IsVisible = true; + IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false; + IsBgDrawnThisFrame = false; + WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false; +} + +ImGuiDockNode::~ImGuiDockNode() +{ + IM_DELETE(TabBar); + TabBar = NULL; + ChildNodes[0] = ChildNodes[1] = NULL; +} + +int ImGui::DockNodeGetTabOrder(ImGuiWindow *window) +{ + ImGuiTabBar *tab_bar = window->DockNode->TabBar; + if (tab_bar == NULL) + return -1; + ImGuiTabItem *tab = TabBarFindTabByID(tab_bar, window->TabId); + return tab ? tab_bar->GetTabOrder(tab) : -1; +} + +static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow *window) +{ + window->Hidden = true; + window->HiddenFramesCanSkipItems = window->Active ? 1 : 2; +} + +static void ImGui::DockNodeAddWindow(ImGuiDockNode *node, ImGuiWindow *window, bool add_to_tab_bar) +{ + ImGuiContext &g = *GImGui; + (void)g; + if (window->DockNode) + { + // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node) + IM_ASSERT(window->DockNode->ID != node->ID); + DockNodeRemoveWindow(window->DockNode, window, 0); + } + IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); + IMGUI_DEBUG_LOG_DOCKING("DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name); + + // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window, + // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame). + // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin() + if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false) + DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]); + + node->Windows.push_back(window); + node->WantHiddenTabBarUpdate = true; + window->DockNode = node; + window->DockId = node->ID; + window->DockIsActive = (node->Windows.Size > 1); + window->DockTabWantClose = false; + + // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage. + // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one. + if (node->HostWindow == NULL && node->IsFloatingNode()) + { + if (node->AuthorityForPos == ImGuiDataAuthority_Auto) + node->AuthorityForPos = ImGuiDataAuthority_Window; + if (node->AuthorityForSize == ImGuiDataAuthority_Auto) + node->AuthorityForSize = ImGuiDataAuthority_Window; + if (node->AuthorityForViewport == ImGuiDataAuthority_Auto) + node->AuthorityForViewport = ImGuiDataAuthority_Window; + } + + // Add to tab bar if requested + if (add_to_tab_bar) + { + if (node->TabBar == NULL) + { + DockNodeAddTabBar(node); + node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId; + + // Add existing windows + for (int n = 0; n < node->Windows.Size - 1; n++) + TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]); + } + TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window); + } + + DockNodeUpdateVisibleFlag(node); + + // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame. + if (node->HostWindow) + UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow); +} + +static void ImGui::DockNodeRemoveWindow(ImGuiDockNode *node, ImGuiWindow *window, ImGuiID save_dock_id) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(window->DockNode == node); + // IM_ASSERT(window->RootWindowDockTree == node->HostWindow); + // IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin() + IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID); + IMGUI_DEBUG_LOG_DOCKING("DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name); + + window->DockNode = NULL; + window->DockIsActive = window->DockTabWantClose = false; + window->DockId = save_dock_id; + window->Flags &= ~ImGuiWindowFlags_ChildWindow; + if (window->ParentWindow) + window->ParentWindow->DC.ChildWindows.find_erase(window); + UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately + + // Remove window + bool erased = false; + for (int n = 0; n < node->Windows.Size; n++) + if (node->Windows[n] == window) + { + node->Windows.erase(node->Windows.Data + n); + erased = true; + break; + } + if (!erased) + IM_ASSERT(erased); + if (node->VisibleWindow == window) + node->VisibleWindow = NULL; + + // Remove tab and possibly tab bar + node->WantHiddenTabBarUpdate = true; + if (node->TabBar) + { + TabBarRemoveTab(node->TabBar, window->TabId); + const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2; + if (node->Windows.Size < tab_count_threshold_for_tab_bar) + DockNodeRemoveTabBar(node); + } + + if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID) + { + // Automatic dock node delete themselves if they are not holding at least one tab + DockContextRemoveNode(&g, node, true); + return; + } + + if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow) + { + ImGuiWindow *remaining_window = node->Windows[0]; + if (node->HostWindow->ViewportOwned && node->IsRootNode()) + { + // Transfer viewport back to the remaining loose window + IMGUI_DEBUG_LOG_VIEWPORT("Node %08X transfer Viewport %08X=>%08X for Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, remaining_window->ID, remaining_window->Name); + IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow); + node->HostWindow->Viewport->Window = remaining_window; + node->HostWindow->Viewport->ID = remaining_window->ID; + } + remaining_window->Collapsed = node->HostWindow->Collapsed; + } + + // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree + DockNodeUpdateVisibleFlag(node); +} + +static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode *dst_node, ImGuiDockNode *src_node) +{ + IM_ASSERT(dst_node->Windows.Size == 0); + dst_node->ChildNodes[0] = src_node->ChildNodes[0]; + dst_node->ChildNodes[1] = src_node->ChildNodes[1]; + if (dst_node->ChildNodes[0]) + dst_node->ChildNodes[0]->ParentNode = dst_node; + if (dst_node->ChildNodes[1]) + dst_node->ChildNodes[1]->ParentNode = dst_node; + dst_node->SplitAxis = src_node->SplitAxis; + dst_node->SizeRef = src_node->SizeRef; + src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL; +} + +static void ImGui::DockNodeMoveWindows(ImGuiDockNode *dst_node, ImGuiDockNode *src_node) +{ + // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered) + IM_ASSERT(src_node && dst_node && dst_node != src_node); + ImGuiTabBar *src_tab_bar = src_node->TabBar; + if (src_tab_bar != NULL) + IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size); + + // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.) + bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL); + if (move_tab_bar) + { + dst_node->TabBar = src_node->TabBar; + src_node->TabBar = NULL; + } + + for (int n = 0; n < src_node->Windows.Size; n++) + { + // DockNode's TabBar may have non-window Tabs manually appended by user + if (ImGuiWindow *window = src_tab_bar ? src_tab_bar->Tabs[n].Window : src_node->Windows[n]) + { + window->DockNode = NULL; + window->DockIsActive = false; + DockNodeAddWindow(dst_node, window, move_tab_bar ? false : true); + } + } + src_node->Windows.clear(); + + if (!move_tab_bar && src_node->TabBar) + { + if (dst_node->TabBar) + dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId; + DockNodeRemoveTabBar(src_node); + } +} + +static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode *node) +{ + for (int n = 0; n < node->Windows.Size; n++) + { + SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame + SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always); + } +} + +static void ImGui::DockNodeHideHostWindow(ImGuiDockNode *node) +{ + if (node->HostWindow) + { + if (node->HostWindow->DockNodeAsHost == node) + node->HostWindow->DockNodeAsHost = NULL; + node->HostWindow = NULL; + } + + if (node->Windows.Size == 1) + { + node->VisibleWindow = node->Windows[0]; + node->Windows[0]->DockIsActive = false; + } + + if (node->TabBar) + DockNodeRemoveTabBar(node); +} + +// Search function called once by root node in DockNodeUpdate() +struct ImGuiDockNodeTreeInfo +{ + ImGuiDockNode *CentralNode; + ImGuiDockNode *FirstNodeWithWindows; + int CountNodesWithWindows; + // ImGuiWindowClass WindowClassForMerges; + + ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); } +}; + +static void DockNodeFindInfo(ImGuiDockNode *node, ImGuiDockNodeTreeInfo *info) +{ + if (node->Windows.Size > 0) + { + if (info->FirstNodeWithWindows == NULL) + info->FirstNodeWithWindows = node; + info->CountNodesWithWindows++; + } + if (node->IsCentralNode()) + { + IM_ASSERT(info->CentralNode == NULL); // Should be only one + IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this."); + info->CentralNode = node; + } + if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL) + return; + if (node->ChildNodes[0]) + DockNodeFindInfo(node->ChildNodes[0], info); + if (node->ChildNodes[1]) + DockNodeFindInfo(node->ChildNodes[1], info); +} + +static ImGuiWindow *ImGui::DockNodeFindWindowByID(ImGuiDockNode *node, ImGuiID id) +{ + IM_ASSERT(id != 0); + for (int n = 0; n < node->Windows.Size; n++) + if (node->Windows[n]->ID == id) + return node->Windows[n]; + return NULL; +} + +// - Remove inactive windows/nodes. +// - Update visibility flag. +static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode *node) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); + + // Inherit most flags + if (node->ParentNode) + node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; + + // Recurse into children + // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'. + // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node' + // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless) + node->HasCentralNodeChild = false; + if (node->ChildNodes[0]) + DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]); + if (node->ChildNodes[1]) + DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]); + + // Remove inactive windows, collapse nodes + // Merge node flags overrides stored in windows + node->LocalFlagsInWindows = ImGuiDockNodeFlags_None; + for (int window_n = 0; window_n < node->Windows.Size; window_n++) + { + ImGuiWindow *window = node->Windows[window_n]; + IM_ASSERT(window->DockNode == node); + + bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount); + bool remove = false; + remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount); + remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame + remove |= (window->DockTabWantClose); + if (remove) + { + window->DockTabWantClose = false; + if (node->Windows.Size == 1 && !node->IsCentralNode()) + { + DockNodeHideHostWindow(node); + node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow; + DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return + return; + } + DockNodeRemoveWindow(node, window, node->ID); + window_n--; + continue; + } + + // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this. + // node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear; + node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet; + } + node->UpdateMergedFlags(); + + // Auto-hide tab bar option + ImGuiDockNodeFlags node_flags = node->MergedFlags; + if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar()) + node->WantHiddenTabBarToggle = true; + node->WantHiddenTabBarUpdate = false; + + // Cancel toggling if we know our tab bar is enforced to be hidden at all times + if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar)) + node->WantHiddenTabBarToggle = false; + + // Apply toggles at a single point of the frame (here!) + if (node->Windows.Size > 1) + node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar); + else if (node->WantHiddenTabBarToggle) + node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar); + node->WantHiddenTabBarToggle = false; + + DockNodeUpdateVisibleFlag(node); +} + +// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames. +static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode *node) +{ + node->HasCentralNodeChild = false; + if (node->ChildNodes[0]) + DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]); + if (node->ChildNodes[1]) + DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]); + if (node->IsRootNode()) + { + ImGuiDockNode *mark_node = node->CentralNode; + while (mark_node) + { + mark_node->HasCentralNodeChild = true; + mark_node = mark_node->ParentNode; + } + } +} + +static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode *node) +{ + // Update visibility flag + bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode(); + is_visible |= (node->Windows.Size > 0); + is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible); + is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible); + node->IsVisible = is_visible; +} + +static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode *node, ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(node->WantMouseMove == true); + StartMouseMovingWindow(window); + g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos; + g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision. + node->WantMouseMove = false; +} + +// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class. +static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode *node) +{ + DockNodeUpdateFlagsAndCollapse(node); + + // - Setup central node pointers + // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!) + // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing + ImGuiDockNodeTreeInfo info; + DockNodeFindInfo(node, &info); + node->CentralNode = info.CentralNode; + node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL; + node->CountNodeWithWindows = info.CountNodesWithWindows; + if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL) + node->LastFocusedNodeId = info.FirstNodeWithWindows->ID; + + // Copy the window class from of our first window so it can be used for proper dock filtering. + // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy. + // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec. + if (ImGuiDockNode *first_node_with_windows = info.FirstNodeWithWindows) + { + node->WindowClass = first_node_with_windows->Windows[0]->WindowClass; + for (int n = 1; n < first_node_with_windows->Windows.Size; n++) + if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false) + { + node->WindowClass = first_node_with_windows->Windows[n]->WindowClass; + break; + } + } + + ImGuiDockNode *mark_node = node->CentralNode; + while (mark_node) + { + mark_node->HasCentralNodeChild = true; + mark_node = mark_node->ParentNode; + } +} + +static void DockNodeSetupHostWindow(ImGuiDockNode *node, ImGuiWindow *host_window) +{ + // Remove ourselves from any previous different host window + // This can happen if a user mistakenly does (see #4295 for details): + // - N+0: DockBuilderAddNode(id, 0) // missing ImGuiDockNodeFlags_DockSpace + // - N+1: NewFrame() // will create floating host window for that node + // - N+1: DockSpace(id) // requalify node as dockspace, moving host window + if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node) + node->HostWindow->DockNodeAsHost = NULL; + + host_window->DockNodeAsHost = node; + node->HostWindow = host_window; +} + +static void ImGui::DockNodeUpdate(ImGuiDockNode *node) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(node->LastFrameActive != g.FrameCount); + node->LastFrameAlive = g.FrameCount; + node->IsBgDrawnThisFrame = false; + + node->CentralNode = node->OnlyNodeWithWindows = NULL; + if (node->IsRootNode()) + DockNodeUpdateForRootNode(node); + + // Remove tab bar if not needed + if (node->TabBar && node->IsNoTabBar()) + DockNodeRemoveTabBar(node); + + // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId) + bool want_to_hide_host_window = false; + if (node->IsFloatingNode()) + { + if (node->Windows.Size <= 1 && node->IsLeafNode()) + if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar)) + want_to_hide_host_window = true; + if (node->CountNodeWithWindows == 0) + want_to_hide_host_window = true; + } + if (want_to_hide_host_window) + { + if (node->Windows.Size == 1) + { + // Floating window pos/size is authoritative + ImGuiWindow *single_window = node->Windows[0]; + node->Pos = single_window->Pos; + node->Size = single_window->SizeFull; + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; + + // Transfer focus immediately so when we revert to a regular window it is immediately selected + if (node->HostWindow && g.NavWindow == node->HostWindow) + FocusWindow(single_window); + if (node->HostWindow) + { + single_window->Viewport = node->HostWindow->Viewport; + single_window->ViewportId = node->HostWindow->ViewportId; + if (node->HostWindow->ViewportOwned) + { + single_window->Viewport->Window = single_window; + single_window->ViewportOwned = true; + } + } + } + + DockNodeHideHostWindow(node); + node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow; + node->WantCloseAll = false; + node->WantCloseTabId = 0; + node->HasCloseButton = node->HasWindowMenuButton = false; + node->LastFrameActive = g.FrameCount; + + if (node->WantMouseMove && node->Windows.Size == 1) + DockNodeStartMouseMovingWindow(node, node->Windows[0]); + return; + } + + // In some circumstance we will defer creating the host window (so everything will be kept hidden), + // while the expected visible window is resizing itself. + // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled, + // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up: + // N+0: Begin(): window created (with no known size), node is created + // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible + // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible + // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code. + // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin(). + // In reality it isn't very important as user quickly ends up with size data in .ini file. + if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode()) + { + IM_ASSERT(node->Windows.Size > 0); + ImGuiWindow *ref_window = NULL; + if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them! + ref_window = DockNodeFindWindowByID(node, node->SelectedTabId); + if (ref_window == NULL) + ref_window = node->Windows[0]; + if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0) + { + node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing; + return; + } + } + + const ImGuiDockNodeFlags node_flags = node->MergedFlags; + + // Decide if the node will have a close button and a window menu button + node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0; + node->HasCloseButton = false; + for (int window_n = 0; window_n < node->Windows.Size; window_n++) + { + // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call. + ImGuiWindow *window = node->Windows[window_n]; + node->HasCloseButton |= window->HasCloseButton; + window->DockIsActive = (node->Windows.Size > 1); + } + if (node_flags & ImGuiDockNodeFlags_NoCloseButton) + node->HasCloseButton = false; + + // Bind or create host window + ImGuiWindow *host_window = NULL; + bool beginned_into_host_window = false; + if (node->IsDockSpace()) + { + // [Explicit root dockspace node] + IM_ASSERT(node->HostWindow); + host_window = node->HostWindow; + } + else + { + // [Automatic root or child nodes] + if (node->IsRootNode() && node->IsVisible) + { + ImGuiWindow *ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL; + + // Sync Pos + if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window) + SetNextWindowPos(ref_window->Pos); + else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode) + SetNextWindowPos(node->Pos); + + // Sync Size + if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window) + SetNextWindowSize(ref_window->SizeFull); + else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode) + SetNextWindowSize(node->Size); + + // Sync Collapsed + if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window) + SetNextWindowCollapsed(ref_window->Collapsed); + + // Sync Viewport + if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window) + SetNextWindowViewport(ref_window->ViewportId); + + SetNextWindowClass(&node->WindowClass); + + // Begin into the host window + char window_label[20]; + DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label)); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost; + window_flags |= ImGuiWindowFlags_NoFocusOnAppearing; + window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse; + window_flags |= ImGuiWindowFlags_NoTitleBar; + + SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders + PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); + Begin(window_label, NULL, window_flags); + PopStyleVar(); + beginned_into_host_window = true; + + host_window = g.CurrentWindow; + DockNodeSetupHostWindow(node, host_window); + host_window->DC.CursorPos = host_window->Pos; + node->Pos = host_window->Pos; + node->Size = host_window->Size; + + // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow) + // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags. + // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again. + // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window + // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back + // after the dock host window, losing their top-most status. + if (node->HostWindow->Appearing) + BringWindowToDisplayFront(node->HostWindow); + + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto; + } + else if (node->ParentNode) + { + node->HostWindow = host_window = node->ParentNode->HostWindow; + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto; + } + if (node->WantMouseMove && node->HostWindow) + DockNodeStartMouseMovingWindow(node, node->HostWindow); + } + + // Update focused node (the one whose title bar is highlight) within a node tree + if (node->IsSplitNode()) + IM_ASSERT(node->TabBar == NULL); + if (node->IsRootNode()) + if (g.NavWindow && g.NavWindow->RootWindow->DockNode && g.NavWindow->RootWindow->ParentWindow == host_window) + node->LastFocusedNodeId = g.NavWindow->RootWindow->DockNode->ID; + + // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace + ImGuiDockNode *central_node = node->CentralNode; + const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty(); + bool central_node_hole_register_hit_test_hole = central_node_hole; + if (central_node_hole) + if (const ImGuiPayload *payload = ImGui::GetDragDropPayload()) + if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow **)payload->Data)) + central_node_hole_register_hit_test_hole = false; + if (central_node_hole_register_hit_test_hole) + { + // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily. + // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen + // covering passthru node we'd have a gap on the edge not covered by the hole) + IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode + ImGuiDockNode *root_node = DockNodeGetRootNode(central_node); + ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size); + ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size); + if (hole_rect.Min.x > root_rect.Min.x) + { + hole_rect.Min.x += WINDOWS_HOVER_PADDING; + } + if (hole_rect.Max.x < root_rect.Max.x) + { + hole_rect.Max.x -= WINDOWS_HOVER_PADDING; + } + if (hole_rect.Min.y > root_rect.Min.y) + { + hole_rect.Min.y += WINDOWS_HOVER_PADDING; + } + if (hole_rect.Max.y < root_rect.Max.y) + { + hole_rect.Max.y -= WINDOWS_HOVER_PADDING; + } + // GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255)); + if (central_node_hole && !hole_rect.IsInverted()) + { + SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min); + if (host_window->ParentWindow) + SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min); + } + } + + // Update position/size, process and draw resizing splitters + if (node->IsRootNode() && host_window) + { + host_window->DrawList->ChannelsSetCurrent(1); + DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size); + DockNodeTreeUpdateSplitter(node); + } + + // Draw empty node background (currently can only be the Central Node) + if (host_window && node->IsEmpty() && node->IsVisible) + { + host_window->DrawList->ChannelsSetCurrent(0); + node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg); + if (node->LastBgColor != 0) + host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor); + node->IsBgDrawnThisFrame = true; + } + + // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set. + // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size + // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order! + const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0; + if (render_dockspace_bg && node->IsVisible) + { + host_window->DrawList->ChannelsSetCurrent(0); + if (central_node_hole) + RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f); + else + host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f); + } + + // Draw and populate Tab Bar + if (host_window) + host_window->DrawList->ChannelsSetCurrent(1); + if (host_window && node->Windows.Size > 0) + { + DockNodeUpdateTabBar(node, host_window); + } + else + { + node->WantCloseAll = false; + node->WantCloseTabId = 0; + node->IsFocused = false; + } + if (node->TabBar && node->TabBar->SelectedTabId) + node->SelectedTabId = node->TabBar->SelectedTabId; + else if (node->Windows.Size > 0) + node->SelectedTabId = node->Windows[0]->ID; + + // Draw payload drop target + if (host_window && node->IsVisible) + if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window)) + BeginDockableDragDropTarget(host_window); + + // We update this after DockNodeUpdateTabBar() + node->LastFrameActive = g.FrameCount; + + // Recurse into children + // FIXME-DOCK FIXME-OPT: Should not need to recurse into children + if (host_window) + { + if (node->ChildNodes[0]) + DockNodeUpdate(node->ChildNodes[0]); + if (node->ChildNodes[1]) + DockNodeUpdate(node->ChildNodes[1]); + + // Render outer borders last (after the tab bar) + if (node->IsRootNode()) + { + host_window->DrawList->ChannelsSetCurrent(1); + RenderWindowOuterBorders(host_window); + } + + // Further rendering (= hosted windows background) will be drawn on layer 0 + host_window->DrawList->ChannelsSetCurrent(0); + } + + // End host window + if (beginned_into_host_window) //-V1020 + End(); +} + +// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame. +static int IMGUI_CDECL TabItemComparerByDockOrder(const void *lhs, const void *rhs) +{ + ImGuiWindow *a = ((const ImGuiTabItem *)lhs)->Window; + ImGuiWindow *b = ((const ImGuiTabItem *)rhs)->Window; + if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder)) + return d; + return (a->BeginOrderWithinContext - b->BeginOrderWithinContext); +} + +static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode *node, ImGuiTabBar *tab_bar) +{ + // Try to position the menu so it is more likely to stays within the same viewport + ImGuiContext &g = *GImGui; + ImGuiID ret_tab_id = 0; + if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left) + SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f)); + else + SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f)); + if (BeginPopup("#WindowMenu")) + { + node->IsFocused = true; + if (tab_bar->Tabs.Size == 1) + { + if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar())) + node->WantHiddenTabBarToggle = true; + } + else + { + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem *tab = &tab_bar->Tabs[tab_n]; + if (tab->Flags & ImGuiTabItemFlags_Button) + continue; + if (Selectable(tab_bar->GetTabName(tab), tab->ID == tab_bar->SelectedTabId)) + ret_tab_id = tab->ID; + SameLine(); + Text(" "); + } + } + EndPopup(); + } + return ret_tab_id; +} + +// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button. +bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode *node) +{ + if (node->TabBar == NULL || node->HostWindow == NULL) + return false; + if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) + return false; + Begin(node->HostWindow->Name); + PushOverrideID(node->ID); + bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node); + IM_UNUSED(ret); + IM_ASSERT(ret); + return true; +} + +void ImGui::DockNodeEndAmendTabBar() +{ + EndTabBar(); + PopID(); + End(); +} + +// Submit the tab bar corresponding to a dock node and various housekeeping details. +static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode *node, ImGuiWindow *host_window) +{ + ImGuiContext &g = *GImGui; + ImGuiStyle &style = g.Style; + + const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount); + const bool closed_all = node->WantCloseAll && node_was_active; + const ImGuiID closed_one = node->WantCloseTabId && node_was_active; + node->WantCloseAll = false; + node->WantCloseTabId = 0; + + // Decide if we should use a focused title bar color + bool is_focused = false; + ImGuiDockNode *root_node = DockNodeGetRootNode(node); + if (g.NavWindowingTarget) + is_focused = (g.NavWindowingTarget->DockNode == node); + else if (g.NavWindow && g.NavWindow->RootWindowForTitleBarHighlight == host_window->RootWindowDockTree && root_node->LastFocusedNodeId == node->ID) + is_focused = true; + + // Hidden tab bar will show a triangle on the upper-left (in Begin) + if (node->IsHiddenTabBar() || node->IsNoTabBar()) + { + node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL; + node->IsFocused = is_focused; + if (is_focused) + node->LastFrameFocused = g.FrameCount; + if (node->VisibleWindow) + { + // Notify root of visible window (used to display title in OS task bar) + if (is_focused || root_node->VisibleWindow == NULL) + root_node->VisibleWindow = node->VisibleWindow; + if (node->TabBar) + node->TabBar->VisibleTabId = node->VisibleWindow->TabId; + } + return; + } + + // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed + bool backup_skip_item = host_window->SkipItems; + if (!node->IsDockSpace()) + { + host_window->SkipItems = false; + host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + } + + // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID. + // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs, + // as docked windows themselves will override the stack with their own root ID. + PushOverrideID(node->ID); + ImGuiTabBar *tab_bar = node->TabBar; + bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden + if (tab_bar == NULL) + { + DockNodeAddTabBar(node); + tab_bar = node->TabBar; + } + + ImGuiID focus_tab_id = 0; + node->IsFocused = is_focused; + + const ImGuiDockNodeFlags node_flags = node->MergedFlags; + const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None); + + // In a dock node, the Collapse Button turns into the Window Menu button. + // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes? + if (has_window_menu_button && IsPopupOpen("#WindowMenu")) + { + if (ImGuiID tab_id = DockNodeUpdateWindowMenu(node, tab_bar)) + focus_tab_id = tab_bar->NextSelectedTabId = tab_id; + is_focused |= node->IsFocused; + } + + // Layout + ImRect title_bar_rect, tab_bar_rect; + ImVec2 window_menu_button_pos; + ImVec2 close_button_pos; + DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos); + + // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value. + const int tabs_count_old = tab_bar->Tabs.Size; + for (int window_n = 0; window_n < node->Windows.Size; window_n++) + { + ImGuiWindow *window = node->Windows[window_n]; + if (TabBarFindTabByID(tab_bar, window->TabId) == NULL) + TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window); + } + + // Title bar + if (is_focused) + node->LastFrameFocused = g.FrameCount; + ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive + : ImGuiCol_TitleBg); + ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE); + host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags); + + // Docking/Collapse button + if (has_window_menu_button) + { + if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node) + OpenPopup("#WindowMenu"); + if (IsItemActive()) + focus_tab_id = tab_bar->SelectedTabId; + } + + // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value + int tabs_unsorted_start = tab_bar->Tabs.Size; + for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--) + { + // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? + tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted; + tabs_unsorted_start = tab_n; + } + if (tab_bar->Tabs.Size > tabs_unsorted_start) + { + IMGUI_DEBUG_LOG_DOCKING("In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : ""); + for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++) + IMGUI_DEBUG_LOG_DOCKING(" - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder); + if (tab_bar->Tabs.Size > tabs_unsorted_start + 1) + ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder); + } + + // Apply NavWindow focus back to the tab bar + if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node) + tab_bar->SelectedTabId = g.NavWindow->RootWindow->ID; + + // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated + if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL) + tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId; + else if (tab_bar->Tabs.Size > tabs_count_old) + tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId; + + // Begin tab bar + ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons); + tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode; + if (!host_window->Collapsed && is_focused) + tab_bar_flags |= ImGuiTabBarFlags_IsFocused; + BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node); + // host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255)); + + // Backup style colors + ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT]; + for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) + backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]]; + + // Submit actual tabs + node->VisibleWindow = NULL; + for (int window_n = 0; window_n < node->Windows.Size; window_n++) + { + ImGuiWindow *window = node->Windows[window_n]; + if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument)) + continue; + if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active) + { + ImGuiTabItemFlags tab_item_flags = 0; + tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet; + if (window->Flags & ImGuiWindowFlags_UnsavedDocument) + tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument; + if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) + tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; + + // Apply stored style overrides for the window + for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) + g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]); + + // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so) + bool tab_open = true; + TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window); + if (!tab_open) + node->WantCloseTabId = window->TabId; + if (tab_bar->VisibleTabId == window->TabId) + node->VisibleWindow = window; + + // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call + window->DockTabItemStatusFlags = g.LastItemData.StatusFlags; + window->DockTabItemRect = g.LastItemData.Rect; + + // Update navigation ID on menu layer + if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0) + host_window->NavLastIds[1] = window->TabId; + } + } + + // Restore style colors + for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) + g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n]; + + // Notify root of visible window (used to display title in OS task bar) + if (node->VisibleWindow) + if (is_focused || root_node->VisibleWindow == NULL) + root_node->VisibleWindow = node->VisibleWindow; + + // Close button (after VisibleWindow was updated) + // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId + const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton; + const bool close_button_is_visible = node->HasCloseButton; + // const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one) + if (close_button_is_visible) + { + if (!close_button_is_enabled) + { + PushItemFlag(ImGuiItemFlags_Disabled, true); + PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f, 1.0f, 1.0f, 0.4f)); + } + if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos)) + { + node->WantCloseAll = true; + for (int n = 0; n < tab_bar->Tabs.Size; n++) + TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]); + } + // if (IsItemActive()) + // focus_tab_id = tab_bar->SelectedTabId; + if (!close_button_is_enabled) + { + PopStyleColor(); + PopItemFlag(); + } + } + + // When clicking on the title bar outside of tabs, we still focus the selected tab for that node + // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) + ImGuiID title_bar_id = host_window->GetID("#TITLEBAR"); + if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id) + { + bool held; + ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap); + if (g.HoveredId == title_bar_id) + { + // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar, + // otherwise dragging window will steal HoveredId and amended tabs cannot get them. + g.LastItemData.ID = title_bar_id; + SetItemAllowOverlap(); + } + if (held) + { + if (IsMouseClicked(0)) + focus_tab_id = tab_bar->SelectedTabId; + + // Forward moving request to selected window + if (ImGuiTabItem *tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) + StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); + } + } + + // Forward focus from host node to selected window + // if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget) + // focus_tab_id = tab_bar->SelectedTabId; + + // When clicked on a tab we requested focus to the docked child + // This overrides the value set by "forward focus from host node to selected window". + if (tab_bar->NextSelectedTabId) + focus_tab_id = tab_bar->NextSelectedTabId; + + // Apply navigation focus + if (focus_tab_id != 0) + if (ImGuiTabItem *tab = TabBarFindTabByID(tab_bar, focus_tab_id)) + if (tab->Window) + { + FocusWindow(tab->Window); + NavInitWindow(tab->Window, false); + } + + EndTabBar(); + PopID(); + + // Restore SkipItems flag + if (!node->IsDockSpace()) + { + host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + host_window->SkipItems = backup_skip_item; + } +} + +static void ImGui::DockNodeAddTabBar(ImGuiDockNode *node) +{ + IM_ASSERT(node->TabBar == NULL); + node->TabBar = IM_NEW(ImGuiTabBar); +} + +static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode *node) +{ + if (node->TabBar == NULL) + return; + IM_DELETE(node->TabBar); + node->TabBar = NULL; +} + +static bool DockNodeIsDropAllowedOne(ImGuiWindow *payload, ImGuiWindow *host_window) +{ + if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext) + return false; + + ImGuiWindowClass *host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass; + ImGuiWindowClass *payload_class = &payload->WindowClass; + if (host_class->ClassId != payload_class->ClassId) + { + if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0) + return true; + if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0) + return true; + return false; + } + + // Prevent docking any window created above a popup + // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features), + // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test. + // But it would requires more work on our end because the dock host windows is technically created in NewFrame() + // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking. + ImGuiContext &g = *GImGui; + for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--) + if (ImGuiWindow *popup_window = g.OpenPopupStack[i].Window) + if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window)) // Payload is created from within a popup begin stack. + return false; + + return true; +} + +static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow *host_window, ImGuiWindow *root_payload) +{ + if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering + return true; + + const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1; + for (int payload_n = 0; payload_n < payload_count; payload_n++) + { + ImGuiWindow *payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload; + if (DockNodeIsDropAllowedOne(payload, host_window)) + return true; + } + return false; +} + +// window menu button == collapse button when not in a dock node. +// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code. +static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode *node, ImRect *out_title_rect, ImRect *out_tab_bar_rect, ImVec2 *out_window_menu_button_pos, ImVec2 *out_close_button_pos) +{ + ImGuiContext &g = *GImGui; + ImGuiStyle &style = g.Style; + + ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f); + if (out_title_rect) + { + *out_title_rect = r; + } + + r.Min.x += style.WindowBorderSize; + r.Max.x -= style.WindowBorderSize; + + float button_sz = g.FontSize; + + ImVec2 window_menu_button_pos = r.Min; + r.Min.x += style.FramePadding.x; + r.Max.x -= style.FramePadding.x; + if (node->HasCloseButton) + { + r.Max.x -= button_sz; + if (out_close_button_pos) + *out_close_button_pos = ImVec2(r.Max.x - style.FramePadding.x, r.Min.y); + } + if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left) + { + r.Min.x += button_sz + style.ItemInnerSpacing.x; + } + else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right) + { + r.Max.x -= button_sz + style.FramePadding.x; + window_menu_button_pos = ImVec2(r.Max.x, r.Min.y); + } + if (out_tab_bar_rect) + { + *out_tab_bar_rect = r; + } + if (out_window_menu_button_pos) + { + *out_window_menu_button_pos = window_menu_button_pos; + } +} + +void ImGui::DockNodeCalcSplitRects(ImVec2 &pos_old, ImVec2 &size_old, ImVec2 &pos_new, ImVec2 &size_new, ImGuiDir dir, ImVec2 size_new_desired) +{ + ImGuiContext &g = *GImGui; + const float dock_spacing = g.Style.ItemInnerSpacing.x; + const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; + pos_new[axis ^ 1] = pos_old[axis ^ 1]; + size_new[axis ^ 1] = size_old[axis ^ 1]; + + // Distribute size on given axis (with a desired size or equally) + const float w_avail = size_old[axis] - dock_spacing; + if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f) + { + size_new[axis] = size_new_desired[axis]; + size_old[axis] = IM_FLOOR(w_avail - size_new[axis]); + } + else + { + size_new[axis] = IM_FLOOR(w_avail * 0.5f); + size_old[axis] = IM_FLOOR(w_avail - size_new[axis]); + } + + // Position each node + if (dir == ImGuiDir_Right || dir == ImGuiDir_Down) + { + pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing; + } + else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up) + { + pos_new[axis] = pos_old[axis]; + pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing; + } +} + +// Retrieve the drop rectangles for a given direction or for the center + perform hit testing. +bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect &parent, ImGuiDir dir, ImRect &out_r, bool outer_docking, ImVec2 *test_mouse_pos) +{ + ImGuiContext &g = *GImGui; + + const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight()); + const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f)); + float hs_w; // Half-size, longer axis + float hs_h; // Half-size, smaller axis + ImVec2 off; // Distance from edge or center + if (outer_docking) + { + // hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f)); + // hs_h = ImFloor(hs_w * 0.15f); + // off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h)); + hs_w = ImFloor(hs_for_central_nodes * 1.50f); + hs_h = ImFloor(hs_for_central_nodes * 0.80f); + off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h)); + } + else + { + hs_w = ImFloor(hs_for_central_nodes); + hs_h = ImFloor(hs_for_central_nodes * 0.90f); + off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f)); + } + + ImVec2 c = ImFloor(parent.GetCenter()); + if (dir == ImGuiDir_None) + { + out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); + } + else if (dir == ImGuiDir_Up) + { + out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); + } + else if (dir == ImGuiDir_Down) + { + out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); + } + else if (dir == ImGuiDir_Left) + { + out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); + } + else if (dir == ImGuiDir_Right) + { + out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); + } + + if (test_mouse_pos == NULL) + return false; + + ImRect hit_r = out_r; + if (!outer_docking) + { + // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides + hit_r.Expand(ImFloor(hs_w * 0.30f)); + ImVec2 mouse_delta = (*test_mouse_pos - c); + float mouse_delta_len2 = ImLengthSqr(mouse_delta); + float r_threshold_center = hs_w * 1.4f; + float r_threshold_sides = hs_w * (1.4f + 1.2f); + if (mouse_delta_len2 < r_threshold_center * r_threshold_center) + return (dir == ImGuiDir_None); + if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides) + return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y)); + } + return hit_r.Contains(*test_mouse_pos); +} + +// host_node may be NULL if the window doesn't have a DockNode already. +// FIXME-DOCK: This is misnamed since it's also doing the filtering. +static void ImGui::DockNodePreviewDockSetup(ImGuiWindow *host_window, ImGuiDockNode *host_node, ImGuiWindow *root_payload, ImGuiDockPreviewData *data, bool is_explicit_target, bool is_outer_docking) +{ + ImGuiContext &g = *GImGui; + + // There is an edge case when docking into a dockspace which only has inactive nodes. + // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive. + // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference. + ImGuiDockNode *root_payload_as_host = root_payload->DockNodeAsHost; + ImGuiDockNode *ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node; + if (ref_node_for_rect) + IM_ASSERT(ref_node_for_rect->IsVisible); + + // Filter, figure out where we are allowed to dock + ImGuiDockNodeFlags src_node_flags = root_payload_as_host ? root_payload_as_host->MergedFlags : root_payload->WindowClass.DockNodeFlagsOverrideSet; + ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet; + data->IsCenterAvailable = true; + if (is_outer_docking) + data->IsCenterAvailable = false; + else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking) + data->IsCenterAvailable = false; + else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode()) + data->IsCenterAvailable = false; + else if ((!host_node || !host_node->IsEmpty()) && root_payload_as_host && root_payload_as_host->IsSplitNode() && (root_payload_as_host->OnlyNodeWithWindows == NULL)) // Is _visibly_ split? + data->IsCenterAvailable = false; + else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe) + data->IsCenterAvailable = false; + else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty())) + data->IsCenterAvailable = false; + else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty()) + data->IsCenterAvailable = false; + + data->IsSidesAvailable = true; + if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit) + data->IsSidesAvailable = false; + else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode()) + data->IsSidesAvailable = false; + else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)) + data->IsSidesAvailable = false; + + // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split) + data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (root_payload->HasCloseButton); + data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0); + data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos; + data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size; + + // Calculate drop shapes geometry for allowed splitting directions + IM_ASSERT(ImGuiDir_None == -1); + data->SplitNode = host_node; + data->SplitDir = ImGuiDir_None; + data->IsSplitDirExplicit = false; + if (!host_window->Collapsed) + for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++) + { + if (dir == ImGuiDir_None && !data->IsCenterAvailable) + continue; + if (dir != ImGuiDir_None && !data->IsSidesAvailable) + continue; + if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir + 1], is_outer_docking, &g.IO.MousePos)) + { + data->SplitDir = (ImGuiDir)dir; + data->IsSplitDirExplicit = true; + } + } + + // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar + data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable); + if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift) + data->IsDropAllowed = false; + + // Calculate split area + data->SplitRatio = 0.0f; + if (data->SplitDir != ImGuiDir_None) + { + ImGuiDir split_dir = data->SplitDir; + ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; + ImVec2 pos_new, pos_old = data->FutureNode.Pos; + ImVec2 size_new, size_old = data->FutureNode.Size; + DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, root_payload->Size); + + // Calculate split ratio so we can pass it down the docking request + float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]); + data->FutureNode.Pos = pos_new; + data->FutureNode.Size = size_new; + data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio); + } +} + +static void ImGui::DockNodePreviewDockRender(ImGuiWindow *host_window, ImGuiDockNode *host_node, ImGuiWindow *root_payload, const ImGuiDockPreviewData *data) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes + + // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent. + // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes. + const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload; + + // In case the two windows involved are on different viewports, we will draw the overlay on each of them. + int overlay_draw_lists_count = 0; + ImDrawList *overlay_draw_lists[2]; + overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport); + if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload) + overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport); + + // Draw main preview rectangle + const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f); + const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f); + const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f); + const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f); + + // Display area preview + const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0); + if (data->IsDropAllowed) + { + ImRect overlay_rect = data->FutureNode.Rect(); + if (data->SplitDir == ImGuiDir_None && can_preview_tabs) + overlay_rect.Min.y += GetFrameHeight(); + if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable) + for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) + overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE)); + } + + // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read) + if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable) + { + // Compute target tab bar geometry so we can locate our preview tabs + ImRect tab_bar_rect; + DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL); + ImVec2 tab_pos = tab_bar_rect.Min; + if (host_node && host_node->TabBar) + { + if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar()) + tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission. + else + tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]->Name, host_node->Windows[0]->HasCloseButton).x; + } + else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost)) + { + tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window->Name, host_window->HasCloseButton).x; // Account for slight offset which will be added when changing from title bar to tab bar + } + + // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows) + if (root_payload->DockNodeAsHost) + IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size); + ImGuiTabBar *tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL; + const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1; + for (int payload_n = 0; payload_n < payload_count; payload_n++) + { + // DockNode's TabBar may have non-window Tabs manually appended by user + ImGuiWindow *payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload; + if (tab_bar_with_payload && payload_window == NULL) + continue; + if (!DockNodeIsDropAllowedOne(payload_window, host_window)) + continue; + + // Calculate the tab bounding box for each payload window + ImVec2 tab_size = TabItemCalcSize(payload_window->Name, payload_window->HasCloseButton); + ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y); + tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x; + const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]); + const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]); + PushStyleColor(ImGuiCol_Text, overlay_col_text); + for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) + { + ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0); + if (!tab_bar_rect.Contains(tab_bb)) + overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max); + TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs); + TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL); + if (!tab_bar_rect.Contains(tab_bb)) + overlay_draw_lists[overlay_n]->PopClipRect(); + } + PopStyleColor(); + } + } + + // Display drop boxes + const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding); + for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++) + { + if (!data->DropRectsDraw[dir + 1].IsInverted()) + { + ImRect draw_r = data->DropRectsDraw[dir + 1]; + ImRect draw_r_in = draw_r; + draw_r_in.Expand(-2.0f); + ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop; + for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) + { + ImVec2 center = ImFloor(draw_r_in.GetCenter()); + overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding); + overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding); + if (dir == ImGuiDir_Left || dir == ImGuiDir_Right) + overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines); + if (dir == ImGuiDir_Up || dir == ImGuiDir_Down) + overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines); + } + } + + // Stop after ImGuiDir_None + if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit) + return; + } +} + +//----------------------------------------------------------------------------- +// Docking: ImGuiDockNode Tree manipulation functions +//----------------------------------------------------------------------------- +// - DockNodeTreeSplit() +// - DockNodeTreeMerge() +// - DockNodeTreeUpdatePosSize() +// - DockNodeTreeUpdateSplitterFindTouchingNode() +// - DockNodeTreeUpdateSplitter() +// - DockNodeTreeFindFallbackLeafNode() +// - DockNodeTreeFindNodeByPos() +//----------------------------------------------------------------------------- + +void ImGui::DockNodeTreeSplit(ImGuiContext *ctx, ImGuiDockNode *parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode *new_node) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(split_axis != ImGuiAxis_None); + + ImGuiDockNode *child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0); + child_0->ParentNode = parent_node; + + ImGuiDockNode *child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0); + child_1->ParentNode = parent_node; + + ImGuiDockNode *child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1; + DockNodeMoveChildNodes(child_inheritor, parent_node); + parent_node->ChildNodes[0] = child_0; + parent_node->ChildNodes[1] = child_1; + parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow; + parent_node->SplitAxis = split_axis; + parent_node->VisibleWindow = NULL; + parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode; + + float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE); + size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f); + IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting. + child_0->SizeRef = child_1->SizeRef = parent_node->Size; + child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio); + child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]); + + DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node); + DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID); + DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node)); + DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size); + + // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property) + child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; + child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; + child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_; + parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; + child_0->UpdateMergedFlags(); + child_1->UpdateMergedFlags(); + parent_node->UpdateMergedFlags(); + if (child_inheritor->IsCentralNode()) + DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor; +} + +void ImGui::DockNodeTreeMerge(ImGuiContext *ctx, ImGuiDockNode *parent_node, ImGuiDockNode *merge_lead_child) +{ + // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL. + ImGuiDockNode *child_0 = parent_node->ChildNodes[0]; + ImGuiDockNode *child_1 = parent_node->ChildNodes[1]; + IM_ASSERT(child_0 || child_1); + IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1); + if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0)) + { + IM_ASSERT(parent_node->TabBar == NULL); + IM_ASSERT(parent_node->Windows.Size == 0); + } + IMGUI_DEBUG_LOG_DOCKING("DockNodeTreeMerge 0x%08X & 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID); + + ImVec2 backup_last_explicit_size = parent_node->SizeRef; + DockNodeMoveChildNodes(parent_node, merge_lead_child); + if (child_0) + { + DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows + DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID); + } + if (child_1) + { + DockNodeMoveWindows(parent_node, child_1); + DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID); + } + DockNodeApplyPosSizeToWindows(parent_node); + parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto; + parent_node->VisibleWindow = merge_lead_child->VisibleWindow; + parent_node->SizeRef = backup_last_explicit_size; + + // Flags transfer + parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag + parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; + parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; + parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows + parent_node->UpdateMergedFlags(); + + if (child_0) + { + ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL); + IM_DELETE(child_0); + } + if (child_1) + { + ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL); + IM_DELETE(child_1); + } +} + +// Update Pos/Size for a node hierarchy (don't affect child Windows yet) +// (Depth-first, Pre-Order) +void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode *node, ImVec2 pos, ImVec2 size, ImGuiDockNode *only_write_to_single_node) +{ + // During the regular dock node update we write to all nodes. + // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away. + const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node; + if (write_to_node) + { + node->Pos = pos; + node->Size = size; + } + + if (node->IsLeafNode()) + return; + + ImGuiDockNode *child_0 = node->ChildNodes[0]; + ImGuiDockNode *child_1 = node->ChildNodes[1]; + ImVec2 child_0_pos = pos, child_1_pos = pos; + ImVec2 child_0_size = size, child_1_size = size; + + const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0)); + const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1)); + const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node; + const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node; + + if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible) + { + ImGuiContext &g = *GImGui; + const float spacing = DOCKING_SPLITTER_SIZE; + const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis; + const float size_avail = ImMax(size[axis] - spacing, 0.0f); + + // Size allocation policy + // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows. + const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f); + + // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing. + // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImFloor() + // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce + + // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge) + if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce) + { + child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]); + child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); + IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); + } + else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce) + { + child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]); + child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]); + IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); + } + else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce) + { + // FIXME-DOCK: We cannot honor the requested size, so apply ratio. + // Currently this path will only be taken if code programmatically sets WantLockSizeOnce + float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]); + child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * split_ratio); + child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); + IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); + } + + // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node + else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild) + { + child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]); + child_1_size[axis] = (size_avail - child_0_size[axis]); + } + else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild) + { + child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]); + child_0_size[axis] = (size_avail - child_1_size[axis]); + } + else + { + // 4) Otherwise distribute according to the relative ratio of each SizeRef value + float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]); + child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5f)); + child_1_size[axis] = (size_avail - child_0_size[axis]); + } + + child_1_pos[axis] += spacing + child_0_size[axis]; + } + + if (only_write_to_single_node == NULL) + child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false; + + const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible; + const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible; + if (child_0_recurse) + DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size); + if (child_1_recurse) + DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size); +} + +static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode *node, ImGuiAxis axis, int side, ImVector *touching_nodes) +{ + if (node->IsLeafNode()) + { + touching_nodes->push_back(node); + return; + } + if (node->ChildNodes[0]->IsVisible) + if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible) + DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes); + if (node->ChildNodes[1]->IsVisible) + if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible) + DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes); +} + +// (Depth-First, Pre-Order) +void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode *node) +{ + if (node->IsLeafNode()) + return; + + ImGuiContext &g = *GImGui; + + ImGuiDockNode *child_0 = node->ChildNodes[0]; + ImGuiDockNode *child_1 = node->ChildNodes[1]; + if (child_0->IsVisible && child_1->IsVisible) + { + // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally) + const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis; + IM_ASSERT(axis != ImGuiAxis_None); + ImRect bb; + bb.Min = child_0->Pos; + bb.Max = child_1->Pos; + bb.Min[axis] += child_0->Size[axis]; + bb.Max[axis ^ 1] += child_1->Size[axis ^ 1]; + // if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255)); + + const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs + const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY; + if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag)) + { + ImGuiWindow *window = g.CurrentWindow; + window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding); + } + else + { + // bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node. + // bb.Max[axis] -= 1; + PushID(node->ID); + + // Find resizing limits by gathering list of nodes that are touching the splitter line. + ImVector touching_nodes[2]; + float min_size = g.Style.WindowMinSize[axis]; + float resize_limits[2]; + resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size; + resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size; + + ImGuiID splitter_id = GetID("##Splitter"); + if (g.ActiveId == splitter_id) // Only process when splitter is active + { + DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]); + DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]); + for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++) + resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size); + for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++) + resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size); + + // [DEBUG] Render touching nodes & limits + /* + ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport()); + for (int n = 0; n < 2; n++) + { + for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++) + draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255)); + if (axis == ImGuiAxis_X) + draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f); + else + draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f); + } + */ + } + + // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters + float cur_size_0 = child_0->Size[axis]; + float cur_size_1 = child_1->Size[axis]; + float min_size_0 = resize_limits[0] - child_0->Pos[axis]; + float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1]; + ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg); + if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col)) + { + if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0) + { + child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0; + child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis]; + child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1; + + // Lock the size of every node that is a sibling of the node we are touching + // This might be less desirable if we can merge sibling of a same axis into the same parental level. + for (int side_n = 0; side_n < 2; side_n++) + for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++) + { + ImGuiDockNode *touching_node = touching_nodes[side_n][touching_node_n]; + // ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport()); + // draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255)); + while (touching_node->ParentNode != node) + { + if (touching_node->ParentNode->SplitAxis == axis) + { + // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize(). + ImGuiDockNode *node_to_preserve = touching_node->ParentNode->ChildNodes[side_n]; + node_to_preserve->WantLockSizeOnce = true; + // draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255)); + // draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100)); + } + touching_node = touching_node->ParentNode; + } + } + + DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size); + DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size); + MarkIniSettingsDirty(); + } + } + PopID(); + } + } + + if (child_0->IsVisible) + DockNodeTreeUpdateSplitter(child_0); + if (child_1->IsVisible) + DockNodeTreeUpdateSplitter(child_1); +} + +ImGuiDockNode *ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode *node) +{ + if (node->IsLeafNode()) + return node; + if (ImGuiDockNode *leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0])) + return leaf_node; + if (ImGuiDockNode *leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1])) + return leaf_node; + return NULL; +} + +ImGuiDockNode *ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode *node, ImVec2 pos) +{ + if (!node->IsVisible) + return NULL; + + const float dock_spacing = 0.0f; // g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE? + ImRect r(node->Pos, node->Pos + node->Size); + r.Expand(dock_spacing * 0.5f); + bool inside = r.Contains(pos); + if (!inside) + return NULL; + + if (node->IsLeafNode()) + return node; + if (ImGuiDockNode *hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos)) + return hovered_node; + if (ImGuiDockNode *hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos)) + return hovered_node; + + return NULL; +} + +//----------------------------------------------------------------------------- +// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) +//----------------------------------------------------------------------------- +// - SetWindowDock() [Internal] +// - DockSpace() +// - DockSpaceOverViewport() +//----------------------------------------------------------------------------- + +// [Internal] Called via SetNextWindowDockID() +void ImGui::SetWindowDock(ImGuiWindow *window, ImGuiID dock_id, ImGuiCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowDockAllowFlags & cond) == 0) + return; + window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); + + if (window->DockId == dock_id) + return; + + // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot + ImGuiContext *ctx = GImGui; + if (ImGuiDockNode *new_node = DockContextFindNodeByID(ctx, dock_id)) + if (new_node->IsSplitNode()) + { + // Policy: Find central node or latest focused node. We first move back to our root node. + new_node = DockNodeGetRootNode(new_node); + if (new_node->CentralNode) + { + IM_ASSERT(new_node->CentralNode->IsCentralNode()); + dock_id = new_node->CentralNode->ID; + } + else + { + dock_id = new_node->LastFocusedNodeId; + } + } + + if (window->DockId == dock_id) + return; + + if (window->DockNode) + DockNodeRemoveWindow(window->DockNode, window, 0); + window->DockId = dock_id; +} + +// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default. +// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors. +// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app. +ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2 &size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass *window_class) +{ + ImGuiContext *ctx = GImGui; + ImGuiContext &g = *ctx; + ImGuiWindow *window = GetCurrentWindow(); + if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) + return 0; + + // Early out if parent window is hidden/collapsed + // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960. + // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true. + if (window->SkipItems) + flags |= ImGuiDockNodeFlags_KeepAliveOnly; + + IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0); + IM_ASSERT(id != 0); + ImGuiDockNode *node = DockContextFindNodeByID(ctx, id); + if (!node) + { + IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X created\n", id); + node = DockContextAddNode(ctx, id); + node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode); + } + if (window_class && window_class->ClassId != node->WindowClass.ClassId) + IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId); + node->SharedFlags = flags; + node->WindowClass = window_class ? *window_class : ImGuiWindowClass(); + + // When a DockSpace transitioned form implicit to explicit this may be called a second time + // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again. + if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly)) + { + IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID"); + node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace); + return id; + } + node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace); + + // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible + if (flags & ImGuiDockNodeFlags_KeepAliveOnly) + { + node->LastFrameAlive = g.FrameCount; + return id; + } + + const ImVec2 content_avail = GetContentRegionAvail(); + ImVec2 size = ImFloor(size_arg); + if (size.x <= 0.0f) + size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues) + if (size.y <= 0.0f) + size.y = ImMax(content_avail.y + size.y, 4.0f); + IM_ASSERT(size.x > 0.0f && size.y > 0.0f); + + node->Pos = window->DC.CursorPos; + node->Size = node->SizeRef = size; + SetNextWindowPos(node->Pos); + SetNextWindowSize(node->Size); + g.NextWindowData.PosUndock = false; + + // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window? + // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented) + ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost; + window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar; + window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; + window_flags |= ImGuiWindowFlags_NoBackground; + + char title[256]; + ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id); + + PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f); + Begin(title, NULL, window_flags); + PopStyleVar(); + + ImGuiWindow *host_window = g.CurrentWindow; + DockNodeSetupHostWindow(node, host_window); + host_window->ChildId = window->GetID(title); + node->OnlyNodeWithWindows = NULL; + + IM_ASSERT(node->IsRootNode()); + + // We need to handle the rare case were a central node is missing. + // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace. + // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split. + // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining. + // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property, + // as it doesn't make sense for an empty dockspace to not have this property. + if (node->IsLeafNode() && !node->IsCentralNode()) + node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode); + + // Update the node + DockNodeUpdate(node); + + End(); + ItemSize(size); + return id; +} + +// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode! +// The limitation with this call is that your window won't have a menu bar. +// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function. +// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it. +ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport *viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass *window_class) +{ + if (viewport == NULL) + viewport = GetMainViewport(); + + SetNextWindowPos(viewport->WorkPos); + SetNextWindowSize(viewport->WorkSize); + SetNextWindowViewport(viewport->ID); + + ImGuiWindowFlags host_window_flags = 0; + host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking; + host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; + if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) + host_window_flags |= ImGuiWindowFlags_NoBackground; + + char label[32]; + ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID); + + PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + Begin(label, NULL, host_window_flags); + PopStyleVar(3); + + ImGuiID dockspace_id = GetID("DockSpace"); + DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class); + End(); + + return dockspace_id; +} + +//----------------------------------------------------------------------------- +// Docking: Builder Functions +//----------------------------------------------------------------------------- +// Very early end-user API to manipulate dock nodes. +// Only available in imgui_internal.h. Expect this API to change/break! +// It is expected that those functions are all called _before_ the dockspace node submission. +//----------------------------------------------------------------------------- +// - DockBuilderDockWindow() +// - DockBuilderGetNode() +// - DockBuilderSetNodePos() +// - DockBuilderSetNodeSize() +// - DockBuilderAddNode() +// - DockBuilderRemoveNode() +// - DockBuilderRemoveNodeChildNodes() +// - DockBuilderRemoveNodeDockedWindows() +// - DockBuilderSplitNode() +// - DockBuilderCopyNodeRec() +// - DockBuilderCopyNode() +// - DockBuilderCopyWindowSettings() +// - DockBuilderCopyDockSpace() +// - DockBuilderFinish() +//----------------------------------------------------------------------------- + +void ImGui::DockBuilderDockWindow(const char *window_name, ImGuiID node_id) +{ + // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1) + ImGuiID window_id = ImHashStr(window_name); + if (ImGuiWindow *window = FindWindowByID(window_id)) + { + // Apply to created window + SetWindowDock(window, node_id, ImGuiCond_Always); + window->DockOrder = -1; + } + else + { + // Apply to settings + ImGuiWindowSettings *settings = FindWindowSettings(window_id); + if (settings == NULL) + settings = CreateNewWindowSettings(window_name); + settings->DockId = node_id; + settings->DockOrder = -1; + } +} + +ImGuiDockNode *ImGui::DockBuilderGetNode(ImGuiID node_id) +{ + ImGuiContext *ctx = GImGui; + return DockContextFindNodeByID(ctx, node_id); +} + +void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos) +{ + ImGuiContext *ctx = GImGui; + ImGuiDockNode *node = DockContextFindNodeByID(ctx, node_id); + if (node == NULL) + return; + node->Pos = pos; + node->AuthorityForPos = ImGuiDataAuthority_DockNode; +} + +void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size) +{ + ImGuiContext *ctx = GImGui; + ImGuiDockNode *node = DockContextFindNodeByID(ctx, node_id); + if (node == NULL) + return; + IM_ASSERT(size.x > 0.0f && size.y > 0.0f); + node->Size = node->SizeRef = size; + node->AuthorityForSize = ImGuiDataAuthority_DockNode; +} + +// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node! +// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node. +// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary. +// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand! +// For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect. +// - Use (id == 0) to let the system allocate a node identifier. +// - Existing node with a same id will be removed. +ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) +{ + ImGuiContext *ctx = GImGui; + + if (id != 0) + DockBuilderRemoveNode(id); + + ImGuiDockNode *node = NULL; + if (flags & ImGuiDockNodeFlags_DockSpace) + { + DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly); + node = DockContextFindNodeByID(ctx, id); + } + else + { + node = DockContextAddNode(ctx, id); + node->SetLocalFlags(flags); + } + node->LastFrameAlive = ctx->FrameCount; // Set this otherwise BeginDocked will undock during the same frame. + return node->ID; +} + +void ImGui::DockBuilderRemoveNode(ImGuiID node_id) +{ + ImGuiContext *ctx = GImGui; + ImGuiDockNode *node = DockContextFindNodeByID(ctx, node_id); + if (node == NULL) + return; + DockBuilderRemoveNodeDockedWindows(node_id, true); + DockBuilderRemoveNodeChildNodes(node_id); + // Node may have moved or deleted if e.g. any merge happened + node = DockContextFindNodeByID(ctx, node_id); + if (node == NULL) + return; + if (node->IsCentralNode() && node->ParentNode) + node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode); + DockContextRemoveNode(ctx, node, true); +} + +// root_id = 0 to remove all, root_id != 0 to remove child of given node. +void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) +{ + ImGuiContext *ctx = GImGui; + ImGuiDockContext *dc = &ctx->DockContext; + + ImGuiDockNode *root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL; + if (root_id && root_node == NULL) + return; + bool has_central_node = false; + + ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto; + ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto; + + // Process active windows + ImVector nodes_to_remove; + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode *node = (ImGuiDockNode *)dc->Nodes.Data[n].val_p) + { + bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id); + if (want_removal) + { + if (node->IsCentralNode()) + has_central_node = true; + if (root_id != 0) + DockContextQueueNotifyRemovedNode(ctx, node); + if (root_node) + { + DockNodeMoveWindows(root_node, node); + DockSettingsRenameNodeReferences(node->ID, root_node->ID); + } + nodes_to_remove.push_back(node); + } + } + + // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge) + // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead) + if (root_node) + { + root_node->AuthorityForPos = backup_root_node_authority_for_pos; + root_node->AuthorityForSize = backup_root_node_authority_for_size; + } + + // Apply to settings + for (ImGuiWindowSettings *settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings)) + if (ImGuiID window_settings_dock_id = settings->DockId) + for (int n = 0; n < nodes_to_remove.Size; n++) + if (nodes_to_remove[n]->ID == window_settings_dock_id) + { + settings->DockId = root_id; + break; + } + + // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes + if (nodes_to_remove.Size > 1) + ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode *), DockNodeComparerDepthMostFirst); + for (int n = 0; n < nodes_to_remove.Size; n++) + DockContextRemoveNode(ctx, nodes_to_remove[n], false); + + if (root_id == 0) + { + dc->Nodes.Clear(); + dc->Requests.clear(); + } + else if (has_central_node) + { + root_node->CentralNode = root_node; + root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode); + } +} + +void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs) +{ + // Clear references in settings + ImGuiContext *ctx = GImGui; + ImGuiContext &g = *ctx; + if (clear_settings_refs) + { + for (ImGuiWindowSettings *settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + { + bool want_removal = (root_id == 0) || (settings->DockId == root_id); + if (!want_removal && settings->DockId != 0) + if (ImGuiDockNode *node = DockContextFindNodeByID(ctx, settings->DockId)) + if (DockNodeGetRootNode(node)->ID == root_id) + want_removal = true; + if (want_removal) + settings->DockId = 0; + } + } + + // Clear references in windows + for (int n = 0; n < g.Windows.Size; n++) + { + ImGuiWindow *window = g.Windows[n]; + bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id); + if (want_removal) + { + const ImGuiID backup_dock_id = window->DockId; + IM_UNUSED(backup_dock_id); + DockContextProcessUndockWindow(ctx, window, clear_settings_refs); + if (!clear_settings_refs) + IM_ASSERT(window->DockId == backup_dock_id); + } + } +} + +// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created. +// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set. +// FIXME-DOCK: We are not exposing nor using split_outer. +ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID *out_id_at_dir, ImGuiID *out_id_at_opposite_dir) +{ + ImGuiContext *ctx = GImGui; + IM_ASSERT(split_dir != ImGuiDir_None); + IMGUI_DEBUG_LOG_DOCKING("DockBuilderSplitNode node 0x%08X, split_dir %d\n", id, split_dir); + + ImGuiDockNode *node = DockContextFindNodeByID(ctx, id); + if (node == NULL) + { + IM_ASSERT(node != NULL); + return 0; + } + + IM_ASSERT(!node->IsSplitNode()); // Assert if already Split + + ImGuiDockRequest req; + req.Type = ImGuiDockRequestType_Split; + req.DockTargetWindow = NULL; + req.DockTargetNode = node; + req.DockPayload = NULL; + req.DockSplitDir = split_dir; + req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir); + req.DockSplitOuter = false; + DockContextProcessDock(ctx, &req); + + ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID; + ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID; + if (out_id_at_dir) + *out_id_at_dir = id_at_dir; + if (out_id_at_opposite_dir) + *out_id_at_opposite_dir = id_at_opposite_dir; + return id_at_dir; +} + +static ImGuiDockNode *DockBuilderCopyNodeRec(ImGuiDockNode *src_node, ImGuiID dst_node_id_if_known, ImVector *out_node_remap_pairs) +{ + ImGuiContext *ctx = GImGui; + ImGuiDockNode *dst_node = ImGui::DockContextAddNode(ctx, dst_node_id_if_known); + dst_node->SharedFlags = src_node->SharedFlags; + dst_node->LocalFlags = src_node->LocalFlags; + dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None; + dst_node->Pos = src_node->Pos; + dst_node->Size = src_node->Size; + dst_node->SizeRef = src_node->SizeRef; + dst_node->SplitAxis = src_node->SplitAxis; + dst_node->UpdateMergedFlags(); + + out_node_remap_pairs->push_back(src_node->ID); + out_node_remap_pairs->push_back(dst_node->ID); + + for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++) + if (src_node->ChildNodes[child_n]) + { + dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs); + dst_node->ChildNodes[child_n]->ParentNode = dst_node; + } + + IMGUI_DEBUG_LOG_DOCKING("Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0); + return dst_node; +} + +void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector *out_node_remap_pairs) +{ + ImGuiContext *ctx = GImGui; + IM_ASSERT(src_node_id != 0); + IM_ASSERT(dst_node_id != 0); + IM_ASSERT(out_node_remap_pairs != NULL); + + DockBuilderRemoveNode(dst_node_id); + + ImGuiDockNode *src_node = DockContextFindNodeByID(ctx, src_node_id); + IM_ASSERT(src_node != NULL); + + out_node_remap_pairs->clear(); + DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs); + + IM_ASSERT((out_node_remap_pairs->Size % 2) == 0); +} + +void ImGui::DockBuilderCopyWindowSettings(const char *src_name, const char *dst_name) +{ + ImGuiWindow *src_window = FindWindowByName(src_name); + if (src_window == NULL) + return; + if (ImGuiWindow *dst_window = FindWindowByName(dst_name)) + { + dst_window->Pos = src_window->Pos; + dst_window->Size = src_window->Size; + dst_window->SizeFull = src_window->SizeFull; + dst_window->Collapsed = src_window->Collapsed; + } + else if (ImGuiWindowSettings *dst_settings = FindOrCreateWindowSettings(dst_name)) + { + ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos); + if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID) + { + dst_settings->ViewportPos = window_pos_2ih; + dst_settings->ViewportId = src_window->ViewportId; + dst_settings->Pos = ImVec2ih(0, 0); + } + else + { + dst_settings->Pos = window_pos_2ih; + } + dst_settings->Size = ImVec2ih(src_window->SizeFull); + dst_settings->Collapsed = src_window->Collapsed; + } +} + +// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed. +void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector *in_window_remap_pairs) +{ + IM_ASSERT(src_dockspace_id != 0); + IM_ASSERT(dst_dockspace_id != 0); + IM_ASSERT(in_window_remap_pairs != NULL); + IM_ASSERT((in_window_remap_pairs->Size % 2) == 0); + + // Duplicate entire dock + // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart, + // whereas we could attempt to at least keep them together in a new, same floating node. + ImVector node_remap_pairs; + DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs); + + // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes + // (The windows associated to src_dockspace_id are staying in place) + ImVector src_windows; + for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2) + { + const char *src_window_name = (*in_window_remap_pairs)[remap_window_n]; + const char *dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1]; + ImGuiID src_window_id = ImHashStr(src_window_name); + src_windows.push_back(src_window_id); + + // Search in the remapping tables + ImGuiID src_dock_id = 0; + if (ImGuiWindow *src_window = FindWindowByID(src_window_id)) + src_dock_id = src_window->DockId; + else if (ImGuiWindowSettings *src_window_settings = FindWindowSettings(src_window_id)) + src_dock_id = src_window_settings->DockId; + ImGuiID dst_dock_id = 0; + for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2) + if (node_remap_pairs[dock_remap_n] == src_dock_id) + { + dst_dock_id = node_remap_pairs[dock_remap_n + 1]; + // node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear + break; + } + + if (dst_dock_id != 0) + { + // Docked windows gets redocked into the new node hierarchy. + IMGUI_DEBUG_LOG_DOCKING("Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id); + DockBuilderDockWindow(dst_window_name, dst_dock_id); + } + else + { + // Floating windows gets their settings transferred (regardless of whether the new window already exist or not) + // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together? + IMGUI_DEBUG_LOG_DOCKING("Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name); + DockBuilderCopyWindowSettings(src_window_name, dst_window_name); + } + } + + // Anything else in the source nodes of 'node_remap_pairs' are windows that were docked in src_dockspace_id but are not owned by it (unaffiliated windows, e.g. "ImGui Demo") + // Find those windows and move to them to the cloned dock node. This may be optional? + for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2) + if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n]) + { + ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1]; + ImGuiDockNode *node = DockBuilderGetNode(src_dock_id); + for (int window_n = 0; window_n < node->Windows.Size; window_n++) + { + ImGuiWindow *window = node->Windows[window_n]; + if (src_windows.contains(window->ID)) + continue; + + // Docked windows gets redocked into the new node hierarchy. + IMGUI_DEBUG_LOG_DOCKING("Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id); + DockBuilderDockWindow(window->Name, dst_dock_id); + } + } +} + +// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node. +void ImGui::DockBuilderFinish(ImGuiID root_id) +{ + ImGuiContext *ctx = GImGui; + // DockContextRebuild(ctx); + DockContextBuildAddWindowsToNodes(ctx, root_id); +} + +//----------------------------------------------------------------------------- +// Docking: Begin/End Support Functions (called from Begin/End) +//----------------------------------------------------------------------------- +// - GetWindowAlwaysWantOwnTabBar() +// - DockContextBindNodeToWindow() +// - BeginDocked() +// - BeginDockableDragDropSource() +// - BeginDockableDragDropTarget() +//----------------------------------------------------------------------------- + +bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar) + if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0) + if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise + return true; + return false; +} + +static ImGuiDockNode *ImGui::DockContextBindNodeToWindow(ImGuiContext *ctx, ImGuiWindow *window) +{ + ImGuiContext &g = *ctx; + ImGuiDockNode *node = DockContextFindNodeByID(ctx, window->DockId); + IM_ASSERT(window->DockNode == NULL); + + // We should not be docking into a split node (SetWindowDock should avoid this) + if (node && node->IsSplitNode()) + { + DockContextProcessUndockWindow(ctx, window); + return NULL; + } + + // Create node + if (node == NULL) + { + node = DockContextAddNode(ctx, window->DockId); + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; + node->LastFrameAlive = g.FrameCount; + } + + // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, + // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node). + // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout. + // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame. + if (!node->IsVisible) + { + ImGuiDockNode *ancestor_node = node; + while (!ancestor_node->IsVisible && ancestor_node->ParentNode) + ancestor_node = ancestor_node->ParentNode; + IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f); + DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node)); + DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node); + } + + // Add window to node + bool node_was_visible = node->IsVisible; + DockNodeAddWindow(node, window, true); + node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see) + IM_ASSERT(node == window->DockNode); + return node; +} + +void ImGui::BeginDocked(ImGuiWindow *window, bool *p_open) +{ + ImGuiContext *ctx = GImGui; + ImGuiContext &g = *ctx; + + // Clear fields ahead so most early-out paths don't have to do it + window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false; + + const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window); + if (auto_dock_node) + { + if (window->DockId == 0) + { + IM_ASSERT(window->DockNode == NULL); + window->DockId = DockContextGenNodeID(ctx); + } + } + else + { + // Calling SetNextWindowPos() undock windows by default (by setting PosUndock) + bool want_undock = false; + want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0; + want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock; + if (want_undock) + { + DockContextProcessUndockWindow(ctx, window); + return; + } + } + + // Bind to our dock node + ImGuiDockNode *node = window->DockNode; + if (node != NULL) + IM_ASSERT(window->DockId == node->ID); + if (window->DockId != 0 && node == NULL) + { + node = DockContextBindNodeToWindow(ctx, window); + if (node == NULL) + return; + } + +#if 0 + // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set + if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode)) + { + DockContextProcessUndockWindow(ctx, window); + return; + } +#endif + + // Undock if our dockspace node disappeared + // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly. + if (node->LastFrameAlive < g.FrameCount) + { + // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking() + ImGuiDockNode *root_node = DockNodeGetRootNode(node); + if (root_node->LastFrameAlive < g.FrameCount) + DockContextProcessUndockWindow(ctx, window); + else + window->DockIsActive = true; + return; + } + + // Store style overrides + for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) + window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]); + + // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window, + // and never create neither a host window neither a tab bar. + // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test) + if (node->HostWindow == NULL) + { + if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing) + window->DockIsActive = true; + if (node->Windows.Size > 1) + DockNodeHideWindowDuringHostWindowCreation(window); + return; + } + + // We can have zero-sized nodes (e.g. children of a small-size dockspace) + IM_ASSERT(node->HostWindow); + IM_ASSERT(node->IsLeafNode()); + IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f); + node->State = ImGuiDockNodeState_HostWindowVisible; + + // Undock if we are submitted earlier than the host window + if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext) + { + DockContextProcessUndockWindow(ctx, window); + return; + } + + // Position/Size window + SetNextWindowPos(node->Pos); + SetNextWindowSize(node->Size); + g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos() + window->DockIsActive = true; + window->DockNodeIsVisible = true; + window->DockTabIsVisible = false; + if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) + return; + + // When the window is selected we mark it as visible. + if (node->VisibleWindow == window) + window->DockTabIsVisible = true; + + // Update window flag + IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0); + window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize; + if (node->IsHiddenTabBar() || node->IsNoTabBar()) + window->Flags |= ImGuiWindowFlags_NoTitleBar; + else + window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed! + + // Save new dock order only if the window has been visible once already + // This allows multiple windows to be created in the same frame and have their respective dock orders preserved. + if (node->TabBar && window->WasActive) + window->DockOrder = (short)DockNodeGetTabOrder(window); + + if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL) + *p_open = false; + + // Update ChildId to allow returning from Child to Parent with Escape + ImGuiWindow *parent_window = window->DockNode->HostWindow; + window->ChildId = parent_window->GetID(window->Name); +} + +void ImGui::BeginDockableDragDropSource(ImGuiWindow *window) +{ + ImGuiContext &g = *GImGui; + IM_ASSERT(g.ActiveId == window->MoveId); + IM_ASSERT(g.MovingWindow == window); + IM_ASSERT(g.CurrentWindow == window); + + g.LastItemData.ID = window->MoveId; + window = window->RootWindowDockTree; + IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); + bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit + if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload)) + { + SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window)); + EndDragDropSource(); + + // Store style overrides + for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) + window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]); + } +} + +void ImGui::BeginDockableDragDropTarget(ImGuiWindow *window) +{ + ImGuiContext *ctx = GImGui; + ImGuiContext &g = *ctx; + + // IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace + IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); + if (!g.DragDropActive) + return; + // GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + if (!BeginDragDropTargetCustom(window->Rect(), window->ID)) + return; + + // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering + // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly) + const ImGuiPayload *payload = &g.DragDropPayload; + if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow **)payload->Data)) + { + EndDragDropTarget(); + return; + } + + ImGuiWindow *payload_window = *(ImGuiWindow **)payload->Data; + if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + { + // Select target node + // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation) + bool dock_into_floating_window = false; + ImGuiDockNode *node = NULL; + if (window->DockNodeAsHost) + { + // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos(). + node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos); + + // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active) + // In this case we need to fallback into any leaf mode, possibly the central node. + // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. + if (node && node->IsDockSpace() && node->IsRootNode()) + node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node); + } + else + { + if (window->DockNode) + node = window->DockNode; + else + dock_into_floating_window = true; // Dock into a regular window + } + + const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); + const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max); + + // Preview docking request and find out split direction/ratio + // const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window. + const bool do_preview = payload->IsPreview() || payload->IsDelivery(); + if (do_preview && (node != NULL || dock_into_floating_window)) + { + ImGuiDockPreviewData split_inner; + ImGuiDockPreviewData split_outer; + ImGuiDockPreviewData *split_data = &split_inner; + if (node && (node->ParentNode || node->IsCentralNode())) + if (ImGuiDockNode *root_node = DockNodeGetRootNode(node)) + { + DockNodePreviewDockSetup(window, root_node, payload_window, &split_outer, is_explicit_target, true); + if (split_outer.IsSplitDirExplicit) + split_data = &split_outer; + } + DockNodePreviewDockSetup(window, node, payload_window, &split_inner, is_explicit_target, false); + if (split_data == &split_outer) + split_inner.IsDropAllowed = false; + + // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes + DockNodePreviewDockRender(window, node, payload_window, &split_inner); + DockNodePreviewDockRender(window, node, payload_window, &split_outer); + + // Queue docking request + if (split_data->IsDropAllowed && payload->IsDelivery()) + DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer); + } + } + EndDragDropTarget(); +} + +//----------------------------------------------------------------------------- +// Docking: Settings +//----------------------------------------------------------------------------- +// - DockSettingsRenameNodeReferences() +// - DockSettingsRemoveNodeReferences() +// - DockSettingsFindNodeSettings() +// - DockSettingsHandler_ApplyAll() +// - DockSettingsHandler_ReadOpen() +// - DockSettingsHandler_ReadLine() +// - DockSettingsHandler_DockNodeToSettings() +// - DockSettingsHandler_WriteAll() +//----------------------------------------------------------------------------- + +static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id) +{ + ImGuiContext &g = *GImGui; + IMGUI_DEBUG_LOG_DOCKING("DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id); + for (int window_n = 0; window_n < g.Windows.Size; window_n++) + { + ImGuiWindow *window = g.Windows[window_n]; + if (window->DockId == old_node_id && window->DockNode == NULL) + window->DockId = new_node_id; + } + //// FIXME-OPT: We could remove this loop by storing the index in the map + for (ImGuiWindowSettings *settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->DockId == old_node_id) + settings->DockId = new_node_id; +} + +// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings +static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID *node_ids, int node_ids_count) +{ + ImGuiContext &g = *GImGui; + int found = 0; + //// FIXME-OPT: We could remove this loop by storing the index in the map + for (ImGuiWindowSettings *settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + for (int node_n = 0; node_n < node_ids_count; node_n++) + if (settings->DockId == node_ids[node_n]) + { + settings->DockId = 0; + settings->DockOrder = -1; + if (++found < node_ids_count) + break; + return; + } +} + +static ImGuiDockNodeSettings *ImGui::DockSettingsFindNodeSettings(ImGuiContext *ctx, ImGuiID id) +{ + // FIXME-OPT + ImGuiDockContext *dc = &ctx->DockContext; + for (int n = 0; n < dc->NodesSettings.Size; n++) + if (dc->NodesSettings[n].ID == id) + return &dc->NodesSettings[n]; + return NULL; +} + +// Clear settings data +static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext *ctx, ImGuiSettingsHandler *) +{ + ImGuiDockContext *dc = &ctx->DockContext; + dc->NodesSettings.clear(); + DockContextClearNodes(ctx, 0, true); +} + +// Recreate nodes based on settings data +static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext *ctx, ImGuiSettingsHandler *) +{ + // Prune settings at boot time only + ImGuiDockContext *dc = &ctx->DockContext; + if (ctx->Windows.Size == 0) + DockContextPruneUnusedSettingsNodes(ctx); + DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); + DockContextBuildAddWindowsToNodes(ctx, 0); +} + +static void *ImGui::DockSettingsHandler_ReadOpen(ImGuiContext *, ImGuiSettingsHandler *, const char *name) +{ + if (strcmp(name, "Data") != 0) + return NULL; + return (void *)1; +} + +static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext *ctx, ImGuiSettingsHandler *, void *, const char *line) +{ + char c = 0; + int x = 0, y = 0; + int r = 0; + + // Parsing, e.g. + // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 " + // " DockNode ID=0x00000002 Parent=0x00000001 " + // Important: this code expect currently fields in a fixed order. + ImGuiDockNodeSettings node; + line = ImStrSkipBlank(line); + if (strncmp(line, "DockNode", 8) == 0) + { + line = ImStrSkipBlank(line + strlen("DockNode")); + } + else if (strncmp(line, "DockSpace", 9) == 0) + { + line = ImStrSkipBlank(line + strlen("DockSpace")); + node.Flags |= ImGuiDockNodeFlags_DockSpace; + } + else + return; + if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) + { + line += r; + } + else + return; + if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) + { + line += r; + if (node.ParentNodeId == 0) + return; + } + if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) == 1) + { + line += r; + if (node.ParentWindowId == 0) + return; + } + if (node.ParentNodeId == 0) + { + if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) + { + line += r; + node.Pos = ImVec2ih((short)x, (short)y); + } + else + return; + if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) + { + line += r; + node.Size = ImVec2ih((short)x, (short)y); + } + else + return; + } + else + { + if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) + { + line += r; + node.SizeRef = ImVec2ih((short)x, (short)y); + } + } + if (sscanf(line, " Split=%c%n", &c, &r) == 1) + { + line += r; + if (c == 'X') + node.SplitAxis = ImGuiAxis_X; + else if (c == 'Y') + node.SplitAxis = ImGuiAxis_Y; + } + if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) + { + line += r; + if (x != 0) + node.Flags |= ImGuiDockNodeFlags_NoResize; + } + if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) + { + line += r; + if (x != 0) + node.Flags |= ImGuiDockNodeFlags_CentralNode; + } + if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) + { + line += r; + if (x != 0) + node.Flags |= ImGuiDockNodeFlags_NoTabBar; + } + if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) + { + line += r; + if (x != 0) + node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; + } + if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) + { + line += r; + if (x != 0) + node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; + } + if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) + { + line += r; + if (x != 0) + node.Flags |= ImGuiDockNodeFlags_NoCloseButton; + } + if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId, &r) == 1) + { + line += r; + } + if (node.ParentNodeId != 0) + if (ImGuiDockNodeSettings *parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId)) + node.Depth = parent_settings->Depth + 1; + ctx->DockContext.NodesSettings.push_back(node); +} + +static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext *dc, ImGuiDockNode *node, int depth) +{ + ImGuiDockNodeSettings node_settings; + IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3))); + node_settings.ID = node->ID; + node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0; + node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0; + node_settings.SelectedTabId = node->SelectedTabId; + node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None); + node_settings.Depth = (char)depth; + node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_); + node_settings.Pos = ImVec2ih(node->Pos); + node_settings.Size = ImVec2ih(node->Size); + node_settings.SizeRef = ImVec2ih(node->SizeRef); + dc->NodesSettings.push_back(node_settings); + if (node->ChildNodes[0]) + DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1); + if (node->ChildNodes[1]) + DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1); +} + +static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext *ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf) +{ + ImGuiContext &g = *ctx; + ImGuiDockContext *dc = &ctx->DockContext; + if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) + return; + + // Gather settings data + // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer) + dc->NodesSettings.resize(0); + dc->NodesSettings.reserve(dc->Nodes.Data.Size); + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode *node = (ImGuiDockNode *)dc->Nodes.Data[n].val_p) + if (node->IsRootNode()) + DockSettingsHandler_DockNodeToSettings(dc, node, 0); + + int max_depth = 0; + for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) + max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth); + + // Write to text buffer + buf->appendf("[%s][Data]\n", handler->TypeName); + for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) + { + const int line_start_pos = buf->size(); + (void)line_start_pos; + const ImGuiDockNodeSettings *node_settings = &dc->NodesSettings[node_n]; + buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file + buf->appendf(" ID=0x%08X", node_settings->ID); + if (node_settings->ParentNodeId) + { + buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y); + } + else + { + if (node_settings->ParentWindowId) + buf->appendf(" Window=0x%08X", node_settings->ParentWindowId); + buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y); + } + if (node_settings->SplitAxis != ImGuiAxis_None) + buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y'); + if (node_settings->Flags & ImGuiDockNodeFlags_NoResize) + buf->appendf(" NoResize=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode) + buf->appendf(" CentralNode=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar) + buf->appendf(" NoTabBar=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar) + buf->appendf(" HiddenTabBar=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton) + buf->appendf(" NoWindowMenuButton=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton) + buf->appendf(" NoCloseButton=1"); + if (node_settings->SelectedTabId) + buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId); + +#if IMGUI_DEBUG_INI_SETTINGS + // [DEBUG] Include comments in the .ini file to ease debugging + if (ImGuiDockNode *node = DockContextFindNodeByID(ctx, node_settings->ID)) + { + buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything + if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) + buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name); + // Iterate settings so we can give info about windows that didn't exist during the session. + int contains_window = 0; + for (ImGuiWindowSettings *settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->DockId == node_settings->ID) + { + if (contains_window++ == 0) + buf->appendf(" ; contains "); + buf->appendf("'%s' ", settings->GetName()); + } + } +#endif + buf->appendf("\n"); + } + buf->appendf("\n"); +} + +//----------------------------------------------------------------------------- +// [SECTION] PLATFORM DEPENDENT HELPERS +//----------------------------------------------------------------------------- + +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) + +#ifdef _MSC_VER +#pragma comment(lib, "user32") +#pragma comment(lib, "kernel32") +#endif + +// Win32 clipboard implementation +// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown() +static const char *GetClipboardTextFn_DefaultImpl(void *) +{ + ImGuiContext &g = *GImGui; + g.ClipboardHandlerData.clear(); + if (!::OpenClipboard(NULL)) + return NULL; + HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT); + if (wbuf_handle == NULL) + { + ::CloseClipboard(); + return NULL; + } + if (const WCHAR *wbuf_global = (const WCHAR *)::GlobalLock(wbuf_handle)) + { + int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL); + g.ClipboardHandlerData.resize(buf_len); + ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL); + } + ::GlobalUnlock(wbuf_handle); + ::CloseClipboard(); + return g.ClipboardHandlerData.Data; +} + +static void SetClipboardTextFn_DefaultImpl(void *, const char *text) +{ + if (!::OpenClipboard(NULL)) + return; + const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0); + HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR)); + if (wbuf_handle == NULL) + { + ::CloseClipboard(); + return; + } + WCHAR *wbuf_global = (WCHAR *)::GlobalLock(wbuf_handle); + ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length); + ::GlobalUnlock(wbuf_handle); + ::EmptyClipboard(); + if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL) + ::GlobalFree(wbuf_handle); + ::CloseClipboard(); +} + +#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS) + +#include // Use old API to avoid need for separate .mm file +static PasteboardRef main_clipboard = 0; + +// OSX clipboard implementation +// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line! +static void SetClipboardTextFn_DefaultImpl(void *, const char *text) +{ + if (!main_clipboard) + PasteboardCreate(kPasteboardClipboard, &main_clipboard); + PasteboardClear(main_clipboard); + CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)text, strlen(text)); + if (cf_data) + { + PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0); + CFRelease(cf_data); + } +} + +static const char *GetClipboardTextFn_DefaultImpl(void *) +{ + if (!main_clipboard) + PasteboardCreate(kPasteboardClipboard, &main_clipboard); + PasteboardSynchronize(main_clipboard); + + ItemCount item_count = 0; + PasteboardGetItemCount(main_clipboard, &item_count); + for (ItemCount i = 0; i < item_count; i++) + { + PasteboardItemID item_id = 0; + PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id); + CFArrayRef flavor_type_array = 0; + PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array); + for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++) + { + CFDataRef cf_data; + if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr) + { + ImGuiContext &g = *GImGui; + g.ClipboardHandlerData.clear(); + int length = (int)CFDataGetLength(cf_data); + g.ClipboardHandlerData.resize(length + 1); + CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8 *)g.ClipboardHandlerData.Data); + g.ClipboardHandlerData[length] = 0; + CFRelease(cf_data); + return g.ClipboardHandlerData.Data; + } + } + } + return NULL; +} + +#else + +// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers. +static const char *GetClipboardTextFn_DefaultImpl(void *) +{ + ImGuiContext &g = *GImGui; + return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin(); +} + +static void SetClipboardTextFn_DefaultImpl(void *, const char *text) +{ + ImGuiContext &g = *GImGui; + g.ClipboardHandlerData.clear(); + const char *text_end = text + strlen(text); + g.ClipboardHandlerData.resize((int)(text_end - text) + 1); + memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text)); + g.ClipboardHandlerData[(int)(text_end - text)] = 0; +} + +#endif + +// Win32 API IME support (for Asian languages, etc.) +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) + +#include +#ifdef _MSC_VER +#pragma comment(lib, "imm32") +#endif + +static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport *viewport, ImGuiPlatformImeData *data) +{ + // Notify OS Input Method Editor of text input position + HWND hwnd = (HWND)viewport->PlatformHandleRaw; +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if (hwnd == 0) + hwnd = (HWND)ImGui::GetIO().ImeWindowHandle; +#endif + if (hwnd == 0) + return; + + ::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0); + + if (HIMC himc = ::ImmGetContext(hwnd)) + { + COMPOSITIONFORM composition_form = {}; + composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x); + composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y); + composition_form.dwStyle = CFS_FORCE_POSITION; + ::ImmSetCompositionWindow(himc, &composition_form); + CANDIDATEFORM candidate_form = {}; + candidate_form.dwStyle = CFS_CANDIDATEPOS; + candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x); + candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y); + ::ImmSetCandidateWindow(himc, &candidate_form); + ::ImmReleaseContext(hwnd, himc); + } +} + +#else + +static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport *, ImGuiPlatformImeData *) +{ +} + +#endif + +//----------------------------------------------------------------------------- +// [SECTION] METRICS/DEBUGGER WINDOW +//----------------------------------------------------------------------------- +// - RenderViewportThumbnail() [Internal] +// - RenderViewportsThumbnails() [Internal] +// - DebugTextEncoding() +// - MetricsHelpMarker() [Internal] +// - ShowFontAtlas() [Internal] +// - ShowMetricsWindow() +// - DebugNodeColumns() [Internal] +// - DebugNodeDockNode() [Internal] +// - DebugNodeDrawList() [Internal] +// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal] +// - DebugNodeFont() [Internal] +// - DebugNodeFontGlyph() [Internal] +// - DebugNodeStorage() [Internal] +// - DebugNodeTabBar() [Internal] +// - DebugNodeViewport() [Internal] +// - DebugNodeWindow() [Internal] +// - DebugNodeWindowSettings() [Internal] +// - DebugNodeWindowsList() [Internal] +// - DebugNodeWindowsListByBeginStackParent() [Internal] +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_METRICS_WINDOW + +void ImGui::DebugRenderViewportThumbnail(ImDrawList *draw_list, ImGuiViewportP *viewport, const ImRect &bb) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + ImVec2 scale = bb.GetSize() / viewport->Size; + ImVec2 off = bb.Min - viewport->Pos * scale; + float alpha_mul = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f; + window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f)); + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow *thumb_window = g.Windows[i]; + if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow)) + continue; + if (thumb_window->Viewport != viewport) + continue; + + ImRect thumb_r = thumb_window->Rect(); + ImRect title_r = thumb_window->TitleBarRect(); + thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off + thumb_r.Max * scale)); + title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off + ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0, 5)); // Exaggerate title bar height + thumb_r.ClipWithFull(bb); + title_r.ClipWithFull(bb); + const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight); + window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul)); + window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul)); + window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul)); + window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name)); + } + draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul)); +} + +static void RenderViewportsThumbnails() +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + + // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports. + float SCALE = 1.0f / 8.0f; + ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); + for (int n = 0; n < g.Viewports.Size; n++) + bb_full.Add(g.Viewports[n]->GetMainRect()); + ImVec2 p = window->DC.CursorPos; + ImVec2 off = p - bb_full.Min * SCALE; + for (int n = 0; n < g.Viewports.Size; n++) + { + ImGuiViewportP *viewport = g.Viewports[n]; + ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE); + ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb); + } + ImGui::Dummy(bb_full.GetSize() * SCALE); +} + +static int IMGUI_CDECL ViewportComparerByFrontMostStampCount(const void *lhs, const void *rhs) +{ + const ImGuiViewportP *a = *(const ImGuiViewportP *const *)lhs; + const ImGuiViewportP *b = *(const ImGuiViewportP *const *)rhs; + return b->LastFrontMostStampCount - a->LastFrontMostStampCount; +} + +// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct. +void ImGui::DebugTextEncoding(const char *str) +{ + Text("Text: \"%s\"", str); + if (!BeginTable("list", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit)) + return; + TableSetupColumn("Offset"); + TableSetupColumn("UTF-8"); + TableSetupColumn("Glyph"); + TableSetupColumn("Codepoint"); + TableHeadersRow(); + for (const char *p = str; *p != 0;) + { + unsigned int c; + const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL); + TableNextColumn(); + Text("%d", (int)(p - str)); + TableNextColumn(); + for (int byte_index = 0; byte_index < c_utf8_len; byte_index++) + { + if (byte_index > 0) + SameLine(); + Text("0x%02X", (int)(unsigned char)p[byte_index]); + } + TableNextColumn(); + if (GetFont()->FindGlyphNoFallback((ImWchar)c)) + TextUnformatted(p, p + c_utf8_len); + else + TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]"); + TableNextColumn(); + Text("U+%04X", (int)c); + p += c_utf8_len; + } + EndTable(); +} + +// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds. +static void MetricsHelpMarker(const char *desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +// [DEBUG] List fonts in a font atlas and display its texture +void ImGui::ShowFontAtlas(ImFontAtlas *atlas) +{ + for (int i = 0; i < atlas->Fonts.Size; i++) + { + ImFont *font = atlas->Fonts[i]; + PushID(font); + DebugNodeFont(font); + PopID(); + } + if (TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) + { + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); + Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col); + TreePop(); + } +} + +void ImGui::ShowMetricsWindow(bool *p_open) +{ + ImGuiContext &g = *GImGui; + ImGuiIO &io = g.IO; + ImGuiMetricsConfig *cfg = &g.DebugMetricsConfig; + if (cfg->ShowStackTool) + ShowStackToolWindow(&cfg->ShowStackTool); + + if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1) + { + End(); + return; + } + + // Basic info + Text("Dear ImGui %s", GetVersion()); + Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); + Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations); + // SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; } + + Separator(); + + // Debugging enums + enum + { + WRT_OuterRect, + WRT_OuterRectClipped, + WRT_InnerRect, + WRT_InnerClipRect, + WRT_WorkRect, + WRT_Content, + WRT_ContentIdeal, + WRT_ContentRegionRect, + WRT_Count + }; // Windows Rect Type + const char *wrt_rects_names[WRT_Count] = {"OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect"}; + enum + { + TRT_OuterRect, + TRT_InnerRect, + TRT_WorkRect, + TRT_HostClipRect, + TRT_InnerClipRect, + TRT_BackgroundClipRect, + TRT_ColumnsRect, + TRT_ColumnsWorkRect, + TRT_ColumnsClipRect, + TRT_ColumnsContentHeadersUsed, + TRT_ColumnsContentHeadersIdeal, + TRT_ColumnsContentFrozen, + TRT_ColumnsContentUnfrozen, + TRT_Count + }; // Tables Rect Type + const char *trt_rects_names[TRT_Count] = {"OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen"}; + if (cfg->ShowWindowsRectsType < 0) + cfg->ShowWindowsRectsType = WRT_WorkRect; + if (cfg->ShowTablesRectsType < 0) + cfg->ShowTablesRectsType = TRT_WorkRect; + + struct Funcs + { + static ImRect GetTableRect(ImGuiTable *table, int rect_type, int n) + { + ImGuiTableInstanceData *table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance + if (rect_type == TRT_OuterRect) + { + return table->OuterRect; + } + else if (rect_type == TRT_InnerRect) + { + return table->InnerRect; + } + else if (rect_type == TRT_WorkRect) + { + return table->WorkRect; + } + else if (rect_type == TRT_HostClipRect) + { + return table->HostClipRect; + } + else if (rect_type == TRT_InnerClipRect) + { + return table->InnerClipRect; + } + else if (rect_type == TRT_BackgroundClipRect) + { + return table->BgClipRect; + } + else if (rect_type == TRT_ColumnsRect) + { + ImGuiTableColumn *c = &table->Columns[n]; + return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); + } + else if (rect_type == TRT_ColumnsWorkRect) + { + ImGuiTableColumn *c = &table->Columns[n]; + return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); + } + else if (rect_type == TRT_ColumnsClipRect) + { + ImGuiTableColumn *c = &table->Columns[n]; + return c->ClipRect; + } + else if (rect_type == TRT_ColumnsContentHeadersUsed) + { + ImGuiTableColumn *c = &table->Columns[n]; + return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); + } // Note: y1/y2 not always accurate + else if (rect_type == TRT_ColumnsContentHeadersIdeal) + { + ImGuiTableColumn *c = &table->Columns[n]; + return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); + } + else if (rect_type == TRT_ColumnsContentFrozen) + { + ImGuiTableColumn *c = &table->Columns[n]; + return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); + } + else if (rect_type == TRT_ColumnsContentUnfrozen) + { + ImGuiTableColumn *c = &table->Columns[n]; + return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); + } + IM_ASSERT(0); + return ImRect(); + } + + static ImRect GetWindowRect(ImGuiWindow *window, int rect_type) + { + if (rect_type == WRT_OuterRect) + { + return window->Rect(); + } + else if (rect_type == WRT_OuterRectClipped) + { + return window->OuterRectClipped; + } + else if (rect_type == WRT_InnerRect) + { + return window->InnerRect; + } + else if (rect_type == WRT_InnerClipRect) + { + return window->InnerClipRect; + } + else if (rect_type == WRT_WorkRect) + { + return window->WorkRect; + } + else if (rect_type == WRT_Content) + { + ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; + return ImRect(min, min + window->ContentSize); + } + else if (rect_type == WRT_ContentIdeal) + { + ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; + return ImRect(min, min + window->ContentSizeIdeal); + } + else if (rect_type == WRT_ContentRegionRect) + { + return window->ContentRegionRect; + } + IM_ASSERT(0); + return ImRect(); + } + }; + + // Tools + if (TreeNode("Tools")) + { + bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer"); + SameLine(); + MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct."); + if (show_encoding_viewer) + { + static char buf[100] = ""; + SetNextItemWidth(-FLT_MIN); + InputText("##Text", buf, IM_ARRAYSIZE(buf)); + if (buf[0] != 0) + DebugTextEncoding(buf); + TreePop(); + } + + // Stack Tool is your best friend! + Checkbox("Show stack tool", &cfg->ShowStackTool); + SameLine(); + MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code."); + + Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder); + Checkbox("Show windows rectangles", &cfg->ShowWindowsRects); + SameLine(); + SetNextItemWidth(GetFontSize() * 12); + cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count); + if (cfg->ShowWindowsRects && g.NavWindow != NULL) + { + BulletText("'%s':", g.NavWindow->Name); + Indent(); + for (int rect_n = 0; rect_n < WRT_Count; rect_n++) + { + ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n); + Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]); + } + Unindent(); + } + + Checkbox("Show tables rectangles", &cfg->ShowTablesRects); + SameLine(); + SetNextItemWidth(GetFontSize() * 12); + cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count); + if (cfg->ShowTablesRects && g.NavWindow != NULL) + { + for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++) + { + ImGuiTable *table = g.Tables.TryGetMapData(table_n); + if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow)) + continue; + + BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name); + if (IsItemHovered()) + GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); + Indent(); + char buf[128]; + for (int rect_n = 0; rect_n < TRT_Count; rect_n++) + { + if (rect_n >= TRT_ColumnsRect) + { + if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect) + continue; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImRect r = Funcs::GetTableRect(table, rect_n, column_n); + ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]); + Selectable(buf); + if (IsItemHovered()) + GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); + } + } + else + { + ImRect r = Funcs::GetTableRect(table, rect_n, -1); + ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]); + Selectable(buf); + if (IsItemHovered()) + GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f); + } + } + Unindent(); + } + } + + // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted. + if (Button("Item Picker..")) + DebugStartItemPicker(); + SameLine(); + MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash."); + + TreePop(); + } + + // Windows + if (TreeNode("Windows", "Windows (%d)", g.Windows.Size)) + { + // SetNextItemOpen(true, ImGuiCond_Once); + DebugNodeWindowsList(&g.Windows, "By display order"); + DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)"); + if (TreeNode("By submission order (begin stack)")) + { + // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship! + ImVector &temp_buffer = g.WindowsTempSortBuffer; + temp_buffer.resize(0); + for (int i = 0; i < g.Windows.Size; i++) + if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount) + temp_buffer.push_back(g.Windows[i]); + struct Func + { + static int IMGUI_CDECL WindowComparerByBeginOrder(const void *lhs, const void *rhs) { return ((int)(*(const ImGuiWindow *const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow *const *)rhs)->BeginOrderWithinContext); } + }; + ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow *), Func::WindowComparerByBeginOrder); + DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL); + TreePop(); + } + + TreePop(); + } + + // DrawLists + int drawlist_count = 0; + for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++) + drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount(); + if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count)) + { + Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh); + Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes); + for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++) + { + ImGuiViewportP *viewport = g.Viewports[viewport_i]; + bool viewport_has_drawlist = false; + for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++) + for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++) + { + if (!viewport_has_drawlist) + Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID); + viewport_has_drawlist = true; + DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList"); + } + } + TreePop(); + } + + // Viewports + if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size)) + { + Indent(GetTreeNodeToLabelSpacing()); + RenderViewportsThumbnails(); + Unindent(GetTreeNodeToLabelSpacing()); + + bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size); + SameLine(); + MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors."); + if (open) + { + for (int i = 0; i < g.PlatformIO.Monitors.Size; i++) + { + const ImGuiPlatformMonitor &mon = g.PlatformIO.Monitors[i]; + BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)", + i, mon.DpiScale * 100.0f, + mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y, + mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y); + } + TreePop(); + } + + BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0); + if (TreeNode("Inferred Z order (front-to-back)")) + { + static ImVector viewports; + viewports.resize(g.Viewports.Size); + memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes()); + if (viewports.Size > 1) + ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport *), ViewportComparerByFrontMostStampCount); + for (int i = 0; i < viewports.Size; i++) + BulletText("Viewport #%d, ID: 0x%08X, FrontMostStampCount = %08d, Window: \"%s\"", viewports[i]->Idx, viewports[i]->ID, viewports[i]->LastFrontMostStampCount, viewports[i]->Window ? viewports[i]->Window->Name : "N/A"); + TreePop(); + } + + for (int i = 0; i < g.Viewports.Size; i++) + DebugNodeViewport(g.Viewports[i]); + TreePop(); + } + + // Details for Popups + if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) + { + for (int i = 0; i < g.OpenPopupStack.Size; i++) + { + ImGuiWindow *window = g.OpenPopupStack[i].Window; + BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); + } + TreePop(); + } + + // Details for TabBars + if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount())) + { + for (int n = 0; n < g.TabBars.GetMapSize(); n++) + if (ImGuiTabBar *tab_bar = g.TabBars.TryGetMapData(n)) + { + PushID(tab_bar); + DebugNodeTabBar(tab_bar, "TabBar"); + PopID(); + } + TreePop(); + } + + // Details for Tables + if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount())) + { + for (int n = 0; n < g.Tables.GetMapSize(); n++) + if (ImGuiTable *table = g.Tables.TryGetMapData(n)) + DebugNodeTable(table); + TreePop(); + } + + // Details for Fonts + ImFontAtlas *atlas = g.IO.Fonts; + if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size)) + { + ShowFontAtlas(atlas); + TreePop(); + } + + // Details for Docking +#ifdef IMGUI_HAS_DOCK + if (TreeNode("Docking")) + { + static bool root_nodes_only = true; + ImGuiDockContext *dc = &g.DockContext; + Checkbox("List root nodes", &root_nodes_only); + Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes); + if (SmallButton("Clear nodes")) + { + DockContextClearNodes(&g, 0, true); + } + SameLine(); + if (SmallButton("Rebuild all")) + { + dc->WantFullRebuild = true; + } + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode *node = (ImGuiDockNode *)dc->Nodes.Data[n].val_p) + if (!root_nodes_only || node->IsRootNode()) + DebugNodeDockNode(node, "Node"); + TreePop(); + } +#endif // #ifdef IMGUI_HAS_DOCK + + // Settings + if (TreeNode("Settings")) + { + if (SmallButton("Clear")) + ClearIniSettings(); + SameLine(); + if (SmallButton("Save to memory")) + SaveIniSettingsToMemory(); + SameLine(); + if (SmallButton("Save to disk")) + SaveIniSettingsToDisk(g.IO.IniFilename); + SameLine(); + if (g.IO.IniFilename) + Text("\"%s\"", g.IO.IniFilename); + else + TextUnformatted(""); + Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer); + if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) + { + for (int n = 0; n < g.SettingsHandlers.Size; n++) + BulletText("%s", g.SettingsHandlers[n].TypeName); + TreePop(); + } + if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) + { + for (ImGuiWindowSettings *settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + DebugNodeWindowSettings(settings); + TreePop(); + } + + if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) + { + for (ImGuiTableSettings *settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + DebugNodeTableSettings(settings); + TreePop(); + } + +#ifdef IMGUI_HAS_DOCK + if (TreeNode("SettingsDocking", "Settings packed data: Docking")) + { + ImGuiDockContext *dc = &g.DockContext; + Text("In SettingsWindows:"); + for (ImGuiWindowSettings *settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->DockId != 0) + BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId); + Text("In SettingsNodes:"); + for (int n = 0; n < dc->NodesSettings.Size; n++) + { + ImGuiDockNodeSettings *settings = &dc->NodesSettings[n]; + const char *selected_tab_name = NULL; + if (settings->SelectedTabId) + { + if (ImGuiWindow *window = FindWindowByID(settings->SelectedTabId)) + selected_tab_name = window->Name; + else if (ImGuiWindowSettings *window_settings = FindWindowSettings(settings->SelectedTabId)) + selected_tab_name = window_settings->GetName(); + } + BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" + : ""); + } + TreePop(); + } +#endif // #ifdef IMGUI_HAS_DOCK + + if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) + { + InputTextMultiline("##Ini", (char *)(void *)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly); + TreePop(); + } + TreePop(); + } + + // Misc Details + if (TreeNode("Internal state")) + { + Text("WINDOWING"); + Indent(); + Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); + Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL"); + Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); + Text("HoveredDockNode: 0x%08X", g.HoveredDockNode ? g.HoveredDockNode->ID : 0); + Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); + Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0); + Unindent(); + + Text("ITEMS"); + Indent(); + Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource)); + Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); + + int active_id_using_key_input_count = 0; + for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++) + active_id_using_key_input_count += g.ActiveIdUsingKeyInputMask[n] ? 1 : 0; + Text("ActiveIdUsing: Wheel: %d, NavDirMask: %X, NavInputMask: %X, KeyInputMask: %d key(s)", g.ActiveIdUsingMouseWheel, g.ActiveIdUsingNavDirMask, g.ActiveIdUsingNavInputMask, active_id_using_key_input_count); + Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame + Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); + Unindent(); + + Text("NAV,FOCUS"); + Indent(); + Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); + Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); + Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource)); + Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); + Text("NavActivateId/DownId/PressedId/InputId: %08X/%08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId, g.NavActivateInputId); + Text("NavActivateFlags: %04X", g.NavActivateFlags); + Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover); + Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId); + Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL"); + Unindent(); + + TreePop(); + } + + // Overlay: Display windows Rectangles and Begin Order + if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder) + { + for (int n = 0; n < g.Windows.Size; n++) + { + ImGuiWindow *window = g.Windows[n]; + if (!window->WasActive) + continue; + ImDrawList *draw_list = GetForegroundDrawList(window); + if (cfg->ShowWindowsRects) + { + ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType); + draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); + } + if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow)) + { + char buf[32]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext); + float font_size = GetFontSize(); + draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255)); + draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf); + } + } + } + + // Overlay: Display Tables Rectangles + if (cfg->ShowTablesRects) + { + for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++) + { + ImGuiTable *table = g.Tables.TryGetMapData(table_n); + if (table == NULL || table->LastFrameActive < g.FrameCount - 1) + continue; + ImDrawList *draw_list = GetForegroundDrawList(table->OuterWindow); + if (cfg->ShowTablesRectsType >= TRT_ColumnsRect) + { + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n); + ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255); + float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f; + draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness); + } + } + else + { + ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1); + draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); + } + } + } + +#ifdef IMGUI_HAS_DOCK + // Overlay: Display Docking info + if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.HoveredDockNode) + { + char buf[64] = ""; + char *p = buf; + ImGuiDockNode *node = g.HoveredDockNode; + ImDrawList *overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport()); + p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : ""); + p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId); + p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y); + p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y); + int depth = DockNodeGetDepth(node); + overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255)); + ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth; + overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255)); + overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf); + } +#endif // #ifdef IMGUI_HAS_DOCK + + End(); +} + +// [DEBUG] Display contents of Columns +void ImGui::DebugNodeColumns(ImGuiOldColumns *columns) +{ + if (!TreeNode((void *)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags)) + return; + BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX); + for (int column_n = 0; column_n < columns->Columns.Size; column_n++) + BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm)); + TreePop(); +} + +static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags *p_flags, const char *label, bool enabled) +{ + using namespace ImGui; + PushID(label); + PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f)); + Text("%s:", label); + if (!enabled) + BeginDisabled(); + CheckboxFlags("NoSplit", p_flags, ImGuiDockNodeFlags_NoSplit); + CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize); + CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX); + CheckboxFlags("NoResizeY", p_flags, ImGuiDockNodeFlags_NoResizeY); + CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar); + CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar); + CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton); + CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton); + CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); + CheckboxFlags("NoDockingSplitMe", p_flags, ImGuiDockNodeFlags_NoDockingSplitMe); + CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther); + CheckboxFlags("NoDockingOverMe", p_flags, ImGuiDockNodeFlags_NoDockingOverMe); + CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther); + CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty); + if (!enabled) + EndDisabled(); + PopStyleVar(); + PopID(); +} + +// [DEBUG] Display contents of ImDockNode +void ImGui::DebugNodeDockNode(ImGuiDockNode *node, const char *label) +{ + ImGuiContext &g = *GImGui; + const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly + const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted + if (!is_alive) + { + PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); + } + bool open; + if (node->Windows.Size > 0) + open = TreeNode((void *)(intptr_t)node->ID, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); + else + open = TreeNode((void *)(intptr_t)node->ID, "%s 0x%04X%s: %s split (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical" + : "n/a", + node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); + if (!is_alive) + { + PopStyleColor(); + } + if (is_active && IsItemHovered()) + if (ImGuiWindow *window = node->HostWindow ? node->HostWindow : node->VisibleWindow) + GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255)); + if (open) + { + IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node); + IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node); + BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)", + node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y); + DebugNodeWindow(node->HostWindow, "HostWindow"); + DebugNodeWindow(node->VisibleWindow, "VisibleWindow"); + BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId); + BulletText("Misc:%s%s%s%s%s%s", + node->IsDockSpace() ? " IsDockSpace" : "", + node->IsCentralNode() ? " IsCentralNode" : "", + is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", + node->WantLockSizeOnce ? " WantLockSizeOnce" : "", + node->HasCentralNodeChild ? " HasCentralNodeChild" : ""); + if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags)) + { + if (BeginTable("flags", 4)) + { + TableNextColumn(); + DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false); + TableNextColumn(); + DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true); + TableNextColumn(); + DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false); + TableNextColumn(); + DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true); + EndTable(); + } + TreePop(); + } + if (node->ParentNode) + DebugNodeDockNode(node->ParentNode, "ParentNode"); + if (node->ChildNodes[0]) + DebugNodeDockNode(node->ChildNodes[0], "Child[0]"); + if (node->ChildNodes[1]) + DebugNodeDockNode(node->ChildNodes[1], "Child[1]"); + if (node->TabBar) + DebugNodeTabBar(node->TabBar, "TabBar"); + TreePop(); + } +} + +// [DEBUG] Display contents of ImDrawList +// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport. +void ImGui::DebugNodeDrawList(ImGuiWindow *window, ImGuiViewportP *viewport, const ImDrawList *draw_list, const char *label) +{ + ImGuiContext &g = *GImGui; + ImGuiMetricsConfig *cfg = &g.DebugMetricsConfig; + int cmd_count = draw_list->CmdBuffer.Size; + if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL) + cmd_count--; + bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count); + if (draw_list == GetWindowDrawList()) + { + SameLine(); + TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) + if (node_open) + TreePop(); + return; + } + + ImDrawList *fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list + if (window && IsItemHovered() && fg_draw_list) + fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + if (!node_open) + return; + + if (window && !window->WasActive) + TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!"); + + for (const ImDrawCmd *pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++) + { + if (pcmd->UserCallback) + { + BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); + continue; + } + + char buf[300]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", + pcmd->ElemCount / 3, (void *)(intptr_t)pcmd->TextureId, + pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + bool pcmd_node_open = TreeNode((void *)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); + if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list) + DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes); + if (!pcmd_node_open) + continue; + + // Calculate approximate coverage area (touched pixel count) + // This will be in pixels squared as long there's no post-scaling happening to the renderer output. + const ImDrawIdx *idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + const ImDrawVert *vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset; + float total_area = 0.0f; + for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount;) + { + ImVec2 triangle[3]; + for (int n = 0; n < 3; n++, idx_n++) + triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos; + total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]); + } + + // Display vertex information summary. Hover to get all triangles drawn in wire-frame + ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area); + Selectable(buf); + if (IsItemHovered() && fg_draw_list) + DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false); + + // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. + ImGuiListClipper clipper; + clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. + while (clipper.Step()) + for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) + { + char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); + ImVec2 triangle[3]; + for (int n = 0; n < 3; n++, idx_i++) + { + const ImDrawVert &v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i]; + triangle[n] = v.pos; + buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", + (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); + } + + Selectable(buf, false); + if (fg_draw_list && IsItemHovered()) + { + ImDrawListFlags backup_flags = fg_draw_list->Flags; + fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. + fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); + fg_draw_list->Flags = backup_flags; + } + } + TreePop(); + } + TreePop(); +} + +// [DEBUG] Display mesh/aabb of a ImDrawCmd +void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList *out_draw_list, const ImDrawList *draw_list, const ImDrawCmd *draw_cmd, bool show_mesh, bool show_aabb) +{ + IM_ASSERT(show_mesh || show_aabb); + + // Draw wire-frame version of all triangles + ImRect clip_rect = draw_cmd->ClipRect; + ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); + ImDrawListFlags backup_flags = out_draw_list->Flags; + out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. + for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end;) + { + ImDrawIdx *idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list + ImDrawVert *vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset; + + ImVec2 triangle[3]; + for (int n = 0; n < 3; n++, idx_n++) + vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos)); + if (show_mesh) + out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles + } + // Draw bounding boxes + if (show_aabb) + { + out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU + out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles + } + out_draw_list->Flags = backup_flags; +} + +// [DEBUG] Display details for a single font, called by ShowStyleEditor(). +void ImGui::DebugNodeFont(ImFont *font) +{ + bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)", + font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount); + SameLine(); + if (SmallButton("Set as default")) + GetIO().FontDefault = font; + if (!opened) + return; + + // Display preview text + PushFont(font); + Text("The quick brown fox jumps over the lazy dog"); + PopFont(); + + // Display details + SetNextItemWidth(GetFontSize() * 8); + DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); + SameLine(); + MetricsHelpMarker( + "Note than the default embedded font is NOT meant to be scaled.\n\n" + "Font are currently rendered into bitmaps at a given size at the time of building the atlas. " + "You may oversample them to get some flexibility with scaling. " + "You can also render at multiple sizes and select which one to use at runtime.\n\n" + "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)"); + Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); + char c_str[5]; + Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar); + Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar); + const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface); + Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt); + for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) + if (font->ConfigData) + if (const ImFontConfig *cfg = &font->ConfigData[config_i]) + BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", + config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y); + + // Display all glyphs of the fonts in separate pages of 256 characters + if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) + { + ImDrawList *draw_list = GetWindowDrawList(); + const ImU32 glyph_col = GetColorU32(ImGuiCol_Text); + const float cell_size = font->FontSize * 1; + const float cell_spacing = GetStyle().ItemSpacing.y; + for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) + { + // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) + // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT + // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) + if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095)) + { + base += 4096 - 256; + continue; + } + + int count = 0; + for (unsigned int n = 0; n < 256; n++) + if (font->FindGlyphNoFallback((ImWchar)(base + n))) + count++; + if (count <= 0) + continue; + if (!TreeNode((void *)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) + continue; + + // Draw a 16x16 grid of glyphs + ImVec2 base_pos = GetCursorScreenPos(); + for (unsigned int n = 0; n < 256; n++) + { + // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions + // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. + ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); + ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); + const ImFontGlyph *glyph = font->FindGlyphNoFallback((ImWchar)(base + n)); + draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); + if (!glyph) + continue; + font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); + if (IsMouseHoveringRect(cell_p1, cell_p2)) + { + BeginTooltip(); + DebugNodeFontGlyph(font, glyph); + EndTooltip(); + } + } + Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); + TreePop(); + } + TreePop(); + } + TreePop(); +} + +void ImGui::DebugNodeFontGlyph(ImFont *, const ImFontGlyph *glyph) +{ + Text("Codepoint: U+%04X", glyph->Codepoint); + Separator(); + Text("Visible: %d", glyph->Visible); + Text("AdvanceX: %.1f", glyph->AdvanceX); + Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); + Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); +} + +// [DEBUG] Display contents of ImGuiStorage +void ImGui::DebugNodeStorage(ImGuiStorage *storage, const char *label) +{ + if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes())) + return; + for (int n = 0; n < storage->Data.Size; n++) + { + const ImGuiStorage::ImGuiStoragePair &p = storage->Data[n]; + BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer. + } + TreePop(); +} + +// [DEBUG] Display contents of ImGuiTabBar +void ImGui::DebugNodeTabBar(ImGuiTabBar *tab_bar, const char *label) +{ + // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. + char buf[256]; + char *p = buf; + const char *buf_end = buf + IM_ARRAYSIZE(buf); + const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2); + p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*"); + p += ImFormatString(p, buf_end - p, " { "); + for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++) + { + ImGuiTabItem *tab = &tab_bar->Tabs[tab_n]; + p += ImFormatString(p, buf_end - p, "%s'%s'", + tab_n > 0 ? ", " : "", (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???"); + } + p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } "); + if (!is_active) + { + PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); + } + bool open = TreeNode(label, "%s", buf); + if (!is_active) + { + PopStyleColor(); + } + if (is_active && IsItemHovered()) + { + ImDrawList *draw_list = GetForegroundDrawList(); + draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); + draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + } + if (open) + { + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + const ImGuiTabItem *tab = &tab_bar->Tabs[tab_n]; + PushID(tab); + if (SmallButton("<")) + { + TabBarQueueReorder(tab_bar, tab, -1); + } + SameLine(0, 2); + if (SmallButton(">")) + { + TabBarQueueReorder(tab_bar, tab, +1); + } + SameLine(); + Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f", + tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???", tab->Offset, tab->Width, tab->ContentWidth); + PopID(); + } + TreePop(); + } +} + +void ImGui::DebugNodeViewport(ImGuiViewportP *viewport) +{ + SetNextItemOpen(true, ImGuiCond_Once); + if (TreeNode((void *)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A")) + { + ImGuiWindowFlags flags = viewport->Flags; + BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%", + viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y, + viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y, + viewport->PlatformMonitor, viewport->DpiScale * 100.0f); + if (viewport->Idx > 0) + { + SameLine(); + if (SmallButton("Reset Pos")) + { + viewport->Pos = ImVec2(200, 200); + viewport->UpdateWorkRect(); + if (viewport->Window) + viewport->Window->Pos = viewport->Pos; + } + } + BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags, + //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard + (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "", + (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "", + (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "", + (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "", + (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "", + (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "", + (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "", + (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", + (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "", + (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "", + (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "", + (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : ""); + for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++) + for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++) + DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList"); + TreePop(); + } +} + +void ImGui::DebugNodeWindow(ImGuiWindow *window, const char *label) +{ + if (window == NULL) + { + BulletText("%s: NULL", label); + return; + } + + ImGuiContext &g = *GImGui; + const bool is_active = window->WasActive; + ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None; + if (!is_active) + { + PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); + } + const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*"); + if (!is_active) + { + PopStyleColor(); + } + if (IsItemHovered() && is_active) + GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + if (!open) + return; + + if (window->MemoryCompacted) + TextDisabled("Note: some memory buffers have been compacted/freed."); + + ImGuiWindowFlags flags = window->Flags; + DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList"); + BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y); + BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags, + (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", + (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", + (flags & ImGuiWindowFlags_NoMouseInputs) ? "NoMouseInputs" : "", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); + BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId); + BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : ""); + BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); + BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); + for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++) + { + ImRect r = window->NavRectRel[layer]; + if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y) + { + BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]); + continue; + } + BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y); + if (IsItemHovered()) + GetForegroundDrawList(window)->AddRect(r.Min + window->Pos, r.Max + window->Pos, IM_COL32(255, 255, 0, 255)); + } + BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); + + BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y); + BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1); + BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible); + if (window->DockNode || window->DockNodeAsHost) + DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode"); + + if (window->RootWindow != window) + { + DebugNodeWindow(window->RootWindow, "RootWindow"); + } + if (window->RootWindowDockTree != window->RootWindow) + { + DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); + } + if (window->ParentWindow != NULL) + { + DebugNodeWindow(window->ParentWindow, "ParentWindow"); + } + if (window->DC.ChildWindows.Size > 0) + { + DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); + } + if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size)) + { + for (int n = 0; n < window->ColumnsStorage.Size; n++) + DebugNodeColumns(&window->ColumnsStorage[n]); + TreePop(); + } + DebugNodeStorage(&window->StateStorage, "Storage"); + TreePop(); +} + +void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings *settings) +{ + Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d", + settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed); +} + +void ImGui::DebugNodeWindowsList(ImVector *windows, const char *label) +{ + if (!TreeNode(label, "%s (%d)", label, windows->Size)) + return; + for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back + { + PushID((*windows)[i]); + DebugNodeWindow((*windows)[i], "Window"); + PopID(); + } + TreePop(); +} + +// FIXME-OPT: This is technically suboptimal, but it is simpler this way. +void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow **windows, int windows_size, ImGuiWindow *parent_in_begin_stack) +{ + for (int i = 0; i < windows_size; i++) + { + ImGuiWindow *window = windows[i]; + if (window->ParentWindowInBeginStack != parent_in_begin_stack) + continue; + char buf[20]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext); + // BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name); + DebugNodeWindow(window, buf); + Indent(); + DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window); + Unindent(); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL) +//----------------------------------------------------------------------------- + +// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack. +void ImGui::UpdateDebugToolItemPicker() +{ + ImGuiContext &g = *GImGui; + g.DebugItemPickerBreakId = 0; + if (!g.DebugItemPickerActive) + return; + + const ImGuiID hovered_id = g.HoveredIdPreviousFrame; + SetMouseCursor(ImGuiMouseCursor_Hand); + if (IsKeyPressed(ImGuiKey_Escape)) + g.DebugItemPickerActive = false; + if (IsMouseClicked(0) && hovered_id) + { + g.DebugItemPickerBreakId = hovered_id; + g.DebugItemPickerActive = false; + } + SetNextWindowBgAlpha(0.60f); + BeginTooltip(); + Text("HoveredId: 0x%08X", hovered_id); + Text("Press ESC to abort picking."); + TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!"); + EndTooltip(); +} + +// [DEBUG] Stack Tool: update queries. Called by NewFrame() +void ImGui::UpdateDebugToolStackQueries() +{ + ImGuiContext &g = *GImGui; + ImGuiStackTool *tool = &g.DebugStackTool; + + // Clear hook when stack tool is not visible + g.DebugHookIdInfo = 0; + if (g.FrameCount != tool->LastActiveFrame + 1) + return; + + // Update queries. The steps are: -1: query Stack, >= 0: query each stack item + // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time + const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId; + if (tool->QueryId != query_id) + { + tool->QueryId = query_id; + tool->StackLevel = -1; + tool->Results.resize(0); + } + if (query_id == 0) + return; + + // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result) + int stack_level = tool->StackLevel; + if (stack_level >= 0 && stack_level < tool->Results.Size) + if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2) + tool->StackLevel++; + + // Update hook + stack_level = tool->StackLevel; + if (stack_level == -1) + g.DebugHookIdInfo = query_id; + if (stack_level >= 0 && stack_level < tool->Results.Size) + { + g.DebugHookIdInfo = tool->Results[stack_level].ID; + tool->Results[stack_level].QueryFrameCount++; + } +} + +// [DEBUG] Stack tool: hooks called by GetID() family functions +void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void *data_id, const void *data_id_end) +{ + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + ImGuiStackTool *tool = &g.DebugStackTool; + + // Step 0: stack query + // This assume that the ID was computed with the current ID stack, which tends to be the case for our widget. + if (tool->StackLevel == -1) + { + tool->StackLevel++; + tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo()); + for (int n = 0; n < window->IDStack.Size + 1; n++) + tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id; + return; + } + + // Step 1+: query for individual level + IM_ASSERT(tool->StackLevel >= 0); + if (tool->StackLevel != window->IDStack.Size) + return; + ImGuiStackLevelInfo *info = &tool->Results[tool->StackLevel]; + IM_ASSERT(info->ID == id && info->QueryFrameCount > 0); + + switch (data_type) + { + case ImGuiDataType_S32: + ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id); + break; + case ImGuiDataType_String: + ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char *)data_id_end - (const char *)data_id) : (int)strlen((const char *)data_id), (const char *)data_id); + break; + case ImGuiDataType_Pointer: + ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id); + break; + case ImGuiDataType_ID: + if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one. + return; + ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id); + break; + default: + IM_ASSERT(0); + } + info->QuerySuccess = true; + info->DataType = data_type; +} + +static int StackToolFormatLevelInfo(ImGuiStackTool *tool, int n, bool format_for_ui, char *buf, size_t buf_size) +{ + ImGuiStackLevelInfo *info = &tool->Results[n]; + ImGuiWindow *window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL; + if (window) // Source: window name (because the root ID don't call GetID() and so doesn't get hooked) + return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name); + if (info->QuerySuccess) // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id) + return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc); + if (tool->StackLevel < tool->Results.Size) // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. + return (*buf = 0); +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (const char *label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID)) // Source: ImGuiTestEngine's ItemInfo() + return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label); +#endif + return ImFormatString(buf, buf_size, "???"); +} + +// Stack Tool: Display UI +void ImGui::ShowStackToolWindow(bool *p_open) +{ + ImGuiContext &g = *GImGui; + if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)) + SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver); + if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1) + { + End(); + return; + } + + // Display hovered/active status + ImGuiStackTool *tool = &g.DebugStackTool; + const ImGuiID hovered_id = g.HoveredIdPreviousFrame; + const ImGuiID active_id = g.ActiveId; +#ifdef IMGUI_ENABLE_TEST_ENGINE + Text("HoveredId: 0x%08X (\"%s\"), ActiveId: 0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : ""); +#else + Text("HoveredId: 0x%08X, ActiveId: 0x%08X", hovered_id, active_id); +#endif + SameLine(); + MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details."); + + // CTRL+C to copy path + const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime; + Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC); + SameLine(); + TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*"); + if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiKey_ModCtrl) && IsKeyPressed(ImGuiKey_C)) + { + tool->CopyToClipboardLastTime = (float)g.Time; + char *p = g.TempBuffer; + char *p_end = p + IM_ARRAYSIZE(g.TempBuffer); + for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++) + { + *p++ = '/'; + char level_desc[256]; + StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc)); + for (int n = 0; level_desc[n] && p + 2 < p_end; n++) + { + if (level_desc[n] == '/') + *p++ = '\\'; + *p++ = level_desc[n]; + } + } + *p = '\0'; + SetClipboardText(g.TempBuffer); + } + + // Display decorated stack + tool->LastActiveFrame = g.FrameCount; + if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders)) + { + const float id_width = CalcTextSize("0xDDDDDDDD").x; + TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width); + TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch); + TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width); + TableHeadersRow(); + for (int n = 0; n < tool->Results.Size; n++) + { + ImGuiStackLevelInfo *info = &tool->Results[n]; + TableNextColumn(); + Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0); + TableNextColumn(); + StackToolFormatLevelInfo(tool, n, true, g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer)); + TextUnformatted(g.TempBuffer); + TableNextColumn(); + Text("0x%08X", info->ID); + if (n == tool->Results.Size - 1) + TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header)); + } + EndTable(); + } + End(); +} + +#else + +void ImGui::ShowMetricsWindow(bool *) +{ +} +void ImGui::ShowFontAtlas(ImFontAtlas *) {} +void ImGui::DebugNodeColumns(ImGuiOldColumns *) {} +void ImGui::DebugNodeDrawList(ImGuiWindow *, ImGuiViewportP *, const ImDrawList *, const char *) {} +void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList *, const ImDrawList *, const ImDrawCmd *, bool, bool) {} +void ImGui::DebugNodeFont(ImFont *) {} +void ImGui::DebugNodeStorage(ImGuiStorage *, const char *) {} +void ImGui::DebugNodeTabBar(ImGuiTabBar *, const char *) {} +void ImGui::DebugNodeWindow(ImGuiWindow *, const char *) {} +void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings *) {} +void ImGui::DebugNodeWindowsList(ImVector *, const char *) {} +void ImGui::DebugNodeViewport(ImGuiViewportP *) {} + +void ImGui::ShowStackToolWindow(bool *) {} +void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void *, const void *) {} +void ImGui::UpdateDebugToolItemPicker() {} +void ImGui::UpdateDebugToolStackQueries() {} + +#endif // #ifndef IMGUI_DISABLE_METRICS_WINDOW + +//----------------------------------------------------------------------------- + +// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. +// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. +#ifdef IMGUI_INCLUDE_IMGUI_USER_INL +#include "imgui_user.inl" +#endif + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/src/editors/xrEUI/imgui.h b/src/editors/xrEUI/imgui.h new file mode 100644 index 00000000000..04c48e32253 --- /dev/null +++ b/src/editors/xrEUI/imgui.h @@ -0,0 +1,3306 @@ +// dear imgui, v1.88 WIP +// (headers) + +// Help: +// - Read FAQ at http://dearimgui.org/faq +// - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. +// Read imgui.cpp for details, links and comments. + +// Resources: +// - FAQ http://dearimgui.org/faq +// - Homepage & latest https://github.com/ocornut/imgui +// - Releases & changelog https://github.com/ocornut/imgui/releases +// - Gallery https://github.com/ocornut/imgui/issues/5243 (please post your screenshots/video there!) +// - Wiki https://github.com/ocornut/imgui/wiki (lots of good stuff there) +// - Glossary https://github.com/ocornut/imgui/wiki/Glossary +// - Issues & support https://github.com/ocornut/imgui/issues + +// Getting Started? +// - For first-time users having issues compiling/linking/running or issues loading fonts: +// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. + +/* + +Index of this file: +// [SECTION] Header mess +// [SECTION] Forward declarations and basic types +// [SECTION] Dear ImGui end-user API functions +// [SECTION] Flags & Enumerations +// [SECTION] Helpers: Memory allocations macros, ImVector<> +// [SECTION] ImGuiStyle +// [SECTION] ImGuiIO +// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiWindowClass, ImGuiPayload, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor) +// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) +// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) +// [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) +// [SECTION] Platform Dependent Interfaces (ImGuiPlatformIO, ImGuiPlatformMonitor, ImGuiPlatformImeData) +// [SECTION] Obsolete functions and types + +*/ + +#pragma once + +// Configuration file with compile-time options (edit imconfig.h or '#define IMGUI_USER_CONFIG "myfilename.h" from your build system') +#ifdef IMGUI_USER_CONFIG +#include IMGUI_USER_CONFIG +#endif +#if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H) +#include "imconfig.h" +#endif + +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// [SECTION] Header mess +//----------------------------------------------------------------------------- + +// Includes +#include // FLT_MIN, FLT_MAX +#include // va_list, va_start, va_end +#include // ptrdiff_t, NULL +#include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp + +// Version +// (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) +#define IMGUI_VERSION "1.88 WIP" +#define IMGUI_VERSION_NUM 18724 +#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) +#define IMGUI_HAS_TABLE +#define IMGUI_HAS_VIEWPORT // Viewport WIP branch +#define IMGUI_HAS_DOCK // Docking WIP branch + +// Define attributes of all API symbols declarations (e.g. for DLL under Windows) +// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default backends files (imgui_impl_xxx.h) +// Using dear imgui via a shared library is not recommended, because we don't guarantee backward nor forward ABI compatibility (also function call overhead, as dear imgui is a call-heavy API) +#ifndef IMGUI_API +#define IMGUI_API +#endif +#ifndef IMGUI_IMPL_API +#define IMGUI_IMPL_API IMGUI_API +#endif + +// Helper Macros +#ifndef IM_ASSERT +#include +#define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h +#endif +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! +#define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. +#define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in C++11 + +// Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions. +#if !defined(IMGUI_USE_STB_SPRINTF) && defined(__MINGW32__) && !defined(__clang__) +#define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) +#define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) +#elif !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__)) +#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) +#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) +#else +#define IM_FMTARGS(FMT) +#define IM_FMTLIST(FMT) +#endif + +// Disable some of MSVC most aggressive Debug runtime checks in function header/footer (used in some simple/low-level functions) +#if defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(IMGUI_DEBUG_PARANOID) +#define IM_MSVC_RUNTIME_CHECKS_OFF __pragma(runtime_checks("",off)) __pragma(check_stack(off)) __pragma(strict_gs_check(push,off)) +#define IM_MSVC_RUNTIME_CHECKS_RESTORE __pragma(runtime_checks("",restore)) __pragma(check_stack()) __pragma(strict_gs_check(pop)) +#else +#define IM_MSVC_RUNTIME_CHECKS_OFF +#define IM_MSVC_RUNTIME_CHECKS_RESTORE +#endif + +// Warnings +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). +#endif +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" +#if __has_warning("-Wzero-as-null-pointer-constant") +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#endif +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Forward declarations and basic types +//----------------------------------------------------------------------------- + +// Forward declarations +struct ImDrawChannel; // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit() +struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback) +struct ImDrawData; // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix. +struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) +struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) +struct ImDrawListSplitter; // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back. +struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +struct ImFont; // Runtime data for a single font within a parent ImFontAtlas +struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader +struct ImFontBuilderIO; // Opaque interface to a font builder (stb_truetype or FreeType). +struct ImFontConfig; // Configuration data when adding a font or merging fonts +struct ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) +struct ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data +struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using) +struct ImGuiContext; // Dear ImGui context (opaque structure, unless including imgui_internal.h) +struct ImGuiIO; // Main configuration and I/O between your application and ImGui +struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) +struct ImGuiKeyData; // Storage for ImGuiIO and IsKeyDown(), IsKeyPressed() etc functions. +struct ImGuiListClipper; // Helper to manually clip large list of items +struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame +struct ImGuiPayload; // User data payload for drag and drop operations +struct ImGuiPlatformIO; // Multi-viewport support: interface for Platform/Renderer backends + viewports to render +struct ImGuiPlatformMonitor; // Multi-viewport support: user-provided bounds for each connected monitor/display. Used when positioning popups and tooltips to avoid them straddling monitors +struct ImGuiPlatformImeData; // Platform IME data for io.SetPlatformImeDataFn() function. +struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) +struct ImGuiStorage; // Helper for key->value storage +struct ImGuiStyle; // Runtime data for styling/colors +struct ImGuiTableSortSpecs; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +struct ImGuiTableColumnSortSpecs; // Sorting specification for one column of a table +struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder) +struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]") +struct ImGuiViewport; // A Platform Window (always 1 unless multi-viewport are enabled. One per platform window to output to). In the future may represent Platform Monitor +struct ImGuiWindowClass; // Window class (rare/advanced uses: provide hints to the platform backend via altered viewport flags and parent/child info) + +// Enums/Flags (declared as int for compatibility with old C++, to allow using as flags without overhead, and to not pollute the top of this file) +// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! +// In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. +// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. +typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling +typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for many Set*() functions +typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type +typedef int ImGuiDir; // -> enum ImGuiDir_ // Enum: A cardinal direction +typedef int ImGuiKey; // -> enum ImGuiKey_ // Enum: A key identifier +typedef int ImGuiNavInput; // -> enum ImGuiNavInput_ // Enum: An input identifier for navigation +typedef int ImGuiMouseButton; // -> enum ImGuiMouseButton_ // Enum: A mouse button identifier (0=left, 1=right, 2=middle) +typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor identifier +typedef int ImGuiSortDirection; // -> enum ImGuiSortDirection_ // Enum: A sorting direction (ascending or descending) +typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling +typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A color target for TableSetBgColor() +typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions +typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance +typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build +typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags +typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton() +typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. +typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags +typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() +typedef int ImGuiDockNodeFlags; // -> enum ImGuiDockNodeFlags_ // Flags: for DockSpace() +typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() +typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() +typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. +typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() +typedef int ImGuiModFlags; // -> enum ImGuiModFlags_ // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super) +typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() +typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() +typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() +typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() +typedef int ImGuiTableFlags; // -> enum ImGuiTableFlags_ // Flags: For BeginTable() +typedef int ImGuiTableColumnFlags; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn() +typedef int ImGuiTableRowFlags; // -> enum ImGuiTableRowFlags_ // Flags: For TableNextRow() +typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() +typedef int ImGuiViewportFlags; // -> enum ImGuiViewportFlags_ // Flags: for ImGuiViewport +typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() + +// ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type] +// - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. +// - This can be whatever to you want it to be! read the FAQ about ImTextureID for details. +#ifndef ImTextureID +typedef void* ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) +#endif + +// ImDrawIdx: vertex index. [Compile-time configurable type] +// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). +// - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. +#ifndef ImDrawIdx +typedef unsigned short ImDrawIdx; // Default: 16-bit (for maximum compatibility with renderer backends) +#endif + +// Scalar data types +typedef unsigned int ImGuiID;// A unique ID used by widgets (typically the result of hashing a stack of string) +typedef signed char ImS8; // 8-bit signed integer +typedef unsigned char ImU8; // 8-bit unsigned integer +typedef signed short ImS16; // 16-bit signed integer +typedef unsigned short ImU16; // 16-bit unsigned integer +typedef signed int ImS32; // 32-bit signed integer == int +typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors) +typedef signed long long ImS64; // 64-bit signed integer +typedef unsigned long long ImU64; // 64-bit unsigned integer + +// Character types +// (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display) +typedef unsigned short ImWchar16; // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings. +typedef unsigned int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings. +#ifdef IMGUI_USE_WCHAR32 // ImWchar [configurable type: override in imconfig.h with '#define IMGUI_USE_WCHAR32' to support Unicode planes 1-16] +typedef ImWchar32 ImWchar; +#else +typedef ImWchar16 ImWchar; +#endif + +// Callback and functions types +typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); // Callback function for ImGui::InputText() +typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Callback function for ImGui::SetNextWindowSizeConstraints() +typedef void* (*ImGuiMemAllocFunc)(size_t sz, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() +typedef void (*ImGuiMemFreeFunc)(void* ptr, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() + +// ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type] +// This is a frequently used type in the API. Consider using IM_VEC2_CLASS_EXTRA to create implicit cast from/to our preferred type. +IM_MSVC_RUNTIME_CHECKS_OFF +struct ImVec2 +{ + float x, y; + constexpr ImVec2() : x(0.0f), y(0.0f) { } + constexpr ImVec2(float _x, float _y) : x(_x), y(_y) { } + float operator[] (size_t idx) const { IM_ASSERT(idx <= 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine. + float& operator[] (size_t idx) { IM_ASSERT(idx <= 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine. +#ifdef IM_VEC2_CLASS_EXTRA + IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2. +#endif +}; + +// ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] +struct ImVec4 +{ + float x, y, z, w; + constexpr ImVec4() : x(0.0f), y(0.0f), z(0.0f), w(0.0f) { } + constexpr ImVec4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) { } +#ifdef IM_VEC4_CLASS_EXTRA + IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4. +#endif +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] Dear ImGui end-user API functions +// (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!) +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // Context creation and access + // - Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between contexts. + // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() + // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for details. + IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL); + IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context + IMGUI_API ImGuiContext* GetCurrentContext(); + IMGUI_API void SetCurrentContext(ImGuiContext* ctx); + + // Main + IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) + IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame! + IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame(). + IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all! + IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData(). + IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. + + // Demo, Debug, Information + IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Metrics/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc. + IMGUI_API void ShowStackToolWindow(bool* p_open = NULL); // create Stack Tool window. hover items with mouse to query information about the source of their unique ID. + IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information. + IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) + IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. + IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. + IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls). + IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp) + + // Styles + IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default) + IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font + IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style + + // Windows + // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack. + // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window, + // which clicking will set the boolean to false when clicked. + // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times. + // Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin(). + // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting + // anything to the window. Always call a matching End() for each Begin() call, regardless of its return value! + // [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu, + // BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function + // returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] + // - Note that the bottom of window stack always contains a window called "Debug". + IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); + IMGUI_API void End(); + + // Child Windows + // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. + // - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400). + // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. + // Always call a matching EndChild() for each BeginChild() call, regardless of its return value. + // [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu, + // BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function + // returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API void EndChild(); + + // Windows Utilities + // - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into. + IMGUI_API bool IsWindowAppearing(); + IMGUI_API bool IsWindowCollapsed(); + IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. + IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ! + IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives + IMGUI_API float GetWindowDpiScale(); // get DPI scale currently associated to the current window's viewport. + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API) + IMGUI_API ImVec2 GetWindowSize(); // get current window size + IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x) + IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y) + IMGUI_API ImGuiViewport*GetWindowViewport(); // get viewport currently associated to the current window. + + // Window manipulation + // - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). + IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0, 0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. + IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() + IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints. + IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin() + IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() + IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin() + IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. + IMGUI_API void SetNextWindowViewport(ImGuiID viewport_id); // set next window viewport + IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. + IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. + IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). + IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus(). + IMGUI_API void SetWindowFontScale(float scale); // [OBSOLETE] set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes(). + IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. + IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. + IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state + IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus. + + // Content region + // - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful. + // - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion) + IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() + IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates + IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min for the full window (roughly (0,0)-Scroll), in window coordinates + IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max for the full window (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates + + // Windows Scrolling + IMGUI_API float GetScrollX(); // get scrolling amount [0 .. GetScrollMaxX()] + IMGUI_API float GetScrollY(); // get scrolling amount [0 .. GetScrollMaxY()] + IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0 .. GetScrollMaxX()] + IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0 .. GetScrollMaxY()] + IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x + IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y + IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. + IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. + IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. + IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. + + // Parameters stacks (shared) + IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font + IMGUI_API void PopFont(); + IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). + IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); + IMGUI_API void PopStyleColor(int count = 1); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame(). + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. always use this if you modify the style after NewFrame(). + IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // == tab stop enable. Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets + IMGUI_API void PopAllowKeyboardFocus(); + IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. + IMGUI_API void PopButtonRepeat(); + + // Parameters stacks (current window) + IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). + IMGUI_API void PopItemWidth(); + IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side) + IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions. + IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space + IMGUI_API void PopTextWrapPos(); + + // Style read access + // - Use the style editor (ShowStyleEditor() function) to interactively see what the colors are) + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied + IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList + IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList + IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList + IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in. + + // Cursor / Layout + // - By "cursor" we mean the current output position. + // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down. + // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget. + // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: + // Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos() + // Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. + IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. + IMGUI_API void SameLine(float offset_from_start_x=0.0f, float spacing=-1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates. + IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in an horizontal-layout context. + IMGUI_API void Spacing(); // add vertical spacing. + IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into. + IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0 + IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0 + IMGUI_API void BeginGroup(); // lock horizontal starting position + IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) + IMGUI_API ImVec2 GetCursorPos(); // cursor position in window coordinates (relative to window position) + IMGUI_API float GetCursorPosX(); // (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc. + IMGUI_API float GetCursorPosY(); // other functions such as GetCursorScreenPos or everything in ImDrawList:: + IMGUI_API void SetCursorPos(const ImVec2& local_pos); // are using the main, absolute coordinate system. + IMGUI_API void SetCursorPosX(float local_x); // GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.) + IMGUI_API void SetCursorPosY(float local_y); // + IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position in window coordinates + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute coordinates (useful to work with ImDrawList API). generally top-left == GetMainViewport()->Pos == (0,0) in single viewport mode, and bottom-right == GetMainViewport()->Pos+Size == io.DisplaySize in single-viewport mode. + IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute coordinates + IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item) + IMGUI_API float GetTextLineHeight(); // ~ FontSize + IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text) + IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2 + IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets) + + // ID stack/scopes + // Read the FAQ (docs/FAQ.md or http://dearimgui.org/faq) for more details about how ID are handled in dear imgui. + // - Those questions are answered and impacted by understanding of the ID stack system: + // - "Q: Why is my widget not reacting when I click on it?" + // - "Q: How can I have widgets with an empty label?" + // - "Q: How can I have multiple widgets with the same label?" + // - Short version: ID are hashes of the entire ID stack. If you are creating widgets in a loop you most likely + // want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them. + // - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others. + // - In this header file we use the "label"/"name" terminology to denote a string that will be displayed + used as an ID, + // whereas "str_id" denote a string that is only used as an ID and not normally displayed. + IMGUI_API void PushID(const char* str_id); // push string into the ID stack (will hash string). + IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string). + IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer). + IMGUI_API void PushID(int int_id); // push integer into the ID stack (will hash integer). + IMGUI_API void PopID(); // pop from the ID stack. + IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself + IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); + IMGUI_API ImGuiID GetID(const void* ptr_id); + + // Widgets: Text + IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. + IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // formatted text + IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). + IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1); + IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets + IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() + IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Widgets: Main + // - Most widgets return true when the value has been changed or when pressed/selected + // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. + IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0, 0)); // button + IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text + IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) + IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); + IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding + IMGUI_API bool Checkbox(const char* label, bool* v); + IMGUI_API bool CheckboxFlags(const char* label, int* flags, int flags_value); + IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); + IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } + IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL); + IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + + // Widgets: Combo Box + // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. + // - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. This is analogous to how ListBox are created. + IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0); + IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true! + IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1); + IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" + IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1); + + // Widgets: Drag Sliders + // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. + // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', + // the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x + // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). + // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). + // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used. + // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. + // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. + // - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + + // Widgets: Regular Sliders + // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. + // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). + // - Legacy: Pre-1.78 there are SliderXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + + // Widgets: Input with Keyboard + // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. + // - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc. + IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = "%.6f", ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); + + // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.) + // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. + // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x + IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); + IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); + IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed. + IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. + + // Widgets: Trees + // - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents. + IMGUI_API bool TreeNode(const char* label); + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). + IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " + IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); + IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); + IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); + IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); + IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. + IMGUI_API void TreePush(const void* ptr_id = NULL); // " + IMGUI_API void TreePop(); // ~ Unindent()+PopId() + IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode + IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). + IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. + IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. + + // Widgets: Selectables + // - A selectable highlights when hovered, and can display another color when selected. + // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous. + IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. + + // Widgets: List Boxes + // - This is essentially a thin wrapper to using BeginChild/EndChild with some stylistic changes. + // - The BeginListBox()/EndListBox() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() or any items. + // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analoguous to how Combos are created. + // - Choose frame width: size.x > 0.0f: custom / size.x < 0.0f or -FLT_MIN: right-align / size.x = 0.0f (default): use current ItemWidth + // - Choose frame height: size.y > 0.0f: custom / size.y < 0.0f or -FLT_MIN: bottom-align / size.y = 0.0f (default): arbitrary default height which can fit ~7 items + IMGUI_API bool BeginListBox(const char* label, const ImVec2& size = ImVec2(0, 0)); // open a framed scrolling region + IMGUI_API void EndListBox(); // only call EndListBox() if BeginListBox() returned true! + IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); + IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); + + // Widgets: Data Plotting + // - Consider using ImPlot (https://github.com/epezent/implot) which is much better! + IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); + IMGUI_API void PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); + + // Widgets: Value() Helpers. + // - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) + IMGUI_API void Value(const char* prefix, bool b); + IMGUI_API void Value(const char* prefix, int v); + IMGUI_API void Value(const char* prefix, unsigned int v); + IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); + + // Widgets: Menus + // - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar. + // - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it. + // - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it. + // - Not that MenuItem() keyboardshortcuts are displayed as a convenience but _not processed_ by Dear ImGui at the moment. + IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). + IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true! + IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. + IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true! + IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! + IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true! + IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. + IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL + + // Tooltips + // - Tooltip are windows following the mouse. They do not take focus away. + IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of items). + IMGUI_API void EndTooltip(); + IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). override any previous call to SetTooltip(). + IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Popups, Modals + // - They block normal mouse hovering detection (and therefore most mouse interactions) behind them. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls. + // - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time. + // - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). + // - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack. + // This is sometimes leading to confusing mistakes. May rework this in the future. + + // Popups: begin/end functions + // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window. + // - BeginPopupModal(): block every interactions behind the window, cannot be closed by user, add a dimming background, has a title bar. + IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. + IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! + + // Popups: open/close functions + // - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually. + // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). + // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). + // - Use IsWindowAppearing() after BeginPopup() to tell if a window just opened. + // - IMPORTANT: Notice that for OpenPopupOnItemClick() we exceptionally default flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter + IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). + IMGUI_API void OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags = 0); // id overload to facilitate calling from nested stacks + IMGUI_API void OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. Default to ImGuiPopupFlags_MouseButtonRight == 1. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. + + // Popups: open+begin combined functions helpers + // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. + // - They are convenient to easily create context menus, hence the name. + // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future. + // - IMPORTANT: Notice that we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight. + IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked on last item. Use str_id==NULL to associate the popup to previous item. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows). + + // Popups: query functions + // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open. + IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. + + // Tables + // - Full-featured replacement for old Columns API. + // - See Demo->Tables for demo code. See top of imgui_tables.cpp for general commentary. + // - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags. + // The typical call flow is: + // - 1. Call BeginTable(), early out if returning false. + // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults. + // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows. + // - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data. + // - 5. Populate contents: + // - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column. + // - If you are using tables as a sort of grid, where every columns is holding the same type of contents, + // you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex(). + // TableNextColumn() will automatically wrap-around into the next row if needed. + // - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column! + // - Summary of possible call flow: + // -------------------------------------------------------------------------------------------------------- + // TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK + // TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK + // TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row! + // TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear! + // -------------------------------------------------------------------------------------------------------- + // - 5. Call EndTable() + IMGUI_API bool BeginTable(const char* str_id, int column, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f); + IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! + IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row. + IMGUI_API bool TableNextColumn(); // append into the next column (or first column of next row if currently in last column). Return true when column is visible. + IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true when column is visible. + + // Tables: Headers & Columns declaration + // - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc. + // - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column. + // Headers are required to perform: reordering, sorting, and opening the context menu. + // The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody. + // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in + // some advanced use cases (e.g. adding custom widgets in header row). + // - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled. + IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImGuiID user_id = 0); + IMGUI_API void TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled. + IMGUI_API void TableHeadersRow(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu + IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used) + + // Tables: Sorting & Miscellaneous functions + // - Sorting: call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting. + // When 'sort_specs->SpecsDirty == true' you should sort your data. It will be true when sorting specs have + // changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, + // else you may wastefully sort your data every frame! + // - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index. + IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable(). + IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable) + IMGUI_API int TableGetColumnIndex(); // return current column index. + IMGUI_API int TableGetRowIndex(); // return current row index. + IMGUI_API const char* TableGetColumnName(int column_n = -1); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. + IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column. + IMGUI_API void TableSetColumnEnabled(int column_n, bool v);// change user accessible enabled/disabled state of a column. Set to false to hide the column. User can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody) + IMGUI_API void TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. + + // Legacy Columns API (prefer using Tables!) + // - You can also use SameLine(pos_x) to mimic simplified columns. + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); + IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished + IMGUI_API int GetColumnIndex(); // get current column index + IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column + IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column + IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f + IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column + IMGUI_API int GetColumnsCount(); + + // Tab Bars, Tabs + // Note: Tabs are automatically created by the docking system. Use this to create tab bars/tabs yourself without docking being involved. + IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar + IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true! + IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected. + IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true! + IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. + IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. + + // Docking + // [BETA API] Enable with io.ConfigFlags |= ImGuiConfigFlags_DockingEnable. + // Note: You can use most Docking facilities without calling any API. You DO NOT need to call DockSpace() to use Docking! + // - Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking/undocking. + // - Drag from window menu button (upper-left button) to undock an entire node (all windows). + // - When io.ConfigDockingWithShift == true, you instead need to hold SHIFT to _enable_ docking/undocking. + // About dockspaces: + // - Use DockSpace() to create an explicit dock node _within_ an existing window. See Docking demo for details. + // - Use DockSpaceOverViewport() to create an explicit dock node covering the screen or a specific viewport. + // This is often used with ImGuiDockNodeFlags_PassthruCentralNode. + // - Important: Dockspaces need to be submitted _before_ any window they can host. Submit it early in your frame! + // - Important: Dockspaces need to be kept alive if hidden, otherwise windows docked into it will be undocked. + // e.g. if you have multiple tabs with a dockspace inside each tab: submit the non-visible dockspaces with ImGuiDockNodeFlags_KeepAliveOnly. + IMGUI_API ImGuiID DockSpace(ImGuiID id, const ImVec2& size = ImVec2(0, 0), ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); + IMGUI_API ImGuiID DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); + IMGUI_API void SetNextWindowDockID(ImGuiID dock_id, ImGuiCond cond = 0); // set next window dock id + IMGUI_API void SetNextWindowClass(const ImGuiWindowClass* window_class); // set next window class (control docking compatibility + provide hints to platform backend via custom viewport flags and platform parent/child relationship) + IMGUI_API ImGuiID GetWindowDockID(); + IMGUI_API bool IsWindowDocked(); // is current window docked into another window? + + // Logging/Capture + // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging. + IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout) + IMGUI_API void LogToFile(int auto_open_depth = -1, const char* filename = NULL); // start logging to file + IMGUI_API void LogToClipboard(int auto_open_depth = -1); // start logging to OS clipboard + IMGUI_API void LogFinish(); // stop logging (close file, etc.) + IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard + IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed) + IMGUI_API void LogTextV(const char* fmt, va_list args) IM_FMTLIST(1); + + // Drag and Drop + // - On source items, call BeginDragDropSource(), if it returns true also call SetDragDropPayload() + EndDragDropSource(). + // - On target candidates, call BeginDragDropTarget(), if it returns true also call AcceptDragDropPayload() + EndDragDropTarget(). + // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip, see #1725) + // - An item can be both drag source and drop target. + IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call after submitting an item which may be dragged. when this return true, you can call SetDragDropPayload() + EndDragDropSource() + IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. Return true when payload has been accepted. + IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! + IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() + IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. + IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! + IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type. + + // Disabling [BETA API] + // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) + // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) + // - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it. + IMGUI_API void BeginDisabled(bool disabled = true); + IMGUI_API void EndDisabled(); + + // Clipping + // - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only. + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + IMGUI_API void PopClipRect(); + + // Focus, Activation + // - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item" + IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window. + IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget. + + // Item/Widgets Utilities and Query Functions + // - Most of the functions are referring to the previous Item that has been submitted. + // - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions. + IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options. + IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false) + IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation? + IMGUI_API bool IsItemClicked(ImGuiMouseButton mouse_button = 0); // is the last item hovered and mouse clicked on? (**) == IsMouseClicked(mouse_button) && IsItemHovered()Important. (**) this it NOT equivalent to the behavior of e.g. Button(). Read comments in function definition. + IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling) + IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets. + IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive). + IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing. + IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). + IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode(). + IMGUI_API bool IsAnyItemHovered(); // is any item hovered? + IMGUI_API bool IsAnyItemActive(); // is any item active? + IMGUI_API bool IsAnyItemFocused(); // is any item focused? + IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space) + IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space) + IMGUI_API ImVec2 GetItemRectSize(); // get size of last item + IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. + + // Viewports + // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. + // - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports. + // - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. + IMGUI_API ImGuiViewport* GetMainViewport(); // return primary/default viewport. This can never be NULL. + + // Background/Foreground Draw Lists + IMGUI_API ImDrawList* GetBackgroundDrawList(); // get background draw list for the viewport associated to the current window. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. + IMGUI_API ImDrawList* GetForegroundDrawList(); // get foreground draw list for the viewport associated to the current window. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. + IMGUI_API ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport); // get background draw list for the given viewport. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. + IMGUI_API ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport); // get foreground draw list for the given viewport. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. + + // Miscellaneous Utilities + IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. + IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. + IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame. + IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame. + IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances. + IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.). + IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) + IMGUI_API ImGuiStorage* GetStateStorage(); + IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame + IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window) + + // Text Utilities + IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); + + // Color Utilities + IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); + IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); + IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); + IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); + + // Inputs Utilities: Keyboard + // Without IMGUI_DISABLE_OBSOLETE_KEYIO: (legacy support) + // - For 'ImGuiKey key' you can still use your legacy native/user indices according to how your backend/engine stored them in io.KeysDown[]. + // With IMGUI_DISABLE_OBSOLETE_KEYIO: (this is the way forward) + // - Any use of 'ImGuiKey' will assert when key < 512 will be passed, previously reserved as native/user keys indices + // - GetKeyIndex() is pass-through and therefore deprecated (gone if IMGUI_DISABLE_OBSOLETE_KEYIO is defined) + IMGUI_API bool IsKeyDown(ImGuiKey key); // is key being held. + IMGUI_API bool IsKeyPressed(ImGuiKey key, bool repeat = true); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate + IMGUI_API bool IsKeyReleased(ImGuiKey key); // was key released (went from Down to !Down)? + IMGUI_API int GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate + IMGUI_API const char* GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names a provided for debugging purpose and are not meant to be saved persistently not compared. + IMGUI_API void SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard); // Override io.WantCaptureKeyboard flag next frame (said flag is left for your application to handle, typically when true it instructs your app to ignore inputs). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard"; after the next NewFrame() call. + + // Inputs Utilities: Mouse + // - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right. + // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle. + // - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold') + IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held? + IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down). Same as GetMouseClickedCount() == 1. + IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down) + IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? Same as GetMouseClickedCount() == 2. (note that a double-click will also report IsMouseClicked() == true) + IMGUI_API int GetMouseClickedCount(ImGuiMouseButton button); // return the number of successive mouse-clicks at the time where a click happen (otherwise 0). + IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. + IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available + IMGUI_API bool IsAnyMouseDown(); // [WILL OBSOLETE] is any mouse button held? This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. + IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls + IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves) + IMGUI_API bool IsMouseDragging(ImGuiMouseButton button, float lock_threshold = -1.0f); // is mouse dragging? (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold) + IMGUI_API ImVec2 GetMouseDragDelta(ImGuiMouseButton button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold) + IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); // + IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you + IMGUI_API void SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired cursor type + IMGUI_API void SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instucts your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call. + + // Clipboard Utilities + // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard. + IMGUI_API const char* GetClipboardText(); + IMGUI_API void SetClipboardText(const char* text); + + // Settings/.Ini Utilities + // - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini"). + // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. + // - Important: default value "imgui.ini" is relative to current working dir! Most apps will want to lock this to an absolute path (e.g. same path as executables). + IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). + IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. + IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). + IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. + + // Debug Utilities + IMGUI_API void DebugTextEncoding(const char* text); + IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro. + + // Memory Allocators + // - Those functions are not reliant on the current context. + // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() + // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. + IMGUI_API void SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data = NULL); + IMGUI_API void GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data); + IMGUI_API void* MemAlloc(size_t size); + IMGUI_API void MemFree(void* ptr); + + // (Optional) Platform/OS interface for multi-viewport support + // Read comments around the ImGuiPlatformIO structure for more details. + // Note: You may use GetWindowViewport() to get the current viewport of the current window. + IMGUI_API ImGuiPlatformIO& GetPlatformIO(); // platform/renderer functions, for backend to setup + viewports list. + IMGUI_API void UpdatePlatformWindows(); // call in main loop. will call CreateWindow/ResizeWindow/etc. platform functions for each secondary viewport, and DestroyWindow for each inactive viewport. + IMGUI_API void RenderPlatformWindowsDefault(void* platform_render_arg = NULL, void* renderer_render_arg = NULL); // call in main loop. will call RenderWindow/SwapBuffers platform functions for each secondary viewport which doesn't have the ImGuiViewportFlags_Minimized flag set. May be reimplemented by user for custom rendering needs. + IMGUI_API void DestroyPlatformWindows(); // call DestroyWindow platform functions for all viewports. call from backend Shutdown() if you need to close platform windows before imgui shutdown. otherwise will be called by DestroyContext(). + IMGUI_API ImGuiViewport* FindViewportByID(ImGuiID id); // this is a helper for backends. + IMGUI_API ImGuiViewport* FindViewportByPlatformHandle(void* platform_handle); // this is a helper for backends. the type platform_handle is decided by the backend (e.g. HWND, MyWindow*, GLFWwindow* etc.) +} // namespace ImGui + +//----------------------------------------------------------------------------- +// [SECTION] Flags & Enumerations +//----------------------------------------------------------------------------- + +// Flags for ImGui::Begin() +enum ImGuiWindowFlags_ +{ + ImGuiWindowFlags_None = 0, + ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar + ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip + ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window + ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programmatically) + ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. + ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node). + ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame + ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). + ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file + ImGuiWindowFlags_NoMouseInputs = 1 << 9, // Disable catching mouse, hovering test with pass through. + ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar + ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state + ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) + ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) + ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) + ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) + ImGuiWindowFlags_NoNavInputs = 1 << 18, // No gamepad/keyboard navigation within the window + ImGuiWindowFlags_NoNavFocus = 1 << 19, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB) + ImGuiWindowFlags_UnsavedDocument = 1 << 20, // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + ImGuiWindowFlags_NoDocking = 1 << 21, // Disable docking of this window + + ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, + ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, + + // [Internal] + ImGuiWindowFlags_NavFlattened = 1 << 23, // [BETA] On child window: allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows. + ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip() + ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup() + ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal() + ImGuiWindowFlags_ChildMenu = 1 << 28, // Don't use! For internal use by BeginMenu() + ImGuiWindowFlags_DockNodeHost = 1 << 29 // Don't use! For internal use by Begin()/NewFrame() + + // [Obsolete] + //ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // [Obsolete] --> Set io.ConfigWindowsResizeFromEdges=true and make sure mouse cursors are supported by backend (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) +}; + +// Flags for ImGui::InputText() +enum ImGuiInputTextFlags_ +{ + ImGuiInputTextFlags_None = 0, + ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ + ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef + ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z + ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs + ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus + ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider looking at the IsItemDeactivatedAfterEdit() function. + ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Callback on pressing TAB (for completion handling) + ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Callback on pressing Up/Down arrows (for history handling) + ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Callback on each iteration. User code may query cursor position, modify text buffer. + ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. + ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field + ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). + ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally + ImGuiInputTextFlags_AlwaysOverwrite = 1 << 13, // Overwrite mode + ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode + ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' + ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). + ImGuiInputTextFlags_CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input) + ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) + ImGuiInputTextFlags_CallbackEdit = 1 << 19 // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) + + // Obsolete names (will be removed soon) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiInputTextFlags_AlwaysInsertMode = ImGuiInputTextFlags_AlwaysOverwrite // [renamed in 1.82] name was not matching behavior +#endif +}; + +// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() +enum ImGuiTreeNodeFlags_ +{ + ImGuiTreeNodeFlags_None = 0, + ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected + ImGuiTreeNodeFlags_Framed = 1 << 1, // Draw frame with background (e.g. for CollapsingHeader) + ImGuiTreeNodeFlags_AllowItemOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one + ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. + ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). + ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow + ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding(). + ImGuiTreeNodeFlags_SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line. In the future we may refactor the hit system to be front-to-back, allowing natural overlaps and then this can become the default. + ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (bypass the indented area). + ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) + //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 14, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog +}; + +// Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. +// - To be backward compatible with older API which took an 'int mouse_button = 1' argument, we need to treat +// small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. +// It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. +// - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. +// IMPORTANT: because the default parameter is 1 (==ImGuiPopupFlags_MouseButtonRight), if you rely on the default parameter +// and want to another another flag, you need to pass in the ImGuiPopupFlags_MouseButtonRight flag. +// - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). +enum ImGuiPopupFlags_ +{ + ImGuiPopupFlags_None = 0, + ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as ImGuiMouseButton_Left) + ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as ImGuiMouseButton_Right) + ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as ImGuiMouseButton_Middle) + ImGuiPopupFlags_MouseButtonMask_ = 0x1F, + ImGuiPopupFlags_MouseButtonDefault_ = 1, + ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack + ImGuiPopupFlags_NoOpenOverItems = 1 << 6, // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space + ImGuiPopupFlags_AnyPopupId = 1 << 7, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. + ImGuiPopupFlags_AnyPopupLevel = 1 << 8, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) + ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel +}; + +// Flags for ImGui::Selectable() +enum ImGuiSelectableFlags_ +{ + ImGuiSelectableFlags_None = 0, + ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window + ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) + ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too + ImGuiSelectableFlags_Disabled = 1 << 3, // Cannot be selected, display grayed out text + ImGuiSelectableFlags_AllowItemOverlap = 1 << 4 // (WIP) Hit testing to allow subsequent widgets to overlap this one +}; + +// Flags for ImGui::BeginCombo() +enum ImGuiComboFlags_ +{ + ImGuiComboFlags_None = 0, + ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default + ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() + ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default) + ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible + ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible + ImGuiComboFlags_NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button + ImGuiComboFlags_NoPreview = 1 << 6, // Display only a square arrow button + ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest +}; + +// Flags for ImGui::BeginTabBar() +enum ImGuiTabBarFlags_ +{ + ImGuiTabBarFlags_None = 0, + ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list + ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear + ImGuiTabBarFlags_TabListPopupButton = 1 << 2, // Disable buttons to open the tab list popup + ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. + ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) + ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab + ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 6, // Resize tabs when they don't fit + ImGuiTabBarFlags_FittingPolicyScroll = 1 << 7, // Add scroll buttons when tabs don't fit + ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll, + ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown +}; + +// Flags for ImGui::BeginTabItem() +enum ImGuiTabItemFlags_ +{ + ImGuiTabItemFlags_None = 0, + ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Display a dot next to the title + tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem() + ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. + ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() + ImGuiTabItemFlags_NoTooltip = 1 << 4, // Disable tooltip for the given tab + ImGuiTabItemFlags_NoReorder = 1 << 5, // Disable reordering this tab or having another tab cross over this tab + ImGuiTabItemFlags_Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button) + ImGuiTabItemFlags_Trailing = 1 << 7 // Enforce the tab position to the right of the tab bar (before the scrolling buttons) +}; + +// Flags for ImGui::BeginTable() +// - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. +// Read comments/demos carefully + experiment with live demos to get acquainted with them. +// - The DEFAULT sizing policies are: +// - Default to ImGuiTableFlags_SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags_AlwaysAutoResize. +// - Default to ImGuiTableFlags_SizingStretchSame if ScrollX is off. +// - When ScrollX is off: +// - Table defaults to ImGuiTableFlags_SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch with same weight. +// - Columns sizing policy allowed: Stretch (default), Fixed/Auto. +// - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). +// - Stretch Columns will share the remaining width according to their respective weight. +// - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. +// The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +// (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). +// - When ScrollX is on: +// - Table defaults to ImGuiTableFlags_SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed +// - Columns sizing policy allowed: Fixed/Auto mostly. +// - Fixed Columns can be enlarged as needed. Table will show an horizontal scrollbar if needed. +// - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. +// - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). +// If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. +// - Read on documentation at the top of imgui_tables.cpp for details. +enum ImGuiTableFlags_ +{ + // Features + ImGuiTableFlags_None = 0, + ImGuiTableFlags_Resizable = 1 << 0, // Enable resizing columns. + ImGuiTableFlags_Reorderable = 1 << 1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) + ImGuiTableFlags_Hideable = 1 << 2, // Enable hiding/disabling columns in context menu. + ImGuiTableFlags_Sortable = 1 << 3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. + ImGuiTableFlags_NoSavedSettings = 1 << 4, // Disable persisting columns order, width and sort settings in the .ini file. + ImGuiTableFlags_ContextMenuInBody = 1 << 5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). + // Decorations + ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) + ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows. + ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom. + ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns. + ImGuiTableFlags_BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides. + ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders. + ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders. + ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. + ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. + ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. + ImGuiTableFlags_NoBordersInBody = 1 << 11, // [ALPHA] Disable vertical borders in columns Body (borders will always appears in Headers). -> May move to style + ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12, // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers). -> May move to style + // Sizing Policy (read above for defaults) + ImGuiTableFlags_SizingFixedFit = 1 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. + ImGuiTableFlags_SizingFixedSame = 2 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible. + ImGuiTableFlags_SizingStretchProp = 3 << 13, // Columns default to _WidthStretch with default weights proportional to each columns contents widths. + ImGuiTableFlags_SizingStretchSame = 4 << 13, // Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). + // Sizing Extra Options + ImGuiTableFlags_NoHostExtendX = 1 << 16, // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. + ImGuiTableFlags_NoHostExtendY = 1 << 17, // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. + ImGuiTableFlags_PreciseWidths = 1 << 19, // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. + // Clipping + ImGuiTableFlags_NoClip = 1 << 20, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). + // Padding + ImGuiTableFlags_PadOuterX = 1 << 21, // Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers. + ImGuiTableFlags_NoPadOuterX = 1 << 22, // Default if BordersOuterV is off. Disable outer-most padding. + ImGuiTableFlags_NoPadInnerX = 1 << 23, // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). + // Scrolling + ImGuiTableFlags_ScrollX = 1 << 24, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. + ImGuiTableFlags_ScrollY = 1 << 25, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + // Sorting + ImGuiTableFlags_SortMulti = 1 << 26, // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). + ImGuiTableFlags_SortTristate = 1 << 27, // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). + + // [Internal] Combinations and masks + ImGuiTableFlags_SizingMask_ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame + + // Obsolete names (will be removed soon) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //, ImGuiTableFlags_ColumnsWidthFixed = ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_ColumnsWidthStretch = ImGuiTableFlags_SizingStretchSame // WIP Tables 2020/12 + //, ImGuiTableFlags_SizingPolicyFixed = ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingPolicyStretch = ImGuiTableFlags_SizingStretchSame // WIP Tables 2021/01 +#endif +}; + +// Flags for ImGui::TableSetupColumn() +enum ImGuiTableColumnFlags_ +{ + // Input configuration flags + ImGuiTableColumnFlags_None = 0, + ImGuiTableColumnFlags_Disabled = 1 << 0, // Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) + ImGuiTableColumnFlags_DefaultHide = 1 << 1, // Default as a hidden/disabled column. + ImGuiTableColumnFlags_DefaultSort = 1 << 2, // Default as a sorting column. + ImGuiTableColumnFlags_WidthStretch = 1 << 3, // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). + ImGuiTableColumnFlags_WidthFixed = 1 << 4, // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). + ImGuiTableColumnFlags_NoResize = 1 << 5, // Disable manual resizing. + ImGuiTableColumnFlags_NoReorder = 1 << 6, // Disable manual reordering this column, this will also prevent other columns from crossing over this column. + ImGuiTableColumnFlags_NoHide = 1 << 7, // Disable ability to hide/disable this column. + ImGuiTableColumnFlags_NoClip = 1 << 8, // Disable clipping for this column (all NoClip columns will render in a same draw command). + ImGuiTableColumnFlags_NoSort = 1 << 9, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). + ImGuiTableColumnFlags_NoSortAscending = 1 << 10, // Disable ability to sort in the ascending direction. + ImGuiTableColumnFlags_NoSortDescending = 1 << 11, // Disable ability to sort in the descending direction. + ImGuiTableColumnFlags_NoHeaderLabel = 1 << 12, // TableHeadersRow() will not submit label for this column. Convenient for some small columns. Name will still appear in context menu. + ImGuiTableColumnFlags_NoHeaderWidth = 1 << 13, // Disable header text width contribution to automatic column width. + ImGuiTableColumnFlags_PreferSortAscending = 1 << 14, // Make the initial sort direction Ascending when first sorting on this column (default). + ImGuiTableColumnFlags_PreferSortDescending = 1 << 15, // Make the initial sort direction Descending when first sorting on this column. + ImGuiTableColumnFlags_IndentEnable = 1 << 16, // Use current Indent value when entering cell (default for column 0). + ImGuiTableColumnFlags_IndentDisable = 1 << 17, // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. + + // Output status flags, read-only via TableGetColumnFlags() + ImGuiTableColumnFlags_IsEnabled = 1 << 24, // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. + ImGuiTableColumnFlags_IsVisible = 1 << 25, // Status: is visible == is enabled AND not clipped by scrolling. + ImGuiTableColumnFlags_IsSorted = 1 << 26, // Status: is currently part of the sort specs + ImGuiTableColumnFlags_IsHovered = 1 << 27, // Status: is hovered by mouse + + // [Internal] Combinations and masks + ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed, + ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable, + ImGuiTableColumnFlags_StatusMask_ = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered, + ImGuiTableColumnFlags_NoDirectResize_ = 1 << 30 // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) + + // Obsolete names (will be removed soon) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //ImGuiTableColumnFlags_WidthAuto = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize, // Column will not stretch and keep resizing based on submitted contents. +#endif +}; + +// Flags for ImGui::TableNextRow() +enum ImGuiTableRowFlags_ +{ + ImGuiTableRowFlags_None = 0, + ImGuiTableRowFlags_Headers = 1 << 0 // Identify header row (set default background color + width of its contents accounted differently for auto column width) +}; + +// Enum for ImGui::TableSetBgColor() +// Background colors are rendering in 3 layers: +// - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. +// - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. +// - Layer 2: draw with CellBg color if set. +// The purpose of the two row/columns layers is to let you decide if a background color changes should override or blend with the existing color. +// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. +// If you set the color of RowBg0 target, your color will override the existing RowBg0 color. +// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. +enum ImGuiTableBgTarget_ +{ + ImGuiTableBgTarget_None = 0, + ImGuiTableBgTarget_RowBg0 = 1, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) + ImGuiTableBgTarget_RowBg1 = 2, // Set row background color 1 (generally used for selection marking) + ImGuiTableBgTarget_CellBg = 3 // Set cell background color (top-most color) +}; + +// Flags for ImGui::IsWindowFocused() +enum ImGuiFocusedFlags_ +{ + ImGuiFocusedFlags_None = 0, + ImGuiFocusedFlags_ChildWindows = 1 << 0, // Return true if any children of the window is focused + ImGuiFocusedFlags_RootWindow = 1 << 1, // Test from root window (top most parent of the current hierarchy) + ImGuiFocusedFlags_AnyWindow = 1 << 2, // Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! + ImGuiFocusedFlags_NoPopupHierarchy = 1 << 3, // Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + ImGuiFocusedFlags_DockHierarchy = 1 << 4, // Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows +}; + +// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered() +// Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ! +// Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls. +enum ImGuiHoveredFlags_ +{ + ImGuiHoveredFlags_None = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. + ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered + ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) + ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered + ImGuiHoveredFlags_NoPopupHierarchy = 1 << 3, // IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + ImGuiHoveredFlags_DockHierarchy = 1 << 4, // IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 5, // Return true even if a popup window is normally blocking access to this item/window + //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 6, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 7, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. + ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 8, // IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window + ImGuiHoveredFlags_AllowWhenDisabled = 1 << 9, // IsItemHovered() only: Return true even if the item is disabled + ImGuiHoveredFlags_NoNavOverride = 1 << 10, // Disable using gamepad/keyboard navigation state when active, always query mouse. + ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, + ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows +}; + +// Flags for ImGui::DockSpace(), shared/inherited by child nodes. +// (Some flags can be applied to individual nodes directly) +// FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api. +enum ImGuiDockNodeFlags_ +{ + ImGuiDockNodeFlags_None = 0, + ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // Shared // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. + //ImGuiDockNodeFlags_NoCentralNode = 1 << 1, // Shared // Disable Central Node (the node which can stay empty) + ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 2, // Shared // Disable docking inside the Central Node, which will be always kept empty. + ImGuiDockNodeFlags_PassthruCentralNode = 1 << 3, // Shared // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. + ImGuiDockNodeFlags_NoSplit = 1 << 4, // Shared/Local // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved. + ImGuiDockNodeFlags_NoResize = 1 << 5, // Shared/Local // Disable resizing node using the splitter/separators. Useful with programmatically setup dockspaces. + ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6 // Shared/Local // Tab bar will automatically hide when there is a single window in the dock node. +}; + +// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() +enum ImGuiDragDropFlags_ +{ + ImGuiDragDropFlags_None = 0, + // BeginDragDropSource() flags + ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior. + ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item. + ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. + ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. + ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. + ImGuiDragDropFlags_SourceAutoExpirePayload = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) + // AcceptDragDropPayload() flags + ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. + ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. + ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. + ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect // For peeking ahead and inspecting the payload before delivery. +}; + +// Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui. +#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3]: Standard type for colors, without alpha. User code may use this type. +#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4]: Standard type for colors. User code may use this type. + +// A primary data type +enum ImGuiDataType_ +{ + ImGuiDataType_S8, // signed char / char (with sensible compilers) + ImGuiDataType_U8, // unsigned char + ImGuiDataType_S16, // short + ImGuiDataType_U16, // unsigned short + ImGuiDataType_S32, // int + ImGuiDataType_U32, // unsigned int + ImGuiDataType_S64, // long long / __int64 + ImGuiDataType_U64, // unsigned long long / unsigned __int64 + ImGuiDataType_Float, // float + ImGuiDataType_Double, // double + ImGuiDataType_COUNT +}; + +// A cardinal direction +enum ImGuiDir_ +{ + ImGuiDir_None = -1, + ImGuiDir_Left = 0, + ImGuiDir_Right = 1, + ImGuiDir_Up = 2, + ImGuiDir_Down = 3, + ImGuiDir_COUNT +}; + +// A sorting direction +enum ImGuiSortDirection_ +{ + ImGuiSortDirection_None = 0, + ImGuiSortDirection_Ascending = 1, // Ascending = 0->9, A->Z etc. + ImGuiSortDirection_Descending = 2 // Descending = 9->0, Z->A etc. +}; + +enum ImGuiKey_ +{ + // Keyboard + ImGuiKey_None = 0, + ImGuiKey_Tab = 512, // == ImGuiKey_NamedKey_BEGIN + ImGuiKey_LeftArrow, + ImGuiKey_RightArrow, + ImGuiKey_UpArrow, + ImGuiKey_DownArrow, + ImGuiKey_PageUp, + ImGuiKey_PageDown, + ImGuiKey_Home, + ImGuiKey_End, + ImGuiKey_Insert, + ImGuiKey_Delete, + ImGuiKey_Backspace, + ImGuiKey_Space, + ImGuiKey_Enter, + ImGuiKey_Escape, + ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, + ImGuiKey_RightCtrl, ImGuiKey_RightShift, ImGuiKey_RightAlt, ImGuiKey_RightSuper, + ImGuiKey_Menu, + ImGuiKey_0, ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, + ImGuiKey_A, ImGuiKey_B, ImGuiKey_C, ImGuiKey_D, ImGuiKey_E, ImGuiKey_F, ImGuiKey_G, ImGuiKey_H, ImGuiKey_I, ImGuiKey_J, + ImGuiKey_K, ImGuiKey_L, ImGuiKey_M, ImGuiKey_N, ImGuiKey_O, ImGuiKey_P, ImGuiKey_Q, ImGuiKey_R, ImGuiKey_S, ImGuiKey_T, + ImGuiKey_U, ImGuiKey_V, ImGuiKey_W, ImGuiKey_X, ImGuiKey_Y, ImGuiKey_Z, + ImGuiKey_F1, ImGuiKey_F2, ImGuiKey_F3, ImGuiKey_F4, ImGuiKey_F5, ImGuiKey_F6, + ImGuiKey_F7, ImGuiKey_F8, ImGuiKey_F9, ImGuiKey_F10, ImGuiKey_F11, ImGuiKey_F12, + ImGuiKey_Apostrophe, // ' + ImGuiKey_Comma, // , + ImGuiKey_Minus, // - + ImGuiKey_Period, // . + ImGuiKey_Slash, // / + ImGuiKey_Semicolon, // ; + ImGuiKey_Equal, // = + ImGuiKey_LeftBracket, // [ + ImGuiKey_Backslash, // \ (this text inhibit multiline comment caused by backslash) + ImGuiKey_RightBracket, // ] + ImGuiKey_GraveAccent, // ` + ImGuiKey_CapsLock, + ImGuiKey_ScrollLock, + ImGuiKey_NumLock, + ImGuiKey_PrintScreen, + ImGuiKey_Pause, + ImGuiKey_Keypad0, ImGuiKey_Keypad1, ImGuiKey_Keypad2, ImGuiKey_Keypad3, ImGuiKey_Keypad4, + ImGuiKey_Keypad5, ImGuiKey_Keypad6, ImGuiKey_Keypad7, ImGuiKey_Keypad8, ImGuiKey_Keypad9, + ImGuiKey_KeypadDecimal, + ImGuiKey_KeypadDivide, + ImGuiKey_KeypadMultiply, + ImGuiKey_KeypadSubtract, + ImGuiKey_KeypadAdd, + ImGuiKey_KeypadEnter, + ImGuiKey_KeypadEqual, + + // Gamepad (some of those are analog values, 0.0f to 1.0f) // NAVIGATION action + ImGuiKey_GamepadStart, // Menu (Xbox) + (Switch) Start/Options (PS) // -- + ImGuiKey_GamepadBack, // View (Xbox) - (Switch) Share (PS) // -- + ImGuiKey_GamepadFaceUp, // Y (Xbox) X (Switch) Triangle (PS) // -> ImGuiNavInput_Input + ImGuiKey_GamepadFaceDown, // A (Xbox) B (Switch) Cross (PS) // -> ImGuiNavInput_Activate + ImGuiKey_GamepadFaceLeft, // X (Xbox) Y (Switch) Square (PS) // -> ImGuiNavInput_Menu + ImGuiKey_GamepadFaceRight, // B (Xbox) A (Switch) Circle (PS) // -> ImGuiNavInput_Cancel + ImGuiKey_GamepadDpadUp, // D-pad Up // -> ImGuiNavInput_DpadUp + ImGuiKey_GamepadDpadDown, // D-pad Down // -> ImGuiNavInput_DpadDown + ImGuiKey_GamepadDpadLeft, // D-pad Left // -> ImGuiNavInput_DpadLeft + ImGuiKey_GamepadDpadRight, // D-pad Right // -> ImGuiNavInput_DpadRight + ImGuiKey_GamepadL1, // L Bumper (Xbox) L (Switch) L1 (PS) // -> ImGuiNavInput_FocusPrev + ImGuiNavInput_TweakSlow + ImGuiKey_GamepadR1, // R Bumper (Xbox) R (Switch) R1 (PS) // -> ImGuiNavInput_FocusNext + ImGuiNavInput_TweakFast + ImGuiKey_GamepadL2, // L Trigger (Xbox) ZL (Switch) L2 (PS) [Analog] + ImGuiKey_GamepadR2, // R Trigger (Xbox) ZR (Switch) R2 (PS) [Analog] + ImGuiKey_GamepadL3, // L Thumbstick (Xbox) L3 (Switch) L3 (PS) + ImGuiKey_GamepadR3, // R Thumbstick (Xbox) R3 (Switch) R3 (PS) + ImGuiKey_GamepadLStickUp, // [Analog] // -> ImGuiNavInput_LStickUp + ImGuiKey_GamepadLStickDown, // [Analog] // -> ImGuiNavInput_LStickDown + ImGuiKey_GamepadLStickLeft, // [Analog] // -> ImGuiNavInput_LStickLeft + ImGuiKey_GamepadLStickRight, // [Analog] // -> ImGuiNavInput_LStickRight + ImGuiKey_GamepadRStickUp, // [Analog] + ImGuiKey_GamepadRStickDown, // [Analog] + ImGuiKey_GamepadRStickLeft, // [Analog] + ImGuiKey_GamepadRStickRight, // [Analog] + + // Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) + // - This is mirroring the data also written to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper, in a format allowing + // them to be accessed via standard key API, allowing calls such as IsKeyPressed(), IsKeyReleased(), querying duration etc. + // - Code polling every keys (e.g. an interface to detect a key press for input mapping) might want to ignore those + // and prefer using the real keys (e.g. ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl instead of ImGuiKey_ModCtrl). + // - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys. + // In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and + // backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user... + ImGuiKey_ModCtrl, ImGuiKey_ModShift, ImGuiKey_ModAlt, ImGuiKey_ModSuper, + + // End of list + ImGuiKey_COUNT, // No valid ImGuiKey is ever greater than this value + + // [Internal] Prior to 1.87 we required user to fill io.KeysDown[512] using their own native index + a io.KeyMap[] array. + // We are ditching this method but keeping a legacy path for user code doing e.g. IsKeyPressed(MY_NATIVE_KEY_CODE) + ImGuiKey_NamedKey_BEGIN = 512, + ImGuiKey_NamedKey_END = ImGuiKey_COUNT, + ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN, +#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO + ImGuiKey_KeysData_SIZE = ImGuiKey_NamedKey_COUNT, // Size of KeysData[]: only hold named keys + ImGuiKey_KeysData_OFFSET = ImGuiKey_NamedKey_BEGIN // First key stored in KeysData[0] +#else + ImGuiKey_KeysData_SIZE = ImGuiKey_COUNT, // Size of KeysData[]: hold legacy 0..512 keycodes + named keys + ImGuiKey_KeysData_OFFSET = 0 // First key stored in KeysData[0] +#endif + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter // Renamed in 1.87 +#endif +}; + +// Helper "flags" version of key-mods to store and compare multiple key-mods easily. Sometimes used for storage (e.g. io.KeyMods) but otherwise not much used in public API. +enum ImGuiModFlags_ +{ + ImGuiModFlags_None = 0, + ImGuiModFlags_Ctrl = 1 << 0, + ImGuiModFlags_Shift = 1 << 1, + ImGuiModFlags_Alt = 1 << 2, // Menu + ImGuiModFlags_Super = 1 << 3 // Cmd/Super/Windows key +}; + +// Gamepad/Keyboard navigation +// Keyboard: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.AddKeyEvent() calls. +// Gamepad: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Backend: set ImGuiBackendFlags_HasGamepad and fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame(). +// Read instructions in imgui.cpp for more details. Download PNG/PSD at http://dearimgui.org/controls_sheets. +enum ImGuiNavInput_ +{ + // Gamepad Mapping + ImGuiNavInput_Activate, // Activate / Open / Toggle / Tweak value // e.g. Cross (PS4), A (Xbox), A (Switch), Space (Keyboard) + ImGuiNavInput_Cancel, // Cancel / Close / Exit // e.g. Circle (PS4), B (Xbox), B (Switch), Escape (Keyboard) + ImGuiNavInput_Input, // Text input / On-Screen keyboard // e.g. Triang.(PS4), Y (Xbox), X (Switch), Return (Keyboard) + ImGuiNavInput_Menu, // Tap: Toggle menu / Hold: Focus, Move, Resize // e.g. Square (PS4), X (Xbox), Y (Switch), Alt (Keyboard) + ImGuiNavInput_DpadLeft, // Move / Tweak / Resize window (w/ PadMenu) // e.g. D-pad Left/Right/Up/Down (Gamepads), Arrow keys (Keyboard) + ImGuiNavInput_DpadRight, // + ImGuiNavInput_DpadUp, // + ImGuiNavInput_DpadDown, // + ImGuiNavInput_LStickLeft, // Scroll / Move window (w/ PadMenu) // e.g. Left Analog Stick Left/Right/Up/Down + ImGuiNavInput_LStickRight, // + ImGuiNavInput_LStickUp, // + ImGuiNavInput_LStickDown, // + ImGuiNavInput_FocusPrev, // Focus Next window (w/ PadMenu) // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch) + ImGuiNavInput_FocusNext, // Focus Prev window (w/ PadMenu) // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch) + ImGuiNavInput_TweakSlow, // Slower tweaks // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch) + ImGuiNavInput_TweakFast, // Faster tweaks // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch) + + // [Internal] Don't use directly! This is used internally to differentiate keyboard from gamepad inputs for behaviors that require to differentiate them. + // Keyboard behavior that have no corresponding gamepad mapping (e.g. CTRL+TAB) will be directly reading from keyboard keys instead of io.NavInputs[]. + ImGuiNavInput_KeyLeft_, // Move left // = Arrow keys + ImGuiNavInput_KeyRight_, // Move right + ImGuiNavInput_KeyUp_, // Move up + ImGuiNavInput_KeyDown_, // Move down + ImGuiNavInput_COUNT +}; + +// Configuration flags stored in io.ConfigFlags. Set by user/application. +enum ImGuiConfigFlags_ +{ + ImGuiConfigFlags_None = 0, + ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.AddKeyEvent() calls + ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui backend to fill io.NavInputs[]. Backend also needs to set ImGuiBackendFlags_HasGamepad. + ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your backend, otherwise ImGui will react as if the mouse is jumping around back and forth. + ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set. + ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the backend. + ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. + + // [BETA] Docking + ImGuiConfigFlags_DockingEnable = 1 << 6, // Docking enable flags. + + // [BETA] Viewports + // When using viewports it is recommended that your default value for ImGuiCol_WindowBg is opaque (Alpha=1.0) so transition to a viewport won't be noticeable. + ImGuiConfigFlags_ViewportsEnable = 1 << 10, // Viewport enable flags (require both ImGuiBackendFlags_PlatformHasViewports + ImGuiBackendFlags_RendererHasViewports set by the respective backends) + ImGuiConfigFlags_DpiEnableScaleViewports= 1 << 14, // [BETA: Don't use] FIXME-DPI: Reposition and resize imgui windows when the DpiScale of a viewport changed (mostly useful for the main viewport hosting other window). Note that resizing the main window itself is up to your application. + ImGuiConfigFlags_DpiEnableScaleFonts = 1 << 15, // [BETA: Don't use] FIXME-DPI: Request bitmap-scaled fonts to match DpiScale. This is a very low-quality workaround. The correct way to handle DPI is _currently_ to replace the atlas and/or fonts in the Platform_OnChangedViewport callback, but this is all early work in progress. + + // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core Dear ImGui) + ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. + ImGuiConfigFlags_IsTouchScreen = 1 << 21 // Application is using a touch screen instead of a mouse. +}; + +// Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend. +enum ImGuiBackendFlags_ +{ + ImGuiBackendFlags_None = 0, + ImGuiBackendFlags_HasGamepad = 1 << 0, // Backend Platform supports gamepad and currently has one connected. + ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. + ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). + ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3, // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. + + // [BETA] Viewports + ImGuiBackendFlags_PlatformHasViewports = 1 << 10, // Backend Platform supports multiple viewports. + ImGuiBackendFlags_HasMouseHoveredViewport=1 << 11, // Backend Platform supports calling io.AddMouseViewportEvent() with the viewport under the mouse. IF POSSIBLE, ignore viewports with the ImGuiViewportFlags_NoInputs flag (Win32 backend, GLFW 3.30+ backend can do this, SDL backend cannot). If this cannot be done, Dear ImGui needs to use a flawed heuristic to find the viewport under. + ImGuiBackendFlags_RendererHasViewports = 1 << 12 // Backend Renderer supports multiple viewports. +}; + +// Enumeration for PushStyleColor() / PopStyleColor() +enum ImGuiCol_ +{ + ImGuiCol_Text, + ImGuiCol_TextDisabled, + ImGuiCol_WindowBg, // Background of normal windows + ImGuiCol_ChildBg, // Background of child windows + ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows + ImGuiCol_Border, + ImGuiCol_BorderShadow, + ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input + ImGuiCol_FrameBgHovered, + ImGuiCol_FrameBgActive, + ImGuiCol_TitleBg, + ImGuiCol_TitleBgActive, + ImGuiCol_TitleBgCollapsed, + ImGuiCol_MenuBarBg, + ImGuiCol_ScrollbarBg, + ImGuiCol_ScrollbarGrab, + ImGuiCol_ScrollbarGrabHovered, + ImGuiCol_ScrollbarGrabActive, + ImGuiCol_CheckMark, + ImGuiCol_SliderGrab, + ImGuiCol_SliderGrabActive, + ImGuiCol_Button, + ImGuiCol_ButtonHovered, + ImGuiCol_ButtonActive, + ImGuiCol_Header, // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem + ImGuiCol_HeaderHovered, + ImGuiCol_HeaderActive, + ImGuiCol_Separator, + ImGuiCol_SeparatorHovered, + ImGuiCol_SeparatorActive, + ImGuiCol_ResizeGrip, + ImGuiCol_ResizeGripHovered, + ImGuiCol_ResizeGripActive, + ImGuiCol_Tab, + ImGuiCol_TabHovered, + ImGuiCol_TabActive, + ImGuiCol_TabUnfocused, + ImGuiCol_TabUnfocusedActive, + ImGuiCol_DockingPreview, // Preview overlay color when about to docking something + ImGuiCol_DockingEmptyBg, // Background color for empty node (e.g. CentralNode with no window docked into it) + ImGuiCol_PlotLines, + ImGuiCol_PlotLinesHovered, + ImGuiCol_PlotHistogram, + ImGuiCol_PlotHistogramHovered, + ImGuiCol_TableHeaderBg, // Table header background + ImGuiCol_TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here) + ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here) + ImGuiCol_TableRowBg, // Table row background (even rows) + ImGuiCol_TableRowBgAlt, // Table row background (odd rows) + ImGuiCol_TextSelectedBg, + ImGuiCol_DragDropTarget, + ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item + ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB + ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active + ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active + ImGuiCol_COUNT +}; + +// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. +// - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. +// During initialization or between frames, feel free to just poke into ImGuiStyle directly. +// - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description. +// In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. +// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. +// - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. +enum ImGuiStyleVar_ +{ + // Enum name --------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions) + ImGuiStyleVar_Alpha, // float Alpha + ImGuiStyleVar_DisabledAlpha, // float DisabledAlpha + ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding + ImGuiStyleVar_WindowRounding, // float WindowRounding + ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize + ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize + ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign + ImGuiStyleVar_ChildRounding, // float ChildRounding + ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize + ImGuiStyleVar_PopupRounding, // float PopupRounding + ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize + ImGuiStyleVar_FramePadding, // ImVec2 FramePadding + ImGuiStyleVar_FrameRounding, // float FrameRounding + ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize + ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing + ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing + ImGuiStyleVar_IndentSpacing, // float IndentSpacing + ImGuiStyleVar_CellPadding, // ImVec2 CellPadding + ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize + ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding + ImGuiStyleVar_GrabMinSize, // float GrabMinSize + ImGuiStyleVar_GrabRounding, // float GrabRounding + ImGuiStyleVar_TabRounding, // float TabRounding + ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign + ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign + ImGuiStyleVar_COUNT +}; + +// Flags for InvisibleButton() [extended in imgui_internal.h] +enum ImGuiButtonFlags_ +{ + ImGuiButtonFlags_None = 0, + ImGuiButtonFlags_MouseButtonLeft = 1 << 0, // React on left mouse button (default) + ImGuiButtonFlags_MouseButtonRight = 1 << 1, // React on right mouse button + ImGuiButtonFlags_MouseButtonMiddle = 1 << 2, // React on center mouse button + + // [Internal] + ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, + ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft +}; + +// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() +enum ImGuiColorEditFlags_ +{ + ImGuiColorEditFlags_None = 0, + ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). + ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on color square. + ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. + ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) + ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). + ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. + ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). + ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. + ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. + ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) + + // User Options (right-click on widget to change some of them). + ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. + ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. + ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. + ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). + ImGuiColorEditFlags_DisplayRGB = 1 << 20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. + ImGuiColorEditFlags_DisplayHSV = 1 << 21, // [Display] // " + ImGuiColorEditFlags_DisplayHex = 1 << 22, // [Display] // " + ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. + ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. + ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [Picker] // ColorPicker: bar for Hue, rectangle for Sat/Value. + ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [Picker] // ColorPicker: wheel for Hue, triangle for Sat/Value. + ImGuiColorEditFlags_InputRGB = 1 << 27, // [Input] // ColorEdit, ColorPicker: input and output data in RGB format. + ImGuiColorEditFlags_InputHSV = 1 << 28, // [Input] // ColorEdit, ColorPicker: input and output data in HSV format. + + // Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to + // override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup. + ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar, + + // [Internal] Masks + ImGuiColorEditFlags_DisplayMask_ = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, + ImGuiColorEditFlags_DataTypeMask_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, + ImGuiColorEditFlags_PickerMask_ = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags_InputMask_ = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV + + // Obsolete names (will be removed) + // ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69] +}; + +// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. +enum ImGuiSliderFlags_ +{ + ImGuiSliderFlags_None = 0, + ImGuiSliderFlags_AlwaysClamp = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. + ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. + ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget + ImGuiSliderFlags_InvalidMask_ = 0x7000000F // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiSliderFlags_ClampOnInput = ImGuiSliderFlags_AlwaysClamp // [renamed in 1.79] +#endif +}; + +// Identify a mouse button. +// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. +enum ImGuiMouseButton_ +{ + ImGuiMouseButton_Left = 0, + ImGuiMouseButton_Right = 1, + ImGuiMouseButton_Middle = 2, + ImGuiMouseButton_COUNT = 5 +}; + +// Enumeration for GetMouseCursor() +// User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here +enum ImGuiMouseCursor_ +{ + ImGuiMouseCursor_None = -1, + ImGuiMouseCursor_Arrow = 0, + ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. + ImGuiMouseCursor_ResizeAll, // (Unused by Dear ImGui functions) + ImGuiMouseCursor_ResizeNS, // When hovering over an horizontal border + ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column + ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window + ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window + ImGuiMouseCursor_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks) + ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle. + ImGuiMouseCursor_COUNT +}; + +// Enumeration for ImGui::SetWindow***(), SetNextWindow***(), SetNextItem***() functions +// Represent a condition. +// Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. +enum ImGuiCond_ +{ + ImGuiCond_None = 0, // No condition (always set the variable), same as _Always + ImGuiCond_Always = 1 << 0, // No condition (always set the variable) + ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will succeed) + ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) + ImGuiCond_Appearing = 1 << 3 // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) +}; + +//----------------------------------------------------------------------------- +// [SECTION] Helpers: Memory allocations macros, ImVector<> +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a custom parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +//----------------------------------------------------------------------------- + +struct ImNewWrapper {}; +inline void* operator new(size_t, ImNewWrapper, void* ptr) { return ptr; } +inline void operator delete(void*, ImNewWrapper, void*) {} // This is only required so we can use the symmetrical new() +#define IM_ALLOC(_SIZE) ImGui::MemAlloc(_SIZE) +#define IM_FREE(_PTR) ImGui::MemFree(_PTR) +#define IM_PLACEMENT_NEW(_PTR) new(ImNewWrapper(), _PTR) +#define IM_NEW(_TYPE) new(ImNewWrapper(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE +template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } + +//----------------------------------------------------------------------------- +// ImVector<> +// Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug). +//----------------------------------------------------------------------------- +// - You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our public structures are relying on it. +// - We use std-like naming convention here, which is a little unusual for this codebase. +// - Important: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs. +// - Important: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that, +// Do NOT use this class as a std::vector replacement in your own code! Many of the structures used by dear imgui can be safely initialized by a zero-memset. +//----------------------------------------------------------------------------- + +IM_MSVC_RUNTIME_CHECKS_OFF +template +struct ImVector +{ + int Size; + int Capacity; + T* Data; + + // Provide standard typedefs but we don't use them ourselves. + typedef T value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + + // Constructors, destructor + inline ImVector() { Size = Capacity = 0; Data = NULL; } + inline ImVector(const ImVector& src) { Size = Capacity = 0; Data = NULL; operator=(src); } + inline ImVector& operator=(const ImVector& src) { clear(); resize(src.Size); memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; } + inline ~ImVector() { if (Data) IM_FREE(Data); } // Important: does not destruct anything + + inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } } // Important: does not destruct anything + inline void clear_delete() { for (int n = 0; n < Size; n++) IM_DELETE(Data[n]); clear(); } // Important: never called automatically! always explicit. + inline void clear_destruct() { for (int n = 0; n < Size; n++) Data[n].~T(); clear(); } // Important: never called automatically! always explicit. + + inline bool empty() const { return Size == 0; } + inline int size() const { return Size; } + inline int size_in_bytes() const { return Size * (int)sizeof(T); } + inline int max_size() const { return 0x7FFFFFFF / (int)sizeof(T); } + inline int capacity() const { return Capacity; } + inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } + inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } + + inline T* begin() { return Data; } + inline const T* begin() const { return Data; } + inline T* end() { return Data + Size; } + inline const T* end() const { return Data + Size; } + inline T& front() { IM_ASSERT(Size > 0); return Data[0]; } + inline const T& front() const { IM_ASSERT(Size > 0); return Data[0]; } + inline T& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; } + inline const T& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; } + inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } + + inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity / 2) : 8; return new_capacity > sz ? new_capacity : sz; } + inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } + inline void resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } + inline void shrink(int new_size) { IM_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation + inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; } + + // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden. + inline void push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } + inline void pop_back() { IM_ASSERT(Size > 0); Size--; } + inline void push_front(const T& v) { if (Size == 0) push_back(v); else insert(Data, v); } + inline T* erase(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; } + inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data + Size && it_last >= it && it_last <= Data + Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - (size_t)count) * sizeof(T)); Size -= (int)count; return Data + off; } + inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; if (it < Data + Size - 1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; } + inline T* insert(const T* it, const T& v) { IM_ASSERT(it >= Data && it <= Data + Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } + inline bool contains(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; } + inline T* find(const T& v) { T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } + inline const T* find(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } + inline bool find_erase(const T& v) { const T* it = find(v); if (it < Data + Size) { erase(it); return true; } return false; } + inline bool find_erase_unsorted(const T& v) { const T* it = find(v); if (it < Data + Size) { erase_unsorted(it); return true; } return false; } + inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; return (int)off; } +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiStyle +//----------------------------------------------------------------------------- +// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame(). +// During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, +// and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors. +//----------------------------------------------------------------------------- + +struct ImGuiStyle +{ + float Alpha; // Global alpha applies to everything in Dear ImGui. + float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. + ImVec2 WindowPadding; // Padding within a window. + float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. + float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints(). + ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. + ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left. + float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows. + float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding) + float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets). + float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). + float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). + ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines. + ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label). + ImVec2 CellPadding; // Padding within a table cell + ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). + float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. + float ScrollbarRounding; // Radius of grab corners for scrollbar. + float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. + float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. + float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. + float TabBorderSize; // Thickness of border around tabs. + float TabMinWidthForCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. + ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. + ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). + ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. + ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows. + ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! + float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + ImVec4 Colors[ImGuiCol_COUNT]; + + IMGUI_API ImGuiStyle(); + IMGUI_API void ScaleAllSizes(float scale_factor); +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiIO +//----------------------------------------------------------------------------- +// Communicate most settings and inputs/outputs to Dear ImGui using this structure. +// Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage. +//----------------------------------------------------------------------------- + +// [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions. +// If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and not io.KeysData[key]->DownDuration. +struct ImGuiKeyData +{ + bool Down; // True for if key is down + float DownDuration; // Duration the key has been down (<0.0f: not pressed, 0.0f: just pressed, >0.0f: time held) + float DownDurationPrev; // Last frame duration the key has been down + float AnalogValue; // 0.0f..1.0f for gamepad values +}; + +struct ImGuiIO +{ + //------------------------------------------------------------------ + // Configuration // Default value + //------------------------------------------------------------------ + + ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc. + ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. + ImVec2 DisplaySize; // // Main display size, in pixels (generally == GetMainViewport()->Size). May change every frame. + float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. May change every frame. + float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. + const char* IniFilename; // = "imgui.ini" // Path to .ini file (important: default "imgui.ini" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions. + const char* LogFilename; // = "imgui_log.txt"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified). + float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. + float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. + float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging. + float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds. + void* UserData; // = NULL // Store your own data for retrieval by callbacks. + + ImFontAtlas*Fonts; // // Font atlas: load, rasterize and pack one or more fonts into a single texture. + float FontGlobalScale; // = 1.0f // Global scale all fonts + bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. + ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. + ImVec2 DisplayFramebufferScale; // = (1, 1) // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale. + + // Docking options (when ImGuiConfigFlags_DockingEnable is set) + bool ConfigDockingNoSplit; // = false // Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars. + bool ConfigDockingWithShift; // = false // Enable docking with holding Shift key (reduce visual noise, allows dropping in wider space) + bool ConfigDockingAlwaysTabBar; // = false // [BETA] [FIXME: This currently creates regression with auto-sizing and general overhead] Make every single floating window display within a docking node. + bool ConfigDockingTransparentPayload;// = false // [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge. + + // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) + bool ConfigViewportsNoAutoMerge; // = false; // Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set ImGuiViewportFlags_NoAutoMerge on individual viewport. + bool ConfigViewportsNoTaskBarIcon; // = false // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, ImGuiViewportFlags_NoTaskBarIcon will be set on it. + bool ConfigViewportsNoDecoration; // = true // Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, ImGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size). + bool ConfigViewportsNoDefaultParent; // = false // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = , expecting the platform backend to setup a parent/child relationship between the OS windows (some backend may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows. + + // Miscellaneous options + bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. + bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl. + bool ConfigInputTrickleEventQueue; // = true // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates. + bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor (optional as some users consider it to be distracting). + bool ConfigDragClickToInputText; // = false // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard. + bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) + bool ConfigWindowsMoveFromTitleBarOnly; // = false // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar. + float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. + + //------------------------------------------------------------------ + // Platform Functions + // (the imgui_impl_xxxx backend files are setting those up for you) + //------------------------------------------------------------------ + + // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff. + const char* BackendPlatformName; // = NULL + const char* BackendRendererName; // = NULL + void* BackendPlatformUserData; // = NULL // User data for platform backend + void* BackendRendererUserData; // = NULL // User data for renderer backend + void* BackendLanguageUserData; // = NULL // User data for non C++ programming language backend + + // Optional: Access OS clipboard + // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + const char* (*GetClipboardTextFn)(void* user_data); + void (*SetClipboardTextFn)(void* user_data, const char* text); + void* ClipboardUserData; + + // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) + // (default to use native imm32 api on Windows) + void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + void* ImeWindowHandle; // = NULL // [Obsolete] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning. +#else + void* _UnusedPadding; // Unused field to keep data structure the same size. +#endif + + //------------------------------------------------------------------ + // Input - Call before calling NewFrame() + //------------------------------------------------------------------ + + // Input Functions + IMGUI_API void AddKeyEvent(ImGuiKey key, bool down); // Queue a new key down/up event. Key should be "translated" (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character) + IMGUI_API void AddKeyAnalogEvent(ImGuiKey key, bool down, float v); // Queue a new key down/up event for analog values (e.g. ImGuiKey_Gamepad_ values). Dead-zones should be handled by the backend. + IMGUI_API void AddMousePosEvent(float x, float y); // Queue a mouse position update. Use -FLT_MAX,-FLT_MAX to signify no mouse (e.g. app not focused and not hovered) + IMGUI_API void AddMouseButtonEvent(int button, bool down); // Queue a mouse button change + IMGUI_API void AddMouseWheelEvent(float wh_x, float wh_y); // Queue a mouse wheel update + IMGUI_API void AddMouseViewportEvent(ImGuiID id); // Queue a mouse hovered viewport. Requires backend to set ImGuiBackendFlags_HasMouseHoveredViewport to call this (for multi-viewport support). + IMGUI_API void AddFocusEvent(bool focused); // Queue a gain/loss of focus for the application (generally based on OS/platform focus of your window) + IMGUI_API void AddInputCharacter(unsigned int c); // Queue a new character input + IMGUI_API void AddInputCharacterUTF16(ImWchar16 c); // Queue a new character input from an UTF-16 character, it can be a surrogate + IMGUI_API void AddInputCharactersUTF8(const char* str); // Queue a new characters input from an UTF-8 string + + IMGUI_API void ClearInputCharacters(); // [Internal] Clear the text input buffer manually + IMGUI_API void ClearInputKeys(); // [Internal] Release all keys + IMGUI_API void SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index = -1); // [Optional] Specify index for legacy <1.87 IsKeyXXX() functions with native indices + specify native keycode, scancode. + + //------------------------------------------------------------------ + // Output - Updated by NewFrame() or EndFrame()/Render() + // (when reading from the io.WantCaptureMouse, io.WantCaptureKeyboard flags to dispatch your inputs, it is + // generally easier and more correct to use their state BEFORE calling NewFrame(). See FAQ for details!) + //------------------------------------------------------------------ + + bool WantCaptureMouse; // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). + bool WantCaptureKeyboard; // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). + bool WantTextInput; // Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). + bool WantSetMousePos; // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled. + bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! + bool NavActive; // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag. + bool NavVisible; // Keyboard/Gamepad navigation is visible and allowed (will handle ImGuiKey_NavXXX events). + float Framerate; // Rough estimate of application framerate, in frame per second. Solely for convenience. Rolling average estimation based on io.DeltaTime over 120 frames. + int MetricsRenderVertices; // Vertices output during last call to Render() + int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 + int MetricsRenderWindows; // Number of visible windows + int MetricsActiveWindows; // Number of active windows + int MetricsActiveAllocations; // Number of active allocations, updated by MemAlloc/MemFree based on current context. May be off if you have multiple imgui contexts. + ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. + + // Legacy: before 1.87, we required backend to fill io.KeyMap[] (imgui->native map) during initialization and io.KeysDown[] (native indices) every frame. + // This is still temporarily supported as a legacy feature. However the new preferred scheme is for backend to call io.AddKeyEvent(). +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + int KeyMap[ImGuiKey_COUNT]; // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512. + bool KeysDown[ImGuiKey_COUNT]; // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). This used to be [512] sized. It is now ImGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow. +#endif + + //------------------------------------------------------------------ + // [Internal] Dear ImGui will maintain those fields. Forward compatibility not guaranteed! + //------------------------------------------------------------------ + + // Main Input State + // (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead) + // (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere) + ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) + bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. + float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. + float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all backends. + ImGuiID MouseHoveredViewport; // (Optional) Modify using io.AddMouseViewportEvent(). With multi-viewports: viewport the OS mouse is hovering. If possible _IGNORING_ viewports with the ImGuiViewportFlags_NoInputs flag is much better (few backends can handle that). Set io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport if you can provide this info. If you don't imgui will infer the value using the rectangles and last focused time of the viewports it knows about (ignoring other OS windows). + bool KeyCtrl; // Keyboard modifier down: Control + bool KeyShift; // Keyboard modifier down: Shift + bool KeyAlt; // Keyboard modifier down: Alt + bool KeySuper; // Keyboard modifier down: Cmd/Super/Windows + float NavInputs[ImGuiNavInput_COUNT]; // Gamepad inputs. Cleared back to zero by EndFrame(). Keyboard keys will be auto-mapped and be written here by NewFrame(). + + // Other state maintained from data above + IO function calls + ImGuiModFlags KeyMods; // Key mods flags (same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags), updated by NewFrame() + ImGuiKeyData KeysData[ImGuiKey_KeysData_SIZE]; // Key state for all known keys. Use IsKeyXXX() functions to access this. + bool WantCaptureMouseUnlessPopupClose; // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup. + ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) + ImVec2 MouseClickedPos[5]; // Position at time of clicking + double MouseClickedTime[5]; // Time of last click (used to figure out double-click) + bool MouseClicked[5]; // Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0) + bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2) + ImU16 MouseClickedCount[5]; // == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down + ImU16 MouseClickedLastCount[5]; // Count successive number of clicks. Stays valid after mouse release. Reset after another click is done. + bool MouseReleased[5]; // Mouse button went from Down to !Down + bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds. + bool MouseDownOwnedUnlessPopupClose[5]; // Track if button was clicked inside a dear imgui window. + float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) + float MouseDownDurationPrev[5]; // Previous time the mouse button has been down + ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point + float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) + float NavInputsDownDuration[ImGuiNavInput_COUNT]; + float NavInputsDownDurationPrev[ImGuiNavInput_COUNT]; + float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui. + bool AppFocusLost; + ImS8 BackendUsingLegacyKeyArrays; // -1: unknown, 0: using AddKeyEvent(), 1: using legacy io.KeysDown[] + bool BackendUsingLegacyNavInputArray; // 0: using AddKeyAnalogEvent(), 1: writing to legacy io.NavInputs[] directly + ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16() + ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper. + + IMGUI_API ImGuiIO(); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Misc data structures +//----------------------------------------------------------------------------- + +// Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. +// The callback function should return 0 by default. +// Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) +// - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) +// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration +// - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB +// - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows +// - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. +// - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. +struct ImGuiInputTextCallbackData +{ + ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only + ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only + void* UserData; // What user passed to InputText() // Read-only + + // Arguments for the different callback events + // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary. + // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state. + ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; + ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] + char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! + int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() + int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 + bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] + int CursorPos; // // Read-write // [Completion,History,Always] + int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection) + int SelectionEnd; // // Read-write // [Completion,History,Always] + + // Helper functions for text manipulation. + // Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection. + IMGUI_API ImGuiInputTextCallbackData(); + IMGUI_API void DeleteChars(int pos, int bytes_count); + IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); + void SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; } + void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; } + bool HasSelection() const { return SelectionStart != SelectionEnd; } +}; + +// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). +// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. +struct ImGuiSizeCallbackData +{ + void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints() + ImVec2 Pos; // Read-only. Window position, for reference. + ImVec2 CurrentSize; // Read-only. Current window size. + ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. +}; + +// [ALPHA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions. +// Important: the content of this class is still highly WIP and likely to change and be refactored +// before we stabilize Docking features. Please be mindful if using this. +// Provide hints: +// - To the platform backend via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) +// - To the platform backend for OS level parent/child relationships of viewport. +// - To the docking system for various options and filtering. +struct ImGuiWindowClass +{ + ImGuiID ClassId; // User data. 0 = Default class (unclassed). Windows of different classes cannot be docked with each others. + ImGuiID ParentViewportId; // Hint for the platform backend. -1: use default. 0: request platform backend to not parent the platform. != 0: request platform backend to create a parent<>child relationship between the platform windows. Not conforming backends are free to e.g. parent every viewport to the main viewport or not. + ImGuiViewportFlags ViewportFlagsOverrideSet; // Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ImGuiViewportFlags ViewportFlagsOverrideClear; // Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ImGuiTabItemFlags TabItemFlagsOverrideSet; // [EXPERIMENTAL] TabItem flags to set when a window of this class gets submitted into a dock node tab bar. May use with ImGuiTabItemFlags_Leading or ImGuiTabItemFlags_Trailing. + ImGuiDockNodeFlags DockNodeFlagsOverrideSet; // [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) + bool DockingAlwaysTabBar; // Set to true to enforce single floating windows of this class always having their own docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar) + bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. // FIXME-DOCK: Move to DockNodeFlags override? + + ImGuiWindowClass() { memset(this, 0, sizeof(*this)); ParentViewportId = (ImGuiID)-1; DockingAllowUnclassed = true; } +}; + +// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() +struct ImGuiPayload +{ + // Members + void* Data; // Data (copied and owned by dear imgui) + int DataSize; // Data size + + // [Internal] + ImGuiID SourceId; // Source item id + ImGuiID SourceParentId; // Source parent id (if available) + int DataFrameCount; // Data timestamp + char DataType[32 + 1]; // Data type tag (short user-supplied string, 32 characters max) + bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) + bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. + + ImGuiPayload() { Clear(); } + void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; } + bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; } + bool IsPreview() const { return Preview; } + bool IsDelivery() const { return Delivery; } +}; + +// Sorting specification for one column of a table (sizeof == 12 bytes) +struct ImGuiTableColumnSortSpecs +{ + ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) + ImS16 ColumnIndex; // Index of the column + ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) + ImGuiSortDirection SortDirection : 8; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending (you can use this or SortSign, whichever is more convenient for your sort function) + + ImGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); } +}; + +// Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +// Obtained by calling TableGetSortSpecs(). +// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. +// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! +struct ImGuiTableSortSpecs +{ + const ImGuiTableColumnSortSpecs* Specs; // Pointer to sort spec array. + int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled. + bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag. + + ImGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor) +//----------------------------------------------------------------------------- + +// Helper: Unicode defines +#define IM_UNICODE_CODEPOINT_INVALID 0xFFFD // Invalid Unicode code point (standard value). +#ifdef IMGUI_USE_WCHAR32 +#define IM_UNICODE_CODEPOINT_MAX 0x10FFFF // Maximum Unicode code point supported by this build. +#else +#define IM_UNICODE_CODEPOINT_MAX 0xFFFF // Maximum Unicode code point supported by this build. +#endif + +// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. +// Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame"); +struct ImGuiOnceUponAFrame +{ + ImGuiOnceUponAFrame() { RefFrame = -1; } + mutable int RefFrame; + operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } +}; + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextFilter +{ + IMGUI_API ImGuiTextFilter(const char* default_filter = ""); + IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build + IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; + IMGUI_API void Build(); + void Clear() { InputBuf[0] = 0; Build(); } + bool IsActive() const { return !Filters.empty(); } + + // [Internal] + struct ImGuiTextRange + { + const char* b; + const char* e; + + ImGuiTextRange() { b = e = NULL; } + ImGuiTextRange(const char* _b, const char* _e) { b = _b; e = _e; } + bool empty() const { return b == e; } + IMGUI_API void split(char separator, ImVector* out) const; + }; + char InputBuf[256]; + ImVectorFilters; + int CountGrep; +}; + +// Helper: Growable text buffer for logging/accumulating text +// (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') +struct ImGuiTextBuffer +{ + ImVector Buf; + IMGUI_API static char EmptyString[1]; + + ImGuiTextBuffer() { } + inline char operator[](int i) const { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; } + const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; } + const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator + int size() const { return Buf.Size ? Buf.Size - 1 : 0; } + bool empty() const { return Buf.Size <= 1; } + void clear() { Buf.clear(); } + void reserve(int capacity) { Buf.reserve(capacity); } + const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; } + IMGUI_API void append(const char* str, const char* str_end = NULL); + IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2); + IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2); +}; + +// Helper: Key->Value storage +// Typically you don't have to worry about this since a storage is held within each Window. +// We use it to e.g. store collapse state for a tree (Int 0/1) +// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame) +// You can use it as custom user storage for temporary values. Declare your own storage if, for example: +// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). +// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient) +// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. +struct ImGuiStorage +{ + // [Internal] + struct ImGuiStoragePair + { + ImGuiID key; + union { int val_i; float val_f; void* val_p; }; + ImGuiStoragePair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } + ImGuiStoragePair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } + ImGuiStoragePair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } + }; + + ImVector Data; + + // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) + // - Set***() functions find pair, insertion on demand if missing. + // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. + void Clear() { Data.clear(); } + IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; + IMGUI_API void SetInt(ImGuiID key, int val); + IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; + IMGUI_API void SetBool(ImGuiID key, bool val); + IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; + IMGUI_API void SetFloat(ImGuiID key, float val); + IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL + IMGUI_API void SetVoidPtr(ImGuiID key, void* val); + + // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. + // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. + // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) + // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; + IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); + IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); + IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); + IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); + + // Use on your own storage if you know only integer are being stored (open/close all tree nodes) + IMGUI_API void SetAllInt(int val); + + // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. + IMGUI_API void BuildSortByKey(); +}; + +// Helper: Manually clip large list of items. +// If you have lots evenly spaced items and you have a random access to the list, you can perform coarse +// clipping based on visibility to only submit items that are in view. +// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. +// (Dear ImGui already clip items based on their bounds but: it needs to first layout the item to do so, and generally +// fetching/submitting your own data incurs additional cost. Coarse clipping using ImGuiListClipper allows you to easily +// scale using lists with tens of thousands of items without a problem) +// Usage: +// ImGuiListClipper clipper; +// clipper.Begin(1000); // We have 1000 elements, evenly spaced. +// while (clipper.Step()) +// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) +// ImGui::Text("line number %d", i); +// Generally what happens is: +// - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not. +// - User code submit that one element. +// - Clipper can measure the height of the first element +// - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element. +// - User code submit visible elements. +// - The clipper also handles various subtleties related to keyboard/gamepad navigation, wrapping etc. +struct ImGuiListClipper +{ + int DisplayStart; // First item to display, updated by each call to Step() + int DisplayEnd; // End of items to display (exclusive) + int ItemsCount; // [Internal] Number of items + float ItemsHeight; // [Internal] Height of item after a first step and item submission can calculate it + float StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed + void* TempData; // [Internal] Internal data + + // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step) + // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). + IMGUI_API ImGuiListClipper(); + IMGUI_API ~ImGuiListClipper(); + IMGUI_API void Begin(int items_count, float items_height = -1.0f); + IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. + IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. + + // Call ForceDisplayRangeByIndices() before first call to Step() if you need a range of items to be displayed regardless of visibility. + IMGUI_API void ForceDisplayRangeByIndices(int item_min, int item_max); // item_max is exclusive e.g. use (42, 42+1) to make item 42 always visible BUT due to alignment/padding of certain items it is likely that an extra item may be included on either end of the display range. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79] +#endif +}; + +// Helpers macros to generate 32-bit encoded colors +// User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file. +#ifndef IM_COL32_R_SHIFT +#ifdef IMGUI_USE_BGRA_PACKED_COLOR +#define IM_COL32_R_SHIFT 16 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 0 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#else +#define IM_COL32_R_SHIFT 0 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 16 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#endif +#endif +#define IM_COL32(R,G,B,A) (((ImU32)(A)<> IM_COL32_R_SHIFT) & 0xFF) * sc; Value.y = (float)((rgba >> IM_COL32_G_SHIFT) & 0xFF) * sc; Value.z = (float)((rgba >> IM_COL32_B_SHIFT) & 0xFF) * sc; Value.w = (float)((rgba >> IM_COL32_A_SHIFT) & 0xFF) * sc; } + inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } + inline operator ImVec4() const { return Value; } + + // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. + inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } + static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r, g, b, a); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) +// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. +//----------------------------------------------------------------------------- + +// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. +#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (63) +#endif + +// ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] +// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, +// you can poke into the draw list for that! Draw callback may be useful for example to: +// A) Change your GPU render state, +// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. +// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' +// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering backend accordingly. +#ifndef ImDrawCallback +typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); +#endif + +// Special Draw callback value to request renderer backend to reset the graphics/render state. +// The renderer backend needs to handle this special value, otherwise it will crash trying to call a function at this address. +// This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored. +// It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Image call). +#define ImDrawCallback_ResetRenderState (ImDrawCallback)(-1) + +// Typically, 1 command = 1 GPU draw call (unless command is a callback) +// - VtxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, +// this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. +// Backends made for <1.71. will typically ignore the VtxOffset fields. +// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). +struct ImDrawCmd +{ + ImVec4 ClipRect; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates + ImTextureID TextureId; // 4-8 // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices. + unsigned int IdxOffset; // 4 // Start offset in index buffer. + unsigned int ElemCount; // 4 // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. + ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + void* UserCallbackData; // 4-8 // The draw callback code can access this. + + ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed + + // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) + inline ImTextureID GetTexID() const { return TextureId; } +}; + +// Vertex layout +#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT +struct ImDrawVert +{ + ImVec2 pos; + ImVec2 uv; + ImU32 col; +}; +#else +// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h +// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. +// The type has to be described within the macro (you can either declare the struct or use a typedef). This is because ImVec2/ImU32 are likely not declared a the time you'd want to set your type up. +// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. +IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; +#endif + +// [Internal] For use by ImDrawList +struct ImDrawCmdHeader +{ + ImVec4 ClipRect; + ImTextureID TextureId; + unsigned int VtxOffset; +}; + +// [Internal] For use by ImDrawListSplitter +struct ImDrawChannel +{ + ImVector _CmdBuffer; + ImVector _IdxBuffer; +}; + + +// Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order. +// This is used by the Columns/Tables API, so items of each column can be batched together in a same draw call. +struct ImDrawListSplitter +{ + int _Current; // Current channel number (0) + int _Count; // Number of active channels (1+) + ImVector _Channels; // Draw channels (not resized down so _Count might be < Channels.Size) + + inline ImDrawListSplitter() { memset(this, 0, sizeof(*this)); } + inline ~ImDrawListSplitter() { ClearFreeMemory(); } + inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame + IMGUI_API void ClearFreeMemory(); + IMGUI_API void Split(ImDrawList* draw_list, int count); + IMGUI_API void Merge(ImDrawList* draw_list); + IMGUI_API void SetCurrentChannel(ImDrawList* draw_list, int channel_idx); +}; + +// Flags for ImDrawList functions +// (Legacy: bit 0 must always correspond to ImDrawFlags_Closed to be backward compatible with old API using a bool. Bits 1..3 must be unused) +enum ImDrawFlags_ +{ + ImDrawFlags_None = 0, + ImDrawFlags_Closed = 1 << 0, // PathStroke(), AddPolyline(): specify that shape should be closed (Important: this is always == 1 for legacy reason) + ImDrawFlags_RoundCornersTopLeft = 1 << 4, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-left corner only (when rounding > 0.0f, we default to all corners). Was 0x01. + ImDrawFlags_RoundCornersTopRight = 1 << 5, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-right corner only (when rounding > 0.0f, we default to all corners). Was 0x02. + ImDrawFlags_RoundCornersBottomLeft = 1 << 6, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-left corner only (when rounding > 0.0f, we default to all corners). Was 0x04. + ImDrawFlags_RoundCornersBottomRight = 1 << 7, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-right corner only (when rounding > 0.0f, we default to all corners). Wax 0x08. + ImDrawFlags_RoundCornersNone = 1 << 8, // AddRect(), AddRectFilled(), PathRect(): disable rounding on all corners (when rounding > 0.0f). This is NOT zero, NOT an implicit flag! + ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, + ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersDefault_ = ImDrawFlags_RoundCornersAll, // Default to ALL corners if none of the _RoundCornersXX flags are specified. + ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone +}; + +// Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. +// It is however possible to temporarily alter flags between calls to ImDrawList:: functions. +enum ImDrawListFlags_ +{ + ImDrawListFlags_None = 0, + ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). + ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). + ImDrawListFlags_AllowVtxOffset = 1 << 3 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. +}; + +// Draw command list +// This is the low-level list of polygons that ImGui:: functions are filling. At the end of the frame, +// all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +// Each dear imgui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to +// access the current window draw list and draw custom primitives. +// You can interleave normal ImGui:: calls and adding primitives to the current draw list. +// In single viewport mode, top-left is == GetMainViewport()->Pos (generally 0,0), bottom-right is == GetMainViewport()->Pos+Size (generally io.DisplaySize). +// You are totally free to apply whatever transformation matrix to want to the data (depending on the use of the transformation you may want to apply it to ClipRect as well!) +// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects. +struct ImDrawList +{ + // This is what you have to render + ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. + ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those + ImVector VtxBuffer; // Vertex buffer. + ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. + + // [Internal, used while building lists] + unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. + const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) + const char* _OwnerName; // Pointer to owner window's name for debugging + ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImVector _ClipRectStack; // [Internal] + ImVector _TextureIdStack; // [Internal] + ImVector _Path; // [Internal] current path building + ImDrawCmdHeader _CmdHeader; // [Internal] template of active commands. Fields should match those of CmdBuffer.back(). + ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) + float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content + + // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) + ImDrawList(const ImDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); _Data = shared_data; } + + ~ImDrawList() { _ClearFreeMemory(); } + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) + IMGUI_API void PushClipRectFullScreen(); + IMGUI_API void PopClipRect(); + IMGUI_API void PushTextureID(ImTextureID texture_id); + IMGUI_API void PopTextureID(); + inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } + inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } + + // Primitives + // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. + // - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners. + // - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred). + // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12. + // In future versions we will use textures to provide cheaper and higher-quality circles. + // Use AddNgon() and AddNgonFilled() functions if you need to guaranteed a specific number of sides. + IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size) + IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) + IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); + IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); + IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); + IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f); + IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); + IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f); + IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments); + IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); + IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); + IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); + IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points) + IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0); // Quadratic Bezier (3 control points) + + // Image primitives + // - Read FAQ to understand what ImTextureID is. + // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle. + // - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture. + IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); + + // Stateful path API, add points then finish with PathFillConvex() or PathStroke() + // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. + inline void PathClear() { _Path.Size = 0; } + inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } + inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } + inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } + inline void PathStroke(ImU32 col, ImDrawFlags flags = 0, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, flags, thickness); _Path.Size = 0; } + IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0); + IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle + IMGUI_API void PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0); // Cubic Bezier (4 control points) + IMGUI_API void PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments = 0); // Quadratic Bezier (3 control points) + IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawFlags flags = 0); + + // Advanced + IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. + IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible + IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. + + // Advanced: Channels + // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives) + // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end) + // - FIXME-OBSOLETE: This API shouldn't have been in ImDrawList in the first place! + // Prefer using your own persistent instance of ImDrawListSplitter as you can stack them. + // Using the ImDrawList::ChannelsXXXX you cannot stack a split over another. + inline void ChannelsSplit(int count) { _Splitter.Split(this, count); } + inline void ChannelsMerge() { _Splitter.Merge(this); } + inline void ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); } + + // Advanced: Primitives allocations + // - We render triangles (three vertices) + // - All primitives needs to be reserved via PrimReserve() beforehand. + IMGUI_API void PrimReserve(int idx_count, int vtx_count); + IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); + IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) + IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); + IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); + inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } + inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); } // OBSOLETED in 1.80 (Jan 2021) + inline void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021) +#endif + + // [Internal helpers] + IMGUI_API void _ResetForNewFrame(); + IMGUI_API void _ClearFreeMemory(); + IMGUI_API void _PopUnusedDrawCmd(); + IMGUI_API void _TryMergeDrawCmds(); + IMGUI_API void _OnChangedClipRect(); + IMGUI_API void _OnChangedTextureID(); + IMGUI_API void _OnChangedVtxOffset(); + IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; + IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); + IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); +}; + +// All draw data to render a Dear ImGui frame +// (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, +// as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) +struct ImDrawData +{ + bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. + int CmdListsCount; // Number of ImDrawList* to render + int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size + int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size + ImDrawList** CmdLists; // Array of ImDrawList* to render. The ImDrawList are owned by ImGuiContext and only pointed to from here. + ImVec2 DisplayPos; // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications) + ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications) + ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display. + ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not). + + // Functions + ImDrawData() { Clear(); } + void Clear() { memset(this, 0, sizeof(*this)); } // The ImDrawList are owned by ImGuiContext! + IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! + IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +}; + +//----------------------------------------------------------------------------- +// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) +//----------------------------------------------------------------------------- + +struct ImFontConfig +{ + void* FontData; // // TTF/OTF data + int FontDataSize; // // TTF/OTF data size + bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). + int FontNo; // 0 // Index of font within TTF/OTF file + float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). + int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. Note the difference between 2 and 3 is minimal so you can reduce this to 2 to save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. + int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. This is not really useful as we don't use sub-pixel positions on the Y axis. + bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now. + ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. + const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. + float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font + float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs + bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. + unsigned int FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. + float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. + ImWchar EllipsisChar; // -1 // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. + + // [Internal] + char Name[40]; // Name (strictly to ease debugging) + ImFont* DstFont; + + IMGUI_API ImFontConfig(); +}; + +// Hold rendering data for one glyph. +// (Note: some language parsers may fail to convert the 31+1 bitfield members, in this case maybe drop store a single u32 or we can rework this) +struct ImFontGlyph +{ + unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) + unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering. + unsigned int Codepoint : 30; // 0x0000..0x10FFFF + float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in) + float X0, Y0, X1, Y1; // Glyph corners + float U0, V0, U1, V1; // Texture coordinates +}; + +// Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges(). +// This is essentially a tightly packed of vector of 64k booleans = 8KB storage. +struct ImFontGlyphRangesBuilder +{ + ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) + + ImFontGlyphRangesBuilder() { Clear(); } + inline void Clear() { int size_in_bytes = (IM_UNICODE_CODEPOINT_MAX + 1) / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); } + inline bool GetBit(size_t n) const { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array + inline void SetBit(size_t n) { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array + inline void AddChar(ImWchar c) { SetBit(c); } // Add character + IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) + IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext + IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges +}; + +// See ImFontAtlas::AddCustomRectXXX functions. +struct ImFontAtlasCustomRect +{ + unsigned short Width, Height; // Input // Desired rectangle dimension + unsigned short X, Y; // Output // Packed position in Atlas + unsigned int GlyphID; // Input // For custom font glyphs only (ID < 0x110000) + float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance + ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset + ImFont* Font; // Input // For custom font glyphs only: target font + ImFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } + bool IsPacked() const { return X != 0xFFFF; } +}; + +// Flags for ImFontAtlas build +enum ImFontAtlasFlags_ +{ + ImFontAtlasFlags_None = 0, + ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two + ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) + ImFontAtlasFlags_NoBakedLines = 1 << 2 // Don't build thick line textures into the atlas (save a little texture memory, allow support for point/nearest filtering). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). +}; + +// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: +// - One or more fonts. +// - Custom graphics data needed to render the shapes needed by Dear ImGui. +// - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). +// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api. +// - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you. +// - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. +// - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples) +// - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. +// This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. +// Common pitfalls: +// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the +// atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data. +// - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction. +// You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed, +// - Even though many functions are suffixed with "TTF", OTF data is supported just as well. +// - This is an old API and it is currently awkward for those and and various other reasons! We will address them in the future! +struct ImFontAtlas +{ + IMGUI_API ImFontAtlas(); + IMGUI_API ~ImFontAtlas(); + IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); + IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); + IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); + IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. + IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. + IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. + IMGUI_API void ClearInputData(); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. + IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. + IMGUI_API void ClearFonts(); // Clear output font data (glyphs storage, UV coordinates). + IMGUI_API void Clear(); // Clear all input and output. + + // Build atlas, retrieve pixel data. + // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). + // The pitch is always = Width * BytesPerPixels (1 or 4) + // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into + // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. + IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. + IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel + IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel + bool IsBuilt() const { return Fonts.Size > 0 && TexReady; } // Bit ambiguous: used to detect when user didn't built texture but effectively we should check TexID != 0 except that would be backend dependent... + void SetTexID(ImTextureID id) { TexID = id; } + + //------------------------------------------- + // Glyph Ranges + //------------------------------------------- + + // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) + // NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details. + // NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data. + IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin + IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters + IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese + IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters + IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters + IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters + + //------------------------------------------- + // [BETA] Custom Rectangles/Glyphs API + //------------------------------------------- + + // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. + // - After calling Build(), you can query the rectangle position and render your pixels. + // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of prefered texture format. + // - You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), + // so you can render e.g. custom colorful icons and use them as regular glyphs. + // - Read docs/FONTS.md for more details about using colorful icons. + // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. + IMGUI_API int AddCustomRectRegular(int width, int height); + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); + ImFontAtlasCustomRect* GetCustomRectByIndex(int index) { IM_ASSERT(index >= 0); return &CustomRects[index]; } + + // [Internal] + IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; + IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); + + //------------------------------------------- + // Members + //------------------------------------------- + + ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) + ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. + int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). + bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. + + // [Internal] + // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you. + bool TexReady; // Set when texture was built matching current font input + bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format. + unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight + unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + int TexWidth; // Texture width calculated during Build(). + int TexHeight; // Texture height calculated during Build(). + ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight) + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel + ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. + ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. + ImVector ConfigData; // Configuration data + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + + // [Internal] Font builder + const ImFontBuilderIO* FontBuilderIO; // Opaque interface to a font builder (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). + unsigned int FontBuilderFlags; // Shared flags (for all fonts) for custom font builder. THIS IS BUILD IMPLEMENTATION DEPENDENT. Per-font override is also available in ImFontConfig. + + // [Internal] Packing data + int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors + int PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines + + // [Obsolete] + //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ + //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ +}; + +// Font runtime data and rendering +// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). +struct ImFont +{ + // Members: Hot ~20/24 bytes (for CalcTextSize) + ImVector IndexAdvanceX; // 12-16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this this info, and are often bottleneck in large UI). + float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX + float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading) + + // Members: Hot ~28/40 bytes (for CalcTextSize + render loop) + ImVector IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point. + ImVector Glyphs; // 12-16 // out // // All glyphs. + const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) + + // Members: Cold ~32/40 bytes + ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into + const ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData + short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. + ImWchar FallbackChar; // 2 // out // = FFFD/'?' // Character used if a glyph isn't found. + ImWchar EllipsisChar; // 2 // out // = '...' // Character used for ellipsis rendering. + ImWchar DotChar; // 2 // out // = '.' // Character used for ellipsis rendering (if a single '...' character isn't found) + bool DirtyLookupTables; // 1 // out // + float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() + float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. + + // Methods + IMGUI_API ImFont(); + IMGUI_API ~ImFont(); + IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const; + IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const; + float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } + bool IsLoaded() const { return ContainerAtlas != NULL; } + const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; } + + // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. + // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. + IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 + IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; + IMGUI_API void RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, ImWchar c) const; + IMGUI_API void RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; + + // [Internal] Don't use! + IMGUI_API void BuildLookupTable(); + IMGUI_API void ClearOutputData(); + IMGUI_API void GrowIndex(int new_size); + IMGUI_API void AddGlyph(const ImFontConfig* src_cfg, ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); + IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. + IMGUI_API void SetGlyphVisible(ImWchar c, bool visible); + IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Viewports +//----------------------------------------------------------------------------- + +// Flags stored in ImGuiViewport::Flags, giving indications to the platform backends. +enum ImGuiViewportFlags_ +{ + ImGuiViewportFlags_None = 0, + ImGuiViewportFlags_IsPlatformWindow = 1 << 0, // Represent a Platform Window + ImGuiViewportFlags_IsPlatformMonitor = 1 << 1, // Represent a Platform Monitor (unused yet) + ImGuiViewportFlags_OwnedByApp = 1 << 2, // Platform Window: is created/managed by the application (rather than a dear imgui backend) + ImGuiViewportFlags_NoDecoration = 1 << 3, // Platform Window: Disable platform decorations: title bar, borders, etc. (generally set all windows, but if ImGuiConfigFlags_ViewportsDecoration is set we only set this on popups/tooltips) + ImGuiViewportFlags_NoTaskBarIcon = 1 << 4, // Platform Window: Disable platform task bar icon (generally set on popups/tooltips, or all windows if ImGuiConfigFlags_ViewportsNoTaskBarIcon is set) + ImGuiViewportFlags_NoFocusOnAppearing = 1 << 5, // Platform Window: Don't take focus when created. + ImGuiViewportFlags_NoFocusOnClick = 1 << 6, // Platform Window: Don't take focus when clicked on. + ImGuiViewportFlags_NoInputs = 1 << 7, // Platform Window: Make mouse pass through so we can drag this window while peaking behind it. + ImGuiViewportFlags_NoRendererClear = 1 << 8, // Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely). + ImGuiViewportFlags_TopMost = 1 << 9, // Platform Window: Display on top (for tooltips only). + ImGuiViewportFlags_Minimized = 1 << 10, // Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. + ImGuiViewportFlags_NoAutoMerge = 1 << 11, // Platform Window: Avoid merging this window into another host window. This can only be set via ImGuiWindowClass viewport flags override (because we need to now ahead if we are going to create a viewport in the first place!). + ImGuiViewportFlags_CanHostOtherWindows = 1 << 12 // Main viewport: can host multiple imgui windows (secondary viewports are associated to a single window). +}; + +// - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. +// - With multi-viewport enabled, we extend this concept to have multiple active viewports. +// - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. +// - About Main Area vs Work Area: +// - Main Area = entire viewport. +// - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor). +// - Windows are generally trying to stay within the Work Area of their host viewport. +struct ImGuiViewport +{ + ImGuiID ID; // Unique identifier for the viewport + ImGuiViewportFlags Flags; // See ImGuiViewportFlags_ + ImVec2 Pos; // Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) + ImVec2 Size; // Main Area: Size of the viewport. + ImVec2 WorkPos; // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) + ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) + float DpiScale; // 1.0f = 96 DPI = No extra scale. + ImGuiID ParentViewportId; // (Advanced) 0: no parent. Instruct the platform backend to setup a parent/child relationship between platform windows. + ImDrawData* DrawData; // The ImDrawData corresponding to this viewport. Valid after Render() and until the next call to NewFrame(). + + // Platform/Backend Dependent Data + // Our design separate the Renderer and Platform backends to facilitate combining default backends with each others. + // When our create your own backend for a custom engine, it is possible that both Renderer and Platform will be handled + // by the same system and you may not need to use all the UserData/Handle fields. + // The library never uses those fields, they are merely storage to facilitate backend implementation. + void* RendererUserData; // void* to hold custom data structure for the renderer (e.g. swap chain, framebuffers etc.). generally set by your Renderer_CreateWindow function. + void* PlatformUserData; // void* to hold custom data structure for the OS / platform (e.g. windowing info, render context). generally set by your Platform_CreateWindow function. + void* PlatformHandle; // void* for FindViewportByPlatformHandle(). (e.g. suggested to use natural platform handle such as HWND, GLFWWindow*, SDL_Window*) + void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms), when using an abstraction layer like GLFW or SDL (where PlatformHandle would be a SDL_Window*) + bool PlatformRequestMove; // Platform window requested move (e.g. window was moved by the OS / host window manager, authoritative position will be OS window position) + bool PlatformRequestResize; // Platform window requested resize (e.g. window was resized by the OS / host window manager, authoritative size will be OS window size) + bool PlatformRequestClose; // Platform window requested closure (e.g. window was moved by the OS / host window manager, e.g. pressing ALT-F4) + + ImGuiViewport() { memset(this, 0, sizeof(*this)); } + ~ImGuiViewport() { IM_ASSERT(PlatformUserData == NULL && RendererUserData == NULL); } + + // Helpers + ImVec2 GetCenter() const { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); } + ImVec2 GetWorkCenter() const { return ImVec2(WorkPos.x + WorkSize.x * 0.5f, WorkPos.y + WorkSize.y * 0.5f); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Platform Dependent Interfaces (for e.g. multi-viewport support) +//----------------------------------------------------------------------------- +// [BETA] (Optional) This is completely optional, for advanced users! +// If you are new to Dear ImGui and trying to integrate it into your engine, you can probably ignore this for now. +// +// This feature allows you to seamlessly drag Dear ImGui windows outside of your application viewport. +// This is achieved by creating new Platform/OS windows on the fly, and rendering into them. +// Dear ImGui manages the viewport structures, and the backend create and maintain one Platform/OS window for each of those viewports. +// +// See Glossary https://github.com/ocornut/imgui/wiki/Glossary for details about some of the terminology. +// See Thread https://github.com/ocornut/imgui/issues/1542 for gifs, news and questions about this evolving feature. +// +// About the coordinates system: +// - When multi-viewports are enabled, all Dear ImGui coordinates become absolute coordinates (same as OS coordinates!) +// - So e.g. ImGui::SetNextWindowPos(ImVec2(0,0)) will position a window relative to your primary monitor! +// - If you want to position windows relative to your main application viewport, use ImGui::GetMainViewport()->Pos as a base position. +// +// Steps to use multi-viewports in your application, when using a default backend from the examples/ folder: +// - Application: Enable feature with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// - Backend: The backend initialization will setup all necessary ImGuiPlatformIO's functions and update monitors info every frame. +// - Application: In your main loop, call ImGui::UpdatePlatformWindows(), ImGui::RenderPlatformWindowsDefault() after EndFrame() or Render(). +// - Application: Fix absolute coordinates used in ImGui::SetWindowPos() or ImGui::SetNextWindowPos() calls. +// +// Steps to use multi-viewports in your application, when using a custom backend: +// - Important: THIS IS NOT EASY TO DO and comes with many subtleties not described here! +// It's also an experimental feature, so some of the requirements may evolve. +// Consider using default backends if you can. Either way, carefully follow and refer to examples/ backends for details. +// - Application: Enable feature with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// - Backend: Hook ImGuiPlatformIO's Platform_* and Renderer_* callbacks (see below). +// Set 'io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports' and 'io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports'. +// Update ImGuiPlatformIO's Monitors list every frame. +// Update MousePos every frame, in absolute coordinates. +// - Application: In your main loop, call ImGui::UpdatePlatformWindows(), ImGui::RenderPlatformWindowsDefault() after EndFrame() or Render(). +// You may skip calling RenderPlatformWindowsDefault() if its API is not convenient for your needs. Read comments below. +// - Application: Fix absolute coordinates used in ImGui::SetWindowPos() or ImGui::SetNextWindowPos() calls. +// +// About ImGui::RenderPlatformWindowsDefault(): +// - This function is a mostly a _helper_ for the common-most cases, and to facilitate using default backends. +// - You can check its simple source code to understand what it does. +// It basically iterates secondary viewports and call 4 functions that are setup in ImGuiPlatformIO, if available: +// Platform_RenderWindow(), Renderer_RenderWindow(), Platform_SwapBuffers(), Renderer_SwapBuffers() +// Those functions pointers exists only for the benefit of RenderPlatformWindowsDefault(). +// - If you have very specific rendering needs (e.g. flipping multiple swap-chain simultaneously, unusual sync/threading issues, etc.), +// you may be tempted to ignore RenderPlatformWindowsDefault() and write customized code to perform your renderingg. +// You may decide to setup the platform_io's *RenderWindow and *SwapBuffers pointers and call your functions through those pointers, +// or you may decide to never setup those pointers and call your code directly. They are a convenience, not an obligatory interface. +//----------------------------------------------------------------------------- + +// (Optional) Access via ImGui::GetPlatformIO() +struct ImGuiPlatformIO +{ + //------------------------------------------------------------------ + // Input - Backend interface/functions + Monitor List + //------------------------------------------------------------------ + + // (Optional) Platform functions (e.g. Win32, GLFW, SDL2) + // For reference, the second column shows which function are generally calling the Platform Functions: + // N = ImGui::NewFrame() ~ beginning of the dear imgui frame: read info from platform/OS windows (latest size/position) + // F = ImGui::Begin(), ImGui::EndFrame() ~ during the dear imgui frame + // U = ImGui::UpdatePlatformWindows() ~ after the dear imgui frame: create and update all platform/OS windows + // R = ImGui::RenderPlatformWindowsDefault() ~ render + // D = ImGui::DestroyPlatformWindows() ~ shutdown + // The general idea is that NewFrame() we will read the current Platform/OS state, and UpdatePlatformWindows() will write to it. + // + // The functions are designed so we can mix and match 2 imgui_impl_xxxx files, one for the Platform (~window/input handling), one for Renderer. + // Custom engine backends will often provide both Platform and Renderer interfaces and so may not need to use all functions. + // Platform functions are typically called before their Renderer counterpart, apart from Destroy which are called the other way. + + // Platform function --------------------------------------------------- Called by ----- + void (*Platform_CreateWindow)(ImGuiViewport* vp); // . . U . . // Create a new platform window for the given viewport + void (*Platform_DestroyWindow)(ImGuiViewport* vp); // N . U . D // + void (*Platform_ShowWindow)(ImGuiViewport* vp); // . . U . . // Newly created windows are initially hidden so SetWindowPos/Size/Title can be called on them before showing the window + void (*Platform_SetWindowPos)(ImGuiViewport* vp, ImVec2 pos); // . . U . . // Set platform window position (given the upper-left corner of client area) + ImVec2 (*Platform_GetWindowPos)(ImGuiViewport* vp); // N . . . . // + void (*Platform_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // . . U . . // Set platform window client area size (ignoring OS decorations such as OS title bar etc.) + ImVec2 (*Platform_GetWindowSize)(ImGuiViewport* vp); // N . . . . // Get platform window client area size + void (*Platform_SetWindowFocus)(ImGuiViewport* vp); // N . . . . // Move window to front and set input focus + bool (*Platform_GetWindowFocus)(ImGuiViewport* vp); // . . U . . // + bool (*Platform_GetWindowMinimized)(ImGuiViewport* vp); // N . . . . // Get platform window minimized state. When minimized, we generally won't attempt to get/set size and contents will be culled more easily + void (*Platform_SetWindowTitle)(ImGuiViewport* vp, const char* str); // . . U . . // Set platform window title (given an UTF-8 string) + void (*Platform_SetWindowAlpha)(ImGuiViewport* vp, float alpha); // . . U . . // (Optional) Setup global transparency (not per-pixel transparency) + void (*Platform_UpdateWindow)(ImGuiViewport* vp); // . . U . . // (Optional) Called by UpdatePlatformWindows(). Optional hook to allow the platform backend from doing general book-keeping every frame. + void (*Platform_RenderWindow)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Main rendering (platform side! This is often unused, or just setting a "current" context for OpenGL bindings). 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + void (*Platform_SwapBuffers)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Call Present/SwapBuffers (platform side! This is often unused!). 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + float (*Platform_GetWindowDpiScale)(ImGuiViewport* vp); // N . . . . // (Optional) [BETA] FIXME-DPI: DPI handling: Return DPI scale for this viewport. 1.0f = 96 DPI. + void (*Platform_OnChangedViewport)(ImGuiViewport* vp); // . F . . . // (Optional) [BETA] FIXME-DPI: DPI handling: Called during Begin() every time the viewport we are outputting into changes, so backend has a chance to swap fonts to adjust style. + int (*Platform_CreateVkSurface)(ImGuiViewport* vp, ImU64 vk_inst, const void* vk_allocators, ImU64* out_vk_surface); // (Optional) For a Vulkan Renderer to call into Platform code (since the surface creation needs to tie them both). + + // (Optional) Renderer functions (e.g. DirectX, OpenGL, Vulkan) + void (*Renderer_CreateWindow)(ImGuiViewport* vp); // . . U . . // Create swap chain, frame buffers etc. (called after Platform_CreateWindow) + void (*Renderer_DestroyWindow)(ImGuiViewport* vp); // N . U . D // Destroy swap chain, frame buffers etc. (called before Platform_DestroyWindow) + void (*Renderer_SetWindowSize)(ImGuiViewport* vp, ImVec2 size); // . . U . . // Resize swap chain, frame buffers etc. (called after Platform_SetWindowSize) + void (*Renderer_RenderWindow)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Clear framebuffer, setup render target, then render the viewport->DrawData. 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + void (*Renderer_SwapBuffers)(ImGuiViewport* vp, void* render_arg); // . . . R . // (Optional) Call Present/SwapBuffers. 'render_arg' is the value passed to RenderPlatformWindowsDefault(). + + // (Optional) Monitor list + // - Updated by: app/backend. Update every frame to dynamically support changing monitor or DPI configuration. + // - Used by: dear imgui to query DPI info, clamp popups/tooltips within same monitor and not have them straddle monitors. + ImVector Monitors; + + //------------------------------------------------------------------ + // Output - List of viewports to render into platform windows + //------------------------------------------------------------------ + + // Viewports list (the list is updated by calling ImGui::EndFrame or ImGui::Render) + // (in the future we will attempt to organize this feature to remove the need for a "main viewport") + ImVector Viewports; // Main viewports, followed by all secondary viewports. + ImGuiPlatformIO() { memset(this, 0, sizeof(*this)); } // Zero clear +}; + +// (Optional) This is required when enabling multi-viewport. Represent the bounds of each connected monitor/display and their DPI. +// We use this information for multiple DPI support + clamping the position of popups and tooltips so they don't straddle multiple monitors. +struct ImGuiPlatformMonitor +{ + ImVec2 MainPos, MainSize; // Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right) + ImVec2 WorkPos, WorkSize; // Coordinates without task bars / side bars / menu bars. Used to avoid positioning popups/tooltips inside this region. If you don't have this info, please copy the value for MainPos/MainSize. + float DpiScale; // 1.0f = 96 DPI + ImGuiPlatformMonitor() { MainPos = MainSize = WorkPos = WorkSize = ImVec2(0, 0); DpiScale = 1.0f; } +}; + +// (Optional) Support for IME (Input Method Editor) via the io.SetPlatformImeDataFn() function. +struct ImGuiPlatformImeData +{ + bool WantVisible; // A widget wants the IME to be visible + ImVec2 InputPos; // Position of the input cursor + float InputLineHeight; // Line height + + ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Obsolete functions and types +// (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) +// Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead. +//----------------------------------------------------------------------------- + +namespace ImGui +{ +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + IMGUI_API int GetKeyIndex(ImGuiKey key); // map ImGuiKey_* values into legacy native key index. == io.KeyMap[key] +#else + static inline int GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END && "ImGuiKey and native_index was merged together and native_index is disabled by IMGUI_DISABLE_OBSOLETE_KEYIO. Please switch to ImGuiKey."); return key; } +#endif +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +namespace ImGui +{ + // OBSOLETED in 1.88 (from May 2022) + static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value. + static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value. + // OBSOLETED in 1.86 (from November 2021) + IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Calculate coarse clipping for large list of evenly sized items. Prefer using ImGuiListClipper. + // OBSOLETED in 1.85 (from August 2021) + static inline float GetWindowContentRegionWidth() { return GetWindowContentRegionMax().x - GetWindowContentRegionMin().x; } + // OBSOLETED in 1.81 (from February 2021) + IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // Helper to calculate size from items_count and height_in_items + static inline bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)) { return BeginListBox(label, size); } + static inline void ListBoxFooter() { EndListBox(); } + // OBSOLETED in 1.79 (from August 2020) + static inline void OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry! + // OBSOLETED in 1.78 (from June 2020) + // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags. + // For shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`. + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power); + static inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } + static inline bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } + static inline bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } + static inline bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power); + static inline bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } + static inline bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } + static inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } + static inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } + // OBSOLETED in 1.77 (from June 2020) + static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } + + // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + //static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.72 (from July 2019) + //static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } // OBSOLETED in 1.71 (from June 2019) + //static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // OBSOLETED in 1.70 (from May 2019) + //static inline ImDrawList* GetOverlayDrawList() { return GetForegroundDrawList(); } // OBSOLETED in 1.69 (from Mar 2019) + //static inline void SetScrollHere(float ratio = 0.5f) { SetScrollHereY(ratio); } // OBSOLETED in 1.66 (from Nov 2018) + //static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); } // OBSOLETED in 1.63 (from Aug 2018) + //static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } // OBSOLETED in 1.60 (from Apr 2018) + //static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018) + //static inline void ShowTestWindow() { return ShowDemoWindow(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) + //static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) +} + +// OBSOLETED in 1.82 (from Mars 2021): flags for AddRect(), AddRectFilled(), AddImageRounded(), PathRect() +typedef ImDrawFlags ImDrawCornerFlags; +enum ImDrawCornerFlags_ +{ + ImDrawCornerFlags_None = ImDrawFlags_RoundCornersNone, // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundCornersNone which is != 0 and not implicit + ImDrawCornerFlags_TopLeft = ImDrawFlags_RoundCornersTopLeft, // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally). + ImDrawCornerFlags_TopRight = ImDrawFlags_RoundCornersTopRight, // Was == 0x02 (1 << 1) prior to 1.82. + ImDrawCornerFlags_BotLeft = ImDrawFlags_RoundCornersBottomLeft, // Was == 0x04 (1 << 2) prior to 1.82. + ImDrawCornerFlags_BotRight = ImDrawFlags_RoundCornersBottomRight, // Was == 0x08 (1 << 3) prior to 1.82. + ImDrawCornerFlags_All = ImDrawFlags_RoundCornersAll, // Was == 0x0F prior to 1.82 + ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, + ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, + ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, + ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight +}; + +// RENAMED ImGuiKeyModFlags -> ImGuiModFlags in 1.88 (from April 2022) +typedef int ImGuiKeyModFlags; +enum ImGuiKeyModFlags_ { ImGuiKeyModFlags_None = ImGuiModFlags_None, ImGuiKeyModFlags_Ctrl = ImGuiModFlags_Ctrl, ImGuiKeyModFlags_Shift = ImGuiModFlags_Shift, ImGuiKeyModFlags_Alt = ImGuiModFlags_Alt, ImGuiKeyModFlags_Super = ImGuiModFlags_Super }; + +#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +// Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h) +#ifdef IMGUI_INCLUDE_IMGUI_USER_H +#include "imgui_user.h" +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/src/editors/xrEUI/imgui.natvis b/src/editors/xrEUI/imgui.natvis new file mode 100644 index 00000000000..cc768bfb55f --- /dev/null +++ b/src/editors/xrEUI/imgui.natvis @@ -0,0 +1,39 @@ + + + + + + + + {{Size={Size} Capacity={Capacity}}} + + + Size + Data + + + + + + {{x={x,g} y={y,g}}} + + + + {{x={x,g} y={y,g} z={z,g} w={w,g}}} + + + + {{Min=({Min.x,g} {Min.y,g}) Max=({Max.x,g} {Max.y,g}) Size=({Max.x-Min.x,g} {Max.y-Min.y,g})}} + + Min + Max + Max.x - Min.x + Max.y - Min.y + + + + + {{Name {Name,s} Active {(Active||WasActive)?1:0,d} Child {(Flags & 0x01000000)?1:0,d} Popup {(Flags & 0x04000000)?1:0,d} Hidden {(Hidden)?1:0,d}} + + + \ No newline at end of file diff --git a/src/editors/xrEUI/imgui_demo.cpp b/src/editors/xrEUI/imgui_demo.cpp new file mode 100644 index 00000000000..80ac9592b8d --- /dev/null +++ b/src/editors/xrEUI/imgui_demo.cpp @@ -0,0 +1,8253 @@ +// dear imgui, v1.88 WIP +// (demo code) + +// Help: +// - Read FAQ at http://dearimgui.org/faq +// - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. +// Read imgui.cpp for more details, documentation and comments. +// Get the latest version at https://github.com/ocornut/imgui + +// Message to the person tempted to delete this file when integrating Dear ImGui into their codebase: +// Do NOT remove this file from your project! Think again! It is the most useful reference code that you and other +// coders will want to refer to and call. Have the ImGui::ShowDemoWindow() function wired in an always-available +// debug menu of your game/app! Removing this file from your project is hindering access to documentation for everyone +// in your team, likely leading you to poorer usage of the library. +// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow(). +// If you want to link core Dear ImGui in your shipped builds but want a thorough guarantee that the demo will not be +// linked, you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty. +// In another situation, whenever you have Dear ImGui available you probably want this to be available for reference. +// Thank you, +// -Your beloved friend, imgui_demo.cpp (which you won't delete) + +// Message to beginner C/C++ programmers about the meaning of the 'static' keyword: +// In this demo code, we frequently use 'static' variables inside functions. A static variable persists across calls, +// so it is essentially like a global variable but declared inside the scope of the function. We do this as a way to +// gather code and data in the same place, to make the demo source code faster to read, faster to write, and smaller +// in size. It also happens to be a convenient way of storing simple UI related information as long as your function +// doesn't need to be reentrant or used in multiple threads. This might be a pattern you will want to use in your code, +// but most of the real data you would be editing is likely going to be stored outside your functions. + +// The Demo code in this file is designed to be easy to copy-and-paste into your application! +// Because of this: +// - We never omit the ImGui:: prefix when calling functions, even though most code here is in the same namespace. +// - We try to declare static variables in the local scope, as close as possible to the code using them. +// - We never use any of the helpers/facilities used internally by Dear ImGui, unless available in the public API. +// - We never use maths operators on ImVec2/ImVec4. For our other sources files we use them, and they are provided +// by imgui_internal.h using the IMGUI_DEFINE_MATH_OPERATORS define. For your own sources file they are optional +// and require you either enable those, either provide your own via IM_VEC2_CLASS_EXTRA in imconfig.h. +// Because we can't assume anything about your support of maths operators, we cannot use them in imgui_demo.cpp. + +// Navigating this file: +// - In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. +// - With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. + +/* + +Index of this file: + +// [SECTION] Forward Declarations, Helpers +// [SECTION] Demo Window / ShowDemoWindow() +// - sub section: ShowDemoWindowWidgets() +// - sub section: ShowDemoWindowLayout() +// - sub section: ShowDemoWindowPopups() +// - sub section: ShowDemoWindowTables() +// - sub section: ShowDemoWindowMisc() +// [SECTION] About Window / ShowAboutWindow() +// [SECTION] Style Editor / ShowStyleEditor() +// [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() +// [SECTION] Example App: Debug Console / ShowExampleAppConsole() +// [SECTION] Example App: Debug Log / ShowExampleAppLog() +// [SECTION] Example App: Simple Layout / ShowExampleAppLayout() +// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() +// [SECTION] Example App: Long Text / ShowExampleAppLongText() +// [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() +// [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize() +// [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() +// [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() +// [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles() +// [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() +// [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() +// [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() + +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE + +// System includes +#include // toupper +#include // INT_MIN, INT_MAX +#include // sqrtf, powf, cosf, sinf, floorf, ceilf +#include // vsnprintf, sscanf, printf +#include // NULL, malloc, free, atoi +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used in demo code (so user can copy & paste the code) +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type +#pragma clang diagnostic ignored "-Wformat-security" // warning: format string is not a string literal +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat-security" // warning: format string is not a string literal (potentially insecure) +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub. +#endif + +// Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!) +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" +#else +#define IM_NEWLINE "\n" +#endif + +// Helpers +#if defined(_MSC_VER) && !defined(snprintf) +#define snprintf _snprintf +#endif +#if defined(_MSC_VER) && !defined(vsnprintf) +#define vsnprintf _vsnprintf +#endif + +// Format specifiers, printing 64-bit hasn't been decently standardized... +// In a real application you should be using PRId64 and PRIu64 from (non-windows) and on Windows define them yourself. +#ifdef _MSC_VER +#define IM_PRId64 "I64d" +#define IM_PRIu64 "I64u" +#else +#define IM_PRId64 "lld" +#define IM_PRIu64 "llu" +#endif + +// Helpers macros +// We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste, +// but making an exception here as those are largely simplifying code... +// In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo. +#define IM_MIN(A, B) (((A) < (B)) ? (A) : (B)) +#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) +#define IM_CLAMP(V, MN, MX) ((V) < (MN) ? (MN) : (V) > (MX) ? (MX) : (V)) + +// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall +#ifndef IMGUI_CDECL +#ifdef _MSC_VER +#define IMGUI_CDECL __cdecl +#else +#define IMGUI_CDECL +#endif +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Forward Declarations, Helpers +//----------------------------------------------------------------------------- + +#if !defined(IMGUI_DISABLE_DEMO_WINDOWS) + +// Forward Declarations +static void ShowExampleAppDockSpace(bool* p_open); +static void ShowExampleAppDocuments(bool* p_open); +static void ShowExampleAppMainMenuBar(); +static void ShowExampleAppConsole(bool* p_open); +static void ShowExampleAppLog(bool* p_open); +static void ShowExampleAppLayout(bool* p_open); +static void ShowExampleAppPropertyEditor(bool* p_open); +static void ShowExampleAppLongText(bool* p_open); +static void ShowExampleAppAutoResize(bool* p_open); +static void ShowExampleAppConstrainedResize(bool* p_open); +static void ShowExampleAppSimpleOverlay(bool* p_open); +static void ShowExampleAppFullscreen(bool* p_open); +static void ShowExampleAppWindowTitles(bool* p_open); +static void ShowExampleAppCustomRendering(bool* p_open); +static void ShowExampleMenuFile(); + +// Helper to display a little (?) mark which shows a tooltip when hovered. +// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md) +static void HelpMarker(const char* desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +static void ShowDockingDisabledMessage() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui::Text("ERROR: Docking is not enabled! See Demo > Configuration."); + ImGui::Text("Set io.ConfigFlags |= ImGuiConfigFlags_DockingEnable in your code, or "); + ImGui::SameLine(0.0f, 0.0f); + if (ImGui::SmallButton("click here")) + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; +} + +// Helper to wire demo markers located in code to a interactive browser +typedef void (*ImGuiDemoMarkerCallback)(const char* file, int line, const char* section, void* user_data); +extern ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback; +extern void* GImGuiDemoMarkerCallbackUserData; +ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback = NULL; +void* GImGuiDemoMarkerCallbackUserData = NULL; +#define IMGUI_DEMO_MARKER(section) do { if (GImGuiDemoMarkerCallback != NULL) GImGuiDemoMarkerCallback(__FILE__, __LINE__, section, GImGuiDemoMarkerCallbackUserData); } while (0) + +// Helper to display basic user controls. +void ImGui::ShowUserGuide() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui::BulletText("Double-click on title bar to collapse window."); + ImGui::BulletText( + "Click and drag on lower corner to resize window\n" + "(double-click to auto fit window to its contents)."); + ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text."); + ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); + ImGui::BulletText("CTRL+Tab to select a window."); + if (io.FontAllowUserScaling) + ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); + ImGui::BulletText("While inputing text:\n"); + ImGui::Indent(); + ImGui::BulletText("CTRL+Left/Right to word jump."); + ImGui::BulletText("CTRL+A or double-click to select all."); + ImGui::BulletText("CTRL+X/C/V to use clipboard cut/copy/paste."); + ImGui::BulletText("CTRL+Z,CTRL+Y to undo/redo."); + ImGui::BulletText("ESCAPE to revert."); + ImGui::Unindent(); + ImGui::BulletText("With keyboard navigation enabled:"); + ImGui::Indent(); + ImGui::BulletText("Arrow keys to navigate."); + ImGui::BulletText("Space to activate a widget."); + ImGui::BulletText("Return to input text into a widget."); + ImGui::BulletText("Escape to deactivate a widget, close popup, exit child window."); + ImGui::BulletText("Alt to jump to the menu layer of a window."); + ImGui::Unindent(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Demo Window / ShowDemoWindow() +//----------------------------------------------------------------------------- +// - ShowDemoWindowWidgets() +// - ShowDemoWindowLayout() +// - ShowDemoWindowPopups() +// - ShowDemoWindowTables() +// - ShowDemoWindowColumns() +// - ShowDemoWindowMisc() +//----------------------------------------------------------------------------- + +// We split the contents of the big ShowDemoWindow() function into smaller functions +// (because the link time of very large functions grow non-linearly) +static void ShowDemoWindowWidgets(); +static void ShowDemoWindowLayout(); +static void ShowDemoWindowPopups(); +static void ShowDemoWindowTables(); +static void ShowDemoWindowColumns(); +static void ShowDemoWindowMisc(); + +// Demonstrate most Dear ImGui features (this is big function!) +// You may execute this function to experiment with the UI and understand what it does. +// You may then search for keywords in the code when you are interested by a specific feature. +void ImGui::ShowDemoWindow(bool* p_open) +{ + // Exceptionally add an extra assert here for people confused about initial Dear ImGui setup + // Most ImGui functions would normally just crash if the context is missing. + IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context. Refer to examples app!"); + + // Examples Apps (accessible from the "Examples" menu) + static bool show_app_main_menu_bar = false; + static bool show_app_dockspace = false; + static bool show_app_documents = false; + + static bool show_app_console = false; + static bool show_app_log = false; + static bool show_app_layout = false; + static bool show_app_property_editor = false; + static bool show_app_long_text = false; + static bool show_app_auto_resize = false; + static bool show_app_constrained_resize = false; + static bool show_app_simple_overlay = false; + static bool show_app_fullscreen = false; + static bool show_app_window_titles = false; + static bool show_app_custom_rendering = false; + + if (show_app_main_menu_bar) ShowExampleAppMainMenuBar(); + if (show_app_dockspace) ShowExampleAppDockSpace(&show_app_dockspace); // Process the Docking app first, as explicit DockSpace() nodes needs to be submitted early (read comments near the DockSpace function) + if (show_app_documents) ShowExampleAppDocuments(&show_app_documents); // Process the Document app next, as it may also use a DockSpace() + + if (show_app_console) ShowExampleAppConsole(&show_app_console); + if (show_app_log) ShowExampleAppLog(&show_app_log); + if (show_app_layout) ShowExampleAppLayout(&show_app_layout); + if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor); + if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text); + if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize); + if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize); + if (show_app_simple_overlay) ShowExampleAppSimpleOverlay(&show_app_simple_overlay); + if (show_app_fullscreen) ShowExampleAppFullscreen(&show_app_fullscreen); + if (show_app_window_titles) ShowExampleAppWindowTitles(&show_app_window_titles); + if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering); + + // Dear ImGui Apps (accessible from the "Tools" menu) + static bool show_app_metrics = false; + static bool show_app_stack_tool = false; + static bool show_app_style_editor = false; + static bool show_app_about = false; + + if (show_app_metrics) { ImGui::ShowMetricsWindow(&show_app_metrics); } + if (show_app_stack_tool) { ImGui::ShowStackToolWindow(&show_app_stack_tool); } + if (show_app_about) { ImGui::ShowAboutWindow(&show_app_about); } + if (show_app_style_editor) + { + ImGui::Begin("Dear ImGui Style Editor", &show_app_style_editor); + ImGui::ShowStyleEditor(); + ImGui::End(); + } + + // Demonstrate the various window flags. Typically you would just use the default! + static bool no_titlebar = false; + static bool no_scrollbar = false; + static bool no_menu = false; + static bool no_move = false; + static bool no_resize = false; + static bool no_collapse = false; + static bool no_close = false; + static bool no_nav = false; + static bool no_background = false; + static bool no_bring_to_front = false; + static bool no_docking = false; + static bool unsaved_document = false; + + ImGuiWindowFlags window_flags = 0; + if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar; + if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar; + if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar; + if (no_move) window_flags |= ImGuiWindowFlags_NoMove; + if (no_resize) window_flags |= ImGuiWindowFlags_NoResize; + if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse; + if (no_nav) window_flags |= ImGuiWindowFlags_NoNav; + if (no_background) window_flags |= ImGuiWindowFlags_NoBackground; + if (no_bring_to_front) window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus; + if (no_docking) window_flags |= ImGuiWindowFlags_NoDocking; + if (unsaved_document) window_flags |= ImGuiWindowFlags_UnsavedDocument; + if (no_close) p_open = NULL; // Don't pass our bool* to Begin + + // We specify a default position/size in case there's no data in the .ini file. + // We only do it to make the demo applications a little more welcoming, but typically this isn't required. + const ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(ImVec2(main_viewport->WorkPos.x + 650, main_viewport->WorkPos.y + 20), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver); + + // Main body of the Demo window starts here. + if (!ImGui::Begin("Dear ImGui Demo", p_open, window_flags)) + { + // Early out if the window is collapsed, as an optimization. + ImGui::End(); + return; + } + + // Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details. + + // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align) + //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f); + + // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets. + ImGui::PushItemWidth(ImGui::GetFontSize() * -12); + + // Menu Bar + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Menu")) + { + IMGUI_DEMO_MARKER("Menu/File"); + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Examples")) + { + IMGUI_DEMO_MARKER("Menu/Examples"); + ImGui::MenuItem("Main menu bar", NULL, &show_app_main_menu_bar); + ImGui::MenuItem("Console", NULL, &show_app_console); + ImGui::MenuItem("Log", NULL, &show_app_log); + ImGui::MenuItem("Simple layout", NULL, &show_app_layout); + ImGui::MenuItem("Property editor", NULL, &show_app_property_editor); + ImGui::MenuItem("Long text display", NULL, &show_app_long_text); + ImGui::MenuItem("Auto-resizing window", NULL, &show_app_auto_resize); + ImGui::MenuItem("Constrained-resizing window", NULL, &show_app_constrained_resize); + ImGui::MenuItem("Simple overlay", NULL, &show_app_simple_overlay); + ImGui::MenuItem("Fullscreen window", NULL, &show_app_fullscreen); + ImGui::MenuItem("Manipulating window titles", NULL, &show_app_window_titles); + ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering); + ImGui::MenuItem("Dockspace", NULL, &show_app_dockspace); + ImGui::MenuItem("Documents", NULL, &show_app_documents); + ImGui::EndMenu(); + } + //if (ImGui::MenuItem("MenuItem")) {} // You can also use MenuItem() inside a menu bar! + if (ImGui::BeginMenu("Tools")) + { + IMGUI_DEMO_MARKER("Menu/Tools"); +#ifndef IMGUI_DISABLE_METRICS_WINDOW + ImGui::MenuItem("Metrics/Debugger", NULL, &show_app_metrics); + ImGui::MenuItem("Stack Tool", NULL, &show_app_stack_tool); +#endif + ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor); + ImGui::MenuItem("About Dear ImGui", NULL, &show_app_about); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + ImGui::Text("dear imgui says hello! (%s) (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); + ImGui::Spacing(); + + IMGUI_DEMO_MARKER("Help"); + if (ImGui::CollapsingHeader("Help")) + { + ImGui::Text("ABOUT THIS DEMO:"); + ImGui::BulletText("Sections below are demonstrating many aspects of the library."); + ImGui::BulletText("The \"Examples\" menu above leads to more demo contents."); + ImGui::BulletText("The \"Tools\" menu above gives access to: About Box, Style Editor,\n" + "and Metrics/Debugger (general purpose Dear ImGui debugging tool)."); + ImGui::Separator(); + + ImGui::Text("PROGRAMMER GUIDE:"); + ImGui::BulletText("See the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!"); + ImGui::BulletText("See comments in imgui.cpp."); + ImGui::BulletText("See example applications in the examples/ folder."); + ImGui::BulletText("Read the FAQ at http://www.dearimgui.org/faq/"); + ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableKeyboard' for keyboard controls."); + ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableGamepad' for gamepad controls."); + ImGui::Separator(); + + ImGui::Text("USER GUIDE:"); + ImGui::ShowUserGuide(); + } + + IMGUI_DEMO_MARKER("Configuration"); + if (ImGui::CollapsingHeader("Configuration")) + { + ImGuiIO& io = ImGui::GetIO(); + + if (ImGui::TreeNode("Configuration##2")) + { + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + ImGui::SameLine(); HelpMarker("Enable keyboard controls."); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", &io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); + ImGui::SameLine(); HelpMarker("Enable gamepad controls. Require backend to set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", &io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos); + ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos."); + ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", &io.ConfigFlags, ImGuiConfigFlags_NoMouse); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) + { + // The "NoMouse" option can get us stuck with a disabled mouse! Let's provide an alternative way to fix it: + if (fmodf((float)ImGui::GetTime(), 0.40f) < 0.20f) + { + ImGui::SameLine(); + ImGui::Text("<>"); + } + if (ImGui::IsKeyPressed(ImGuiKey_Space)) + io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse; + } + ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", &io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); + ImGui::SameLine(); HelpMarker("Instruct backend to not alter mouse cursor shape and visibility."); + + ImGui::CheckboxFlags("io.ConfigFlags: DockingEnable", &io.ConfigFlags, ImGuiConfigFlags_DockingEnable); + ImGui::SameLine(); + if (io.ConfigDockingWithShift) + HelpMarker("Drag from window title bar or their tab to dock/undock. Hold SHIFT to enable docking.\n\nDrag from window menu button (upper-left button) to undock an entire node (all windows)."); + else + HelpMarker("Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking.\n\nDrag from window menu button (upper-left button) to undock an entire node (all windows)."); + if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) + { + ImGui::Indent(); + ImGui::Checkbox("io.ConfigDockingNoSplit", &io.ConfigDockingNoSplit); + ImGui::SameLine(); HelpMarker("Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars."); + ImGui::Checkbox("io.ConfigDockingWithShift", &io.ConfigDockingWithShift); + ImGui::SameLine(); HelpMarker("Enable docking when holding Shift only (allow to drop in wider space, reduce visual noise)"); + ImGui::Checkbox("io.ConfigDockingAlwaysTabBar", &io.ConfigDockingAlwaysTabBar); + ImGui::SameLine(); HelpMarker("Create a docking node and tab-bar on single floating windows."); + ImGui::Checkbox("io.ConfigDockingTransparentPayload", &io.ConfigDockingTransparentPayload); + ImGui::SameLine(); HelpMarker("Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge."); + ImGui::Unindent(); + } + + ImGui::CheckboxFlags("io.ConfigFlags: ViewportsEnable", &io.ConfigFlags, ImGuiConfigFlags_ViewportsEnable); + ImGui::SameLine(); HelpMarker("[beta] Enable beta multi-viewports support. See ImGuiPlatformIO for details."); + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + ImGui::Indent(); + ImGui::Checkbox("io.ConfigViewportsNoAutoMerge", &io.ConfigViewportsNoAutoMerge); + ImGui::SameLine(); HelpMarker("Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it."); + ImGui::Checkbox("io.ConfigViewportsNoTaskBarIcon", &io.ConfigViewportsNoTaskBarIcon); + ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform backends won't refresh the task bar icon state right away)."); + ImGui::Checkbox("io.ConfigViewportsNoDecoration", &io.ConfigViewportsNoDecoration); + ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform backends won't refresh the decoration right away)."); + ImGui::Checkbox("io.ConfigViewportsNoDefaultParent", &io.ConfigViewportsNoDefaultParent); + ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform backends won't refresh the parenting right away)."); + ImGui::Unindent(); + } + + ImGui::Checkbox("io.ConfigInputTrickleEventQueue", &io.ConfigInputTrickleEventQueue); + ImGui::SameLine(); HelpMarker("Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates."); + ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink); + ImGui::SameLine(); HelpMarker("Enable blinking cursor (optional as some users consider it to be distracting)."); + ImGui::Checkbox("io.ConfigDragClickToInputText", &io.ConfigDragClickToInputText); + ImGui::SameLine(); HelpMarker("Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving)."); + ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges); + ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback."); + ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly); + ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor); + ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something)."); + ImGui::Text("Also see Style->Rendering for rendering options."); + ImGui::TreePop(); + ImGui::Separator(); + } + + IMGUI_DEMO_MARKER("Configuration/Backend Flags"); + if (ImGui::TreeNode("Backend Flags")) + { + HelpMarker( + "Those flags are set by the backends (imgui_impl_xxx files) to specify their capabilities.\n" + "Here we expose them as read-only fields to avoid breaking interactions with your backend."); + + // Make a local copy to avoid modifying actual backend flags. + // FIXME: We don't use BeginDisabled() to keep label bright, maybe we need a BeginReadonly() equivalent.. + ImGuiBackendFlags backend_flags = io.BackendFlags; + ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", &backend_flags, ImGuiBackendFlags_HasGamepad); + ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &backend_flags, ImGuiBackendFlags_HasMouseCursors); + ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", &backend_flags, ImGuiBackendFlags_HasSetMousePos); + ImGui::CheckboxFlags("io.BackendFlags: PlatformHasViewports", &backend_flags, ImGuiBackendFlags_PlatformHasViewports); + ImGui::CheckboxFlags("io.BackendFlags: HasMouseHoveredViewport",&backend_flags, ImGuiBackendFlags_HasMouseHoveredViewport); + ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", &backend_flags, ImGuiBackendFlags_RendererHasVtxOffset); + ImGui::CheckboxFlags("io.BackendFlags: RendererHasViewports", &backend_flags, ImGuiBackendFlags_RendererHasViewports); + ImGui::TreePop(); + ImGui::Separator(); + } + + IMGUI_DEMO_MARKER("Configuration/Style"); + if (ImGui::TreeNode("Style")) + { + HelpMarker("The same contents can be accessed in 'Tools->Style Editor' or by calling the ShowStyleEditor() function."); + ImGui::ShowStyleEditor(); + ImGui::TreePop(); + ImGui::Separator(); + } + + IMGUI_DEMO_MARKER("Configuration/Capture, Logging"); + if (ImGui::TreeNode("Capture/Logging")) + { + HelpMarker( + "The logging API redirects all text output so you can easily capture the content of " + "a window or a block. Tree nodes can be automatically expanded.\n" + "Try opening any of the contents below in this window and then click one of the \"Log To\" button."); + ImGui::LogButtons(); + + HelpMarker("You can also call ImGui::LogText() to output directly to the log without a visual output."); + if (ImGui::Button("Copy \"Hello, world!\" to clipboard")) + { + ImGui::LogToClipboard(); + ImGui::LogText("Hello, world!"); + ImGui::LogFinish(); + } + ImGui::TreePop(); + } + } + + IMGUI_DEMO_MARKER("Window options"); + if (ImGui::CollapsingHeader("Window options")) + { + if (ImGui::BeginTable("split", 3)) + { + ImGui::TableNextColumn(); ImGui::Checkbox("No titlebar", &no_titlebar); + ImGui::TableNextColumn(); ImGui::Checkbox("No scrollbar", &no_scrollbar); + ImGui::TableNextColumn(); ImGui::Checkbox("No menu", &no_menu); + ImGui::TableNextColumn(); ImGui::Checkbox("No move", &no_move); + ImGui::TableNextColumn(); ImGui::Checkbox("No resize", &no_resize); + ImGui::TableNextColumn(); ImGui::Checkbox("No collapse", &no_collapse); + ImGui::TableNextColumn(); ImGui::Checkbox("No close", &no_close); + ImGui::TableNextColumn(); ImGui::Checkbox("No nav", &no_nav); + ImGui::TableNextColumn(); ImGui::Checkbox("No background", &no_background); + ImGui::TableNextColumn(); ImGui::Checkbox("No bring to front", &no_bring_to_front); + ImGui::TableNextColumn(); ImGui::Checkbox("No docking", &no_docking); + ImGui::TableNextColumn(); ImGui::Checkbox("Unsaved document", &unsaved_document); + ImGui::EndTable(); + } + } + + // All demo contents + ShowDemoWindowWidgets(); + ShowDemoWindowLayout(); + ShowDemoWindowPopups(); + ShowDemoWindowTables(); + ShowDemoWindowMisc(); + + // End of ShowDemoWindow() + ImGui::PopItemWidth(); + ImGui::End(); +} + +static void ShowDemoWindowWidgets() +{ + IMGUI_DEMO_MARKER("Widgets"); + if (!ImGui::CollapsingHeader("Widgets")) + return; + + static bool disable_all = false; // The Checkbox for that is inside the "Disabled" section at the bottom + if (disable_all) + ImGui::BeginDisabled(); + + IMGUI_DEMO_MARKER("Widgets/Basic"); + if (ImGui::TreeNode("Basic")) + { + IMGUI_DEMO_MARKER("Widgets/Basic/Button"); + static int clicked = 0; + if (ImGui::Button("Button")) + clicked++; + if (clicked & 1) + { + ImGui::SameLine(); + ImGui::Text("Thanks for clicking me!"); + } + + IMGUI_DEMO_MARKER("Widgets/Basic/Checkbox"); + static bool check = true; + ImGui::Checkbox("checkbox", &check); + + IMGUI_DEMO_MARKER("Widgets/Basic/RadioButton"); + static int e = 0; + ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); + ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); + ImGui::RadioButton("radio c", &e, 2); + + // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. + IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Colored)"); + for (int i = 0; i < 7; i++) + { + if (i > 0) + ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f)); + ImGui::Button("Click"); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + + // Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements + // (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!) + // See 'Demo->Layout->Text Baseline Alignment' for details. + ImGui::AlignTextToFramePadding(); + ImGui::Text("Hold to repeat:"); + ImGui::SameLine(); + + // Arrow buttons with Repeater + IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Repeating)"); + static int counter = 0; + float spacing = ImGui::GetStyle().ItemInnerSpacing.x; + ImGui::PushButtonRepeat(true); + if (ImGui::ArrowButton("##left", ImGuiDir_Left)) { counter--; } + ImGui::SameLine(0.0f, spacing); + if (ImGui::ArrowButton("##right", ImGuiDir_Right)) { counter++; } + ImGui::PopButtonRepeat(); + ImGui::SameLine(); + ImGui::Text("%d", counter); + + IMGUI_DEMO_MARKER("Widgets/Basic/Tooltips"); + ImGui::Text("Hover over me"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip"); + + ImGui::SameLine(); + ImGui::Text("- or me"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("I am a fancy tooltip"); + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); + ImGui::EndTooltip(); + } + + ImGui::Separator(); + ImGui::LabelText("label", "Value"); + + { + // Using the _simplified_ one-liner Combo() api here + // See "Combo" section for examples of how to use the more flexible BeginCombo()/EndCombo() api. + IMGUI_DEMO_MARKER("Widgets/Basic/Combo"); + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }; + static int item_current = 0; + ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items)); + ImGui::SameLine(); HelpMarker( + "Using the simplified one-liner Combo API here.\nRefer to the \"Combo\" section below for an explanation of how to use the more flexible and general BeginCombo/EndCombo API."); + } + + { + // To wire InputText() with std::string or any other custom string type, + // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. + IMGUI_DEMO_MARKER("Widgets/Basic/InputText"); + static char str0[128] = "Hello, world!"; + ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); + ImGui::SameLine(); HelpMarker( + "USER:\n" + "Hold SHIFT or use mouse to select text.\n" + "CTRL+Left/Right to word jump.\n" + "CTRL+A or double-click to select all.\n" + "CTRL+X,CTRL+C,CTRL+V clipboard.\n" + "CTRL+Z,CTRL+Y undo/redo.\n" + "ESCAPE to revert.\n\n" + "PROGRAMMER:\n" + "You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() " + "to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated " + "in imgui_demo.cpp)."); + + static char str1[128] = ""; + ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_ARRAYSIZE(str1)); + + IMGUI_DEMO_MARKER("Widgets/Basic/InputInt, InputFloat"); + static int i0 = 123; + ImGui::InputInt("input int", &i0); + + static float f0 = 0.001f; + ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f"); + + static double d0 = 999999.00000001; + ImGui::InputDouble("input double", &d0, 0.01f, 1.0f, "%.8f"); + + static float f1 = 1.e10f; + ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e"); + ImGui::SameLine(); HelpMarker( + "You can input value using the scientific notation,\n" + " e.g. \"1e+8\" becomes \"100000000\"."); + + static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + ImGui::InputFloat3("input float3", vec4a); + } + + { + IMGUI_DEMO_MARKER("Widgets/Basic/DragInt, DragFloat"); + static int i1 = 50, i2 = 42; + ImGui::DragInt("drag int", &i1, 1); + ImGui::SameLine(); HelpMarker( + "Click and drag to edit value.\n" + "Hold SHIFT/ALT for faster/slower edit.\n" + "Double-click or CTRL+click to input value."); + + ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp); + + static float f1 = 1.00f, f2 = 0.0067f; + ImGui::DragFloat("drag float", &f1, 0.005f); + ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); + } + + { + IMGUI_DEMO_MARKER("Widgets/Basic/SliderInt, SliderFloat"); + static int i1 = 0; + ImGui::SliderInt("slider int", &i1, -1, 3); + ImGui::SameLine(); HelpMarker("CTRL+click to input value."); + + static float f1 = 0.123f, f2 = 0.0f; + ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); + ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic); + + IMGUI_DEMO_MARKER("Widgets/Basic/SliderAngle"); + static float angle = 0.0f; + ImGui::SliderAngle("slider angle", &angle); + + // Using the format string to display a name instead of an integer. + // Here we completely omit '%d' from the format string, so it'll only display a name. + // This technique can also be used with DragInt(). + IMGUI_DEMO_MARKER("Widgets/Basic/Slider (enum)"); + enum Element { Element_Fire, Element_Earth, Element_Air, Element_Water, Element_COUNT }; + static int elem = Element_Fire; + const char* elems_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" }; + const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : "Unknown"; + ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name); + ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer."); + } + + { + IMGUI_DEMO_MARKER("Widgets/Basic/ColorEdit3, ColorEdit4"); + static float col1[3] = { 1.0f, 0.0f, 0.2f }; + static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::SameLine(); HelpMarker( + "Click on the color square to open a color picker.\n" + "Click and hold to use drag and drop.\n" + "Right-click on the color square to show options.\n" + "CTRL+click on individual component to input value.\n"); + + ImGui::ColorEdit4("color 2", col2); + } + + { + // Using the _simplified_ one-liner ListBox() api here + // See "List boxes" section for examples of how to use the more flexible BeginListBox()/EndListBox() api. + IMGUI_DEMO_MARKER("Widgets/Basic/ListBox"); + const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + static int item_current = 1; + ImGui::ListBox("listbox", &item_current, items, IM_ARRAYSIZE(items), 4); + ImGui::SameLine(); HelpMarker( + "Using the simplified one-liner ListBox API here.\nRefer to the \"List boxes\" section below for an explanation of how to use the more flexible and general BeginListBox/EndListBox API."); + } + + ImGui::TreePop(); + } + + // Testing ImGuiOnceUponAFrame helper. + //static ImGuiOnceUponAFrame once; + //for (int i = 0; i < 5; i++) + // if (once) + // ImGui::Text("This will be displayed only once."); + + IMGUI_DEMO_MARKER("Widgets/Trees"); + if (ImGui::TreeNode("Trees")) + { + IMGUI_DEMO_MARKER("Widgets/Trees/Basic trees"); + if (ImGui::TreeNode("Basic trees")) + { + for (int i = 0; i < 5; i++) + { + // Use SetNextItemOpen() so set the default state of a node to be open. We could + // also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing! + if (i == 0) + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + + if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i)) + { + ImGui::Text("blah blah"); + ImGui::SameLine(); + if (ImGui::SmallButton("button")) {} + ImGui::TreePop(); + } + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Trees/Advanced, with Selectable nodes"); + if (ImGui::TreeNode("Advanced, with Selectable nodes")) + { + HelpMarker( + "This is a more typical looking tree with selectable nodes.\n" + "Click to select, CTRL+Click to toggle, click on arrows or double-click to open."); + static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth; + static bool align_label_with_current_x_position = false; + static bool test_drag_and_drop = false; + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", &base_flags, ImGuiTreeNodeFlags_OpenOnArrow); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", &base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", &base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &base_flags, ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position); + ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop); + ImGui::Text("Hello!"); + if (align_label_with_current_x_position) + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + + // 'selection_mask' is dumb representation of what may be user-side selection state. + // You may retain selection state inside or outside your objects in whatever format you see fit. + // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end + /// of the loop. May be a pointer to your own node type, etc. + static int selection_mask = (1 << 2); + int node_clicked = -1; + for (int i = 0; i < 6; i++) + { + // Disable the default "open on single-click behavior" + set Selected flag according to our selection. + // To alter selection we use IsItemClicked() && !IsItemToggledOpen(), so clicking on an arrow doesn't alter selection. + ImGuiTreeNodeFlags node_flags = base_flags; + const bool is_selected = (selection_mask & (1 << i)) != 0; + if (is_selected) + node_flags |= ImGuiTreeNodeFlags_Selected; + if (i < 3) + { + // Items 0..2 are Tree Node + bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i); + if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) + node_clicked = i; + if (test_drag_and_drop && ImGui::BeginDragDropSource()) + { + ImGui::SetDragDropPayload("_TREENODE", NULL, 0); + ImGui::Text("This is a drag and drop source"); + ImGui::EndDragDropSource(); + } + if (node_open) + { + ImGui::BulletText("Blah blah\nBlah Blah"); + ImGui::TreePop(); + } + } + else + { + // Items 3..5 are Tree Leaves + // The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can + // use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). + node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet + ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i); + if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) + node_clicked = i; + if (test_drag_and_drop && ImGui::BeginDragDropSource()) + { + ImGui::SetDragDropPayload("_TREENODE", NULL, 0); + ImGui::Text("This is a drag and drop source"); + ImGui::EndDragDropSource(); + } + } + } + if (node_clicked != -1) + { + // Update selection state + // (process outside of tree loop to avoid visual inconsistencies during the clicking frame) + if (ImGui::GetIO().KeyCtrl) + selection_mask ^= (1 << node_clicked); // CTRL+click to toggle + else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection + selection_mask = (1 << node_clicked); // Click to single-select + } + if (align_label_with_current_x_position) + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Collapsing Headers"); + if (ImGui::TreeNode("Collapsing Headers")) + { + static bool closable_group = true; + ImGui::Checkbox("Show 2nd header", &closable_group); + if (ImGui::CollapsingHeader("Header", ImGuiTreeNodeFlags_None)) + { + ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); + for (int i = 0; i < 5; i++) + ImGui::Text("Some content %d", i); + } + if (ImGui::CollapsingHeader("Header with a close button", &closable_group)) + { + ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); + for (int i = 0; i < 5; i++) + ImGui::Text("More content %d", i); + } + /* + if (ImGui::CollapsingHeader("Header with a bullet", ImGuiTreeNodeFlags_Bullet)) + ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); + */ + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Bullets"); + if (ImGui::TreeNode("Bullets")) + { + ImGui::BulletText("Bullet point 1"); + ImGui::BulletText("Bullet point 2\nOn multiple lines"); + if (ImGui::TreeNode("Tree node")) + { + ImGui::BulletText("Another bullet point"); + ImGui::TreePop(); + } + ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); + ImGui::Bullet(); ImGui::SmallButton("Button"); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text"); + if (ImGui::TreeNode("Text")) + { + IMGUI_DEMO_MARKER("Widgets/Text/Colored Text"); + if (ImGui::TreeNode("Colorful Text")) + { + // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. + ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink"); + ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Yellow"); + ImGui::TextDisabled("Disabled"); + ImGui::SameLine(); HelpMarker("The TextDisabled color is stored in ImGuiStyle."); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text/Word Wrapping"); + if (ImGui::TreeNode("Word Wrapping")) + { + // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. + ImGui::TextWrapped( + "This text should automatically wrap on the edge of the window. The current implementation " + "for text wrapping follows simple rules suitable for English and possibly other languages."); + ImGui::Spacing(); + + static float wrap_width = 200.0f; + ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); + + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + for (int n = 0; n < 2; n++) + { + ImGui::Text("Test paragraph %d:", n); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec2 marker_min = ImVec2(pos.x + wrap_width, pos.y); + ImVec2 marker_max = ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + if (n == 0) + ImGui::Text("The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); + else + ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); + + // Draw actual text bounding box, following by marker of our expected limit (should not overlap!) + draw_list->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255)); + draw_list->AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255)); + ImGui::PopTextWrapPos(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text/UTF-8 Text"); + if (ImGui::TreeNode("UTF-8 Text")) + { + // UTF-8 test with Japanese characters + // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.) + // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8 + // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you + // can save your source files as 'UTF-8 without signature'). + // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8 + // CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal constants. + // Don't do this in your application! Please use u8"text in any language" in your application! + // Note that characters values are preserved even by InputText() if the font cannot be displayed, + // so you can safely copy & paste garbled characters into another application. + ImGui::TextWrapped( + "CJK text will only appears if the font was loaded with the appropriate CJK character ranges. " + "Call io.Fonts->AddFontFromFileTTF() manually to load extra character ranges. " + "Read docs/FONTS.md for details."); + ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); // Normally we would use u8"blah blah" with the proper characters directly in the string. + ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); + static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; + //static char buf[32] = u8"NIHONGO"; // <- this is how you would write it with C++11, using real kanjis + ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Images"); + if (ImGui::TreeNode("Images")) + { + ImGuiIO& io = ImGui::GetIO(); + ImGui::TextWrapped( + "Below we are displaying the font texture (which is the only texture we have access to in this demo). " + "Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. " + "Hover the texture for a zoomed view!"); + + // Below we are displaying the font texture because it is the only texture we have access to inside the demo! + // Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that + // will be passed to the rendering backend via the ImDrawCmd structure. + // If you use one of the default imgui_impl_XXXX.cpp rendering backend, they all have comments at the top + // of their respective source file to specify what they expect to be stored in ImTextureID, for example: + // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer + // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc. + // More: + // - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers + // to ImGui::Image(), and gather width/height through your own functions, etc. + // - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer, + // it will help you debug issues if you are confused about it. + // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). + // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md + // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + ImTextureID my_tex_id = io.Fonts->TexID; + float my_tex_w = (float)io.Fonts->TexWidth; + float my_tex_h = (float)io.Fonts->TexHeight; + { + ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left + ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint + ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); // 50% opaque white + ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, tint_col, border_col); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + float region_sz = 32.0f; + float region_x = io.MousePos.x - pos.x - region_sz * 0.5f; + float region_y = io.MousePos.y - pos.y - region_sz * 0.5f; + float zoom = 4.0f; + if (region_x < 0.0f) { region_x = 0.0f; } + else if (region_x > my_tex_w - region_sz) { region_x = my_tex_w - region_sz; } + if (region_y < 0.0f) { region_y = 0.0f; } + else if (region_y > my_tex_h - region_sz) { region_y = my_tex_h - region_sz; } + ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y); + ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz); + ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h); + ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h); + ImGui::Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, tint_col, border_col); + ImGui::EndTooltip(); + } + } + + IMGUI_DEMO_MARKER("Widgets/Images/Textured buttons"); + ImGui::TextWrapped("And now some textured buttons.."); + static int pressed_count = 0; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); + int frame_padding = -1 + i; // -1 == uses default padding (style.FramePadding) + ImVec2 size = ImVec2(32.0f, 32.0f); // Size of the image we want to make visible + ImVec2 uv0 = ImVec2(0.0f, 0.0f); // UV coordinates for lower-left + ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32.0f / my_tex_h);// UV coordinates for (32,32) in our texture + ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black background + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint + if (ImGui::ImageButton(my_tex_id, size, uv0, uv1, frame_padding, bg_col, tint_col)) + pressed_count += 1; + ImGui::PopID(); + ImGui::SameLine(); + } + ImGui::NewLine(); + ImGui::Text("Pressed %d times.", pressed_count); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Combo"); + if (ImGui::TreeNode("Combo")) + { + // Expose flags as checkbox for the demo + static ImGuiComboFlags flags = 0; + ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", &flags, ImGuiComboFlags_PopupAlignLeft); + ImGui::SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo"); + if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", &flags, ImGuiComboFlags_NoArrowButton)) + flags &= ~ImGuiComboFlags_NoPreview; // Clear the other flag, as we cannot combine both + if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", &flags, ImGuiComboFlags_NoPreview)) + flags &= ~ImGuiComboFlags_NoArrowButton; // Clear the other flag, as we cannot combine both + + // Using the generic BeginCombo() API, you have full control over how to display the combo contents. + // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + // stored in the object itself, etc.) + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; + static int item_current_idx = 0; // Here we store our selection data as an index. + const char* combo_preview_value = items[item_current_idx]; // Pass in the preview value visible before opening the combo (it could be anything) + if (ImGui::BeginCombo("combo 1", combo_preview_value, flags)) + { + static bool test_check = false; + ImGui::Checkbox("test", &test_check); + for (int n = 0; n < IM_ARRAYSIZE(items); n++) + { + const bool is_selected = (item_current_idx == n); + if (ImGui::Selectable(items[n], is_selected)) + item_current_idx = n; + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) + if (is_selected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + + // Simplified one-liner Combo() API, using values packed in a single constant string + // This is a convenience for when the selection set is small and known at compile-time. + static int item_current_2 = 0; + ImGui::Combo("combo 2 (one-liner)", &item_current_2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); + + // Simplified one-liner Combo() using an array of const char* + // This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control. + static int item_current_3 = -1; // If the selection isn't within 0..count, Combo won't display a preview + ImGui::Combo("combo 3 (array)", &item_current_3, items, IM_ARRAYSIZE(items)); + + // Simplified one-liner Combo() using an accessor function + struct Funcs { static bool ItemGetter(void* data, int n, const char** out_str) { *out_str = ((const char**)data)[n]; return true; } }; + static int item_current_4 = 0; + ImGui::Combo("combo 4 (function)", &item_current_4, &Funcs::ItemGetter, items, IM_ARRAYSIZE(items)); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/List Boxes"); + if (ImGui::TreeNode("List boxes")) + { + // Using the generic BeginListBox() API, you have full control over how to display the combo contents. + // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + // stored in the object itself, etc.) + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; + static int item_current_idx = 0; // Here we store our selection data as an index. + if (ImGui::BeginListBox("listbox 1")) + { + for (int n = 0; n < IM_ARRAYSIZE(items); n++) + { + const bool is_selected = (item_current_idx == n); + if (ImGui::Selectable(items[n], is_selected)) + item_current_idx = n; + + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) + if (is_selected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndListBox(); + } + + // Custom size: use all width, 5 items tall + ImGui::Text("Full-width:"); + if (ImGui::BeginListBox("##listbox 2", ImVec2(-FLT_MIN, 5 * ImGui::GetTextLineHeightWithSpacing()))) + { + for (int n = 0; n < IM_ARRAYSIZE(items); n++) + { + const bool is_selected = (item_current_idx == n); + if (ImGui::Selectable(items[n], is_selected)) + item_current_idx = n; + + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) + if (is_selected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndListBox(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Selectables"); + if (ImGui::TreeNode("Selectables")) + { + // Selectable() has 2 overloads: + // - The one taking "bool selected" as a read-only selection information. + // When Selectable() has been clicked it returns true and you can alter selection state accordingly. + // - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases) + // The earlier is more flexible, as in real application your selection may be stored in many different ways + // and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc). + IMGUI_DEMO_MARKER("Widgets/Selectables/Basic"); + if (ImGui::TreeNode("Basic")) + { + static bool selection[5] = { false, true, false, false, false }; + ImGui::Selectable("1. I am selectable", &selection[0]); + ImGui::Selectable("2. I am selectable", &selection[1]); + ImGui::Text("(I am not selectable)"); + ImGui::Selectable("4. I am selectable", &selection[3]); + if (ImGui::Selectable("5. I am double clickable", selection[4], ImGuiSelectableFlags_AllowDoubleClick)) + if (ImGui::IsMouseDoubleClicked(0)) + selection[4] = !selection[4]; + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Selectables/Single Selection"); + if (ImGui::TreeNode("Selection State: Single Selection")) + { + static int selected = -1; + for (int n = 0; n < 5; n++) + { + char buf[32]; + sprintf(buf, "Object %d", n); + if (ImGui::Selectable(buf, selected == n)) + selected = n; + } + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Selectables/Multiple Selection"); + if (ImGui::TreeNode("Selection State: Multiple Selection")) + { + HelpMarker("Hold CTRL and click to select multiple items."); + static bool selection[5] = { false, false, false, false, false }; + for (int n = 0; n < 5; n++) + { + char buf[32]; + sprintf(buf, "Object %d", n); + if (ImGui::Selectable(buf, selection[n])) + { + if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held + memset(selection, 0, sizeof(selection)); + selection[n] ^= 1; + } + } + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Selectables/Rendering more text into the same line"); + if (ImGui::TreeNode("Rendering more text into the same line")) + { + // Using the Selectable() override that takes "bool* p_selected" parameter, + // this function toggle your bool value automatically. + static bool selected[3] = { false, false, false }; + ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); + ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes"); + ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Selectables/In columns"); + if (ImGui::TreeNode("In columns")) + { + static bool selected[10] = {}; + + if (ImGui::BeginTable("split1", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders)) + { + for (int i = 0; i < 10; i++) + { + char label[32]; + sprintf(label, "Item %d", i); + ImGui::TableNextColumn(); + ImGui::Selectable(label, &selected[i]); // FIXME-TABLE: Selection overlap + } + ImGui::EndTable(); + } + ImGui::Spacing(); + if (ImGui::BeginTable("split2", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders)) + { + for (int i = 0; i < 10; i++) + { + char label[32]; + sprintf(label, "Item %d", i); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Selectable(label, &selected[i], ImGuiSelectableFlags_SpanAllColumns); + ImGui::TableNextColumn(); + ImGui::Text("Some other contents"); + ImGui::TableNextColumn(); + ImGui::Text("123456"); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Selectables/Grid"); + if (ImGui::TreeNode("Grid")) + { + static char selected[4][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; + + // Add in a bit of silly fun... + const float time = (float)ImGui::GetTime(); + const bool winning_state = memchr(selected, 0, sizeof(selected)) == NULL; // If all cells are selected... + if (winning_state) + ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f))); + + for (int y = 0; y < 4; y++) + for (int x = 0; x < 4; x++) + { + if (x > 0) + ImGui::SameLine(); + ImGui::PushID(y * 4 + x); + if (ImGui::Selectable("Sailor", selected[y][x] != 0, 0, ImVec2(50, 50))) + { + // Toggle clicked cell + toggle neighbors + selected[y][x] ^= 1; + if (x > 0) { selected[y][x - 1] ^= 1; } + if (x < 3) { selected[y][x + 1] ^= 1; } + if (y > 0) { selected[y - 1][x] ^= 1; } + if (y < 3) { selected[y + 1][x] ^= 1; } + } + ImGui::PopID(); + } + + if (winning_state) + ImGui::PopStyleVar(); + ImGui::TreePop(); + } + IMGUI_DEMO_MARKER("Widgets/Selectables/Alignment"); + if (ImGui::TreeNode("Alignment")) + { + HelpMarker( + "By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item " + "basis using PushStyleVar(). You'll probably want to always keep your default situation to " + "left-align otherwise it becomes difficult to layout multiple items on a same line"); + static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true }; + for (int y = 0; y < 3; y++) + { + for (int x = 0; x < 3; x++) + { + ImVec2 alignment = ImVec2((float)x / 2.0f, (float)y / 2.0f); + char name[32]; + sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y); + if (x > 0) ImGui::SameLine(); + ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment); + ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80)); + ImGui::PopStyleVar(); + } + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + // To wire InputText() with std::string or any other custom string type, + // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. + IMGUI_DEMO_MARKER("Widgets/Text Input"); + if (ImGui::TreeNode("Text Input")) + { + IMGUI_DEMO_MARKER("Widgets/Text Input/Multi-line Text Input"); + if (ImGui::TreeNode("Multi-line Text Input")) + { + // Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize + // and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings. + static char text[1024 * 16] = + "/*\n" + " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" + " the hexadecimal encoding of one offending instruction,\n" + " more formally, the invalid operand with locked CMPXCHG8B\n" + " instruction bug, is a design flaw in the majority of\n" + " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" + " processors (all in the P5 microarchitecture).\n" + "*/\n\n" + "label:\n" + "\tlock cmpxchg8b eax\n"; + + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; + HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include in here)"); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", &flags, ImGuiInputTextFlags_AllowTabInput); + ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine); + ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Filtered Text Input"); + if (ImGui::TreeNode("Filtered Text Input")) + { + struct TextFilters + { + // Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i' + static int FilterImGuiLetters(ImGuiInputTextCallbackData* data) + { + if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) + return 0; + return 1; + } + }; + + static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); + static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); + static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); + static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); + static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Password input"); + if (ImGui::TreeNode("Password Input")) + { + static char password[64] = "password123"; + ImGui::InputText("password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password); + ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); + ImGui::InputTextWithHint("password (w/ hint)", "", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password); + ImGui::InputText("password (clear)", password, IM_ARRAYSIZE(password)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Completion, History, Edit Callbacks")) + { + struct Funcs + { + static int MyCallback(ImGuiInputTextCallbackData* data) + { + if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion) + { + data->InsertChars(data->CursorPos, ".."); + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory) + { + if (data->EventKey == ImGuiKey_UpArrow) + { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, "Pressed Up!"); + data->SelectAll(); + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, "Pressed Down!"); + data->SelectAll(); + } + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit) + { + // Toggle casing of first character + char c = data->Buf[0]; + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) data->Buf[0] ^= 32; + data->BufDirty = true; + + // Increment a counter + int* p_int = (int*)data->UserData; + *p_int = *p_int + 1; + } + return 0; + } + }; + static char buf1[64]; + ImGui::InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); + ImGui::SameLine(); HelpMarker("Here we append \"..\" each time Tab is pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback."); + + static char buf2[64]; + ImGui::InputText("History", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); + ImGui::SameLine(); HelpMarker("Here we replace and select text each time Up/Down are pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback."); + + static char buf3[64]; + static int edit_count = 0; + ImGui::InputText("Edit", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); + ImGui::SameLine(); HelpMarker("Here we toggle the casing of the first character on every edits + count edits."); + ImGui::SameLine(); ImGui::Text("(%d)", edit_count); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Text Input/Resize Callback"); + if (ImGui::TreeNode("Resize Callback")) + { + // To wire InputText() with std::string or any other custom string type, + // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper + // using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string. + HelpMarker( + "Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\n\n" + "See misc/cpp/imgui_stdlib.h for an implementation of this for std::string."); + struct Funcs + { + static int MyResizeCallback(ImGuiInputTextCallbackData* data) + { + if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) + { + ImVector* my_str = (ImVector*)data->UserData; + IM_ASSERT(my_str->begin() == data->Buf); + my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1 + data->Buf = my_str->begin(); + } + return 0; + } + + // Note: Because ImGui:: is a namespace you would typically add your own function into the namespace. + // For example, you code may declare a function 'ImGui::InputText(const char* label, MyString* my_str)' + static bool MyInputTextMultiline(const char* label, ImVector* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0) + { + IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); + return ImGui::InputTextMultiline(label, my_str->begin(), (size_t)my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs::MyResizeCallback, (void*)my_str); + } + }; + + // For this demo we are using ImVector as a string container. + // Note that because we need to store a terminating zero character, our size/capacity are 1 more + // than usually reported by a typical string class. + static ImVector my_str; + if (my_str.empty()) + my_str.push_back(0); + Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16)); + ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", (void*)my_str.begin(), my_str.size(), my_str.capacity()); + ImGui::TreePop(); + } + + ImGui::TreePop(); + } + + // Tabs + IMGUI_DEMO_MARKER("Widgets/Tabs"); + if (ImGui::TreeNode("Tabs")) + { + IMGUI_DEMO_MARKER("Widgets/Tabs/Basic"); + if (ImGui::TreeNode("Basic")) + { + ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None; + if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) + { + if (ImGui::BeginTabItem("Avocado")) + { + ImGui::Text("This is the Avocado tab!\nblah blah blah blah blah"); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Broccoli")) + { + ImGui::Text("This is the Broccoli tab!\nblah blah blah blah blah"); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Cucumber")) + { + ImGui::Text("This is the Cucumber tab!\nblah blah blah blah blah"); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::Separator(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Tabs/Advanced & Close Button"); + if (ImGui::TreeNode("Advanced & Close Button")) + { + // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0). + static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable; + ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", &tab_bar_flags, ImGuiTabBarFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", &tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs); + ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); + ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", &tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton); + if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) + tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_; + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) + tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) + tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); + + // Tab Bar + const char* names[4] = { "Artichoke", "Beetroot", "Celery", "Daikon" }; + static bool opened[4] = { true, true, true, true }; // Persistent user state + for (int n = 0; n < IM_ARRAYSIZE(opened); n++) + { + if (n > 0) { ImGui::SameLine(); } + ImGui::Checkbox(names[n], &opened[n]); + } + + // Passing a bool* to BeginTabItem() is similar to passing one to Begin(): + // the underlying bool will be set to false when the tab is closed. + if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) + { + for (int n = 0; n < IM_ARRAYSIZE(opened); n++) + if (opened[n] && ImGui::BeginTabItem(names[n], &opened[n], ImGuiTabItemFlags_None)) + { + ImGui::Text("This is the %s tab!", names[n]); + if (n & 1) + ImGui::Text("I am an odd tab."); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::Separator(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Tabs/TabItemButton & Leading-Trailing flags"); + if (ImGui::TreeNode("TabItemButton & Leading/Trailing flags")) + { + static ImVector active_tabs; + static int next_tab_id = 0; + if (next_tab_id == 0) // Initialize with some default tabs + for (int i = 0; i < 3; i++) + active_tabs.push_back(next_tab_id++); + + // TabItemButton() and Leading/Trailing flags are distinct features which we will demo together. + // (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags... + // but they tend to make more sense together) + static bool show_leading_button = true; + static bool show_trailing_button = true; + ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button); + ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button); + + // Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs + static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown; + ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) + tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) + tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); + + if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) + { + // Demo a Leading TabItemButton(): click the "?" button to open a menu + if (show_leading_button) + if (ImGui::TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip)) + ImGui::OpenPopup("MyHelpMenu"); + if (ImGui::BeginPopup("MyHelpMenu")) + { + ImGui::Selectable("Hello!"); + ImGui::EndPopup(); + } + + // Demo Trailing Tabs: click the "+" button to add a new tab (in your app you may want to use a font icon instead of the "+") + // Note that we submit it before the regular tabs, but because of the ImGuiTabItemFlags_Trailing flag it will always appear at the end. + if (show_trailing_button) + if (ImGui::TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip)) + active_tabs.push_back(next_tab_id++); // Add new tab + + // Submit our regular tabs + for (int n = 0; n < active_tabs.Size; ) + { + bool open = true; + char name[16]; + snprintf(name, IM_ARRAYSIZE(name), "%04d", active_tabs[n]); + if (ImGui::BeginTabItem(name, &open, ImGuiTabItemFlags_None)) + { + ImGui::Text("This is the %s tab!", name); + ImGui::EndTabItem(); + } + + if (!open) + active_tabs.erase(active_tabs.Data + n); + else + n++; + } + + ImGui::EndTabBar(); + } + ImGui::Separator(); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + // Plot/Graph widgets are not very good. + // Consider using a third-party library such as ImPlot: https://github.com/epezent/implot + // (see others https://github.com/ocornut/imgui/wiki/Useful-Extensions) + IMGUI_DEMO_MARKER("Widgets/Plotting"); + if (ImGui::TreeNode("Plotting")) + { + static bool animate = true; + ImGui::Checkbox("Animate", &animate); + + // Plot as lines and plot as histogram + IMGUI_DEMO_MARKER("Widgets/Plotting/PlotLines, PlotHistogram"); + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); + ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f)); + + // Fill an array of contiguous float values to plot + // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float + // and the sizeof() of your structure in the "stride" parameter. + static float values[90] = {}; + static int values_offset = 0; + static double refresh_time = 0.0; + if (!animate || refresh_time == 0.0) + refresh_time = ImGui::GetTime(); + while (refresh_time < ImGui::GetTime()) // Create data at fixed 60 Hz rate for the demo + { + static float phase = 0.0f; + values[values_offset] = cosf(phase); + values_offset = (values_offset + 1) % IM_ARRAYSIZE(values); + phase += 0.10f * values_offset; + refresh_time += 1.0f / 60.0f; + } + + // Plots can display overlay texts + // (in this example, we will display an average value) + { + float average = 0.0f; + for (int n = 0; n < IM_ARRAYSIZE(values); n++) + average += values[n]; + average /= (float)IM_ARRAYSIZE(values); + char overlay[32]; + sprintf(overlay, "avg %f", average); + ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f)); + } + + // Use functions to generate output + // FIXME: This is rather awkward because current plot API only pass in indices. + // We probably want an API passing floats and user provide sample rate/count. + struct Funcs + { + static float Sin(void*, int i) { return sinf(i * 0.1f); } + static float Saw(void*, int i) { return (i & 1) ? 1.0f : -1.0f; } + }; + static int func_type = 0, display_count = 70; + ImGui::Separator(); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::Combo("func", &func_type, "Sin\0Saw\0"); + ImGui::SameLine(); + ImGui::SliderInt("Sample count", &display_count, 1, 400); + float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; + ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + ImGui::Separator(); + + // Animate a simple progress bar + IMGUI_DEMO_MARKER("Widgets/Plotting/ProgressBar"); + static float progress = 0.0f, progress_dir = 1.0f; + if (animate) + { + progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; + if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; } + if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; } + } + + // Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width, + // or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. + ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f)); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Text("Progress Bar"); + + float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f); + char buf[32]; + sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753); + ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Color"); + if (ImGui::TreeNode("Color/Picker Widgets")) + { + static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f); + + static bool alpha_preview = true; + static bool alpha_half_preview = false; + static bool drag_and_drop = true; + static bool options_menu = true; + static bool hdr = false; + ImGui::Checkbox("With Alpha Preview", &alpha_preview); + ImGui::Checkbox("With Half Alpha Preview", &alpha_half_preview); + ImGui::Checkbox("With Drag and Drop", &drag_and_drop); + ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options."); + ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); + ImGuiColorEditFlags misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit"); + ImGui::Text("Color widget:"); + ImGui::SameLine(); HelpMarker( + "Click on the color square to open a color picker.\n" + "CTRL+click on individual component to input value.\n"); + ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (HSV, with Alpha)"); + ImGui::Text("Color widget HSV with Alpha:"); + ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | misc_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (float display)"); + ImGui::Text("Color widget with Float Display:"); + ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with Picker)"); + ImGui::Text("Color button with Picker:"); + ImGui::SameLine(); HelpMarker( + "With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n" + "With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only " + "be used for the tooltip and picker popup."); + ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with custom Picker popup)"); + ImGui::Text("Color button with Custom Picker Popup:"); + + // Generate a default palette. The palette will persist and can be edited. + static bool saved_palette_init = true; + static ImVec4 saved_palette[32] = {}; + if (saved_palette_init) + { + for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) + { + ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, + saved_palette[n].x, saved_palette[n].y, saved_palette[n].z); + saved_palette[n].w = 1.0f; // Alpha + } + saved_palette_init = false; + } + + static ImVec4 backup_color; + bool open_popup = ImGui::ColorButton("MyColor##3b", color, misc_flags); + ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x); + open_popup |= ImGui::Button("Palette"); + if (open_popup) + { + ImGui::OpenPopup("mypicker"); + backup_color = color; + } + if (ImGui::BeginPopup("mypicker")) + { + ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!"); + ImGui::Separator(); + ImGui::ColorPicker4("##picker", (float*)&color, misc_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview); + ImGui::SameLine(); + + ImGui::BeginGroup(); // Lock X position + ImGui::Text("Current"); + ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)); + ImGui::Text("Previous"); + if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40))) + color = backup_color; + ImGui::Separator(); + ImGui::Text("Palette"); + for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) + { + ImGui::PushID(n); + if ((n % 8) != 0) + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); + + ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip; + if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20))) + color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! + + // Allow user to drop colors into each palette entry. Note that ColorButton() is already a + // drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag. + if (ImGui::BeginDragDropTarget()) + { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) + memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3); + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) + memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4); + ImGui::EndDragDropTarget(); + } + + ImGui::PopID(); + } + ImGui::EndGroup(); + ImGui::EndPopup(); + } + + IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (simple)"); + ImGui::Text("Color button only:"); + static bool no_border = false; + ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border); + ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80)); + + IMGUI_DEMO_MARKER("Widgets/Color/ColorPicker"); + ImGui::Text("Color picker:"); + static bool alpha = true; + static bool alpha_bar = true; + static bool side_preview = true; + static bool ref_color = false; + static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f); + static int display_mode = 0; + static int picker_mode = 0; + ImGui::Checkbox("With Alpha", &alpha); + ImGui::Checkbox("With Alpha Bar", &alpha_bar); + ImGui::Checkbox("With Side Preview", &side_preview); + if (side_preview) + { + ImGui::SameLine(); + ImGui::Checkbox("With Ref Color", &ref_color); + if (ref_color) + { + ImGui::SameLine(); + ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags); + } + } + ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0None\0RGB Only\0HSV Only\0Hex Only\0"); + ImGui::SameLine(); HelpMarker( + "ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, " + "but the user can change it with a right-click on those inputs.\n\nColorPicker defaults to displaying RGB+HSV+Hex " + "if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions()."); + ImGui::SameLine(); HelpMarker("When not specified explicitly (Auto/Current mode), user can right-click the picker to change mode."); + ImGuiColorEditFlags flags = misc_flags; + if (!alpha) flags |= ImGuiColorEditFlags_NoAlpha; // This is by default if you call ColorPicker3() instead of ColorPicker4() + if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar; + if (!side_preview) flags |= ImGuiColorEditFlags_NoSidePreview; + if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar; + if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel; + if (display_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; // Disable all RGB/HSV/Hex displays + if (display_mode == 2) flags |= ImGuiColorEditFlags_DisplayRGB; // Override display mode + if (display_mode == 3) flags |= ImGuiColorEditFlags_DisplayHSV; + if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex; + ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL); + + ImGui::Text("Set defaults in code:"); + ImGui::SameLine(); HelpMarker( + "SetColorEditOptions() is designed to allow you to set boot-time default.\n" + "We don't have Push/Pop functions because you can force options on a per-widget basis if needed," + "and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid" + "encouraging you to persistently save values that aren't forward-compatible."); + if (ImGui::Button("Default: Uint8 + HSV + Hue Bar")) + ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar); + if (ImGui::Button("Default: Float + HDR + Hue Wheel")) + ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel); + + // Always both a small version of both types of pickers (to make it more visible in the demo to people who are skimming quickly through it) + ImGui::Text("Both types:"); + float w = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.y) * 0.40f; + ImGui::SetNextItemWidth(w); + ImGui::ColorPicker3("##MyColor##5", (float*)&color, ImGuiColorEditFlags_PickerHueBar | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha); + ImGui::SameLine(); + ImGui::SetNextItemWidth(w); + ImGui::ColorPicker3("##MyColor##6", (float*)&color, ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha); + + // HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0) + static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV! + ImGui::Spacing(); + ImGui::Text("HSV encoded colors"); + ImGui::SameLine(); HelpMarker( + "By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV" + "allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the" + "added benefit that you can manipulate hue values with the picker even when saturation or value are zero."); + ImGui::Text("Color widget with InputHSV:"); + ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::DragFloat4("Raw HSV values", (float*)&color_hsv, 0.01f, 0.0f, 1.0f); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Drag and Slider Flags"); + if (ImGui::TreeNode("Drag/Slider Flags")) + { + // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! + static ImGuiSliderFlags flags = ImGuiSliderFlags_None; + ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", &flags, ImGuiSliderFlags_AlwaysClamp); + ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); + ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", &flags, ImGuiSliderFlags_Logarithmic); + ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", &flags, ImGuiSliderFlags_NoRoundToFormat); + ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput); + ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); + + // Drags + static float drag_f = 0.5f; + static int drag_i = 50; + ImGui::Text("Underlying float value: %f", drag_f); + ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", flags); + ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", flags); + ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", flags); + ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags); + ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", flags); + + // Sliders + static float slider_f = 0.5f; + static int slider_i = 50; + ImGui::Text("Underlying float value: %f", slider_f); + ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags); + ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Range Widgets"); + if (ImGui::TreeNode("Range Widgets")) + { + static float begin = 10, end = 90; + static int begin_i = 100, end_i = 1000; + ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_AlwaysClamp); + ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); + ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Data Types"); + if (ImGui::TreeNode("Data Types")) + { + // DragScalar/InputScalar/SliderScalar functions allow various data types + // - signed/unsigned + // - 8/16/32/64-bits + // - integer/float/double + // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum + // to pass the type, and passing all arguments by pointer. + // This is the reason the test code below creates local variables to hold "zero" "one" etc. for each types. + // In practice, if you frequently use a given type that is not covered by the normal API entry points, + // you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*, + // and then pass their address to the generic function. For example: + // bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = "%lld") + // { + // return SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format); + // } + + // Setup limits (as helper variables so we can take their address, as explained above) + // Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2. + #ifndef LLONG_MIN + ImS64 LLONG_MIN = -9223372036854775807LL - 1; + ImS64 LLONG_MAX = 9223372036854775807LL; + ImU64 ULLONG_MAX = (2ULL * 9223372036854775807LL + 1); + #endif + const char s8_zero = 0, s8_one = 1, s8_fifty = 50, s8_min = -128, s8_max = 127; + const ImU8 u8_zero = 0, u8_one = 1, u8_fifty = 50, u8_min = 0, u8_max = 255; + const short s16_zero = 0, s16_one = 1, s16_fifty = 50, s16_min = -32768, s16_max = 32767; + const ImU16 u16_zero = 0, u16_one = 1, u16_fifty = 50, u16_min = 0, u16_max = 65535; + const ImS32 s32_zero = 0, s32_one = 1, s32_fifty = 50, s32_min = INT_MIN/2, s32_max = INT_MAX/2, s32_hi_a = INT_MAX/2 - 100, s32_hi_b = INT_MAX/2; + const ImU32 u32_zero = 0, u32_one = 1, u32_fifty = 50, u32_min = 0, u32_max = UINT_MAX/2, u32_hi_a = UINT_MAX/2 - 100, u32_hi_b = UINT_MAX/2; + const ImS64 s64_zero = 0, s64_one = 1, s64_fifty = 50, s64_min = LLONG_MIN/2, s64_max = LLONG_MAX/2, s64_hi_a = LLONG_MAX/2 - 100, s64_hi_b = LLONG_MAX/2; + const ImU64 u64_zero = 0, u64_one = 1, u64_fifty = 50, u64_min = 0, u64_max = ULLONG_MAX/2, u64_hi_a = ULLONG_MAX/2 - 100, u64_hi_b = ULLONG_MAX/2; + const float f32_zero = 0.f, f32_one = 1.f, f32_lo_a = -10000000000.0f, f32_hi_a = +10000000000.0f; + const double f64_zero = 0., f64_one = 1., f64_lo_a = -1000000000000000.0, f64_hi_a = +1000000000000000.0; + + // State + static char s8_v = 127; + static ImU8 u8_v = 255; + static short s16_v = 32767; + static ImU16 u16_v = 65535; + static ImS32 s32_v = -1; + static ImU32 u32_v = (ImU32)-1; + static ImS64 s64_v = -1; + static ImU64 u64_v = (ImU64)-1; + static float f32_v = 0.123f; + static double f64_v = 90000.01234567890123456789; + + const float drag_speed = 0.2f; + static bool drag_clamp = false; + IMGUI_DEMO_MARKER("Widgets/Data Types/Drags"); + ImGui::Text("Drags:"); + ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); + ImGui::SameLine(); HelpMarker( + "As with every widgets in dear imgui, we never modify values unless there is a user interaction.\n" + "You can override the clamping limits by using CTRL+Click to input a value."); + ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL); + ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms"); + ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL); + ImGui::DragScalar("drag u16", ImGuiDataType_U16, &u16_v, drag_speed, drag_clamp ? &u16_zero : NULL, drag_clamp ? &u16_fifty : NULL, "%u ms"); + ImGui::DragScalar("drag s32", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL); + ImGui::DragScalar("drag s32 hex", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL, "0x%08X"); + ImGui::DragScalar("drag u32", ImGuiDataType_U32, &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, "%u ms"); + ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL); + ImGui::DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL); + ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f"); + ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiSliderFlags_Logarithmic); + ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams"); + ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiSliderFlags_Logarithmic); + + IMGUI_DEMO_MARKER("Widgets/Data Types/Sliders"); + ImGui::Text("Sliders"); + ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d"); + ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u"); + ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d"); + ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u"); + ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty,"%d"); + ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d"); + ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d"); + ImGui::SliderScalar("slider s32 hex", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty, "0x%04X"); + ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u"); + ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u"); + ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u"); + ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%" IM_PRId64); + ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%" IM_PRId64); + ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%" IM_PRId64); + ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%" IM_PRIu64 " ms"); + ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%" IM_PRIu64 " ms"); + ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%" IM_PRIu64 " ms"); + ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one); + ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiSliderFlags_Logarithmic); + ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e"); + ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams"); + ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiSliderFlags_Logarithmic); + ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams"); + + ImGui::Text("Sliders (reverse)"); + ImGui::SliderScalar("slider s8 reverse", ImGuiDataType_S8, &s8_v, &s8_max, &s8_min, "%d"); + ImGui::SliderScalar("slider u8 reverse", ImGuiDataType_U8, &u8_v, &u8_max, &u8_min, "%u"); + ImGui::SliderScalar("slider s32 reverse", ImGuiDataType_S32, &s32_v, &s32_fifty, &s32_zero, "%d"); + ImGui::SliderScalar("slider u32 reverse", ImGuiDataType_U32, &u32_v, &u32_fifty, &u32_zero, "%u"); + ImGui::SliderScalar("slider s64 reverse", ImGuiDataType_S64, &s64_v, &s64_fifty, &s64_zero, "%" IM_PRId64); + ImGui::SliderScalar("slider u64 reverse", ImGuiDataType_U64, &u64_v, &u64_fifty, &u64_zero, "%" IM_PRIu64 " ms"); + + IMGUI_DEMO_MARKER("Widgets/Data Types/Inputs"); + static bool inputs_step = true; + ImGui::Text("Inputs"); + ImGui::Checkbox("Show step buttons", &inputs_step); + ImGui::InputScalar("input s8", ImGuiDataType_S8, &s8_v, inputs_step ? &s8_one : NULL, NULL, "%d"); + ImGui::InputScalar("input u8", ImGuiDataType_U8, &u8_v, inputs_step ? &u8_one : NULL, NULL, "%u"); + ImGui::InputScalar("input s16", ImGuiDataType_S16, &s16_v, inputs_step ? &s16_one : NULL, NULL, "%d"); + ImGui::InputScalar("input u16", ImGuiDataType_U16, &u16_v, inputs_step ? &u16_one : NULL, NULL, "%u"); + ImGui::InputScalar("input s32", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%d"); + ImGui::InputScalar("input s32 hex", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%04X"); + ImGui::InputScalar("input u32", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%u"); + ImGui::InputScalar("input u32 hex", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%08X"); + ImGui::InputScalar("input s64", ImGuiDataType_S64, &s64_v, inputs_step ? &s64_one : NULL); + ImGui::InputScalar("input u64", ImGuiDataType_U64, &u64_v, inputs_step ? &u64_one : NULL); + ImGui::InputScalar("input float", ImGuiDataType_Float, &f32_v, inputs_step ? &f32_one : NULL); + ImGui::InputScalar("input double", ImGuiDataType_Double, &f64_v, inputs_step ? &f64_one : NULL); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Multi-component Widgets"); + if (ImGui::TreeNode("Multi-component Widgets")) + { + static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + static int vec4i[4] = { 1, 5, 100, 255 }; + + ImGui::InputFloat2("input float2", vec4f); + ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); + ImGui::InputInt2("input int2", vec4i); + ImGui::DragInt2("drag int2", vec4i, 1, 0, 255); + ImGui::SliderInt2("slider int2", vec4i, 0, 255); + ImGui::Spacing(); + + ImGui::InputFloat3("input float3", vec4f); + ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); + ImGui::InputInt3("input int3", vec4i); + ImGui::DragInt3("drag int3", vec4i, 1, 0, 255); + ImGui::SliderInt3("slider int3", vec4i, 0, 255); + ImGui::Spacing(); + + ImGui::InputFloat4("input float4", vec4f); + ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); + ImGui::InputInt4("input int4", vec4i); + ImGui::DragInt4("drag int4", vec4i, 1, 0, 255); + ImGui::SliderInt4("slider int4", vec4i, 0, 255); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Vertical Sliders"); + if (ImGui::TreeNode("Vertical Sliders")) + { + const float spacing = 4; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); + + static int int_value = 0; + ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5); + ImGui::SameLine(); + + static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; + ImGui::PushID("set1"); + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values[i]); + ImGui::PopStyleColor(4); + ImGui::PopID(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set2"); + static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; + const int rows = 3; + const ImVec2 small_slider_size(18, (float)(int)((160.0f - (rows - 1) * spacing) / rows)); + for (int nx = 0; nx < 4; nx++) + { + if (nx > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + for (int ny = 0; ny < rows; ny++) + { + ImGui::PushID(nx * rows + ny); + ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values2[nx]); + ImGui::PopID(); + } + ImGui::EndGroup(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set3"); + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); + ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::PopStyleVar(); + ImGui::PopID(); + } + ImGui::PopID(); + ImGui::PopStyleVar(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Drag and drop"); + if (ImGui::TreeNode("Drag and Drop")) + { + IMGUI_DEMO_MARKER("Widgets/Drag and drop/Standard widgets"); + if (ImGui::TreeNode("Drag and drop in standard widgets")) + { + // ColorEdit widgets automatically act as drag source and drag target. + // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F + // to allow your own widgets to use colors in their drag and drop interaction. + // Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo. + HelpMarker("You can drag from the color squares."); + static float col1[3] = { 1.0f, 0.0f, 0.2f }; + static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::ColorEdit4("color 2", col2); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Drag and drop/Copy-swap items"); + if (ImGui::TreeNode("Drag and drop to copy/swap items")) + { + enum Mode + { + Mode_Copy, + Mode_Move, + Mode_Swap + }; + static int mode = 0; + if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine(); + if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine(); + if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; } + static const char* names[9] = + { + "Bobby", "Beatrice", "Betty", + "Brianna", "Barry", "Bernard", + "Bibi", "Blaine", "Bryn" + }; + for (int n = 0; n < IM_ARRAYSIZE(names); n++) + { + ImGui::PushID(n); + if ((n % 3) != 0) + ImGui::SameLine(); + ImGui::Button(names[n], ImVec2(60, 60)); + + // Our buttons are both drag sources and drag targets here! + if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) + { + // Set payload to carry the index of our item (could be anything) + ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int)); + + // Display preview (could be anything, e.g. when dragging an image we could decide to display + // the filename and a small preview of the image, etc.) + if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); } + if (mode == Mode_Move) { ImGui::Text("Move %s", names[n]); } + if (mode == Mode_Swap) { ImGui::Text("Swap %s", names[n]); } + ImGui::EndDragDropSource(); + } + if (ImGui::BeginDragDropTarget()) + { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("DND_DEMO_CELL")) + { + IM_ASSERT(payload->DataSize == sizeof(int)); + int payload_n = *(const int*)payload->Data; + if (mode == Mode_Copy) + { + names[n] = names[payload_n]; + } + if (mode == Mode_Move) + { + names[n] = names[payload_n]; + names[payload_n] = ""; + } + if (mode == Mode_Swap) + { + const char* tmp = names[n]; + names[n] = names[payload_n]; + names[payload_n] = tmp; + } + } + ImGui::EndDragDropTarget(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Drag to reorder items (simple)"); + if (ImGui::TreeNode("Drag to reorder items (simple)")) + { + // Simple reordering + HelpMarker( + "We don't use the drag and drop api at all here! " + "Instead we query when the item is held but not hovered, and order items accordingly."); + static const char* item_names[] = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" }; + for (int n = 0; n < IM_ARRAYSIZE(item_names); n++) + { + const char* item = item_names[n]; + ImGui::Selectable(item); + + if (ImGui::IsItemActive() && !ImGui::IsItemHovered()) + { + int n_next = n + (ImGui::GetMouseDragDelta(0).y < 0.f ? -1 : 1); + if (n_next >= 0 && n_next < IM_ARRAYSIZE(item_names)) + { + item_names[n] = item_names[n_next]; + item_names[n_next] = item; + ImGui::ResetMouseDragDelta(); + } + } + } + ImGui::TreePop(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Querying Item Status (Edited,Active,Hovered etc.)"); + if (ImGui::TreeNode("Querying Item Status (Edited/Active/Hovered etc.)")) + { + // Select an item type + const char* item_names[] = + { + "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputTextMultiline", "InputFloat", + "InputFloat3", "ColorEdit4", "Selectable", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "Combo", "ListBox" + }; + static int item_type = 4; + static bool item_disabled = false; + ImGui::Combo("Item Type", &item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names)); + ImGui::SameLine(); + HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions. Note that the bool return value of most ImGui function is generally equivalent to calling ImGui::IsItemHovered()."); + ImGui::Checkbox("Item Disabled", &item_disabled); + + // Submit selected item item so we can query their status in the code following it. + bool ret = false; + static bool b = false; + static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f }; + static char str[16] = {}; + if (item_disabled) + ImGui::BeginDisabled(true); + if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction + if (item_type == 1) { ret = ImGui::Button("ITEM: Button"); } // Testing button + if (item_type == 2) { ImGui::PushButtonRepeat(true); ret = ImGui::Button("ITEM: Button"); ImGui::PopButtonRepeat(); } // Testing button (with repeater) + if (item_type == 3) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox + if (item_type == 4) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item + if (item_type == 5) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing) + if (item_type == 6) { ret = ImGui::InputTextMultiline("ITEM: InputTextMultiline", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which uses a child window) + if (item_type == 7) { ret = ImGui::InputFloat("ITEM: InputFloat", col4f, 1.0f); } // Testing +/- buttons on scalar input + if (item_type == 8) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 9) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 10){ ret = ImGui::Selectable("ITEM: Selectable"); } // Testing selectable item + if (item_type == 11){ ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy) + if (item_type == 12){ ret = ImGui::TreeNode("ITEM: TreeNode"); if (ret) ImGui::TreePop(); } // Testing tree node + if (item_type == 13){ ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. + if (item_type == 14){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::Combo("ITEM: Combo", ¤t, items, IM_ARRAYSIZE(items)); } + if (item_type == 15){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } + + // Display the values of IsItemHovered() and other common item state functions. + // Note that the ImGuiHoveredFlags_XXX flags can be combined. + // Because BulletText is an item itself and that would affect the output of IsItemXXX functions, + // we query every state in a single call to avoid storing them and to simplify the code. + ImGui::BulletText( + "Return value = %d\n" + "IsItemFocused() = %d\n" + "IsItemHovered() = %d\n" + "IsItemHovered(_AllowWhenBlockedByPopup) = %d\n" + "IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\n" + "IsItemHovered(_AllowWhenOverlapped) = %d\n" + "IsItemHovered(_AllowWhenDisabled) = %d\n" + "IsItemHovered(_RectOnly) = %d\n" + "IsItemActive() = %d\n" + "IsItemEdited() = %d\n" + "IsItemActivated() = %d\n" + "IsItemDeactivated() = %d\n" + "IsItemDeactivatedAfterEdit() = %d\n" + "IsItemVisible() = %d\n" + "IsItemClicked() = %d\n" + "IsItemToggledOpen() = %d\n" + "GetItemRectMin() = (%.1f, %.1f)\n" + "GetItemRectMax() = (%.1f, %.1f)\n" + "GetItemRectSize() = (%.1f, %.1f)", + ret, + ImGui::IsItemFocused(), + ImGui::IsItemHovered(), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlapped), + ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled), + ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly), + ImGui::IsItemActive(), + ImGui::IsItemEdited(), + ImGui::IsItemActivated(), + ImGui::IsItemDeactivated(), + ImGui::IsItemDeactivatedAfterEdit(), + ImGui::IsItemVisible(), + ImGui::IsItemClicked(), + ImGui::IsItemToggledOpen(), + ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y, + ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y, + ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y + ); + + if (item_disabled) + ImGui::EndDisabled(); + + char buf[1] = ""; + ImGui::InputText("unused", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_ReadOnly); + ImGui::SameLine(); + HelpMarker("This widget is only here to be able to tab-out of the widgets above and see e.g. Deactivated() status."); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Widgets/Querying Window Status (Focused,Hovered etc.)"); + if (ImGui::TreeNode("Querying Window Status (Focused/Hovered etc.)")) + { + static bool embed_all_inside_a_child_window = false; + ImGui::Checkbox("Embed everything inside a child window for testing _RootWindow flag.", &embed_all_inside_a_child_window); + if (embed_all_inside_a_child_window) + ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), true); + + // Testing IsWindowFocused() function with its various flags. + ImGui::BulletText( + "IsWindowFocused() = %d\n" + "IsWindowFocused(_ChildWindows) = %d\n" + "IsWindowFocused(_ChildWindows|_NoPopupHierarchy) = %d\n" + "IsWindowFocused(_ChildWindows|_DockHierarchy) = %d\n" + "IsWindowFocused(_ChildWindows|_RootWindow) = %d\n" + "IsWindowFocused(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowFocused(_ChildWindows|_RootWindow|_DockHierarchy) = %d\n" + "IsWindowFocused(_RootWindow) = %d\n" + "IsWindowFocused(_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowFocused(_RootWindow|_DockHierarchy) = %d\n" + "IsWindowFocused(_AnyWindow) = %d\n", + ImGui::IsWindowFocused(), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_NoPopupHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_DockHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_DockHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow), + ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_DockHierarchy), + ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)); + + // Testing IsWindowHovered() function with its various flags. + ImGui::BulletText( + "IsWindowHovered() = %d\n" + "IsWindowHovered(_AllowWhenBlockedByPopup) = %d\n" + "IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n" + "IsWindowHovered(_ChildWindows) = %d\n" + "IsWindowHovered(_ChildWindows|_NoPopupHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_DockHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_RootWindow) = %d\n" + "IsWindowHovered(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_RootWindow|_DockHierarchy) = %d\n" + "IsWindowHovered(_RootWindow) = %d\n" + "IsWindowHovered(_RootWindow|_NoPopupHierarchy) = %d\n" + "IsWindowHovered(_RootWindow|_DockHierarchy) = %d\n" + "IsWindowHovered(_ChildWindows|_AllowWhenBlockedByPopup) = %d\n" + "IsWindowHovered(_AnyWindow) = %d\n", + ImGui::IsWindowHovered(), + ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup), + ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_DockHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_DockHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_DockHierarchy), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup), + ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)); + + ImGui::BeginChild("child", ImVec2(0, 50), true); + ImGui::Text("This is another child window for testing the _ChildWindows flag."); + ImGui::EndChild(); + if (embed_all_inside_a_child_window) + ImGui::EndChild(); + + // Calling IsItemHovered() after begin returns the hovered status of the title bar. + // This is useful in particular if you want to create a context menu associated to the title bar of a window. + // This will also work when docked into a Tab (the Tab replace the Title Bar and guarantee the same properties). + static bool test_window = false; + ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window); + if (test_window) + { + // FIXME-DOCK: This window cannot be docked within the ImGui Demo window, this will cause a feedback loop and get them stuck. + // Could we fix this through an ImGuiWindowClass feature? Or an API call to tag our parent as "don't skip items"? + ImGui::Begin("Title bar Hovered/Active tests", &test_window); + if (ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered() + { + if (ImGui::MenuItem("Close")) { test_window = false; } + ImGui::EndPopup(); + } + ImGui::Text( + "IsItemHovered() after begin = %d (== is title bar hovered)\n" + "IsItemActive() after begin = %d (== is window being clicked/moved)\n", + ImGui::IsItemHovered(), ImGui::IsItemActive()); + ImGui::End(); + } + + ImGui::TreePop(); + } + + // Demonstrate BeginDisabled/EndDisabled using a checkbox located at the bottom of the section (which is a bit odd: + // logically we'd have this checkbox at the top of the section, but we don't want this feature to steal that space) + if (disable_all) + ImGui::EndDisabled(); + + IMGUI_DEMO_MARKER("Widgets/Disable Block"); + if (ImGui::TreeNode("Disable block")) + { + ImGui::Checkbox("Disable entire section above", &disable_all); + ImGui::SameLine(); HelpMarker("Demonstrate using BeginDisabled()/EndDisabled() across this section."); + ImGui::TreePop(); + } +} + +static void ShowDemoWindowLayout() +{ + IMGUI_DEMO_MARKER("Layout"); + if (!ImGui::CollapsingHeader("Layout & Scrolling")) + return; + + IMGUI_DEMO_MARKER("Layout/Child windows"); + if (ImGui::TreeNode("Child windows")) + { + HelpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window."); + static bool disable_mouse_wheel = false; + static bool disable_menu = false; + ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel); + ImGui::Checkbox("Disable Menu", &disable_menu); + + // Child 1: no border, enable horizontal scrollbar + { + ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar; + if (disable_mouse_wheel) + window_flags |= ImGuiWindowFlags_NoScrollWithMouse; + ImGui::BeginChild("ChildL", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 260), false, window_flags); + for (int i = 0; i < 100; i++) + ImGui::Text("%04d: scrollable region", i); + ImGui::EndChild(); + } + + ImGui::SameLine(); + + // Child 2: rounded border + { + ImGuiWindowFlags window_flags = ImGuiWindowFlags_None; + if (disable_mouse_wheel) + window_flags |= ImGuiWindowFlags_NoScrollWithMouse; + if (!disable_menu) + window_flags |= ImGuiWindowFlags_MenuBar; + ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); + ImGui::BeginChild("ChildR", ImVec2(0, 260), true, window_flags); + if (!disable_menu && ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Menu")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + if (ImGui::BeginTable("split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings)) + { + for (int i = 0; i < 100; i++) + { + char buf[32]; + sprintf(buf, "%03d", i); + ImGui::TableNextColumn(); + ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f)); + } + ImGui::EndTable(); + } + ImGui::EndChild(); + ImGui::PopStyleVar(); + } + + ImGui::Separator(); + + // Demonstrate a few extra things + // - Changing ImGuiCol_ChildBg (which is transparent black in default styles) + // - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window) + // You can also call SetNextWindowPos() to position the child window. The parent window will effectively + // layout from this position. + // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from + // the POV of the parent window). See 'Demo->Querying Status (Edited/Active/Hovered etc.)' for details. + { + static int offset_x = 0; + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::DragInt("Offset X", &offset_x, 1.0f, -1000, 1000); + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x); + ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); + ImGui::BeginChild("Red", ImVec2(200, 100), true, ImGuiWindowFlags_None); + for (int n = 0; n < 50; n++) + ImGui::Text("Some test %d", n); + ImGui::EndChild(); + bool child_is_hovered = ImGui::IsItemHovered(); + ImVec2 child_rect_min = ImGui::GetItemRectMin(); + ImVec2 child_rect_max = ImGui::GetItemRectMax(); + ImGui::PopStyleColor(); + ImGui::Text("Hovered: %d", child_is_hovered); + ImGui::Text("Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)", child_rect_min.x, child_rect_min.y, child_rect_max.x, child_rect_max.y); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Widgets Width"); + if (ImGui::TreeNode("Widgets Width")) + { + static float f = 0.0f; + static bool show_indented_items = true; + ImGui::Checkbox("Show indented items", &show_indented_items); + + // Use SetNextItemWidth() to set the width of a single upcoming item. + // Use PushItemWidth()/PopItemWidth() to set the width of a group of items. + // In real code use you'll probably want to choose width values that are proportional to your font size + // e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc. + + ImGui::Text("SetNextItemWidth/PushItemWidth(100)"); + ImGui::SameLine(); HelpMarker("Fixed width."); + ImGui::PushItemWidth(100); + ImGui::DragFloat("float##1b", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##1b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + ImGui::Text("SetNextItemWidth/PushItemWidth(-100)"); + ImGui::SameLine(); HelpMarker("Align to right edge minus 100"); + ImGui::PushItemWidth(-100); + ImGui::DragFloat("float##2a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##2b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + ImGui::Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)"); + ImGui::SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); + ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.5f); + ImGui::DragFloat("float##3a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##3b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + ImGui::Text("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)"); + ImGui::SameLine(); HelpMarker("Align to right edge minus half"); + ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f); + ImGui::DragFloat("float##4a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##4b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + // Demonstrate using PushItemWidth to surround three items. + // Calling SetNextItemWidth() before each of them would have the same effect. + ImGui::Text("SetNextItemWidth/PushItemWidth(-FLT_MIN)"); + ImGui::SameLine(); HelpMarker("Align to right edge"); + ImGui::PushItemWidth(-FLT_MIN); + ImGui::DragFloat("##float5a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##5b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout"); + if (ImGui::TreeNode("Basic Horizontal Layout")) + { + ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceding item)"); + + // Text + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/SameLine"); + ImGui::Text("Two items: Hello"); ImGui::SameLine(); + ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); + + // Adjust spacing + ImGui::Text("More spacing: Hello"); ImGui::SameLine(0, 20); + ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); + + // Button + ImGui::AlignTextToFramePadding(); + ImGui::Text("Normal buttons"); ImGui::SameLine(); + ImGui::Button("Banana"); ImGui::SameLine(); + ImGui::Button("Apple"); ImGui::SameLine(); + ImGui::Button("Corniflower"); + + // Button + ImGui::Text("Small buttons"); ImGui::SameLine(); + ImGui::SmallButton("Like this one"); ImGui::SameLine(); + ImGui::Text("can fit within a text block."); + + // Aligned to arbitrary position. Easy/cheap column. + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/SameLine (with offset)"); + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::Text("x=150"); + ImGui::SameLine(300); ImGui::Text("x=300"); + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::SmallButton("x=150"); + ImGui::SameLine(300); ImGui::SmallButton("x=300"); + + // Checkbox + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/SameLine (more)"); + static bool c1 = false, c2 = false, c3 = false, c4 = false; + ImGui::Checkbox("My", &c1); ImGui::SameLine(); + ImGui::Checkbox("Tailor", &c2); ImGui::SameLine(); + ImGui::Checkbox("Is", &c3); ImGui::SameLine(); + ImGui::Checkbox("Rich", &c4); + + // Various + static float f0 = 1.0f, f1 = 2.0f, f2 = 3.0f; + ImGui::PushItemWidth(80); + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; + static int item = -1; + ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); + ImGui::SliderFloat("X", &f0, 0.0f, 5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Y", &f1, 0.0f, 5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Z", &f2, 0.0f, 5.0f); + ImGui::PopItemWidth(); + + ImGui::PushItemWidth(80); + ImGui::Text("Lists:"); + static int selection[4] = { 0, 1, 2, 3 }; + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items)); + ImGui::PopID(); + //if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i); + } + ImGui::PopItemWidth(); + + // Dummy + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Dummy"); + ImVec2 button_sz(40, 40); + ImGui::Button("A", button_sz); ImGui::SameLine(); + ImGui::Dummy(button_sz); ImGui::SameLine(); + ImGui::Button("B", button_sz); + + // Manually wrapping + // (we should eventually provide this as an automatic layout feature, but for now you can do it manually) + IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Manual wrapping"); + ImGui::Text("Manual wrapping:"); + ImGuiStyle& style = ImGui::GetStyle(); + int buttons_count = 20; + float window_visible_x2 = ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x; + for (int n = 0; n < buttons_count; n++) + { + ImGui::PushID(n); + ImGui::Button("Box", button_sz); + float last_button_x2 = ImGui::GetItemRectMax().x; + float next_button_x2 = last_button_x2 + style.ItemSpacing.x + button_sz.x; // Expected position if next button was on same line + if (n + 1 < buttons_count && next_button_x2 < window_visible_x2) + ImGui::SameLine(); + ImGui::PopID(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Groups"); + if (ImGui::TreeNode("Groups")) + { + HelpMarker( + "BeginGroup() basically locks the horizontal position for new line. " + "EndGroup() bundles the whole group so that you can use \"item\" functions such as " + "IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group."); + ImGui::BeginGroup(); + { + ImGui::BeginGroup(); + ImGui::Button("AAA"); + ImGui::SameLine(); + ImGui::Button("BBB"); + ImGui::SameLine(); + ImGui::BeginGroup(); + ImGui::Button("CCC"); + ImGui::Button("DDD"); + ImGui::EndGroup(); + ImGui::SameLine(); + ImGui::Button("EEE"); + ImGui::EndGroup(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("First group hovered"); + } + // Capture the group size and create widgets using the same size + ImVec2 size = ImGui::GetItemRectSize(); + const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; + ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); + + ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y)); + ImGui::SameLine(); + ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y)); + ImGui::EndGroup(); + ImGui::SameLine(); + + ImGui::Button("LEVERAGE\nBUZZWORD", size); + ImGui::SameLine(); + + if (ImGui::BeginListBox("List", size)) + { + ImGui::Selectable("Selected", true); + ImGui::Selectable("Not Selected", false); + ImGui::EndListBox(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Text Baseline Alignment"); + if (ImGui::TreeNode("Text Baseline Alignment")) + { + { + ImGui::BulletText("Text baseline:"); + ImGui::SameLine(); HelpMarker( + "This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. " + "Lines only composed of text or \"small\" widgets use less vertical space than lines with framed widgets."); + ImGui::Indent(); + + ImGui::Text("KO Blahblah"); ImGui::SameLine(); + ImGui::Button("Some framed item"); ImGui::SameLine(); + HelpMarker("Baseline of button will look misaligned with text.."); + + // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. + // (because we don't know what's coming after the Text() statement, we need to move the text baseline + // down by FramePadding.y ahead of time) + ImGui::AlignTextToFramePadding(); + ImGui::Text("OK Blahblah"); ImGui::SameLine(); + ImGui::Button("Some framed item"); ImGui::SameLine(); + HelpMarker("We call AlignTextToFramePadding() to vertically align the text baseline by +FramePadding.y"); + + // SmallButton() uses the same vertical padding as Text + ImGui::Button("TEST##1"); ImGui::SameLine(); + ImGui::Text("TEST"); ImGui::SameLine(); + ImGui::SmallButton("TEST##2"); + + // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. + ImGui::AlignTextToFramePadding(); + ImGui::Text("Text aligned to framed item"); ImGui::SameLine(); + ImGui::Button("Item##1"); ImGui::SameLine(); + ImGui::Text("Item"); ImGui::SameLine(); + ImGui::SmallButton("Item##2"); ImGui::SameLine(); + ImGui::Button("Item##3"); + + ImGui::Unindent(); + } + + ImGui::Spacing(); + + { + ImGui::BulletText("Multi-line text:"); + ImGui::Indent(); + ImGui::Text("One\nTwo\nThree"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("One\nTwo\nThree"); + + ImGui::Button("HOP##1"); ImGui::SameLine(); + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Button("HOP##2"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + ImGui::Unindent(); + } + + ImGui::Spacing(); + + { + ImGui::BulletText("Misc items:"); + ImGui::Indent(); + + // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. + ImGui::Button("80x80", ImVec2(80, 80)); + ImGui::SameLine(); + ImGui::Button("50x50", ImVec2(50, 50)); + ImGui::SameLine(); + ImGui::Button("Button()"); + ImGui::SameLine(); + ImGui::SmallButton("SmallButton()"); + + // Tree + const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; + ImGui::Button("Button##1"); + ImGui::SameLine(0.0f, spacing); + if (ImGui::TreeNode("Node##1")) + { + // Placeholder tree data + for (int i = 0; i < 6; i++) + ImGui::BulletText("Item %d..", i); + ImGui::TreePop(); + } + + // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. + // Otherwise you can use SmallButton() (smaller fit). + ImGui::AlignTextToFramePadding(); + + // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add + // other contents below the node. + bool node_open = ImGui::TreeNode("Node##2"); + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); + if (node_open) + { + // Placeholder tree data + for (int i = 0; i < 6; i++) + ImGui::BulletText("Item %d..", i); + ImGui::TreePop(); + } + + // Bullet + ImGui::Button("Button##3"); + ImGui::SameLine(0.0f, spacing); + ImGui::BulletText("Bullet text"); + + ImGui::AlignTextToFramePadding(); + ImGui::BulletText("Node"); + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##4"); + ImGui::Unindent(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Scrolling"); + if (ImGui::TreeNode("Scrolling")) + { + // Vertical scroll functions + IMGUI_DEMO_MARKER("Layout/Scrolling/Vertical"); + HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position."); + + static int track_item = 50; + static bool enable_track = true; + static bool enable_extra_decorations = false; + static float scroll_to_off_px = 0.0f; + static float scroll_to_pos_px = 200.0f; + + ImGui::Checkbox("Decoration", &enable_extra_decorations); + + ImGui::Checkbox("Track", &enable_track); + ImGui::PushItemWidth(100); + ImGui::SameLine(140); enable_track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d"); + + bool scroll_to_off = ImGui::Button("Scroll Offset"); + ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, FLT_MAX, "+%.0f px"); + + bool scroll_to_pos = ImGui::Button("Scroll To Pos"); + ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, FLT_MAX, "X/Y = %.0f px"); + ImGui::PopItemWidth(); + + if (scroll_to_off || scroll_to_pos) + enable_track = false; + + ImGuiStyle& style = ImGui::GetStyle(); + float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5; + if (child_w < 1.0f) + child_w = 1.0f; + ImGui::PushID("##VerticalScrolling"); + for (int i = 0; i < 5; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + const char* names[] = { "Top", "25%", "Center", "75%", "Bottom" }; + ImGui::TextUnformatted(names[i]); + + const ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0; + const ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i); + const bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(child_w, 200.0f), true, child_flags); + if (ImGui::BeginMenuBar()) + { + ImGui::TextUnformatted("abc"); + ImGui::EndMenuBar(); + } + if (scroll_to_off) + ImGui::SetScrollY(scroll_to_off_px); + if (scroll_to_pos) + ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f); + if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items + { + for (int item = 0; item < 100; item++) + { + if (enable_track && item == track_item) + { + ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item); + ImGui::SetScrollHereY(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom + } + else + { + ImGui::Text("Item %d", item); + } + } + } + float scroll_y = ImGui::GetScrollY(); + float scroll_max_y = ImGui::GetScrollMaxY(); + ImGui::EndChild(); + ImGui::Text("%.0f/%.0f", scroll_y, scroll_max_y); + ImGui::EndGroup(); + } + ImGui::PopID(); + + // Horizontal scroll functions + IMGUI_DEMO_MARKER("Layout/Scrolling/Horizontal"); + ImGui::Spacing(); + HelpMarker( + "Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n" + "Because the clipping rectangle of most window hides half worth of WindowPadding on the " + "left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the " + "equivalent SetScrollFromPosY(+1) wouldn't."); + ImGui::PushID("##HorizontalScrolling"); + for (int i = 0; i < 5; i++) + { + float child_height = ImGui::GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0f; + ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0); + ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i); + bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(-100, child_height), true, child_flags); + if (scroll_to_off) + ImGui::SetScrollX(scroll_to_off_px); + if (scroll_to_pos) + ImGui::SetScrollFromPosX(ImGui::GetCursorStartPos().x + scroll_to_pos_px, i * 0.25f); + if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items + { + for (int item = 0; item < 100; item++) + { + if (item > 0) + ImGui::SameLine(); + if (enable_track && item == track_item) + { + ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item); + ImGui::SetScrollHereX(i * 0.25f); // 0.0f:left, 0.5f:center, 1.0f:right + } + else + { + ImGui::Text("Item %d", item); + } + } + } + float scroll_x = ImGui::GetScrollX(); + float scroll_max_x = ImGui::GetScrollMaxX(); + ImGui::EndChild(); + ImGui::SameLine(); + const char* names[] = { "Left", "25%", "Center", "75%", "Right" }; + ImGui::Text("%s\n%.0f/%.0f", names[i], scroll_x, scroll_max_x); + ImGui::Spacing(); + } + ImGui::PopID(); + + // Miscellaneous Horizontal Scrolling Demo + IMGUI_DEMO_MARKER("Layout/Scrolling/Horizontal (more)"); + HelpMarker( + "Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\n" + "You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin()."); + static int lines = 7; + ImGui::SliderInt("Lines", &lines, 1, 15); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f)); + ImVec2 scrolling_child_size = ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30); + ImGui::BeginChild("scrolling", scrolling_child_size, true, ImGuiWindowFlags_HorizontalScrollbar); + for (int line = 0; line < lines; line++) + { + // Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine() + // If you want to create your own time line for a real application you may be better off manipulating + // the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets + // yourself. You may also want to use the lower-level ImDrawList API. + int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3); + for (int n = 0; n < num_buttons; n++) + { + if (n > 0) ImGui::SameLine(); + ImGui::PushID(n + line * 1000); + char num_buf[16]; + sprintf(num_buf, "%d", n); + const char* label = (!(n % 15)) ? "FizzBuzz" : (!(n % 3)) ? "Fizz" : (!(n % 5)) ? "Buzz" : num_buf; + float hue = n * 0.05f; + ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f)); + ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f)); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + } + float scroll_x = ImGui::GetScrollX(); + float scroll_max_x = ImGui::GetScrollMaxX(); + ImGui::EndChild(); + ImGui::PopStyleVar(2); + float scroll_x_delta = 0.0f; + ImGui::SmallButton("<<"); + if (ImGui::IsItemActive()) + scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); + ImGui::Text("Scroll from code"); ImGui::SameLine(); + ImGui::SmallButton(">>"); + if (ImGui::IsItemActive()) + scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); + ImGui::Text("%.0f/%.0f", scroll_x, scroll_max_x); + if (scroll_x_delta != 0.0f) + { + // Demonstrate a trick: you can use Begin to set yourself in the context of another window + // (here we are already out of your child window) + ImGui::BeginChild("scrolling"); + ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta); + ImGui::EndChild(); + } + ImGui::Spacing(); + + static bool show_horizontal_contents_size_demo_window = false; + ImGui::Checkbox("Show Horizontal contents size demo window", &show_horizontal_contents_size_demo_window); + + if (show_horizontal_contents_size_demo_window) + { + static bool show_h_scrollbar = true; + static bool show_button = true; + static bool show_tree_nodes = true; + static bool show_text_wrapped = false; + static bool show_columns = true; + static bool show_tab_bar = true; + static bool show_child = false; + static bool explicit_content_size = false; + static float contents_size_x = 300.0f; + if (explicit_content_size) + ImGui::SetNextWindowContentSize(ImVec2(contents_size_x, 0.0f)); + ImGui::Begin("Horizontal contents size demo window", &show_horizontal_contents_size_demo_window, show_h_scrollbar ? ImGuiWindowFlags_HorizontalScrollbar : 0); + IMGUI_DEMO_MARKER("Layout/Scrolling/Horizontal contents size demo window"); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 0)); + HelpMarker("Test of different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\nUse 'Metrics->Tools->Show windows rectangles' to visualize rectangles."); + ImGui::Checkbox("H-scrollbar", &show_h_scrollbar); + ImGui::Checkbox("Button", &show_button); // Will grow contents size (unless explicitly overwritten) + ImGui::Checkbox("Tree nodes", &show_tree_nodes); // Will grow contents size and display highlight over full width + ImGui::Checkbox("Text wrapped", &show_text_wrapped);// Will grow and use contents size + ImGui::Checkbox("Columns", &show_columns); // Will use contents size + ImGui::Checkbox("Tab bar", &show_tab_bar); // Will use contents size + ImGui::Checkbox("Child", &show_child); // Will grow and use contents size + ImGui::Checkbox("Explicit content size", &explicit_content_size); + ImGui::Text("Scroll %.1f/%.1f %.1f/%.1f", ImGui::GetScrollX(), ImGui::GetScrollMaxX(), ImGui::GetScrollY(), ImGui::GetScrollMaxY()); + if (explicit_content_size) + { + ImGui::SameLine(); + ImGui::SetNextItemWidth(100); + ImGui::DragFloat("##csx", &contents_size_x); + ImVec2 p = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + 10, p.y + 10), IM_COL32_WHITE); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(p.x + contents_size_x - 10, p.y), ImVec2(p.x + contents_size_x, p.y + 10), IM_COL32_WHITE); + ImGui::Dummy(ImVec2(0, 10)); + } + ImGui::PopStyleVar(2); + ImGui::Separator(); + if (show_button) + { + ImGui::Button("this is a 300-wide button", ImVec2(300, 0)); + } + if (show_tree_nodes) + { + bool open = true; + if (ImGui::TreeNode("this is a tree node")) + { + if (ImGui::TreeNode("another one of those tree node...")) + { + ImGui::Text("Some tree contents"); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::CollapsingHeader("CollapsingHeader", &open); + } + if (show_text_wrapped) + { + ImGui::TextWrapped("This text should automatically wrap on the edge of the work rectangle."); + } + if (show_columns) + { + ImGui::Text("Tables:"); + if (ImGui::BeginTable("table", 4, ImGuiTableFlags_Borders)) + { + for (int n = 0; n < 4; n++) + { + ImGui::TableNextColumn(); + ImGui::Text("Width %.2f", ImGui::GetContentRegionAvail().x); + } + ImGui::EndTable(); + } + ImGui::Text("Columns:"); + ImGui::Columns(4); + for (int n = 0; n < 4; n++) + { + ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); + ImGui::NextColumn(); + } + ImGui::Columns(1); + } + if (show_tab_bar && ImGui::BeginTabBar("Hello")) + { + if (ImGui::BeginTabItem("OneOneOne")) { ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("TwoTwoTwo")) { ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("ThreeThreeThree")) { ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("FourFourFour")) { ImGui::EndTabItem(); } + ImGui::EndTabBar(); + } + if (show_child) + { + ImGui::BeginChild("child", ImVec2(0, 0), true); + ImGui::EndChild(); + } + ImGui::End(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Layout/Clipping"); + if (ImGui::TreeNode("Clipping")) + { + static ImVec2 size(100.0f, 100.0f); + static ImVec2 offset(30.0f, 30.0f); + ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f"); + ImGui::TextWrapped("(Click and drag to scroll)"); + + for (int n = 0; n < 3; n++) + { + if (n > 0) + ImGui::SameLine(); + ImGui::PushID(n); + ImGui::BeginGroup(); // Lock X position + + ImGui::InvisibleButton("##empty", size); + if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + offset.x += ImGui::GetIO().MouseDelta.x; + offset.y += ImGui::GetIO().MouseDelta.y; + } + const ImVec2 p0 = ImGui::GetItemRectMin(); + const ImVec2 p1 = ImGui::GetItemRectMax(); + const char* text_str = "Line 1 hello\nLine 2 clip me!"; + const ImVec2 text_pos = ImVec2(p0.x + offset.x, p0.y + offset.y); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + switch (n) + { + case 0: + HelpMarker( + "Using ImGui::PushClipRect():\n" + "Will alter ImGui hit-testing logic + ImDrawList rendering.\n" + "(use this if you want your clipping rectangle to affect interactions)"); + ImGui::PushClipRect(p0, p1, true); + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(text_pos, IM_COL32_WHITE, text_str); + ImGui::PopClipRect(); + break; + case 1: + HelpMarker( + "Using ImDrawList::PushClipRect():\n" + "Will alter ImDrawList rendering only.\n" + "(use this as a shortcut if you are only using ImDrawList calls)"); + draw_list->PushClipRect(p0, p1, true); + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(text_pos, IM_COL32_WHITE, text_str); + draw_list->PopClipRect(); + break; + case 2: + HelpMarker( + "Using ImDrawList::AddText() with a fine ClipRect:\n" + "Will alter only this specific ImDrawList::AddText() rendering.\n" + "(this is often used internally to avoid altering the clipping rectangle and minimize draw calls)"); + ImVec4 clip_rect(p0.x, p0.y, p1.x, p1.y); // AddText() takes a ImVec4* here so let's convert. + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(ImGui::GetFont(), ImGui::GetFontSize(), text_pos, IM_COL32_WHITE, text_str, NULL, 0.0f, &clip_rect); + break; + } + ImGui::EndGroup(); + ImGui::PopID(); + } + + ImGui::TreePop(); + } +} + +static void ShowDemoWindowPopups() +{ + IMGUI_DEMO_MARKER("Popups"); + if (!ImGui::CollapsingHeader("Popups & Modal windows")) + return; + + // The properties of popups windows are: + // - They block normal mouse hovering detection outside them. (*) + // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as + // we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup(). + // (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even + // when normally blocked by a popup. + // Those three properties are connected. The library needs to hold their visibility state BECAUSE it can close + // popups at any time. + + // Typical use for regular windows: + // bool my_tool_is_active = false; if (ImGui::Button("Open")) my_tool_is_active = true; [...] if (my_tool_is_active) Begin("My Tool", &my_tool_is_active) { [...] } End(); + // Typical use for popups: + // if (ImGui::Button("Open")) ImGui::OpenPopup("MyPopup"); if (ImGui::BeginPopup("MyPopup") { [...] EndPopup(); } + + // With popups we have to go through a library call (here OpenPopup) to manipulate the visibility state. + // This may be a bit confusing at first but it should quickly make sense. Follow on the examples below. + + IMGUI_DEMO_MARKER("Popups/Popups"); + if (ImGui::TreeNode("Popups")) + { + ImGui::TextWrapped( + "When a popup is active, it inhibits interacting with windows that are behind the popup. " + "Clicking outside the popup closes it."); + + static int selected_fish = -1; + const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; + static bool toggles[] = { true, false, false, false, false }; + + // Simple selection popup (if you want to show the current selection inside the Button itself, + // you may want to build a string using the "###" operator to preserve a constant ID with a variable label) + if (ImGui::Button("Select..")) + ImGui::OpenPopup("my_select_popup"); + ImGui::SameLine(); + ImGui::TextUnformatted(selected_fish == -1 ? "" : names[selected_fish]); + if (ImGui::BeginPopup("my_select_popup")) + { + ImGui::Text("Aquarium"); + ImGui::Separator(); + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + if (ImGui::Selectable(names[i])) + selected_fish = i; + ImGui::EndPopup(); + } + + // Showing a menu with toggles + if (ImGui::Button("Toggle..")) + ImGui::OpenPopup("my_toggle_popup"); + if (ImGui::BeginPopup("my_toggle_popup")) + { + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + ImGui::EndMenu(); + } + + ImGui::Separator(); + ImGui::Text("Tooltip here"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip over a popup"); + + if (ImGui::Button("Stacked Popup")) + ImGui::OpenPopup("another popup"); + if (ImGui::BeginPopup("another popup")) + { + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + if (ImGui::Button("Stacked Popup")) + ImGui::OpenPopup("another popup"); + if (ImGui::BeginPopup("another popup")) + { + ImGui::Text("I am the last one here."); + ImGui::EndPopup(); + } + ImGui::EndMenu(); + } + ImGui::EndPopup(); + } + ImGui::EndPopup(); + } + + // Call the more complete ShowExampleMenuFile which we use in various places of this demo + if (ImGui::Button("With a menu..")) + ImGui::OpenPopup("my_file_popup"); + if (ImGui::BeginPopup("my_file_popup", ImGuiWindowFlags_MenuBar)) + { + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Edit")) + { + ImGui::MenuItem("Dummy"); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + ImGui::Text("Hello from popup!"); + ImGui::Button("This is a dummy button.."); + ImGui::EndPopup(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Popups/Context menus"); + if (ImGui::TreeNode("Context menus")) + { + HelpMarker("\"Context\" functions are simple helpers to associate a Popup to a given Item or Window identifier."); + + // BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing: + // if (id == 0) + // id = GetItemID(); // Use last item id + // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) + // OpenPopup(id); + // return BeginPopup(id); + // For advanced advanced uses you may want to replicate and customize this code. + // See more details in BeginPopupContextItem(). + + // Example 1 + // When used after an item that has an ID (e.g. Button), we can skip providing an ID to BeginPopupContextItem(), + // and BeginPopupContextItem() will use the last item ID as the popup ID. + { + const char* names[5] = { "Label1", "Label2", "Label3", "Label4", "Label5" }; + for (int n = 0; n < 5; n++) + { + ImGui::Selectable(names[n]); + if (ImGui::BeginPopupContextItem()) // <-- use last item id as popup id + { + ImGui::Text("This a popup for \"%s\"!", names[n]); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Right-click to open popup"); + } + } + + // Example 2 + // Popup on a Text() element which doesn't have an identifier: we need to provide an identifier to BeginPopupContextItem(). + // Using an explicit identifier is also convenient if you want to activate the popups from different locations. + { + HelpMarker("Text() elements don't have stable identifiers so we need to provide one."); + static float value = 0.5f; + ImGui::Text("Value = %.3f <-- (1) right-click this text", value); + if (ImGui::BeginPopupContextItem("my popup")) + { + if (ImGui::Selectable("Set to zero")) value = 0.0f; + if (ImGui::Selectable("Set to PI")) value = 3.1415f; + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::DragFloat("##Value", &value, 0.1f, 0.0f, 0.0f); + ImGui::EndPopup(); + } + + // We can also use OpenPopupOnItemClick() to toggle the visibility of a given popup. + // Here we make it that right-clicking this other text element opens the same popup as above. + // The popup itself will be submitted by the code above. + ImGui::Text("(2) Or right-click this text"); + ImGui::OpenPopupOnItemClick("my popup", ImGuiPopupFlags_MouseButtonRight); + + // Back to square one: manually open the same popup. + if (ImGui::Button("(3) Or click this button")) + ImGui::OpenPopup("my popup"); + } + + // Example 3 + // When using BeginPopupContextItem() with an implicit identifier (NULL == use last item ID), + // we need to make sure your item identifier is stable. + // In this example we showcase altering the item label while preserving its identifier, using the ### operator (see FAQ). + { + HelpMarker("Showcase using a popup ID linked to item ID, with the item having a changing label + stable ID using the ### operator."); + static char name[32] = "Label1"; + char buf[64]; + sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label + ImGui::Button(buf); + if (ImGui::BeginPopupContextItem()) + { + ImGui::Text("Edit name:"); + ImGui::InputText("##edit", name, IM_ARRAYSIZE(name)); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::SameLine(); ImGui::Text("(<-- right-click here)"); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Popups/Modals"); + if (ImGui::TreeNode("Modals")) + { + ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside."); + + if (ImGui::Button("Delete..")) + ImGui::OpenPopup("Delete?"); + + // Always center this window when appearing + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + + if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); + ImGui::Separator(); + + //static int unused_i = 0; + //ImGui::Combo("Combo", &unused_i, "Delete\0Delete harder\0"); + + static bool dont_ask_me_next_time = false; + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time); + ImGui::PopStyleVar(); + + if (ImGui::Button("OK", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); } + ImGui::SetItemDefaultFocus(); + ImGui::SameLine(); + if (ImGui::Button("Cancel", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); } + ImGui::EndPopup(); + } + + if (ImGui::Button("Stacked modals..")) + ImGui::OpenPopup("Stacked 1"); + if (ImGui::BeginPopupModal("Stacked 1", NULL, ImGuiWindowFlags_MenuBar)) + { + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Some menu item")) {} + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + ImGui::Text("Hello from Stacked The First\nUsing style.Colors[ImGuiCol_ModalWindowDimBg] behind it."); + + // Testing behavior of widgets stacking their own regular popups over the modal. + static int item = 1; + static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; + ImGui::Combo("Combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); + ImGui::ColorEdit4("color", color); + + if (ImGui::Button("Add another modal..")) + ImGui::OpenPopup("Stacked 2"); + + // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which + // will close the popup. Note that the visibility state of popups is owned by imgui, so the input value + // of the bool actually doesn't matter here. + bool unused_open = true; + if (ImGui::BeginPopupModal("Stacked 2", &unused_open)) + { + ImGui::Text("Hello from Stacked The Second!"); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Popups/Menus inside a regular window"); + if (ImGui::TreeNode("Menus inside a regular window")) + { + ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!"); + ImGui::Separator(); + + // Note: As a quirk in this very specific example, we want to differentiate the parent of this menu from the + // parent of the various popup menus above. To do so we are encloding the items in a PushID()/PopID() block + // to make them two different menusets. If we don't, opening any popup above and hovering our menu here would + // open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, + // which is the desired behavior for regular menus. + ImGui::PushID("foo"); + ImGui::MenuItem("Menu item", "CTRL+M"); + if (ImGui::BeginMenu("Menu inside a regular window")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::PopID(); + ImGui::Separator(); + ImGui::TreePop(); + } +} + +// Dummy data structure that we use for the Table demo. +// (pre-C++11 doesn't allow us to instantiate ImVector template if this structure if defined inside the demo function) +namespace +{ +// We are passing our own identifier to TableSetupColumn() to facilitate identifying columns in the sorting code. +// This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID. +// But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex) +// If you don't use sorting, you will generally never care about giving column an ID! +enum MyItemColumnID +{ + MyItemColumnID_ID, + MyItemColumnID_Name, + MyItemColumnID_Action, + MyItemColumnID_Quantity, + MyItemColumnID_Description +}; + +struct MyItem +{ + int ID; + const char* Name; + int Quantity; + + // We have a problem which is affecting _only this demo_ and should not affect your code: + // As we don't rely on std:: or other third-party library to compile dear imgui, we only have reliable access to qsort(), + // however qsort doesn't allow passing user data to comparing function. + // As a workaround, we are storing the sort specs in a static/global for the comparing function to access. + // In your own use case you would probably pass the sort specs to your sorting/comparing functions directly and not use a global. + // We could technically call ImGui::TableGetSortSpecs() in CompareWithSortSpecs(), but considering that this function is called + // very often by the sorting algorithm it would be a little wasteful. + static const ImGuiTableSortSpecs* s_current_sort_specs; + + // Compare function to be used by qsort() + static int IMGUI_CDECL CompareWithSortSpecs(const void* lhs, const void* rhs) + { + const MyItem* a = (const MyItem*)lhs; + const MyItem* b = (const MyItem*)rhs; + for (int n = 0; n < s_current_sort_specs->SpecsCount; n++) + { + // Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn() + // We could also choose to identify columns based on their index (sort_spec->ColumnIndex), which is simpler! + const ImGuiTableColumnSortSpecs* sort_spec = &s_current_sort_specs->Specs[n]; + int delta = 0; + switch (sort_spec->ColumnUserID) + { + case MyItemColumnID_ID: delta = (a->ID - b->ID); break; + case MyItemColumnID_Name: delta = (strcmp(a->Name, b->Name)); break; + case MyItemColumnID_Quantity: delta = (a->Quantity - b->Quantity); break; + case MyItemColumnID_Description: delta = (strcmp(a->Name, b->Name)); break; + default: IM_ASSERT(0); break; + } + if (delta > 0) + return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1; + if (delta < 0) + return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1; + } + + // qsort() is instable so always return a way to differenciate items. + // Your own compare function may want to avoid fallback on implicit sort specs e.g. a Name compare if it wasn't already part of the sort specs. + return (a->ID - b->ID); + } +}; +const ImGuiTableSortSpecs* MyItem::s_current_sort_specs = NULL; +} + +// Make the UI compact because there are so many fields +static void PushStyleCompact() +{ + ImGuiStyle& style = ImGui::GetStyle(); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, (float)(int)(style.FramePadding.y * 0.60f))); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, (float)(int)(style.ItemSpacing.y * 0.60f))); +} + +static void PopStyleCompact() +{ + ImGui::PopStyleVar(2); +} + +// Show a combo box with a choice of sizing policies +static void EditTableSizingFlags(ImGuiTableFlags* p_flags) +{ + struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; }; + static const EnumDesc policies[] = + { + { ImGuiTableFlags_None, "Default", "Use default sizing policy:\n- ImGuiTableFlags_SizingFixedFit if ScrollX is on or if host window has ImGuiWindowFlags_AlwaysAutoResize.\n- ImGuiTableFlags_SizingStretchSame otherwise." }, + { ImGuiTableFlags_SizingFixedFit, "ImGuiTableFlags_SizingFixedFit", "Columns default to _WidthFixed (if resizable) or _WidthAuto (if not resizable), matching contents width." }, + { ImGuiTableFlags_SizingFixedSame, "ImGuiTableFlags_SizingFixedSame", "Columns are all the same width, matching the maximum contents width.\nImplicitly disable ImGuiTableFlags_Resizable and enable ImGuiTableFlags_NoKeepColumnsVisible." }, + { ImGuiTableFlags_SizingStretchProp, "ImGuiTableFlags_SizingStretchProp", "Columns default to _WidthStretch with weights proportional to their widths." }, + { ImGuiTableFlags_SizingStretchSame, "ImGuiTableFlags_SizingStretchSame", "Columns default to _WidthStretch with same weights." } + }; + int idx; + for (idx = 0; idx < IM_ARRAYSIZE(policies); idx++) + if (policies[idx].Value == (*p_flags & ImGuiTableFlags_SizingMask_)) + break; + const char* preview_text = (idx < IM_ARRAYSIZE(policies)) ? policies[idx].Name + (idx > 0 ? strlen("ImGuiTableFlags") : 0) : ""; + if (ImGui::BeginCombo("Sizing Policy", preview_text)) + { + for (int n = 0; n < IM_ARRAYSIZE(policies); n++) + if (ImGui::Selectable(policies[n].Name, idx == n)) + *p_flags = (*p_flags & ~ImGuiTableFlags_SizingMask_) | policies[n].Value; + ImGui::EndCombo(); + } + ImGui::SameLine(); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 50.0f); + for (int m = 0; m < IM_ARRAYSIZE(policies); m++) + { + ImGui::Separator(); + ImGui::Text("%s:", policies[m].Name); + ImGui::Separator(); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetStyle().IndentSpacing * 0.5f); + ImGui::TextUnformatted(policies[m].Tooltip); + } + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +static void EditTableColumnsFlags(ImGuiTableColumnFlags* p_flags) +{ + ImGui::CheckboxFlags("_Disabled", p_flags, ImGuiTableColumnFlags_Disabled); ImGui::SameLine(); HelpMarker("Master disable flag (also hide from context menu)"); + ImGui::CheckboxFlags("_DefaultHide", p_flags, ImGuiTableColumnFlags_DefaultHide); + ImGui::CheckboxFlags("_DefaultSort", p_flags, ImGuiTableColumnFlags_DefaultSort); + if (ImGui::CheckboxFlags("_WidthStretch", p_flags, ImGuiTableColumnFlags_WidthStretch)) + *p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthStretch); + if (ImGui::CheckboxFlags("_WidthFixed", p_flags, ImGuiTableColumnFlags_WidthFixed)) + *p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthFixed); + ImGui::CheckboxFlags("_NoResize", p_flags, ImGuiTableColumnFlags_NoResize); + ImGui::CheckboxFlags("_NoReorder", p_flags, ImGuiTableColumnFlags_NoReorder); + ImGui::CheckboxFlags("_NoHide", p_flags, ImGuiTableColumnFlags_NoHide); + ImGui::CheckboxFlags("_NoClip", p_flags, ImGuiTableColumnFlags_NoClip); + ImGui::CheckboxFlags("_NoSort", p_flags, ImGuiTableColumnFlags_NoSort); + ImGui::CheckboxFlags("_NoSortAscending", p_flags, ImGuiTableColumnFlags_NoSortAscending); + ImGui::CheckboxFlags("_NoSortDescending", p_flags, ImGuiTableColumnFlags_NoSortDescending); + ImGui::CheckboxFlags("_NoHeaderLabel", p_flags, ImGuiTableColumnFlags_NoHeaderLabel); + ImGui::CheckboxFlags("_NoHeaderWidth", p_flags, ImGuiTableColumnFlags_NoHeaderWidth); + ImGui::CheckboxFlags("_PreferSortAscending", p_flags, ImGuiTableColumnFlags_PreferSortAscending); + ImGui::CheckboxFlags("_PreferSortDescending", p_flags, ImGuiTableColumnFlags_PreferSortDescending); + ImGui::CheckboxFlags("_IndentEnable", p_flags, ImGuiTableColumnFlags_IndentEnable); ImGui::SameLine(); HelpMarker("Default for column 0"); + ImGui::CheckboxFlags("_IndentDisable", p_flags, ImGuiTableColumnFlags_IndentDisable); ImGui::SameLine(); HelpMarker("Default for column >0"); +} + +static void ShowTableColumnsStatusFlags(ImGuiTableColumnFlags flags) +{ + ImGui::CheckboxFlags("_IsEnabled", &flags, ImGuiTableColumnFlags_IsEnabled); + ImGui::CheckboxFlags("_IsVisible", &flags, ImGuiTableColumnFlags_IsVisible); + ImGui::CheckboxFlags("_IsSorted", &flags, ImGuiTableColumnFlags_IsSorted); + ImGui::CheckboxFlags("_IsHovered", &flags, ImGuiTableColumnFlags_IsHovered); +} + +static void ShowDemoWindowTables() +{ + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); + IMGUI_DEMO_MARKER("Tables"); + if (!ImGui::CollapsingHeader("Tables & Columns")) + return; + + // Using those as a base value to create width/height that are factor of the size of our font + const float TEXT_BASE_WIDTH = ImGui::CalcTextSize("A").x; + const float TEXT_BASE_HEIGHT = ImGui::GetTextLineHeightWithSpacing(); + + ImGui::PushID("Tables"); + + int open_action = -1; + if (ImGui::Button("Open all")) + open_action = 1; + ImGui::SameLine(); + if (ImGui::Button("Close all")) + open_action = 0; + ImGui::SameLine(); + + // Options + static bool disable_indent = false; + ImGui::Checkbox("Disable tree indentation", &disable_indent); + ImGui::SameLine(); + HelpMarker("Disable the indenting of tree nodes so demo tables can use the full window width."); + ImGui::Separator(); + if (disable_indent) + ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0f); + + // About Styling of tables + // Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs. + // There are however a few settings that a shared and part of the ImGuiStyle structure: + // style.CellPadding // Padding within each cell + // style.Colors[ImGuiCol_TableHeaderBg] // Table header background + // style.Colors[ImGuiCol_TableBorderStrong] // Table outer and header borders + // style.Colors[ImGuiCol_TableBorderLight] // Table inner borders + // style.Colors[ImGuiCol_TableRowBg] // Table row background when ImGuiTableFlags_RowBg is enabled (even rows) + // style.Colors[ImGuiCol_TableRowBgAlt] // Table row background when ImGuiTableFlags_RowBg is enabled (odds rows) + + // Demos + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Basic"); + if (ImGui::TreeNode("Basic")) + { + // Here we will showcase three different ways to output a table. + // They are very simple variations of a same thing! + + // [Method 1] Using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column. + // In many situations, this is the most flexible and easy to use pattern. + HelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop."); + if (ImGui::BeginTable("table1", 3)) + { + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Row %d Column %d", row, column); + } + } + ImGui::EndTable(); + } + + // [Method 2] Using TableNextColumn() called multiple times, instead of using a for loop + TableSetColumnIndex(). + // This is generally more convenient when you have code manually submitting the contents of each columns. + HelpMarker("Using TableNextRow() + calling TableNextColumn() _before_ each cell, manually."); + if (ImGui::BeginTable("table2", 3)) + { + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("Row %d", row); + ImGui::TableNextColumn(); + ImGui::Text("Some contents"); + ImGui::TableNextColumn(); + ImGui::Text("123.456"); + } + ImGui::EndTable(); + } + + // [Method 3] We call TableNextColumn() _before_ each cell. We never call TableNextRow(), + // as TableNextColumn() will automatically wrap around and create new roes as needed. + // This is generally more convenient when your cells all contains the same type of data. + HelpMarker( + "Only using TableNextColumn(), which tends to be convenient for tables where every cells contains the same type of contents.\n" + "This is also more similar to the old NextColumn() function of the Columns API, and provided to facilitate the Columns->Tables API transition."); + if (ImGui::BeginTable("table3", 3)) + { + for (int item = 0; item < 14; item++) + { + ImGui::TableNextColumn(); + ImGui::Text("Item %d", item); + } + ImGui::EndTable(); + } + + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Borders, background"); + if (ImGui::TreeNode("Borders, background")) + { + // Expose a few Borders related flags interactively + enum ContentsType { CT_Text, CT_FillButton }; + static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg; + static bool display_headers = false; + static int contents_type = CT_Text; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg); + ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags, ImGuiTableFlags_Borders); + ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterV\n | ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterH"); + ImGui::Indent(); + + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags, ImGuiTableFlags_BordersH); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", &flags, ImGuiTableFlags_BordersOuterH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", &flags, ImGuiTableFlags_BordersInnerH); + ImGui::Unindent(); + + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags, ImGuiTableFlags_BordersInnerV); + ImGui::Unindent(); + + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags, ImGuiTableFlags_BordersOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags, ImGuiTableFlags_BordersInner); + ImGui::Unindent(); + + ImGui::AlignTextToFramePadding(); ImGui::Text("Cell contents:"); + ImGui::SameLine(); ImGui::RadioButton("Text", &contents_type, CT_Text); + ImGui::SameLine(); ImGui::RadioButton("FillButton", &contents_type, CT_FillButton); + ImGui::Checkbox("Display headers", &display_headers); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appears in Headers"); + PopStyleCompact(); + + if (ImGui::BeginTable("table1", 3, flags)) + { + // Display headers so we can inspect their interaction with borders. + // (Headers are not the main purpose of this section of the demo, so we are not elaborating on them too much. See other sections for details) + if (display_headers) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + } + + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + char buf[32]; + sprintf(buf, "Hello %d,%d", column, row); + if (contents_type == CT_Text) + ImGui::TextUnformatted(buf); + else if (contents_type == CT_FillButton) + ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f)); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Resizable, stretch"); + if (ImGui::TreeNode("Resizable, stretch")) + { + // By default, if we don't enable ScrollX the sizing policy for each columns is "Stretch" + // Each columns maintain a sizing weight, and they will occupy all available width. + static ImGuiTableFlags flags = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV); + ImGui::SameLine(); HelpMarker("Using the _Resizable flag automatically enables the _BordersInnerV flag as well, this is why the resize borders are still showing when unchecking this."); + PopStyleCompact(); + + if (ImGui::BeginTable("table1", 3, flags)) + { + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Resizable, fixed"); + if (ImGui::TreeNode("Resizable, fixed")) + { + // Here we use ImGuiTableFlags_SizingFixedFit (even though _ScrollX is not set) + // So columns will adopt the "Fixed" policy and will maintain a fixed width regardless of the whole available width (unless table is small) + // If there is not enough available width to fit all columns, they will however be resized down. + // FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings + HelpMarker( + "Using _Resizable + _SizingFixedFit flags.\n" + "Fixed-width columns generally makes more sense if you want to use horizontal scrolling.\n\n" + "Double-click a column border to auto-fit the column to its contents."); + PushStyleCompact(); + static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody; + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX); + PopStyleCompact(); + + if (ImGui::BeginTable("table1", 3, flags)) + { + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Resizable, mixed"); + if (ImGui::TreeNode("Resizable, mixed")) + { + HelpMarker( + "Using TableSetupColumn() to alter resizing policy on a per-column basis.\n\n" + "When combining Fixed and Stretch columns, generally you only want one, maybe two trailing columns to use _WidthStretch."); + static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + + if (ImGui::BeginTable("table1", 3, flags)) + { + ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableHeadersRow(); + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%s %d,%d", (column == 2) ? "Stretch" : "Fixed", column, row); + } + } + ImGui::EndTable(); + } + if (ImGui::BeginTable("table2", 6, flags)) + { + ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_DefaultHide); + ImGui::TableSetupColumn("DDD", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("EEE", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("FFF", ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide); + ImGui::TableHeadersRow(); + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 6; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%s %d,%d", (column >= 3) ? "Stretch" : "Fixed", column, row); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Reorderable, hideable, with headers"); + if (ImGui::TreeNode("Reorderable, hideable, with headers")) + { + HelpMarker( + "Click and drag column headers to reorder columns.\n\n" + "Right-click on a header to open a context menu."); + static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", &flags, ImGuiTableFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", &flags, ImGuiTableFlags_Hideable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)"); + PopStyleCompact(); + + if (ImGui::BeginTable("table1", 3, flags)) + { + // Submit columns name with TableSetupColumn() and call TableHeadersRow() to create a row with a header in each column. + // (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.) + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + for (int row = 0; row < 6; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", column, row); + } + } + ImGui::EndTable(); + } + + // Use outer_size.x == 0.0f instead of default to make the table as tight as possible (only valid when no scrolling and no stretch column) + if (ImGui::BeginTable("table2", 3, flags | ImGuiTableFlags_SizingFixedFit, ImVec2(0.0f, 0.0f))) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + for (int row = 0; row < 6; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Fixed %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Padding"); + if (ImGui::TreeNode("Padding")) + { + // First example: showcase use of padding flags and effect of BorderOuterV/BorderInnerV on X padding. + // We don't expose BorderOuterH/BorderInnerH here because they have no effect on X padding. + HelpMarker( + "We often want outer padding activated when any using features which makes the edges of a column visible:\n" + "e.g.:\n" + "- BorderOuterV\n" + "- any form of row selection\n" + "Because of this, activating BorderOuterV sets the default to PadOuterX. Using PadOuterX or NoPadOuterX you can override the default.\n\n" + "Actual padding values are using style.CellPadding.\n\n" + "In this demo we don't show horizontal borders to emphasis how they don't affect default horizontal padding."); + + static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags1, ImGuiTableFlags_PadOuterX); + ImGui::SameLine(); HelpMarker("Enable outer-most padding (default if ImGuiTableFlags_BordersOuterV is set)"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoPadOuterX", &flags1, ImGuiTableFlags_NoPadOuterX); + ImGui::SameLine(); HelpMarker("Disable outer-most padding (default if ImGuiTableFlags_BordersOuterV is not set)"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoPadInnerX", &flags1, ImGuiTableFlags_NoPadInnerX); + ImGui::SameLine(); HelpMarker("Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off)"); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags1, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags1, ImGuiTableFlags_BordersInnerV); + static bool show_headers = false; + ImGui::Checkbox("show_headers", &show_headers); + PopStyleCompact(); + + if (ImGui::BeginTable("table_padding", 3, flags1)) + { + if (show_headers) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + } + + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + if (row == 0) + { + ImGui::Text("Avail %.2f", ImGui::GetContentRegionAvail().x); + } + else + { + char buf[32]; + sprintf(buf, "Hello %d,%d", column, row); + ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f)); + } + //if (ImGui::TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) + // ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, IM_COL32(0, 100, 0, 255)); + } + } + ImGui::EndTable(); + } + + // Second example: set style.CellPadding to (0.0) or a custom value. + // FIXME-TABLE: Vertical border effectively not displayed the same way as horizontal one... + HelpMarker("Setting style.CellPadding to (0,0) or a custom value."); + static ImGuiTableFlags flags2 = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg; + static ImVec2 cell_padding(0.0f, 0.0f); + static bool show_widget_frame_bg = true; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags2, ImGuiTableFlags_Borders); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags2, ImGuiTableFlags_BordersH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags2, ImGuiTableFlags_BordersV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags2, ImGuiTableFlags_BordersInner); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags2, ImGuiTableFlags_BordersOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags2, ImGuiTableFlags_RowBg); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags2, ImGuiTableFlags_Resizable); + ImGui::Checkbox("show_widget_frame_bg", &show_widget_frame_bg); + ImGui::SliderFloat2("CellPadding", &cell_padding.x, 0.0f, 10.0f, "%.0f"); + PopStyleCompact(); + + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, cell_padding); + if (ImGui::BeginTable("table_padding_2", 3, flags2)) + { + static char text_bufs[3 * 5][16]; // Mini text storage for 3x5 cells + static bool init = true; + if (!show_widget_frame_bg) + ImGui::PushStyleColor(ImGuiCol_FrameBg, 0); + for (int cell = 0; cell < 3 * 5; cell++) + { + ImGui::TableNextColumn(); + if (init) + strcpy(text_bufs[cell], "edit me"); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::PushID(cell); + ImGui::InputText("##cell", text_bufs[cell], IM_ARRAYSIZE(text_bufs[cell])); + ImGui::PopID(); + } + if (!show_widget_frame_bg) + ImGui::PopStyleColor(); + init = false; + ImGui::EndTable(); + } + ImGui::PopStyleVar(); + + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Explicit widths"); + if (ImGui::TreeNode("Sizing policies")) + { + static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags1, ImGuiTableFlags_NoHostExtendX); + PopStyleCompact(); + + static ImGuiTableFlags sizing_policy_flags[4] = { ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingFixedSame, ImGuiTableFlags_SizingStretchProp, ImGuiTableFlags_SizingStretchSame }; + for (int table_n = 0; table_n < 4; table_n++) + { + ImGui::PushID(table_n); + ImGui::SetNextItemWidth(TEXT_BASE_WIDTH * 30); + EditTableSizingFlags(&sizing_policy_flags[table_n]); + + // To make it easier to understand the different sizing policy, + // For each policy: we display one table where the columns have equal contents width, and one where the columns have different contents width. + if (ImGui::BeginTable("table1", 3, sizing_policy_flags[table_n] | flags1)) + { + for (int row = 0; row < 3; row++) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); ImGui::Text("Oh dear"); + ImGui::TableNextColumn(); ImGui::Text("Oh dear"); + ImGui::TableNextColumn(); ImGui::Text("Oh dear"); + } + ImGui::EndTable(); + } + if (ImGui::BeginTable("table2", 3, sizing_policy_flags[table_n] | flags1)) + { + for (int row = 0; row < 3; row++) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); ImGui::Text("AAAA"); + ImGui::TableNextColumn(); ImGui::Text("BBBBBBBB"); + ImGui::TableNextColumn(); ImGui::Text("CCCCCCCCCCCC"); + } + ImGui::EndTable(); + } + ImGui::PopID(); + } + + ImGui::Spacing(); + ImGui::TextUnformatted("Advanced"); + ImGui::SameLine(); + HelpMarker("This section allows you to interact and see the effect of various sizing policies depending on whether Scroll is enabled and the contents of your columns."); + + enum ContentsType { CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText }; + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable; + static int contents_type = CT_ShowWidth; + static int column_count = 3; + + PushStyleCompact(); + ImGui::PushID("Advanced"); + ImGui::PushItemWidth(TEXT_BASE_WIDTH * 30); + EditTableSizingFlags(&flags); + ImGui::Combo("Contents", &contents_type, "Show width\0Short Text\0Long Text\0Button\0Fill Button\0InputText\0"); + if (contents_type == CT_FillButton) + { + ImGui::SameLine(); + HelpMarker("Be mindful that using right-alignment (e.g. size.x = -FLT_MIN) creates a feedback loop where contents width can feed into auto-column width can feed into contents width."); + } + ImGui::DragInt("Columns", &column_count, 0.1f, 1, 64, "%d", ImGuiSliderFlags_AlwaysClamp); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_PreciseWidths", &flags, ImGuiTableFlags_PreciseWidths); + ImGui::SameLine(); HelpMarker("Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth."); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY); + ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", &flags, ImGuiTableFlags_NoClip); + ImGui::PopItemWidth(); + ImGui::PopID(); + PopStyleCompact(); + + if (ImGui::BeginTable("table2", column_count, flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 7))) + { + for (int cell = 0; cell < 10 * column_count; cell++) + { + ImGui::TableNextColumn(); + int column = ImGui::TableGetColumnIndex(); + int row = ImGui::TableGetRowIndex(); + + ImGui::PushID(cell); + char label[32]; + static char text_buf[32] = ""; + sprintf(label, "Hello %d,%d", column, row); + switch (contents_type) + { + case CT_ShortText: ImGui::TextUnformatted(label); break; + case CT_LongText: ImGui::Text("Some %s text %d,%d\nOver two lines..", column == 0 ? "long" : "longeeer", column, row); break; + case CT_ShowWidth: ImGui::Text("W: %.1f", ImGui::GetContentRegionAvail().x); break; + case CT_Button: ImGui::Button(label); break; + case CT_FillButton: ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); break; + case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText("##", text_buf, IM_ARRAYSIZE(text_buf)); break; + } + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Vertical scrolling, with clipping"); + if (ImGui::TreeNode("Vertical scrolling, with clipping")) + { + HelpMarker("Here we activate ScrollY, which will create a child window container to allow hosting scrollable contents.\n\nWe also demonstrate using ImGuiListClipper to virtualize the submission of many items."); + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY); + PopStyleCompact(); + + // When using ScrollX or ScrollY we need to specify a size for our table container! + // Otherwise by default the table will fit all available space, like a BeginChild() call. + ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 8); + if (ImGui::BeginTable("table_scrolly", 3, flags, outer_size)) + { + ImGui::TableSetupScrollFreeze(0, 1); // Make top row always visible + ImGui::TableSetupColumn("One", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Two", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Three", ImGuiTableColumnFlags_None); + ImGui::TableHeadersRow(); + + // Demonstrate using clipper for large vertical lists + ImGuiListClipper clipper; + clipper.Begin(1000); + while (clipper.Step()) + { + for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", column, row); + } + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Horizontal scrolling"); + if (ImGui::TreeNode("Horizontal scrolling")) + { + HelpMarker( + "When ScrollX is enabled, the default sizing policy becomes ImGuiTableFlags_SizingFixedFit, " + "as automatically stretching columns doesn't make much sense with horizontal scrolling.\n\n" + "Also note that as of the current version, you will almost always want to enable ScrollY along with ScrollX," + "because the container window won't automatically extend vertically to fix contents (this may be improved in future versions)."); + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + static int freeze_cols = 1; + static int freeze_rows = 1; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + PopStyleCompact(); + + // When using ScrollX or ScrollY we need to specify a size for our table container! + // Otherwise by default the table will fit all available space, like a BeginChild() call. + ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 8); + if (ImGui::BeginTable("table_scrollx", 7, flags, outer_size)) + { + ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows); + ImGui::TableSetupColumn("Line #", ImGuiTableColumnFlags_NoHide); // Make the first column not hideable to match our use of TableSetupScrollFreeze() + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableSetupColumn("Four"); + ImGui::TableSetupColumn("Five"); + ImGui::TableSetupColumn("Six"); + ImGui::TableHeadersRow(); + for (int row = 0; row < 20; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 7; column++) + { + // Both TableNextColumn() and TableSetColumnIndex() return true when a column is visible or performing width measurement. + // Because here we know that: + // - A) all our columns are contributing the same to row height + // - B) column 0 is always visible, + // We only always submit this one column and can skip others. + // More advanced per-column clipping behaviors may benefit from polling the status flags via TableGetColumnFlags(). + if (!ImGui::TableSetColumnIndex(column) && column > 0) + continue; + if (column == 0) + ImGui::Text("Line %d", row); + else + ImGui::Text("Hello world %d,%d", column, row); + } + } + ImGui::EndTable(); + } + + ImGui::Spacing(); + ImGui::TextUnformatted("Stretch + ScrollX"); + ImGui::SameLine(); + HelpMarker( + "Showcase using Stretch columns + ScrollX together: " + "this is rather unusual and only makes sense when specifying an 'inner_width' for the table!\n" + "Without an explicit value, inner_width is == outer_size.x and therefore using Stretch columns + ScrollX together doesn't make sense."); + static ImGuiTableFlags flags2 = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody; + static float inner_width = 1000.0f; + PushStyleCompact(); + ImGui::PushID("flags3"); + ImGui::PushItemWidth(TEXT_BASE_WIDTH * 30); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags2, ImGuiTableFlags_ScrollX); + ImGui::DragFloat("inner_width", &inner_width, 1.0f, 0.0f, FLT_MAX, "%.1f"); + ImGui::PopItemWidth(); + ImGui::PopID(); + PopStyleCompact(); + if (ImGui::BeginTable("table2", 7, flags2, outer_size, inner_width)) + { + for (int cell = 0; cell < 20 * 7; cell++) + { + ImGui::TableNextColumn(); + ImGui::Text("Hello world %d,%d", ImGui::TableGetColumnIndex(), ImGui::TableGetRowIndex()); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Columns flags"); + if (ImGui::TreeNode("Columns flags")) + { + // Create a first table just to show all the options/flags we want to make visible in our example! + const int column_count = 3; + const char* column_names[column_count] = { "One", "Two", "Three" }; + static ImGuiTableColumnFlags column_flags[column_count] = { ImGuiTableColumnFlags_DefaultSort, ImGuiTableColumnFlags_None, ImGuiTableColumnFlags_DefaultHide }; + static ImGuiTableColumnFlags column_flags_out[column_count] = { 0, 0, 0 }; // Output from TableGetColumnFlags() + + if (ImGui::BeginTable("table_columns_flags_checkboxes", column_count, ImGuiTableFlags_None)) + { + PushStyleCompact(); + for (int column = 0; column < column_count; column++) + { + ImGui::TableNextColumn(); + ImGui::PushID(column); + ImGui::AlignTextToFramePadding(); // FIXME-TABLE: Workaround for wrong text baseline propagation across columns + ImGui::Text("'%s'", column_names[column]); + ImGui::Spacing(); + ImGui::Text("Input flags:"); + EditTableColumnsFlags(&column_flags[column]); + ImGui::Spacing(); + ImGui::Text("Output flags:"); + ImGui::BeginDisabled(); + ShowTableColumnsStatusFlags(column_flags_out[column]); + ImGui::EndDisabled(); + ImGui::PopID(); + } + PopStyleCompact(); + ImGui::EndTable(); + } + + // Create the real table we care about for the example! + // We use a scrolling table to be able to showcase the difference between the _IsEnabled and _IsVisible flags above, otherwise in + // a non-scrolling table columns are always visible (unless using ImGuiTableFlags_NoKeepColumnsVisible + resizing the parent window down) + const ImGuiTableFlags flags + = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY + | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV + | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable; + ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 9); + if (ImGui::BeginTable("table_columns_flags", column_count, flags, outer_size)) + { + for (int column = 0; column < column_count; column++) + ImGui::TableSetupColumn(column_names[column], column_flags[column]); + ImGui::TableHeadersRow(); + for (int column = 0; column < column_count; column++) + column_flags_out[column] = ImGui::TableGetColumnFlags(column); + float indent_step = (float)((int)TEXT_BASE_WIDTH / 2); + for (int row = 0; row < 8; row++) + { + ImGui::Indent(indent_step); // Add some indentation to demonstrate usage of per-column IndentEnable/IndentDisable flags. + ImGui::TableNextRow(); + for (int column = 0; column < column_count; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%s %s", (column == 0) ? "Indented" : "Hello", ImGui::TableGetColumnName(column)); + } + } + ImGui::Unindent(indent_step * 8.0f); + + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Columns widths"); + if (ImGui::TreeNode("Columns widths")) + { + HelpMarker("Using TableSetupColumn() to setup default width."); + + static ImGuiTableFlags flags1 = ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBodyUntilResize; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags1, ImGuiTableFlags_NoBordersInBodyUntilResize); + PopStyleCompact(); + if (ImGui::BeginTable("table1", 3, flags1)) + { + // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. + ImGui::TableSetupColumn("one", ImGuiTableColumnFlags_WidthFixed, 100.0f); // Default to 100.0f + ImGui::TableSetupColumn("two", ImGuiTableColumnFlags_WidthFixed, 200.0f); // Default to 200.0f + ImGui::TableSetupColumn("three", ImGuiTableColumnFlags_WidthFixed); // Default to auto + ImGui::TableHeadersRow(); + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + if (row == 0) + ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x); + else + ImGui::Text("Hello %d,%d", column, row); + } + } + ImGui::EndTable(); + } + + HelpMarker("Using TableSetupColumn() to setup explicit width.\n\nUnless _NoKeepColumnsVisible is set, fixed columns with set width may still be shrunk down if there's not enough space in the host."); + + static ImGuiTableFlags flags2 = ImGuiTableFlags_None; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags2, ImGuiTableFlags_NoKeepColumnsVisible); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags2, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags2, ImGuiTableFlags_BordersOuterV); + PopStyleCompact(); + if (ImGui::BeginTable("table2", 4, flags2)) + { + // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 100.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 30.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f); + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 4; column++) + { + ImGui::TableSetColumnIndex(column); + if (row == 0) + ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x); + else + ImGui::Text("Hello %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Nested tables"); + if (ImGui::TreeNode("Nested tables")) + { + HelpMarker("This demonstrate embedding a table into another table cell."); + + if (ImGui::BeginTable("table_nested1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + { + ImGui::TableSetupColumn("A0"); + ImGui::TableSetupColumn("A1"); + ImGui::TableHeadersRow(); + + ImGui::TableNextColumn(); + ImGui::Text("A0 Row 0"); + { + float rows_height = TEXT_BASE_HEIGHT * 2; + if (ImGui::BeginTable("table_nested2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + { + ImGui::TableSetupColumn("B0"); + ImGui::TableSetupColumn("B1"); + ImGui::TableHeadersRow(); + + ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height); + ImGui::TableNextColumn(); + ImGui::Text("B0 Row 0"); + ImGui::TableNextColumn(); + ImGui::Text("B1 Row 0"); + ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height); + ImGui::TableNextColumn(); + ImGui::Text("B0 Row 1"); + ImGui::TableNextColumn(); + ImGui::Text("B1 Row 1"); + + ImGui::EndTable(); + } + } + ImGui::TableNextColumn(); ImGui::Text("A1 Row 0"); + ImGui::TableNextColumn(); ImGui::Text("A0 Row 1"); + ImGui::TableNextColumn(); ImGui::Text("A1 Row 1"); + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Row height"); + if (ImGui::TreeNode("Row height")) + { + HelpMarker("You can pass a 'min_row_height' to TableNextRow().\n\nRows are padded with 'style.CellPadding.y' on top and bottom, so effectively the minimum row height will always be >= 'style.CellPadding.y * 2.0f'.\n\nWe cannot honor a _maximum_ row height as that would requires a unique clipping rectangle per row."); + if (ImGui::BeginTable("table_row_height", 1, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersInnerV)) + { + for (int row = 0; row < 10; row++) + { + float min_row_height = (float)(int)(TEXT_BASE_HEIGHT * 0.30f * row); + ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height); + ImGui::TableNextColumn(); + ImGui::Text("min_row_height = %.2f", min_row_height); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Outer size"); + if (ImGui::TreeNode("Outer size")) + { + // Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY + // Important to that note how the two flags have slightly different behaviors! + ImGui::Text("Using NoHostExtendX and NoHostExtendY:"); + PushStyleCompact(); + static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_ContextMenuInBody | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoHostExtendX; + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX); + ImGui::SameLine(); HelpMarker("Make outer width auto-fit to columns, overriding outer_size.x value.\n\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", &flags, ImGuiTableFlags_NoHostExtendY); + ImGui::SameLine(); HelpMarker("Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\n\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible."); + PopStyleCompact(); + + ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 5.5f); + if (ImGui::BeginTable("table1", 3, flags, outer_size)) + { + for (int row = 0; row < 10; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableNextColumn(); + ImGui::Text("Cell %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::SameLine(); + ImGui::Text("Hello!"); + + ImGui::Spacing(); + + ImGui::Text("Using explicit size:"); + if (ImGui::BeginTable("table2", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f))) + { + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableNextColumn(); + ImGui::Text("Cell %d,%d", column, row); + } + } + ImGui::EndTable(); + } + ImGui::SameLine(); + if (ImGui::BeginTable("table3", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f))) + { + for (int row = 0; row < 3; row++) + { + ImGui::TableNextRow(0, TEXT_BASE_HEIGHT * 1.5f); + for (int column = 0; column < 3; column++) + { + ImGui::TableNextColumn(); + ImGui::Text("Cell %d,%d", column, row); + } + } + ImGui::EndTable(); + } + + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Background color"); + if (ImGui::TreeNode("Background color")) + { + static ImGuiTableFlags flags = ImGuiTableFlags_RowBg; + static int row_bg_type = 1; + static int row_bg_target = 1; + static int cell_bg_type = 1; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags, ImGuiTableFlags_Borders); + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg); + ImGui::SameLine(); HelpMarker("ImGuiTableFlags_RowBg automatically sets RowBg0 to alternative colors pulled from the Style."); + ImGui::Combo("row bg type", (int*)&row_bg_type, "None\0Red\0Gradient\0"); + ImGui::Combo("row bg target", (int*)&row_bg_target, "RowBg0\0RowBg1\0"); ImGui::SameLine(); HelpMarker("Target RowBg0 to override the alternating odd/even colors,\nTarget RowBg1 to blend with them."); + ImGui::Combo("cell bg type", (int*)&cell_bg_type, "None\0Blue\0"); ImGui::SameLine(); HelpMarker("We are colorizing cells to B1->C2 here."); + IM_ASSERT(row_bg_type >= 0 && row_bg_type <= 2); + IM_ASSERT(row_bg_target >= 0 && row_bg_target <= 1); + IM_ASSERT(cell_bg_type >= 0 && cell_bg_type <= 1); + PopStyleCompact(); + + if (ImGui::BeginTable("table1", 5, flags)) + { + for (int row = 0; row < 6; row++) + { + ImGui::TableNextRow(); + + // Demonstrate setting a row background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBgX, ...)' + // We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag. + if (row_bg_type != 0) + { + ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.65f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.65f)); // Flat or Gradient? + ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0 + row_bg_target, row_bg_color); + } + + // Fill cells + for (int column = 0; column < 5; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%c%c", 'A' + row, '0' + column); + + // Change background of Cells B1->C2 + // Demonstrate setting a cell background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ...)' + // (the CellBg color will be blended over the RowBg and ColumnBg colors) + // We can also pass a column number as a third parameter to TableSetBgColor() and do this outside the column loop. + if (row >= 1 && row <= 2 && column >= 1 && column <= 2 && cell_bg_type == 1) + { + ImU32 cell_bg_color = ImGui::GetColorU32(ImVec4(0.3f, 0.3f, 0.7f, 0.65f)); + ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color); + } + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Tree view"); + if (ImGui::TreeNode("Tree view")) + { + static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody; + + if (ImGui::BeginTable("3ways", 3, flags)) + { + // The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide); + ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f); + ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 18.0f); + ImGui::TableHeadersRow(); + + // Simple storage to output a dummy file-system. + struct MyTreeNode + { + const char* Name; + const char* Type; + int Size; + int ChildIdx; + int ChildCount; + static void DisplayNode(const MyTreeNode* node, const MyTreeNode* all_nodes) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + const bool is_folder = (node->ChildCount > 0); + if (is_folder) + { + bool open = ImGui::TreeNodeEx(node->Name, ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::TableNextColumn(); + ImGui::TextDisabled("--"); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(node->Type); + if (open) + { + for (int child_n = 0; child_n < node->ChildCount; child_n++) + DisplayNode(&all_nodes[node->ChildIdx + child_n], all_nodes); + ImGui::TreePop(); + } + } + else + { + ImGui::TreeNodeEx(node->Name, ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::TableNextColumn(); + ImGui::Text("%d", node->Size); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(node->Type); + } + } + }; + static const MyTreeNode nodes[] = + { + { "Root", "Folder", -1, 1, 3 }, // 0 + { "Music", "Folder", -1, 4, 2 }, // 1 + { "Textures", "Folder", -1, 6, 3 }, // 2 + { "desktop.ini", "System file", 1024, -1,-1 }, // 3 + { "File1_a.wav", "Audio file", 123000, -1,-1 }, // 4 + { "File1_b.wav", "Audio file", 456000, -1,-1 }, // 5 + { "Image001.png", "Image file", 203128, -1,-1 }, // 6 + { "Copy of Image001.png", "Image file", 203256, -1,-1 }, // 7 + { "Copy of Image001 (Final2).png","Image file", 203512, -1,-1 }, // 8 + }; + + MyTreeNode::DisplayNode(&nodes[0], nodes); + + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Item width"); + if (ImGui::TreeNode("Item width")) + { + HelpMarker( + "Showcase using PushItemWidth() and how it is preserved on a per-column basis.\n\n" + "Note that on auto-resizing non-resizable fixed columns, querying the content width for e.g. right-alignment doesn't make sense."); + if (ImGui::BeginTable("table_item_width", 3, ImGuiTableFlags_Borders)) + { + ImGui::TableSetupColumn("small"); + ImGui::TableSetupColumn("half"); + ImGui::TableSetupColumn("right-align"); + ImGui::TableHeadersRow(); + + for (int row = 0; row < 3; row++) + { + ImGui::TableNextRow(); + if (row == 0) + { + // Setup ItemWidth once (instead of setting up every time, which is also possible but less efficient) + ImGui::TableSetColumnIndex(0); + ImGui::PushItemWidth(TEXT_BASE_WIDTH * 3.0f); // Small + ImGui::TableSetColumnIndex(1); + ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f); + ImGui::TableSetColumnIndex(2); + ImGui::PushItemWidth(-FLT_MIN); // Right-aligned + } + + // Draw our contents + static float dummy_f = 0.0f; + ImGui::PushID(row); + ImGui::TableSetColumnIndex(0); + ImGui::SliderFloat("float0", &dummy_f, 0.0f, 1.0f); + ImGui::TableSetColumnIndex(1); + ImGui::SliderFloat("float1", &dummy_f, 0.0f, 1.0f); + ImGui::TableSetColumnIndex(2); + ImGui::SliderFloat("float2", &dummy_f, 0.0f, 1.0f); + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + // Demonstrate using TableHeader() calls instead of TableHeadersRow() + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Custom headers"); + if (ImGui::TreeNode("Custom headers")) + { + const int COLUMNS_COUNT = 3; + if (ImGui::BeginTable("table_custom_headers", COLUMNS_COUNT, ImGuiTableFlags_Borders | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + { + ImGui::TableSetupColumn("Apricot"); + ImGui::TableSetupColumn("Banana"); + ImGui::TableSetupColumn("Cherry"); + + // Dummy entire-column selection storage + // FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox. + static bool column_selected[3] = {}; + + // Instead of calling TableHeadersRow() we'll submit custom headers ourselves + ImGui::TableNextRow(ImGuiTableRowFlags_Headers); + for (int column = 0; column < COLUMNS_COUNT; column++) + { + ImGui::TableSetColumnIndex(column); + const char* column_name = ImGui::TableGetColumnName(column); // Retrieve name passed to TableSetupColumn() + ImGui::PushID(column); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::Checkbox("##checkall", &column_selected[column]); + ImGui::PopStyleVar(); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::TableHeader(column_name); + ImGui::PopID(); + } + + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + char buf[32]; + sprintf(buf, "Cell %d,%d", column, row); + ImGui::TableSetColumnIndex(column); + ImGui::Selectable(buf, column_selected[column]); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + // Demonstrate creating custom context menus inside columns, while playing it nice with context menus provided by TableHeadersRow()/TableHeader() + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Context menus"); + if (ImGui::TreeNode("Context menus")) + { + HelpMarker("By default, right-clicking over a TableHeadersRow()/TableHeader() line will open the default context-menu.\nUsing ImGuiTableFlags_ContextMenuInBody we also allow right-clicking over columns body."); + static ImGuiTableFlags flags1 = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_ContextMenuInBody; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", &flags1, ImGuiTableFlags_ContextMenuInBody); + PopStyleCompact(); + + // Context Menus: first example + // [1.1] Right-click on the TableHeadersRow() line to open the default table context menu. + // [1.2] Right-click in columns also open the default table context menu (if ImGuiTableFlags_ContextMenuInBody is set) + const int COLUMNS_COUNT = 3; + if (ImGui::BeginTable("table_context_menu", COLUMNS_COUNT, flags1)) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + + // [1.1]] Right-click on the TableHeadersRow() line to open the default table context menu. + ImGui::TableHeadersRow(); + + // Submit dummy contents + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < COLUMNS_COUNT; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Cell %d,%d", column, row); + } + } + ImGui::EndTable(); + } + + // Context Menus: second example + // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu. + // [2.2] Right-click on the ".." to open a custom popup + // [2.3] Right-click in columns to open another custom popup + HelpMarker("Demonstrate mixing table context menu (over header), item context button (over button) and custom per-colum context menu (over column body)."); + ImGuiTableFlags flags2 = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders; + if (ImGui::BeginTable("table_context_menu_2", COLUMNS_COUNT, flags2)) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + + // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu. + ImGui::TableHeadersRow(); + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < COLUMNS_COUNT; column++) + { + // Submit dummy contents + ImGui::TableSetColumnIndex(column); + ImGui::Text("Cell %d,%d", column, row); + ImGui::SameLine(); + + // [2.2] Right-click on the ".." to open a custom popup + ImGui::PushID(row * COLUMNS_COUNT + column); + ImGui::SmallButton(".."); + if (ImGui::BeginPopupContextItem()) + { + ImGui::Text("This is the popup for Button(\"..\") in Cell %d,%d", column, row); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::PopID(); + } + } + + // [2.3] Right-click anywhere in columns to open another custom popup + // (instead of testing for !IsAnyItemHovered() we could also call OpenPopup() with ImGuiPopupFlags_NoOpenOverExistingPopup + // to manage popup priority as the popups triggers, here "are we hovering a column" are overlapping) + int hovered_column = -1; + for (int column = 0; column < COLUMNS_COUNT + 1; column++) + { + ImGui::PushID(column); + if (ImGui::TableGetColumnFlags(column) & ImGuiTableColumnFlags_IsHovered) + hovered_column = column; + if (hovered_column == column && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(1)) + ImGui::OpenPopup("MyPopup"); + if (ImGui::BeginPopup("MyPopup")) + { + if (column == COLUMNS_COUNT) + ImGui::Text("This is a custom popup for unused space after the last column."); + else + ImGui::Text("This is a custom popup for Column %d", column); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::PopID(); + } + + ImGui::EndTable(); + ImGui::Text("Hovered column: %d", hovered_column); + } + ImGui::TreePop(); + } + + // Demonstrate creating multiple tables with the same ID + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Synced instances"); + if (ImGui::TreeNode("Synced instances")) + { + HelpMarker("Multiple tables with the same identifier will share their settings, width, visibility, order etc."); + for (int n = 0; n < 3; n++) + { + char buf[32]; + sprintf(buf, "Synced Table %d", n); + bool open = ImGui::CollapsingHeader(buf, ImGuiTreeNodeFlags_DefaultOpen); + if (open && ImGui::BeginTable("Table", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoSavedSettings)) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + for (int cell = 0; cell < 9; cell++) + { + ImGui::TableNextColumn(); + ImGui::Text("this cell %d", cell); + } + ImGui::EndTable(); + } + } + ImGui::TreePop(); + } + + // Demonstrate using Sorting facilities + // This is a simplified version of the "Advanced" example, where we mostly focus on the code necessary to handle sorting. + // Note that the "Advanced" example also showcase manually triggering a sort (e.g. if item quantities have been modified) + static const char* template_items_names[] = + { + "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango", + "Kiwi", "Orange", "Pineapple", "Blueberry", "Plum", "Coconut", "Pear", "Apricot" + }; + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Sorting"); + if (ImGui::TreeNode("Sorting")) + { + // Create item list + static ImVector items; + if (items.Size == 0) + { + items.resize(50, MyItem()); + for (int n = 0; n < items.Size; n++) + { + const int template_n = n % IM_ARRAYSIZE(template_items_names); + MyItem& item = items[n]; + item.ID = n; + item.Name = template_items_names[template_n]; + item.Quantity = (n * n - n) % 20; // Assign default quantities + } + } + + // Options + static ImGuiTableFlags flags = + ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti + | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_NoBordersInBody + | ImGuiTableFlags_ScrollY; + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_SortMulti", &flags, ImGuiTableFlags_SortMulti); + ImGui::SameLine(); HelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1)."); + ImGui::CheckboxFlags("ImGuiTableFlags_SortTristate", &flags, ImGuiTableFlags_SortTristate); + ImGui::SameLine(); HelpMarker("When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0)."); + PopStyleCompact(); + + if (ImGui::BeginTable("table_sorting", 4, flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 15), 0.0f)) + { + // Declare columns + // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! + // Demonstrate using a mixture of flags among available sort-related flags: + // - ImGuiTableColumnFlags_DefaultSort + // - ImGuiTableColumnFlags_NoSort / ImGuiTableColumnFlags_NoSortAscending / ImGuiTableColumnFlags_NoSortDescending + // - ImGuiTableColumnFlags_PreferSortAscending / ImGuiTableColumnFlags_PreferSortDescending + ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_ID); + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Name); + ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Action); + ImGui::TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, 0.0f, MyItemColumnID_Quantity); + ImGui::TableSetupScrollFreeze(0, 1); // Make row always visible + ImGui::TableHeadersRow(); + + // Sort our data if sort specs have been changed! + if (ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs()) + if (sorts_specs->SpecsDirty) + { + MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function. + if (items.Size > 1) + qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs); + MyItem::s_current_sort_specs = NULL; + sorts_specs->SpecsDirty = false; + } + + // Demonstrate using clipper for large vertical lists + ImGuiListClipper clipper; + clipper.Begin(items.Size); + while (clipper.Step()) + for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++) + { + // Display a data item + MyItem* item = &items[row_n]; + ImGui::PushID(item->ID); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("%04d", item->ID); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(item->Name); + ImGui::TableNextColumn(); + ImGui::SmallButton("None"); + ImGui::TableNextColumn(); + ImGui::Text("%d", item->Quantity); + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + // In this example we'll expose most table flags and settings. + // For specific flags and settings refer to the corresponding section for more detailed explanation. + // This section is mostly useful to experiment with combining certain flags or settings with each others. + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // [DEBUG] + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + IMGUI_DEMO_MARKER("Tables/Advanced"); + if (ImGui::TreeNode("Advanced")) + { + static ImGuiTableFlags flags = + ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable + | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti + | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBody + | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY + | ImGuiTableFlags_SizingFixedFit; + + enum ContentsType { CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow }; + static int contents_type = CT_SelectableSpanRow; + const char* contents_type_names[] = { "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" }; + static int freeze_cols = 1; + static int freeze_rows = 1; + static int items_count = IM_ARRAYSIZE(template_items_names) * 2; + static ImVec2 outer_size_value = ImVec2(0.0f, TEXT_BASE_HEIGHT * 12); + static float row_min_height = 0.0f; // Auto + static float inner_width_with_scroll = 0.0f; // Auto-extend + static bool outer_size_enabled = true; + static bool show_headers = true; + static bool show_wrapped_text = false; + //static ImGuiTextFilter filter; + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // FIXME-TABLE: Enabling this results in initial clipped first pass on table which tend to affects column sizing + if (ImGui::TreeNode("Options")) + { + // Make the UI compact because there are so many fields + PushStyleCompact(); + ImGui::PushItemWidth(TEXT_BASE_WIDTH * 28.0f); + + if (ImGui::TreeNodeEx("Features:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", &flags, ImGuiTableFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", &flags, ImGuiTableFlags_Hideable); + ImGui::CheckboxFlags("ImGuiTableFlags_Sortable", &flags, ImGuiTableFlags_Sortable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoSavedSettings", &flags, ImGuiTableFlags_NoSavedSettings); + ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", &flags, ImGuiTableFlags_ContextMenuInBody); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Decorations:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags, ImGuiTableFlags_BordersH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", &flags, ImGuiTableFlags_BordersOuterH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", &flags, ImGuiTableFlags_BordersInnerH); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appears in Headers"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)"); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Sizing:", ImGuiTreeNodeFlags_DefaultOpen)) + { + EditTableSizingFlags(&flags); + ImGui::SameLine(); HelpMarker("In the Advanced demo we override the policy of each column so those table-wide settings have less effect that typical."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX); + ImGui::SameLine(); HelpMarker("Make outer width auto-fit to columns, overriding outer_size.x value.\n\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", &flags, ImGuiTableFlags_NoHostExtendY); + ImGui::SameLine(); HelpMarker("Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\n\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags, ImGuiTableFlags_NoKeepColumnsVisible); + ImGui::SameLine(); HelpMarker("Only available if ScrollX is disabled."); + ImGui::CheckboxFlags("ImGuiTableFlags_PreciseWidths", &flags, ImGuiTableFlags_PreciseWidths); + ImGui::SameLine(); HelpMarker("Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", &flags, ImGuiTableFlags_NoClip); + ImGui::SameLine(); HelpMarker("Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options."); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Padding:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags, ImGuiTableFlags_PadOuterX); + ImGui::CheckboxFlags("ImGuiTableFlags_NoPadOuterX", &flags, ImGuiTableFlags_NoPadOuterX); + ImGui::CheckboxFlags("ImGuiTableFlags_NoPadInnerX", &flags, ImGuiTableFlags_NoPadInnerX); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Scrolling:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX); + ImGui::SameLine(); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY); + ImGui::SameLine(); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Sorting:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_SortMulti", &flags, ImGuiTableFlags_SortMulti); + ImGui::SameLine(); HelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1)."); + ImGui::CheckboxFlags("ImGuiTableFlags_SortTristate", &flags, ImGuiTableFlags_SortTristate); + ImGui::SameLine(); HelpMarker("When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0)."); + ImGui::TreePop(); + } + + if (ImGui::TreeNodeEx("Other:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::Checkbox("show_headers", &show_headers); + ImGui::Checkbox("show_wrapped_text", &show_wrapped_text); + + ImGui::DragFloat2("##OuterSize", &outer_size_value.x); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Checkbox("outer_size", &outer_size_enabled); + ImGui::SameLine(); + HelpMarker("If scrolling is disabled (ScrollX and ScrollY not set):\n" + "- The table is output directly in the parent window.\n" + "- OuterSize.x < 0.0f will right-align the table.\n" + "- OuterSize.x = 0.0f will narrow fit the table unless there are any Stretch column.\n" + "- OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendY is set)."); + + // From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling. + // To facilitate toying with this demo we will actually pass 0.0f to the BeginTable() when ScrollX is disabled. + ImGui::DragFloat("inner_width (when ScrollX active)", &inner_width_with_scroll, 1.0f, 0.0f, FLT_MAX); + + ImGui::DragFloat("row_min_height", &row_min_height, 1.0f, 0.0f, FLT_MAX); + ImGui::SameLine(); HelpMarker("Specify height of the Selectable item."); + + ImGui::DragInt("items_count", &items_count, 0.1f, 0, 9999); + ImGui::Combo("items_type (first column)", &contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names)); + //filter.Draw("filter"); + ImGui::TreePop(); + } + + ImGui::PopItemWidth(); + PopStyleCompact(); + ImGui::Spacing(); + ImGui::TreePop(); + } + + // Update item list if we changed the number of items + static ImVector items; + static ImVector selection; + static bool items_need_sort = false; + if (items.Size != items_count) + { + items.resize(items_count, MyItem()); + for (int n = 0; n < items_count; n++) + { + const int template_n = n % IM_ARRAYSIZE(template_items_names); + MyItem& item = items[n]; + item.ID = n; + item.Name = template_items_names[template_n]; + item.Quantity = (template_n == 3) ? 10 : (template_n == 4) ? 20 : 0; // Assign default quantities + } + } + + const ImDrawList* parent_draw_list = ImGui::GetWindowDrawList(); + const int parent_draw_list_draw_cmd_count = parent_draw_list->CmdBuffer.Size; + ImVec2 table_scroll_cur, table_scroll_max; // For debug display + const ImDrawList* table_draw_list = NULL; // " + + // Submit table + const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : 0.0f; + if (ImGui::BeginTable("table_advanced", 6, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use)) + { + // Declare columns + // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! + ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoHide, 0.0f, MyItemColumnID_ID); + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Name); + ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Action); + ImGui::TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending, 0.0f, MyItemColumnID_Quantity); + ImGui::TableSetupColumn("Description", (flags & ImGuiTableFlags_NoHostExtendX) ? 0 : ImGuiTableColumnFlags_WidthStretch, 0.0f, MyItemColumnID_Description); + ImGui::TableSetupColumn("Hidden", ImGuiTableColumnFlags_DefaultHide | ImGuiTableColumnFlags_NoSort); + ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows); + + // Sort our data if sort specs have been changed! + ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs(); + if (sorts_specs && sorts_specs->SpecsDirty) + items_need_sort = true; + if (sorts_specs && items_need_sort && items.Size > 1) + { + MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function. + qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs); + MyItem::s_current_sort_specs = NULL; + sorts_specs->SpecsDirty = false; + } + items_need_sort = false; + + // Take note of whether we are currently sorting based on the Quantity field, + // we will use this to trigger sorting when we know the data of this column has been modified. + const bool sorts_specs_using_quantity = (ImGui::TableGetColumnFlags(3) & ImGuiTableColumnFlags_IsSorted) != 0; + + // Show headers + if (show_headers) + ImGui::TableHeadersRow(); + + // Show data + // FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here? + ImGui::PushButtonRepeat(true); +#if 1 + // Demonstrate using clipper for large vertical lists + ImGuiListClipper clipper; + clipper.Begin(items.Size); + while (clipper.Step()) + { + for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++) +#else + // Without clipper + { + for (int row_n = 0; row_n < items.Size; row_n++) +#endif + { + MyItem* item = &items[row_n]; + //if (!filter.PassFilter(item->Name)) + // continue; + + const bool item_is_selected = selection.contains(item->ID); + ImGui::PushID(item->ID); + ImGui::TableNextRow(ImGuiTableRowFlags_None, row_min_height); + + // For the demo purpose we can select among different type of items submitted in the first column + ImGui::TableSetColumnIndex(0); + char label[32]; + sprintf(label, "%04d", item->ID); + if (contents_type == CT_Text) + ImGui::TextUnformatted(label); + else if (contents_type == CT_Button) + ImGui::Button(label); + else if (contents_type == CT_SmallButton) + ImGui::SmallButton(label); + else if (contents_type == CT_FillButton) + ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); + else if (contents_type == CT_Selectable || contents_type == CT_SelectableSpanRow) + { + ImGuiSelectableFlags selectable_flags = (contents_type == CT_SelectableSpanRow) ? ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowItemOverlap : ImGuiSelectableFlags_None; + if (ImGui::Selectable(label, item_is_selected, selectable_flags, ImVec2(0, row_min_height))) + { + if (ImGui::GetIO().KeyCtrl) + { + if (item_is_selected) + selection.find_erase_unsorted(item->ID); + else + selection.push_back(item->ID); + } + else + { + selection.clear(); + selection.push_back(item->ID); + } + } + } + + if (ImGui::TableSetColumnIndex(1)) + ImGui::TextUnformatted(item->Name); + + // Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity, + // and we are currently sorting on the column showing the Quantity. + // To avoid triggering a sort while holding the button, we only trigger it when the button has been released. + // You will probably need a more advanced system in your code if you want to automatically sort when a specific entry changes. + if (ImGui::TableSetColumnIndex(2)) + { + if (ImGui::SmallButton("Chop")) { item->Quantity += 1; } + if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; } + ImGui::SameLine(); + if (ImGui::SmallButton("Eat")) { item->Quantity -= 1; } + if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; } + } + + if (ImGui::TableSetColumnIndex(3)) + ImGui::Text("%d", item->Quantity); + + ImGui::TableSetColumnIndex(4); + if (show_wrapped_text) + ImGui::TextWrapped("Lorem ipsum dolor sit amet"); + else + ImGui::Text("Lorem ipsum dolor sit amet"); + + if (ImGui::TableSetColumnIndex(5)) + ImGui::Text("1234"); + + ImGui::PopID(); + } + } + ImGui::PopButtonRepeat(); + + // Store some info to display debug details below + table_scroll_cur = ImVec2(ImGui::GetScrollX(), ImGui::GetScrollY()); + table_scroll_max = ImVec2(ImGui::GetScrollMaxX(), ImGui::GetScrollMaxY()); + table_draw_list = ImGui::GetWindowDrawList(); + ImGui::EndTable(); + } + static bool show_debug_details = false; + ImGui::Checkbox("Debug details", &show_debug_details); + if (show_debug_details && table_draw_list) + { + ImGui::SameLine(0.0f, 0.0f); + const int table_draw_list_draw_cmd_count = table_draw_list->CmdBuffer.Size; + if (table_draw_list == parent_draw_list) + ImGui::Text(": DrawCmd: +%d (in same window)", + table_draw_list_draw_cmd_count - parent_draw_list_draw_cmd_count); + else + ImGui::Text(": DrawCmd: +%d (in child window), Scroll: (%.f/%.f) (%.f/%.f)", + table_draw_list_draw_cmd_count - 1, table_scroll_cur.x, table_scroll_max.x, table_scroll_cur.y, table_scroll_max.y); + } + ImGui::TreePop(); + } + + ImGui::PopID(); + + ShowDemoWindowColumns(); + + if (disable_indent) + ImGui::PopStyleVar(); +} + +// Demonstrate old/legacy Columns API! +// [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!] +static void ShowDemoWindowColumns() +{ + IMGUI_DEMO_MARKER("Columns (legacy API)"); + bool open = ImGui::TreeNode("Legacy Columns API"); + ImGui::SameLine(); + HelpMarker("Columns() is an old API! Prefer using the more flexible and powerful BeginTable() API!"); + if (!open) + return; + + // Basic columns + IMGUI_DEMO_MARKER("Columns (legacy API)/Basic"); + if (ImGui::TreeNode("Basic")) + { + ImGui::Text("Without border:"); + ImGui::Columns(3, "mycolumns3", false); // 3-ways, no border + ImGui::Separator(); + for (int n = 0; n < 14; n++) + { + char label[32]; + sprintf(label, "Item %d", n); + if (ImGui::Selectable(label)) {} + //if (ImGui::Button(label, ImVec2(-FLT_MIN,0.0f))) {} + ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + + ImGui::Text("With border:"); + ImGui::Columns(4, "mycolumns"); // 4-ways, with border + ImGui::Separator(); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Text("Hovered"); ImGui::NextColumn(); + ImGui::Separator(); + const char* names[3] = { "One", "Two", "Three" }; + const char* paths[3] = { "/path/one", "/path/two", "/path/three" }; + static int selected = -1; + for (int i = 0; i < 3; i++) + { + char label[32]; + sprintf(label, "%04d", i); + if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns)) + selected = i; + bool hovered = ImGui::IsItemHovered(); + ImGui::NextColumn(); + ImGui::Text(names[i]); ImGui::NextColumn(); + ImGui::Text(paths[i]); ImGui::NextColumn(); + ImGui::Text("%d", hovered); ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Columns (legacy API)/Borders"); + if (ImGui::TreeNode("Borders")) + { + // NB: Future columns API should allow automatic horizontal borders. + static bool h_borders = true; + static bool v_borders = true; + static int columns_count = 4; + const int lines_count = 3; + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::DragInt("##columns_count", &columns_count, 0.1f, 2, 10, "%d columns"); + if (columns_count < 2) + columns_count = 2; + ImGui::SameLine(); + ImGui::Checkbox("horizontal", &h_borders); + ImGui::SameLine(); + ImGui::Checkbox("vertical", &v_borders); + ImGui::Columns(columns_count, NULL, v_borders); + for (int i = 0; i < columns_count * lines_count; i++) + { + if (h_borders && ImGui::GetColumnIndex() == 0) + ImGui::Separator(); + ImGui::Text("%c%c%c", 'a' + i, 'a' + i, 'a' + i); + ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); + ImGui::Text("Avail %.2f", ImGui::GetContentRegionAvail().x); + ImGui::Text("Offset %.2f", ImGui::GetColumnOffset()); + ImGui::Text("Long text that is likely to clip"); + ImGui::Button("Button", ImVec2(-FLT_MIN, 0.0f)); + ImGui::NextColumn(); + } + ImGui::Columns(1); + if (h_borders) + ImGui::Separator(); + ImGui::TreePop(); + } + + // Create multiple items in a same cell before switching to next column + IMGUI_DEMO_MARKER("Columns (legacy API)/Mixed items"); + if (ImGui::TreeNode("Mixed items")) + { + ImGui::Columns(3, "mixed"); + ImGui::Separator(); + + ImGui::Text("Hello"); + ImGui::Button("Banana"); + ImGui::NextColumn(); + + ImGui::Text("ImGui"); + ImGui::Button("Apple"); + static float foo = 1.0f; + ImGui::InputFloat("red", &foo, 0.05f, 0, "%.3f"); + ImGui::Text("An extra line here."); + ImGui::NextColumn(); + + ImGui::Text("Sailor"); + ImGui::Button("Corniflower"); + static float bar = 1.0f; + ImGui::InputFloat("blue", &bar, 0.05f, 0, "%.3f"); + ImGui::NextColumn(); + + if (ImGui::CollapsingHeader("Category A")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category B")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category C")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + // Word wrapping + IMGUI_DEMO_MARKER("Columns (legacy API)/Word-wrapping"); + if (ImGui::TreeNode("Word-wrapping")) + { + ImGui::Columns(2, "word-wrapping"); + ImGui::Separator(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Left"); + ImGui::NextColumn(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Right"); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Columns (legacy API)/Horizontal Scrolling"); + if (ImGui::TreeNode("Horizontal Scrolling")) + { + ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f)); + ImVec2 child_size = ImVec2(0, ImGui::GetFontSize() * 20.0f); + ImGui::BeginChild("##ScrollingRegion", child_size, false, ImGuiWindowFlags_HorizontalScrollbar); + ImGui::Columns(10); + + // Also demonstrate using clipper for large vertical lists + int ITEMS_COUNT = 2000; + ImGuiListClipper clipper; + clipper.Begin(ITEMS_COUNT); + while (clipper.Step()) + { + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + for (int j = 0; j < 10; j++) + { + ImGui::Text("Line %d Column %d...", i, j); + ImGui::NextColumn(); + } + } + ImGui::Columns(1); + ImGui::EndChild(); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Columns (legacy API)/Tree"); + if (ImGui::TreeNode("Tree")) + { + ImGui::Columns(2, "tree", true); + for (int x = 0; x < 3; x++) + { + bool open1 = ImGui::TreeNode((void*)(intptr_t)x, "Node%d", x); + ImGui::NextColumn(); + ImGui::Text("Node contents"); + ImGui::NextColumn(); + if (open1) + { + for (int y = 0; y < 3; y++) + { + bool open2 = ImGui::TreeNode((void*)(intptr_t)y, "Node%d.%d", x, y); + ImGui::NextColumn(); + ImGui::Text("Node contents"); + if (open2) + { + ImGui::Text("Even more contents"); + if (ImGui::TreeNode("Tree in column")) + { + ImGui::Text("The quick brown fox jumps over the lazy dog"); + ImGui::TreePop(); + } + } + ImGui::NextColumn(); + if (open2) + ImGui::TreePop(); + } + ImGui::TreePop(); + } + } + ImGui::Columns(1); + ImGui::TreePop(); + } + + ImGui::TreePop(); +} + +namespace ImGui { extern ImGuiKeyData* GetKeyData(ImGuiKey key); } + +static void ShowDemoWindowMisc() +{ + IMGUI_DEMO_MARKER("Filtering"); + if (ImGui::CollapsingHeader("Filtering")) + { + // Helper class to easy setup a text filter. + // You may want to implement a more feature-full filtering scheme in your own application. + static ImGuiTextFilter filter; + ImGui::Text("Filter usage:\n" + " \"\" display all lines\n" + " \"xxx\" display lines containing \"xxx\"\n" + " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" + " \"-xxx\" hide lines containing \"xxx\""); + filter.Draw(); + const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; + for (int i = 0; i < IM_ARRAYSIZE(lines); i++) + if (filter.PassFilter(lines[i])) + ImGui::BulletText("%s", lines[i]); + } + + IMGUI_DEMO_MARKER("Inputs, Navigation & Focus"); + if (ImGui::CollapsingHeader("Inputs, Navigation & Focus")) + { + ImGuiIO& io = ImGui::GetIO(); + + // Display ImGuiIO output flags + IMGUI_DEMO_MARKER("Inputs, Navigation & Focus/Output"); + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode("Output")) + { + ImGui::Text("io.WantCaptureMouse: %d", io.WantCaptureMouse); + ImGui::Text("io.WantCaptureMouseUnlessPopupClose: %d", io.WantCaptureMouseUnlessPopupClose); + ImGui::Text("io.WantCaptureKeyboard: %d", io.WantCaptureKeyboard); + ImGui::Text("io.WantTextInput: %d", io.WantTextInput); + ImGui::Text("io.WantSetMousePos: %d", io.WantSetMousePos); + ImGui::Text("io.NavActive: %d, io.NavVisible: %d", io.NavActive, io.NavVisible); + ImGui::TreePop(); + } + + // Display Mouse state + IMGUI_DEMO_MARKER("Inputs, Navigation & Focus/Mouse State"); + if (ImGui::TreeNode("Mouse State")) + { + if (ImGui::IsMousePosValid()) + ImGui::Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y); + else + ImGui::Text("Mouse pos: "); + ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y); + + int count = IM_ARRAYSIZE(io.MouseDown); + ImGui::Text("Mouse down:"); for (int i = 0; i < count; i++) if (ImGui::IsMouseDown(i)) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } + ImGui::Text("Mouse clicked:"); for (int i = 0; i < count; i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d (%d)", i, ImGui::GetMouseClickedCount(i)); } + ImGui::Text("Mouse released:"); for (int i = 0; i < count; i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse wheel: %.1f", io.MouseWheel); + ImGui::Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused + ImGui::TreePop(); + } + + // Display Keyboard/Mouse state + IMGUI_DEMO_MARKER("Inputs, Navigation & Focus/Keyboard, Gamepad & Navigation State"); + if (ImGui::TreeNode("Keyboard, Gamepad & Navigation State")) + { + // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allow displaying the data for old/new backends. + // User code should never have to go through such hoops: old code may use native keycodes, new code may use ImGuiKey codes. +#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO + struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } }; + const ImGuiKey key_first = ImGuiKey_NamedKey_BEGIN; +#else + struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && ImGui::GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array + const ImGuiKey key_first = 0; + //ImGui::Text("Legacy raw:"); for (ImGuiKey key = key_first; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { ImGui::SameLine(); ImGui::Text("\"%s\" %d", ImGui::GetKeyName(key), key); } } +#endif + ImGui::Text("Keys down:"); for (ImGuiKey key = key_first; key < ImGuiKey_COUNT; key++) { if (funcs::IsLegacyNativeDupe(key)) continue; if (ImGui::IsKeyDown(key)) { ImGui::SameLine(); ImGui::Text("\"%s\" %d (%.02f secs)", ImGui::GetKeyName(key), key, ImGui::GetKeyData(key)->DownDuration); } } + ImGui::Text("Keys pressed:"); for (ImGuiKey key = key_first; key < ImGuiKey_COUNT; key++) { if (funcs::IsLegacyNativeDupe(key)) continue; if (ImGui::IsKeyPressed(key)) { ImGui::SameLine(); ImGui::Text("\"%s\" %d", ImGui::GetKeyName(key), key); } } + ImGui::Text("Keys released:"); for (ImGuiKey key = key_first; key < ImGuiKey_COUNT; key++) { if (funcs::IsLegacyNativeDupe(key)) continue; if (ImGui::IsKeyReleased(key)) { ImGui::SameLine(); ImGui::Text("\"%s\" %d", ImGui::GetKeyName(key), key); } } + ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); + ImGui::Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine(); ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public. + ImGui::Text("NavInputs down:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputs[i] > 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f (%.02f secs)", i, io.NavInputs[i], io.NavInputsDownDuration[i]); } + ImGui::Text("NavInputs pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] == 0.0f) { ImGui::SameLine(); ImGui::Text("[%d]", i); } + + // Draw an arbitrary US keyboard layout to visualize translated keys + { + const ImVec2 key_size = ImVec2(35.0f, 35.0f); + const float key_rounding = 3.0f; + const ImVec2 key_face_size = ImVec2(25.0f, 25.0f); + const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f); + const float key_face_rounding = 2.0f; + const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f); + const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f); + const float key_row_offset = 9.0f; + + ImVec2 board_min = ImGui::GetCursorScreenPos(); + ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f); + ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y); + + struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; }; + const KeyLayoutData keys_to_display[] = + { + { 0, 0, "", ImGuiKey_Tab }, { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R }, + { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F }, + { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V } + }; + + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + draw_list->PushClipRect(board_min, board_max, true); + for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++) + { + const KeyLayoutData* key_data = &keys_to_display[n]; + ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y); + ImVec2 key_max = ImVec2(key_min.x + key_size.x, key_min.y + key_size.y); + draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding); + draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding); + ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y); + ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y); + draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f); + draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding); + ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y); + draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label); + if (ImGui::IsKeyDown(key_data->Key)) + draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding); + } + draw_list->PopClipRect(); + ImGui::Dummy(ImVec2(board_max.x - board_min.x, board_max.y - board_min.y)); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Capture override")) + { + HelpMarker( + "The value of io.WantCaptureMouse and io.WantCaptureKeyboard are normally set by Dear ImGui " + "to instruct your application of how to route inputs. Typically, when a value is true, it means " + "Dear ImGui wants the corresponding inputs and we expect the underlying application to ignore them.\n\n" + "The most typical case is: when hovering a window, Dear ImGui set io.WantCaptureMouse to true, " + "and underlying application should ignore mouse inputs (in practice there are many and more subtle " + "rules leading to how those flags are set)."); + + ImGui::Text("io.WantCaptureMouse: %d", io.WantCaptureMouse); + ImGui::Text("io.WantCaptureMouseUnlessPopupClose: %d", io.WantCaptureMouseUnlessPopupClose); + ImGui::Text("io.WantCaptureKeyboard: %d", io.WantCaptureKeyboard); + + HelpMarker( + "Hovering the colored canvas will override io.WantCaptureXXX fields.\n" + "Notice how normally (when set to none), the value of io.WantCaptureKeyboard would be false when hovering and true when clicking."); + static int capture_override_mouse = -1; + static int capture_override_keyboard = -1; + const char* capture_override_desc[] = { "None", "Set to false", "Set to true" }; + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 15); + ImGui::SliderInt("SetNextFrameWantCaptureMouse()", &capture_override_mouse, -1, +1, capture_override_desc[capture_override_mouse + 1], ImGuiSliderFlags_AlwaysClamp); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 15); + ImGui::SliderInt("SetNextFrameWantCaptureKeyboard()", &capture_override_keyboard, -1, +1, capture_override_desc[capture_override_keyboard + 1], ImGuiSliderFlags_AlwaysClamp); + + ImGui::ColorButton("##panel", ImVec4(0.7f, 0.1f, 0.7f, 1.0f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoDragDrop, ImVec2(256.0f, 192.0f)); // Dummy item + if (ImGui::IsItemHovered() && capture_override_mouse != -1) + ImGui::SetNextFrameWantCaptureMouse(capture_override_mouse == 1); + if (ImGui::IsItemHovered() && capture_override_keyboard != -1) + ImGui::SetNextFrameWantCaptureKeyboard(capture_override_keyboard == 1); + + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Inputs, Navigation & Focus/Tabbing"); + if (ImGui::TreeNode("Tabbing")) + { + ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields."); + static char buf[32] = "hello"; + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); + ImGui::PushAllowKeyboardFocus(false); + ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); + ImGui::SameLine(); HelpMarker("Item won't be cycled through when using TAB or Shift+Tab."); + ImGui::PopAllowKeyboardFocus(); + ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Inputs, Navigation & Focus/Focus from code"); + if (ImGui::TreeNode("Focus from code")) + { + bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); + bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); + bool focus_3 = ImGui::Button("Focus on 3"); + int has_focus = 0; + static char buf[128] = "click on a button to set focus"; + + if (focus_1) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 1; + + if (focus_2) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 2; + + ImGui::PushAllowKeyboardFocus(false); + if (focus_3) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 3; + ImGui::SameLine(); HelpMarker("Item won't be cycled through when using TAB or Shift+Tab."); + ImGui::PopAllowKeyboardFocus(); + + if (has_focus) + ImGui::Text("Item with focus: %d", has_focus); + else + ImGui::Text("Item with focus: "); + + // Use >= 0 parameter to SetKeyboardFocusHere() to focus an upcoming item + static float f3[3] = { 0.0f, 0.0f, 0.0f }; + int focus_ahead = -1; + if (ImGui::Button("Focus on X")) { focus_ahead = 0; } ImGui::SameLine(); + if (ImGui::Button("Focus on Y")) { focus_ahead = 1; } ImGui::SameLine(); + if (ImGui::Button("Focus on Z")) { focus_ahead = 2; } + if (focus_ahead != -1) ImGui::SetKeyboardFocusHere(focus_ahead); + ImGui::SliderFloat3("Float3", &f3[0], 0.0f, 1.0f); + + ImGui::TextWrapped("NB: Cursor & selection are preserved when refocusing last used item in code."); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Inputs, Navigation & Focus/Dragging"); + if (ImGui::TreeNode("Dragging")) + { + ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget."); + for (int button = 0; button < 3; button++) + { + ImGui::Text("IsMouseDragging(%d):", button); + ImGui::Text(" w/ default threshold: %d,", ImGui::IsMouseDragging(button)); + ImGui::Text(" w/ zero threshold: %d,", ImGui::IsMouseDragging(button, 0.0f)); + ImGui::Text(" w/ large threshold: %d,", ImGui::IsMouseDragging(button, 20.0f)); + } + + ImGui::Button("Drag Me"); + if (ImGui::IsItemActive()) + ImGui::GetForegroundDrawList()->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); // Draw a line between the button and the mouse cursor + + // Drag operations gets "unlocked" when the mouse has moved past a certain threshold + // (the default threshold is stored in io.MouseDragThreshold). You can request a lower or higher + // threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta(). + ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); + ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); + ImVec2 mouse_delta = io.MouseDelta; + ImGui::Text("GetMouseDragDelta(0):"); + ImGui::Text(" w/ default threshold: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y); + ImGui::Text(" w/ zero threshold: (%.1f, %.1f)", value_raw.x, value_raw.y); + ImGui::Text("io.MouseDelta: (%.1f, %.1f)", mouse_delta.x, mouse_delta.y); + ImGui::TreePop(); + } + + IMGUI_DEMO_MARKER("Inputs, Navigation & Focus/Mouse cursors"); + if (ImGui::TreeNode("Mouse cursors")) + { + const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "NotAllowed" }; + IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT); + + ImGuiMouseCursor current = ImGui::GetMouseCursor(); + ImGui::Text("Current mouse cursor = %d: %s", current, mouse_cursors_names[current]); + ImGui::Text("Hover to see mouse cursors:"); + ImGui::SameLine(); HelpMarker( + "Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. " + "If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, " + "otherwise your backend needs to handle it."); + for (int i = 0; i < ImGuiMouseCursor_COUNT; i++) + { + char label[32]; + sprintf(label, "Mouse cursor %d: %s", i, mouse_cursors_names[i]); + ImGui::Bullet(); ImGui::Selectable(label, false); + if (ImGui::IsItemHovered()) + ImGui::SetMouseCursor(i); + } + ImGui::TreePop(); + } + } +} + +//----------------------------------------------------------------------------- +// [SECTION] About Window / ShowAboutWindow() +// Access from Dear ImGui Demo -> Tools -> About +//----------------------------------------------------------------------------- + +void ImGui::ShowAboutWindow(bool* p_open) +{ + if (!ImGui::Begin("About Dear ImGui", p_open, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::End(); + return; + } + IMGUI_DEMO_MARKER("Tools/About Dear ImGui"); + ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); + ImGui::Separator(); + ImGui::Text("By Omar Cornut and all Dear ImGui contributors."); + ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information."); + + static bool show_config_info = false; + ImGui::Checkbox("Config/Build Information", &show_config_info); + if (show_config_info) + { + ImGuiIO& io = ImGui::GetIO(); + ImGuiStyle& style = ImGui::GetStyle(); + + bool copy_to_clipboard = ImGui::Button("Copy to clipboard"); + ImVec2 child_size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18); + ImGui::BeginChildFrame(ImGui::GetID("cfg_infos"), child_size, ImGuiWindowFlags_NoMove); + if (copy_to_clipboard) + { + ImGui::LogToClipboard(); + ImGui::LogText("```\n"); // Back quotes will make text appears without formatting when pasting on GitHub + } + + ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); + ImGui::Separator(); + ImGui::Text("sizeof(size_t): %d, sizeof(ImDrawIdx): %d, sizeof(ImDrawVert): %d", (int)sizeof(size_t), (int)sizeof(ImDrawIdx), (int)sizeof(ImDrawVert)); + ImGui::Text("define: __cplusplus=%d", (int)__cplusplus); +#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_OBSOLETE_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO + ImGui::Text("define: IMGUI_DISABLE_OBSOLETE_KEYIO"); +#endif +#ifdef IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_WIN32_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_WIN32_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_FILE_FUNCTIONS + ImGui::Text("define: IMGUI_DISABLE_FILE_FUNCTIONS"); +#endif +#ifdef IMGUI_DISABLE_DEFAULT_ALLOCATORS + ImGui::Text("define: IMGUI_DISABLE_DEFAULT_ALLOCATORS"); +#endif +#ifdef IMGUI_USE_BGRA_PACKED_COLOR + ImGui::Text("define: IMGUI_USE_BGRA_PACKED_COLOR"); +#endif +#ifdef _WIN32 + ImGui::Text("define: _WIN32"); +#endif +#ifdef _WIN64 + ImGui::Text("define: _WIN64"); +#endif +#ifdef __linux__ + ImGui::Text("define: __linux__"); +#endif +#ifdef __APPLE__ + ImGui::Text("define: __APPLE__"); +#endif +#ifdef _MSC_VER + ImGui::Text("define: _MSC_VER=%d", _MSC_VER); +#endif +#ifdef _MSVC_LANG + ImGui::Text("define: _MSVC_LANG=%d", (int)_MSVC_LANG); +#endif +#ifdef __MINGW32__ + ImGui::Text("define: __MINGW32__"); +#endif +#ifdef __MINGW64__ + ImGui::Text("define: __MINGW64__"); +#endif +#ifdef __GNUC__ + ImGui::Text("define: __GNUC__=%d", (int)__GNUC__); +#endif +#ifdef __clang_version__ + ImGui::Text("define: __clang_version__=%s", __clang_version__); +#endif +#ifdef IMGUI_HAS_VIEWPORT + ImGui::Text("define: IMGUI_HAS_VIEWPORT"); +#endif +#ifdef IMGUI_HAS_DOCK + ImGui::Text("define: IMGUI_HAS_DOCK"); +#endif + ImGui::Separator(); + ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL"); + ImGui::Text("io.BackendRendererName: %s", io.BackendRendererName ? io.BackendRendererName : "NULL"); + ImGui::Text("io.ConfigFlags: 0x%08X", io.ConfigFlags); + if (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) ImGui::Text(" NavEnableKeyboard"); + if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) ImGui::Text(" NavEnableGamepad"); + if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) ImGui::Text(" NavEnableSetMousePos"); + if (io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard) ImGui::Text(" NavNoCaptureKeyboard"); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) ImGui::Text(" NoMouse"); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) ImGui::Text(" NoMouseCursorChange"); + if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) ImGui::Text(" DockingEnable"); + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ImGui::Text(" ViewportsEnable"); + if (io.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) ImGui::Text(" DpiEnableScaleViewports"); + if (io.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ImGui::Text(" DpiEnableScaleFonts"); + if (io.MouseDrawCursor) ImGui::Text("io.MouseDrawCursor"); + if (io.ConfigViewportsNoAutoMerge) ImGui::Text("io.ConfigViewportsNoAutoMerge"); + if (io.ConfigViewportsNoTaskBarIcon) ImGui::Text("io.ConfigViewportsNoTaskBarIcon"); + if (io.ConfigViewportsNoDecoration) ImGui::Text("io.ConfigViewportsNoDecoration"); + if (io.ConfigViewportsNoDefaultParent) ImGui::Text("io.ConfigViewportsNoDefaultParent"); + if (io.ConfigDockingNoSplit) ImGui::Text("io.ConfigDockingNoSplit"); + if (io.ConfigDockingWithShift) ImGui::Text("io.ConfigDockingWithShift"); + if (io.ConfigDockingAlwaysTabBar) ImGui::Text("io.ConfigDockingAlwaysTabBar"); + if (io.ConfigDockingTransparentPayload) ImGui::Text("io.ConfigDockingTransparentPayload"); + if (io.ConfigMacOSXBehaviors) ImGui::Text("io.ConfigMacOSXBehaviors"); + if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink"); + if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges"); + if (io.ConfigWindowsMoveFromTitleBarOnly) ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly"); + if (io.ConfigMemoryCompactTimer >= 0.0f) ImGui::Text("io.ConfigMemoryCompactTimer = %.1f", io.ConfigMemoryCompactTimer); + ImGui::Text("io.BackendFlags: 0x%08X", io.BackendFlags); + if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad"); + if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); + if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos"); + if (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) ImGui::Text(" PlatformHasViewports"); + if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)ImGui::Text(" HasMouseHoveredViewport"); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset"); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasViewports) ImGui::Text(" RendererHasViewports"); + ImGui::Separator(); + ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight); + ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); + ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); + ImGui::Separator(); + ImGui::Text("style.WindowPadding: %.2f,%.2f", style.WindowPadding.x, style.WindowPadding.y); + ImGui::Text("style.WindowBorderSize: %.2f", style.WindowBorderSize); + ImGui::Text("style.FramePadding: %.2f,%.2f", style.FramePadding.x, style.FramePadding.y); + ImGui::Text("style.FrameRounding: %.2f", style.FrameRounding); + ImGui::Text("style.FrameBorderSize: %.2f", style.FrameBorderSize); + ImGui::Text("style.ItemSpacing: %.2f,%.2f", style.ItemSpacing.x, style.ItemSpacing.y); + ImGui::Text("style.ItemInnerSpacing: %.2f,%.2f", style.ItemInnerSpacing.x, style.ItemInnerSpacing.y); + + if (copy_to_clipboard) + { + ImGui::LogText("\n```\n"); + ImGui::LogFinish(); + } + ImGui::EndChildFrame(); + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Style Editor / ShowStyleEditor() +//----------------------------------------------------------------------------- +// - ShowFontSelector() +// - ShowStyleSelector() +// - ShowStyleEditor() +//----------------------------------------------------------------------------- + +// Forward declare ShowFontAtlas() which isn't worth putting in public API yet +namespace ImGui { IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); } + +// Demo helper function to select among loaded fonts. +// Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one. +void ImGui::ShowFontSelector(const char* label) +{ + ImGuiIO& io = ImGui::GetIO(); + ImFont* font_current = ImGui::GetFont(); + if (ImGui::BeginCombo(label, font_current->GetDebugName())) + { + for (int n = 0; n < io.Fonts->Fonts.Size; n++) + { + ImFont* font = io.Fonts->Fonts[n]; + ImGui::PushID((void*)font); + if (ImGui::Selectable(font->GetDebugName(), font == font_current)) + io.FontDefault = font; + ImGui::PopID(); + } + ImGui::EndCombo(); + } + ImGui::SameLine(); + HelpMarker( + "- Load additional fonts with io.Fonts->AddFontFromFileTTF().\n" + "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n" + "- Read FAQ and docs/FONTS.md for more details.\n" + "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); +} + +// Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. +// Here we use the simplified Combo() api that packs items into a single literal string. +// Useful for quick combo boxes where the choices are known locally. +bool ImGui::ShowStyleSelector(const char* label) +{ + static int style_idx = -1; + if (ImGui::Combo(label, &style_idx, "Dark\0Light\0Classic\0")) + { + switch (style_idx) + { + case 0: ImGui::StyleColorsDark(); break; + case 1: ImGui::StyleColorsLight(); break; + case 2: ImGui::StyleColorsClassic(); break; + } + return true; + } + return false; +} + +void ImGui::ShowStyleEditor(ImGuiStyle* ref) +{ + IMGUI_DEMO_MARKER("Tools/Style Editor"); + // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to + // (without a reference style pointer, we will use one compared locally as a reference) + ImGuiStyle& style = ImGui::GetStyle(); + static ImGuiStyle ref_saved_style; + + // Default to using internal storage as reference + static bool init = true; + if (init && ref == NULL) + ref_saved_style = style; + init = false; + if (ref == NULL) + ref = &ref_saved_style; + + ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f); + + if (ImGui::ShowStyleSelector("Colors##Selector")) + ref_saved_style = style; + ImGui::ShowFontSelector("Fonts##Selector"); + + // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) + if (ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) + style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding + { bool border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } + ImGui::SameLine(); + { bool border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } + ImGui::SameLine(); + { bool border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } + + // Save/Revert button + if (ImGui::Button("Save Ref")) + *ref = ref_saved_style = style; + ImGui::SameLine(); + if (ImGui::Button("Revert Ref")) + style = *ref; + ImGui::SameLine(); + HelpMarker( + "Save/Revert in local non-persistent storage. Default Colors definition are not affected. " + "Use \"Export\" below to save them somewhere."); + + ImGui::Separator(); + + if (ImGui::BeginTabBar("##tabs", ImGuiTabBarFlags_None)) + { + if (ImGui::BeginTabItem("Sizes")) + { + ImGui::Text("Main"); + ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("CellPadding", (float*)&style.CellPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); + ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); + ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); + ImGui::Text("Borders"); + ImGui::SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f"); + ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); + ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); + ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); + ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); + ImGui::Text("Rounding"); + ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); + ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f"); + ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"); + ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f"); + ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); + ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f"); + ImGui::SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); + ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); + ImGui::Text("Alignment"); + ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); + int window_menu_button_position = style.WindowMenuButtonPosition + 1; + if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) + style.WindowMenuButtonPosition = window_menu_button_position - 1; + ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); + ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); + ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); + ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); + ImGui::SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content."); + ImGui::Text("Safe Area Padding"); + ImGui::SameLine(); HelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); + ImGui::SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f"); + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Colors")) + { + static int output_dest = 0; + static bool output_only_modified = true; + if (ImGui::Button("Export")) + { + if (output_dest == 0) + ImGui::LogToClipboard(); + else + ImGui::LogToTTY(); + ImGui::LogText("ImVec4* colors = ImGui::GetStyle().Colors;" IM_NEWLINE); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const ImVec4& col = style.Colors[i]; + const char* name = ImGui::GetStyleColorName(i); + if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) + ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, + name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w); + } + ImGui::LogFinish(); + } + ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); + ImGui::SameLine(); ImGui::Checkbox("Only Modified Colors", &output_only_modified); + + static ImGuiTextFilter filter; + filter.Draw("Filter colors", ImGui::GetFontSize() * 16); + + static ImGuiColorEditFlags alpha_flags = 0; + if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine(); + if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine(); + if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine(); + HelpMarker( + "In the color list:\n" + "Left-click on color square to open color picker,\n" + "Right-click to open edit options menu."); + + ImGui::BeginChild("##colors", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened); + ImGui::PushItemWidth(-160); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const char* name = ImGui::GetStyleColorName(i); + if (!filter.PassFilter(name)) + continue; + ImGui::PushID(i); + ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags); + if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0) + { + // Tips: in a real user application, you may want to merge and use an icon font into the main font, + // so instead of "Save"/"Revert" you'd use icons! + // Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient! + ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) { ref->Colors[i] = style.Colors[i]; } + ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) { style.Colors[i] = ref->Colors[i]; } + } + ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); + ImGui::TextUnformatted(name); + ImGui::PopID(); + } + ImGui::PopItemWidth(); + ImGui::EndChild(); + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Fonts")) + { + ImGuiIO& io = ImGui::GetIO(); + ImFontAtlas* atlas = io.Fonts; + HelpMarker("Read FAQ and docs/FONTS.md for details on font loading."); + ImGui::ShowFontAtlas(atlas); + + // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below. + // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds). + const float MIN_SCALE = 0.3f; + const float MAX_SCALE = 2.0f; + HelpMarker( + "Those are old settings provided for convenience.\n" + "However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, " + "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n" + "Using those settings here will give you poor quality results."); + static float window_scale = 1.0f; + ImGui::PushItemWidth(ImGui::GetFontSize() * 8); + if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window + ImGui::SetWindowFontScale(window_scale); + ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything + ImGui::PopItemWidth(); + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Rendering")) + { + ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); + ImGui::SameLine(); + HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); + + ImGui::Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); + ImGui::SameLine(); + HelpMarker("Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering)."); + + ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); + ImGui::PushItemWidth(ImGui::GetFontSize() * 8); + ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); + if (style.CurveTessellationTol < 0.10f) style.CurveTessellationTol = 0.10f; + + // When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles. + ImGui::DragFloat("Circle Tessellation Max Error", &style.CircleTessellationMaxError , 0.005f, 0.10f, 5.0f, "%.2f", ImGuiSliderFlags_AlwaysClamp); + if (ImGui::IsItemActive()) + { + ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); + ImGui::BeginTooltip(); + ImGui::TextUnformatted("(R = radius, N = number of segments)"); + ImGui::Spacing(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + const float min_widget_width = ImGui::CalcTextSize("N: MMM\nR: MMM").x; + for (int n = 0; n < 8; n++) + { + const float RAD_MIN = 5.0f; + const float RAD_MAX = 70.0f; + const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (8.0f - 1.0f); + + ImGui::BeginGroup(); + + ImGui::Text("R: %.f\nN: %d", rad, draw_list->_CalcCircleAutoSegmentCount(rad)); + + const float canvas_width = IM_MAX(min_widget_width, rad * 2.0f); + const float offset_x = floorf(canvas_width * 0.5f); + const float offset_y = floorf(RAD_MAX); + + const ImVec2 p1 = ImGui::GetCursorScreenPos(); + draw_list->AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, ImGui::GetColorU32(ImGuiCol_Text)); + ImGui::Dummy(ImVec2(canvas_width, RAD_MAX * 2)); + + /* + const ImVec2 p2 = ImGui::GetCursorScreenPos(); + draw_list->AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, ImGui::GetColorU32(ImGuiCol_Text)); + ImGui::Dummy(ImVec2(canvas_width, RAD_MAX * 2)); + */ + + ImGui::EndGroup(); + ImGui::SameLine(); + } + ImGui::EndTooltip(); + } + ImGui::SameLine(); + HelpMarker("When drawing circle primitives with \"num_segments == 0\" tesselation will be calculated automatically."); + + ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. + ImGui::DragFloat("Disabled Alpha", &style.DisabledAlpha, 0.005f, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha)."); + ImGui::PopItemWidth(); + + ImGui::EndTabItem(); + } + + ImGui::EndTabBar(); + } + + ImGui::PopItemWidth(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() +//----------------------------------------------------------------------------- +// - ShowExampleAppMainMenuBar() +// - ShowExampleMenuFile() +//----------------------------------------------------------------------------- + +// Demonstrate creating a "main" fullscreen menu bar and populating it. +// Note the difference between BeginMainMenuBar() and BeginMenuBar(): +// - BeginMenuBar() = menu-bar inside current window (which needs the ImGuiWindowFlags_MenuBar flag!) +// - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it. +static void ShowExampleAppMainMenuBar() +{ + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Edit")) + { + if (ImGui::MenuItem("Undo", "CTRL+Z")) {} + if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item + ImGui::Separator(); + if (ImGui::MenuItem("Cut", "CTRL+X")) {} + if (ImGui::MenuItem("Copy", "CTRL+C")) {} + if (ImGui::MenuItem("Paste", "CTRL+V")) {} + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } +} + +// Note that shortcuts are currently provided for display only +// (future version will add explicit flags to BeginMenu() to request processing shortcuts) +static void ShowExampleMenuFile() +{ + IMGUI_DEMO_MARKER("Examples/Menu"); + ImGui::MenuItem("(demo menu)", NULL, false, false); + if (ImGui::MenuItem("New")) {} + if (ImGui::MenuItem("Open", "Ctrl+O")) {} + if (ImGui::BeginMenu("Open Recent")) + { + ImGui::MenuItem("fish_hat.c"); + ImGui::MenuItem("fish_hat.inl"); + ImGui::MenuItem("fish_hat.h"); + if (ImGui::BeginMenu("More..")) + { + ImGui::MenuItem("Hello"); + ImGui::MenuItem("Sailor"); + if (ImGui::BeginMenu("Recurse..")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Save", "Ctrl+S")) {} + if (ImGui::MenuItem("Save As..")) {} + + ImGui::Separator(); + IMGUI_DEMO_MARKER("Examples/Menu/Options"); + if (ImGui::BeginMenu("Options")) + { + static bool enabled = true; + ImGui::MenuItem("Enabled", "", &enabled); + ImGui::BeginChild("child", ImVec2(0, 60), true); + for (int i = 0; i < 10; i++) + ImGui::Text("Scrolling Text %d", i); + ImGui::EndChild(); + static float f = 0.5f; + static int n = 0; + ImGui::SliderFloat("Value", &f, 0.0f, 1.0f); + ImGui::InputFloat("Input", &f, 0.1f); + ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0"); + ImGui::EndMenu(); + } + + IMGUI_DEMO_MARKER("Examples/Menu/Colors"); + if (ImGui::BeginMenu("Colors")) + { + float sz = ImGui::GetTextLineHeight(); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const char* name = ImGui::GetStyleColorName((ImGuiCol)i); + ImVec2 p = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + sz, p.y + sz), ImGui::GetColorU32((ImGuiCol)i)); + ImGui::Dummy(ImVec2(sz, sz)); + ImGui::SameLine(); + ImGui::MenuItem(name); + } + ImGui::EndMenu(); + } + + // Here we demonstrate appending again to the "Options" menu (which we already created above) + // Of course in this demo it is a little bit silly that this function calls BeginMenu("Options") twice. + // In a real code-base using it would make senses to use this feature from very different code locations. + if (ImGui::BeginMenu("Options")) // <-- Append! + { + IMGUI_DEMO_MARKER("Examples/Menu/Append to an existing menu"); + static bool b = true; + ImGui::Checkbox("SomeOption", &b); + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu("Disabled", false)) // Disabled + { + IM_ASSERT(0); + } + if (ImGui::MenuItem("Checked", NULL, true)) {} + if (ImGui::MenuItem("Quit", "Alt+F4")) {} +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Debug Console / ShowExampleAppConsole() +//----------------------------------------------------------------------------- + +// Demonstrate creating a simple console window, with scrolling, filtering, completion and history. +// For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions. +struct ExampleAppConsole +{ + char InputBuf[256]; + ImVector Items; + ImVector Commands; + ImVector History; + int HistoryPos; // -1: new line, 0..History.Size-1 browsing history. + ImGuiTextFilter Filter; + bool AutoScroll; + bool ScrollToBottom; + + ExampleAppConsole() + { + IMGUI_DEMO_MARKER("Examples/Console"); + ClearLog(); + memset(InputBuf, 0, sizeof(InputBuf)); + HistoryPos = -1; + + // "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. + Commands.push_back("HELP"); + Commands.push_back("HISTORY"); + Commands.push_back("CLEAR"); + Commands.push_back("CLASSIFY"); + AutoScroll = true; + ScrollToBottom = false; + AddLog("Welcome to Dear ImGui!"); + } + ~ExampleAppConsole() + { + ClearLog(); + for (int i = 0; i < History.Size; i++) + free(History[i]); + } + + // Portable helpers + static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; } + static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; } + static char* Strdup(const char* s) { IM_ASSERT(s); size_t len = strlen(s) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); } + static void Strtrim(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; } + + void ClearLog() + { + for (int i = 0; i < Items.Size; i++) + free(Items[i]); + Items.clear(); + } + + void AddLog(const char* fmt, ...) IM_FMTARGS(2) + { + // FIXME-OPT + char buf[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args); + buf[IM_ARRAYSIZE(buf)-1] = 0; + va_end(args); + Items.push_back(Strdup(buf)); + } + + void Draw(const char* title, bool* p_open) + { + ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver); + if (!ImGui::Begin(title, p_open)) + { + ImGui::End(); + return; + } + + // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. + // So e.g. IsItemHovered() will return true when hovering the title bar. + // Here we create a context menu only available from the title bar. + if (ImGui::BeginPopupContextItem()) + { + if (ImGui::MenuItem("Close Console")) + *p_open = false; + ImGui::EndPopup(); + } + + ImGui::TextWrapped( + "This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate " + "implementation may want to store entries along with extra data such as timestamp, emitter, etc."); + ImGui::TextWrapped("Enter 'HELP' for help."); + + // TODO: display items starting from the bottom + + if (ImGui::SmallButton("Add Debug Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } + ImGui::SameLine(); + if (ImGui::SmallButton("Add Debug Error")) { AddLog("[error] something went wrong"); } + ImGui::SameLine(); + if (ImGui::SmallButton("Clear")) { ClearLog(); } + ImGui::SameLine(); + bool copy_to_clipboard = ImGui::SmallButton("Copy"); + //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } + + ImGui::Separator(); + + // Options menu + if (ImGui::BeginPopup("Options")) + { + ImGui::Checkbox("Auto-scroll", &AutoScroll); + ImGui::EndPopup(); + } + + // Options, Filter + if (ImGui::Button("Options")) + ImGui::OpenPopup("Options"); + ImGui::SameLine(); + Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); + ImGui::Separator(); + + // Reserve enough left-over height for 1 separator + 1 input text + const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); + ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar); + if (ImGui::BeginPopupContextWindow()) + { + if (ImGui::Selectable("Clear")) ClearLog(); + ImGui::EndPopup(); + } + + // Display every line as a separate entry so we can change their color or add custom widgets. + // If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); + // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping + // to only process visible items. The clipper will automatically measure the height of your first item and then + // "seek" to display only items in the visible area. + // To use the clipper we can replace your standard loop: + // for (int i = 0; i < Items.Size; i++) + // With: + // ImGuiListClipper clipper; + // clipper.Begin(Items.Size); + // while (clipper.Step()) + // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + // - That your items are evenly spaced (same height) + // - That you have cheap random access to your elements (you can access them given their index, + // without processing all the ones before) + // You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property. + // We would need random-access on the post-filtered list. + // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices + // or offsets of items that passed the filtering test, recomputing this array when user changes the filter, + // and appending newly elements as they are inserted. This is left as a task to the user until we can manage + // to improve this example code! + // If your items are of variable height: + // - Split them into same height items would be simpler and facilitate random-seeking into your list. + // - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing + if (copy_to_clipboard) + ImGui::LogToClipboard(); + for (int i = 0; i < Items.Size; i++) + { + const char* item = Items[i]; + if (!Filter.PassFilter(item)) + continue; + + // Normally you would store more information in your item than just a string. + // (e.g. make Items[] an array of structure, store color/type etc.) + ImVec4 color; + bool has_color = false; + if (strstr(item, "[error]")) { color = ImVec4(1.0f, 0.4f, 0.4f, 1.0f); has_color = true; } + else if (strncmp(item, "# ", 2) == 0) { color = ImVec4(1.0f, 0.8f, 0.6f, 1.0f); has_color = true; } + if (has_color) + ImGui::PushStyleColor(ImGuiCol_Text, color); + ImGui::TextUnformatted(item); + if (has_color) + ImGui::PopStyleColor(); + } + if (copy_to_clipboard) + ImGui::LogFinish(); + + if (ScrollToBottom || (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY())) + ImGui::SetScrollHereY(1.0f); + ScrollToBottom = false; + + ImGui::PopStyleVar(); + ImGui::EndChild(); + ImGui::Separator(); + + // Command-line + bool reclaim_focus = false; + ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory; + if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), input_text_flags, &TextEditCallbackStub, (void*)this)) + { + char* s = InputBuf; + Strtrim(s); + if (s[0]) + ExecCommand(s); + strcpy(s, ""); + reclaim_focus = true; + } + + // Auto-focus on window apparition + ImGui::SetItemDefaultFocus(); + if (reclaim_focus) + ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget + + ImGui::End(); + } + + void ExecCommand(const char* command_line) + { + AddLog("# %s\n", command_line); + + // Insert into history. First find match and delete it so it can be pushed to the back. + // This isn't trying to be smart or optimal. + HistoryPos = -1; + for (int i = History.Size - 1; i >= 0; i--) + if (Stricmp(History[i], command_line) == 0) + { + free(History[i]); + History.erase(History.begin() + i); + break; + } + History.push_back(Strdup(command_line)); + + // Process command + if (Stricmp(command_line, "CLEAR") == 0) + { + ClearLog(); + } + else if (Stricmp(command_line, "HELP") == 0) + { + AddLog("Commands:"); + for (int i = 0; i < Commands.Size; i++) + AddLog("- %s", Commands[i]); + } + else if (Stricmp(command_line, "HISTORY") == 0) + { + int first = History.Size - 10; + for (int i = first > 0 ? first : 0; i < History.Size; i++) + AddLog("%3d: %s\n", i, History[i]); + } + else + { + AddLog("Unknown command: '%s'\n", command_line); + } + + // On command input, we scroll to bottom even if AutoScroll==false + ScrollToBottom = true; + } + + // In C++11 you'd be better off using lambdas for this sort of forwarding callbacks + static int TextEditCallbackStub(ImGuiInputTextCallbackData* data) + { + ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; + return console->TextEditCallback(data); + } + + int TextEditCallback(ImGuiInputTextCallbackData* data) + { + //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); + switch (data->EventFlag) + { + case ImGuiInputTextFlags_CallbackCompletion: + { + // Example of TEXT COMPLETION + + // Locate beginning of current word + const char* word_end = data->Buf + data->CursorPos; + const char* word_start = word_end; + while (word_start > data->Buf) + { + const char c = word_start[-1]; + if (c == ' ' || c == '\t' || c == ',' || c == ';') + break; + word_start--; + } + + // Build a list of candidates + ImVector candidates; + for (int i = 0; i < Commands.Size; i++) + if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0) + candidates.push_back(Commands[i]); + + if (candidates.Size == 0) + { + // No match + AddLog("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start); + } + else if (candidates.Size == 1) + { + // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing. + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); + data->InsertChars(data->CursorPos, candidates[0]); + data->InsertChars(data->CursorPos, " "); + } + else + { + // Multiple matches. Complete as much as we can.. + // So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches. + int match_len = (int)(word_end - word_start); + for (;;) + { + int c = 0; + bool all_candidates_matches = true; + for (int i = 0; i < candidates.Size && all_candidates_matches; i++) + if (i == 0) + c = toupper(candidates[i][match_len]); + else if (c == 0 || c != toupper(candidates[i][match_len])) + all_candidates_matches = false; + if (!all_candidates_matches) + break; + match_len++; + } + + if (match_len > 0) + { + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); + data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); + } + + // List matches + AddLog("Possible matches:\n"); + for (int i = 0; i < candidates.Size; i++) + AddLog("- %s\n", candidates[i]); + } + + break; + } + case ImGuiInputTextFlags_CallbackHistory: + { + // Example of HISTORY + const int prev_history_pos = HistoryPos; + if (data->EventKey == ImGuiKey_UpArrow) + { + if (HistoryPos == -1) + HistoryPos = History.Size - 1; + else if (HistoryPos > 0) + HistoryPos--; + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + if (HistoryPos != -1) + if (++HistoryPos >= History.Size) + HistoryPos = -1; + } + + // A better implementation would preserve the data on the current input line along with cursor position. + if (prev_history_pos != HistoryPos) + { + const char* history_str = (HistoryPos >= 0) ? History[HistoryPos] : ""; + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, history_str); + } + } + } + return 0; + } +}; + +static void ShowExampleAppConsole(bool* p_open) +{ + static ExampleAppConsole console; + console.Draw("Example: Console", p_open); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Debug Log / ShowExampleAppLog() +//----------------------------------------------------------------------------- + +// Usage: +// static ExampleAppLog my_log; +// my_log.AddLog("Hello %d world\n", 123); +// my_log.Draw("title"); +struct ExampleAppLog +{ + ImGuiTextBuffer Buf; + ImGuiTextFilter Filter; + ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls. + bool AutoScroll; // Keep scrolling if already at the bottom. + + ExampleAppLog() + { + AutoScroll = true; + Clear(); + } + + void Clear() + { + Buf.clear(); + LineOffsets.clear(); + LineOffsets.push_back(0); + } + + void AddLog(const char* fmt, ...) IM_FMTARGS(2) + { + int old_size = Buf.size(); + va_list args; + va_start(args, fmt); + Buf.appendfv(fmt, args); + va_end(args); + for (int new_size = Buf.size(); old_size < new_size; old_size++) + if (Buf[old_size] == '\n') + LineOffsets.push_back(old_size + 1); + } + + void Draw(const char* title, bool* p_open = NULL) + { + if (!ImGui::Begin(title, p_open)) + { + ImGui::End(); + return; + } + + // Options menu + if (ImGui::BeginPopup("Options")) + { + ImGui::Checkbox("Auto-scroll", &AutoScroll); + ImGui::EndPopup(); + } + + // Main window + if (ImGui::Button("Options")) + ImGui::OpenPopup("Options"); + ImGui::SameLine(); + bool clear = ImGui::Button("Clear"); + ImGui::SameLine(); + bool copy = ImGui::Button("Copy"); + ImGui::SameLine(); + Filter.Draw("Filter", -100.0f); + + ImGui::Separator(); + ImGui::BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar); + + if (clear) + Clear(); + if (copy) + ImGui::LogToClipboard(); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + const char* buf = Buf.begin(); + const char* buf_end = Buf.end(); + if (Filter.IsActive()) + { + // In this example we don't use the clipper when Filter is enabled. + // This is because we don't have a random access on the result on our filter. + // A real application processing logs with ten of thousands of entries may want to store the result of + // search/filter.. especially if the filtering function is not trivial (e.g. reg-exp). + for (int line_no = 0; line_no < LineOffsets.Size; line_no++) + { + const char* line_start = buf + LineOffsets[line_no]; + const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end; + if (Filter.PassFilter(line_start, line_end)) + ImGui::TextUnformatted(line_start, line_end); + } + } + else + { + // The simplest and easy way to display the entire buffer: + // ImGui::TextUnformatted(buf_begin, buf_end); + // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward + // to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are + // within the visible area. + // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them + // on your side is recommended. Using ImGuiListClipper requires + // - A) random access into your data + // - B) items all being the same height, + // both of which we can handle since we an array pointing to the beginning of each line of text. + // When using the filter (in the block of code above) we don't have random access into the data to display + // anymore, which is why we don't use the clipper. Storing or skimming through the search result would make + // it possible (and would be recommended if you want to search through tens of thousands of entries). + ImGuiListClipper clipper; + clipper.Begin(LineOffsets.Size); + while (clipper.Step()) + { + for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++) + { + const char* line_start = buf + LineOffsets[line_no]; + const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end; + ImGui::TextUnformatted(line_start, line_end); + } + } + clipper.End(); + } + ImGui::PopStyleVar(); + + if (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) + ImGui::SetScrollHereY(1.0f); + + ImGui::EndChild(); + ImGui::End(); + } +}; + +// Demonstrate creating a simple log window with basic filtering. +static void ShowExampleAppLog(bool* p_open) +{ + static ExampleAppLog log; + + // For the demo: add a debug button _BEFORE_ the normal log window contents + // We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window. + // Most of the contents of the window will be added by the log.Draw() call. + ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver); + ImGui::Begin("Example: Log", p_open); + IMGUI_DEMO_MARKER("Examples/Log"); + if (ImGui::SmallButton("[Debug] Add 5 entries")) + { + static int counter = 0; + const char* categories[3] = { "info", "warn", "error" }; + const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" }; + for (int n = 0; n < 5; n++) + { + const char* category = categories[counter % IM_ARRAYSIZE(categories)]; + const char* word = words[counter % IM_ARRAYSIZE(words)]; + log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n", + ImGui::GetFrameCount(), category, ImGui::GetTime(), word); + counter++; + } + } + ImGui::End(); + + // Actually call in the regular Log helper (which will Begin() into the same window as we just did) + log.Draw("Example: Log", p_open); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Simple Layout / ShowExampleAppLayout() +//----------------------------------------------------------------------------- + +// Demonstrate create a window with multiple child windows. +static void ShowExampleAppLayout(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiCond_FirstUseEver); + if (ImGui::Begin("Example: Simple layout", p_open, ImGuiWindowFlags_MenuBar)) + { + IMGUI_DEMO_MARKER("Examples/Simple layout"); + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Close")) *p_open = false; + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + // Left + static int selected = 0; + { + ImGui::BeginChild("left pane", ImVec2(150, 0), true); + for (int i = 0; i < 100; i++) + { + // FIXME: Good candidate to use ImGuiSelectableFlags_SelectOnNav + char label[128]; + sprintf(label, "MyObject %d", i); + if (ImGui::Selectable(label, selected == i)) + selected = i; + } + ImGui::EndChild(); + } + ImGui::SameLine(); + + // Right + { + ImGui::BeginGroup(); + ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us + ImGui::Text("MyObject: %d", selected); + ImGui::Separator(); + if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None)) + { + if (ImGui::BeginTabItem("Description")) + { + ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("Details")) + { + ImGui::Text("ID: 0123456789"); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::EndChild(); + if (ImGui::Button("Revert")) {} + ImGui::SameLine(); + if (ImGui::Button("Save")) {} + ImGui::EndGroup(); + } + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() +//----------------------------------------------------------------------------- + +static void ShowPlaceholderObject(const char* prefix, int uid) +{ + // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. + ImGui::PushID(uid); + + // Text and Tree nodes are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the tree lines equal high. + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::AlignTextToFramePadding(); + bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); + ImGui::TableSetColumnIndex(1); + ImGui::Text("my sailor is rich"); + + if (node_open) + { + static float placeholder_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f }; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); // Use field index as identifier. + if (i < 2) + { + ShowPlaceholderObject("Child", 424242); + } + else + { + // Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well) + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::AlignTextToFramePadding(); + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet; + ImGui::TreeNodeEx("Field", flags, "Field_%d", i); + + ImGui::TableSetColumnIndex(1); + ImGui::SetNextItemWidth(-FLT_MIN); + if (i >= 5) + ImGui::InputFloat("##value", &placeholder_members[i], 1.0f); + else + ImGui::DragFloat("##value", &placeholder_members[i], 0.01f); + ImGui::NextColumn(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::PopID(); +} + +// Demonstrate create a simple property editor. +static void ShowExampleAppPropertyEditor(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver); + if (!ImGui::Begin("Example: Property editor", p_open)) + { + ImGui::End(); + return; + } + IMGUI_DEMO_MARKER("Examples/Property Editor"); + + HelpMarker( + "This example shows how you may implement a property editor using two columns.\n" + "All objects/fields data are dummies here.\n" + "Remember that in many simple cases, you can use ImGui::SameLine(xxx) to position\n" + "your cursor horizontally instead of using the Columns() API."); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); + if (ImGui::BeginTable("split", 2, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_Resizable)) + { + // Iterate placeholder objects (all the same data) + for (int obj_i = 0; obj_i < 4; obj_i++) + { + ShowPlaceholderObject("Object", obj_i); + //ImGui::Separator(); + } + ImGui::EndTable(); + } + ImGui::PopStyleVar(); + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Long Text / ShowExampleAppLongText() +//----------------------------------------------------------------------------- + +// Demonstrate/test rendering huge amount of text, and the incidence of clipping. +static void ShowExampleAppLongText(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver); + if (!ImGui::Begin("Example: Long text display", p_open)) + { + ImGui::End(); + return; + } + IMGUI_DEMO_MARKER("Examples/Long text display"); + + static int test_type = 0; + static ImGuiTextBuffer log; + static int lines = 0; + ImGui::Text("Printing unusually long amount of text."); + ImGui::Combo("Test type", &test_type, + "Single call to TextUnformatted()\0" + "Multiple calls to Text(), clipped\0" + "Multiple calls to Text(), not clipped (slow)\0"); + ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); + if (ImGui::Button("Clear")) { log.clear(); lines = 0; } + ImGui::SameLine(); + if (ImGui::Button("Add 1000 lines")) + { + for (int i = 0; i < 1000; i++) + log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines + i); + lines += 1000; + } + ImGui::BeginChild("Log"); + switch (test_type) + { + case 0: + // Single call to TextUnformatted() with a big buffer + ImGui::TextUnformatted(log.begin(), log.end()); + break; + case 1: + { + // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + ImGuiListClipper clipper; + clipper.Begin(lines); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + case 2: + // Multiple calls to Text(), not clipped (slow) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); + for (int i = 0; i < lines; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + ImGui::EndChild(); + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() +//----------------------------------------------------------------------------- + +// Demonstrate creating a window which gets auto-resized according to its content. +static void ShowExampleAppAutoResize(bool* p_open) +{ + if (!ImGui::Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::End(); + return; + } + IMGUI_DEMO_MARKER("Examples/Auto-resizing window"); + + static int lines = 10; + ImGui::TextUnformatted( + "Window will resize every-frame to the size of its content.\n" + "Note that you probably don't want to query the window size to\n" + "output your content because that would create a feedback loop."); + ImGui::SliderInt("Number of lines", &lines, 1, 20); + for (int i = 0; i < lines; i++) + ImGui::Text("%*sThis is line %d", i * 4, "", i); // Pad with space to extend size horizontally + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize() +//----------------------------------------------------------------------------- + +// Demonstrate creating a window with custom resize constraints. +static void ShowExampleAppConstrainedResize(bool* p_open) +{ + struct CustomConstraints + { + // Helper functions to demonstrate programmatic constraints + static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = IM_MAX(data->DesiredSize.x, data->DesiredSize.y); } + static void Step(ImGuiSizeCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } + }; + + const char* test_desc[] = + { + "Resize vertical only", + "Resize horizontal only", + "Width > 100, Height > 100", + "Width 400-500", + "Height 400-500", + "Custom: Always Square", + "Custom: Fixed Steps (100)", + }; + + static bool auto_resize = false; + static int type = 0; + static int display_lines = 10; + if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Vertical only + if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Horizontal only + if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100 + if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)); // Width 400-500 + if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, 500)); // Height 400-500 + if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square + if (type == 6) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)(intptr_t)100); // Fixed Step + + ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0; + if (ImGui::Begin("Example: Constrained Resize", p_open, flags)) + { + IMGUI_DEMO_MARKER("Examples/Constrained Resizing window"); + if (ImGui::IsWindowDocked()) + ImGui::Text("Warning: Sizing Constraints won't work if the window is docked!"); + if (ImGui::Button("200x200")) { ImGui::SetWindowSize(ImVec2(200, 200)); } ImGui::SameLine(); + if (ImGui::Button("500x500")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine(); + if (ImGui::Button("800x200")) { ImGui::SetWindowSize(ImVec2(800, 200)); } + ImGui::SetNextItemWidth(200); + ImGui::Combo("Constraint", &type, test_desc, IM_ARRAYSIZE(test_desc)); + ImGui::SetNextItemWidth(200); + ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100); + ImGui::Checkbox("Auto-resize", &auto_resize); + for (int i = 0; i < display_lines; i++) + ImGui::Text("%*sHello, sailor! Making this line long enough for the example.", i * 4, ""); + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() +//----------------------------------------------------------------------------- + +// Demonstrate creating a simple static window with no decoration +// + a context-menu to choose which corner of the screen to use. +static void ShowExampleAppSimpleOverlay(bool* p_open) +{ + static int corner = 0; + ImGuiIO& io = ImGui::GetIO(); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav; + if (corner != -1) + { + const float PAD = 10.0f; + const ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImVec2 work_pos = viewport->WorkPos; // Use work area to avoid menu-bar/task-bar, if any! + ImVec2 work_size = viewport->WorkSize; + ImVec2 window_pos, window_pos_pivot; + window_pos.x = (corner & 1) ? (work_pos.x + work_size.x - PAD) : (work_pos.x + PAD); + window_pos.y = (corner & 2) ? (work_pos.y + work_size.y - PAD) : (work_pos.y + PAD); + window_pos_pivot.x = (corner & 1) ? 1.0f : 0.0f; + window_pos_pivot.y = (corner & 2) ? 1.0f : 0.0f; + ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); + ImGui::SetNextWindowViewport(viewport->ID); + window_flags |= ImGuiWindowFlags_NoMove; + } + ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background + if (ImGui::Begin("Example: Simple overlay", p_open, window_flags)) + { + IMGUI_DEMO_MARKER("Examples/Simple Overlay"); + ImGui::Text("Simple overlay\n" "in the corner of the screen.\n" "(right-click to change position)"); + ImGui::Separator(); + if (ImGui::IsMousePosValid()) + ImGui::Text("Mouse Position: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y); + else + ImGui::Text("Mouse Position: "); + if (ImGui::BeginPopupContextWindow()) + { + if (ImGui::MenuItem("Custom", NULL, corner == -1)) corner = -1; + if (ImGui::MenuItem("Top-left", NULL, corner == 0)) corner = 0; + if (ImGui::MenuItem("Top-right", NULL, corner == 1)) corner = 1; + if (ImGui::MenuItem("Bottom-left", NULL, corner == 2)) corner = 2; + if (ImGui::MenuItem("Bottom-right", NULL, corner == 3)) corner = 3; + if (p_open && ImGui::MenuItem("Close")) *p_open = false; + ImGui::EndPopup(); + } + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() +//----------------------------------------------------------------------------- + +// Demonstrate creating a window covering the entire screen/viewport +static void ShowExampleAppFullscreen(bool* p_open) +{ + static bool use_work_area = true; + static ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings; + + // We demonstrate using the full viewport area or the work area (without menu-bars, task-bars etc.) + // Based on your use case you may want one of the other. + const ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(use_work_area ? viewport->WorkPos : viewport->Pos); + ImGui::SetNextWindowSize(use_work_area ? viewport->WorkSize : viewport->Size); + + if (ImGui::Begin("Example: Fullscreen window", p_open, flags)) + { + ImGui::Checkbox("Use work area instead of main area", &use_work_area); + ImGui::SameLine(); + HelpMarker("Main Area = entire viewport,\nWork Area = entire viewport minus sections used by the main menu bars, task bars etc.\n\nEnable the main-menu bar in Examples menu to see the difference."); + + ImGui::CheckboxFlags("ImGuiWindowFlags_NoBackground", &flags, ImGuiWindowFlags_NoBackground); + ImGui::CheckboxFlags("ImGuiWindowFlags_NoDecoration", &flags, ImGuiWindowFlags_NoDecoration); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiWindowFlags_NoTitleBar", &flags, ImGuiWindowFlags_NoTitleBar); + ImGui::CheckboxFlags("ImGuiWindowFlags_NoCollapse", &flags, ImGuiWindowFlags_NoCollapse); + ImGui::CheckboxFlags("ImGuiWindowFlags_NoScrollbar", &flags, ImGuiWindowFlags_NoScrollbar); + ImGui::Unindent(); + + if (p_open && ImGui::Button("Close this window")) + *p_open = false; + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles() +//----------------------------------------------------------------------------- + +// Demonstrate using "##" and "###" in identifiers to manipulate ID generation. +// This apply to all regular items as well. +// Read FAQ section "How can I have multiple widgets with the same label?" for details. +static void ShowExampleAppWindowTitles(bool*) +{ + const ImGuiViewport* viewport = ImGui::GetMainViewport(); + const ImVec2 base_pos = viewport->Pos; + + // By default, Windows are uniquely identified by their title. + // You can use the "##" and "###" markers to manipulate the display/ID. + + // Using "##" to display same title but have unique identifier. + ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 100), ImGuiCond_FirstUseEver); + ImGui::Begin("Same title as another window##1"); + IMGUI_DEMO_MARKER("Examples/Manipulating window titles"); + ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique."); + ImGui::End(); + + ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 200), ImGuiCond_FirstUseEver); + ImGui::Begin("Same title as another window##2"); + ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique."); + ImGui::End(); + + // Using "###" to display a changing title but keep a static identifier "AnimatedTitle" + char buf[128]; + sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime() / 0.25f) & 3], ImGui::GetFrameCount()); + ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 300), ImGuiCond_FirstUseEver); + ImGui::Begin(buf); + ImGui::Text("This window has a changing title."); + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() +//----------------------------------------------------------------------------- + +// Demonstrate using the low-level ImDrawList to draw custom shapes. +static void ShowExampleAppCustomRendering(bool* p_open) +{ + if (!ImGui::Begin("Example: Custom rendering", p_open)) + { + ImGui::End(); + return; + } + IMGUI_DEMO_MARKER("Examples/Custom Rendering"); + + // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of + // overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your + // types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not + // exposed outside (to avoid messing with your types) In this example we are not using the maths operators! + + if (ImGui::BeginTabBar("##TabBar")) + { + if (ImGui::BeginTabItem("Primitives")) + { + ImGui::PushItemWidth(-ImGui::GetFontSize() * 15); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + // Draw gradients + // (note that those are currently exacerbating our sRGB/Linear issues) + // Calling ImGui::GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well.. + ImGui::Text("Gradients"); + ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight()); + { + ImVec2 p0 = ImGui::GetCursorScreenPos(); + ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); + ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 0, 0, 255)); + ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 255, 255, 255)); + draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); + ImGui::InvisibleButton("##gradient1", gradient_size); + } + { + ImVec2 p0 = ImGui::GetCursorScreenPos(); + ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); + ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 255, 0, 255)); + ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 0, 0, 255)); + draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); + ImGui::InvisibleButton("##gradient2", gradient_size); + } + + // Draw a bunch of primitives + ImGui::Text("All primitives"); + static float sz = 36.0f; + static float thickness = 3.0f; + static int ngon_sides = 6; + static bool circle_segments_override = false; + static int circle_segments_override_v = 12; + static bool curve_segments_override = false; + static int curve_segments_override_v = 8; + static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); + ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 100.0f, "%.0f"); + ImGui::DragFloat("Thickness", &thickness, 0.05f, 1.0f, 8.0f, "%.02f"); + ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12); + ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + circle_segments_override |= ImGui::SliderInt("Circle segments override", &circle_segments_override_v, 3, 40); + ImGui::Checkbox("##curvessegmentoverride", &curve_segments_override); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40); + ImGui::ColorEdit4("Color", &colf.x); + + const ImVec2 p = ImGui::GetCursorScreenPos(); + const ImU32 col = ImColor(colf); + const float spacing = 10.0f; + const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight; + const float rounding = sz / 5.0f; + const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; + const int curve_segments = curve_segments_override ? curve_segments_override_v : 0; + float x = p.x + 4.0f; + float y = p.y + 4.0f; + for (int n = 0; n < 2; n++) + { + // First line uses a thickness of 1.0f, second line uses the configurable thickness + float th = (n == 0) ? 1.0f : thickness; + draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, ImDrawFlags_None, th); x += sz + spacing; // Square + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, ImDrawFlags_None, th); x += sz + spacing; // Square with all rounded corners + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br, th); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th);x += sz + spacing; // Triangle + //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line + + // Quadratic Bezier Curve (3 control points) + ImVec2 cp3[3] = { ImVec2(x, y + sz * 0.6f), ImVec2(x + sz * 0.5f, y - sz * 0.4f), ImVec2(x + sz, y + sz) }; + draw_list->AddBezierQuadratic(cp3[0], cp3[1], cp3[2], col, th, curve_segments); x += sz + spacing; + + // Cubic Bezier Curve (4 control points) + ImVec2 cp4[4] = { ImVec2(x, y), ImVec2(x + sz * 1.3f, y + sz * 0.3f), ImVec2(x + sz - sz * 1.3f, y + sz - sz * 0.3f), ImVec2(x + sz, y + sz) }; + draw_list->AddBezierCubic(cp4[0], cp4[1], cp4[2], cp4[3], col, th, curve_segments); + + x = p.x + 4; + y += sz + spacing; + } + draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz*0.5f, col, ngon_sides); x += sz + spacing; // N-gon + draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments); x += sz + spacing; // Circle + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; // Square + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f); x += sz + spacing; // Square with all rounded corners + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col); x += sz + spacing; // Triangle + //draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing * 2.0f;// Vertical line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; // Pixel (faster than AddLine) + draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + sz, y + sz), IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255)); + + ImGui::Dummy(ImVec2((sz + spacing) * 10.2f, (sz + spacing) * 3.0f)); + ImGui::PopItemWidth(); + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("Canvas")) + { + static ImVector points; + static ImVec2 scrolling(0.0f, 0.0f); + static bool opt_enable_grid = true; + static bool opt_enable_context_menu = true; + static bool adding_line = false; + + ImGui::Checkbox("Enable grid", &opt_enable_grid); + ImGui::Checkbox("Enable context menu", &opt_enable_context_menu); + ImGui::Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu."); + + // Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling. + // Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls. + // To use a child window instead we could use, e.g: + // ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Disable padding + // ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(50, 50, 50, 255)); // Set a background color + // ImGui::BeginChild("canvas", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_NoMove); + // ImGui::PopStyleColor(); + // ImGui::PopStyleVar(); + // [...] + // ImGui::EndChild(); + + // Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive() + ImVec2 canvas_p0 = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + ImVec2 canvas_sz = ImGui::GetContentRegionAvail(); // Resize canvas to what's available + if (canvas_sz.x < 50.0f) canvas_sz.x = 50.0f; + if (canvas_sz.y < 50.0f) canvas_sz.y = 50.0f; + ImVec2 canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y); + + // Draw border and background color + ImGuiIO& io = ImGui::GetIO(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + draw_list->AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255)); + draw_list->AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255)); + + // This will catch our interactions + ImGui::InvisibleButton("canvas", canvas_sz, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight); + const bool is_hovered = ImGui::IsItemHovered(); // Hovered + const bool is_active = ImGui::IsItemActive(); // Held + const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); // Lock scrolled origin + const ImVec2 mouse_pos_in_canvas(io.MousePos.x - origin.x, io.MousePos.y - origin.y); + + // Add first and second point + if (is_hovered && !adding_line && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + { + points.push_back(mouse_pos_in_canvas); + points.push_back(mouse_pos_in_canvas); + adding_line = true; + } + if (adding_line) + { + points.back() = mouse_pos_in_canvas; + if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) + adding_line = false; + } + + // Pan (we use a zero mouse threshold when there's no context menu) + // You may decide to make that threshold dynamic based on whether the mouse is hovering something etc. + const float mouse_threshold_for_pan = opt_enable_context_menu ? -1.0f : 0.0f; + if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, mouse_threshold_for_pan)) + { + scrolling.x += io.MouseDelta.x; + scrolling.y += io.MouseDelta.y; + } + + // Context menu (under default mouse threshold) + ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right); + if (opt_enable_context_menu && drag_delta.x == 0.0f && drag_delta.y == 0.0f) + ImGui::OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + if (ImGui::BeginPopup("context")) + { + if (adding_line) + points.resize(points.size() - 2); + adding_line = false; + if (ImGui::MenuItem("Remove one", NULL, false, points.Size > 0)) { points.resize(points.size() - 2); } + if (ImGui::MenuItem("Remove all", NULL, false, points.Size > 0)) { points.clear(); } + ImGui::EndPopup(); + } + + // Draw grid + all lines in the canvas + draw_list->PushClipRect(canvas_p0, canvas_p1, true); + if (opt_enable_grid) + { + const float GRID_STEP = 64.0f; + for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP) + draw_list->AddLine(ImVec2(canvas_p0.x + x, canvas_p0.y), ImVec2(canvas_p0.x + x, canvas_p1.y), IM_COL32(200, 200, 200, 40)); + for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP) + draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40)); + } + for (int n = 0; n < points.Size; n += 2) + draw_list->AddLine(ImVec2(origin.x + points[n].x, origin.y + points[n].y), ImVec2(origin.x + points[n + 1].x, origin.y + points[n + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); + draw_list->PopClipRect(); + + ImGui::EndTabItem(); + } + + if (ImGui::BeginTabItem("BG/FG draw lists")) + { + static bool draw_bg = true; + static bool draw_fg = true; + ImGui::Checkbox("Draw in Background draw list", &draw_bg); + ImGui::SameLine(); HelpMarker("The Background draw list will be rendered below every Dear ImGui windows."); + ImGui::Checkbox("Draw in Foreground draw list", &draw_fg); + ImGui::SameLine(); HelpMarker("The Foreground draw list will be rendered over every Dear ImGui windows."); + ImVec2 window_pos = ImGui::GetWindowPos(); + ImVec2 window_size = ImGui::GetWindowSize(); + ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f); + if (draw_bg) + ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 0, 10 + 4); + if (draw_fg) + ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 0, 10); + ImGui::EndTabItem(); + } + + ImGui::EndTabBar(); + } + + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() +//----------------------------------------------------------------------------- + +// Demonstrate using DockSpace() to create an explicit docking node within an existing window. +// Note: You can use most Docking facilities without calling any API. You DO NOT need to call DockSpace() to use Docking! +// - Drag from window title bar or their tab to dock/undock. Hold SHIFT to disable docking. +// - Drag from window menu button (upper-left button) to undock an entire node (all windows). +// - When io.ConfigDockingWithShift == true, you instead need to hold SHIFT to _enable_ docking/undocking. +// About dockspaces: +// - Use DockSpace() to create an explicit dock node _within_ an existing window. +// - Use DockSpaceOverViewport() to create an explicit dock node covering the screen or a specific viewport. +// This is often used with ImGuiDockNodeFlags_PassthruCentralNode. +// - Important: Dockspaces need to be submitted _before_ any window they can host. Submit it early in your frame! (*) +// - Important: Dockspaces need to be kept alive if hidden, otherwise windows docked into it will be undocked. +// e.g. if you have multiple tabs with a dockspace inside each tab: submit the non-visible dockspaces with ImGuiDockNodeFlags_KeepAliveOnly. +// (*) because of this constraint, the implicit \"Debug\" window can not be docked into an explicit DockSpace() node, +// because that window is submitted as part of the part of the NewFrame() call. An easy workaround is that you can create +// your own implicit "Debug##2" window after calling DockSpace() and leave it in the window stack for anyone to use. +void ShowExampleAppDockSpace(bool* p_open) +{ + // If you strip some features of, this demo is pretty much equivalent to calling DockSpaceOverViewport()! + // In most cases you should be able to just call DockSpaceOverViewport() and ignore all the code below! + // In this specific demo, we are not using DockSpaceOverViewport() because: + // - we allow the host window to be floating/moveable instead of filling the viewport (when opt_fullscreen == false) + // - we allow the host window to have padding (when opt_padding == true) + // - we have a local menu bar in the host window (vs. you could use BeginMainMenuBar() + DockSpaceOverViewport() in your code!) + // TL;DR; this demo is more complicated than what you would normally use. + // If we removed all the options we are showcasing, this demo would become: + // void ShowExampleAppDockSpace() + // { + // ImGui::DockSpaceOverViewport(ImGui::GetMainViewport()); + // } + + static bool opt_fullscreen = true; + static bool opt_padding = false; + static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None; + + // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, + // because it would be confusing to have two docking targets within each others. + ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; + if (opt_fullscreen) + { + const ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(viewport->WorkPos); + ImGui::SetNextWindowSize(viewport->WorkSize); + ImGui::SetNextWindowViewport(viewport->ID); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); + window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; + window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; + } + else + { + dockspace_flags &= ~ImGuiDockNodeFlags_PassthruCentralNode; + } + + // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background + // and handle the pass-thru hole, so we ask Begin() to not render a background. + if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) + window_flags |= ImGuiWindowFlags_NoBackground; + + // Important: note that we proceed even if Begin() returns false (aka window is collapsed). + // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, + // all active windows docked into it will lose their parent and become undocked. + // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise + // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. + if (!opt_padding) + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + ImGui::Begin("DockSpace Demo", p_open, window_flags); + if (!opt_padding) + ImGui::PopStyleVar(); + + if (opt_fullscreen) + ImGui::PopStyleVar(2); + + // Submit the DockSpace + ImGuiIO& io = ImGui::GetIO(); + if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) + { + ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); + ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); + } + else + { + ShowDockingDisabledMessage(); + } + + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Options")) + { + // Disabling fullscreen would allow the window to be moved to the front of other windows, + // which we can't undo at the moment without finer window depth/z control. + ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen); + ImGui::MenuItem("Padding", NULL, &opt_padding); + ImGui::Separator(); + + if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoSplit; } + if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoResize; } + if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; } + if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; } + if (ImGui::MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0, opt_fullscreen)) { dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode; } + ImGui::Separator(); + + if (ImGui::MenuItem("Close", NULL, false, p_open != NULL)) + *p_open = false; + ImGui::EndMenu(); + } + HelpMarker( + "When docking is enabled, you can ALWAYS dock MOST window into another! Try it now!" "\n" + "- Drag from window title bar or their tab to dock/undock." "\n" + "- Drag from window menu button (upper-left button) to undock an entire node (all windows)." "\n" + "- Hold SHIFT to disable docking (if io.ConfigDockingWithShift == false, default)" "\n" + "- Hold SHIFT to enable docking (if io.ConfigDockingWithShift == true)" "\n" + "This demo app has nothing to do with enabling docking!" "\n\n" + "This demo app only demonstrate the use of ImGui::DockSpace() which allows you to manually create a docking node _within_ another window." "\n\n" + "Read comments in ShowExampleAppDockSpace() for more details."); + + ImGui::EndMenuBar(); + } + + ImGui::End(); +} + +//----------------------------------------------------------------------------- +// [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() +//----------------------------------------------------------------------------- + +// Simplified structure to mimic a Document model +struct MyDocument +{ + const char* Name; // Document title + bool Open; // Set when open (we keep an array of all available documents to simplify demo code!) + bool OpenPrev; // Copy of Open from last update. + bool Dirty; // Set when the document has been modified + bool WantClose; // Set when the document + ImVec4 Color; // An arbitrary variable associated to the document + + MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f, 1.0f, 1.0f, 1.0f)) + { + Name = name; + Open = OpenPrev = open; + Dirty = false; + WantClose = false; + Color = color; + } + void DoOpen() { Open = true; } + void DoQueueClose() { WantClose = true; } + void DoForceClose() { Open = false; Dirty = false; } + void DoSave() { Dirty = false; } + + // Display placeholder contents for the Document + static void DisplayContents(MyDocument* doc) + { + ImGui::PushID(doc); + ImGui::Text("Document \"%s\"", doc->Name); + ImGui::PushStyleColor(ImGuiCol_Text, doc->Color); + ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); + ImGui::PopStyleColor(); + if (ImGui::Button("Modify", ImVec2(100, 0))) + doc->Dirty = true; + ImGui::SameLine(); + if (ImGui::Button("Save", ImVec2(100, 0))) + doc->DoSave(); + ImGui::ColorEdit3("color", &doc->Color.x); // Useful to test drag and drop and hold-dragged-to-open-tab behavior. + ImGui::PopID(); + } + + // Display context menu for the Document + static void DisplayContextMenu(MyDocument* doc) + { + if (!ImGui::BeginPopupContextItem()) + return; + + char buf[256]; + sprintf(buf, "Save %s", doc->Name); + if (ImGui::MenuItem(buf, "CTRL+S", false, doc->Open)) + doc->DoSave(); + if (ImGui::MenuItem("Close", "CTRL+W", false, doc->Open)) + doc->DoQueueClose(); + ImGui::EndPopup(); + } +}; + +struct ExampleAppDocuments +{ + ImVector Documents; + + ExampleAppDocuments() + { + Documents.push_back(MyDocument("Lettuce", true, ImVec4(0.4f, 0.8f, 0.4f, 1.0f))); + Documents.push_back(MyDocument("Eggplant", true, ImVec4(0.8f, 0.5f, 1.0f, 1.0f))); + Documents.push_back(MyDocument("Carrot", true, ImVec4(1.0f, 0.8f, 0.5f, 1.0f))); + Documents.push_back(MyDocument("Tomato", false, ImVec4(1.0f, 0.3f, 0.4f, 1.0f))); + Documents.push_back(MyDocument("A Rather Long Title", false)); + Documents.push_back(MyDocument("Some Document", false)); + } +}; + +// [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface. +// If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, +// as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for +// the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has +// disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively +// give the impression of a flicker for one frame. +// We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch. +// Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags_Reorderable flag. +static void NotifyOfDocumentsClosedElsewhere(ExampleAppDocuments& app) +{ + for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) + { + MyDocument* doc = &app.Documents[doc_n]; + if (!doc->Open && doc->OpenPrev) + ImGui::SetTabItemClosed(doc->Name); + doc->OpenPrev = doc->Open; + } +} + +void ShowExampleAppDocuments(bool* p_open) +{ + static ExampleAppDocuments app; + + // Options + enum Target + { + Target_None, + Target_Tab, // Create documents as local tab into a local tab bar + Target_DockSpaceAndWindow // Create documents as regular windows, and create an embedded dockspace + }; + static Target opt_target = Target_Tab; + static bool opt_reorderable = true; + static ImGuiTabBarFlags opt_fitting_flags = ImGuiTabBarFlags_FittingPolicyDefault_; + + // When (opt_target == Target_DockSpaceAndWindow) there is the possibily that one of our child Document window (e.g. "Eggplant") + // that we emit gets docked into the same spot as the parent window ("Example: Documents"). + // This would create a problematic feedback loop because selecting the "Eggplant" tab would make the "Example: Documents" tab + // not visible, which in turn would stop submitting the "Eggplant" window. + // We avoid this problem by submitting our documents window even if our parent window is not currently visible. + // Another solution may be to make the "Example: Documents" window use the ImGuiWindowFlags_NoDocking. + + bool window_contents_visible = ImGui::Begin("Example: Documents", p_open, ImGuiWindowFlags_MenuBar); + if (!window_contents_visible && opt_target != Target_DockSpaceAndWindow) + { + ImGui::End(); + return; + } + + // Menu + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + int open_count = 0; + for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) + open_count += app.Documents[doc_n].Open ? 1 : 0; + + if (ImGui::BeginMenu("Open", open_count < app.Documents.Size)) + { + for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) + { + MyDocument* doc = &app.Documents[doc_n]; + if (!doc->Open) + if (ImGui::MenuItem(doc->Name)) + doc->DoOpen(); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Close All Documents", NULL, false, open_count > 0)) + for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) + app.Documents[doc_n].DoQueueClose(); + if (ImGui::MenuItem("Exit", "Alt+F4")) {} + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + // [Debug] List documents with one checkbox for each + for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) + { + MyDocument* doc = &app.Documents[doc_n]; + if (doc_n > 0) + ImGui::SameLine(); + ImGui::PushID(doc); + if (ImGui::Checkbox(doc->Name, &doc->Open)) + if (!doc->Open) + doc->DoForceClose(); + ImGui::PopID(); + } + ImGui::PushItemWidth(ImGui::GetFontSize() * 12); + ImGui::Combo("Output", (int*)&opt_target, "None\0TabBar+Tabs\0DockSpace+Window\0"); + ImGui::PopItemWidth(); + bool redock_all = false; + if (opt_target == Target_Tab) { ImGui::SameLine(); ImGui::Checkbox("Reorderable Tabs", &opt_reorderable); } + if (opt_target == Target_DockSpaceAndWindow) { ImGui::SameLine(); redock_all = ImGui::Button("Redock all"); } + + ImGui::Separator(); + + // About the ImGuiWindowFlags_UnsavedDocument / ImGuiTabItemFlags_UnsavedDocument flags. + // They have multiple effects: + // - Display a dot next to the title. + // - Tab is selected when clicking the X close button. + // - Closure is not assumed (will wait for user to stop submitting the tab). + // Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + // We need to assume closure by default otherwise waiting for "lack of submission" on the next frame would leave an empty + // hole for one-frame, both in the tab-bar and in tab-contents when closing a tab/window. + // The rarely used SetTabItemClosed() function is a way to notify of programmatic closure to avoid the one-frame hole. + + // Tabs + if (opt_target == Target_Tab) + { + ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0); + if (ImGui::BeginTabBar("##tabs", tab_bar_flags)) + { + if (opt_reorderable) + NotifyOfDocumentsClosedElsewhere(app); + + // [DEBUG] Stress tests + //if ((ImGui::GetFrameCount() % 30) == 0) docs[1].Open ^= 1; // [DEBUG] Automatically show/hide a tab. Test various interactions e.g. dragging with this on. + //if (ImGui::GetIO().KeyCtrl) ImGui::SetTabItemSelected(docs[1].Name); // [DEBUG] Test SetTabItemSelected(), probably not very useful as-is anyway.. + + // Submit Tabs + for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) + { + MyDocument* doc = &app.Documents[doc_n]; + if (!doc->Open) + continue; + + ImGuiTabItemFlags tab_flags = (doc->Dirty ? ImGuiTabItemFlags_UnsavedDocument : 0); + bool visible = ImGui::BeginTabItem(doc->Name, &doc->Open, tab_flags); + + // Cancel attempt to close when unsaved add to save queue so we can display a popup. + if (!doc->Open && doc->Dirty) + { + doc->Open = true; + doc->DoQueueClose(); + } + + MyDocument::DisplayContextMenu(doc); + if (visible) + { + MyDocument::DisplayContents(doc); + ImGui::EndTabItem(); + } + } + + ImGui::EndTabBar(); + } + } + else if (opt_target == Target_DockSpaceAndWindow) + { + if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable) + { + NotifyOfDocumentsClosedElsewhere(app); + + // Create a DockSpace node where any window can be docked + ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); + ImGui::DockSpace(dockspace_id); + + // Create Windows + for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) + { + MyDocument* doc = &app.Documents[doc_n]; + if (!doc->Open) + continue; + + ImGui::SetNextWindowDockID(dockspace_id, redock_all ? ImGuiCond_Always : ImGuiCond_FirstUseEver); + ImGuiWindowFlags window_flags = (doc->Dirty ? ImGuiWindowFlags_UnsavedDocument : 0); + bool visible = ImGui::Begin(doc->Name, &doc->Open, window_flags); + + // Cancel attempt to close when unsaved add to save queue so we can display a popup. + if (!doc->Open && doc->Dirty) + { + doc->Open = true; + doc->DoQueueClose(); + } + + MyDocument::DisplayContextMenu(doc); + if (visible) + MyDocument::DisplayContents(doc); + + ImGui::End(); + } + } + else + { + ShowDockingDisabledMessage(); + } + } + + // Early out other contents + if (!window_contents_visible) + { + ImGui::End(); + return; + } + + // Update closing queue + static ImVector close_queue; + if (close_queue.empty()) + { + // Close queue is locked once we started a popup + for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++) + { + MyDocument* doc = &app.Documents[doc_n]; + if (doc->WantClose) + { + doc->WantClose = false; + close_queue.push_back(doc); + } + } + } + + // Display closing confirmation UI + if (!close_queue.empty()) + { + int close_queue_unsaved_documents = 0; + for (int n = 0; n < close_queue.Size; n++) + if (close_queue[n]->Dirty) + close_queue_unsaved_documents++; + + if (close_queue_unsaved_documents == 0) + { + // Close documents when all are unsaved + for (int n = 0; n < close_queue.Size; n++) + close_queue[n]->DoForceClose(); + close_queue.clear(); + } + else + { + if (!ImGui::IsPopupOpen("Save?")) + ImGui::OpenPopup("Save?"); + if (ImGui::BeginPopupModal("Save?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::Text("Save change to the following items?"); + float item_height = ImGui::GetTextLineHeightWithSpacing(); + if (ImGui::BeginChildFrame(ImGui::GetID("frame"), ImVec2(-FLT_MIN, 6.25f * item_height))) + { + for (int n = 0; n < close_queue.Size; n++) + if (close_queue[n]->Dirty) + ImGui::Text("%s", close_queue[n]->Name); + ImGui::EndChildFrame(); + } + + ImVec2 button_size(ImGui::GetFontSize() * 7.0f, 0.0f); + if (ImGui::Button("Yes", button_size)) + { + for (int n = 0; n < close_queue.Size; n++) + { + if (close_queue[n]->Dirty) + close_queue[n]->DoSave(); + close_queue[n]->DoForceClose(); + } + close_queue.clear(); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button("No", button_size)) + { + for (int n = 0; n < close_queue.Size; n++) + close_queue[n]->DoForceClose(); + close_queue.clear(); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button("Cancel", button_size)) + { + close_queue.clear(); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + } + } + } + + ImGui::End(); +} + +// End of Demo code +#else + +void ImGui::ShowAboutWindow(bool*) {} +void ImGui::ShowDemoWindow(bool*) {} +void ImGui::ShowUserGuide() {} +void ImGui::ShowStyleEditor(ImGuiStyle*) {} + +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/src/editors/xrEUI/imgui_draw.cpp b/src/editors/xrEUI/imgui_draw.cpp new file mode 100644 index 00000000000..5765f25c46f --- /dev/null +++ b/src/editors/xrEUI/imgui_draw.cpp @@ -0,0 +1,7449 @@ +// dear imgui, v1.88 WIP +// (drawing and font code) + +/* + +Index of this file: + +// [SECTION] STB libraries implementation +// [SECTION] Style functions +// [SECTION] ImDrawList +// [SECTION] ImDrawListSplitter +// [SECTION] ImDrawData +// [SECTION] Helpers ShadeVertsXXX functions +// [SECTION] ImFontConfig +// [SECTION] ImFontAtlas +// [SECTION] ImFontAtlas glyph ranges helpers +// [SECTION] ImFontGlyphRangesBuilder +// [SECTION] ImFont +// [SECTION] ImGui Internal Render Helpers +// [SECTION] Decompression code +// [SECTION] Default font data (ProggyClean.ttf) + +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif + +#include "imgui_internal.h" +#ifdef IMGUI_ENABLE_FREETYPE +#include "misc/freetype/imgui_freetype.h" +#endif + +#if !defined(alloca) +#if defined(__GLIBC__) || defined(__sun) || defined(__APPLE__) || defined(__NEWLIB__) +#include // alloca (glibc uses . Note that Cygwin may have _WIN32 defined, so the order matters here) +#elif defined(_WIN32) +#include // alloca +#if !defined(alloca) +#define alloca _alloca // for clang with MS Codegen +#endif +#else +#include // alloca +#endif +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning(disable : 4127) // condition expression is constant +#pragma warning(disable : 4505) // unreferenced local function has been removed (stb stuff) +#pragma warning(disable : 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#pragma warning(disable : 6255) // [Static Analyzer] _alloca indicates failure by raising a stack overflow exception. Consider using _malloca instead. +#pragma warning(disable : 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). +#pragma warning(disable : 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer) +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#if __has_warning("-Walloca") +#pragma clang diagnostic ignored "-Walloca" // warning: use of function '__builtin_alloca' is discouraged +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wstack-protector" // warning: stack protector not protecting local variables: variable length buffer +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif + +//------------------------------------------------------------------------- +// [SECTION] STB libraries implementation (for stb_truetype and stb_rect_pack) +//------------------------------------------------------------------------- + +// Compile time options: +// #define IMGUI_STB_NAMESPACE ImStb +// #define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" +// #define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" +// #define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +// #define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION + +#ifdef IMGUI_STB_NAMESPACE +namespace IMGUI_STB_NAMESPACE +{ +#endif + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4456) // declaration of 'xx' hides previous local declaration +#pragma warning(disable : 6011) // (stb_rectpack) Dereferencing NULL pointer 'cur->next'. +#pragma warning(disable : 6385) // (stb_truetype) Reading invalid data from 'buffer': the readable size is '_Old_3`kernel_width' bytes, but '3' bytes may be read. +#pragma warning(disable : 28182) // (stb_rectpack) Dereferencing NULL pointer. 'cur' contains the same NULL value as 'cur->next' did. +#endif + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" +#pragma clang diagnostic ignored "-Wmissing-prototypes" +#pragma clang diagnostic ignored "-Wimplicit-fallthrough" +#pragma clang diagnostic ignored "-Wcast-qual" // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier +#endif + +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits] +#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers +#endif + +#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) +#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in another compilation unit +#define STBRP_STATIC +#define STBRP_ASSERT(x) \ + do \ + { \ + IM_ASSERT(x); \ + } while (0) +#define STBRP_SORT ImQsort +#define STB_RECT_PACK_IMPLEMENTATION +#endif +#ifdef IMGUI_STB_RECT_PACK_FILENAME +#include IMGUI_STB_RECT_PACK_FILENAME +#else +#include "imstb_rectpack.h" +#endif +#endif + +#ifdef IMGUI_ENABLE_STB_TRUETYPE +#ifndef STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) +#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in another compilation unit +#define STBTT_malloc(x, u) ((void)(u), IM_ALLOC(x)) +#define STBTT_free(x, u) ((void)(u), IM_FREE(x)) +#define STBTT_assert(x) \ + do \ + { \ + IM_ASSERT(x); \ + } while (0) +#define STBTT_fmod(x, y) ImFmod(x, y) +#define STBTT_sqrt(x) ImSqrt(x) +#define STBTT_pow(x, y) ImPow(x, y) +#define STBTT_fabs(x) ImFabs(x) +#define STBTT_ifloor(x) ((int)ImFloorSigned(x)) +#define STBTT_iceil(x) ((int)ImCeil(x)) +#define STBTT_STATIC +#define STB_TRUETYPE_IMPLEMENTATION +#else +#define STBTT_DEF extern +#endif +#ifdef IMGUI_STB_TRUETYPE_FILENAME +#include IMGUI_STB_TRUETYPE_FILENAME +#else +#include "imstb_truetype.h" +#endif +#endif +#endif // IMGUI_ENABLE_STB_TRUETYPE + +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +#ifdef IMGUI_STB_NAMESPACE +} // namespace ImStb +using namespace IMGUI_STB_NAMESPACE; +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Style functions +//----------------------------------------------------------------------------- + +void ImGui::StyleColorsDark(ImGuiStyle *dst) +{ + ImGuiStyle *style = dst ? dst : &ImGui::GetStyle(); + ImVec4 *colors = style->Colors; + + colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); + colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f); + colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_Separator] = colors[ImGuiCol_Border]; + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f); + colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.20f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); + colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_HeaderActive] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f); + colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); + colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); +} + +void ImGui::StyleColorsClassic(ImGuiStyle *dst) +{ + ImGuiStyle *style = dst ? dst : &ImGui::GetStyle(); + ImVec4 *colors = style->Colors; + + colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.50f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f); + colors[ImGuiCol_Border] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.47f, 0.47f, 0.69f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.42f, 0.41f, 0.64f, 0.69f); + colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f); + colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); + colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f); + colors[ImGuiCol_Button] = ImVec4(0.35f, 0.40f, 0.61f, 0.62f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.40f, 0.48f, 0.71f, 0.79f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.46f, 0.54f, 0.80f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); + colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 0.60f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f); + colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.10f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f); + colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f); + colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_Header] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f); + colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); + colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.27f, 0.27f, 0.38f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.45f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.26f, 0.26f, 0.28f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); + colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); +} + +// Those light colors are better suited with a thicker font than the default one + FrameBorder +void ImGui::StyleColorsLight(ImGuiStyle *dst) +{ + ImGuiStyle *style = dst ? dst : &ImGui::GetStyle(); + ImVec4 *colors = style->Colors; + + colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f); + colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.30f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.49f, 0.49f, 0.49f, 0.80f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f); + colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_SliderGrab] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.46f, 0.54f, 0.80f, 0.60f); + colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 0.62f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f); + colors[ImGuiCol_ResizeGrip] = ImVec4(0.35f, 0.35f, 0.35f, 0.17f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f); + colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f); + colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f); + colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f); + colors[ImGuiCol_DockingPreview] = colors[ImGuiCol_Header] * ImVec4(1.0f, 1.0f, 1.0f, 0.7f); + colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); + colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f); + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.78f, 0.87f, 0.98f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.57f, 0.57f, 0.64f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.68f, 0.68f, 0.74f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.30f, 0.30f, 0.30f, 0.09f); + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); + colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImDrawList +//----------------------------------------------------------------------------- + +ImDrawListSharedData::ImDrawListSharedData() +{ + memset(this, 0, sizeof(*this)); + for (int i = 0; i < IM_ARRAYSIZE(ArcFastVtx); i++) + { + const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(ArcFastVtx); + ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a)); + } + ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError); +} + +void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error) +{ + if (CircleSegmentMaxError == max_error) + return; + + IM_ASSERT(max_error > 0.0f); + CircleSegmentMaxError = max_error; + for (int i = 0; i < IM_ARRAYSIZE(CircleSegmentCounts); i++) + { + const float radius = (float)i; + CircleSegmentCounts[i] = (ImU8)((i > 0) ? IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, CircleSegmentMaxError) : IM_DRAWLIST_ARCFAST_SAMPLE_MAX); + } + ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError); +} + +// Initialize before use in a new frame. We always have a command ready in the buffer. +void ImDrawList::_ResetForNewFrame() +{ + // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory. + IM_STATIC_ASSERT(IM_OFFSETOF(ImDrawCmd, ClipRect) == 0); + IM_STATIC_ASSERT(IM_OFFSETOF(ImDrawCmd, TextureId) == sizeof(ImVec4)); + IM_STATIC_ASSERT(IM_OFFSETOF(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID)); + if (_Splitter._Count > 1) + _Splitter.Merge(this); + + CmdBuffer.resize(0); + IdxBuffer.resize(0); + VtxBuffer.resize(0); + Flags = _Data->InitialFlags; + memset(&_CmdHeader, 0, sizeof(_CmdHeader)); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.resize(0); + _TextureIdStack.resize(0); + _Path.resize(0); + _Splitter.Clear(); + CmdBuffer.push_back(ImDrawCmd()); + _FringeScale = 1.0f; +} + +void ImDrawList::_ClearFreeMemory() +{ + CmdBuffer.clear(); + IdxBuffer.clear(); + VtxBuffer.clear(); + Flags = ImDrawListFlags_None; + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.clear(); + _TextureIdStack.clear(); + _Path.clear(); + _Splitter.ClearFreeMemory(); +} + +ImDrawList *ImDrawList::CloneOutput() const +{ + ImDrawList *dst = IM_NEW(ImDrawList(_Data)); + dst->CmdBuffer = CmdBuffer; + dst->IdxBuffer = IdxBuffer; + dst->VtxBuffer = VtxBuffer; + dst->Flags = Flags; + return dst; +} + +void ImDrawList::AddDrawCmd() +{ + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = _CmdHeader.ClipRect; // Same as calling ImDrawCmd_HeaderCopy() + draw_cmd.TextureId = _CmdHeader.TextureId; + draw_cmd.VtxOffset = _CmdHeader.VtxOffset; + draw_cmd.IdxOffset = IdxBuffer.Size; + + IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); + CmdBuffer.push_back(draw_cmd); +} + +// Pop trailing draw command (used before merging or presenting to user) +// Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == NULL +void ImDrawList::_PopUnusedDrawCmd() +{ + if (CmdBuffer.Size == 0) + return; + ImDrawCmd *curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount == 0 && curr_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); +} + +void ImDrawList::AddCallback(ImDrawCallback callback, void *callback_data) +{ + IM_ASSERT_PARANOID(CmdBuffer.Size > 0); + ImDrawCmd *curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + IM_ASSERT(curr_cmd->UserCallback == NULL); + if (curr_cmd->ElemCount != 0) + { + AddDrawCmd(); + curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + } + curr_cmd->UserCallback = callback; + curr_cmd->UserCallbackData = callback_data; + + AddDrawCmd(); // Force a new command after us (see comment below) +} + +// Compare ClipRect, TextureId and VtxOffset with a single memcmp() +#define ImDrawCmd_HeaderSize (IM_OFFSETOF(ImDrawCmd, VtxOffset) + sizeof(unsigned int)) +#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TextureId, VtxOffset +#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TextureId, VtxOffset +#define ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1) (CMD_0->IdxOffset + CMD_0->ElemCount == CMD_1->IdxOffset) + +// Try to merge two last draw commands +void ImDrawList::_TryMergeDrawCmds() +{ + IM_ASSERT_PARANOID(CmdBuffer.Size > 0); + ImDrawCmd *curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + ImDrawCmd *prev_cmd = curr_cmd - 1; + if (ImDrawCmd_HeaderCompare(curr_cmd, prev_cmd) == 0 && ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) && curr_cmd->UserCallback == NULL && prev_cmd->UserCallback == NULL) + { + prev_cmd->ElemCount += curr_cmd->ElemCount; + CmdBuffer.pop_back(); + } +} + +// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. +// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. +void ImDrawList::_OnChangedClipRect() +{ + // If current command is used with different settings we need to add a new command + IM_ASSERT_PARANOID(CmdBuffer.Size > 0); + ImDrawCmd *curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0) + { + AddDrawCmd(); + return; + } + IM_ASSERT(curr_cmd->UserCallback == NULL); + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd *prev_cmd = curr_cmd - 1; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) && prev_cmd->UserCallback == NULL) + { + CmdBuffer.pop_back(); + return; + } + + curr_cmd->ClipRect = _CmdHeader.ClipRect; +} + +void ImDrawList::_OnChangedTextureID() +{ + // If current command is used with different settings we need to add a new command + IM_ASSERT_PARANOID(CmdBuffer.Size > 0); + ImDrawCmd *curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId) + { + AddDrawCmd(); + return; + } + IM_ASSERT(curr_cmd->UserCallback == NULL); + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd *prev_cmd = curr_cmd - 1; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) && prev_cmd->UserCallback == NULL) + { + CmdBuffer.pop_back(); + return; + } + + curr_cmd->TextureId = _CmdHeader.TextureId; +} + +void ImDrawList::_OnChangedVtxOffset() +{ + // We don't need to compare curr_cmd->VtxOffset != _CmdHeader.VtxOffset because we know it'll be different at the time we call this. + _VtxCurrentIdx = 0; + IM_ASSERT_PARANOID(CmdBuffer.Size > 0); + ImDrawCmd *curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + // IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); // See #3349 + if (curr_cmd->ElemCount != 0) + { + AddDrawCmd(); + return; + } + IM_ASSERT(curr_cmd->UserCallback == NULL); + curr_cmd->VtxOffset = _CmdHeader.VtxOffset; +} + +int ImDrawList::_CalcCircleAutoSegmentCount(float radius) const +{ + // Automatic segment count + const int radius_idx = (int)(radius + 0.999999f); // ceil to never reduce accuracy + if (radius_idx < IM_ARRAYSIZE(_Data->CircleSegmentCounts)) + return _Data->CircleSegmentCounts[radius_idx]; // Use cached value + else + return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, _Data->CircleSegmentMaxError); +} + +// Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) +void ImDrawList::PushClipRect(const ImVec2 &cr_min, const ImVec2 &cr_max, bool intersect_with_current_clip_rect) +{ + ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); + if (intersect_with_current_clip_rect) + { + ImVec4 current = _CmdHeader.ClipRect; + if (cr.x < current.x) + cr.x = current.x; + if (cr.y < current.y) + cr.y = current.y; + if (cr.z > current.z) + cr.z = current.z; + if (cr.w > current.w) + cr.w = current.w; + } + cr.z = ImMax(cr.x, cr.z); + cr.w = ImMax(cr.y, cr.w); + + _ClipRectStack.push_back(cr); + _CmdHeader.ClipRect = cr; + _OnChangedClipRect(); +} + +void ImDrawList::PushClipRectFullScreen() +{ + PushClipRect(ImVec2(_Data->ClipRectFullscreen.x, _Data->ClipRectFullscreen.y), ImVec2(_Data->ClipRectFullscreen.z, _Data->ClipRectFullscreen.w)); +} + +void ImDrawList::PopClipRect() +{ + _ClipRectStack.pop_back(); + _CmdHeader.ClipRect = (_ClipRectStack.Size == 0) ? _Data->ClipRectFullscreen : _ClipRectStack.Data[_ClipRectStack.Size - 1]; + _OnChangedClipRect(); +} + +void ImDrawList::PushTextureID(ImTextureID texture_id) +{ + _TextureIdStack.push_back(texture_id); + _CmdHeader.TextureId = texture_id; + _OnChangedTextureID(); +} + +void ImDrawList::PopTextureID() +{ + _TextureIdStack.pop_back(); + _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1]; + _OnChangedTextureID(); +} + +// Reserve space for a number of vertices and indices. +// You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or +// submit the intermediate results. PrimUnreserve() can be used to release unused allocations. +void ImDrawList::PrimReserve(int idx_count, int vtx_count) +{ + // Large mesh support (when enabled) + IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); + if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) + { + // FIXME: In theory we should be testing that vtx_count <64k here. + // In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us + // to not make that check until we rework the text functions to handle clipping and large horizontal lines better. + _CmdHeader.VtxOffset = VtxBuffer.Size; + _OnChangedVtxOffset(); + } + + ImDrawCmd *draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + draw_cmd->ElemCount += idx_count; + + int vtx_buffer_old_size = VtxBuffer.Size; + VtxBuffer.resize(vtx_buffer_old_size + vtx_count); + _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size; + + int idx_buffer_old_size = IdxBuffer.Size; + IdxBuffer.resize(idx_buffer_old_size + idx_count); + _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size; +} + +// Release the a number of reserved vertices/indices from the end of the last reservation made with PrimReserve(). +void ImDrawList::PrimUnreserve(int idx_count, int vtx_count) +{ + IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); + + ImDrawCmd *draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + draw_cmd->ElemCount -= idx_count; + VtxBuffer.shrink(VtxBuffer.Size - vtx_count); + IdxBuffer.shrink(IdxBuffer.Size - idx_count); +} + +// Fully unrolled with inline call to keep our debug builds decently fast. +void ImDrawList::PrimRect(const ImVec2 &a, const ImVec2 &c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv(_Data->TexUvWhitePixel); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; + _IdxWritePtr[1] = (ImDrawIdx)(idx + 1); + _IdxWritePtr[2] = (ImDrawIdx)(idx + 2); + _IdxWritePtr[3] = idx; + _IdxWritePtr[4] = (ImDrawIdx)(idx + 2); + _IdxWritePtr[5] = (ImDrawIdx)(idx + 3); + _VtxWritePtr[0].pos = a; + _VtxWritePtr[0].uv = uv; + _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; + _VtxWritePtr[1].uv = uv; + _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; + _VtxWritePtr[2].uv = uv; + _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; + _VtxWritePtr[3].uv = uv; + _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimRectUV(const ImVec2 &a, const ImVec2 &c, const ImVec2 &uv_a, const ImVec2 &uv_c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; + _IdxWritePtr[1] = (ImDrawIdx)(idx + 1); + _IdxWritePtr[2] = (ImDrawIdx)(idx + 2); + _IdxWritePtr[3] = idx; + _IdxWritePtr[4] = (ImDrawIdx)(idx + 2); + _IdxWritePtr[5] = (ImDrawIdx)(idx + 3); + _VtxWritePtr[0].pos = a; + _VtxWritePtr[0].uv = uv_a; + _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; + _VtxWritePtr[1].uv = uv_b; + _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; + _VtxWritePtr[2].uv = uv_c; + _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; + _VtxWritePtr[3].uv = uv_d; + _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimQuadUV(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &d, const ImVec2 &uv_a, const ImVec2 &uv_b, const ImVec2 &uv_c, const ImVec2 &uv_d, ImU32 col) +{ + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; + _IdxWritePtr[1] = (ImDrawIdx)(idx + 1); + _IdxWritePtr[2] = (ImDrawIdx)(idx + 2); + _IdxWritePtr[3] = idx; + _IdxWritePtr[4] = (ImDrawIdx)(idx + 2); + _IdxWritePtr[5] = (ImDrawIdx)(idx + 3); + _VtxWritePtr[0].pos = a; + _VtxWritePtr[0].uv = uv_a; + _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; + _VtxWritePtr[1].uv = uv_b; + _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; + _VtxWritePtr[2].uv = uv_c; + _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; + _VtxWritePtr[3].uv = uv_d; + _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +// On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds. +// - Those macros expects l-values and need to be used as their own statement. +// - Those macros are intentionally not surrounded by the 'do {} while (0)' idiom because even that translates to runtime with debug compilers. +#define IM_NORMALIZE2F_OVER_ZERO(VX, VY) \ + { \ + float d2 = VX * VX + VY * VY; \ + if (d2 > 0.0f) \ + { \ + float inv_len = ImRsqrt(d2); \ + VX *= inv_len; \ + VY *= inv_len; \ + } \ + } \ + (void)0 +#define IM_FIXNORMAL2F_MAX_INVLEN2 100.0f // 500.0f (see #4053, #3366) +#define IM_FIXNORMAL2F(VX, VY) \ + { \ + float d2 = VX * VX + VY * VY; \ + if (d2 > 0.000001f) \ + { \ + float inv_len2 = 1.0f / d2; \ + if (inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2) \ + inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2; \ + VX *= inv_len2; \ + VY *= inv_len2; \ + } \ + } \ + (void)0 + +// TODO: Thickness anti-aliased lines cap are missing their AA fringe. +// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds. +void ImDrawList::AddPolyline(const ImVec2 *points, const int points_count, ImU32 col, ImDrawFlags flags, float thickness) +{ + if (points_count < 2) + return; + + const bool closed = (flags & ImDrawFlags_Closed) != 0; + const ImVec2 opaque_uv = _Data->TexUvWhitePixel; + const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw + const bool thick_line = (thickness > _FringeScale); + + if (Flags & ImDrawListFlags_AntiAliasedLines) + { + // Anti-aliased stroke + const float AA_SIZE = _FringeScale; + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + + // Thicknesses <1.0 should behave like thickness 1.0 + thickness = ImMax(thickness, 1.0f); + const int integer_thickness = (int)thickness; + const float fractional_thickness = thickness - integer_thickness; + + // Do we want to draw this line using a texture? + // - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved. + // - If AA_SIZE is not 1.0f we cannot use the texture path. + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f); + + // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTex unless ImFontAtlasFlags_NoBakedLines is off + IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)); + + const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12); + const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); + PrimReserve(idx_count, vtx_count); + + // Temporary buffer + // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point + ImVec2 *temp_normals = (ImVec2 *)alloca(points_count * ((use_texture || !thick_line) ? 3 : 5) * sizeof(ImVec2)); //-V630 + ImVec2 *temp_points = temp_normals + points_count; + + // Calculate normals (tangents) for each line segment + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; + float dx = points[i2].x - points[i1].x; + float dy = points[i2].y - points[i1].y; + IM_NORMALIZE2F_OVER_ZERO(dx, dy); + temp_normals[i1].x = dy; + temp_normals[i1].y = -dx; + } + if (!closed) + temp_normals[points_count - 1] = temp_normals[points_count - 2]; + + // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point + if (use_texture || !thick_line) + { + // [PATH 1] Texture-based lines (thick or non-thick) + // [PATH 2] Non texture-based lines (non-thick) + + // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus "one pixel" for AA. + // - In the texture-based path, we don't use AA_SIZE here because the +1 is tied to the generated texture + // (see ImFontAtlasBuildRenderLinesTexData() function), and so alternate values won't work without changes to that code. + // - In the non texture-based paths, we would allow AA_SIZE to potentially be != 1.0f with a patch (e.g. fringe_scale patch to + // allow scaling geometry while preserving one-screen-pixel AA fringe). + const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE; + + // If line is not closed, the first and last points need to be generated differently as there are no normals to blend + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * half_draw_size; + temp_points[1] = points[0] - temp_normals[0] * half_draw_size; + temp_points[(points_count - 1) * 2 + 0] = points[points_count - 1] + temp_normals[points_count - 1] * half_draw_size; + temp_points[(points_count - 1) * 2 + 1] = points[points_count - 1] - temp_normals[points_count - 1] * half_draw_size; + } + + // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges + // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment + for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment + { + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment + const unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment + + // Average normals + float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; + float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; + IM_FIXNORMAL2F(dm_x, dm_y); + dm_x *= half_draw_size; // dm_x, dm_y are offset to the outer edge of the AA area + dm_y *= half_draw_size; + + // Add temporary vertexes for the outer edges + ImVec2 *out_vtx = &temp_points[i2 * 2]; + out_vtx[0].x = points[i2].x + dm_x; + out_vtx[0].y = points[i2].y + dm_y; + out_vtx[1].x = points[i2].x - dm_x; + out_vtx[1].y = points[i2].y - dm_y; + + if (use_texture) + { + // Add indices for two triangles + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); + _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); + _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri + _IdxWritePtr[3] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[4] = (ImDrawIdx)(idx1 + 1); + _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Left tri + _IdxWritePtr += 6; + } + else + { + // Add indexes for four triangles + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); + _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); + _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); // Right tri 1 + _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); + _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); + _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Right tri 2 + _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); + _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); // Left tri 1 + _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); + _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); + _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); // Left tri 2 + _IdxWritePtr += 12; + } + + idx1 = idx2; + } + + // Add vertexes for each point on the line + if (use_texture) + { + // If we're using textures we only need to emit the left/right edge vertices + ImVec4 tex_uvs = _Data->TexUvLines[integer_thickness]; + /*if (fractional_thickness != 0.0f) // Currently always zero when use_texture==false! + { + const ImVec4 tex_uvs_1 = _Data->TexUvLines[integer_thickness + 1]; + tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp() + tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness; + tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness; + tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness; + }*/ + ImVec2 tex_uv0(tex_uvs.x, tex_uvs.y); + ImVec2 tex_uv1(tex_uvs.z, tex_uvs.w); + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; + _VtxWritePtr[0].uv = tex_uv0; + _VtxWritePtr[0].col = col; // Left-side outer edge + _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; + _VtxWritePtr[1].uv = tex_uv1; + _VtxWritePtr[1].col = col; // Right-side outer edge + _VtxWritePtr += 2; + } + } + else + { + // If we're not using a texture, we need the center vertex as well + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = points[i]; + _VtxWritePtr[0].uv = opaque_uv; + _VtxWritePtr[0].col = col; // Center of line + _VtxWritePtr[1].pos = temp_points[i * 2 + 0]; + _VtxWritePtr[1].uv = opaque_uv; + _VtxWritePtr[1].col = col_trans; // Left-side outer edge + _VtxWritePtr[2].pos = temp_points[i * 2 + 1]; + _VtxWritePtr[2].uv = opaque_uv; + _VtxWritePtr[2].col = col_trans; // Right-side outer edge + _VtxWritePtr += 3; + } + } + } + else + { + // [PATH 2] Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point + const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; + + // If line is not closed, the first and last points need to be generated differently as there are no normals to blend + if (!closed) + { + const int points_last = points_count - 1; + temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); + temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); + temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[points_last * 4 + 0] = points[points_last] + temp_normals[points_last] * (half_inner_thickness + AA_SIZE); + temp_points[points_last * 4 + 1] = points[points_last] + temp_normals[points_last] * (half_inner_thickness); + temp_points[points_last * 4 + 2] = points[points_last] - temp_normals[points_last] * (half_inner_thickness); + temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE); + } + + // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges + // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment + for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment + { + const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment + const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment + + // Average normals + float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; + float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; + IM_FIXNORMAL2F(dm_x, dm_y); + float dm_out_x = dm_x * (half_inner_thickness + AA_SIZE); + float dm_out_y = dm_y * (half_inner_thickness + AA_SIZE); + float dm_in_x = dm_x * half_inner_thickness; + float dm_in_y = dm_y * half_inner_thickness; + + // Add temporary vertices + ImVec2 *out_vtx = &temp_points[i2 * 4]; + out_vtx[0].x = points[i2].x + dm_out_x; + out_vtx[0].y = points[i2].y + dm_out_y; + out_vtx[1].x = points[i2].x + dm_in_x; + out_vtx[1].y = points[i2].y + dm_in_y; + out_vtx[2].x = points[i2].x - dm_in_x; + out_vtx[2].y = points[i2].y - dm_in_y; + out_vtx[3].x = points[i2].x - dm_out_x; + out_vtx[3].y = points[i2].y - dm_out_y; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 1); + _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); + _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); + _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); + _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); + _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); + _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[12] = (ImDrawIdx)(idx2 + 2); + _IdxWritePtr[13] = (ImDrawIdx)(idx1 + 2); + _IdxWritePtr[14] = (ImDrawIdx)(idx1 + 3); + _IdxWritePtr[15] = (ImDrawIdx)(idx1 + 3); + _IdxWritePtr[16] = (ImDrawIdx)(idx2 + 3); + _IdxWritePtr[17] = (ImDrawIdx)(idx2 + 2); + _IdxWritePtr += 18; + + idx1 = idx2; + } + + // Add vertices + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i * 4 + 0]; + _VtxWritePtr[0].uv = opaque_uv; + _VtxWritePtr[0].col = col_trans; + _VtxWritePtr[1].pos = temp_points[i * 4 + 1]; + _VtxWritePtr[1].uv = opaque_uv; + _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = temp_points[i * 4 + 2]; + _VtxWritePtr[2].uv = opaque_uv; + _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = temp_points[i * 4 + 3]; + _VtxWritePtr[3].uv = opaque_uv; + _VtxWritePtr[3].col = col_trans; + _VtxWritePtr += 4; + } + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // [PATH 4] Non texture-based, Non anti-aliased lines + const int idx_count = count * 6; + const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges + PrimReserve(idx_count, vtx_count); + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; + const ImVec2 &p1 = points[i1]; + const ImVec2 &p2 = points[i2]; + + float dx = p2.x - p1.x; + float dy = p2.y - p1.y; + IM_NORMALIZE2F_OVER_ZERO(dx, dy); + dx *= (thickness * 0.5f); + dy *= (thickness * 0.5f); + + _VtxWritePtr[0].pos.x = p1.x + dy; + _VtxWritePtr[0].pos.y = p1.y - dx; + _VtxWritePtr[0].uv = opaque_uv; + _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos.x = p2.x + dy; + _VtxWritePtr[1].pos.y = p2.y - dx; + _VtxWritePtr[1].uv = opaque_uv; + _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos.x = p2.x - dy; + _VtxWritePtr[2].pos.y = p2.y + dx; + _VtxWritePtr[2].uv = opaque_uv; + _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos.x = p1.x - dy; + _VtxWritePtr[3].pos.y = p1.y + dx; + _VtxWritePtr[3].uv = opaque_uv; + _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); + _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + 1); + _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + 2); + _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); + _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx + 2); + _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx + 3); + _IdxWritePtr += 6; + _VtxCurrentIdx += 4; + } + } +} + +// - We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds. +// - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. +void ImDrawList::AddConvexPolyFilled(const ImVec2 *points, const int points_count, ImU32 col) +{ + if (points_count < 3) + return; + + const ImVec2 uv = _Data->TexUvWhitePixel; + + if (Flags & ImDrawListFlags_AntiAliasedFill) + { + // Anti-aliased Fill + const float AA_SIZE = _FringeScale; + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + const int idx_count = (points_count - 2) * 3 + points_count * 6; + const int vtx_count = (points_count * 2); + PrimReserve(idx_count, vtx_count); + + // Add indexes for fill + unsigned int vtx_inner_idx = _VtxCurrentIdx; + unsigned int vtx_outer_idx = _VtxCurrentIdx + 1; + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); + _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + ((i - 1) << 1)); + _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (i << 1)); + _IdxWritePtr += 3; + } + + // Compute normals + ImVec2 *temp_normals = (ImVec2 *)alloca(points_count * sizeof(ImVec2)); //-V630 + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + { + const ImVec2 &p0 = points[i0]; + const ImVec2 &p1 = points[i1]; + float dx = p1.x - p0.x; + float dy = p1.y - p0.y; + IM_NORMALIZE2F_OVER_ZERO(dx, dy); + temp_normals[i0].x = dy; + temp_normals[i0].y = -dx; + } + + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2 &n0 = temp_normals[i0]; + const ImVec2 &n1 = temp_normals[i1]; + float dm_x = (n0.x + n1.x) * 0.5f; + float dm_y = (n0.y + n1.y) * 0.5f; + IM_FIXNORMAL2F(dm_x, dm_y); + dm_x *= AA_SIZE * 0.5f; + dm_y *= AA_SIZE * 0.5f; + + // Add vertices + _VtxWritePtr[0].pos.x = (points[i1].x - dm_x); + _VtxWritePtr[0].pos.y = (points[i1].y - dm_y); + _VtxWritePtr[0].uv = uv; + _VtxWritePtr[0].col = col; // Inner + _VtxWritePtr[1].pos.x = (points[i1].x + dm_x); + _VtxWritePtr[1].pos.y = (points[i1].y + dm_y); + _VtxWritePtr[1].uv = uv; + _VtxWritePtr[1].col = col_trans; // Outer + _VtxWritePtr += 2; + + // Add indexes for fringes + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); + _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); + _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); + _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); + _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); + _IdxWritePtr += 6; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Fill + const int idx_count = (points_count - 2) * 3; + const int vtx_count = points_count; + PrimReserve(idx_count, vtx_count); + for (int i = 0; i < vtx_count; i++) + { + _VtxWritePtr[0].pos = points[i]; + _VtxWritePtr[0].uv = uv; + _VtxWritePtr[0].col = col; + _VtxWritePtr++; + } + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); + _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + i - 1); + _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + i); + _IdxWritePtr += 3; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } +} + +void ImDrawList::_PathArcToFastEx(const ImVec2 ¢er, float radius, int a_min_sample, int a_max_sample, int a_step) +{ + if (radius < 0.5f) + { + _Path.push_back(center); + return; + } + + // Calculate arc auto segment step size + if (a_step <= 0) + a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(radius); + + // Make sure we never do steps larger than one quarter of the circle + a_step = ImClamp(a_step, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); + + const int sample_range = ImAbs(a_max_sample - a_min_sample); + const int a_next_step = a_step; + + int samples = sample_range + 1; + bool extra_max_sample = false; + if (a_step > 1) + { + samples = sample_range / a_step + 1; + const int overstep = sample_range % a_step; + + if (overstep > 0) + { + extra_max_sample = true; + samples++; + + // When we have overstep to avoid awkwardly looking one long line and one tiny one at the end, + // distribute first step range evenly between them by reducing first step size. + if (sample_range > 0) + a_step -= (a_step - overstep) / 2; + } + } + + _Path.resize(_Path.Size + samples); + ImVec2 *out_ptr = _Path.Data + (_Path.Size - samples); + + int sample_index = a_min_sample; + if (sample_index < 0 || sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX) + { + sample_index = sample_index % IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + if (sample_index < 0) + sample_index += IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + } + + if (a_max_sample >= a_min_sample) + { + for (int a = a_min_sample; a <= a_max_sample; a += a_step, sample_index += a_step, a_step = a_next_step) + { + // a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more + if (sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX) + sample_index -= IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + + const ImVec2 s = _Data->ArcFastVtx[sample_index]; + out_ptr->x = center.x + s.x * radius; + out_ptr->y = center.y + s.y * radius; + out_ptr++; + } + } + else + { + for (int a = a_min_sample; a >= a_max_sample; a -= a_step, sample_index -= a_step, a_step = a_next_step) + { + // a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more + if (sample_index < 0) + sample_index += IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + + const ImVec2 s = _Data->ArcFastVtx[sample_index]; + out_ptr->x = center.x + s.x * radius; + out_ptr->y = center.y + s.y * radius; + out_ptr++; + } + } + + if (extra_max_sample) + { + int normalized_max_sample = a_max_sample % IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + if (normalized_max_sample < 0) + normalized_max_sample += IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + + const ImVec2 s = _Data->ArcFastVtx[normalized_max_sample]; + out_ptr->x = center.x + s.x * radius; + out_ptr->y = center.y + s.y * radius; + out_ptr++; + } + + IM_ASSERT_PARANOID(_Path.Data + _Path.Size == out_ptr); +} + +void ImDrawList::_PathArcToN(const ImVec2 ¢er, float radius, float a_min, float a_max, int num_segments) +{ + if (radius < 0.5f) + { + _Path.push_back(center); + return; + } + + // Note that we are adding a point at both a_min and a_max. + // If you are trying to draw a full closed circle you don't want the overlapping points! + _Path.reserve(_Path.Size + (num_segments + 1)); + for (int i = 0; i <= num_segments; i++) + { + const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min); + _Path.push_back(ImVec2(center.x + ImCos(a) * radius, center.y + ImSin(a) * radius)); + } +} + +// 0: East, 3: South, 6: West, 9: North, 12: East +void ImDrawList::PathArcToFast(const ImVec2 ¢er, float radius, int a_min_of_12, int a_max_of_12) +{ + if (radius < 0.5f) + { + _Path.push_back(center); + return; + } + _PathArcToFastEx(center, radius, a_min_of_12 * IM_DRAWLIST_ARCFAST_SAMPLE_MAX / 12, a_max_of_12 * IM_DRAWLIST_ARCFAST_SAMPLE_MAX / 12, 0); +} + +void ImDrawList::PathArcTo(const ImVec2 ¢er, float radius, float a_min, float a_max, int num_segments) +{ + if (radius < 0.5f) + { + _Path.push_back(center); + return; + } + + if (num_segments > 0) + { + _PathArcToN(center, radius, a_min, a_max, num_segments); + return; + } + + // Automatic segment count + if (radius <= _Data->ArcFastRadiusCutoff) + { + const bool a_is_reverse = a_max < a_min; + + // We are going to use precomputed values for mid samples. + // Determine first and last sample in lookup table that belong to the arc. + const float a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0f); + const float a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0f); + + const int a_min_sample = a_is_reverse ? (int)ImFloorSigned(a_min_sample_f) : (int)ImCeil(a_min_sample_f); + const int a_max_sample = a_is_reverse ? (int)ImCeil(a_max_sample_f) : (int)ImFloorSigned(a_max_sample_f); + const int a_mid_samples = a_is_reverse ? ImMax(a_min_sample - a_max_sample, 0) : ImMax(a_max_sample - a_min_sample, 0); + + const float a_min_segment_angle = a_min_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + const float a_max_segment_angle = a_max_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX; + const bool a_emit_start = ImAbs(a_min_segment_angle - a_min) >= 1e-5f; + const bool a_emit_end = ImAbs(a_max - a_max_segment_angle) >= 1e-5f; + + _Path.reserve(_Path.Size + (a_mid_samples + 1 + (a_emit_start ? 1 : 0) + (a_emit_end ? 1 : 0))); + if (a_emit_start) + _Path.push_back(ImVec2(center.x + ImCos(a_min) * radius, center.y + ImSin(a_min) * radius)); + if (a_mid_samples > 0) + _PathArcToFastEx(center, radius, a_min_sample, a_max_sample, 0); + if (a_emit_end) + _Path.push_back(ImVec2(center.x + ImCos(a_max) * radius, center.y + ImSin(a_max) * radius)); + } + else + { + const float arc_length = ImAbs(a_max - a_min); + const int circle_segment_count = _CalcCircleAutoSegmentCount(radius); + const int arc_segment_count = ImMax((int)ImCeil(circle_segment_count * arc_length / (IM_PI * 2.0f)), (int)(2.0f * IM_PI / arc_length)); + _PathArcToN(center, radius, a_min, a_max, arc_segment_count); + } +} + +ImVec2 ImBezierCubicCalc(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, float t) +{ + float u = 1.0f - t; + float w1 = u * u * u; + float w2 = 3 * u * u * t; + float w3 = 3 * u * t * t; + float w4 = t * t * t; + return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x, w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y); +} + +ImVec2 ImBezierQuadraticCalc(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, float t) +{ + float u = 1.0f - t; + float w1 = u * u; + float w2 = 2 * u * t; + float w3 = t * t; + return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x, w1 * p1.y + w2 * p2.y + w3 * p3.y); +} + +// Closely mimics ImBezierCubicClosestPointCasteljau() in imgui.cpp +static void PathBezierCubicCurveToCasteljau(ImVector *path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) +{ + float dx = x4 - x1; + float dy = y4 - y1; + float d2 = (x2 - x4) * dy - (y2 - y4) * dx; + float d3 = (x3 - x4) * dy - (y3 - y4) * dx; + d2 = (d2 >= 0) ? d2 : -d2; + d3 = (d3 >= 0) ? d3 : -d3; + if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy)) + { + path->push_back(ImVec2(x4, y4)); + } + else if (level < 10) + { + float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f; + float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f; + float x34 = (x3 + x4) * 0.5f, y34 = (y3 + y4) * 0.5f; + float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f; + float x234 = (x23 + x34) * 0.5f, y234 = (y23 + y34) * 0.5f; + float x1234 = (x123 + x234) * 0.5f, y1234 = (y123 + y234) * 0.5f; + PathBezierCubicCurveToCasteljau(path, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1); + PathBezierCubicCurveToCasteljau(path, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1); + } +} + +static void PathBezierQuadraticCurveToCasteljau(ImVector *path, float x1, float y1, float x2, float y2, float x3, float y3, float tess_tol, int level) +{ + float dx = x3 - x1, dy = y3 - y1; + float det = (x2 - x3) * dy - (y2 - y3) * dx; + if (det * det * 4.0f < tess_tol * (dx * dx + dy * dy)) + { + path->push_back(ImVec2(x3, y3)); + } + else if (level < 10) + { + float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f; + float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f; + float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f; + PathBezierQuadraticCurveToCasteljau(path, x1, y1, x12, y12, x123, y123, tess_tol, level + 1); + PathBezierQuadraticCurveToCasteljau(path, x123, y123, x23, y23, x3, y3, tess_tol, level + 1); + } +} + +void ImDrawList::PathBezierCubicCurveTo(const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, int num_segments) +{ + ImVec2 p1 = _Path.back(); + if (num_segments == 0) + { + PathBezierCubicCurveToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, _Data->CurveTessellationTol, 0); // Auto-tessellated + } + else + { + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + _Path.push_back(ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step)); + } +} + +void ImDrawList::PathBezierQuadraticCurveTo(const ImVec2 &p2, const ImVec2 &p3, int num_segments) +{ + ImVec2 p1 = _Path.back(); + if (num_segments == 0) + { + PathBezierQuadraticCurveToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, _Data->CurveTessellationTol, 0); // Auto-tessellated + } + else + { + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + _Path.push_back(ImBezierQuadraticCalc(p1, p2, p3, t_step * i_step)); + } +} + +IM_STATIC_ASSERT(ImDrawFlags_RoundCornersTopLeft == (1 << 4)); +static inline ImDrawFlags FixRectCornerFlags(ImDrawFlags flags) +{ +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // Legacy Support for hard coded ~0 (used to be a suggested equivalent to ImDrawCornerFlags_All) + // ~0 --> ImDrawFlags_RoundCornersAll or 0 + if (flags == ~0) + return ImDrawFlags_RoundCornersAll; + + // Legacy Support for hard coded 0x01 to 0x0F (matching 15 out of 16 old flags combinations) + // 0x01 --> ImDrawFlags_RoundCornersTopLeft (VALUE 0x01 OVERLAPS ImDrawFlags_Closed but ImDrawFlags_Closed is never valid in this path!) + // 0x02 --> ImDrawFlags_RoundCornersTopRight + // 0x03 --> ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight + // 0x04 --> ImDrawFlags_RoundCornersBotLeft + // 0x05 --> ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBotLeft + // ... + // 0x0F --> ImDrawFlags_RoundCornersAll or 0 + // (See all values in ImDrawCornerFlags_) + if (flags >= 0x01 && flags <= 0x0F) + return (flags << 4); + + // We cannot support hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundCornersNone or use 'float rounding = 0.0f' +#endif + + // If this triggers, please update your code replacing hardcoded values with new ImDrawFlags_RoundCorners* values. + // Note that ImDrawFlags_Closed (== 0x01) is an invalid flag for AddRect(), AddRectFilled(), PathRect() etc... + IM_ASSERT((flags & 0x0F) == 0 && "Misuse of legacy hardcoded ImDrawCornerFlags values!"); + + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags |= ImDrawFlags_RoundCornersAll; + + return flags; +} + +void ImDrawList::PathRect(const ImVec2 &a, const ImVec2 &b, float rounding, ImDrawFlags flags) +{ + flags = FixRectCornerFlags(flags); + rounding = ImMin(rounding, ImFabs(b.x - a.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(b.y - a.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); + + if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + PathLineTo(a); + PathLineTo(ImVec2(b.x, a.y)); + PathLineTo(b); + PathLineTo(ImVec2(a.x, b.y)); + } + else + { + const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? rounding : 0.0f; + const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? rounding : 0.0f; + const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? rounding : 0.0f; + const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? rounding : 0.0f; + PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9); + PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12); + PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3); + PathArcToFast(ImVec2(a.x + rounding_bl, b.y - rounding_bl), rounding_bl, 3, 6); + } +} + +void ImDrawList::AddLine(const ImVec2 &p1, const ImVec2 &p2, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + PathLineTo(p1 + ImVec2(0.5f, 0.5f)); + PathLineTo(p2 + ImVec2(0.5f, 0.5f)); + PathStroke(col, 0, thickness); +} + +// p_min = upper-left, p_max = lower-right +// Note we don't render 1 pixels sized rectangles properly. +void ImDrawList::AddRect(const ImVec2 &p_min, const ImVec2 &p_max, ImU32 col, float rounding, ImDrawFlags flags, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + if (Flags & ImDrawListFlags_AntiAliasedLines) + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags); + else + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. + PathStroke(col, ImDrawFlags_Closed, thickness); +} + +void ImDrawList::AddRectFilled(const ImVec2 &p_min, const ImVec2 &p_max, ImU32 col, float rounding, ImDrawFlags flags) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + PrimReserve(6, 4); + PrimRect(p_min, p_max, col); + } + else + { + PathRect(p_min, p_max, rounding, flags); + PathFillConvex(col); + } +} + +// p_min = upper-left, p_max = lower-right +void ImDrawList::AddRectFilledMultiColor(const ImVec2 &p_min, const ImVec2 &p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) +{ + if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0) + return; + + const ImVec2 uv = _Data->TexUvWhitePixel; + PrimReserve(6, 4); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 1)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 3)); + PrimWriteVtx(p_min, uv, col_upr_left); + PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv, col_upr_right); + PrimWriteVtx(p_max, uv, col_bot_right); + PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left); +} + +void ImDrawList::AddQuad(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathLineTo(p4); + PathStroke(col, ImDrawFlags_Closed, thickness); +} + +void ImDrawList::AddQuadFilled(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathLineTo(p4); + PathFillConvex(col); +} + +void ImDrawList::AddTriangle(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathStroke(col, ImDrawFlags_Closed, thickness); +} + +void ImDrawList::AddTriangleFilled(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathFillConvex(col); +} + +void ImDrawList::AddCircle(const ImVec2 ¢er, float radius, ImU32 col, int num_segments, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f) + return; + + if (num_segments <= 0) + { + // Use arc with automatic segment count + _PathArcToFastEx(center, radius - 0.5f, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); + _Path.Size--; + } + else + { + // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes) + num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX); + + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1); + } + + PathStroke(col, ImDrawFlags_Closed, thickness); +} + +void ImDrawList::AddCircleFilled(const ImVec2 ¢er, float radius, ImU32 col, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f) + return; + + if (num_segments <= 0) + { + // Use arc with automatic segment count + _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); + _Path.Size--; + } + else + { + // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes) + num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX); + + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); + } + + PathFillConvex(col); +} + +// Guaranteed to honor 'num_segments' +void ImDrawList::AddNgon(const ImVec2 ¢er, float radius, ImU32 col, int num_segments, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) + return; + + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1); + PathStroke(col, ImDrawFlags_Closed, thickness); +} + +// Guaranteed to honor 'num_segments' +void ImDrawList::AddNgonFilled(const ImVec2 ¢er, float radius, ImU32 col, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) + return; + + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); + PathFillConvex(col); +} + +// Cubic Bezier takes 4 controls points +void ImDrawList::AddBezierCubic(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, ImU32 col, float thickness, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathBezierCubicCurveTo(p2, p3, p4, num_segments); + PathStroke(col, 0, thickness); +} + +// Quadratic Bezier takes 3 controls points +void ImDrawList::AddBezierQuadratic(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, ImU32 col, float thickness, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(p1); + PathBezierQuadraticCurveTo(p2, p3, num_segments); + PathStroke(col, 0, thickness); +} + +void ImDrawList::AddText(const ImFont *font, float font_size, const ImVec2 &pos, ImU32 col, const char *text_begin, const char *text_end, float wrap_width, const ImVec4 *cpu_fine_clip_rect) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + if (text_end == NULL) + text_end = text_begin + strlen(text_begin); + if (text_begin == text_end) + return; + + // Pull default font/size from the shared ImDrawListSharedData instance + if (font == NULL) + font = _Data->Font; + if (font_size == 0.0f) + font_size = _Data->FontSize; + + IM_ASSERT(font->ContainerAtlas->TexID == _CmdHeader.TextureId); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. + + ImVec4 clip_rect = _CmdHeader.ClipRect; + if (cpu_fine_clip_rect) + { + clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); + clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y); + clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); + clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); + } + font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL); +} + +void ImDrawList::AddText(const ImVec2 &pos, ImU32 col, const char *text_begin, const char *text_end) +{ + AddText(NULL, 0.0f, pos, col, text_begin, text_end); +} + +void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2 &p_min, const ImVec2 &p_max, const ImVec2 &uv_min, const ImVec2 &uv_max, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; + if (push_texture_id) + PushTextureID(user_texture_id); + + PrimReserve(6, 4); + PrimRectUV(p_min, p_max, uv_min, uv_max, col); + + if (push_texture_id) + PopTextureID(); +} + +void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, const ImVec2 &uv1, const ImVec2 &uv2, const ImVec2 &uv3, const ImVec2 &uv4, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; + if (push_texture_id) + PushTextureID(user_texture_id); + + PrimReserve(6, 4); + PrimQuadUV(p1, p2, p3, p4, uv1, uv2, uv3, uv4, col); + + if (push_texture_id) + PopTextureID(); +} + +void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2 &p_min, const ImVec2 &p_max, const ImVec2 &uv_min, const ImVec2 &uv_max, ImU32 col, float rounding, ImDrawFlags flags) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + flags = FixRectCornerFlags(flags); + if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + AddImage(user_texture_id, p_min, p_max, uv_min, uv_max, col); + return; + } + + const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; + if (push_texture_id) + PushTextureID(user_texture_id); + + int vert_start_idx = VtxBuffer.Size; + PathRect(p_min, p_max, rounding, flags); + PathFillConvex(col); + int vert_end_idx = VtxBuffer.Size; + ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true); + + if (push_texture_id) + PopTextureID(); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImDrawListSplitter +//----------------------------------------------------------------------------- +// FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. +//----------------------------------------------------------------------------- + +void ImDrawListSplitter::ClearFreeMemory() +{ + for (int i = 0; i < _Channels.Size; i++) + { + if (i == _Current) + memset(&_Channels[i], 0, sizeof(_Channels[i])); // Current channel is a copy of CmdBuffer/IdxBuffer, don't destruct again + _Channels[i]._CmdBuffer.clear(); + _Channels[i]._IdxBuffer.clear(); + } + _Current = 0; + _Count = 1; + _Channels.clear(); +} + +void ImDrawListSplitter::Split(ImDrawList *draw_list, int channels_count) +{ + IM_UNUSED(draw_list); + IM_ASSERT(_Current == 0 && _Count <= 1 && "Nested channel splitting is not supported. Please use separate instances of ImDrawListSplitter."); + int old_channels_count = _Channels.Size; + if (old_channels_count < channels_count) + { + _Channels.reserve(channels_count); // Avoid over reserving since this is likely to stay stable + _Channels.resize(channels_count); + } + _Count = channels_count; + + // Channels[] (24/32 bytes each) hold storage that we'll swap with draw_list->_CmdBuffer/_IdxBuffer + // The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + // When we switch to the next channel, we'll copy draw_list->_CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list->CmdBuffer/_IdxBuffer + memset(&_Channels[0], 0, sizeof(ImDrawChannel)); + for (int i = 1; i < channels_count; i++) + { + if (i >= old_channels_count) + { + IM_PLACEMENT_NEW(&_Channels[i]) + ImDrawChannel(); + } + else + { + _Channels[i]._CmdBuffer.resize(0); + _Channels[i]._IdxBuffer.resize(0); + } + } +} + +void ImDrawListSplitter::Merge(ImDrawList *draw_list) +{ + // Note that we never use or rely on _Channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. + if (_Count <= 1) + return; + + SetCurrentChannel(draw_list, 0); + draw_list->_PopUnusedDrawCmd(); + + // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. + int new_cmd_buffer_count = 0; + int new_idx_buffer_count = 0; + ImDrawCmd *last_cmd = (_Count > 0 && draw_list->CmdBuffer.Size > 0) ? &draw_list->CmdBuffer.back() : NULL; + int idx_offset = last_cmd ? last_cmd->IdxOffset + last_cmd->ElemCount : 0; + for (int i = 1; i < _Count; i++) + { + ImDrawChannel &ch = _Channels[i]; + if (ch._CmdBuffer.Size > 0 && ch._CmdBuffer.back().ElemCount == 0 && ch._CmdBuffer.back().UserCallback == NULL) // Equivalent of PopUnusedDrawCmd() + ch._CmdBuffer.pop_back(); + + if (ch._CmdBuffer.Size > 0 && last_cmd != NULL) + { + // Do not include ImDrawCmd_AreSequentialIdxOffset() in the compare as we rebuild IdxOffset values ourselves. + // Manipulating IdxOffset (e.g. by reordering draw commands like done by RenderDimmedBackgroundBehindWindow()) is not supported within a splitter. + ImDrawCmd *next_cmd = &ch._CmdBuffer[0]; + if (ImDrawCmd_HeaderCompare(last_cmd, next_cmd) == 0 && last_cmd->UserCallback == NULL && next_cmd->UserCallback == NULL) + { + // Merge previous channel last draw command with current channel first draw command if matching. + last_cmd->ElemCount += next_cmd->ElemCount; + idx_offset += next_cmd->ElemCount; + ch._CmdBuffer.erase(ch._CmdBuffer.Data); // FIXME-OPT: Improve for multiple merges. + } + } + if (ch._CmdBuffer.Size > 0) + last_cmd = &ch._CmdBuffer.back(); + new_cmd_buffer_count += ch._CmdBuffer.Size; + new_idx_buffer_count += ch._IdxBuffer.Size; + for (int cmd_n = 0; cmd_n < ch._CmdBuffer.Size; cmd_n++) + { + ch._CmdBuffer.Data[cmd_n].IdxOffset = idx_offset; + idx_offset += ch._CmdBuffer.Data[cmd_n].ElemCount; + } + } + draw_list->CmdBuffer.resize(draw_list->CmdBuffer.Size + new_cmd_buffer_count); + draw_list->IdxBuffer.resize(draw_list->IdxBuffer.Size + new_idx_buffer_count); + + // Write commands and indices in order (they are fairly small structures, we don't copy vertices only indices) + ImDrawCmd *cmd_write = draw_list->CmdBuffer.Data + draw_list->CmdBuffer.Size - new_cmd_buffer_count; + ImDrawIdx *idx_write = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size - new_idx_buffer_count; + for (int i = 1; i < _Count; i++) + { + ImDrawChannel &ch = _Channels[i]; + if (int sz = ch._CmdBuffer.Size) + { + memcpy(cmd_write, ch._CmdBuffer.Data, sz * sizeof(ImDrawCmd)); + cmd_write += sz; + } + if (int sz = ch._IdxBuffer.Size) + { + memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); + idx_write += sz; + } + } + draw_list->_IdxWritePtr = idx_write; + + // Ensure there's always a non-callback draw command trailing the command-buffer + if (draw_list->CmdBuffer.Size == 0 || draw_list->CmdBuffer.back().UserCallback != NULL) + draw_list->AddDrawCmd(); + + // If current command is used with different settings we need to add a new command + ImDrawCmd *curr_cmd = &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount == 0) + ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset + else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) + draw_list->AddDrawCmd(); + + _Count = 1; +} + +void ImDrawListSplitter::SetCurrentChannel(ImDrawList *draw_list, int idx) +{ + IM_ASSERT(idx >= 0 && idx < _Count); + if (_Current == idx) + return; + + // Overwrite ImVector (12/16 bytes), four times. This is merely a silly optimization instead of doing .swap() + memcpy(&_Channels.Data[_Current]._CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer)); + memcpy(&_Channels.Data[_Current]._IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer)); + _Current = idx; + memcpy(&draw_list->CmdBuffer, &_Channels.Data[idx]._CmdBuffer, sizeof(draw_list->CmdBuffer)); + memcpy(&draw_list->IdxBuffer, &_Channels.Data[idx]._IdxBuffer, sizeof(draw_list->IdxBuffer)); + draw_list->_IdxWritePtr = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size; + + // If current command is used with different settings we need to add a new command + ImDrawCmd *curr_cmd = (draw_list->CmdBuffer.Size == 0) ? NULL : &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1]; + if (curr_cmd == NULL) + draw_list->AddDrawCmd(); + else if (curr_cmd->ElemCount == 0) + ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset + else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) + draw_list->AddDrawCmd(); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImDrawData +//----------------------------------------------------------------------------- + +// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! +void ImDrawData::DeIndexAllBuffers() +{ + ImVector new_vtx_buffer; + TotalVtxCount = TotalIdxCount = 0; + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList *cmd_list = CmdLists[i]; + if (cmd_list->IdxBuffer.empty()) + continue; + new_vtx_buffer.resize(cmd_list->IdxBuffer.Size); + for (int j = 0; j < cmd_list->IdxBuffer.Size; j++) + new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]]; + cmd_list->VtxBuffer.swap(new_vtx_buffer); + cmd_list->IdxBuffer.resize(0); + TotalVtxCount += cmd_list->VtxBuffer.Size; + } +} + +// Helper to scale the ClipRect field of each ImDrawCmd. +// Use if your final output buffer is at a different scale than draw_data->DisplaySize, +// or if there is a difference between your window resolution and framebuffer resolution. +void ImDrawData::ScaleClipRects(const ImVec2 &fb_scale) +{ + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList *cmd_list = CmdLists[i]; + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + ImDrawCmd *cmd = &cmd_list->CmdBuffer[cmd_i]; + cmd->ClipRect = ImVec4(cmd->ClipRect.x * fb_scale.x, cmd->ClipRect.y * fb_scale.y, cmd->ClipRect.z * fb_scale.x, cmd->ClipRect.w * fb_scale.y); + } + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Helpers ShadeVertsXXX functions +//----------------------------------------------------------------------------- + +// Generic linear color gradient, write to RGB fields, leave A untouched. +void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawList *draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1) +{ + ImVec2 gradient_extent = gradient_p1 - gradient_p0; + float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent); + ImDrawVert *vert_start = draw_list->VtxBuffer.Data + vert_start_idx; + ImDrawVert *vert_end = draw_list->VtxBuffer.Data + vert_end_idx; + const int col0_r = (int)(col0 >> IM_COL32_R_SHIFT) & 0xFF; + const int col0_g = (int)(col0 >> IM_COL32_G_SHIFT) & 0xFF; + const int col0_b = (int)(col0 >> IM_COL32_B_SHIFT) & 0xFF; + const int col_delta_r = ((int)(col1 >> IM_COL32_R_SHIFT) & 0xFF) - col0_r; + const int col_delta_g = ((int)(col1 >> IM_COL32_G_SHIFT) & 0xFF) - col0_g; + const int col_delta_b = ((int)(col1 >> IM_COL32_B_SHIFT) & 0xFF) - col0_b; + for (ImDrawVert *vert = vert_start; vert < vert_end; vert++) + { + float d = ImDot(vert->pos - gradient_p0, gradient_extent); + float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f); + int r = (int)(col0_r + col_delta_r * t); + int g = (int)(col0_g + col_delta_g * t); + int b = (int)(col0_b + col_delta_b * t); + vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK); + } +} + +// Distribute UV over (a, b) rectangle +void ImGui::ShadeVertsLinearUV(ImDrawList *draw_list, int vert_start_idx, int vert_end_idx, const ImVec2 &a, const ImVec2 &b, const ImVec2 &uv_a, const ImVec2 &uv_b, bool clamp) +{ + const ImVec2 size = b - a; + const ImVec2 uv_size = uv_b - uv_a; + const ImVec2 scale = ImVec2( + size.x != 0.0f ? (uv_size.x / size.x) : 0.0f, + size.y != 0.0f ? (uv_size.y / size.y) : 0.0f); + + ImDrawVert *vert_start = draw_list->VtxBuffer.Data + vert_start_idx; + ImDrawVert *vert_end = draw_list->VtxBuffer.Data + vert_end_idx; + if (clamp) + { + const ImVec2 min = ImMin(uv_a, uv_b); + const ImVec2 max = ImMax(uv_a, uv_b); + for (ImDrawVert *vertex = vert_start; vertex < vert_end; ++vertex) + vertex->uv = ImClamp(uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale), min, max); + } + else + { + for (ImDrawVert *vertex = vert_start; vertex < vert_end; ++vertex) + vertex->uv = uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontConfig +//----------------------------------------------------------------------------- + +ImFontConfig::ImFontConfig() +{ + memset(this, 0, sizeof(*this)); + FontDataOwnedByAtlas = true; + OversampleH = 3; // FIXME: 2 may be a better default? + OversampleV = 1; + GlyphMaxAdvanceX = FLT_MAX; + RasterizerMultiply = 1.0f; + EllipsisChar = (ImWchar)-1; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontAtlas +//----------------------------------------------------------------------------- + +// A work of art lies ahead! (. = white layer, X = black layer, others are blank) +// The 2x2 white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes. +// (This is used when io.MouseDrawCursor = true) +const int FONT_ATLAS_DEFAULT_TEX_DATA_W = 122; // Actual texture will be 2 times that + 1 spacing. +const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27; +static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] = + { + "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX - XX XX " + "..- -X.....X- X.X - X.X -X.....X - X.....X- X..X -X..X X..X" + "--- -XXX.XXX- X...X - X...X -X....X - X....X- X..X -X...X X...X" + "X - X.X - X.....X - X.....X -X...X - X...X- X..X - X...X X...X " + "XX - X.X -X.......X- X.......X -X..X.X - X.X..X- X..X - X...X...X " + "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X- X..XXX - X.....X " + "X..X - X.X - X.X - X.X -XX X.X - X.X XX- X..X..XXX - X...X " + "X...X - X.X - X.X - XX X.X XX - X.X - X.X - X..X..X..XX - X.X " + "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X - X..X..X..X.X - X...X " + "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X -XXX X..X..X..X..X- X.....X " + "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X -X..XX........X..X- X...X...X " + "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X -X...X...........X- X...X X...X " + "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X - X..............X-X...X X...X" + "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X - X.............X-X..X X..X" + "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X - X.............X- XX XX " + "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X - X............X--------------" + "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX - X...........X - " + "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------- X..........X - " + "X.X X..X - -X.......X- X.......X - XX XX - - X..........X - " + "XX X..X - - X.....X - X.....X - X.X X.X - - X........X - " + " X..X - - X...X - X...X - X..X X..X - - X........X - " + " XX - - X.X - X.X - X...XXXXXXXXXXXXX...X - - XXXXXXXXXX - " + "------------- - X - X -X.....................X- ------------------- " + " ----------------------------------- X...XXXXXXXXXXXXX...X - " + " - X..X X..X - " + " - X.X X.X - " + " - XX XX - "}; + +static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3] = + { + // Pos ........ Size ......... Offset ...... + {ImVec2(0, 3), ImVec2(12, 19), ImVec2(0, 0)}, // ImGuiMouseCursor_Arrow + {ImVec2(13, 0), ImVec2(7, 16), ImVec2(1, 8)}, // ImGuiMouseCursor_TextInput + {ImVec2(31, 0), ImVec2(23, 23), ImVec2(11, 11)}, // ImGuiMouseCursor_ResizeAll + {ImVec2(21, 0), ImVec2(9, 23), ImVec2(4, 11)}, // ImGuiMouseCursor_ResizeNS + {ImVec2(55, 18), ImVec2(23, 9), ImVec2(11, 4)}, // ImGuiMouseCursor_ResizeEW + {ImVec2(73, 0), ImVec2(17, 17), ImVec2(8, 8)}, // ImGuiMouseCursor_ResizeNESW + {ImVec2(55, 0), ImVec2(17, 17), ImVec2(8, 8)}, // ImGuiMouseCursor_ResizeNWSE + {ImVec2(91, 0), ImVec2(17, 22), ImVec2(5, 0)}, // ImGuiMouseCursor_Hand + {ImVec2(109, 0), ImVec2(13, 15), ImVec2(6, 7)}, // ImGuiMouseCursor_NotAllowed +}; + +ImFontAtlas::ImFontAtlas() +{ + memset(this, 0, sizeof(*this)); + TexGlyphPadding = 1; + PackIdMouseCursors = PackIdLines = -1; +} + +ImFontAtlas::~ImFontAtlas() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + Clear(); +} + +void ImFontAtlas::ClearInputData() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + for (int i = 0; i < ConfigData.Size; i++) + if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) + { + IM_FREE(ConfigData[i].FontData); + ConfigData[i].FontData = NULL; + } + + // When clearing this we lose access to the font name and other information used to build the font. + for (int i = 0; i < Fonts.Size; i++) + if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size) + { + Fonts[i]->ConfigData = NULL; + Fonts[i]->ConfigDataCount = 0; + } + ConfigData.clear(); + CustomRects.clear(); + PackIdMouseCursors = PackIdLines = -1; + // Important: we leave TexReady untouched +} + +void ImFontAtlas::ClearTexData() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + if (TexPixelsAlpha8) + IM_FREE(TexPixelsAlpha8); + if (TexPixelsRGBA32) + IM_FREE(TexPixelsRGBA32); + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; + TexPixelsUseColors = false; + // Important: we leave TexReady untouched +} + +void ImFontAtlas::ClearFonts() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + Fonts.clear_delete(); + TexReady = false; +} + +void ImFontAtlas::Clear() +{ + ClearInputData(); + ClearTexData(); + ClearFonts(); +} + +void ImFontAtlas::GetTexDataAsAlpha8(unsigned char **out_pixels, int *out_width, int *out_height, int *out_bytes_per_pixel) +{ + // Build atlas on demand + if (TexPixelsAlpha8 == NULL) + Build(); + + *out_pixels = TexPixelsAlpha8; + if (out_width) + *out_width = TexWidth; + if (out_height) + *out_height = TexHeight; + if (out_bytes_per_pixel) + *out_bytes_per_pixel = 1; +} + +void ImFontAtlas::GetTexDataAsRGBA32(unsigned char **out_pixels, int *out_width, int *out_height, int *out_bytes_per_pixel) +{ + // Convert to RGBA32 format on demand + // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp + if (!TexPixelsRGBA32) + { + unsigned char *pixels = NULL; + GetTexDataAsAlpha8(&pixels, NULL, NULL); + if (pixels) + { + TexPixelsRGBA32 = (unsigned int *)IM_ALLOC((size_t)TexWidth * (size_t)TexHeight * 4); + const unsigned char *src = pixels; + unsigned int *dst = TexPixelsRGBA32; + for (int n = TexWidth * TexHeight; n > 0; n--) + *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++)); + } + } + + *out_pixels = (unsigned char *)TexPixelsRGBA32; + if (out_width) + *out_width = TexWidth; + if (out_height) + *out_height = TexHeight; + if (out_bytes_per_pixel) + *out_bytes_per_pixel = 4; +} + +ImFont *ImFontAtlas::AddFont(const ImFontConfig *font_cfg) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); + IM_ASSERT(font_cfg->SizePixels > 0.0f); + + // Create new font + if (!font_cfg->MergeMode) + Fonts.push_back(IM_NEW(ImFont)); + else + IM_ASSERT(!Fonts.empty() && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font. + + ConfigData.push_back(*font_cfg); + ImFontConfig &new_font_cfg = ConfigData.back(); + if (new_font_cfg.DstFont == NULL) + new_font_cfg.DstFont = Fonts.back(); + if (!new_font_cfg.FontDataOwnedByAtlas) + { + new_font_cfg.FontData = IM_ALLOC(new_font_cfg.FontDataSize); + new_font_cfg.FontDataOwnedByAtlas = true; + memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); + } + + if (new_font_cfg.DstFont->EllipsisChar == (ImWchar)-1) + new_font_cfg.DstFont->EllipsisChar = font_cfg->EllipsisChar; + + // Invalidate texture + TexReady = false; + ClearTexData(); + return new_font_cfg.DstFont; +} + +// Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder) +static unsigned int stb_decompress_length(const unsigned char *input); +static unsigned int stb_decompress(unsigned char *output, const unsigned char *input, unsigned int length); +static const char *GetDefaultCompressedFontDataTTFBase85(); +static unsigned int Decode85Byte(char c) { return c >= '\\' ? c - 36 : c - 35; } +static void Decode85(const unsigned char *src, unsigned char *dst) +{ + while (*src) + { + unsigned int tmp = Decode85Byte(src[0]) + 85 * (Decode85Byte(src[1]) + 85 * (Decode85Byte(src[2]) + 85 * (Decode85Byte(src[3]) + 85 * Decode85Byte(src[4])))); + dst[0] = ((tmp >> 0) & 0xFF); + dst[1] = ((tmp >> 8) & 0xFF); + dst[2] = ((tmp >> 16) & 0xFF); + dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness. + src += 5; + dst += 4; + } +} + +// Load embedded ProggyClean.ttf at size 13, disable oversampling +ImFont *ImFontAtlas::AddFontDefault(const ImFontConfig *font_cfg_template) +{ + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (!font_cfg_template) + { + font_cfg.OversampleH = font_cfg.OversampleV = 1; + font_cfg.PixelSnapH = true; + } + if (font_cfg.SizePixels <= 0.0f) + font_cfg.SizePixels = 13.0f * 1.0f; + if (font_cfg.Name[0] == '\0') + ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels); + font_cfg.EllipsisChar = (ImWchar)0x0085; + font_cfg.GlyphOffset.y = 1.0f * IM_FLOOR(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units + + const char *ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); + const ImWchar *glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault(); + ImFont *font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, glyph_ranges); + return font; +} + +ImFont *ImFontAtlas::AddFontFromFileTTF(const char *filename, float size_pixels, const ImFontConfig *font_cfg_template, const ImWchar *glyph_ranges) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + size_t data_size = 0; + void *data = ImFileLoadToMemory(filename, "rb", &data_size, 0); + if (!data) + { + IM_ASSERT_USER_ERROR(0, "Could not load font file!"); + return NULL; + } + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (font_cfg.Name[0] == '\0') + { + // Store a short copy of filename into into the font name for convenience + const char *p; + for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) + { + } + ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels); + } + return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges); +} + +// NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). +ImFont *ImFontAtlas::AddFontFromMemoryTTF(void *ttf_data, int ttf_size, float size_pixels, const ImFontConfig *font_cfg_template, const ImWchar *glyph_ranges) +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontData = ttf_data; + font_cfg.FontDataSize = ttf_size; + font_cfg.SizePixels = size_pixels > 0.0f ? size_pixels : font_cfg.SizePixels; + if (glyph_ranges) + font_cfg.GlyphRanges = glyph_ranges; + return AddFont(&font_cfg); +} + +ImFont *ImFontAtlas::AddFontFromMemoryCompressedTTF(const void *compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig *font_cfg_template, const ImWchar *glyph_ranges) +{ + const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char *)compressed_ttf_data); + unsigned char *buf_decompressed_data = (unsigned char *)IM_ALLOC(buf_decompressed_size); + stb_decompress(buf_decompressed_data, (const unsigned char *)compressed_ttf_data, (unsigned int)compressed_ttf_size); + + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontDataOwnedByAtlas = true; + return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges); +} + +ImFont *ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char *compressed_ttf_data_base85, float size_pixels, const ImFontConfig *font_cfg, const ImWchar *glyph_ranges) +{ + int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; + void *compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size); + Decode85((const unsigned char *)compressed_ttf_data_base85, (unsigned char *)compressed_ttf); + ImFont *font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); + IM_FREE(compressed_ttf); + return font; +} + +int ImFontAtlas::AddCustomRectRegular(int width, int height) +{ + IM_ASSERT(width > 0 && width <= 0xFFFF); + IM_ASSERT(height > 0 && height <= 0xFFFF); + ImFontAtlasCustomRect r; + r.Width = (unsigned short)width; + r.Height = (unsigned short)height; + CustomRects.push_back(r); + return CustomRects.Size - 1; // Return index +} + +int ImFontAtlas::AddCustomRectFontGlyph(ImFont *font, ImWchar id, int width, int height, float advance_x, const ImVec2 &offset) +{ +#ifdef IMGUI_USE_WCHAR32 + IM_ASSERT(id <= IM_UNICODE_CODEPOINT_MAX); +#endif + IM_ASSERT(font != NULL); + IM_ASSERT(width > 0 && width <= 0xFFFF); + IM_ASSERT(height > 0 && height <= 0xFFFF); + ImFontAtlasCustomRect r; + r.Width = (unsigned short)width; + r.Height = (unsigned short)height; + r.GlyphID = id; + r.GlyphAdvanceX = advance_x; + r.GlyphOffset = offset; + r.Font = font; + CustomRects.push_back(r); + return CustomRects.Size - 1; // Return index +} + +void ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect *rect, ImVec2 *out_uv_min, ImVec2 *out_uv_max) const +{ + IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates + IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed + *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y); + *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y); +} + +bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2 *out_offset, ImVec2 *out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]) +{ + if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_COUNT) + return false; + if (Flags & ImFontAtlasFlags_NoMouseCursors) + return false; + + IM_ASSERT(PackIdMouseCursors != -1); + ImFontAtlasCustomRect *r = GetCustomRectByIndex(PackIdMouseCursors); + ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r->X, (float)r->Y); + ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; + *out_size = size; + *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; + out_uv_border[0] = (pos)*TexUvScale; + out_uv_border[1] = (pos + size) * TexUvScale; + pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; + out_uv_fill[0] = (pos)*TexUvScale; + out_uv_fill[1] = (pos + size) * TexUvScale; + return true; +} + +bool ImFontAtlas::Build() +{ + IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); + + // Default font is none are specified + if (ConfigData.Size == 0) + AddFontDefault(); + + // Select builder + // - Note that we do not reassign to atlas->FontBuilderIO, since it is likely to point to static data which + // may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are + // using a hot-reloading scheme that messes up static data, store your own instance of ImFontBuilderIO somewhere + // and point to it instead of pointing directly to return value of the GetBuilderXXX functions. + const ImFontBuilderIO *builder_io = FontBuilderIO; + if (builder_io == NULL) + { +#ifdef IMGUI_ENABLE_FREETYPE + builder_io = ImGuiFreeType::GetBuilderForFreeType(); +#elif defined(IMGUI_ENABLE_STB_TRUETYPE) + builder_io = ImFontAtlasGetBuilderForStbTruetype(); +#else + IM_ASSERT(0); // Invalid Build function +#endif + } + + // Build + return builder_io->FontBuilder_Build(this); +} + +void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor) +{ + for (unsigned int i = 0; i < 256; i++) + { + unsigned int value = (unsigned int)(i * in_brighten_factor); + out_table[i] = value > 255 ? 255 : (value & 0xFF); + } +} + +void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char *pixels, int x, int y, int w, int h, int stride) +{ + unsigned char *data = pixels + x + y * stride; + for (int j = h; j > 0; j--, data += stride) + for (int i = 0; i < w; i++) + data[i] = table[data[i]]; +} + +#ifdef IMGUI_ENABLE_STB_TRUETYPE +// Temporary data for one source font (multiple source fonts can be merged into one destination ImFont) +// (C++03 doesn't allow instancing ImVector<> with function-local types so we declare the type here.) +struct ImFontBuildSrcData +{ + stbtt_fontinfo FontInfo; + stbtt_pack_range PackRange; // Hold the list of codepoints to pack (essentially points to Codepoints.Data) + stbrp_rect *Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position. + stbtt_packedchar *PackedChars; // Output glyphs + const ImWchar *SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF) + int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[] + int GlyphsHighest; // Highest requested codepoint + int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font) + ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB) + ImVector GlyphsList; // Glyph codepoints list (flattened version of GlyphsMap) +}; + +// Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont) +struct ImFontBuildDstData +{ + int SrcCount; // Number of source fonts targeting this destination font. + int GlyphsHighest; + int GlyphsCount; + ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font. +}; + +static void UnpackBitVectorToFlatIndexList(const ImBitVector *in, ImVector *out) +{ + IM_ASSERT(sizeof(in->Storage.Data[0]) == sizeof(int)); + const ImU32 *it_begin = in->Storage.begin(); + const ImU32 *it_end = in->Storage.end(); + for (const ImU32 *it = it_begin; it < it_end; it++) + if (ImU32 entries_32 = *it) + for (ImU32 bit_n = 0; bit_n < 32; bit_n++) + if (entries_32 & ((ImU32)1 << bit_n)) + out->push_back((int)(((it - it_begin) << 5) + bit_n)); +} + +static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas *atlas) +{ + IM_ASSERT(atlas->ConfigData.Size > 0); + + ImFontAtlasBuildInit(atlas); + + // Clear atlas + atlas->TexID = (ImTextureID)NULL; + atlas->TexWidth = atlas->TexHeight = 0; + atlas->TexUvScale = ImVec2(0.0f, 0.0f); + atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f); + atlas->ClearTexData(); + + // Temporary storage for building + ImVector src_tmp_array; + ImVector dst_tmp_array; + src_tmp_array.resize(atlas->ConfigData.Size); + dst_tmp_array.resize(atlas->Fonts.Size); + memset(src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes()); + memset(dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes()); + + // 1. Initialize font loading structure, check font data validity + for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++) + { + ImFontBuildSrcData &src_tmp = src_tmp_array[src_i]; + ImFontConfig &cfg = atlas->ConfigData[src_i]; + IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas)); + + // Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices) + src_tmp.DstIndex = -1; + for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++) + if (cfg.DstFont == atlas->Fonts[output_i]) + src_tmp.DstIndex = output_i; + if (src_tmp.DstIndex == -1) + { + IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array? + return false; + } + // Initialize helper structure for font loading and verify that the TTF/OTF data is correct + const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char *)cfg.FontData, cfg.FontNo); + IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found."); + if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char *)cfg.FontData, font_offset)) + return false; + + // Measure highest codepoints + ImFontBuildDstData &dst_tmp = dst_tmp_array[src_tmp.DstIndex]; + src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault(); + for (const ImWchar *src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) + src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]); + dst_tmp.SrcCount++; + dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest); + } + + // 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs. + int total_glyphs_count = 0; + for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) + { + ImFontBuildSrcData &src_tmp = src_tmp_array[src_i]; + ImFontBuildDstData &dst_tmp = dst_tmp_array[src_tmp.DstIndex]; + src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1); + if (dst_tmp.GlyphsSet.Storage.empty()) + dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1); + + for (const ImWchar *src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) + for (unsigned int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++) + { + if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option for MergeMode (e.g. MergeOverwrite==true) + continue; + if (!stbtt_FindGlyphIndex(&src_tmp.FontInfo, codepoint)) // It is actually in the font? + continue; + + // Add to avail set/counters + src_tmp.GlyphsCount++; + dst_tmp.GlyphsCount++; + src_tmp.GlyphsSet.SetBit(codepoint); + dst_tmp.GlyphsSet.SetBit(codepoint); + total_glyphs_count++; + } + } + + // 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another) + for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) + { + ImFontBuildSrcData &src_tmp = src_tmp_array[src_i]; + src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount); + UnpackBitVectorToFlatIndexList(&src_tmp.GlyphsSet, &src_tmp.GlyphsList); + src_tmp.GlyphsSet.Clear(); + IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount); + } + for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++) + dst_tmp_array[dst_i].GlyphsSet.Clear(); + dst_tmp_array.clear(); + + // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) + // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity) + ImVector buf_rects; + ImVector buf_packedchars; + buf_rects.resize(total_glyphs_count); + buf_packedchars.resize(total_glyphs_count); + memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes()); + memset(buf_packedchars.Data, 0, (size_t)buf_packedchars.size_in_bytes()); + + // 4. Gather glyphs sizes so we can pack them in our virtual canvas. + int total_surface = 0; + int buf_rects_out_n = 0; + int buf_packedchars_out_n = 0; + for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) + { + ImFontBuildSrcData &src_tmp = src_tmp_array[src_i]; + if (src_tmp.GlyphsCount == 0) + continue; + + src_tmp.Rects = &buf_rects[buf_rects_out_n]; + src_tmp.PackedChars = &buf_packedchars[buf_packedchars_out_n]; + buf_rects_out_n += src_tmp.GlyphsCount; + buf_packedchars_out_n += src_tmp.GlyphsCount; + + // Convert our ranges in the format stb_truetype wants + ImFontConfig &cfg = atlas->ConfigData[src_i]; + src_tmp.PackRange.font_size = cfg.SizePixels; + src_tmp.PackRange.first_unicode_codepoint_in_range = 0; + src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data; + src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size; + src_tmp.PackRange.chardata_for_range = src_tmp.PackedChars; + src_tmp.PackRange.h_oversample = (unsigned char)cfg.OversampleH; + src_tmp.PackRange.v_oversample = (unsigned char)cfg.OversampleV; + + // Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects) + const float scale = (cfg.SizePixels > 0) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -cfg.SizePixels); + const int padding = atlas->TexGlyphPadding; + for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++) + { + int x0, y0, x1, y1; + const int glyph_index_in_font = stbtt_FindGlyphIndex(&src_tmp.FontInfo, src_tmp.GlyphsList[glyph_i]); + IM_ASSERT(glyph_index_in_font != 0); + stbtt_GetGlyphBitmapBoxSubpixel(&src_tmp.FontInfo, glyph_index_in_font, scale * cfg.OversampleH, scale * cfg.OversampleV, 0, 0, &x0, &y0, &x1, &y1); + src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + padding + cfg.OversampleH - 1); + src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + padding + cfg.OversampleV - 1); + total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h; + } + } + + // We need a width for the skyline algorithm, any width! + // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height. + // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface. + const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1; + atlas->TexHeight = 0; + if (atlas->TexDesiredWidth > 0) + atlas->TexWidth = atlas->TexDesiredWidth; + else + atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 + : (surface_sqrt >= 1024 * 0.7f) ? 1024 + : 512; + + // 5. Start packing + // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). + const int TEX_HEIGHT_MAX = 1024 * 32; + stbtt_pack_context spc = {}; + stbtt_PackBegin(&spc, NULL, atlas->TexWidth, TEX_HEIGHT_MAX, 0, atlas->TexGlyphPadding, NULL); + ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info); + + // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point. + for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) + { + ImFontBuildSrcData &src_tmp = src_tmp_array[src_i]; + if (src_tmp.GlyphsCount == 0) + continue; + + stbrp_pack_rects((stbrp_context *)spc.pack_info, src_tmp.Rects, src_tmp.GlyphsCount); + + // Extend texture height and mark missing glyphs as non-packed so we won't render them. + // FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?) + for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) + if (src_tmp.Rects[glyph_i].was_packed) + atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h); + } + + // 7. Allocate texture + atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); + atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); + atlas->TexPixelsAlpha8 = (unsigned char *)IM_ALLOC(atlas->TexWidth * atlas->TexHeight); + memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight); + spc.pixels = atlas->TexPixelsAlpha8; + spc.height = atlas->TexHeight; + + // 8. Render/rasterize font characters into the texture + for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) + { + ImFontConfig &cfg = atlas->ConfigData[src_i]; + ImFontBuildSrcData &src_tmp = src_tmp_array[src_i]; + if (src_tmp.GlyphsCount == 0) + continue; + + stbtt_PackFontRangesRenderIntoRects(&spc, &src_tmp.FontInfo, &src_tmp.PackRange, 1, src_tmp.Rects); + + // Apply multiply operator + if (cfg.RasterizerMultiply != 1.0f) + { + unsigned char multiply_table[256]; + ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply); + stbrp_rect *r = &src_tmp.Rects[0]; + for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++, r++) + if (r->was_packed) + ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, atlas->TexPixelsAlpha8, r->x, r->y, r->w, r->h, atlas->TexWidth * 1); + } + src_tmp.Rects = NULL; + } + + // End packing + stbtt_PackEnd(&spc); + buf_rects.clear(); + + // 9. Setup ImFont and glyphs for runtime + for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) + { + ImFontBuildSrcData &src_tmp = src_tmp_array[src_i]; + if (src_tmp.GlyphsCount == 0) + continue; + + // When merging fonts with MergeMode=true: + // - We can have multiple input fonts writing into a same destination font. + // - dst_font->ConfigData is != from cfg which is our source configuration. + ImFontConfig &cfg = atlas->ConfigData[src_i]; + ImFont *dst_font = cfg.DstFont; + + const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels); + int unscaled_ascent, unscaled_descent, unscaled_line_gap; + stbtt_GetFontVMetrics(&src_tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); + + const float ascent = ImFloor(unscaled_ascent * font_scale + ((unscaled_ascent > 0.0f) ? +1 : -1)); + const float descent = ImFloor(unscaled_descent * font_scale + ((unscaled_descent > 0.0f) ? +1 : -1)); + ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent); + const float font_off_x = cfg.GlyphOffset.x; + const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent); + + for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) + { + // Register glyph + const int codepoint = src_tmp.GlyphsList[glyph_i]; + const stbtt_packedchar &pc = src_tmp.PackedChars[glyph_i]; + stbtt_aligned_quad q; + float unused_x = 0.0f, unused_y = 0.0f; + stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &unused_x, &unused_y, &q, 0); + dst_font->AddGlyph(&cfg, (ImWchar)codepoint, q.x0 + font_off_x, q.y0 + font_off_y, q.x1 + font_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance); + } + } + + // Cleanup + src_tmp_array.clear_destruct(); + + ImFontAtlasBuildFinish(atlas); + return true; +} + +const ImFontBuilderIO *ImFontAtlasGetBuilderForStbTruetype() +{ + static ImFontBuilderIO io; + io.FontBuilder_Build = ImFontAtlasBuildWithStbTruetype; + return &io; +} + +#endif // IMGUI_ENABLE_STB_TRUETYPE + +void ImFontAtlasBuildSetupFont(ImFontAtlas *atlas, ImFont *font, ImFontConfig *font_config, float ascent, float descent) +{ + if (!font_config->MergeMode) + { + font->ClearOutputData(); + font->FontSize = font_config->SizePixels; + font->ConfigData = font_config; + font->ConfigDataCount = 0; + font->ContainerAtlas = atlas; + font->Ascent = ascent; + font->Descent = descent; + } + font->ConfigDataCount++; +} + +void ImFontAtlasBuildPackCustomRects(ImFontAtlas *atlas, void *stbrp_context_opaque) +{ + stbrp_context *pack_context = (stbrp_context *)stbrp_context_opaque; + IM_ASSERT(pack_context != NULL); + + ImVector &user_rects = atlas->CustomRects; + IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong. + + ImVector pack_rects; + pack_rects.resize(user_rects.Size); + memset(pack_rects.Data, 0, (size_t)pack_rects.size_in_bytes()); + for (int i = 0; i < user_rects.Size; i++) + { + pack_rects[i].w = user_rects[i].Width; + pack_rects[i].h = user_rects[i].Height; + } + stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size); + for (int i = 0; i < pack_rects.Size; i++) + if (pack_rects[i].was_packed) + { + user_rects[i].X = (unsigned short)pack_rects[i].x; + user_rects[i].Y = (unsigned short)pack_rects[i].y; + IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height); + atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h); + } +} + +void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas *atlas, int x, int y, int w, int h, const char *in_str, char in_marker_char, unsigned char in_marker_pixel_value) +{ + IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth); + IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight); + unsigned char *out_pixel = atlas->TexPixelsAlpha8 + x + (y * atlas->TexWidth); + for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w) + for (int off_x = 0; off_x < w; off_x++) + out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : 0x00; +} + +void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas *atlas, int x, int y, int w, int h, const char *in_str, char in_marker_char, unsigned int in_marker_pixel_value) +{ + IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth); + IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight); + unsigned int *out_pixel = atlas->TexPixelsRGBA32 + x + (y * atlas->TexWidth); + for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w) + for (int off_x = 0; off_x < w; off_x++) + out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : IM_COL32_BLACK_TRANS; +} + +static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas *atlas) +{ + ImFontAtlasCustomRect *r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors); + IM_ASSERT(r->IsPacked()); + + const int w = atlas->TexWidth; + if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) + { + // Render/copy pixels + IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); + const int x_for_white = r->X; + const int x_for_black = r->X + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; + if (atlas->TexPixelsAlpha8 != NULL) + { + ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', 0xFF); + ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', 0xFF); + } + else + { + ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', IM_COL32_WHITE); + ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', IM_COL32_WHITE); + } + } + else + { + // Render 4 white pixels + IM_ASSERT(r->Width == 2 && r->Height == 2); + const int offset = (int)r->X + (int)r->Y * w; + if (atlas->TexPixelsAlpha8 != NULL) + { + atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF; + } + else + { + atlas->TexPixelsRGBA32[offset] = atlas->TexPixelsRGBA32[offset + 1] = atlas->TexPixelsRGBA32[offset + w] = atlas->TexPixelsRGBA32[offset + w + 1] = IM_COL32_WHITE; + } + } + atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); +} + +static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas *atlas) +{ + if (atlas->Flags & ImFontAtlasFlags_NoBakedLines) + return; + + // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them + ImFontAtlasCustomRect *r = atlas->GetCustomRectByIndex(atlas->PackIdLines); + IM_ASSERT(r->IsPacked()); + for (unsigned int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row + { + // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle + unsigned int y = n; + unsigned int line_width = n; + unsigned int pad_left = (r->Width - line_width) / 2; + unsigned int pad_right = r->Width - (pad_left + line_width); + + // Write each slice + IM_ASSERT(pad_left + line_width + pad_right == r->Width && y < r->Height); // Make sure we're inside the texture bounds before we start writing pixels + if (atlas->TexPixelsAlpha8 != NULL) + { + unsigned char *write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * atlas->TexWidth)]; + for (unsigned int i = 0; i < pad_left; i++) + *(write_ptr + i) = 0x00; + + for (unsigned int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = 0xFF; + + for (unsigned int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = 0x00; + } + else + { + unsigned int *write_ptr = &atlas->TexPixelsRGBA32[r->X + ((r->Y + y) * atlas->TexWidth)]; + for (unsigned int i = 0; i < pad_left; i++) + *(write_ptr + i) = IM_COL32(255, 255, 255, 0); + + for (unsigned int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = IM_COL32_WHITE; + + for (unsigned int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); + } + + // Calculate UVs for this line + ImVec2 uv0 = ImVec2((float)(r->X + pad_left - 1), (float)(r->Y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r->X + pad_left + line_width + 1), (float)(r->Y + y + 1)) * atlas->TexUvScale; + float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts + atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); + } +} + +// Note: this is called / shared by both the stb_truetype and the FreeType builder +void ImFontAtlasBuildInit(ImFontAtlas *atlas) +{ + // Register texture region for mouse cursors or standard white pixels + if (atlas->PackIdMouseCursors < 0) + { + if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + else + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); + } + + // Register texture region for thick lines + // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row + if (atlas->PackIdLines < 0) + { + if (!(atlas->Flags & ImFontAtlasFlags_NoBakedLines)) + atlas->PackIdLines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); + } +} + +// This is called/shared by both the stb_truetype and the FreeType builder. +void ImFontAtlasBuildFinish(ImFontAtlas *atlas) +{ + // Render into our custom data blocks + IM_ASSERT(atlas->TexPixelsAlpha8 != NULL || atlas->TexPixelsRGBA32 != NULL); + ImFontAtlasBuildRenderDefaultTexData(atlas); + ImFontAtlasBuildRenderLinesTexData(atlas); + + // Register custom rectangle glyphs + for (int i = 0; i < atlas->CustomRects.Size; i++) + { + const ImFontAtlasCustomRect *r = &atlas->CustomRects[i]; + if (r->Font == NULL || r->GlyphID == 0) + continue; + + // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, GlyphExtraSpacing, PixelSnapH + IM_ASSERT(r->Font->ContainerAtlas == atlas); + ImVec2 uv0, uv1; + atlas->CalcCustomRectUV(r, &uv0, &uv1); + r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX); + } + + // Build all fonts lookup tables + for (int i = 0; i < atlas->Fonts.Size; i++) + if (atlas->Fonts[i]->DirtyLookupTables) + atlas->Fonts[i]->BuildLookupTable(); + + atlas->TexReady = true; +} + +// Retrieve list of range (2 int per range, values are inclusive) +const ImWchar *ImFontAtlas::GetGlyphRangesDefault() +{ + static const ImWchar ranges[] = + { + 0x0020, + 0x00FF, // Basic Latin + Latin Supplement + 0, + }; + return &ranges[0]; +} + +const ImWchar *ImFontAtlas::GetGlyphRangesKorean() +{ + static const ImWchar ranges[] = + { + 0x0020, + 0x00FF, // Basic Latin + Latin Supplement + 0x3131, + 0x3163, // Korean alphabets + 0xAC00, + 0xD7A3, // Korean characters + 0xFFFD, + 0xFFFD, // Invalid + 0, + }; + return &ranges[0]; +} + +const ImWchar *ImFontAtlas::GetGlyphRangesChineseFull() +{ + static const ImWchar ranges[] = + { + 0x0020, + 0x00FF, // Basic Latin + Latin Supplement + 0x2000, + 0x206F, // General Punctuation + 0x3000, + 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana + 0x31F0, + 0x31FF, // Katakana Phonetic Extensions + 0xFF00, + 0xFFEF, // Half-width characters + 0xFFFD, + 0xFFFD, // Invalid + 0x4e00, + 0x9FAF, // CJK Ideograms + 0, + }; + return &ranges[0]; +} + +static void UnpackAccumulativeOffsetsIntoRanges(int base_codepoint, const short *accumulative_offsets, int accumulative_offsets_count, ImWchar *out_ranges) +{ + for (int n = 0; n < accumulative_offsets_count; n++, out_ranges += 2) + { + out_ranges[0] = out_ranges[1] = (ImWchar)(base_codepoint + accumulative_offsets[n]); + base_codepoint += accumulative_offsets[n]; + } + out_ranges[0] = 0; +} + +//------------------------------------------------------------------------- +// [SECTION] ImFontAtlas glyph ranges helpers +//------------------------------------------------------------------------- + +const ImWchar *ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon() +{ + // Store 2500 regularly used characters for Simplified Chinese. + // Sourced from https://zh.wiktionary.org/wiki/%E9%99%84%E5%BD%95:%E7%8E%B0%E4%BB%A3%E6%B1%89%E8%AF%AD%E5%B8%B8%E7%94%A8%E5%AD%97%E8%A1%A8 + // This table covers 97.97% of all characters used during the month in July, 1987. + // You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters. + // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.) + static const short accumulative_offsets_from_0x4E00[] = + { + 0, 1, 2, 4, 1, 1, 1, 1, 2, 1, 3, 2, 1, 2, 2, 1, 1, 1, 1, 1, 5, 2, 1, 2, 3, 3, 3, 2, 2, 4, 1, 1, 1, 2, 1, 5, 2, 3, 1, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 4, 1, 1, 1, 1, 5, 10, 1, 2, 19, 2, 1, 2, 1, 2, 1, 2, 1, 2, + 1, 5, 1, 6, 3, 2, 1, 2, 2, 1, 1, 1, 4, 8, 5, 1, 1, 4, 1, 1, 3, 1, 2, 1, 5, 1, 2, 1, 1, 1, 10, 1, 1, 5, 2, 4, 6, 1, 4, 2, 2, 2, 12, 2, 1, 1, 6, 1, 1, 1, 4, 1, 1, 4, 6, 5, 1, 4, 2, 2, 4, 10, 7, 1, 1, 4, 2, 4, + 2, 1, 4, 3, 6, 10, 12, 5, 7, 2, 14, 2, 9, 1, 1, 6, 7, 10, 4, 7, 13, 1, 5, 4, 8, 4, 1, 1, 2, 28, 5, 6, 1, 1, 5, 2, 5, 20, 2, 2, 9, 8, 11, 2, 9, 17, 1, 8, 6, 8, 27, 4, 6, 9, 20, 11, 27, 6, 68, 2, 2, 1, 1, + 1, 2, 1, 2, 2, 7, 6, 11, 3, 3, 1, 1, 3, 1, 2, 1, 1, 1, 1, 1, 3, 1, 1, 8, 3, 4, 1, 5, 7, 2, 1, 4, 4, 8, 4, 2, 1, 2, 1, 1, 4, 5, 6, 3, 6, 2, 12, 3, 1, 3, 9, 2, 4, 3, 4, 1, 5, 3, 3, 1, 3, 7, 1, 5, 1, 1, 1, 1, 2, + 3, 4, 5, 2, 3, 2, 6, 1, 1, 2, 1, 7, 1, 7, 3, 4, 5, 15, 2, 2, 1, 5, 3, 22, 19, 2, 1, 1, 1, 1, 2, 5, 1, 1, 1, 6, 1, 1, 12, 8, 2, 9, 18, 22, 4, 1, 1, 5, 1, 16, 1, 2, 7, 10, 15, 1, 1, 6, 2, 4, 1, 2, 4, 1, 6, + 1, 1, 3, 2, 4, 1, 6, 4, 5, 1, 2, 1, 1, 2, 1, 10, 3, 1, 3, 2, 1, 9, 3, 2, 5, 7, 2, 19, 4, 3, 6, 1, 1, 1, 1, 1, 4, 3, 2, 1, 1, 1, 2, 5, 3, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 3, 1, 1, 1, 3, 7, 1, 4, 1, 1, 2, 1, + 1, 2, 1, 2, 4, 4, 3, 8, 1, 1, 1, 2, 1, 3, 5, 1, 3, 1, 3, 4, 6, 2, 2, 14, 4, 6, 6, 11, 9, 1, 15, 3, 1, 28, 5, 2, 5, 5, 3, 1, 3, 4, 5, 4, 6, 14, 3, 2, 3, 5, 21, 2, 7, 20, 10, 1, 2, 19, 2, 4, 28, 28, 2, 3, + 2, 1, 14, 4, 1, 26, 28, 42, 12, 40, 3, 52, 79, 5, 14, 17, 3, 2, 2, 11, 3, 4, 6, 3, 1, 8, 2, 23, 4, 5, 8, 10, 4, 2, 7, 3, 5, 1, 1, 6, 3, 1, 2, 2, 2, 5, 28, 1, 1, 7, 7, 20, 5, 3, 29, 3, 17, 26, 1, 8, 4, + 27, 3, 6, 11, 23, 5, 3, 4, 6, 13, 24, 16, 6, 5, 10, 25, 35, 7, 3, 2, 3, 3, 14, 3, 6, 2, 6, 1, 4, 2, 3, 8, 2, 1, 1, 3, 3, 3, 4, 1, 1, 13, 2, 2, 4, 5, 2, 1, 14, 14, 1, 2, 2, 1, 4, 5, 2, 3, 1, 14, 3, 12, + 3, 17, 2, 16, 5, 1, 2, 1, 8, 9, 3, 19, 4, 2, 2, 4, 17, 25, 21, 20, 28, 75, 1, 10, 29, 103, 4, 1, 2, 1, 1, 4, 2, 4, 1, 2, 3, 24, 2, 2, 2, 1, 1, 2, 1, 3, 8, 1, 1, 1, 2, 1, 1, 3, 1, 1, 1, 6, 1, 5, 3, 1, 1, + 1, 3, 4, 1, 1, 5, 2, 1, 5, 6, 13, 9, 16, 1, 1, 1, 1, 3, 2, 3, 2, 4, 5, 2, 5, 2, 2, 3, 7, 13, 7, 2, 2, 1, 1, 1, 1, 2, 3, 3, 2, 1, 6, 4, 9, 2, 1, 14, 2, 14, 2, 1, 18, 3, 4, 14, 4, 11, 41, 15, 23, 15, 23, + 176, 1, 3, 4, 1, 1, 1, 1, 5, 3, 1, 2, 3, 7, 3, 1, 1, 2, 1, 2, 4, 4, 6, 2, 4, 1, 9, 7, 1, 10, 5, 8, 16, 29, 1, 1, 2, 2, 3, 1, 3, 5, 2, 4, 5, 4, 1, 1, 2, 2, 3, 3, 7, 1, 6, 10, 1, 17, 1, 44, 4, 6, 2, 1, 1, 6, + 5, 4, 2, 10, 1, 6, 9, 2, 8, 1, 24, 1, 2, 13, 7, 8, 8, 2, 1, 4, 1, 3, 1, 3, 3, 5, 2, 5, 10, 9, 4, 9, 12, 2, 1, 6, 1, 10, 1, 1, 7, 7, 4, 10, 8, 3, 1, 13, 4, 3, 1, 6, 1, 3, 5, 2, 1, 2, 17, 16, 5, 2, 16, 6, + 1, 4, 2, 1, 3, 3, 6, 8, 5, 11, 11, 1, 3, 3, 2, 4, 6, 10, 9, 5, 7, 4, 7, 4, 7, 1, 1, 4, 2, 1, 3, 6, 8, 7, 1, 6, 11, 5, 5, 3, 24, 9, 4, 2, 7, 13, 5, 1, 8, 82, 16, 61, 1, 1, 1, 4, 2, 2, 16, 10, 3, 8, 1, 1, + 6, 4, 2, 1, 3, 1, 1, 1, 4, 3, 8, 4, 2, 2, 1, 1, 1, 1, 1, 6, 3, 5, 1, 1, 4, 6, 9, 2, 1, 1, 1, 2, 1, 7, 2, 1, 6, 1, 5, 4, 4, 3, 1, 8, 1, 3, 3, 1, 3, 2, 2, 2, 2, 3, 1, 6, 1, 2, 1, 2, 1, 3, 7, 1, 8, 2, 1, 2, 1, 5, + 2, 5, 3, 5, 10, 1, 2, 1, 1, 3, 2, 5, 11, 3, 9, 3, 5, 1, 1, 5, 9, 1, 2, 1, 5, 7, 9, 9, 8, 1, 3, 3, 3, 6, 8, 2, 3, 2, 1, 1, 32, 6, 1, 2, 15, 9, 3, 7, 13, 1, 3, 10, 13, 2, 14, 1, 13, 10, 2, 1, 3, 10, 4, 15, + 2, 15, 15, 10, 1, 3, 9, 6, 9, 32, 25, 26, 47, 7, 3, 2, 3, 1, 6, 3, 4, 3, 2, 8, 5, 4, 1, 9, 4, 2, 2, 19, 10, 6, 2, 3, 8, 1, 2, 2, 4, 2, 1, 9, 4, 4, 4, 6, 4, 8, 9, 2, 3, 1, 1, 1, 1, 3, 5, 5, 1, 3, 8, 4, 6, + 2, 1, 4, 12, 1, 5, 3, 7, 13, 2, 5, 8, 1, 6, 1, 2, 5, 14, 6, 1, 5, 2, 4, 8, 15, 5, 1, 23, 6, 62, 2, 10, 1, 1, 8, 1, 2, 2, 10, 4, 2, 2, 9, 2, 1, 1, 3, 2, 3, 1, 5, 3, 3, 2, 1, 3, 8, 1, 1, 1, 11, 3, 1, 1, 4, + 3, 7, 1, 14, 1, 2, 3, 12, 5, 2, 5, 1, 6, 7, 5, 7, 14, 11, 1, 3, 1, 8, 9, 12, 2, 1, 11, 8, 4, 4, 2, 6, 10, 9, 13, 1, 1, 3, 1, 5, 1, 3, 2, 4, 4, 1, 18, 2, 3, 14, 11, 4, 29, 4, 2, 7, 1, 3, 13, 9, 2, 2, 5, + 3, 5, 20, 7, 16, 8, 5, 72, 34, 6, 4, 22, 12, 12, 28, 45, 36, 9, 7, 39, 9, 191, 1, 1, 1, 4, 11, 8, 4, 9, 2, 3, 22, 1, 1, 1, 1, 4, 17, 1, 7, 7, 1, 11, 31, 10, 2, 4, 8, 2, 3, 2, 1, 4, 2, 16, 4, 32, 2, + 3, 19, 13, 4, 9, 1, 5, 2, 14, 8, 1, 1, 3, 6, 19, 6, 5, 1, 16, 6, 2, 10, 8, 5, 1, 2, 3, 1, 5, 5, 1, 11, 6, 6, 1, 3, 3, 2, 6, 3, 8, 1, 1, 4, 10, 7, 5, 7, 7, 5, 8, 9, 2, 1, 3, 4, 1, 1, 3, 1, 3, 3, 2, 6, 16, + 1, 4, 6, 3, 1, 10, 6, 1, 3, 15, 2, 9, 2, 10, 25, 13, 9, 16, 6, 2, 2, 10, 11, 4, 3, 9, 1, 2, 6, 6, 5, 4, 30, 40, 1, 10, 7, 12, 14, 33, 6, 3, 6, 7, 3, 1, 3, 1, 11, 14, 4, 9, 5, 12, 11, 49, 18, 51, 31, + 140, 31, 2, 2, 1, 5, 1, 8, 1, 10, 1, 4, 4, 3, 24, 1, 10, 1, 3, 6, 6, 16, 3, 4, 5, 2, 1, 4, 2, 57, 10, 6, 22, 2, 22, 3, 7, 22, 6, 10, 11, 36, 18, 16, 33, 36, 2, 5, 5, 1, 1, 1, 4, 10, 1, 4, 13, 2, 7, + 5, 2, 9, 3, 4, 1, 7, 43, 3, 7, 3, 9, 14, 7, 9, 1, 11, 1, 1, 3, 7, 4, 18, 13, 1, 14, 1, 3, 6, 10, 73, 2, 2, 30, 6, 1, 11, 18, 19, 13, 22, 3, 46, 42, 37, 89, 7, 3, 16, 34, 2, 2, 3, 9, 1, 7, 1, 1, 1, 2, + 2, 4, 10, 7, 3, 10, 3, 9, 5, 28, 9, 2, 6, 13, 7, 3, 1, 3, 10, 2, 7, 2, 11, 3, 6, 21, 54, 85, 2, 1, 4, 2, 2, 1, 39, 3, 21, 2, 2, 5, 1, 1, 1, 4, 1, 1, 3, 4, 15, 1, 3, 2, 4, 4, 2, 3, 8, 2, 20, 1, 8, 7, 13, + 4, 1, 26, 6, 2, 9, 34, 4, 21, 52, 10, 4, 4, 1, 5, 12, 2, 11, 1, 7, 2, 30, 12, 44, 2, 30, 1, 1, 3, 6, 16, 9, 17, 39, 82, 2, 2, 24, 7, 1, 7, 3, 16, 9, 14, 44, 2, 1, 2, 1, 2, 3, 5, 2, 4, 1, 6, 7, 5, 3, + 2, 6, 1, 11, 5, 11, 2, 1, 18, 19, 8, 1, 3, 24, 29, 2, 1, 3, 5, 2, 2, 1, 13, 6, 5, 1, 46, 11, 3, 5, 1, 1, 5, 8, 2, 10, 6, 12, 6, 3, 7, 11, 2, 4, 16, 13, 2, 5, 1, 1, 2, 2, 5, 2, 28, 5, 2, 23, 10, 8, 4, + 4, 22, 39, 95, 38, 8, 14, 9, 5, 1, 13, 5, 4, 3, 13, 12, 11, 1, 9, 1, 27, 37, 2, 5, 4, 4, 63, 211, 95, 2, 2, 2, 1, 3, 5, 2, 1, 1, 2, 2, 1, 1, 1, 3, 2, 4, 1, 2, 1, 1, 5, 2, 2, 1, 1, 2, 3, 1, 3, 1, 1, 1, + 3, 1, 4, 2, 1, 3, 6, 1, 1, 3, 7, 15, 5, 3, 2, 5, 3, 9, 11, 4, 2, 22, 1, 6, 3, 8, 7, 1, 4, 28, 4, 16, 3, 3, 25, 4, 4, 27, 27, 1, 4, 1, 2, 2, 7, 1, 3, 5, 2, 28, 8, 2, 14, 1, 8, 6, 16, 25, 3, 3, 3, 14, 3, + 3, 1, 1, 2, 1, 4, 6, 3, 8, 4, 1, 1, 1, 2, 3, 6, 10, 6, 2, 3, 18, 3, 2, 5, 5, 4, 3, 1, 5, 2, 5, 4, 23, 7, 6, 12, 6, 4, 17, 11, 9, 5, 1, 1, 10, 5, 12, 1, 1, 11, 26, 33, 7, 3, 6, 1, 17, 7, 1, 5, 12, 1, 11, + 2, 4, 1, 8, 14, 17, 23, 1, 2, 1, 7, 8, 16, 11, 9, 6, 5, 2, 6, 4, 16, 2, 8, 14, 1, 11, 8, 9, 1, 1, 1, 9, 25, 4, 11, 19, 7, 2, 15, 2, 12, 8, 52, 7, 5, 19, 2, 16, 4, 36, 8, 1, 16, 8, 24, 26, 4, 6, 2, 9, + 5, 4, 36, 3, 28, 12, 25, 15, 37, 27, 17, 12, 59, 38, 5, 32, 127, 1, 2, 9, 17, 14, 4, 1, 2, 1, 1, 8, 11, 50, 4, 14, 2, 19, 16, 4, 17, 5, 4, 5, 26, 12, 45, 2, 23, 45, 104, 30, 12, 8, 3, 10, 2, 2, + 3, 3, 1, 4, 20, 7, 2, 9, 6, 15, 2, 20, 1, 3, 16, 4, 11, 15, 6, 134, 2, 5, 59, 1, 2, 2, 2, 1, 9, 17, 3, 26, 137, 10, 211, 59, 1, 2, 4, 1, 4, 1, 1, 1, 2, 6, 2, 3, 1, 1, 2, 3, 2, 3, 1, 3, 4, 4, 2, 3, 3, + 1, 4, 3, 1, 7, 2, 2, 3, 1, 2, 1, 3, 3, 3, 2, 2, 3, 2, 1, 3, 14, 6, 1, 3, 2, 9, 6, 15, 27, 9, 34, 145, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2, 3, 1, 2, 1, 1, 1, 2, 3, 5, 8, 3, 5, 2, 4, 1, 3, 2, 2, 2, 12, + 4, 1, 1, 1, 10, 4, 5, 1, 20, 4, 16, 1, 15, 9, 5, 12, 2, 9, 2, 5, 4, 2, 26, 19, 7, 1, 26, 4, 30, 12, 15, 42, 1, 6, 8, 172, 1, 1, 4, 2, 1, 1, 11, 2, 2, 4, 2, 1, 2, 1, 10, 8, 1, 2, 1, 4, 5, 1, 2, 5, 1, 8, + 4, 1, 3, 4, 2, 1, 6, 2, 1, 3, 4, 1, 2, 1, 1, 1, 1, 12, 5, 7, 2, 4, 3, 1, 1, 1, 3, 3, 6, 1, 2, 2, 3, 3, 3, 2, 1, 2, 12, 14, 11, 6, 6, 4, 12, 2, 8, 1, 7, 10, 1, 35, 7, 4, 13, 15, 4, 3, 23, 21, 28, 52, 5, + 26, 5, 6, 1, 7, 10, 2, 7, 53, 3, 2, 1, 1, 1, 2, 163, 532, 1, 10, 11, 1, 3, 3, 4, 8, 2, 8, 6, 2, 2, 23, 22, 4, 2, 2, 4, 2, 1, 3, 1, 3, 3, 5, 9, 8, 2, 1, 2, 8, 1, 10, 2, 12, 21, 20, 15, 105, 2, 3, 1, 1, + 3, 2, 3, 1, 1, 2, 5, 1, 4, 15, 11, 19, 1, 1, 1, 1, 5, 4, 5, 1, 1, 2, 5, 3, 5, 12, 1, 2, 5, 1, 11, 1, 1, 15, 9, 1, 4, 5, 3, 26, 8, 2, 1, 3, 1, 1, 15, 19, 2, 12, 1, 2, 5, 2, 7, 2, 19, 2, 20, 6, 26, 7, 5, + 2, 2, 7, 34, 21, 13, 70, 2, 128, 1, 1, 2, 1, 1, 2, 1, 1, 3, 2, 2, 2, 15, 1, 4, 1, 3, 4, 42, 10, 6, 1, 49, 85, 8, 1, 2, 1, 1, 4, 4, 2, 3, 6, 1, 5, 7, 4, 3, 211, 4, 1, 2, 1, 2, 5, 1, 2, 4, 2, 2, 6, 5, 6, + 10, 3, 4, 48, 100, 6, 2, 16, 296, 5, 27, 387, 2, 2, 3, 7, 16, 8, 5, 38, 15, 39, 21, 9, 10, 3, 7, 59, 13, 27, 21, 47, 5, 21, 6}; + static ImWchar base_ranges[] = // not zero-terminated + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x2000, 0x206F, // General Punctuation + 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + 0xFFFD, 0xFFFD // Invalid + }; + static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00) * 2 + 1] = {0}; + if (!full_ranges[0]) + { + memcpy(full_ranges, base_ranges, sizeof(base_ranges)); + UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges)); + } + return &full_ranges[0]; +} + +const ImWchar *ImFontAtlas::GetGlyphRangesJapanese() +{ + // 2999 ideograms code points for Japanese + // - 2136 Joyo (meaning "for regular use" or "for common use") Kanji code points + // - 863 Jinmeiyo (meaning "for personal name") Kanji code points + // - Sourced from the character information database of the Information-technology Promotion Agency, Japan + // - https://mojikiban.ipa.go.jp/mji/ + // - Available under the terms of the Creative Commons Attribution-ShareAlike 2.1 Japan (CC BY-SA 2.1 JP). + // - https://creativecommons.org/licenses/by-sa/2.1/jp/deed.en + // - https://creativecommons.org/licenses/by-sa/2.1/jp/legalcode + // - You can generate this code by the script at: + // - https://github.com/vaiorabbit/everyday_use_kanji + // - References: + // - List of Joyo Kanji + // - (Official list by the Agency for Cultural Affairs) https://www.bunka.go.jp/kokugo_nihongo/sisaku/joho/joho/kakuki/14/tosin02/index.html + // - (Wikipedia) https://en.wikipedia.org/wiki/List_of_j%C5%8Dy%C5%8D_kanji + // - List of Jinmeiyo Kanji + // - (Official list by the Ministry of Justice) http://www.moj.go.jp/MINJI/minji86.html + // - (Wikipedia) https://en.wikipedia.org/wiki/Jinmeiy%C5%8D_kanji + // - Missing 1 Joyo Kanji: U+20B9F (Kun'yomi: Shikaru, On'yomi: Shitsu,shichi), see https://github.com/ocornut/imgui/pull/3627 for details. + // You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters. + // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.) + static const short accumulative_offsets_from_0x4E00[] = + { + 0, + 1, + 2, + 4, + 1, + 1, + 1, + 1, + 2, + 1, + 3, + 3, + 2, + 2, + 1, + 5, + 3, + 5, + 7, + 5, + 6, + 1, + 2, + 1, + 7, + 2, + 6, + 3, + 1, + 8, + 1, + 1, + 4, + 1, + 1, + 18, + 2, + 11, + 2, + 6, + 2, + 1, + 2, + 1, + 5, + 1, + 2, + 1, + 3, + 1, + 2, + 1, + 2, + 3, + 3, + 1, + 1, + 2, + 3, + 1, + 1, + 1, + 12, + 7, + 9, + 1, + 4, + 5, + 1, + 1, + 2, + 1, + 10, + 1, + 1, + 9, + 2, + 2, + 4, + 5, + 6, + 9, + 3, + 1, + 1, + 1, + 1, + 9, + 3, + 18, + 5, + 2, + 2, + 2, + 2, + 1, + 6, + 3, + 7, + 1, + 1, + 1, + 1, + 2, + 2, + 4, + 2, + 1, + 23, + 2, + 10, + 4, + 3, + 5, + 2, + 4, + 10, + 2, + 4, + 13, + 1, + 6, + 1, + 9, + 3, + 1, + 1, + 6, + 6, + 7, + 6, + 3, + 1, + 2, + 11, + 3, + 2, + 2, + 3, + 2, + 15, + 2, + 2, + 5, + 4, + 3, + 6, + 4, + 1, + 2, + 5, + 2, + 12, + 16, + 6, + 13, + 9, + 13, + 2, + 1, + 1, + 7, + 16, + 4, + 7, + 1, + 19, + 1, + 5, + 1, + 2, + 2, + 7, + 7, + 8, + 2, + 6, + 5, + 4, + 9, + 18, + 7, + 4, + 5, + 9, + 13, + 11, + 8, + 15, + 2, + 1, + 1, + 1, + 2, + 1, + 2, + 2, + 1, + 2, + 2, + 8, + 2, + 9, + 3, + 3, + 1, + 1, + 4, + 4, + 1, + 1, + 1, + 4, + 9, + 1, + 4, + 3, + 5, + 5, + 2, + 7, + 5, + 3, + 4, + 8, + 2, + 1, + 13, + 2, + 3, + 3, + 1, + 14, + 1, + 1, + 4, + 5, + 1, + 3, + 6, + 1, + 5, + 2, + 1, + 1, + 3, + 3, + 3, + 3, + 1, + 1, + 2, + 7, + 6, + 6, + 7, + 1, + 4, + 7, + 6, + 1, + 1, + 1, + 1, + 1, + 12, + 3, + 3, + 9, + 5, + 2, + 6, + 1, + 5, + 6, + 1, + 2, + 3, + 18, + 2, + 4, + 14, + 4, + 1, + 3, + 6, + 1, + 1, + 6, + 3, + 5, + 5, + 3, + 2, + 2, + 2, + 2, + 12, + 3, + 1, + 4, + 2, + 3, + 2, + 3, + 11, + 1, + 7, + 4, + 1, + 2, + 1, + 3, + 17, + 1, + 9, + 1, + 24, + 1, + 1, + 4, + 2, + 2, + 4, + 1, + 2, + 7, + 1, + 1, + 1, + 3, + 1, + 2, + 2, + 4, + 15, + 1, + 1, + 2, + 1, + 1, + 2, + 1, + 5, + 2, + 5, + 20, + 2, + 5, + 9, + 1, + 10, + 8, + 7, + 6, + 1, + 1, + 1, + 1, + 1, + 1, + 6, + 2, + 1, + 2, + 8, + 1, + 1, + 1, + 1, + 5, + 1, + 1, + 3, + 1, + 1, + 1, + 1, + 3, + 1, + 1, + 12, + 4, + 1, + 3, + 1, + 1, + 1, + 1, + 1, + 10, + 3, + 1, + 7, + 5, + 13, + 1, + 2, + 3, + 4, + 6, + 1, + 1, + 30, + 2, + 9, + 9, + 1, + 15, + 38, + 11, + 3, + 1, + 8, + 24, + 7, + 1, + 9, + 8, + 10, + 2, + 1, + 9, + 31, + 2, + 13, + 6, + 2, + 9, + 4, + 49, + 5, + 2, + 15, + 2, + 1, + 10, + 2, + 1, + 1, + 1, + 2, + 2, + 6, + 15, + 30, + 35, + 3, + 14, + 18, + 8, + 1, + 16, + 10, + 28, + 12, + 19, + 45, + 38, + 1, + 3, + 2, + 3, + 13, + 2, + 1, + 7, + 3, + 6, + 5, + 3, + 4, + 3, + 1, + 5, + 7, + 8, + 1, + 5, + 3, + 18, + 5, + 3, + 6, + 1, + 21, + 4, + 24, + 9, + 24, + 40, + 3, + 14, + 3, + 21, + 3, + 2, + 1, + 2, + 4, + 2, + 3, + 1, + 15, + 15, + 6, + 5, + 1, + 1, + 3, + 1, + 5, + 6, + 1, + 9, + 7, + 3, + 3, + 2, + 1, + 4, + 3, + 8, + 21, + 5, + 16, + 4, + 5, + 2, + 10, + 11, + 11, + 3, + 6, + 3, + 2, + 9, + 3, + 6, + 13, + 1, + 2, + 1, + 1, + 1, + 1, + 11, + 12, + 6, + 6, + 1, + 4, + 2, + 6, + 5, + 2, + 1, + 1, + 3, + 3, + 6, + 13, + 3, + 1, + 1, + 5, + 1, + 2, + 3, + 3, + 14, + 2, + 1, + 2, + 2, + 2, + 5, + 1, + 9, + 5, + 1, + 1, + 6, + 12, + 3, + 12, + 3, + 4, + 13, + 2, + 14, + 2, + 8, + 1, + 17, + 5, + 1, + 16, + 4, + 2, + 2, + 21, + 8, + 9, + 6, + 23, + 20, + 12, + 25, + 19, + 9, + 38, + 8, + 3, + 21, + 40, + 25, + 33, + 13, + 4, + 3, + 1, + 4, + 1, + 2, + 4, + 1, + 2, + 5, + 26, + 2, + 1, + 1, + 2, + 1, + 3, + 6, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 3, + 1, + 1, + 1, + 9, + 2, + 3, + 1, + 1, + 1, + 3, + 6, + 3, + 2, + 1, + 1, + 6, + 6, + 1, + 8, + 2, + 2, + 2, + 1, + 4, + 1, + 2, + 3, + 2, + 7, + 3, + 2, + 4, + 1, + 2, + 1, + 2, + 2, + 1, + 1, + 1, + 1, + 1, + 3, + 1, + 2, + 5, + 4, + 10, + 9, + 4, + 9, + 1, + 1, + 1, + 1, + 1, + 1, + 5, + 3, + 2, + 1, + 6, + 4, + 9, + 6, + 1, + 10, + 2, + 31, + 17, + 8, + 3, + 7, + 5, + 40, + 1, + 7, + 7, + 1, + 6, + 5, + 2, + 10, + 7, + 8, + 4, + 15, + 39, + 25, + 6, + 28, + 47, + 18, + 10, + 7, + 1, + 3, + 1, + 1, + 2, + 1, + 1, + 1, + 3, + 3, + 3, + 1, + 1, + 1, + 3, + 4, + 2, + 1, + 4, + 1, + 3, + 6, + 10, + 7, + 8, + 6, + 2, + 2, + 1, + 3, + 3, + 2, + 5, + 8, + 7, + 9, + 12, + 2, + 15, + 1, + 1, + 4, + 1, + 2, + 1, + 1, + 1, + 3, + 2, + 1, + 3, + 3, + 5, + 6, + 2, + 3, + 2, + 10, + 1, + 4, + 2, + 8, + 1, + 1, + 1, + 11, + 6, + 1, + 21, + 4, + 16, + 3, + 1, + 3, + 1, + 4, + 2, + 3, + 6, + 5, + 1, + 3, + 1, + 1, + 3, + 3, + 4, + 6, + 1, + 1, + 10, + 4, + 2, + 7, + 10, + 4, + 7, + 4, + 2, + 9, + 4, + 3, + 1, + 1, + 1, + 4, + 1, + 8, + 3, + 4, + 1, + 3, + 1, + 6, + 1, + 4, + 2, + 1, + 4, + 7, + 2, + 1, + 8, + 1, + 4, + 5, + 1, + 1, + 2, + 2, + 4, + 6, + 2, + 7, + 1, + 10, + 1, + 1, + 3, + 4, + 11, + 10, + 8, + 21, + 4, + 6, + 1, + 3, + 5, + 2, + 1, + 2, + 28, + 5, + 5, + 2, + 3, + 13, + 1, + 2, + 3, + 1, + 4, + 2, + 1, + 5, + 20, + 3, + 8, + 11, + 1, + 3, + 3, + 3, + 1, + 8, + 10, + 9, + 2, + 10, + 9, + 2, + 3, + 1, + 1, + 2, + 4, + 1, + 8, + 3, + 6, + 1, + 7, + 8, + 6, + 11, + 1, + 4, + 29, + 8, + 4, + 3, + 1, + 2, + 7, + 13, + 1, + 4, + 1, + 6, + 2, + 6, + 12, + 12, + 2, + 20, + 3, + 2, + 3, + 6, + 4, + 8, + 9, + 2, + 7, + 34, + 5, + 1, + 18, + 6, + 1, + 1, + 4, + 4, + 5, + 7, + 9, + 1, + 2, + 2, + 4, + 3, + 4, + 1, + 7, + 2, + 2, + 2, + 6, + 2, + 3, + 25, + 5, + 3, + 6, + 1, + 4, + 6, + 7, + 4, + 2, + 1, + 4, + 2, + 13, + 6, + 4, + 4, + 3, + 1, + 5, + 3, + 4, + 4, + 3, + 2, + 1, + 1, + 4, + 1, + 2, + 1, + 1, + 3, + 1, + 11, + 1, + 6, + 3, + 1, + 7, + 3, + 6, + 2, + 8, + 8, + 6, + 9, + 3, + 4, + 11, + 3, + 2, + 10, + 12, + 2, + 5, + 11, + 1, + 6, + 4, + 5, + 3, + 1, + 8, + 5, + 4, + 6, + 6, + 3, + 5, + 1, + 1, + 3, + 2, + 1, + 2, + 2, + 6, + 17, + 12, + 1, + 10, + 1, + 6, + 12, + 1, + 6, + 6, + 19, + 9, + 6, + 16, + 1, + 13, + 4, + 4, + 15, + 7, + 17, + 6, + 11, + 9, + 15, + 12, + 6, + 7, + 2, + 1, + 2, + 2, + 15, + 9, + 3, + 21, + 4, + 6, + 49, + 18, + 7, + 3, + 2, + 3, + 1, + 6, + 8, + 2, + 2, + 6, + 2, + 9, + 1, + 3, + 6, + 4, + 4, + 1, + 2, + 16, + 2, + 5, + 2, + 1, + 6, + 2, + 3, + 5, + 3, + 1, + 2, + 5, + 1, + 2, + 1, + 9, + 3, + 1, + 8, + 6, + 4, + 8, + 11, + 3, + 1, + 1, + 1, + 1, + 3, + 1, + 13, + 8, + 4, + 1, + 3, + 2, + 2, + 1, + 4, + 1, + 11, + 1, + 5, + 2, + 1, + 5, + 2, + 5, + 8, + 6, + 1, + 1, + 7, + 4, + 3, + 8, + 3, + 2, + 7, + 2, + 1, + 5, + 1, + 5, + 2, + 4, + 7, + 6, + 2, + 8, + 5, + 1, + 11, + 4, + 5, + 3, + 6, + 18, + 1, + 2, + 13, + 3, + 3, + 1, + 21, + 1, + 1, + 4, + 1, + 4, + 1, + 1, + 1, + 8, + 1, + 2, + 2, + 7, + 1, + 2, + 4, + 2, + 2, + 9, + 2, + 1, + 1, + 1, + 4, + 3, + 6, + 3, + 12, + 5, + 1, + 1, + 1, + 5, + 6, + 3, + 2, + 4, + 8, + 2, + 2, + 4, + 2, + 7, + 1, + 8, + 9, + 5, + 2, + 3, + 2, + 1, + 3, + 2, + 13, + 7, + 14, + 6, + 5, + 1, + 1, + 2, + 1, + 4, + 2, + 23, + 2, + 1, + 1, + 6, + 3, + 1, + 4, + 1, + 15, + 3, + 1, + 7, + 3, + 9, + 14, + 1, + 3, + 1, + 4, + 1, + 1, + 5, + 8, + 1, + 3, + 8, + 3, + 8, + 15, + 11, + 4, + 14, + 4, + 4, + 2, + 5, + 5, + 1, + 7, + 1, + 6, + 14, + 7, + 7, + 8, + 5, + 15, + 4, + 8, + 6, + 5, + 6, + 2, + 1, + 13, + 1, + 20, + 15, + 11, + 9, + 2, + 5, + 6, + 2, + 11, + 2, + 6, + 2, + 5, + 1, + 5, + 8, + 4, + 13, + 19, + 25, + 4, + 1, + 1, + 11, + 1, + 34, + 2, + 5, + 9, + 14, + 6, + 2, + 2, + 6, + 1, + 1, + 14, + 1, + 3, + 14, + 13, + 1, + 6, + 12, + 21, + 14, + 14, + 6, + 32, + 17, + 8, + 32, + 9, + 28, + 1, + 2, + 4, + 11, + 8, + 3, + 1, + 14, + 2, + 5, + 15, + 1, + 1, + 1, + 1, + 3, + 6, + 4, + 1, + 3, + 4, + 11, + 3, + 1, + 1, + 11, + 30, + 1, + 5, + 1, + 4, + 1, + 5, + 8, + 1, + 1, + 3, + 2, + 4, + 3, + 17, + 35, + 2, + 6, + 12, + 17, + 3, + 1, + 6, + 2, + 1, + 1, + 12, + 2, + 7, + 3, + 3, + 2, + 1, + 16, + 2, + 8, + 3, + 6, + 5, + 4, + 7, + 3, + 3, + 8, + 1, + 9, + 8, + 5, + 1, + 2, + 1, + 3, + 2, + 8, + 1, + 2, + 9, + 12, + 1, + 1, + 2, + 3, + 8, + 3, + 24, + 12, + 4, + 3, + 7, + 5, + 8, + 3, + 3, + 3, + 3, + 3, + 3, + 1, + 23, + 10, + 3, + 1, + 2, + 2, + 6, + 3, + 1, + 16, + 1, + 16, + 22, + 3, + 10, + 4, + 11, + 6, + 9, + 7, + 7, + 3, + 6, + 2, + 2, + 2, + 4, + 10, + 2, + 1, + 1, + 2, + 8, + 7, + 1, + 6, + 4, + 1, + 3, + 3, + 3, + 5, + 10, + 12, + 12, + 2, + 3, + 12, + 8, + 15, + 1, + 1, + 16, + 6, + 6, + 1, + 5, + 9, + 11, + 4, + 11, + 4, + 2, + 6, + 12, + 1, + 17, + 5, + 13, + 1, + 4, + 9, + 5, + 1, + 11, + 2, + 1, + 8, + 1, + 5, + 7, + 28, + 8, + 3, + 5, + 10, + 2, + 17, + 3, + 38, + 22, + 1, + 2, + 18, + 12, + 10, + 4, + 38, + 18, + 1, + 4, + 44, + 19, + 4, + 1, + 8, + 4, + 1, + 12, + 1, + 4, + 31, + 12, + 1, + 14, + 7, + 75, + 7, + 5, + 10, + 6, + 6, + 13, + 3, + 2, + 11, + 11, + 3, + 2, + 5, + 28, + 15, + 6, + 18, + 18, + 5, + 6, + 4, + 3, + 16, + 1, + 7, + 18, + 7, + 36, + 3, + 5, + 3, + 1, + 7, + 1, + 9, + 1, + 10, + 7, + 2, + 4, + 2, + 6, + 2, + 9, + 7, + 4, + 3, + 32, + 12, + 3, + 7, + 10, + 2, + 23, + 16, + 3, + 1, + 12, + 3, + 31, + 4, + 11, + 1, + 3, + 8, + 9, + 5, + 1, + 30, + 15, + 6, + 12, + 3, + 2, + 2, + 11, + 19, + 9, + 14, + 2, + 6, + 2, + 3, + 19, + 13, + 17, + 5, + 3, + 3, + 25, + 3, + 14, + 1, + 1, + 1, + 36, + 1, + 3, + 2, + 19, + 3, + 13, + 36, + 9, + 13, + 31, + 6, + 4, + 16, + 34, + 2, + 5, + 4, + 2, + 3, + 3, + 5, + 1, + 1, + 1, + 4, + 3, + 1, + 17, + 3, + 2, + 3, + 5, + 3, + 1, + 3, + 2, + 3, + 5, + 6, + 3, + 12, + 11, + 1, + 3, + 1, + 2, + 26, + 7, + 12, + 7, + 2, + 14, + 3, + 3, + 7, + 7, + 11, + 25, + 25, + 28, + 16, + 4, + 36, + 1, + 2, + 1, + 6, + 2, + 1, + 9, + 3, + 27, + 17, + 4, + 3, + 4, + 13, + 4, + 1, + 3, + 2, + 2, + 1, + 10, + 4, + 2, + 4, + 6, + 3, + 8, + 2, + 1, + 18, + 1, + 1, + 24, + 2, + 2, + 4, + 33, + 2, + 3, + 63, + 7, + 1, + 6, + 40, + 7, + 3, + 4, + 4, + 2, + 4, + 15, + 18, + 1, + 16, + 1, + 1, + 11, + 2, + 41, + 14, + 1, + 3, + 18, + 13, + 3, + 2, + 4, + 16, + 2, + 17, + 7, + 15, + 24, + 7, + 18, + 13, + 44, + 2, + 2, + 3, + 6, + 1, + 1, + 7, + 5, + 1, + 7, + 1, + 4, + 3, + 3, + 5, + 10, + 8, + 2, + 3, + 1, + 8, + 1, + 1, + 27, + 4, + 2, + 1, + 12, + 1, + 2, + 1, + 10, + 6, + 1, + 6, + 7, + 5, + 2, + 3, + 7, + 11, + 5, + 11, + 3, + 6, + 6, + 2, + 3, + 15, + 4, + 9, + 1, + 1, + 2, + 1, + 2, + 11, + 2, + 8, + 12, + 8, + 5, + 4, + 2, + 3, + 1, + 5, + 2, + 2, + 1, + 14, + 1, + 12, + 11, + 4, + 1, + 11, + 17, + 17, + 4, + 3, + 2, + 5, + 5, + 7, + 3, + 1, + 5, + 9, + 9, + 8, + 2, + 5, + 6, + 6, + 13, + 13, + 2, + 1, + 2, + 6, + 1, + 2, + 2, + 49, + 4, + 9, + 1, + 2, + 10, + 16, + 7, + 8, + 4, + 3, + 2, + 23, + 4, + 58, + 3, + 29, + 1, + 14, + 19, + 19, + 11, + 11, + 2, + 7, + 5, + 1, + 3, + 4, + 6, + 2, + 18, + 5, + 12, + 12, + 17, + 17, + 3, + 3, + 2, + 4, + 1, + 6, + 2, + 3, + 4, + 3, + 1, + 1, + 1, + 1, + 5, + 1, + 1, + 9, + 1, + 3, + 1, + 3, + 6, + 1, + 8, + 1, + 1, + 2, + 6, + 4, + 14, + 3, + 1, + 4, + 11, + 4, + 1, + 3, + 32, + 1, + 2, + 4, + 13, + 4, + 1, + 2, + 4, + 2, + 1, + 3, + 1, + 11, + 1, + 4, + 2, + 1, + 4, + 4, + 6, + 3, + 5, + 1, + 6, + 5, + 7, + 6, + 3, + 23, + 3, + 5, + 3, + 5, + 3, + 3, + 13, + 3, + 9, + 10, + 1, + 12, + 10, + 2, + 3, + 18, + 13, + 7, + 160, + 52, + 4, + 2, + 2, + 3, + 2, + 14, + 5, + 4, + 12, + 4, + 6, + 4, + 1, + 20, + 4, + 11, + 6, + 2, + 12, + 27, + 1, + 4, + 1, + 2, + 2, + 7, + 4, + 5, + 2, + 28, + 3, + 7, + 25, + 8, + 3, + 19, + 3, + 6, + 10, + 2, + 2, + 1, + 10, + 2, + 5, + 4, + 1, + 3, + 4, + 1, + 5, + 3, + 2, + 6, + 9, + 3, + 6, + 2, + 16, + 3, + 3, + 16, + 4, + 5, + 5, + 3, + 2, + 1, + 2, + 16, + 15, + 8, + 2, + 6, + 21, + 2, + 4, + 1, + 22, + 5, + 8, + 1, + 1, + 21, + 11, + 2, + 1, + 11, + 11, + 19, + 13, + 12, + 4, + 2, + 3, + 2, + 3, + 6, + 1, + 8, + 11, + 1, + 4, + 2, + 9, + 5, + 2, + 1, + 11, + 2, + 9, + 1, + 1, + 2, + 14, + 31, + 9, + 3, + 4, + 21, + 14, + 4, + 8, + 1, + 7, + 2, + 2, + 2, + 5, + 1, + 4, + 20, + 3, + 3, + 4, + 10, + 1, + 11, + 9, + 8, + 2, + 1, + 4, + 5, + 14, + 12, + 14, + 2, + 17, + 9, + 6, + 31, + 4, + 14, + 1, + 20, + 13, + 26, + 5, + 2, + 7, + 3, + 6, + 13, + 2, + 4, + 2, + 19, + 6, + 2, + 2, + 18, + 9, + 3, + 5, + 12, + 12, + 14, + 4, + 6, + 2, + 3, + 6, + 9, + 5, + 22, + 4, + 5, + 25, + 6, + 4, + 8, + 5, + 2, + 6, + 27, + 2, + 35, + 2, + 16, + 3, + 7, + 8, + 8, + 6, + 6, + 5, + 9, + 17, + 2, + 20, + 6, + 19, + 2, + 13, + 3, + 1, + 1, + 1, + 4, + 17, + 12, + 2, + 14, + 7, + 1, + 4, + 18, + 12, + 38, + 33, + 2, + 10, + 1, + 1, + 2, + 13, + 14, + 17, + 11, + 50, + 6, + 33, + 20, + 26, + 74, + 16, + 23, + 45, + 50, + 13, + 38, + 33, + 6, + 6, + 7, + 4, + 4, + 2, + 1, + 3, + 2, + 5, + 8, + 7, + 8, + 9, + 3, + 11, + 21, + 9, + 13, + 1, + 3, + 10, + 6, + 7, + 1, + 2, + 2, + 18, + 5, + 5, + 1, + 9, + 9, + 2, + 68, + 9, + 19, + 13, + 2, + 5, + 1, + 4, + 4, + 7, + 4, + 13, + 3, + 9, + 10, + 21, + 17, + 3, + 26, + 2, + 1, + 5, + 2, + 4, + 5, + 4, + 1, + 7, + 4, + 7, + 3, + 4, + 2, + 1, + 6, + 1, + 1, + 20, + 4, + 1, + 9, + 2, + 2, + 1, + 3, + 3, + 2, + 3, + 2, + 1, + 1, + 1, + 20, + 2, + 3, + 1, + 6, + 2, + 3, + 6, + 2, + 4, + 8, + 1, + 3, + 2, + 10, + 3, + 5, + 3, + 4, + 4, + 3, + 4, + 16, + 1, + 6, + 1, + 10, + 2, + 4, + 2, + 1, + 1, + 2, + 10, + 11, + 2, + 2, + 3, + 1, + 24, + 31, + 4, + 10, + 10, + 2, + 5, + 12, + 16, + 164, + 15, + 4, + 16, + 7, + 9, + 15, + 19, + 17, + 1, + 2, + 1, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 3, + 1, + 4, + 3, + 1, + 3, + 1, + 3, + 1, + 2, + 1, + 1, + 3, + 3, + 7, + 2, + 8, + 1, + 2, + 2, + 2, + 1, + 3, + 4, + 3, + 7, + 8, + 12, + 92, + 2, + 10, + 3, + 1, + 3, + 14, + 5, + 25, + 16, + 42, + 4, + 7, + 7, + 4, + 2, + 21, + 5, + 27, + 26, + 27, + 21, + 25, + 30, + 31, + 2, + 1, + 5, + 13, + 3, + 22, + 5, + 6, + 6, + 11, + 9, + 12, + 1, + 5, + 9, + 7, + 5, + 5, + 22, + 60, + 3, + 5, + 13, + 1, + 1, + 8, + 1, + 1, + 3, + 3, + 2, + 1, + 9, + 3, + 3, + 18, + 4, + 1, + 2, + 3, + 7, + 6, + 3, + 1, + 2, + 3, + 9, + 1, + 3, + 1, + 3, + 2, + 1, + 3, + 1, + 1, + 1, + 2, + 1, + 11, + 3, + 1, + 6, + 9, + 1, + 3, + 2, + 3, + 1, + 2, + 1, + 5, + 1, + 1, + 4, + 3, + 4, + 1, + 2, + 2, + 4, + 4, + 1, + 7, + 2, + 1, + 2, + 2, + 3, + 5, + 13, + 18, + 3, + 4, + 14, + 9, + 9, + 4, + 16, + 3, + 7, + 5, + 8, + 2, + 6, + 48, + 28, + 3, + 1, + 1, + 4, + 2, + 14, + 8, + 2, + 9, + 2, + 1, + 15, + 2, + 4, + 3, + 2, + 10, + 16, + 12, + 8, + 7, + 1, + 1, + 3, + 1, + 1, + 1, + 2, + 7, + 4, + 1, + 6, + 4, + 38, + 39, + 16, + 23, + 7, + 15, + 15, + 3, + 2, + 12, + 7, + 21, + 37, + 27, + 6, + 5, + 4, + 8, + 2, + 10, + 8, + 8, + 6, + 5, + 1, + 2, + 1, + 3, + 24, + 1, + 16, + 17, + 9, + 23, + 10, + 17, + 6, + 1, + 51, + 55, + 44, + 13, + 294, + 9, + 3, + 6, + 2, + 4, + 2, + 2, + 15, + 1, + 1, + 1, + 13, + 21, + 17, + 68, + 14, + 8, + 9, + 4, + 1, + 4, + 9, + 3, + 11, + 7, + 1, + 1, + 1, + 5, + 6, + 3, + 2, + 1, + 1, + 1, + 2, + 3, + 8, + 1, + 2, + 2, + 4, + 1, + 5, + 5, + 2, + 1, + 4, + 3, + 7, + 13, + 4, + 1, + 4, + 1, + 3, + 1, + 1, + 1, + 5, + 5, + 10, + 1, + 6, + 1, + 5, + 2, + 1, + 5, + 2, + 4, + 1, + 4, + 5, + 7, + 3, + 18, + 2, + 9, + 11, + 32, + 4, + 3, + 3, + 2, + 4, + 7, + 11, + 16, + 9, + 11, + 8, + 13, + 38, + 32, + 8, + 4, + 2, + 1, + 1, + 2, + 1, + 2, + 4, + 4, + 1, + 1, + 1, + 4, + 1, + 21, + 3, + 11, + 1, + 16, + 1, + 1, + 6, + 1, + 3, + 2, + 4, + 9, + 8, + 57, + 7, + 44, + 1, + 3, + 3, + 13, + 3, + 10, + 1, + 1, + 7, + 5, + 2, + 7, + 21, + 47, + 63, + 3, + 15, + 4, + 7, + 1, + 16, + 1, + 1, + 2, + 8, + 2, + 3, + 42, + 15, + 4, + 1, + 29, + 7, + 22, + 10, + 3, + 78, + 16, + 12, + 20, + 18, + 4, + 67, + 11, + 5, + 1, + 3, + 15, + 6, + 21, + 31, + 32, + 27, + 18, + 13, + 71, + 35, + 5, + 142, + 4, + 10, + 1, + 2, + 50, + 19, + 33, + 16, + 35, + 37, + 16, + 19, + 27, + 7, + 1, + 133, + 19, + 1, + 4, + 8, + 7, + 20, + 1, + 4, + 4, + 1, + 10, + 3, + 1, + 6, + 1, + 2, + 51, + 5, + 40, + 15, + 24, + 43, + 22928, + 11, + 1, + 13, + 154, + 70, + 3, + 1, + 1, + 7, + 4, + 10, + 1, + 2, + 1, + 1, + 2, + 1, + 2, + 1, + 2, + 2, + 1, + 1, + 2, + 1, + 1, + 1, + 1, + 1, + 2, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 1, + 1, + 1, + 3, + 2, + 1, + 1, + 1, + 1, + 2, + 1, + 1, + }; + static ImWchar base_ranges[] = // not zero-terminated + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + 0xFFFD, 0xFFFD // Invalid + }; + static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00) * 2 + 1] = {0}; + if (!full_ranges[0]) + { + memcpy(full_ranges, base_ranges, sizeof(base_ranges)); + UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges)); + } + return &full_ranges[0]; +} + +const ImWchar *ImFontAtlas::GetGlyphRangesCyrillic() +{ + static const ImWchar ranges[] = + { + 0x0020, + 0x00FF, // Basic Latin + Latin Supplement + 0x0400, + 0x052F, // Cyrillic + Cyrillic Supplement + 0x2DE0, + 0x2DFF, // Cyrillic Extended-A + 0xA640, + 0xA69F, // Cyrillic Extended-B + 0, + }; + return &ranges[0]; +} + +const ImWchar *ImFontAtlas::GetGlyphRangesThai() +{ + static const ImWchar ranges[] = + { + 0x0020, + 0x00FF, // Basic Latin + 0x2010, + 0x205E, // Punctuations + 0x0E00, + 0x0E7F, // Thai + 0, + }; + return &ranges[0]; +} + +const ImWchar *ImFontAtlas::GetGlyphRangesVietnamese() +{ + static const ImWchar ranges[] = + { + 0x0020, + 0x00FF, // Basic Latin + 0x0102, + 0x0103, + 0x0110, + 0x0111, + 0x0128, + 0x0129, + 0x0168, + 0x0169, + 0x01A0, + 0x01A1, + 0x01AF, + 0x01B0, + 0x1EA0, + 0x1EF9, + 0, + }; + return &ranges[0]; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontGlyphRangesBuilder +//----------------------------------------------------------------------------- + +void ImFontGlyphRangesBuilder::AddText(const char *text, const char *text_end) +{ + while (text_end ? (text < text_end) : *text) + { + unsigned int c = 0; + int c_len = ImTextCharFromUtf8(&c, text, text_end); + text += c_len; + if (c_len == 0) + break; + AddChar((ImWchar)c); + } +} + +void ImFontGlyphRangesBuilder::AddRanges(const ImWchar *ranges) +{ + for (; ranges[0]; ranges += 2) + for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560 + AddChar((ImWchar)c); +} + +void ImFontGlyphRangesBuilder::BuildRanges(ImVector *out_ranges) +{ + const int max_codepoint = IM_UNICODE_CODEPOINT_MAX; + for (int n = 0; n <= max_codepoint; n++) + if (GetBit(n)) + { + out_ranges->push_back((ImWchar)n); + while (n < max_codepoint && GetBit(n + 1)) + n++; + out_ranges->push_back((ImWchar)n); + } + out_ranges->push_back(0); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFont +//----------------------------------------------------------------------------- + +ImFont::ImFont() +{ + FontSize = 0.0f; + FallbackAdvanceX = 0.0f; + FallbackChar = (ImWchar)-1; + EllipsisChar = (ImWchar)-1; + DotChar = (ImWchar)-1; + FallbackGlyph = NULL; + ContainerAtlas = NULL; + ConfigData = NULL; + ConfigDataCount = 0; + DirtyLookupTables = false; + Scale = 1.0f; + Ascent = Descent = 0.0f; + MetricsTotalSurface = 0; + memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap)); +} + +ImFont::~ImFont() +{ + ClearOutputData(); +} + +void ImFont::ClearOutputData() +{ + FontSize = 0.0f; + FallbackAdvanceX = 0.0f; + Glyphs.clear(); + IndexAdvanceX.clear(); + IndexLookup.clear(); + FallbackGlyph = NULL; + ContainerAtlas = NULL; + DirtyLookupTables = true; + Ascent = Descent = 0.0f; + MetricsTotalSurface = 0; +} + +static ImWchar FindFirstExistingGlyph(ImFont *font, const ImWchar *candidate_chars, int candidate_chars_count) +{ + for (int n = 0; n < candidate_chars_count; n++) + if (font->FindGlyphNoFallback(candidate_chars[n]) != NULL) + return candidate_chars[n]; + return (ImWchar)-1; +} + +void ImFont::BuildLookupTable() +{ + int max_codepoint = 0; + for (int i = 0; i != Glyphs.Size; i++) + max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); + + // Build lookup table + IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved + IndexAdvanceX.clear(); + IndexLookup.clear(); + DirtyLookupTables = false; + memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap)); + GrowIndex(max_codepoint + 1); + for (int i = 0; i < Glyphs.Size; i++) + { + int codepoint = (int)Glyphs[i].Codepoint; + IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX; + IndexLookup[codepoint] = (ImWchar)i; + + // Mark 4K page as used + const int page_n = codepoint / 4096; + Used4kPagesMap[page_n >> 3] |= 1 << (page_n & 7); + } + + // Create a glyph to handle TAB + // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) + if (FindGlyph((ImWchar)' ')) + { + if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times (FIXME: Flaky) + Glyphs.resize(Glyphs.Size + 1); + ImFontGlyph &tab_glyph = Glyphs.back(); + tab_glyph = *FindGlyph((ImWchar)' '); + tab_glyph.Codepoint = '\t'; + tab_glyph.AdvanceX *= IM_TABSIZE; + IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX; + IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size - 1); + } + + // Mark special glyphs as not visible (note that AddGlyph already mark as non-visible glyphs with zero-size polygons) + SetGlyphVisible((ImWchar)' ', false); + SetGlyphVisible((ImWchar)'\t', false); + + // Ellipsis character is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis). + // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character. + // FIXME: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots. + const ImWchar ellipsis_chars[] = {(ImWchar)0x2026, (ImWchar)0x0085}; + const ImWchar dots_chars[] = {(ImWchar)'.', (ImWchar)0xFF0E}; + if (EllipsisChar == (ImWchar)-1) + EllipsisChar = FindFirstExistingGlyph(this, ellipsis_chars, IM_ARRAYSIZE(ellipsis_chars)); + if (DotChar == (ImWchar)-1) + DotChar = FindFirstExistingGlyph(this, dots_chars, IM_ARRAYSIZE(dots_chars)); + + // Setup fallback character + const ImWchar fallback_chars[] = {(ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' '}; + FallbackGlyph = FindGlyphNoFallback(FallbackChar); + if (FallbackGlyph == NULL) + { + FallbackChar = FindFirstExistingGlyph(this, fallback_chars, IM_ARRAYSIZE(fallback_chars)); + FallbackGlyph = FindGlyphNoFallback(FallbackChar); + if (FallbackGlyph == NULL) + { + FallbackGlyph = &Glyphs.back(); + FallbackChar = (ImWchar)FallbackGlyph->Codepoint; + } + } + + FallbackAdvanceX = FallbackGlyph->AdvanceX; + for (int i = 0; i < max_codepoint + 1; i++) + if (IndexAdvanceX[i] < 0.0f) + IndexAdvanceX[i] = FallbackAdvanceX; +} + +// API is designed this way to avoid exposing the 4K page size +// e.g. use with IsGlyphRangeUnused(0, 255) +bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last) +{ + unsigned int page_begin = (c_begin / 4096); + unsigned int page_last = (c_last / 4096); + for (unsigned int page_n = page_begin; page_n <= page_last; page_n++) + if ((page_n >> 3) < sizeof(Used4kPagesMap)) + if (Used4kPagesMap[page_n >> 3] & (1 << (page_n & 7))) + return false; + return true; +} + +void ImFont::SetGlyphVisible(ImWchar c, bool visible) +{ + if (ImFontGlyph *glyph = (ImFontGlyph *)(void *)FindGlyph((ImWchar)c)) + glyph->Visible = visible ? 1 : 0; +} + +void ImFont::GrowIndex(int new_size) +{ + IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size); + if (new_size <= IndexLookup.Size) + return; + IndexAdvanceX.resize(new_size, -1.0f); + IndexLookup.resize(new_size, (ImWchar)-1); +} + +// x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. +// Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). +// 'cfg' is not necessarily == 'this->ConfigData' because multiple source fonts+configs can be used to build one target font. +void ImFont::AddGlyph(const ImFontConfig *cfg, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) +{ + if (cfg != NULL) + { + // Clamp & recenter if needed + const float advance_x_original = advance_x; + advance_x = ImClamp(advance_x, cfg->GlyphMinAdvanceX, cfg->GlyphMaxAdvanceX); + if (advance_x != advance_x_original) + { + float char_off_x = cfg->PixelSnapH ? ImFloor((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f; + x0 += char_off_x; + x1 += char_off_x; + } + + // Snap to pixel + if (cfg->PixelSnapH) + advance_x = IM_ROUND(advance_x); + + // Bake spacing + advance_x += cfg->GlyphExtraSpacing.x; + } + + Glyphs.resize(Glyphs.Size + 1); + ImFontGlyph &glyph = Glyphs.back(); + glyph.Codepoint = (unsigned int)codepoint; + glyph.Visible = (x0 != x1) && (y0 != y1); + glyph.Colored = false; + glyph.X0 = x0; + glyph.Y0 = y0; + glyph.X1 = x1; + glyph.Y1 = y1; + glyph.U0 = u0; + glyph.V0 = v0; + glyph.U1 = u1; + glyph.V1 = v1; + glyph.AdvanceX = advance_x; + + // Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round) + // We use (U1-U0)*TexWidth instead of X1-X0 to account for oversampling. + float pad = ContainerAtlas->TexGlyphPadding + 0.99f; + DirtyLookupTables = true; + MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + pad) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + pad); +} + +void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) +{ + IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. + unsigned int index_size = (unsigned int)IndexLookup.Size; + + if (dst < index_size && IndexLookup.Data[dst] == (ImWchar)-1 && !overwrite_dst) // 'dst' already exists + return; + if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op + return; + + GrowIndex(dst + 1); + IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (ImWchar)-1; + IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f; +} + +const ImFontGlyph *ImFont::FindGlyph(ImWchar c) const +{ + if (c >= (size_t)IndexLookup.Size) + return FallbackGlyph; + const ImWchar i = IndexLookup.Data[c]; + if (i == (ImWchar)-1) + return FallbackGlyph; + return &Glyphs.Data[i]; +} + +const ImFontGlyph *ImFont::FindGlyphNoFallback(ImWchar c) const +{ + if (c >= (size_t)IndexLookup.Size) + return NULL; + const ImWchar i = IndexLookup.Data[c]; + if (i == (ImWchar)-1) + return NULL; + return &Glyphs.Data[i]; +} + +const char *ImFont::CalcWordWrapPositionA(float scale, const char *text, const char *text_end, float wrap_width) const +{ + // Simple word-wrapping for English, not full-featured. Please submit failing cases! + // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) + + // For references, possible wrap point marked with ^ + // "aaa bbb, ccc,ddd. eee fff. ggg!" + // ^ ^ ^ ^ ^__ ^ ^ + + // List of hardcoded separators: .,;!?'" + + // Skip extra blanks after a line returns (that includes not counting them in width computation) + // e.g. "Hello world" --> "Hello" "World" + + // Cut words that cannot possibly fit within one line. + // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + + float line_width = 0.0f; + float word_width = 0.0f; + float blank_width = 0.0f; + wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters + + const char *word_end = text; + const char *prev_word_end = NULL; + bool inside_word = true; + + const char *s = text; + while (s < text_end) + { + unsigned int c = (unsigned int)*s; + const char *next_s; + if (c < 0x80) + next_s = s + 1; + else + next_s = s + ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) + break; + + if (c < 32) + { + if (c == '\n') + { + line_width = word_width = blank_width = 0.0f; + inside_word = true; + s = next_s; + continue; + } + if (c == '\r') + { + s = next_s; + continue; + } + } + + const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX); + if (ImCharIsBlankW(c)) + { + if (inside_word) + { + line_width += blank_width; + blank_width = 0.0f; + word_end = s; + } + blank_width += char_width; + inside_word = false; + } + else + { + word_width += char_width; + if (inside_word) + { + word_end = next_s; + } + else + { + prev_word_end = word_end; + line_width += word_width + blank_width; + word_width = blank_width = 0.0f; + } + + // Allow wrapping after punctuation. + inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\"'); + } + + // We ignore blank width at the end of the line (they can be skipped) + if (line_width + word_width > wrap_width) + { + // Words that cannot possibly fit within an entire line will be cut anywhere. + if (word_width < wrap_width) + s = prev_word_end ? prev_word_end : word_end; + break; + } + + s = next_s; + } + + return s; +} + +ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char *text_begin, const char *text_end, const char **remaining) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. + + const float line_height = size; + const float scale = size / FontSize; + + ImVec2 text_size = ImVec2(0, 0); + float line_width = 0.0f; + + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char *word_wrap_eol = NULL; + + const char *s = text_begin; + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + line_width = 0.0f; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsBlankA(c)) + { + s++; + } + else if (c == '\n') + { + s++; + break; + } + else + { + break; + } + } + continue; + } + } + + // Decode and advance source + const char *prev_s = s; + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) // Malformed UTF-8? + break; + } + + if (c < 32) + { + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + continue; + } + if (c == '\r') + continue; + } + + const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX) * scale; + if (line_width + char_width >= max_width) + { + s = prev_s; + break; + } + + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (line_width > 0 || text_size.y == 0.0f) + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + +// Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. +void ImFont::RenderChar(ImDrawList *draw_list, float size, const ImVec2 &pos, ImU32 col, ImWchar c) const +{ + const ImFontGlyph *glyph = FindGlyph(c); + if (!glyph || !glyph->Visible) + return; + if (glyph->Colored) + col |= ~IM_COL32_A_MASK; + float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; + float x = IM_FLOOR(pos.x); + float y = IM_FLOOR(pos.y); + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(ImVec2(x + glyph->X0 * scale, y + glyph->Y0 * scale), ImVec2(x + glyph->X1 * scale, y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); +} + +// Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. +void ImFont::RenderText(ImDrawList *draw_list, float size, const ImVec2 &pos, ImU32 col, const ImVec4 &clip_rect, const char *text_begin, const char *text_end, float wrap_width, bool cpu_fine_clip) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. + + // Align to be pixel perfect + float x = IM_FLOOR(pos.x); + float y = IM_FLOOR(pos.y); + if (y > clip_rect.w) + return; + + const float start_x = x; + const float scale = size / FontSize; + const float line_height = FontSize * scale; + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char *word_wrap_eol = NULL; + + // Fast-forward to first visible line + const char *s = text_begin; + if (y + line_height < clip_rect.y && !word_wrap_enabled) + while (y + line_height < clip_rect.y && s < text_end) + { + s = (const char *)memchr(s, '\n', text_end - s); + s = s ? s + 1 : text_end; + y += line_height; + } + + // For large text, scan for the last visible line in order to avoid over-reserving in the call to PrimReserve() + // Note that very large horizontal line will still be affected by the issue (e.g. a one megabyte string buffer without a newline will likely crash atm) + if (text_end - s > 10000 && !word_wrap_enabled) + { + const char *s_end = s; + float y_end = y; + while (y_end < clip_rect.w && s_end < text_end) + { + s_end = (const char *)memchr(s_end, '\n', text_end - s_end); + s_end = s_end ? s_end + 1 : text_end; + y_end += line_height; + } + text_end = s_end; + } + if (s == text_end) + return; + + // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) + const int vtx_count_max = (int)(text_end - s) * 4; + const int idx_count_max = (int)(text_end - s) * 6; + const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; + draw_list->PrimReserve(idx_count_max, vtx_count_max); + + ImDrawVert *vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx *idx_write = draw_list->_IdxWritePtr; + unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx; + + const ImU32 col_untinted = col | ~IM_COL32_A_MASK; + + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - start_x)); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + x = start_x; + y += line_height; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsBlankA(c)) + { + s++; + } + else if (c == '\n') + { + s++; + break; + } + else + { + break; + } + } + continue; + } + } + + // Decode and advance source + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) // Malformed UTF-8? + break; + } + + if (c < 32) + { + if (c == '\n') + { + x = start_x; + y += line_height; + if (y > clip_rect.w) + break; // break out of main loop + continue; + } + if (c == '\r') + continue; + } + + const ImFontGlyph *glyph = FindGlyph((ImWchar)c); + if (glyph == NULL) + continue; + + float char_width = glyph->AdvanceX * scale; + if (glyph->Visible) + { + // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w + float x1 = x + glyph->X0 * scale; + float x2 = x + glyph->X1 * scale; + float y1 = y + glyph->Y0 * scale; + float y2 = y + glyph->Y1 * scale; + if (x1 <= clip_rect.z && x2 >= clip_rect.x) + { + // Render a character + float u1 = glyph->U0; + float v1 = glyph->V0; + float u2 = glyph->U1; + float v2 = glyph->V1; + + // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. + if (cpu_fine_clip) + { + if (x1 < clip_rect.x) + { + u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1); + x1 = clip_rect.x; + } + if (y1 < clip_rect.y) + { + v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1); + y1 = clip_rect.y; + } + if (x2 > clip_rect.z) + { + u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1); + x2 = clip_rect.z; + } + if (y2 > clip_rect.w) + { + v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1); + y2 = clip_rect.w; + } + if (y1 >= y2) + { + x += char_width; + continue; + } + } + + // Support for untinted glyphs + ImU32 glyph_col = glyph->Colored ? col_untinted : col; + + // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here: + { + idx_write[0] = (ImDrawIdx)(vtx_current_idx); + idx_write[1] = (ImDrawIdx)(vtx_current_idx + 1); + idx_write[2] = (ImDrawIdx)(vtx_current_idx + 2); + idx_write[3] = (ImDrawIdx)(vtx_current_idx); + idx_write[4] = (ImDrawIdx)(vtx_current_idx + 2); + idx_write[5] = (ImDrawIdx)(vtx_current_idx + 3); + vtx_write[0].pos.x = x1; + vtx_write[0].pos.y = y1; + vtx_write[0].col = glyph_col; + vtx_write[0].uv.x = u1; + vtx_write[0].uv.y = v1; + vtx_write[1].pos.x = x2; + vtx_write[1].pos.y = y1; + vtx_write[1].col = glyph_col; + vtx_write[1].uv.x = u2; + vtx_write[1].uv.y = v1; + vtx_write[2].pos.x = x2; + vtx_write[2].pos.y = y2; + vtx_write[2].col = glyph_col; + vtx_write[2].uv.x = u2; + vtx_write[2].uv.y = v2; + vtx_write[3].pos.x = x1; + vtx_write[3].pos.y = y2; + vtx_write[3].col = glyph_col; + vtx_write[3].uv.x = u1; + vtx_write[3].uv.y = v2; + vtx_write += 4; + vtx_current_idx += 4; + idx_write += 6; + } + } + } + x += char_width; + } + + // Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. + draw_list->VtxBuffer.Size = (int)(vtx_write - draw_list->VtxBuffer.Data); // Same as calling shrink() + draw_list->IdxBuffer.Size = (int)(idx_write - draw_list->IdxBuffer.Data); + draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); + draw_list->_VtxWritePtr = vtx_write; + draw_list->_IdxWritePtr = idx_write; + draw_list->_VtxCurrentIdx = vtx_current_idx; +} + +//----------------------------------------------------------------------------- +// [SECTION] ImGui Internal Render Helpers +//----------------------------------------------------------------------------- +// Vaguely redesigned to stop accessing ImGui global state: +// - RenderArrow() +// - RenderBullet() +// - RenderCheckMark() +// - RenderArrowDockMenu() +// - RenderArrowPointingAt() +// - RenderRectFilledRangeH() +// - RenderRectFilledWithHole() +//----------------------------------------------------------------------------- +// Function in need of a redesign (legacy mess) +// - RenderColorRectWithAlphaCheckerboard() +//----------------------------------------------------------------------------- + +// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state +void ImGui::RenderArrow(ImDrawList *draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale) +{ + const float h = draw_list->_Data->FontSize * 1.00f; + float r = h * 0.40f * scale; + ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale); + + ImVec2 a, b, c; + switch (dir) + { + case ImGuiDir_Up: + case ImGuiDir_Down: + if (dir == ImGuiDir_Up) + r = -r; + a = ImVec2(+0.000f, +0.750f) * r; + b = ImVec2(-0.866f, -0.750f) * r; + c = ImVec2(+0.866f, -0.750f) * r; + break; + case ImGuiDir_Left: + case ImGuiDir_Right: + if (dir == ImGuiDir_Left) + r = -r; + a = ImVec2(+0.750f, +0.000f) * r; + b = ImVec2(-0.750f, +0.866f) * r; + c = ImVec2(-0.750f, -0.866f) * r; + break; + case ImGuiDir_None: + case ImGuiDir_COUNT: + IM_ASSERT(0); + break; + } + draw_list->AddTriangleFilled(center + a, center + b, center + c, col); +} + +void ImGui::RenderBullet(ImDrawList *draw_list, ImVec2 pos, ImU32 col) +{ + draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8); +} + +void ImGui::RenderCheckMark(ImDrawList *draw_list, ImVec2 pos, ImU32 col, float sz) +{ + float thickness = ImMax(sz / 5.0f, 1.0f); + sz -= thickness * 0.5f; + pos += ImVec2(thickness * 0.25f, thickness * 0.25f); + + float third = sz / 3.0f; + float bx = pos.x + third; + float by = pos.y + sz - third * 0.5f; + draw_list->PathLineTo(ImVec2(bx - third, by - third)); + draw_list->PathLineTo(ImVec2(bx, by)); + draw_list->PathLineTo(ImVec2(bx + third * 2.0f, by - third * 2.0f)); + draw_list->PathStroke(col, 0, thickness); +} + +// Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. +void ImGui::RenderArrowPointingAt(ImDrawList *draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col) +{ + switch (direction) + { + case ImGuiDir_Left: + draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); + return; + case ImGuiDir_Right: + draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); + return; + case ImGuiDir_Up: + draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); + return; + case ImGuiDir_Down: + draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); + return; + case ImGuiDir_None: + case ImGuiDir_COUNT: + break; // Fix warnings + } +} + +// This is less wide than RenderArrow() and we use in dock nodes instead of the regular RenderArrow() to denote a change of functionality, +// and because the saved space means that the left-most tab label can stay at exactly the same position as the label of a loose window. +void ImGui::RenderArrowDockMenu(ImDrawList *draw_list, ImVec2 p_min, float sz, ImU32 col) +{ + draw_list->AddRectFilled(p_min + ImVec2(sz * 0.20f, sz * 0.15f), p_min + ImVec2(sz * 0.80f, sz * 0.30f), col); + RenderArrowPointingAt(draw_list, p_min + ImVec2(sz * 0.50f, sz * 0.85f), ImVec2(sz * 0.30f, sz * 0.40f), ImGuiDir_Down, col); +} + +static inline float ImAcos01(float x) +{ + if (x <= 0.0f) + return IM_PI * 0.5f; + if (x >= 1.0f) + return 0.0f; + return ImAcos(x); + // return (-0.69813170079773212f * x * x - 0.87266462599716477f) * x + 1.5707963267948966f; // Cheap approximation, may be enough for what we do. +} + +// FIXME: Cleanup and move code to ImDrawList. +void ImGui::RenderRectFilledRangeH(ImDrawList *draw_list, const ImRect &rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding) +{ + if (x_end_norm == x_start_norm) + return; + if (x_start_norm > x_end_norm) + ImSwap(x_start_norm, x_end_norm); + + ImVec2 p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y); + ImVec2 p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y); + if (rounding == 0.0f) + { + draw_list->AddRectFilled(p0, p1, col, 0.0f); + return; + } + + rounding = ImClamp(ImMin((rect.Max.x - rect.Min.x) * 0.5f, (rect.Max.y - rect.Min.y) * 0.5f) - 1.0f, 0.0f, rounding); + const float inv_rounding = 1.0f / rounding; + const float arc0_b = ImAcos01(1.0f - (p0.x - rect.Min.x) * inv_rounding); + const float arc0_e = ImAcos01(1.0f - (p1.x - rect.Min.x) * inv_rounding); + const float half_pi = IM_PI * 0.5f; // We will == compare to this because we know this is the exact value ImAcos01 can return. + const float x0 = ImMax(p0.x, rect.Min.x + rounding); + if (arc0_b == arc0_e) + { + draw_list->PathLineTo(ImVec2(x0, p1.y)); + draw_list->PathLineTo(ImVec2(x0, p0.y)); + } + else if (arc0_b == 0.0f && arc0_e == half_pi) + { + draw_list->PathArcToFast(ImVec2(x0, p1.y - rounding), rounding, 3, 6); // BL + draw_list->PathArcToFast(ImVec2(x0, p0.y + rounding), rounding, 6, 9); // TR + } + else + { + draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b, 3); // BL + draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e, 3); // TR + } + if (p1.x > rect.Min.x + rounding) + { + const float arc1_b = ImAcos01(1.0f - (rect.Max.x - p1.x) * inv_rounding); + const float arc1_e = ImAcos01(1.0f - (rect.Max.x - p0.x) * inv_rounding); + const float x1 = ImMin(p1.x, rect.Max.x - rounding); + if (arc1_b == arc1_e) + { + draw_list->PathLineTo(ImVec2(x1, p0.y)); + draw_list->PathLineTo(ImVec2(x1, p1.y)); + } + else if (arc1_b == 0.0f && arc1_e == half_pi) + { + draw_list->PathArcToFast(ImVec2(x1, p0.y + rounding), rounding, 9, 12); // TR + draw_list->PathArcToFast(ImVec2(x1, p1.y - rounding), rounding, 0, 3); // BR + } + else + { + draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b, 3); // TR + draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e, 3); // BR + } + } + draw_list->PathFillConvex(col); +} + +void ImGui::RenderRectFilledWithHole(ImDrawList *draw_list, const ImRect &outer, const ImRect &inner, ImU32 col, float rounding) +{ + const bool fill_L = (inner.Min.x > outer.Min.x); + const bool fill_R = (inner.Max.x < outer.Max.x); + const bool fill_U = (inner.Min.y > outer.Min.y); + const bool fill_D = (inner.Max.y < outer.Max.y); + if (fill_L) + draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Min.y), ImVec2(inner.Min.x, inner.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_U ? 0 : ImDrawFlags_RoundCornersTopLeft) | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomLeft)); + if (fill_R) + draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Min.y), ImVec2(outer.Max.x, inner.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_U ? 0 : ImDrawFlags_RoundCornersTopRight) | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomRight)); + if (fill_U) + draw_list->AddRectFilled(ImVec2(inner.Min.x, outer.Min.y), ImVec2(inner.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_L ? 0 : ImDrawFlags_RoundCornersTopLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersTopRight)); + if (fill_D) + draw_list->AddRectFilled(ImVec2(inner.Min.x, inner.Max.y), ImVec2(inner.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_L ? 0 : ImDrawFlags_RoundCornersBottomLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersBottomRight)); + if (fill_L && fill_U) + draw_list->AddRectFilled(ImVec2(outer.Min.x, outer.Min.y), ImVec2(inner.Min.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopLeft); + if (fill_R && fill_U) + draw_list->AddRectFilled(ImVec2(inner.Max.x, outer.Min.y), ImVec2(outer.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopRight); + if (fill_L && fill_D) + draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Max.y), ImVec2(inner.Min.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomLeft); + if (fill_R && fill_D) + draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomRight); +} + +ImDrawFlags ImGui::CalcRoundingFlagsForRectInRect(const ImRect &r_in, const ImRect &r_outer, float threshold) +{ + bool round_l = r_in.Min.x <= r_outer.Min.x + threshold; + bool round_r = r_in.Max.x >= r_outer.Max.x - threshold; + bool round_t = r_in.Min.y <= r_outer.Min.y + threshold; + bool round_b = r_in.Max.y >= r_outer.Max.y - threshold; + return ImDrawFlags_RoundCornersNone | ((round_t && round_l) ? ImDrawFlags_RoundCornersTopLeft : 0) | ((round_t && round_r) ? ImDrawFlags_RoundCornersTopRight : 0) | ((round_b && round_l) ? ImDrawFlags_RoundCornersBottomLeft : 0) | ((round_b && round_r) ? ImDrawFlags_RoundCornersBottomRight : 0); +} + +// Helper for ColorPicker4() +// NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. +// Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether. +// FIXME: uses ImGui::GetColorU32 +void ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList *draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, ImDrawFlags flags) +{ + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags = ImDrawFlags_RoundCornersDefault_; + if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF) + { + ImU32 col_bg1 = GetColorU32(ImAlphaBlendColors(IM_COL32(204, 204, 204, 255), col)); + ImU32 col_bg2 = GetColorU32(ImAlphaBlendColors(IM_COL32(128, 128, 128, 255), col)); + draw_list->AddRectFilled(p_min, p_max, col_bg1, rounding, flags); + + int yi = 0; + for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++) + { + float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y); + if (y2 <= y1) + continue; + for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f) + { + float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x); + if (x2 <= x1) + continue; + ImDrawFlags cell_flags = ImDrawFlags_RoundCornersNone; + if (y1 <= p_min.y) + { + if (x1 <= p_min.x) + cell_flags |= ImDrawFlags_RoundCornersTopLeft; + if (x2 >= p_max.x) + cell_flags |= ImDrawFlags_RoundCornersTopRight; + } + if (y2 >= p_max.y) + { + if (x1 <= p_min.x) + cell_flags |= ImDrawFlags_RoundCornersBottomLeft; + if (x2 >= p_max.x) + cell_flags |= ImDrawFlags_RoundCornersBottomRight; + } + + // Combine flags + cell_flags = (flags == ImDrawFlags_RoundCornersNone || cell_flags == ImDrawFlags_RoundCornersNone) ? ImDrawFlags_RoundCornersNone : (cell_flags & flags); + draw_list->AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), col_bg2, rounding, cell_flags); + } + } + } + else + { + draw_list->AddRectFilled(p_min, p_max, col, rounding, flags); + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Decompression code +//----------------------------------------------------------------------------- +// Compressed with stb_compress() then converted to a C array and encoded as base85. +// Use the program in misc/fonts/binary_to_compressed_c.cpp to create the array from a TTF file. +// The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size. +// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h +//----------------------------------------------------------------------------- + +static unsigned int stb_decompress_length(const unsigned char *input) +{ + return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; +} + +static unsigned char *stb__barrier_out_e, *stb__barrier_out_b; +static const unsigned char *stb__barrier_in_b; +static unsigned char *stb__dout; +static void stb__match(const unsigned char *data, unsigned int length) +{ + // INVERSE of memmove... write each byte before copying the next... + IM_ASSERT(stb__dout + length <= stb__barrier_out_e); + if (stb__dout + length > stb__barrier_out_e) + { + stb__dout += length; + return; + } + if (data < stb__barrier_out_b) + { + stb__dout = stb__barrier_out_e + 1; + return; + } + while (length--) + *stb__dout++ = *data++; +} + +static void stb__lit(const unsigned char *data, unsigned int length) +{ + IM_ASSERT(stb__dout + length <= stb__barrier_out_e); + if (stb__dout + length > stb__barrier_out_e) + { + stb__dout += length; + return; + } + if (data < stb__barrier_in_b) + { + stb__dout = stb__barrier_out_e + 1; + return; + } + memcpy(stb__dout, data, length); + stb__dout += length; +} + +#define stb__in2(x) ((i[x] << 8) + i[(x) + 1]) +#define stb__in3(x) ((i[x] << 16) + stb__in2((x) + 1)) +#define stb__in4(x) ((i[x] << 24) + stb__in3((x) + 1)) + +static const unsigned char *stb_decompress_token(const unsigned char *i) +{ + if (*i >= 0x20) + { // use fewer if's for cases that expand small + if (*i >= 0x80) + stb__match(stb__dout - i[1] - 1, i[0] - 0x80 + 1), i += 2; + else if (*i >= 0x40) + stb__match(stb__dout - (stb__in2(0) - 0x4000 + 1), i[2] + 1), i += 3; + else /* *i >= 0x20 */ + stb__lit(i + 1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); + } + else + { // more ifs for cases that expand large, since overhead is amortized + if (*i >= 0x18) + stb__match(stb__dout - (stb__in3(0) - 0x180000 + 1), i[3] + 1), i += 4; + else if (*i >= 0x10) + stb__match(stb__dout - (stb__in3(0) - 0x100000 + 1), stb__in2(3) + 1), i += 5; + else if (*i >= 0x08) + stb__lit(i + 2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); + else if (*i == 0x07) + stb__lit(i + 3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); + else if (*i == 0x06) + stb__match(stb__dout - (stb__in3(1) + 1), i[4] + 1), i += 5; + else if (*i == 0x04) + stb__match(stb__dout - (stb__in3(1) + 1), stb__in2(4) + 1), i += 6; + } + return i; +} + +static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) +{ + const unsigned long ADLER_MOD = 65521; + unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; + unsigned long blocklen = buflen % 5552; + + unsigned long i; + while (buflen) + { + for (i = 0; i + 7 < blocklen; i += 8) + { + s1 += buffer[0], s2 += s1; + s1 += buffer[1], s2 += s1; + s1 += buffer[2], s2 += s1; + s1 += buffer[3], s2 += s1; + s1 += buffer[4], s2 += s1; + s1 += buffer[5], s2 += s1; + s1 += buffer[6], s2 += s1; + s1 += buffer[7], s2 += s1; + + buffer += 8; + } + + for (; i < blocklen; ++i) + s1 += *buffer++, s2 += s1; + + s1 %= ADLER_MOD, s2 %= ADLER_MOD; + buflen -= blocklen; + blocklen = 5552; + } + return (unsigned int)(s2 << 16) + (unsigned int)s1; +} + +static unsigned int stb_decompress(unsigned char *output, const unsigned char *i, unsigned int /*length*/) +{ + if (stb__in4(0) != 0x57bC0000) + return 0; + if (stb__in4(4) != 0) + return 0; // error! stream is > 4GB + const unsigned int olen = stb_decompress_length(i); + stb__barrier_in_b = i; + stb__barrier_out_e = output + olen; + stb__barrier_out_b = output; + i += 16; + + stb__dout = output; + for (;;) + { + const unsigned char *old_i = i; + i = stb_decompress_token(i); + if (i == old_i) + { + if (*i == 0x05 && i[1] == 0xfa) + { + IM_ASSERT(stb__dout == output + olen); + if (stb__dout != output + olen) + return 0; + if (stb_adler32(1, output, olen) != (unsigned int)stb__in4(2)) + return 0; + return olen; + } + else + { + IM_ASSERT(0); /* NOTREACHED */ + return 0; + } + } + IM_ASSERT(stb__dout <= output + olen); + if (stb__dout > output + olen) + return 0; + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Default font data (ProggyClean.ttf) +//----------------------------------------------------------------------------- +// ProggyClean.ttf +// Copyright (c) 2004, 2005 Tristan Grimmer +// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) +// Download and more information at http://upperbounds.net +//----------------------------------------------------------------------------- +// File: 'ProggyClean.ttf' (41208 bytes) +// Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding). +// The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size. +//----------------------------------------------------------------------------- +static const char proggy_clean_ttf_compressed_data_base85[11980 + 1] = + "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" + "2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;--VsM.M0rJfLH2eTM`*oJMHRC`N" + "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`�j@'DbG&#^$PG.Ll+DNa&VZ>1i%h1S9u5o@YaaW$e+bROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc." + "x]Ip.PH^'/aqUO/$1WxLoW0[iLAw=4h(9.`G" + "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?Ggv:[7MI2k).'2($5FNP&EQ(,)" + "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#" + "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM" + "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu" + "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/" + "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[Ket`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO" + "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%" + "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$MhLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]" + "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et" + "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:" + "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VBpqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<-+k?'(^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M" + "D?@f&1'BW-)Ju#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(" + "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs" + "bIu)'Z,*[>br5fX^:FPAWr-m2KgLQ_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q" + "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aege0jT6'N#(q%.O=?2S]u*(m<-" + "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i" + "sZ88+dKQ)W6>J%CL`.d*(B`-n8D9oK-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P r+$%CE=68>K8r0=dSC%%(@p7" + ".m7jilQ02'0-VWAgTlGW'b)Tq7VT9q^*^$$.:&N@@" + "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*" + "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u" + "@-W$U%VEQ/,,>>#)D#%8cY#YZ?=,`Wdxu/ae&#" + "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$so8lKN%5/$(vdfq7+ebA#" + "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8" + "6e%B/:=>)N4xeW.*wft-;$'58-ESqr#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#" + "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjLV#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#SfD07&6D@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5" + "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%" + "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;" + "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmLq9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:" + "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3$U4O]GKx'm9)b@p7YsvK3w^YR-" + "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*" + "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdFTi1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IXSsDiWP,##P`%/L-" + "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdFl*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj" + "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#$(>.Z-I&J(Q0Hd5Q%7Co-b`-cP)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8WlA2);Sa" + ">gXm8YB`1d@K#n]76-a$U,mF%Ul:#/'xoFM9QX-$.QN'>" + "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I" + "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-uW%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)" + "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo" + "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P" + "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*'IAO" + "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#" + ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T" + "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4" + "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#" + "/QHC#3^ZC#7jmC#;v)D#?,)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP" + "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp" + "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#"; + +static const char *GetDefaultCompressedFontDataTTFBase85() +{ + return proggy_clean_ttf_compressed_data_base85; +} + +#endif // #ifndef IMGUI_DISABLE diff --git a/src/editors/xrEUI/imgui_impl_dx9.cpp b/src/editors/xrEUI/imgui_impl_dx9.cpp new file mode 100644 index 00000000000..c2f83dc8d8c --- /dev/null +++ b/src/editors/xrEUI/imgui_impl_dx9.cpp @@ -0,0 +1,306 @@ +// dear imgui: Renderer for DirectX9 +// This needs to be used along with a Platform Binding (e.g. Win32) + +// Implemented features: +// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. +// https://github.com/ocornut/imgui + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. +// 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. +// 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). +// 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288. +// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. +// 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example. +// 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. +// 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud. +// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself. +// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. + +#include "imgui_impl_dx9.h" + +// DirectX +#include +#define DIRECTINPUT_VERSION 0x0800 +#include + +// DirectX data +static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; +static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; +static LPDIRECT3DINDEXBUFFER9 g_pIB = NULL; +static LPDIRECT3DTEXTURE9 g_FontTexture = NULL; +static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000; + +struct CUSTOMVERTEX +{ + float pos[3]; + D3DCOLOR col; + float uv[2]; +}; +#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1) + +static void ImGui_ImplDX9_SetupRenderState(ImDrawData *draw_data) +{ + // Setup viewport + D3DVIEWPORT9 vp; + vp.X = vp.Y = 0; + vp.Width = (DWORD)draw_data->DisplaySize.x; + vp.Height = (DWORD)draw_data->DisplaySize.y; + vp.MinZ = 0.0f; + vp.MaxZ = 1.0f; + g_pd3dDevice->SetViewport(&vp); + + // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient) + g_pd3dDevice->SetPixelShader(NULL); + g_pd3dDevice->SetVertexShader(NULL); + g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); + g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE); + g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE); + g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); + g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); + g_pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); + g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); + g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); + g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE); + g_pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); + g_pd3dDevice->SetRenderState(D3DRS_FOGENABLE, FALSE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); + g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); + g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); + + // Setup orthographic projection matrix + // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. + // Being agnostic of whether or can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH() + { + float L = draw_data->DisplayPos.x + 0.5f; + float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f; + float T = draw_data->DisplayPos.y + 0.5f; + float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f; + D3DMATRIX mat_identity = {{{1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}}}; + D3DMATRIX mat_projection = + {{{2.0f / (R - L), 0.0f, 0.0f, 0.0f, + 0.0f, 2.0f / (T - B), 0.0f, 0.0f, + 0.0f, 0.0f, 0.5f, 0.0f, + (L + R) / (L - R), (T + B) / (B - T), 0.5f, 1.0f}}}; + g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity); + g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity); + g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection); + } +} + +// Render function. +// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) +void ImGui_ImplDX9_RenderDrawData(ImDrawData *draw_data) +{ + // Avoid rendering when minimized + if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) + return; + + // Create and grow buffers if needed + if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount) + { + if (g_pVB) + { + g_pVB->Release(); + g_pVB = NULL; + } + g_VertexBufferSize = draw_data->TotalVtxCount + 5000; + if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0) + return; + } + if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount) + { + if (g_pIB) + { + g_pIB->Release(); + g_pIB = NULL; + } + g_IndexBufferSize = draw_data->TotalIdxCount + 10000; + if (g_pd3dDevice->CreateIndexBuffer(g_IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &g_pIB, NULL) < 0) + return; + } + + // Backup the DX9 state + IDirect3DStateBlock9 *d3d9_state_block = NULL; + if (g_pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0) + return; + + // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to) + D3DMATRIX last_world, last_view, last_projection; + g_pd3dDevice->GetTransform(D3DTS_WORLD, &last_world); + g_pd3dDevice->GetTransform(D3DTS_VIEW, &last_view); + g_pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection); + + // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format. + // FIXME-OPT: This is a waste of resource, the ideal is to use imconfig.h and + // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR + // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; } + CUSTOMVERTEX *vtx_dst; + ImDrawIdx *idx_dst; + if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void **)&vtx_dst, D3DLOCK_DISCARD) < 0) + return; + if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void **)&idx_dst, D3DLOCK_DISCARD) < 0) + return; + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList *cmd_list = draw_data->CmdLists[n]; + const ImDrawVert *vtx_src = cmd_list->VtxBuffer.Data; + for (int i = 0; i < cmd_list->VtxBuffer.Size; i++) + { + vtx_dst->pos[0] = vtx_src->pos.x; + vtx_dst->pos[1] = vtx_src->pos.y; + vtx_dst->pos[2] = 0.0f; + vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000) >> 16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9 + vtx_dst->uv[0] = vtx_src->uv.x; + vtx_dst->uv[1] = vtx_src->uv.y; + vtx_dst++; + vtx_src++; + } + memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + idx_dst += cmd_list->IdxBuffer.Size; + } + g_pVB->Unlock(); + g_pIB->Unlock(); + g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX)); + g_pd3dDevice->SetIndices(g_pIB); + g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX); + + // Setup desired DX state + ImGui_ImplDX9_SetupRenderState(draw_data); + + // Render command lists + // (Because we merged all buffers into a single one, we maintain our own offset into them) + int global_vtx_offset = 0; + int global_idx_offset = 0; + ImVec2 clip_off = draw_data->DisplayPos; + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList *cmd_list = draw_data->CmdLists[n]; + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd *pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback != NULL) + { + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplDX9_SetupRenderState(draw_data); + else + pcmd->UserCallback(cmd_list, pcmd); + } + else + { + const RECT r = {(LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y)}; + const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->TextureId; + g_pd3dDevice->SetTexture(0, texture); + g_pd3dDevice->SetScissorRect(&r); + g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3); + } + } + global_idx_offset += cmd_list->IdxBuffer.Size; + global_vtx_offset += cmd_list->VtxBuffer.Size; + } + + // Restore the DX9 transform + g_pd3dDevice->SetTransform(D3DTS_WORLD, &last_world); + g_pd3dDevice->SetTransform(D3DTS_VIEW, &last_view); + g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection); + + // Restore the DX9 state + d3d9_state_block->Apply(); + d3d9_state_block->Release(); +} + +bool ImGui_ImplDX9_Init(IDirect3DDevice9 *device) +{ + // Setup back-end capabilities flags + ImGuiIO &io = ImGui::GetIO(); + io.BackendRendererName = "imgui_impl_dx9"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + + g_pd3dDevice = device; + g_pd3dDevice->AddRef(); + return true; +} + +void ImGui_ImplDX9_Shutdown() +{ + ImGui_ImplDX9_InvalidateDeviceObjects(); + if (g_pd3dDevice) + { + g_pd3dDevice->Release(); + g_pd3dDevice = NULL; + } +} + +static bool ImGui_ImplDX9_CreateFontsTexture() +{ + // Build texture atlas + ImGuiIO &io = ImGui::GetIO(); + unsigned char *pixels; + int width, height, bytes_per_pixel; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel); + + // Upload texture to graphics system + g_FontTexture = NULL; + if (g_pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_FontTexture, NULL) < 0) + return false; + D3DLOCKED_RECT tex_locked_rect; + if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK) + return false; + for (int y = 0; y < height; y++) + memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel)); + g_FontTexture->UnlockRect(0); + + // Store our identifier + io.Fonts->TexID = (ImTextureID)g_FontTexture; + + return true; +} + +bool ImGui_ImplDX9_CreateDeviceObjects() +{ + if (!g_pd3dDevice) + return false; + if (!ImGui_ImplDX9_CreateFontsTexture()) + return false; + return true; +} + +void ImGui_ImplDX9_InvalidateDeviceObjects() +{ + if (!g_pd3dDevice) + return; + if (g_pVB) + { + g_pVB->Release(); + g_pVB = NULL; + } + if (g_pIB) + { + g_pIB->Release(); + g_pIB = NULL; + } + if (g_FontTexture) + { + g_FontTexture->Release(); + g_FontTexture = NULL; + ImGui::GetIO().Fonts->TexID = NULL; + } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. +} + +void ImGui_ImplDX9_NewFrame() +{ + if (!g_FontTexture) + ImGui_ImplDX9_CreateDeviceObjects(); +} diff --git a/src/editors/xrEUI/imgui_impl_dx9.h b/src/editors/xrEUI/imgui_impl_dx9.h new file mode 100644 index 00000000000..23018c683ef --- /dev/null +++ b/src/editors/xrEUI/imgui_impl_dx9.h @@ -0,0 +1,24 @@ +// dear imgui: Renderer for DirectX9 +// This needs to be used along with a Platform Binding (e.g. Win32) + +// Implemented features: +// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. +// https://github.com/ocornut/imgui + +#pragma once +#include "..\xrEUI\stdafx.h" // IMGUI_IMPL_API + +struct IDirect3DDevice9; + +IMGUI_IMPL_API bool ImGui_ImplDX9_Init(IDirect3DDevice9 *device); +IMGUI_IMPL_API void ImGui_ImplDX9_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplDX9_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData *draw_data); + +// Use if you want to reset your rendering device without losing Dear ImGui state. +IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); diff --git a/src/editors/xrEUI/imgui_impl_win32.cpp b/src/editors/xrEUI/imgui_impl_win32.cpp new file mode 100644 index 00000000000..97e8c910fd3 --- /dev/null +++ b/src/editors/xrEUI/imgui_impl_win32.cpp @@ -0,0 +1,1390 @@ +// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) +// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) + +// Implemented features: +// [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs + +#include "imgui.h" +#include "imgui_impl_win32.h" +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include // GET_X_LPARAM(), GET_Y_LPARAM() +#include +#include + +// Configuration flags to add in your imconfig.h file: +// #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD // Disable gamepad support. This was meaningful before <1.81 but we now load XInput dynamically so the option is now less relevant. + +// Using XInput for gamepad (will load DLL dynamically) +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD +#include +typedef DWORD(WINAPI *PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES *); +typedef DWORD(WINAPI *PFN_XInputGetState)(DWORD, XINPUT_STATE *); +#endif + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2022-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. +// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago)with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. +// 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[]. +// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). +// 2022-01-17: Inputs: always update key mods next and before a key event (not in NewFrame) to fix input queue with very low framerates. +// 2022-01-12: Inputs: Update mouse inputs using WM_MOUSEMOVE/WM_MOUSELEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API. +// 2022-01-12: Inputs: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted. +// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. +// 2021-12-16: Inputs: Fill VK_LCONTROL/VK_RCONTROL/VK_LSHIFT/VK_RSHIFT/VK_LMENU/VK_RMENU for completeness. +// 2021-08-17: Calling io.AddFocusEvent() on WM_SETFOCUS/WM_KILLFOCUS messages. +// 2021-08-02: Inputs: Fixed keyboard modifiers being reported when host window doesn't have focus. +// 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using TrackMouseEvent() to receive WM_MOUSELEAVE events). +// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). +// 2021-06-08: Fixed ImGui_ImplWin32_EnableDpiAwareness() and ImGui_ImplWin32_GetDpiScaleForMonitor() to handle Windows 8.1/10 features without a manifest (per-monitor DPI, and properly calls SetProcessDpiAwareness() on 8.1). +// 2021-03-23: Inputs: Clearing keyboard down array when losing focus (WM_KILLFOCUS). +// 2021-02-18: Added ImGui_ImplWin32_EnableAlphaCompositing(). Non Visual Studio users will need to link with dwmapi.lib (MinGW/gcc: use -ldwmapi). +// 2021-02-17: Fixed ImGui_ImplWin32_EnableDpiAwareness() attempting to get SetProcessDpiAwareness from shcore.dll on Windows 8 whereas it is only supported on Windows 8.1. +// 2021-01-25: Inputs: Dynamically loading XInput DLL. +// 2020-12-04: Misc: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed. +// 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs) +// 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions. +// 2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT. +// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. +// 2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter(). +// 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent. +// 2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages. +// 2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application). +// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. +// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. +// 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads). +// 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples. +// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag. +// 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling). +// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. +// 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set). +// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. +// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. +// 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert. +// 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag. +// 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read. +// 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging. +// 2016-11-12: Inputs: Only call Win32 ::SetCursor(NULL) when io.MouseDrawCursor is set. + +// Forward Declarations +static void ImGui_ImplWin32_InitPlatformInterface(); +static void ImGui_ImplWin32_ShutdownPlatformInterface(); +static void ImGui_ImplWin32_UpdateMonitors(); + +struct ImGui_ImplWin32_Data +{ + HWND hWnd; + HWND MouseHwnd; + bool MouseTracked; + int MouseButtonsDown; + INT64 Time; + INT64 TicksPerSecond; + ImGuiMouseCursor LastMouseCursor; + bool HasGamepad; + bool WantUpdateHasGamepad; + bool WantUpdateMonitors; + +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + HMODULE XInputDLL; + PFN_XInputGetCapabilities XInputGetCapabilities; + PFN_XInputGetState XInputGetState; +#endif + + ImGui_ImplWin32_Data() + { + memset((void *)this, 0, sizeof(*this)); + } +}; + +// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +// FIXME: multi-context support is not well tested and probably dysfunctional in this backend. +// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. +static ImGui_ImplWin32_Data *ImGui_ImplWin32_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplWin32_Data *)ImGui::GetIO().BackendPlatformUserData : NULL; +} + +// Functions +bool ImGui_ImplWin32_Init(void *hwnd) +{ + ImGuiIO &io = ImGui::GetIO(); + IM_ASSERT(io.BackendPlatformUserData == NULL && "Already initialized a platform backend!"); + + INT64 perf_frequency, perf_counter; + if (!::QueryPerformanceFrequency((LARGE_INTEGER *)&perf_frequency)) + return false; + if (!::QueryPerformanceCounter((LARGE_INTEGER *)&perf_counter)) + return false; + + // Setup backend capabilities flags + ImGui_ImplWin32_Data *bd = IM_NEW(ImGui_ImplWin32_Data)(); + io.BackendPlatformUserData = (void *)bd; + io.BackendPlatformName = "imgui_impl_win32"; + io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) + io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) + io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) + io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can call io.AddMouseViewportEvent() with correct data (optional) + + bd->hWnd = (HWND)hwnd; + bd->WantUpdateHasGamepad = true; + bd->WantUpdateMonitors = true; + bd->TicksPerSecond = perf_frequency; + bd->Time = perf_counter; + bd->LastMouseCursor = ImGuiMouseCursor_COUNT; + + // Our mouse update function expect PlatformHandle to be filled for the main viewport + ImGuiViewport *main_viewport = ImGui::GetMainViewport(); + main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (void *)bd->hWnd; + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + ImGui_ImplWin32_InitPlatformInterface(); + + // Dynamically load XInput library +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + const char *xinput_dll_names[] = + { + "xinput1_4.dll", // Windows 8+ + "xinput1_3.dll", // DirectX SDK + "xinput9_1_0.dll", // Windows Vista, Windows 7 + "xinput1_2.dll", // DirectX SDK + "xinput1_1.dll" // DirectX SDK + }; + for (int n = 0; n < IM_ARRAYSIZE(xinput_dll_names); n++) + if (HMODULE dll = ::LoadLibraryA(xinput_dll_names[n])) + { + bd->XInputDLL = dll; + bd->XInputGetCapabilities = (PFN_XInputGetCapabilities)::GetProcAddress(dll, "XInputGetCapabilities"); + bd->XInputGetState = (PFN_XInputGetState)::GetProcAddress(dll, "XInputGetState"); + break; + } +#endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + + return true; +} + +void ImGui_ImplWin32_Shutdown() +{ + ImGui_ImplWin32_Data *bd = ImGui_ImplWin32_GetBackendData(); + IM_ASSERT(bd != NULL && "No platform backend to shutdown, or already shutdown?"); + ImGuiIO &io = ImGui::GetIO(); + + ImGui_ImplWin32_ShutdownPlatformInterface(); + + // Unload XInput library +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + if (bd->XInputDLL) + ::FreeLibrary(bd->XInputDLL); +#endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + + io.BackendPlatformName = NULL; + io.BackendPlatformUserData = NULL; + IM_DELETE(bd); +} + +static bool ImGui_ImplWin32_UpdateMouseCursor() +{ + ImGuiIO &io = ImGui::GetIO(); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) + return false; + + ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); + if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) + { + // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor + ::SetCursor(NULL); + } + else + { + // Show OS mouse cursor + LPTSTR win32_cursor = IDC_ARROW; + switch (imgui_cursor) + { + case ImGuiMouseCursor_Arrow: + win32_cursor = IDC_ARROW; + break; + case ImGuiMouseCursor_TextInput: + win32_cursor = IDC_IBEAM; + break; + case ImGuiMouseCursor_ResizeAll: + win32_cursor = IDC_SIZEALL; + break; + case ImGuiMouseCursor_ResizeEW: + win32_cursor = IDC_SIZEWE; + break; + case ImGuiMouseCursor_ResizeNS: + win32_cursor = IDC_SIZENS; + break; + case ImGuiMouseCursor_ResizeNESW: + win32_cursor = IDC_SIZENESW; + break; + case ImGuiMouseCursor_ResizeNWSE: + win32_cursor = IDC_SIZENWSE; + break; + case ImGuiMouseCursor_Hand: + win32_cursor = IDC_HAND; + break; + case ImGuiMouseCursor_NotAllowed: + win32_cursor = IDC_NO; + break; + } + ::SetCursor(::LoadCursor(NULL, win32_cursor)); + } + return true; +} + +static bool IsVkDown(int vk) +{ + return (::GetKeyState(vk) & 0x8000) != 0; +} + +static void ImGui_ImplWin32_AddKeyEvent(ImGuiKey key, bool down, int native_keycode, int native_scancode = -1) +{ + ImGuiIO &io = ImGui::GetIO(); + io.AddKeyEvent(key, down); + io.SetKeyEventNativeData(key, native_keycode, native_scancode); // To support legacy indexing (<1.87 user code) + IM_UNUSED(native_scancode); +} + +static void ImGui_ImplWin32_ProcessKeyEventsWorkarounds() +{ + // Left & right Shift keys: when both are pressed together, Windows tend to not generate the WM_KEYUP event for the first released one. + if (ImGui::IsKeyDown(ImGuiKey_LeftShift) && !IsVkDown(VK_LSHIFT)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, false, VK_LSHIFT); + if (ImGui::IsKeyDown(ImGuiKey_RightShift) && !IsVkDown(VK_RSHIFT)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, false, VK_RSHIFT); + + // Sometimes WM_KEYUP for Win key is not passed down to the app (e.g. for Win+V on some setups, according to GLFW). + if (ImGui::IsKeyDown(ImGuiKey_LeftSuper) && !IsVkDown(VK_LWIN)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftSuper, false, VK_LWIN); + if (ImGui::IsKeyDown(ImGuiKey_RightSuper) && !IsVkDown(VK_RWIN)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightSuper, false, VK_RWIN); +} + +static void ImGui_ImplWin32_UpdateKeyModifiers() +{ + ImGuiIO &io = ImGui::GetIO(); + io.AddKeyEvent(ImGuiKey_ModCtrl, IsVkDown(VK_CONTROL)); + io.AddKeyEvent(ImGuiKey_ModShift, IsVkDown(VK_SHIFT)); + io.AddKeyEvent(ImGuiKey_ModAlt, IsVkDown(VK_MENU)); + io.AddKeyEvent(ImGuiKey_ModSuper, IsVkDown(VK_APPS)); +} + +// This code supports multi-viewports (multiple OS Windows mapped into different Dear ImGui viewports) +// Because of that, it is a little more complicated than your typical single-viewport binding code! +static void ImGui_ImplWin32_UpdateMouseData() +{ + ImGui_ImplWin32_Data *bd = ImGui_ImplWin32_GetBackendData(); + ImGuiIO &io = ImGui::GetIO(); + IM_ASSERT(bd->hWnd != 0); + + POINT mouse_screen_pos; + bool has_mouse_screen_pos = ::GetCursorPos(&mouse_screen_pos) != 0; + + HWND focused_window = ::GetForegroundWindow(); + const bool is_app_focused = (focused_window && (focused_window == bd->hWnd || ::IsChild(focused_window, bd->hWnd) || ImGui::FindViewportByPlatformHandle((void *)focused_window))); + if (is_app_focused) + { + // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) + // When multi-viewports are enabled, all Dear ImGui positions are same as OS positions. + if (io.WantSetMousePos) + { + POINT pos = {(int)io.MousePos.x, (int)io.MousePos.y}; + if ((io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) == 0) + ::ClientToScreen(focused_window, &pos); + ::SetCursorPos(pos.x, pos.y); + } + + // (Optional) Fallback to provide mouse position when focused (WM_MOUSEMOVE already provides this when hovered or captured) + if (!io.WantSetMousePos && !bd->MouseTracked && has_mouse_screen_pos) + { + // Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) + // (This is the position you can get with ::GetCursorPos() + ::ScreenToClient() or WM_MOUSEMOVE.) + // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor) + // (This is the position you can get with ::GetCursorPos() or WM_MOUSEMOVE + ::ClientToScreen(). In theory adding viewport->Pos to a client position would also be the same.) + POINT mouse_pos = mouse_screen_pos; + if (!(io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)) + ::ScreenToClient(bd->hWnd, &mouse_pos); + io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y); + } + } + + // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering. + // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic. + // - [X] Win32 backend correctly ignore viewports with the _NoInputs flag (here using ::WindowFromPoint with WM_NCHITTEST + HTTRANSPARENT in WndProc does that) + // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window + // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported + // by the backend, and use its flawed heuristic to guess the viewport behind. + // - [X] Win32 backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target). + ImGuiID mouse_viewport_id = 0; + if (has_mouse_screen_pos) + if (HWND hovered_hwnd = ::WindowFromPoint(mouse_screen_pos)) + if (ImGuiViewport *viewport = ImGui::FindViewportByPlatformHandle((void *)hovered_hwnd)) + mouse_viewport_id = viewport->ID; + io.AddMouseViewportEvent(mouse_viewport_id); +} + +// Gamepad navigation mapping +static void ImGui_ImplWin32_UpdateGamepads() +{ +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + ImGuiIO &io = ImGui::GetIO(); + ImGui_ImplWin32_Data *bd = ImGui_ImplWin32_GetBackendData(); + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) + return; + + // Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow. + // Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE. + if (bd->WantUpdateHasGamepad) + { + XINPUT_CAPABILITIES caps = {}; + bd->HasGamepad = bd->XInputGetCapabilities ? (bd->XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) : false; + bd->WantUpdateHasGamepad = false; + } + + io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; + XINPUT_STATE xinput_state; + XINPUT_GAMEPAD &gamepad = xinput_state.Gamepad; + if (!bd->HasGamepad || bd->XInputGetState == NULL || bd->XInputGetState(0, &xinput_state) != ERROR_SUCCESS) + return; + io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + +#define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f \ + : V) +#define MAP_BUTTON(KEY_NO, BUTTON_ENUM) \ + { \ + io.AddKeyEvent(KEY_NO, (gamepad.wButtons & BUTTON_ENUM) != 0); \ + } +#define MAP_ANALOG(KEY_NO, VALUE, V0, V1) \ + { \ + float vn = (float)(VALUE - V0) / (float)(V1 - V0); \ + io.AddKeyAnalogEvent(KEY_NO, vn > 0.10f, IM_SATURATE(vn)); \ + } + MAP_BUTTON(ImGuiKey_GamepadStart, XINPUT_GAMEPAD_START); + MAP_BUTTON(ImGuiKey_GamepadBack, XINPUT_GAMEPAD_BACK); + MAP_BUTTON(ImGuiKey_GamepadFaceDown, XINPUT_GAMEPAD_A); + MAP_BUTTON(ImGuiKey_GamepadFaceRight, XINPUT_GAMEPAD_B); + MAP_BUTTON(ImGuiKey_GamepadFaceLeft, XINPUT_GAMEPAD_X); + MAP_BUTTON(ImGuiKey_GamepadFaceUp, XINPUT_GAMEPAD_Y); + MAP_BUTTON(ImGuiKey_GamepadDpadLeft, XINPUT_GAMEPAD_DPAD_LEFT); + MAP_BUTTON(ImGuiKey_GamepadDpadRight, XINPUT_GAMEPAD_DPAD_RIGHT); + MAP_BUTTON(ImGuiKey_GamepadDpadUp, XINPUT_GAMEPAD_DPAD_UP); + MAP_BUTTON(ImGuiKey_GamepadDpadDown, XINPUT_GAMEPAD_DPAD_DOWN); + MAP_BUTTON(ImGuiKey_GamepadL1, XINPUT_GAMEPAD_LEFT_SHOULDER); + MAP_BUTTON(ImGuiKey_GamepadR1, XINPUT_GAMEPAD_RIGHT_SHOULDER); + MAP_ANALOG(ImGuiKey_GamepadL2, gamepad.bLeftTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255); + MAP_ANALOG(ImGuiKey_GamepadR2, gamepad.bRightTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255); + MAP_BUTTON(ImGuiKey_GamepadL3, XINPUT_GAMEPAD_LEFT_THUMB); + MAP_BUTTON(ImGuiKey_GamepadR3, XINPUT_GAMEPAD_RIGHT_THUMB); + MAP_ANALOG(ImGuiKey_GamepadLStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); + MAP_ANALOG(ImGuiKey_GamepadLStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); + MAP_ANALOG(ImGuiKey_GamepadLStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); + MAP_ANALOG(ImGuiKey_GamepadLStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); + MAP_ANALOG(ImGuiKey_GamepadRStickLeft, gamepad.sThumbRX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); + MAP_ANALOG(ImGuiKey_GamepadRStickRight, gamepad.sThumbRX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); + MAP_ANALOG(ImGuiKey_GamepadRStickUp, gamepad.sThumbRY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); + MAP_ANALOG(ImGuiKey_GamepadRStickDown, gamepad.sThumbRY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); +#undef MAP_BUTTON +#undef MAP_ANALOG +#endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD +} + +static BOOL CALLBACK ImGui_ImplWin32_UpdateMonitors_EnumFunc(HMONITOR monitor, HDC, LPRECT, LPARAM) +{ + MONITORINFO info = {}; + info.cbSize = sizeof(MONITORINFO); + if (!::GetMonitorInfo(monitor, &info)) + return TRUE; + ImGuiPlatformMonitor imgui_monitor; + imgui_monitor.MainPos = ImVec2((float)info.rcMonitor.left, (float)info.rcMonitor.top); + imgui_monitor.MainSize = ImVec2((float)(info.rcMonitor.right - info.rcMonitor.left), (float)(info.rcMonitor.bottom - info.rcMonitor.top)); + imgui_monitor.WorkPos = ImVec2((float)info.rcWork.left, (float)info.rcWork.top); + imgui_monitor.WorkSize = ImVec2((float)(info.rcWork.right - info.rcWork.left), (float)(info.rcWork.bottom - info.rcWork.top)); + imgui_monitor.DpiScale = ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); + ImGuiPlatformIO &io = ImGui::GetPlatformIO(); + if (info.dwFlags & MONITORINFOF_PRIMARY) + io.Monitors.push_front(imgui_monitor); + else + io.Monitors.push_back(imgui_monitor); + return TRUE; +} + +static void ImGui_ImplWin32_UpdateMonitors() +{ + ImGui_ImplWin32_Data *bd = ImGui_ImplWin32_GetBackendData(); + ImGui::GetPlatformIO().Monitors.resize(0); + ::EnumDisplayMonitors(NULL, NULL, ImGui_ImplWin32_UpdateMonitors_EnumFunc, 0); + bd->WantUpdateMonitors = false; +} + +void ImGui_ImplWin32_NewFrame() +{ + ImGuiIO &io = ImGui::GetIO(); + ImGui_ImplWin32_Data *bd = ImGui_ImplWin32_GetBackendData(); + IM_ASSERT(bd != NULL && "Did you call ImGui_ImplWin32_Init()?"); + + // Setup display size (every frame to accommodate for window resizing) + RECT rect = {0, 0, 0, 0}; + ::GetClientRect(bd->hWnd, &rect); + io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); + if (bd->WantUpdateMonitors) + ImGui_ImplWin32_UpdateMonitors(); + + // Setup time step + INT64 current_time = 0; + ::QueryPerformanceCounter((LARGE_INTEGER *)¤t_time); + io.DeltaTime = (float)(current_time - bd->Time) / bd->TicksPerSecond; + bd->Time = current_time; + + // Update OS mouse position + ImGui_ImplWin32_UpdateMouseData(); + + // Process workarounds for known Windows key handling issues + ImGui_ImplWin32_ProcessKeyEventsWorkarounds(); + + // Update OS mouse cursor with the cursor requested by imgui + ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor(); + if (bd->LastMouseCursor != mouse_cursor) + { + bd->LastMouseCursor = mouse_cursor; + ImGui_ImplWin32_UpdateMouseCursor(); + } + + // Update game controllers (if enabled and available) + ImGui_ImplWin32_UpdateGamepads(); +} + +// There is no distinct VK_xxx for keypad enter, instead it is VK_RETURN + KF_EXTENDED, we assign it an arbitrary value to make code more readable (VK_ codes go up to 255) +#define IM_VK_KEYPAD_ENTER (VK_RETURN + 256) + +// Map VK_xxx to ImGuiKey_xxx. +static ImGuiKey ImGui_ImplWin32_VirtualKeyToImGuiKey(WPARAM wParam) +{ + switch (wParam) + { + case VK_TAB: + return ImGuiKey_Tab; + case VK_LEFT: + return ImGuiKey_LeftArrow; + case VK_RIGHT: + return ImGuiKey_RightArrow; + case VK_UP: + return ImGuiKey_UpArrow; + case VK_DOWN: + return ImGuiKey_DownArrow; + case VK_PRIOR: + return ImGuiKey_PageUp; + case VK_NEXT: + return ImGuiKey_PageDown; + case VK_HOME: + return ImGuiKey_Home; + case VK_END: + return ImGuiKey_End; + case VK_INSERT: + return ImGuiKey_Insert; + case VK_DELETE: + return ImGuiKey_Delete; + case VK_BACK: + return ImGuiKey_Backspace; + case VK_SPACE: + return ImGuiKey_Space; + case VK_RETURN: + return ImGuiKey_Enter; + case VK_ESCAPE: + return ImGuiKey_Escape; + case VK_OEM_7: + return ImGuiKey_Apostrophe; + case VK_OEM_COMMA: + return ImGuiKey_Comma; + case VK_OEM_MINUS: + return ImGuiKey_Minus; + case VK_OEM_PERIOD: + return ImGuiKey_Period; + case VK_OEM_2: + return ImGuiKey_Slash; + case VK_OEM_1: + return ImGuiKey_Semicolon; + case VK_OEM_PLUS: + return ImGuiKey_Equal; + case VK_OEM_4: + return ImGuiKey_LeftBracket; + case VK_OEM_5: + return ImGuiKey_Backslash; + case VK_OEM_6: + return ImGuiKey_RightBracket; + case VK_OEM_3: + return ImGuiKey_GraveAccent; + case VK_CAPITAL: + return ImGuiKey_CapsLock; + case VK_SCROLL: + return ImGuiKey_ScrollLock; + case VK_NUMLOCK: + return ImGuiKey_NumLock; + case VK_SNAPSHOT: + return ImGuiKey_PrintScreen; + case VK_PAUSE: + return ImGuiKey_Pause; + case VK_NUMPAD0: + return ImGuiKey_Keypad0; + case VK_NUMPAD1: + return ImGuiKey_Keypad1; + case VK_NUMPAD2: + return ImGuiKey_Keypad2; + case VK_NUMPAD3: + return ImGuiKey_Keypad3; + case VK_NUMPAD4: + return ImGuiKey_Keypad4; + case VK_NUMPAD5: + return ImGuiKey_Keypad5; + case VK_NUMPAD6: + return ImGuiKey_Keypad6; + case VK_NUMPAD7: + return ImGuiKey_Keypad7; + case VK_NUMPAD8: + return ImGuiKey_Keypad8; + case VK_NUMPAD9: + return ImGuiKey_Keypad9; + case VK_DECIMAL: + return ImGuiKey_KeypadDecimal; + case VK_DIVIDE: + return ImGuiKey_KeypadDivide; + case VK_MULTIPLY: + return ImGuiKey_KeypadMultiply; + case VK_SUBTRACT: + return ImGuiKey_KeypadSubtract; + case VK_ADD: + return ImGuiKey_KeypadAdd; + case IM_VK_KEYPAD_ENTER: + return ImGuiKey_KeypadEnter; + case VK_LSHIFT: + return ImGuiKey_LeftShift; + case VK_LCONTROL: + return ImGuiKey_LeftCtrl; + case VK_LMENU: + return ImGuiKey_LeftAlt; + case VK_LWIN: + return ImGuiKey_LeftSuper; + case VK_RSHIFT: + return ImGuiKey_RightShift; + case VK_RCONTROL: + return ImGuiKey_RightCtrl; + case VK_RMENU: + return ImGuiKey_RightAlt; + case VK_RWIN: + return ImGuiKey_RightSuper; + case VK_APPS: + return ImGuiKey_Menu; + case '0': + return ImGuiKey_0; + case '1': + return ImGuiKey_1; + case '2': + return ImGuiKey_2; + case '3': + return ImGuiKey_3; + case '4': + return ImGuiKey_4; + case '5': + return ImGuiKey_5; + case '6': + return ImGuiKey_6; + case '7': + return ImGuiKey_7; + case '8': + return ImGuiKey_8; + case '9': + return ImGuiKey_9; + case 'A': + return ImGuiKey_A; + case 'B': + return ImGuiKey_B; + case 'C': + return ImGuiKey_C; + case 'D': + return ImGuiKey_D; + case 'E': + return ImGuiKey_E; + case 'F': + return ImGuiKey_F; + case 'G': + return ImGuiKey_G; + case 'H': + return ImGuiKey_H; + case 'I': + return ImGuiKey_I; + case 'J': + return ImGuiKey_J; + case 'K': + return ImGuiKey_K; + case 'L': + return ImGuiKey_L; + case 'M': + return ImGuiKey_M; + case 'N': + return ImGuiKey_N; + case 'O': + return ImGuiKey_O; + case 'P': + return ImGuiKey_P; + case 'Q': + return ImGuiKey_Q; + case 'R': + return ImGuiKey_R; + case 'S': + return ImGuiKey_S; + case 'T': + return ImGuiKey_T; + case 'U': + return ImGuiKey_U; + case 'V': + return ImGuiKey_V; + case 'W': + return ImGuiKey_W; + case 'X': + return ImGuiKey_X; + case 'Y': + return ImGuiKey_Y; + case 'Z': + return ImGuiKey_Z; + case VK_F1: + return ImGuiKey_F1; + case VK_F2: + return ImGuiKey_F2; + case VK_F3: + return ImGuiKey_F3; + case VK_F4: + return ImGuiKey_F4; + case VK_F5: + return ImGuiKey_F5; + case VK_F6: + return ImGuiKey_F6; + case VK_F7: + return ImGuiKey_F7; + case VK_F8: + return ImGuiKey_F8; + case VK_F9: + return ImGuiKey_F9; + case VK_F10: + return ImGuiKey_F10; + case VK_F11: + return ImGuiKey_F11; + case VK_F12: + return ImGuiKey_F12; + default: + return ImGuiKey_None; + } +} + +// Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions. +#ifndef WM_MOUSEHWHEEL +#define WM_MOUSEHWHEEL 0x020E +#endif +#ifndef DBT_DEVNODES_CHANGED +#define DBT_DEVNODES_CHANGED 0x0007 +#endif + +// Win32 message handler (process Win32 mouse/keyboard inputs, etc.) +// Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. +// When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags. +// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds. +// PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag. +#if 0 +// Copy this line into your .cpp file to forward declare the function. +extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); +#endif +IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + if (ImGui::GetCurrentContext() == NULL) + return 0; + + ImGuiIO &io = ImGui::GetIO(); + ImGui_ImplWin32_Data *bd = ImGui_ImplWin32_GetBackendData(); + + switch (msg) + { + case WM_MOUSEMOVE: + { + // We need to call TrackMouseEvent in order to receive WM_MOUSELEAVE events + bd->MouseHwnd = hwnd; + if (!bd->MouseTracked) + { + TRACKMOUSEEVENT tme = {sizeof(tme), TME_LEAVE, hwnd, 0}; + ::TrackMouseEvent(&tme); + bd->MouseTracked = true; + } + POINT mouse_pos = {(LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam)}; + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + ::ClientToScreen(hwnd, &mouse_pos); + io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y); + break; + } + case WM_MOUSELEAVE: + if (bd->MouseHwnd == hwnd) + bd->MouseHwnd = NULL; + bd->MouseTracked = false; + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); + break; + case WM_LBUTTONDOWN: + case WM_LBUTTONDBLCLK: + case WM_RBUTTONDOWN: + case WM_RBUTTONDBLCLK: + case WM_MBUTTONDOWN: + case WM_MBUTTONDBLCLK: + case WM_XBUTTONDOWN: + case WM_XBUTTONDBLCLK: + { + int button = 0; + if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) + { + button = 0; + } + if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) + { + button = 1; + } + if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) + { + button = 2; + } + if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) + { + button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; + } + if (bd->MouseButtonsDown == 0 && ::GetCapture() == NULL) + ::SetCapture(hwnd); + bd->MouseButtonsDown |= 1 << button; + io.AddMouseButtonEvent(button, true); + return 0; + } + case WM_LBUTTONUP: + case WM_RBUTTONUP: + case WM_MBUTTONUP: + case WM_XBUTTONUP: + { + int button = 0; + if (msg == WM_LBUTTONUP) + { + button = 0; + } + if (msg == WM_RBUTTONUP) + { + button = 1; + } + if (msg == WM_MBUTTONUP) + { + button = 2; + } + if (msg == WM_XBUTTONUP) + { + button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; + } + bd->MouseButtonsDown &= ~(1 << button); + if (bd->MouseButtonsDown == 0 && ::GetCapture() == hwnd) + ::ReleaseCapture(); + io.AddMouseButtonEvent(button, false); + return 0; + } + case WM_MOUSEWHEEL: + io.AddMouseWheelEvent(0.0f, (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA); + return 0; + case WM_MOUSEHWHEEL: + io.AddMouseWheelEvent((float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA, 0.0f); + return 0; + case WM_KEYDOWN: + case WM_KEYUP: + case WM_SYSKEYDOWN: + case WM_SYSKEYUP: + { + const bool is_key_down = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN); + if (wParam < 256) + { + // Submit modifiers + ImGui_ImplWin32_UpdateKeyModifiers(); + + // Obtain virtual key code + // (keypad enter doesn't have its own... VK_RETURN with KF_EXTENDED flag means keypad enter, see IM_VK_KEYPAD_ENTER definition for details, it is mapped to ImGuiKey_KeyPadEnter.) + int vk = (int)wParam; + if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED)) + vk = IM_VK_KEYPAD_ENTER; + + // Submit key event + const ImGuiKey key = ImGui_ImplWin32_VirtualKeyToImGuiKey(vk); + const int scancode = (int)LOBYTE(HIWORD(lParam)); + if (key != ImGuiKey_None) + ImGui_ImplWin32_AddKeyEvent(key, is_key_down, vk, scancode); + + // Submit individual left/right modifier events + if (vk == VK_SHIFT) + { + // Important: Shift keys tend to get stuck when pressed together, missing key-up events are corrected in ImGui_ImplWin32_ProcessKeyEventsWorkarounds() + if (IsVkDown(VK_LSHIFT) == is_key_down) + { + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, is_key_down, VK_LSHIFT, scancode); + } + if (IsVkDown(VK_RSHIFT) == is_key_down) + { + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, is_key_down, VK_RSHIFT, scancode); + } + } + else if (vk == VK_CONTROL) + { + if (IsVkDown(VK_LCONTROL) == is_key_down) + { + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftCtrl, is_key_down, VK_LCONTROL, scancode); + } + if (IsVkDown(VK_RCONTROL) == is_key_down) + { + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightCtrl, is_key_down, VK_RCONTROL, scancode); + } + } + else if (vk == VK_MENU) + { + if (IsVkDown(VK_LMENU) == is_key_down) + { + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftAlt, is_key_down, VK_LMENU, scancode); + } + if (IsVkDown(VK_RMENU) == is_key_down) + { + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightAlt, is_key_down, VK_RMENU, scancode); + } + } + } + return 0; + } + case WM_SETFOCUS: + case WM_KILLFOCUS: + io.AddFocusEvent(msg == WM_SETFOCUS); + return 0; + case WM_CHAR: + // You can also use ToAscii()+GetKeyboardState() to retrieve characters. + if (wParam > 0 && wParam < 0x10000) + io.AddInputCharacterUTF16((unsigned short)wParam); + return 0; + case WM_SETCURSOR: + if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor()) + return 1; + return 0; + case WM_DEVICECHANGE: + if ((UINT)wParam == DBT_DEVNODES_CHANGED) + bd->WantUpdateHasGamepad = true; + return 0; + case WM_DISPLAYCHANGE: + bd->WantUpdateMonitors = true; + return 0; + } + return 0; +} + +//-------------------------------------------------------------------------------------------------------- +// DPI-related helpers (optional) +//-------------------------------------------------------------------------------------------------------- +// - Use to enable DPI awareness without having to create an application manifest. +// - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. +// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. +// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, +// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. +//--------------------------------------------------------------------------------------------------------- +// This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable. +// ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically. +// If you are trying to implement your own backend for your own engine, you may ignore that noise. +//--------------------------------------------------------------------------------------------------------- + +// Perform our own check with RtlVerifyVersionInfo() instead of using functions from as they +// require a manifest to be functional for checks above 8.1. See https://github.com/ocornut/imgui/issues/4200 +static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD) +{ + typedef LONG(WINAPI * PFN_RtlVerifyVersionInfo)(OSVERSIONINFOEXW *, ULONG, ULONGLONG); + static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = NULL; + if (RtlVerifyVersionInfoFn == NULL) + if (HMODULE ntdllModule = ::GetModuleHandleA("ntdll.dll")) + RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo"); + if (RtlVerifyVersionInfoFn == NULL) + return FALSE; + + RTL_OSVERSIONINFOEXW versionInfo = {}; + ULONGLONG conditionMask = 0; + versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW); + versionInfo.dwMajorVersion = major; + versionInfo.dwMinorVersion = minor; + VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); + VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); + return (RtlVerifyVersionInfoFn(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, conditionMask) == 0) ? TRUE : FALSE; +} + +#define _IsWindowsVistaOrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0600), LOBYTE(0x0600), 0) // _WIN32_WINNT_VISTA +#define _IsWindows8OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WIN8 +#define _IsWindows8Point1OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0603), LOBYTE(0x0603), 0) // _WIN32_WINNT_WINBLUE +#define _IsWindows10OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0A00), LOBYTE(0x0A00), 0) // _WIN32_WINNT_WINTHRESHOLD / _WIN32_WINNT_WIN10 + +#ifndef DPI_ENUMS_DECLARED +typedef enum +{ + PROCESS_DPI_UNAWARE = 0, + PROCESS_SYSTEM_DPI_AWARE = 1, + PROCESS_PER_MONITOR_DPI_AWARE = 2 +} PROCESS_DPI_AWARENESS; +typedef enum +{ + MDT_EFFECTIVE_DPI = 0, + MDT_ANGULAR_DPI = 1, + MDT_RAW_DPI = 2, + MDT_DEFAULT = MDT_EFFECTIVE_DPI +} MONITOR_DPI_TYPE; +#endif +#ifndef _DPI_AWARENESS_CONTEXTS_ +DECLARE_HANDLE(DPI_AWARENESS_CONTEXT); +#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT) - 3 +#endif +#ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 +#define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT) - 4 +#endif +typedef HRESULT(WINAPI *PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib + dll, Windows 8.1+ +typedef HRESULT(WINAPI *PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT *, UINT *); // Shcore.lib + dll, Windows 8.1+ +typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update) + +// Helper function to enable DPI awareness without setting up a manifest +void ImGui_ImplWin32_EnableDpiAwareness() +{ + // Make sure monitors will be updated with latest correct scaling + if (ImGui_ImplWin32_Data *bd = ImGui_ImplWin32_GetBackendData()) + bd->WantUpdateMonitors = true; + + if (_IsWindows10OrGreater()) + { + static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process + if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext")) + { + SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); + return; + } + } + if (_IsWindows8Point1OrGreater()) + { + static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process + if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness")) + { + SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE); + return; + } + } +#if _WIN32_WINNT >= 0x0600 + ::SetProcessDPIAware(); +#endif +} + +#if defined(_MSC_VER) && !defined(NOGDI) +#pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32' +#endif + +float ImGui_ImplWin32_GetDpiScaleForMonitor(void *monitor) +{ + UINT xdpi = 96, ydpi = 96; + if (_IsWindows8Point1OrGreater()) + { + static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process + static PFN_GetDpiForMonitor GetDpiForMonitorFn = NULL; + if (GetDpiForMonitorFn == NULL && shcore_dll != NULL) + GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"); + if (GetDpiForMonitorFn != NULL) + { + GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi); + IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! + return xdpi / 96.0f; + } + } +#ifndef NOGDI + const HDC dc = ::GetDC(NULL); + xdpi = ::GetDeviceCaps(dc, LOGPIXELSX); + ydpi = ::GetDeviceCaps(dc, LOGPIXELSY); + IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! + ::ReleaseDC(NULL, dc); +#endif + return xdpi / 96.0f; +} + +float ImGui_ImplWin32_GetDpiScaleForHwnd(void *hwnd) +{ + HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST); + return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); +} + +//-------------------------------------------------------------------------------------------------------- +// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT +// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously. +// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. +//-------------------------------------------------------------------------------------------------------- + +// Helper structure we store in the void* RenderUserData field of each ImGuiViewport to easily retrieve our backend data. +struct ImGui_ImplWin32_ViewportData +{ + HWND Hwnd; + bool HwndOwned; + DWORD DwStyle; + DWORD DwExStyle; + + ImGui_ImplWin32_ViewportData() + { + Hwnd = NULL; + HwndOwned = false; + DwStyle = DwExStyle = 0; + } + ~ImGui_ImplWin32_ViewportData() { IM_ASSERT(Hwnd == NULL); } +}; + +static void ImGui_ImplWin32_GetWin32StyleFromViewportFlags(ImGuiViewportFlags flags, DWORD *out_style, DWORD *out_ex_style) +{ + if (flags & ImGuiViewportFlags_NoDecoration) + *out_style = WS_POPUP; + else + *out_style = WS_OVERLAPPEDWINDOW; + + if (flags & ImGuiViewportFlags_NoTaskBarIcon) + *out_ex_style = WS_EX_TOOLWINDOW; + else + *out_ex_style = WS_EX_APPWINDOW; + + if (flags & ImGuiViewportFlags_TopMost) + *out_ex_style |= WS_EX_TOPMOST; +} + +static void ImGui_ImplWin32_CreateWindow(ImGuiViewport *viewport) +{ + ImGui_ImplWin32_ViewportData *vd = IM_NEW(ImGui_ImplWin32_ViewportData)(); + viewport->PlatformUserData = vd; + + // Select style and parent window + ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &vd->DwStyle, &vd->DwExStyle); + HWND parent_window = NULL; + if (viewport->ParentViewportId != 0) + if (ImGuiViewport *parent_viewport = ImGui::FindViewportByID(viewport->ParentViewportId)) + parent_window = (HWND)parent_viewport->PlatformHandle; + + // Create window + RECT rect = {(LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y)}; + ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); + vd->Hwnd = ::CreateWindowEx( + vd->DwExStyle, _T("ImGui Platform"), _T("Untitled"), vd->DwStyle, // Style, class name, window name + rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, // Window area + parent_window, NULL, ::GetModuleHandle(NULL), NULL); // Parent window, Menu, Instance, Param + vd->HwndOwned = true; + viewport->PlatformRequestResize = false; + viewport->PlatformHandle = viewport->PlatformHandleRaw = vd->Hwnd; +} + +static void ImGui_ImplWin32_DestroyWindow(ImGuiViewport *viewport) +{ + ImGui_ImplWin32_Data *bd = ImGui_ImplWin32_GetBackendData(); + if (ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData) + { + if (::GetCapture() == vd->Hwnd) + { + // Transfer capture so if we started dragging from a window that later disappears, we'll still receive the MOUSEUP event. + ::ReleaseCapture(); + ::SetCapture(bd->hWnd); + } + if (vd->Hwnd && vd->HwndOwned) + ::DestroyWindow(vd->Hwnd); + vd->Hwnd = NULL; + IM_DELETE(vd); + } + viewport->PlatformUserData = viewport->PlatformHandle = NULL; +} + +static void ImGui_ImplWin32_ShowWindow(ImGuiViewport *viewport) +{ + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) + ::ShowWindow(vd->Hwnd, SW_SHOWNA); + else + ::ShowWindow(vd->Hwnd, SW_SHOW); +} + +static void ImGui_ImplWin32_UpdateWindow(ImGuiViewport *viewport) +{ + // (Optional) Update Win32 style if it changed _after_ creation. + // Generally they won't change unless configuration flags are changed, but advanced uses (such as manually rewriting viewport flags) make this useful. + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + DWORD new_style; + DWORD new_ex_style; + ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &new_style, &new_ex_style); + + // Only reapply the flags that have been changed from our point of view (as other flags are being modified by Windows) + if (vd->DwStyle != new_style || vd->DwExStyle != new_ex_style) + { + // (Optional) Update TopMost state if it changed _after_ creation + bool top_most_changed = (vd->DwExStyle & WS_EX_TOPMOST) != (new_ex_style & WS_EX_TOPMOST); + HWND insert_after = top_most_changed ? ((viewport->Flags & ImGuiViewportFlags_TopMost) ? HWND_TOPMOST : HWND_NOTOPMOST) : 0; + UINT swp_flag = top_most_changed ? 0 : SWP_NOZORDER; + + // Apply flags and position (since it is affected by flags) + vd->DwStyle = new_style; + vd->DwExStyle = new_ex_style; + ::SetWindowLong(vd->Hwnd, GWL_STYLE, vd->DwStyle); + ::SetWindowLong(vd->Hwnd, GWL_EXSTYLE, vd->DwExStyle); + RECT rect = {(LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y)}; + ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); // Client to Screen + ::SetWindowPos(vd->Hwnd, insert_after, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, swp_flag | SWP_NOACTIVATE | SWP_FRAMECHANGED); + ::ShowWindow(vd->Hwnd, SW_SHOWNA); // This is necessary when we alter the style + viewport->PlatformRequestMove = viewport->PlatformRequestResize = true; + } +} + +static ImVec2 ImGui_ImplWin32_GetWindowPos(ImGuiViewport *viewport) +{ + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + POINT pos = {0, 0}; + ::ClientToScreen(vd->Hwnd, &pos); + return ImVec2((float)pos.x, (float)pos.y); +} + +static void ImGui_ImplWin32_SetWindowPos(ImGuiViewport *viewport, ImVec2 pos) +{ + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + RECT rect = {(LONG)pos.x, (LONG)pos.y, (LONG)pos.x, (LONG)pos.y}; + ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); + ::SetWindowPos(vd->Hwnd, NULL, rect.left, rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE); +} + +static ImVec2 ImGui_ImplWin32_GetWindowSize(ImGuiViewport *viewport) +{ + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + RECT rect; + ::GetClientRect(vd->Hwnd, &rect); + return ImVec2(float(rect.right - rect.left), float(rect.bottom - rect.top)); +} + +static void ImGui_ImplWin32_SetWindowSize(ImGuiViewport *viewport, ImVec2 size) +{ + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + RECT rect = {0, 0, (LONG)size.x, (LONG)size.y}; + ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); // Client to Screen + ::SetWindowPos(vd->Hwnd, NULL, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE); +} + +static void ImGui_ImplWin32_SetWindowFocus(ImGuiViewport *viewport) +{ + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + ::BringWindowToTop(vd->Hwnd); + ::SetForegroundWindow(vd->Hwnd); + ::SetFocus(vd->Hwnd); +} + +static bool ImGui_ImplWin32_GetWindowFocus(ImGuiViewport *viewport) +{ + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + return ::GetForegroundWindow() == vd->Hwnd; +} + +static bool ImGui_ImplWin32_GetWindowMinimized(ImGuiViewport *viewport) +{ + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + return ::IsIconic(vd->Hwnd) != 0; +} + +static void ImGui_ImplWin32_SetWindowTitle(ImGuiViewport *viewport, const char *title) +{ + // ::SetWindowTextA() doesn't properly handle UTF-8 so we explicitely convert our string. + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + int n = ::MultiByteToWideChar(CP_UTF8, 0, title, -1, NULL, 0); + ImVector title_w; + title_w.resize(n); + ::MultiByteToWideChar(CP_UTF8, 0, title, -1, title_w.Data, n); + ::SetWindowTextW(vd->Hwnd, title_w.Data); +} + +static void ImGui_ImplWin32_SetWindowAlpha(ImGuiViewport *viewport, float alpha) +{ + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f); + if (alpha < 1.0f) + { + DWORD style = ::GetWindowLongW(vd->Hwnd, GWL_EXSTYLE) | WS_EX_LAYERED; + ::SetWindowLongW(vd->Hwnd, GWL_EXSTYLE, style); + ::SetLayeredWindowAttributes(vd->Hwnd, 0, (BYTE)(255 * alpha), LWA_ALPHA); + } + else + { + DWORD style = ::GetWindowLongW(vd->Hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED; + ::SetWindowLongW(vd->Hwnd, GWL_EXSTYLE, style); + } +} + +static float ImGui_ImplWin32_GetWindowDpiScale(ImGuiViewport *viewport) +{ + ImGui_ImplWin32_ViewportData *vd = (ImGui_ImplWin32_ViewportData *)viewport->PlatformUserData; + IM_ASSERT(vd->Hwnd != 0); + return ImGui_ImplWin32_GetDpiScaleForHwnd(vd->Hwnd); +} + +// FIXME-DPI: Testing DPI related ideas +static void ImGui_ImplWin32_OnChangedViewport(ImGuiViewport *viewport) +{ + (void)viewport; +#if 0 + ImGuiStyle default_style; + //default_style.WindowPadding = ImVec2(0, 0); + //default_style.WindowBorderSize = 0.0f; + //default_style.ItemSpacing.y = 3.0f; + //default_style.FramePadding = ImVec2(0, 0); + default_style.ScaleAllSizes(viewport->DpiScale); + ImGuiStyle& style = ImGui::GetStyle(); + style = default_style; +#endif +} + +static LRESULT CALLBACK ImGui_ImplWin32_WndProcHandler_PlatformWindow(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + if (ImGuiViewport *viewport = ImGui::FindViewportByPlatformHandle((void *)hWnd)) + { + switch (msg) + { + case WM_CLOSE: + viewport->PlatformRequestClose = true; + return 0; + case WM_MOVE: + viewport->PlatformRequestMove = true; + break; + case WM_SIZE: + viewport->PlatformRequestResize = true; + break; + case WM_MOUSEACTIVATE: + if (viewport->Flags & ImGuiViewportFlags_NoFocusOnClick) + return MA_NOACTIVATE; + break; + case WM_NCHITTEST: + // Let mouse pass-through the window. This will allow the backend to call io.AddMouseViewportEvent() correctly. (which is optional). + // The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging. + // If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in + // your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system. + if (viewport->Flags & ImGuiViewportFlags_NoInputs) + return HTTRANSPARENT; + break; + } + } + + return DefWindowProc(hWnd, msg, wParam, lParam); +} + +static void ImGui_ImplWin32_InitPlatformInterface() +{ + WNDCLASSEX wcex; + wcex.cbSize = sizeof(WNDCLASSEX); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = ImGui_ImplWin32_WndProcHandler_PlatformWindow; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = ::GetModuleHandle(NULL); + wcex.hIcon = NULL; + wcex.hCursor = NULL; + wcex.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1); + wcex.lpszMenuName = NULL; + wcex.lpszClassName = _T("ImGui Platform"); + wcex.hIconSm = NULL; + ::RegisterClassEx(&wcex); + + ImGui_ImplWin32_UpdateMonitors(); + + // Register platform interface (will be coupled with a renderer interface) + ImGuiPlatformIO &platform_io = ImGui::GetPlatformIO(); + platform_io.Platform_CreateWindow = ImGui_ImplWin32_CreateWindow; + platform_io.Platform_DestroyWindow = ImGui_ImplWin32_DestroyWindow; + platform_io.Platform_ShowWindow = ImGui_ImplWin32_ShowWindow; + platform_io.Platform_SetWindowPos = ImGui_ImplWin32_SetWindowPos; + platform_io.Platform_GetWindowPos = ImGui_ImplWin32_GetWindowPos; + platform_io.Platform_SetWindowSize = ImGui_ImplWin32_SetWindowSize; + platform_io.Platform_GetWindowSize = ImGui_ImplWin32_GetWindowSize; + platform_io.Platform_SetWindowFocus = ImGui_ImplWin32_SetWindowFocus; + platform_io.Platform_GetWindowFocus = ImGui_ImplWin32_GetWindowFocus; + platform_io.Platform_GetWindowMinimized = ImGui_ImplWin32_GetWindowMinimized; + platform_io.Platform_SetWindowTitle = ImGui_ImplWin32_SetWindowTitle; + platform_io.Platform_SetWindowAlpha = ImGui_ImplWin32_SetWindowAlpha; + platform_io.Platform_UpdateWindow = ImGui_ImplWin32_UpdateWindow; + platform_io.Platform_GetWindowDpiScale = ImGui_ImplWin32_GetWindowDpiScale; // FIXME-DPI + platform_io.Platform_OnChangedViewport = ImGui_ImplWin32_OnChangedViewport; // FIXME-DPI + + // Register main window handle (which is owned by the main application, not by us) + // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports. + ImGuiViewport *main_viewport = ImGui::GetMainViewport(); + ImGui_ImplWin32_Data *bd = ImGui_ImplWin32_GetBackendData(); + ImGui_ImplWin32_ViewportData *vd = IM_NEW(ImGui_ImplWin32_ViewportData)(); + vd->Hwnd = bd->hWnd; + vd->HwndOwned = false; + main_viewport->PlatformUserData = vd; + main_viewport->PlatformHandle = (void *)bd->hWnd; +} + +static void ImGui_ImplWin32_ShutdownPlatformInterface() +{ + ::UnregisterClass(_T("ImGui Platform"), ::GetModuleHandle(NULL)); + ImGui::DestroyPlatformWindows(); +} + +//--------------------------------------------------------------------------------------------------------- +// Transparency related helpers (optional) +//-------------------------------------------------------------------------------------------------------- + +#if defined(_MSC_VER) +#pragma comment(lib, "dwmapi") // Link with dwmapi.lib. MinGW will require linking with '-ldwmapi' +#endif + +// [experimental] +// Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c +// (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW) +void ImGui_ImplWin32_EnableAlphaCompositing(void *hwnd) +{ + if (!_IsWindowsVistaOrGreater()) + return; + + BOOL composition; + if (FAILED(::DwmIsCompositionEnabled(&composition)) || !composition) + return; + + BOOL opaque; + DWORD color; + if (_IsWindows8OrGreater() || (SUCCEEDED(::DwmGetColorizationColor(&color, &opaque)) && !opaque)) + { + HRGN region = ::CreateRectRgn(0, 0, -1, -1); + DWM_BLURBEHIND bb = {}; + bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION; + bb.hRgnBlur = region; + bb.fEnable = TRUE; + ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb); + ::DeleteObject(region); + } + else + { + DWM_BLURBEHIND bb = {}; + bb.dwFlags = DWM_BB_ENABLE; + ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb); + } +} + +//--------------------------------------------------------------------------------------------------------- diff --git a/src/editors/xrEUI/imgui_impl_win32.h b/src/editors/xrEUI/imgui_impl_win32.h new file mode 100644 index 00000000000..3afb54942ee --- /dev/null +++ b/src/editors/xrEUI/imgui_impl_win32.h @@ -0,0 +1,45 @@ +// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) +// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) + +// Implemented features: +// [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs + +#pragma once +#include "imgui.h" // IMGUI_IMPL_API + +IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void *hwnd); +IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(); + +// Win32 message handler your application need to call. +// - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on from this helper. +// - You should COPY the line below into your .cpp code to forward declare the function and then you can call it. +// - Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. + +#if 0 +extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); +#endif + +// DPI-related helpers (optional) +// - Use to enable DPI awareness without having to create an application manifest. +// - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. +// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. +// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, +// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. +IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness(); +IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void *hwnd); // HWND hwnd +IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void *monitor); // HMONITOR monitor + +// Transparency related helpers (optional) [experimental] +// - Use to enable alpha compositing transparency with the desktop. +// - Use together with e.g. clearing your framebuffer with zero-alpha. +IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void *hwnd); // HWND hwnd diff --git a/src/editors/xrEUI/imgui_internal.h b/src/editors/xrEUI/imgui_internal.h new file mode 100644 index 00000000000..4989f0ae442 --- /dev/null +++ b/src/editors/xrEUI/imgui_internal.h @@ -0,0 +1,3933 @@ +// dear imgui, v1.88 WIP +// (internal structures/api) + +// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! +// Set: +// #define IMGUI_DEFINE_MATH_OPERATORS +// To implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators) + +/* + +Index of this file: + +// [SECTION] Header mess +// [SECTION] Forward declarations +// [SECTION] Context pointer +// [SECTION] STB libraries includes +// [SECTION] Macros +// [SECTION] Generic helpers +// [SECTION] ImDrawList support +// [SECTION] Widgets support: flags, enums, data structures +// [SECTION] Inputs support +// [SECTION] Clipper support +// [SECTION] Navigation support +// [SECTION] Columns support +// [SECTION] Multi-select support +// [SECTION] Docking support +// [SECTION] Viewport support +// [SECTION] Settings support +// [SECTION] Metrics, Debug tools +// [SECTION] Generic context hooks +// [SECTION] ImGuiContext (main imgui context) +// [SECTION] ImGuiWindowTempData, ImGuiWindow +// [SECTION] Tab bar, Tab item support +// [SECTION] Table support +// [SECTION] ImGui internal API +// [SECTION] ImFontAtlas internal API +// [SECTION] Test Engine specific hooks (imgui_test_engine) + +*/ + +#pragma once +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// [SECTION] Header mess +//----------------------------------------------------------------------------- + +#ifndef IMGUI_VERSION +#include "imgui.h" +#endif + +#include // FILE*, sscanf +#include // NULL, malloc, free, qsort, atoi, atof +#include // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf + +// Enable SSE intrinsics if available +#if (defined __SSE__ || defined __x86_64__ || defined _M_X64) && !defined(IMGUI_DISABLE_SSE) +#define IMGUI_ENABLE_SSE +#include +#endif + +// Visual Studio warnings +#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) +#pragma warning(disable : 26812) // The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer) +#pragma warning(disable : 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). +#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later +#pragma warning(disable : 5054) // operator '|': deprecated between enumerations of different types +#endif +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok, for ImFloorSigned() +#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wold-style-cast" +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#pragma clang diagnostic ignored "-Wdouble-promotion" +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#pragma clang diagnostic ignored "-Wmissing-noreturn" // warning: function 'xxx' could be declared with attribute 'noreturn' +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif + +// Legacy defines +#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Renamed in 1.74 +#error Use IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS +#endif +#ifdef IMGUI_DISABLE_MATH_FUNCTIONS // Renamed in 1.74 +#error Use IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS +#endif + +// Enable stb_truetype by default unless FreeType is enabled. +// You can compile with both by defining both IMGUI_ENABLE_FREETYPE and IMGUI_ENABLE_STB_TRUETYPE together. +#ifndef IMGUI_ENABLE_FREETYPE +#define IMGUI_ENABLE_STB_TRUETYPE +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Forward declarations +//----------------------------------------------------------------------------- + +struct ImBitVector; // Store 1-bit per value +struct ImRect; // An axis-aligned rectangle (2 points) +struct ImDrawDataBuilder; // Helper to build a ImDrawData instance +struct ImDrawListSharedData; // Data shared between all ImDrawList instances +struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it +struct ImGuiContext; // Main Dear ImGui context +struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine +struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum +struct ImGuiDockContext; // Docking system context +struct ImGuiDockRequest; // Docking system dock/undock queued request +struct ImGuiDockNode; // Docking system node (hold a list of Windows OR two child dock nodes) +struct ImGuiDockNodeSettings; // Storage for a dock node in .ini file (we preserve those even if the associated dock node isn't active during the session) +struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() +struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box +struct ImGuiLastItemData; // Status storage for last submitted items +struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only +struct ImGuiNavItemData; // Result of a gamepad/keyboard directional navigation move query result +struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions +struct ImGuiNextWindowData; // Storage for SetNextWindow** functions +struct ImGuiNextItemData; // Storage for SetNextItem** functions +struct ImGuiOldColumnData; // Storage data for a single column for legacy Columns() api +struct ImGuiOldColumns; // Storage data for a columns set for legacy Columns() api +struct ImGuiPopupData; // Storage for current popup stack +struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file +struct ImGuiStackSizes; // Storage of stack sizes for debugging/asserting +struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it +struct ImGuiTabBar; // Storage for a tab bar +struct ImGuiTabItem; // Storage for a tab item (within a tab bar) +struct ImGuiTable; // Storage for a table +struct ImGuiTableColumn; // Storage for one column of a table +struct ImGuiTableInstanceData; // Storage for one instance of a same table +struct ImGuiTableTempData; // Temporary storage for one table (one per table in the stack), shared between tables. +struct ImGuiTableSettings; // Storage for a table .ini settings +struct ImGuiTableColumnsSettings; // Storage for a column .ini settings +struct ImGuiWindow; // Storage for one window +struct ImGuiWindowTempData; // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame, in practice we currently keep it for each window) +struct ImGuiWindowSettings; // Storage for a window .ini settings (we keep one of those even if the actual window wasn't instanced during this session) + +// Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. +typedef int ImGuiDataAuthority; // -> enum ImGuiDataAuthority_ // Enum: for storing the source authority (dock node vs window) of a field +typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical +typedef int ImGuiActivateFlags; // -> enum ImGuiActivateFlags_ // Flags: for navigation/focus function (will be for ActivateItem() later) +typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() +typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags +typedef int ImGuiOldColumnFlags; // -> enum ImGuiOldColumnFlags_ // Flags: for BeginColumns() +typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() +typedef int ImGuiNavDirSourceFlags; // -> enum ImGuiNavDirSourceFlags_ // Flags: for GetNavInputAmount2d() +typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests +typedef int ImGuiNextItemDataFlags; // -> enum ImGuiNextItemDataFlags_ // Flags: for SetNextItemXXX() functions +typedef int ImGuiNextWindowDataFlags; // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions +typedef int ImGuiScrollFlags; // -> enum ImGuiScrollFlags_ // Flags: for ScrollToItem() and navigation requests +typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for SeparatorEx() +typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() +typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx() + +typedef void (*ImGuiErrorLogCallback)(void *user_data, const char *fmt, ...); + +//----------------------------------------------------------------------------- +// [SECTION] Context pointer +// See implementation of this variable in imgui.cpp for comments and details. +//----------------------------------------------------------------------------- + +#ifndef GImGui +extern IMGUI_API ImGuiContext *GImGui; // Current implicit context pointer +#endif + +//------------------------------------------------------------------------- +// [SECTION] STB libraries includes +//------------------------------------------------------------------------- + +namespace ImStb +{ + +#undef STB_TEXTEDIT_STRING +#undef STB_TEXTEDIT_CHARTYPE +#define STB_TEXTEDIT_STRING ImGuiInputTextState +#define STB_TEXTEDIT_CHARTYPE ImWchar +#define STB_TEXTEDIT_GETWIDTH_NEWLINE (-1.0f) +#define STB_TEXTEDIT_UNDOSTATECOUNT 99 +#define STB_TEXTEDIT_UNDOCHARCOUNT 999 +#include "imstb_textedit.h" + +} // namespace ImStb + +//----------------------------------------------------------------------------- +// [SECTION] Macros +//----------------------------------------------------------------------------- + +// Internal Drag and Drop payload types. String starting with '_' are reserved for Dear ImGui. +#define IMGUI_PAYLOAD_TYPE_WINDOW "_IMWINDOW" // Payload == ImGuiWindow* + +// Debug Logging +#ifndef IMGUI_DEBUG_LOG +#define IMGUI_DEBUG_LOG(_FMT, ...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__) +#endif + +// Debug Logging for selected systems. Remove the '((void)0) //' to enable. +// #define IMGUI_DEBUG_LOG_POPUP IMGUI_DEBUG_LOG // Enable log +// #define IMGUI_DEBUG_LOG_NAV IMGUI_DEBUG_LOG // Enable log +// #define IMGUI_DEBUG_LOG_IO IMGUI_DEBUG_LOG // Enable log +// #define IMGUI_DEBUG_LOG_VIEWPORT IMGUI_DEBUG_LOG // Enable log +// #define IMGUI_DEBUG_LOG_DOCKING IMGUI_DEBUG_LOG // Enable log +#define IMGUI_DEBUG_LOG_POPUP(...) ((void)0) // Disable log +#define IMGUI_DEBUG_LOG_NAV(...) ((void)0) // Disable log +#define IMGUI_DEBUG_LOG_IO(...) ((void)0) // Disable log +#define IMGUI_DEBUG_LOG_VIEWPORT(...) ((void)0) // Disable log +#define IMGUI_DEBUG_LOG_DOCKING(...) ((void)0) // Disable log + +// Static Asserts +#define IM_STATIC_ASSERT(_COND) static_assert(_COND, "") + +// "Paranoid" Debug Asserts are meant to only be enabled during specific debugging/work, otherwise would slow down the code too much. +// We currently don't have many of those so the effect is currently negligible, but onward intent to add more aggressive ones in the code. +// #define IMGUI_DEBUG_PARANOID +#ifdef IMGUI_DEBUG_PARANOID +#define IM_ASSERT_PARANOID(_EXPR) IM_ASSERT(_EXPR) +#else +#define IM_ASSERT_PARANOID(_EXPR) +#endif + +// Error handling +// Down the line in some frameworks/languages we would like to have a way to redirect those to the programmer and recover from more faults. +#ifndef IM_ASSERT_USER_ERROR +#define IM_ASSERT_USER_ERROR(_EXP, _MSG) IM_ASSERT((_EXP) && _MSG) // Recoverable User Error +#endif + +// Misc Macros +#define IM_PI 3.14159265358979323846f +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" // Play it nice with Windows users (Update: since 2018-05, Notepad finally appears to support Unix-style carriage returns!) +#else +#define IM_NEWLINE "\n" +#endif +#define IM_TABSIZE (4) +#define IM_MEMALIGN(_OFF, _ALIGN) (((_OFF) + ((_ALIGN)-1)) & ~((_ALIGN)-1)) // Memory align e.g. IM_ALIGN(0,4)=0, IM_ALIGN(1,4)=4, IM_ALIGN(4,4)=4, IM_ALIGN(5,4)=8 +#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL)*255.0f + ((_VAL) >= 0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose +#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 +#define IM_FLOOR(_VAL) ((float)(int)(_VAL)) // ImFloor() is not inlined in MSVC debug builds +#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // + +// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall +#ifdef _MSC_VER +#define IMGUI_CDECL __cdecl +#else +#define IMGUI_CDECL +#endif + +// Warnings +#if defined(_MSC_VER) && !defined(__clang__) +#define IM_MSVC_WARNING_SUPPRESS(XXXX) __pragma(warning(suppress \ + : XXXX)) +#else +#define IM_MSVC_WARNING_SUPPRESS(XXXX) +#endif + +// Debug Tools +// Use 'Metrics/Debugger->Tools->Item Picker' to break into the call-stack of a specific item. +// This will call IM_DEBUG_BREAK() which you may redefine yourself. See https://github.com/scottt/debugbreak for more reference. +#ifndef IM_DEBUG_BREAK +#if defined(_MSC_VER) +#define IM_DEBUG_BREAK() __debugbreak() +#elif defined(__clang__) +#define IM_DEBUG_BREAK() __builtin_debugtrap() +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +#define IM_DEBUG_BREAK() __asm__ volatile("int $0x03") +#elif defined(__GNUC__) && defined(__thumb__) +#define IM_DEBUG_BREAK() __asm__ volatile(".inst 0xde01") +#elif defined(__GNUC__) && defined(__arm__) && !defined(__thumb__) +#define IM_DEBUG_BREAK() __asm__ volatile(".inst 0xe7f001f0"); +#else +#define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger! +#endif +#endif // #ifndef IM_DEBUG_BREAK + +//----------------------------------------------------------------------------- +// [SECTION] Generic helpers +// Note that the ImXXX helpers functions are lower-level than ImGui functions. +// ImGui functions or the ImGui context are never called/used from other ImXXX functions. +//----------------------------------------------------------------------------- +// - Helpers: Hashing +// - Helpers: Sorting +// - Helpers: Bit manipulation +// - Helpers: String +// - Helpers: Formatting +// - Helpers: UTF-8 <> wchar conversions +// - Helpers: ImVec2/ImVec4 operators +// - Helpers: Maths +// - Helpers: Geometry +// - Helper: ImVec1 +// - Helper: ImVec2ih +// - Helper: ImRect +// - Helper: ImBitArray +// - Helper: ImBitVector +// - Helper: ImSpan<>, ImSpanAllocator<> +// - Helper: ImPool<> +// - Helper: ImChunkStream<> +//----------------------------------------------------------------------------- + +// Helpers: Hashing +IMGUI_API ImGuiID ImHashData(const void *data, size_t data_size, ImU32 seed = 0); +IMGUI_API ImGuiID ImHashStr(const char *data, size_t data_size = 0, ImU32 seed = 0); + +// Helpers: Sorting +#ifndef ImQsort +static inline void ImQsort(void *base, size_t count, size_t size_of_element, int(IMGUI_CDECL *compare_func)(void const *, void const *)) +{ + if (count > 1) + qsort(base, count, size_of_element, compare_func); +} +#endif + +// Helpers: Color Blending +IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b); + +// Helpers: Bit manipulation +static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; } +static inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & (v - 1)) == 0; } +static inline int ImUpperPowerOfTwo(int v) +{ + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; +} + +// Helpers: String +IMGUI_API int ImStricmp(const char *str1, const char *str2); +IMGUI_API int ImStrnicmp(const char *str1, const char *str2, size_t count); +IMGUI_API void ImStrncpy(char *dst, const char *src, size_t count); +IMGUI_API char *ImStrdup(const char *str); +IMGUI_API char *ImStrdupcpy(char *dst, size_t *p_dst_size, const char *str); +IMGUI_API const char *ImStrchrRange(const char *str_begin, const char *str_end, char c); +IMGUI_API int ImStrlenW(const ImWchar *str); +IMGUI_API const char *ImStreolRange(const char *str, const char *str_end); // End end-of-line +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 void ImStrTrimBlanks(char *str); +IMGUI_API const char *ImStrSkipBlank(const char *str); +static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } +static inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; } + +// Helpers: Formatting +IMGUI_API int ImFormatString(char *buf, size_t buf_size, const char *fmt, ...) IM_FMTARGS(3); +IMGUI_API int ImFormatStringV(char *buf, size_t buf_size, const char *fmt, va_list args) IM_FMTLIST(3); +IMGUI_API const char *ImParseFormatFindStart(const char *format); +IMGUI_API const char *ImParseFormatFindEnd(const char *format); +IMGUI_API const char *ImParseFormatTrimDecorations(const char *format, char *buf, size_t buf_size); +IMGUI_API void ImParseFormatSanitizeForPrinting(const char *fmt_in, char *fmt_out, size_t fmt_out_size); +IMGUI_API const char *ImParseFormatSanitizeForScanning(const char *fmt_in, char *fmt_out, size_t fmt_out_size); +IMGUI_API int ImParseFormatPrecision(const char *format, int default_value); + +// Helpers: UTF-8 <> wchar conversions +IMGUI_API const char *ImTextCharToUtf8(char out_buf[5], unsigned int c); // return out_buf +IMGUI_API int ImTextStrToUtf8(char *out_buf, int out_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); // read one character. return input UTF-8 bytes count +IMGUI_API int ImTextStrFromUtf8(ImWchar *out_buf, int out_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 ImTextCountUtf8BytesFromChar(const char *in_text, const char *in_text_end); // return number of bytes to express one char in UTF-8 +IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar *in_text, const ImWchar *in_text_end); // return number of bytes to express string in UTF-8 + +// Helpers: ImVec2/ImVec4 operators +// We are keeping those disabled by default so they don't leak in user space, to allow user enabling implicit cast operators between ImVec2 and their own types (using IM_VEC2_CLASS_EXTRA etc.) +// We unfortunately don't have a unary- operator for ImVec2 because this would needs to be defined inside the class itself. +#ifdef IMGUI_DEFINE_MATH_OPERATORS +IM_MSVC_RUNTIME_CHECKS_OFF +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 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 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 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 ImVec4 operator+(const ImVec4 &lhs, const ImVec4 &rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); } +static inline ImVec4 operator-(const ImVec4 &lhs, const ImVec4 &rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); } +static inline ImVec4 operator*(const ImVec4 &lhs, const ImVec4 &rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); } +IM_MSVC_RUNTIME_CHECKS_RESTORE +#endif + +// Helpers: File System +#ifdef IMGUI_DISABLE_FILE_FUNCTIONS +#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS +typedef void *ImFileHandle; +static inline ImFileHandle ImFileOpen(const char *, const char *) { return NULL; } +static inline bool ImFileClose(ImFileHandle) { return false; } +static inline ImU64 ImFileGetSize(ImFileHandle) { return (ImU64)-1; } +static inline ImU64 ImFileRead(void *, ImU64, ImU64, ImFileHandle) { return 0; } +static inline ImU64 ImFileWrite(const void *, ImU64, ImU64, ImFileHandle) { return 0; } +#endif +#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS +typedef FILE *ImFileHandle; +IMGUI_API ImFileHandle ImFileOpen(const char *filename, const char *mode); +IMGUI_API bool ImFileClose(ImFileHandle file); +IMGUI_API ImU64 ImFileGetSize(ImFileHandle file); +IMGUI_API ImU64 ImFileRead(void *data, ImU64 size, ImU64 count, ImFileHandle file); +IMGUI_API ImU64 ImFileWrite(const void *data, ImU64 size, ImU64 count, ImFileHandle file); +#else +#define IMGUI_DISABLE_TTY_FUNCTIONS // Can't use stdout, fflush if we are not using default file functions +#endif +IMGUI_API void *ImFileLoadToMemory(const char *filename, const char *mode, size_t *out_file_size = NULL, int padding_bytes = 0); + +// Helpers: Maths +IM_MSVC_RUNTIME_CHECKS_OFF +// - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy) +#ifndef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS +#define ImFabs(X) fabsf(X) +#define ImSqrt(X) sqrtf(X) +#define ImFmod(X, Y) fmodf((X), (Y)) +#define ImCos(X) cosf(X) +#define ImSin(X) sinf(X) +#define ImAcos(X) acosf(X) +#define ImAtan2(Y, X) atan2f((Y), (X)) +#define ImAtof(STR) atof(STR) +// #define ImFloorStd(X) floorf(X) // We use our own, see ImFloor() and ImFloorSigned() +#define ImCeil(X) ceilf(X) +static inline float ImPow(float x, float y) +{ + return powf(x, y); +} // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision +static inline double ImPow(double x, double y) { return pow(x, y); } +static inline float ImLog(float x) { return logf(x); } // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision +static inline double ImLog(double x) { return log(x); } +static inline int ImAbs(int x) { return x < 0 ? -x : x; } +static inline float ImAbs(float x) { return fabsf(x); } +static inline double ImAbs(double x) { return fabs(x); } +static inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : (x > 0.0f) ? 1.0f + : 0.0f; } // Sign operator - returns -1, 0 or 1 based on sign of argument +static inline double ImSign(double x) { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 + : 0.0; } +#ifdef IMGUI_ENABLE_SSE +static inline float ImRsqrt(float x) +{ + return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); +} +#else +static inline float ImRsqrt(float x) +{ + return 1.0f / sqrtf(x); +} +#endif +static inline double ImRsqrt(double x) +{ + return 1.0 / sqrt(x); +} +#endif +// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double +// (Exceptionally using templates here but we could also redefine them for those types) +template +static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } +template +static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } +template +static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx + : v; } +template +static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); } +template +static inline void ImSwap(T &a, T &b) +{ + T tmp = a; + a = b; + b = tmp; +} +template +static inline T ImAddClampOverflow(T a, T b, T mn, T mx) +{ + if (b < 0 && (a < mn - b)) + return mn; + if (b > 0 && (a > mx - b)) + return mx; + return a + b; +} +template +static inline T ImSubClampOverflow(T a, T b, T mn, T mx) +{ + if (b > 0 && (a < mn + b)) + return mn; + if (b < 0 && (a > mx + b)) + return mx; + return a - b; +} +// - Misc maths helpers +static inline ImVec2 ImMin(const ImVec2 &lhs, const ImVec2 &rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); } +static inline ImVec2 ImMax(const ImVec2 &lhs, const ImVec2 &rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); } +static inline ImVec2 ImClamp(const ImVec2 &v, const ImVec2 &mn, ImVec2 mx) { return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x + : v.x, + (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y + : v.y); } +static inline ImVec2 ImLerp(const ImVec2 &a, const ImVec2 &b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); } +static inline ImVec2 ImLerp(const ImVec2 &a, const ImVec2 &b, const ImVec2 &t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } +static inline ImVec4 ImLerp(const ImVec4 &a, const ImVec4 &b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); } +static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f + : f; } +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 ImRsqrt(d); + return fail_value; +} +static inline float ImFloor(float f) { return (float)(int)(f); } +static inline float ImFloorSigned(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() +static inline ImVec2 ImFloor(const ImVec2 &v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } +static inline ImVec2 ImFloorSigned(const ImVec2 &v) { return ImVec2(ImFloorSigned(v.x), ImFloorSigned(v.y)); } +static inline int ImModPositive(int a, int b) { return (a + b) % b; } +static inline float ImDot(const ImVec2 &a, const ImVec2 &b) { return a.x * b.x + a.y * b.y; } +static inline ImVec2 ImRotate(const ImVec2 &v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } +static inline float ImLinearSweep(float current, float target, float speed) +{ + if (current < target) + return ImMin(current + speed, target); + if (current > target) + return ImMax(current - speed, target); + return current; +} +static inline ImVec2 ImMul(const ImVec2 &lhs, const ImVec2 &rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } +static inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; } +IM_MSVC_RUNTIME_CHECKS_RESTORE + +// Helpers: Geometry +IMGUI_API ImVec2 ImBezierCubicCalc(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, float t); +IMGUI_API ImVec2 ImBezierCubicClosestPoint(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, const ImVec2 &p, int num_segments); // For curves with explicit number of segments +IMGUI_API ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, const ImVec2 &p4, const ImVec2 &p, float tess_tol); // For auto-tessellated curves you can use tess_tol = style.CurveTessellationTol +IMGUI_API ImVec2 ImBezierQuadraticCalc(const ImVec2 &p1, const ImVec2 &p2, const ImVec2 &p3, float t); +IMGUI_API ImVec2 ImLineClosestPoint(const ImVec2 &a, const ImVec2 &b, const ImVec2 &p); +IMGUI_API bool ImTriangleContainsPoint(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &p); +IMGUI_API ImVec2 ImTriangleClosestPoint(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &p); +IMGUI_API void ImTriangleBarycentricCoords(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c, const ImVec2 &p, float &out_u, float &out_v, float &out_w); +inline float ImTriangleArea(const ImVec2 &a, const ImVec2 &b, const ImVec2 &c) { return ImFabs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y))) * 0.5f; } +IMGUI_API ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy); + +// Helper: ImVec1 (1D vector) +// (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) +IM_MSVC_RUNTIME_CHECKS_OFF +struct ImVec1 +{ + float x; + constexpr ImVec1() : x(0.0f) {} + constexpr ImVec1(float _x) : x(_x) {} +}; + +// Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage) +struct ImVec2ih +{ + short x, y; + constexpr ImVec2ih() : x(0), y(0) {} + constexpr ImVec2ih(short _x, short _y) : x(_x), y(_y) {} + constexpr explicit ImVec2ih(const ImVec2 &rhs) : x((short)rhs.x), y((short)rhs.y) {} +}; + +// Helper: ImRect (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 + + constexpr ImRect() : Min(0.0f, 0.0f), Max(0.0f, 0.0f) {} + constexpr ImRect(const ImVec2 &min, const ImVec2 &max) : Min(min), Max(max) {} + constexpr ImRect(const ImVec4 &v) : Min(v.x, v.y), Max(v.z, v.w) {} + constexpr 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; } + float GetArea() const { return (Max.x - Min.x) * (Max.y - Min.y); } + ImVec2 GetTL() const { return Min; } // Top-left + ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right + ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left + ImVec2 GetBR() const { return Max; } // Bottom-right + bool Contains(const ImVec2 &p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } + bool Contains(const ImRect &r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; } + bool Overlaps(const ImRect &r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } + void Add(const ImVec2 &p) + { + if (Min.x > p.x) + Min.x = p.x; + if (Min.y > p.y) + Min.y = p.y; + if (Max.x < p.x) + Max.x = p.x; + if (Max.y < p.y) + Max.y = p.y; + } + void Add(const ImRect &r) + { + if (Min.x > r.Min.x) + Min.x = r.Min.x; + if (Min.y > r.Min.y) + Min.y = r.Min.y; + if (Max.x < r.Max.x) + Max.x = r.Max.x; + if (Max.y < r.Max.y) + Max.y = r.Max.y; + } + void Expand(const float amount) + { + Min.x -= amount; + Min.y -= amount; + Max.x += amount; + Max.y += amount; + } + void Expand(const ImVec2 &amount) + { + Min.x -= amount.x; + Min.y -= amount.y; + Max.x += amount.x; + Max.y += amount.y; + } + void Translate(const ImVec2 &d) + { + Min.x += d.x; + Min.y += d.y; + Max.x += d.x; + Max.y += d.y; + } + void TranslateX(float dx) + { + Min.x += dx; + Max.x += dx; + } + void TranslateY(float dy) + { + Min.y += dy; + Max.y += dy; + } + void ClipWith(const ImRect &r) + { + Min = ImMax(Min, r.Min); + Max = ImMin(Max, r.Max); + } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. + void ClipWithFull(const ImRect &r) + { + Min = ImClamp(Min, r.Min, r.Max); + Max = ImClamp(Max, r.Min, r.Max); + } // Full version, ensure both points are fully clipped. + void Floor() + { + Min.x = IM_FLOOR(Min.x); + Min.y = IM_FLOOR(Min.y); + Max.x = IM_FLOOR(Max.x); + Max.y = IM_FLOOR(Max.y); + } + bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } + ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } +}; +IM_MSVC_RUNTIME_CHECKS_RESTORE + +// Helper: ImBitArray +inline bool ImBitArrayTestBit(const ImU32 *arr, int n) +{ + ImU32 mask = (ImU32)1 << (n & 31); + return (arr[n >> 5] & mask) != 0; +} +inline void ImBitArrayClearBit(ImU32 *arr, int n) +{ + ImU32 mask = (ImU32)1 << (n & 31); + arr[n >> 5] &= ~mask; +} +inline void ImBitArraySetBit(ImU32 *arr, int n) +{ + ImU32 mask = (ImU32)1 << (n & 31); + arr[n >> 5] |= mask; +} +inline void ImBitArraySetBitRange(ImU32 *arr, int n, int n2) // Works on range [n..n2) +{ + n2--; + while (n <= n2) + { + int a_mod = (n & 31); + int b_mod = (n2 > (n | 31) ? 31 : (n2 & 31)) + 1; + ImU32 mask = (ImU32)(((ImU64)1 << b_mod) - 1) & ~(ImU32)(((ImU64)1 << a_mod) - 1); + arr[n >> 5] |= mask; + n = (n + 32) & ~31; + } +} + +// Helper: ImBitArray class (wrapper over ImBitArray functions) +// Store 1-bit per value. +template +struct ImBitArray +{ + ImU32 Storage[(BITCOUNT + 31) >> 5]; + ImBitArray() { ClearAllBits(); } + void ClearAllBits() { memset(Storage, 0, sizeof(Storage)); } + void SetAllBits() { memset(Storage, 255, sizeof(Storage)); } + bool TestBit(int n) const + { + n += OFFSET; + IM_ASSERT(n >= 0 && n < BITCOUNT); + return ImBitArrayTestBit(Storage, n); + } + void SetBit(int n) + { + n += OFFSET; + IM_ASSERT(n >= 0 && n < BITCOUNT); + ImBitArraySetBit(Storage, n); + } + void ClearBit(int n) + { + n += OFFSET; + IM_ASSERT(n >= 0 && n < BITCOUNT); + ImBitArrayClearBit(Storage, n); + } + void SetBitRange(int n, int n2) + { + n += OFFSET; + n2 += OFFSET; + IM_ASSERT(n >= 0 && n < BITCOUNT && n2 > n && n2 <= BITCOUNT); + ImBitArraySetBitRange(Storage, n, n2); + } // Works on range [n..n2) + bool operator[](int n) const + { + n += OFFSET; + IM_ASSERT(n >= 0 && n < BITCOUNT); + return ImBitArrayTestBit(Storage, n); + } +}; + +// Helper: ImBitVector +// Store 1-bit per value. +struct IMGUI_API ImBitVector +{ + ImVector Storage; + void Create(int sz) + { + Storage.resize((sz + 31) >> 5); + memset(Storage.Data, 0, (size_t)Storage.Size * sizeof(Storage.Data[0])); + } + void Clear() { Storage.clear(); } + bool TestBit(int n) const + { + IM_ASSERT(n < (Storage.Size << 5)); + return ImBitArrayTestBit(Storage.Data, n); + } + void SetBit(int n) + { + IM_ASSERT(n < (Storage.Size << 5)); + ImBitArraySetBit(Storage.Data, n); + } + void ClearBit(int n) + { + IM_ASSERT(n < (Storage.Size << 5)); + ImBitArrayClearBit(Storage.Data, n); + } +}; + +// Helper: ImSpan<> +// Pointing to a span of data we don't own. +template +struct ImSpan +{ + T *Data; + T *DataEnd; + + // Constructors, destructor + inline ImSpan() { Data = DataEnd = NULL; } + inline ImSpan(T *data, int size) + { + Data = data; + DataEnd = data + size; + } + inline ImSpan(T *data, T *data_end) + { + Data = data; + DataEnd = data_end; + } + + inline void set(T *data, int size) + { + Data = data; + DataEnd = data + size; + } + inline void set(T *data, T *data_end) + { + Data = data; + DataEnd = data_end; + } + inline int size() const { return (int)(ptrdiff_t)(DataEnd - Data); } + inline int size_in_bytes() const { return (int)(ptrdiff_t)(DataEnd - Data) * (int)sizeof(T); } + inline T &operator[](int i) + { + T *p = Data + i; + IM_ASSERT(p >= Data && p < DataEnd); + return *p; + } + inline const T &operator[](int i) const + { + const T *p = Data + i; + IM_ASSERT(p >= Data && p < DataEnd); + return *p; + } + + inline T *begin() { return Data; } + inline const T *begin() const { return Data; } + inline T *end() { return DataEnd; } + inline const T *end() const { return DataEnd; } + + // Utilities + inline int index_from_ptr(const T *it) const + { + IM_ASSERT(it >= Data && it < DataEnd); + const ptrdiff_t off = it - Data; + return (int)off; + } +}; + +// Helper: ImSpanAllocator<> +// Facilitate storing multiple chunks into a single large block (the "arena") +// - Usage: call Reserve() N times, allocate GetArenaSizeInBytes() worth, pass it to SetArenaBasePtr(), call GetSpan() N times to retrieve the aligned ranges. +template +struct ImSpanAllocator +{ + char *BasePtr; + int CurrOff; + int CurrIdx; + int Offsets[CHUNKS]; + int Sizes[CHUNKS]; + + ImSpanAllocator() { memset(this, 0, sizeof(*this)); } + inline void Reserve(int n, size_t sz, int a = 4) + { + IM_ASSERT(n == CurrIdx && n < CHUNKS); + CurrOff = IM_MEMALIGN(CurrOff, a); + Offsets[n] = CurrOff; + Sizes[n] = (int)sz; + CurrIdx++; + CurrOff += (int)sz; + } + inline int GetArenaSizeInBytes() { return CurrOff; } + inline void SetArenaBasePtr(void *base_ptr) { BasePtr = (char *)base_ptr; } + inline void *GetSpanPtrBegin(int n) + { + IM_ASSERT(n >= 0 && n < CHUNKS && CurrIdx == CHUNKS); + return (void *)(BasePtr + Offsets[n]); + } + inline void *GetSpanPtrEnd(int n) + { + IM_ASSERT(n >= 0 && n < CHUNKS && CurrIdx == CHUNKS); + return (void *)(BasePtr + Offsets[n] + Sizes[n]); + } + template + inline void GetSpan(int n, ImSpan *span) { span->set((T *)GetSpanPtrBegin(n), (T *)GetSpanPtrEnd(n)); } +}; + +// Helper: ImPool<> +// Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, +// Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object. +typedef int ImPoolIdx; +template +struct ImPool +{ + ImVector Buf; // Contiguous data + ImGuiStorage Map; // ID->Index + ImPoolIdx FreeIdx; // Next free idx to use + ImPoolIdx AliveCount; // Number of active/alive items (for display purpose) + + ImPool() { FreeIdx = AliveCount = 0; } + ~ImPool() { Clear(); } + T *GetByKey(ImGuiID key) + { + int idx = Map.GetInt(key, -1); + return (idx != -1) ? &Buf[idx] : NULL; + } + T *GetByIndex(ImPoolIdx n) { return &Buf[n]; } + ImPoolIdx GetIndex(const T *p) const + { + IM_ASSERT(p >= Buf.Data && p < Buf.Data + Buf.Size); + return (ImPoolIdx)(p - Buf.Data); + } + T *GetOrAddByKey(ImGuiID key) + { + int *p_idx = Map.GetIntRef(key, -1); + if (*p_idx != -1) + return &Buf[*p_idx]; + *p_idx = FreeIdx; + return Add(); + } + bool Contains(const T *p) const { return (p >= Buf.Data && p < Buf.Data + Buf.Size); } + void Clear() + { + for (int n = 0; n < Map.Data.Size; n++) + { + int idx = Map.Data[n].val_i; + if (idx != -1) + Buf[idx].~T(); + } + Map.Clear(); + Buf.clear(); + FreeIdx = AliveCount = 0; + } + T *Add() + { + int idx = FreeIdx; + if (idx == Buf.Size) + { + Buf.resize(Buf.Size + 1); + FreeIdx++; + } + else + { + FreeIdx = *(int *)&Buf[idx]; + } + IM_PLACEMENT_NEW(&Buf[idx]) + T(); + AliveCount++; + return &Buf[idx]; + } + void Remove(ImGuiID key, const T *p) { Remove(key, GetIndex(p)); } + void Remove(ImGuiID key, ImPoolIdx idx) + { + Buf[idx].~T(); + *(int *)&Buf[idx] = FreeIdx; + FreeIdx = idx; + Map.SetInt(key, -1); + AliveCount--; + } + void Reserve(int capacity) + { + Buf.reserve(capacity); + Map.Data.reserve(capacity); + } + + // To iterate a ImPool: for (int n = 0; n < pool.GetMapSize(); n++) if (T* t = pool.TryGetMapData(n)) { ... } + // Can be avoided if you know .Remove() has never been called on the pool, or AliveCount == GetMapSize() + int GetAliveCount() const { return AliveCount; } // Number of active/alive items in the pool (for display purpose) + int GetBufSize() const { return Buf.Size; } + int GetMapSize() const { return Map.Data.Size; } // It is the map we need iterate to find valid items, since we don't have "alive" storage anywhere + T *TryGetMapData(ImPoolIdx n) + { + int idx = Map.Data[n].val_i; + if (idx == -1) + return NULL; + return GetByIndex(idx); + } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + int GetSize() + { + return GetMapSize(); + } // For ImPlot: should use GetMapSize() from (IMGUI_VERSION_NUM >= 18304) +#endif +}; + +// Helper: ImChunkStream<> +// Build and iterate a contiguous stream of variable-sized structures. +// This is used by Settings to store persistent data while reducing allocation count. +// We store the chunk size first, and align the final size on 4 bytes boundaries. +// The tedious/zealous amount of casting is to avoid -Wcast-align warnings. +template +struct ImChunkStream +{ + ImVector Buf; + + void clear() { Buf.clear(); } + bool empty() const { return Buf.Size == 0; } + int size() const { return Buf.Size; } + T *alloc_chunk(size_t sz) + { + size_t HDR_SZ = 4; + sz = IM_MEMALIGN(HDR_SZ + sz, 4u); + int off = Buf.Size; + Buf.resize(off + (int)sz); + ((int *)(void *)(Buf.Data + off))[0] = (int)sz; + return (T *)(void *)(Buf.Data + off + (int)HDR_SZ); + } + T *begin() + { + size_t HDR_SZ = 4; + if (!Buf.Data) + return NULL; + return (T *)(void *)(Buf.Data + HDR_SZ); + } + T *next_chunk(T *p) + { + size_t HDR_SZ = 4; + IM_ASSERT(p >= begin() && p < end()); + p = (T *)(void *)((char *)(void *)p + chunk_size(p)); + if (p == (T *)(void *)((char *)end() + HDR_SZ)) + return (T *)0; + IM_ASSERT(p < end()); + return p; + } + int chunk_size(const T *p) { return ((const int *)p)[-1]; } + T *end() { return (T *)(void *)(Buf.Data + Buf.Size); } + int offset_from_ptr(const T *p) + { + IM_ASSERT(p >= begin() && p < end()); + const ptrdiff_t off = (const char *)p - Buf.Data; + return (int)off; + } + T *ptr_from_offset(int off) + { + IM_ASSERT(off >= 4 && off < Buf.Size); + return (T *)(void *)(Buf.Data + off); + } + void swap(ImChunkStream &rhs) { rhs.Buf.swap(Buf); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImDrawList support +//----------------------------------------------------------------------------- + +// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value. +// Estimation of number of circle segment based on error is derived using method described in https://stackoverflow.com/a/2244088/15194693 +// Number of segments (N) is calculated using equation: +// N = ceil ( pi / acos(1 - error / r) ) where r > 0, error <= r +// Our equation is significantly simpler that one in the post thanks for choosing segment that is +// perpendicular to X axis. Follow steps in the article from this starting condition and you will +// will get this result. +// +// Rendering circles with an odd number of segments, while mathematically correct will produce +// asymmetrical results on the raster grid. Therefore we're rounding N to next even number (7->8, 8->8, 9->10 etc.) +#define IM_ROUNDUP_TO_EVEN(_V) ((((_V) + 1) / 2) * 2) +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN 4 +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX 512 +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD, _MAXERROR) ImClamp(IM_ROUNDUP_TO_EVEN((int)ImCeil(IM_PI / ImAcos(1 - ImMin((_MAXERROR), (_RAD)) / (_RAD)))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX) + +// Raw equation from IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC rewritten for 'r' and 'error'. +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N, _MAXERROR) ((_MAXERROR) / (1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI)))) +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N, _RAD) ((1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI))) / (_RAD)) + +// ImDrawList: Lookup table size for adaptive arc drawing, cover full circle. +#ifndef IM_DRAWLIST_ARCFAST_TABLE_SIZE +#define IM_DRAWLIST_ARCFAST_TABLE_SIZE 48 // Number of samples in lookup table. +#endif +#define IM_DRAWLIST_ARCFAST_SAMPLE_MAX IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle. + +// Data shared between all ImDrawList instances +// You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. +struct IMGUI_API ImDrawListSharedData +{ + ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas + ImFont *Font; // Current/default font (optional, for simplified AddText overload) + float FontSize; // Current/default font size (optional, for simplified AddText overload) + float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() + float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc + ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() + ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) + + // [Internal] Lookup tables + ImVec2 ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle. + float ArcFastRadiusCutoff; // Cutoff radius after which arc drawing will fallback to slower PathArcTo() + ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) + const ImVec4 *TexUvLines; // UV of anti-aliased lines in the atlas + + ImDrawListSharedData(); + void SetCircleTessellationMaxError(float max_error); +}; + +struct ImDrawDataBuilder +{ + ImVector Layers[2]; // Global layers for: regular, tooltip + + void Clear() + { + for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) + Layers[n].resize(0); + } + void ClearFreeMemory() + { + for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) + Layers[n].clear(); + } + int GetDrawListCount() const + { + int count = 0; + for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) + count += Layers[n].Size; + return count; + } + IMGUI_API void FlattenIntoSingleLayer(); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Widgets support: flags, enums, data structures +//----------------------------------------------------------------------------- + +// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin(). +// This is going to be exposed in imgui.h when stabilized enough. +enum ImGuiItemFlags_ +{ + ImGuiItemFlags_None = 0, + ImGuiItemFlags_NoTabStop = 1 << 0, // false // Disable keyboard tabbing (FIXME: should merge with _NoNav) + ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. + ImGuiItemFlags_Disabled = 1 << 2, // false // Disable interactions but doesn't affect visuals. See BeginDisabled()/EndDisabled(). See github.com/ocornut/imgui/issues/211 + ImGuiItemFlags_NoNav = 1 << 3, // false // Disable keyboard/gamepad directional navigation (FIXME: should merge with _NoTabStop) + ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false // Disable item being a candidate for default focus (e.g. used by title bar items) + ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // Disable MenuItem/Selectable() automatically closing their popup window + ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) + ImGuiItemFlags_ReadOnly = 1 << 7, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. + ImGuiItemFlags_Inputable = 1 << 8 // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. +}; + +// Storage for LastItem data +enum ImGuiItemStatusFlags_ +{ + ImGuiItemStatusFlags_None = 0, + ImGuiItemStatusFlags_HoveredRect = 1 << 0, // Mouse position is within item rectangle (does NOT mean that the window is in correct z-order and can be hovered!, this is only one part of the most-common IsItemHovered test) + ImGuiItemStatusFlags_HasDisplayRect = 1 << 1, // g.LastItemData.DisplayRect is valid + ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets) + ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected", only state changes, in order to easily handle clipping with less issues. + ImGuiItemStatusFlags_ToggledOpen = 1 << 4, // Set when TreeNode() reports toggling their open state. + ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag. + ImGuiItemStatusFlags_Deactivated = 1 << 6, // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. + ImGuiItemStatusFlags_HoveredWindow = 1 << 7, // Override the HoveredWindow test to allow cross-window hover testing. + ImGuiItemStatusFlags_FocusedByTabbing = 1 << 8 // Set when the Focusable item just got focused by Tabbing (FIXME: to be removed soon) + +#ifdef IMGUI_ENABLE_TEST_ENGINE + , // [imgui_tests only] + ImGuiItemStatusFlags_Openable = 1 << 20, // Item is an openable (e.g. TreeNode) + ImGuiItemStatusFlags_Opened = 1 << 21, // + ImGuiItemStatusFlags_Checkable = 1 << 22, // Item is a checkable (e.g. CheckBox, MenuItem) + ImGuiItemStatusFlags_Checked = 1 << 23 // +#endif +}; + +// Extend ImGuiInputTextFlags_ +enum ImGuiInputTextFlagsPrivate_ +{ + // [Internal] + ImGuiInputTextFlags_Multiline = 1 << 26, // For internal use by InputTextMultiline() + ImGuiInputTextFlags_NoMarkEdited = 1 << 27, // For internal use by functions using InputText() before reformatting data + ImGuiInputTextFlags_MergedItem = 1 << 28 // For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match. +}; + +// Extend ImGuiButtonFlags_ +enum ImGuiButtonFlagsPrivate_ +{ + ImGuiButtonFlags_PressedOnClick = 1 << 4, // return true on click (mouse down event) + ImGuiButtonFlags_PressedOnClickRelease = 1 << 5, // [Default] return true on click + release on same item <-- this is what the majority of Button are using + ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 6, // return true on click + release even if the release event is not done while hovering the item + ImGuiButtonFlags_PressedOnRelease = 1 << 7, // return true on release (default requires click+release) + ImGuiButtonFlags_PressedOnDoubleClick = 1 << 8, // return true on double-click (default requires click+release) + ImGuiButtonFlags_PressedOnDragDropHold = 1 << 9, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) + ImGuiButtonFlags_Repeat = 1 << 10, // hold to repeat + ImGuiButtonFlags_FlattenChildren = 1 << 11, // allow interactions even if a child window is overlapping + ImGuiButtonFlags_AllowItemOverlap = 1 << 12, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap() + ImGuiButtonFlags_DontClosePopups = 1 << 13, // disable automatically closing parent popup on press // [UNUSED] + // ImGuiButtonFlags_Disabled = 1 << 14, // disable interactions -> use BeginDisabled() or ImGuiItemFlags_Disabled + ImGuiButtonFlags_AlignTextBaseLine = 1 << 15, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine + ImGuiButtonFlags_NoKeyModifiers = 1 << 16, // disable mouse interaction if a key modifier is held + ImGuiButtonFlags_NoHoldingActiveId = 1 << 17, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) + ImGuiButtonFlags_NoNavFocus = 1 << 18, // don't override navigation focus when activated + ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, // don't report as hovered when nav focus is on this item + ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, + ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease +}; + +// Extend ImGuiComboFlags_ +enum ImGuiComboFlagsPrivate_ +{ + ImGuiComboFlags_CustomPreview = 1 << 20 // enable BeginComboPreview() +}; + +// Extend ImGuiSliderFlags_ +enum ImGuiSliderFlagsPrivate_ +{ + ImGuiSliderFlags_Vertical = 1 << 20, // Should this slider be orientated vertically? + ImGuiSliderFlags_ReadOnly = 1 << 21 +}; + +// Extend ImGuiSelectableFlags_ +enum ImGuiSelectableFlagsPrivate_ +{ + // NB: need to be in sync with last value of ImGuiSelectableFlags_ + ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, + ImGuiSelectableFlags_SelectOnNav = 1 << 21, // (WIP) Auto-select when moved into. This is not exposed in public API as to handle multi-select and modifiers we will need user to explicitly control focus scope. May be replaced with a BeginSelection() API. + ImGuiSelectableFlags_SelectOnClick = 1 << 22, // Override button behavior to react on Click (default is Click+Release) + ImGuiSelectableFlags_SelectOnRelease = 1 << 23, // Override button behavior to react on Release (default is Click+Release) + ImGuiSelectableFlags_SpanAvailWidth = 1 << 24, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus) + ImGuiSelectableFlags_DrawHoveredWhenHeld = 1 << 25, // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow. + ImGuiSelectableFlags_SetNavIdOnHover = 1 << 26, // Set Nav/Focus ID on mouse hover (used by MenuItem) + ImGuiSelectableFlags_NoPadWithHalfSpacing = 1 << 27 // Disable padding each side with ItemSpacing * 0.5f +}; + +// Extend ImGuiTreeNodeFlags_ +enum ImGuiTreeNodeFlagsPrivate_ +{ + ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 20 +}; + +enum ImGuiSeparatorFlags_ +{ + ImGuiSeparatorFlags_None = 0, + ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar + ImGuiSeparatorFlags_Vertical = 1 << 1, + ImGuiSeparatorFlags_SpanAllColumns = 1 << 2 +}; + +enum ImGuiTextFlags_ +{ + ImGuiTextFlags_None = 0, + ImGuiTextFlags_NoWidthForLargeClippedText = 1 << 0 +}; + +enum ImGuiTooltipFlags_ +{ + ImGuiTooltipFlags_None = 0, + ImGuiTooltipFlags_OverridePreviousTooltip = 1 << 0 // Override will clear/ignore previously submitted tooltip (defaults to append) +}; + +// FIXME: this is in development, not exposed/functional as a generic feature yet. +// Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2 +enum ImGuiLayoutType_ +{ + ImGuiLayoutType_Horizontal = 0, + ImGuiLayoutType_Vertical = 1 +}; + +enum ImGuiLogType +{ + ImGuiLogType_None = 0, + ImGuiLogType_TTY, + ImGuiLogType_File, + ImGuiLogType_Buffer, + ImGuiLogType_Clipboard +}; + +// X/Y enums are fixed to 0/1 so they may be used to index ImVec2 +enum ImGuiAxis +{ + ImGuiAxis_None = -1, + ImGuiAxis_X = 0, + ImGuiAxis_Y = 1 +}; + +enum ImGuiPlotType +{ + ImGuiPlotType_Lines, + ImGuiPlotType_Histogram +}; + +enum ImGuiPopupPositionPolicy +{ + ImGuiPopupPositionPolicy_Default, + ImGuiPopupPositionPolicy_ComboBox, + ImGuiPopupPositionPolicy_Tooltip +}; + +struct ImGuiDataTypeTempStorage +{ + ImU8 Data[8]; // Can fit any data up to ImGuiDataType_COUNT +}; + +// Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). +struct ImGuiDataTypeInfo +{ + size_t Size; // Size in bytes + const char *Name; // Short descriptive name for the type, for debugging + const char *PrintFmt; // Default printf format for the type + const char *ScanFmt; // Default scanf format for the type +}; + +// Extend ImGuiDataType_ +enum ImGuiDataTypePrivate_ +{ + ImGuiDataType_String = ImGuiDataType_COUNT + 1, + ImGuiDataType_Pointer, + ImGuiDataType_ID +}; + +// Stacked color modifier, backup of modified data so we can restore it +struct ImGuiColorMod +{ + ImGuiCol Col; + ImVec4 BackupValue; +}; + +// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. +struct ImGuiStyleMod +{ + ImGuiStyleVar VarIdx; + union + { + int BackupInt[2]; + float BackupFloat[2]; + }; + ImGuiStyleMod(ImGuiStyleVar idx, int v) + { + VarIdx = idx; + BackupInt[0] = v; + } + ImGuiStyleMod(ImGuiStyleVar idx, float v) + { + VarIdx = idx; + BackupFloat[0] = v; + } + ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) + { + VarIdx = idx; + BackupFloat[0] = v.x; + BackupFloat[1] = v.y; + } +}; + +// Storage data for BeginComboPreview()/EndComboPreview() +struct IMGUI_API ImGuiComboPreviewData +{ + ImRect PreviewRect; + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + ImVec2 BackupCursorPosPrevLine; + float BackupPrevLineTextBaseOffset; + ImGuiLayoutType BackupLayout; + + ImGuiComboPreviewData() { memset(this, 0, sizeof(*this)); } +}; + +// Stacked storage data for BeginGroup()/EndGroup() +struct IMGUI_API ImGuiGroupData +{ + ImGuiID WindowID; + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + ImVec1 BackupIndent; + ImVec1 BackupGroupOffset; + ImVec2 BackupCurrLineSize; + float BackupCurrLineTextBaseOffset; + ImGuiID BackupActiveIdIsAlive; + bool BackupActiveIdPreviousFrameIsAlive; + bool BackupHoveredIdIsAlive; + bool EmitItem; +}; + +// Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper. +struct IMGUI_API ImGuiMenuColumns +{ + ImU32 TotalWidth; + ImU32 NextTotalWidth; + ImU16 Spacing; + ImU16 OffsetIcon; // Always zero for now + ImU16 OffsetLabel; // Offsets are locked in Update() + ImU16 OffsetShortcut; + ImU16 OffsetMark; + ImU16 Widths[4]; // Width of: Icon, Label, Shortcut, Mark (accumulators for current frame) + + ImGuiMenuColumns() { memset(this, 0, sizeof(*this)); } + void Update(float spacing, bool window_reappearing); + float DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark); + void CalcNextTotalWidth(bool update_offsets); +}; + +// Internal state of the currently focused/edited text input box +// For a given item ID, access with ImGui::GetInputTextState() +struct IMGUI_API ImGuiInputTextState +{ + ImGuiID ID; // widget id owning the text state + int CurLenW, CurLenA; // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 length is valid even if TextA is not. + ImVector TextW; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. + ImVector TextA; // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity. + ImVector InitialTextA; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) + bool TextAIsValid; // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument) + int BufCapacityA; // end-user buffer capacity + float ScrollX; // horizontal scrolling/offset + ImStb::STB_TexteditState Stb; // state for stb_textedit.h + float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately + bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) + bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection + bool Edited; // edited this frame + ImGuiInputTextFlags Flags; // copy of InputText() flags + + ImGuiInputTextState() { memset(this, 0, sizeof(*this)); } + void ClearText() + { + CurLenW = CurLenA = 0; + TextW[0] = 0; + TextA[0] = 0; + CursorClamp(); + } + void ClearFreeMemory() + { + TextW.clear(); + TextA.clear(); + InitialTextA.clear(); + } + int GetUndoAvailCount() const { return Stb.undostate.undo_point; } + int GetRedoAvailCount() const { return STB_TEXTEDIT_UNDOSTATECOUNT - Stb.undostate.redo_point; } + void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation + + // Cursor & Selection + void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking + void CursorClamp() + { + Stb.cursor = ImMin(Stb.cursor, CurLenW); + Stb.select_start = ImMin(Stb.select_start, CurLenW); + Stb.select_end = ImMin(Stb.select_end, CurLenW); + } + bool HasSelection() const { return Stb.select_start != Stb.select_end; } + void ClearSelection() { Stb.select_start = Stb.select_end = Stb.cursor; } + int GetCursorPos() const { return Stb.cursor; } + int GetSelectionStart() const { return Stb.select_start; } + int GetSelectionEnd() const { return Stb.select_end; } + void SelectAll() + { + Stb.select_start = 0; + Stb.cursor = Stb.select_end = CurLenW; + Stb.has_preferred_x = 0; + } +}; + +// Storage for current popup stack +struct ImGuiPopupData +{ + ImGuiID PopupId; // Set on OpenPopup() + ImGuiWindow *Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() + ImGuiWindow *SourceWindow; // Set on OpenPopup() copy of NavWindow at the time of opening the popup + int OpenFrameCount; // Set on OpenPopup() + ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) + ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) + ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup + + ImGuiPopupData() + { + memset(this, 0, sizeof(*this)); + OpenFrameCount = -1; + } +}; + +enum ImGuiNextWindowDataFlags_ +{ + ImGuiNextWindowDataFlags_None = 0, + ImGuiNextWindowDataFlags_HasPos = 1 << 0, + ImGuiNextWindowDataFlags_HasSize = 1 << 1, + ImGuiNextWindowDataFlags_HasContentSize = 1 << 2, + ImGuiNextWindowDataFlags_HasCollapsed = 1 << 3, + ImGuiNextWindowDataFlags_HasSizeConstraint = 1 << 4, + ImGuiNextWindowDataFlags_HasFocus = 1 << 5, + ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6, + ImGuiNextWindowDataFlags_HasScroll = 1 << 7, + ImGuiNextWindowDataFlags_HasViewport = 1 << 8, + ImGuiNextWindowDataFlags_HasDock = 1 << 9, + ImGuiNextWindowDataFlags_HasWindowClass = 1 << 10 +}; + +// Storage for SetNexWindow** functions +struct ImGuiNextWindowData +{ + ImGuiNextWindowDataFlags Flags; + ImGuiCond PosCond; + ImGuiCond SizeCond; + ImGuiCond CollapsedCond; + ImGuiCond DockCond; + ImVec2 PosVal; + ImVec2 PosPivotVal; + ImVec2 SizeVal; + ImVec2 ContentSizeVal; + ImVec2 ScrollVal; + bool PosUndock; + bool CollapsedVal; + ImRect SizeConstraintRect; + ImGuiSizeCallback SizeCallback; + void *SizeCallbackUserData; + float BgAlphaVal; // Override background alpha + ImGuiID ViewportId; + ImGuiID DockId; + ImGuiWindowClass WindowClass; + ImVec2 MenuBarOffsetMinVal; // (Always on) This is not exposed publicly, so we don't clear it and it doesn't have a corresponding flag (could we? for consistency?) + + ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); } + inline void ClearFlags() { Flags = ImGuiNextWindowDataFlags_None; } +}; + +enum ImGuiNextItemDataFlags_ +{ + ImGuiNextItemDataFlags_None = 0, + ImGuiNextItemDataFlags_HasWidth = 1 << 0, + ImGuiNextItemDataFlags_HasOpen = 1 << 1 +}; + +struct ImGuiNextItemData +{ + ImGuiNextItemDataFlags Flags; + float Width; // Set by SetNextItemWidth() + ImGuiID FocusScopeId; // Set by SetNextItemMultiSelectData() (!= 0 signify value has been set, so it's an alternate version of HasSelectionData, we don't use Flags for this because they are cleared too early. This is mostly used for debugging) + ImGuiCond OpenCond; + bool OpenVal; // Set by SetNextItemOpen() + + ImGuiNextItemData() { memset(this, 0, sizeof(*this)); } + inline void ClearFlags() { Flags = ImGuiNextItemDataFlags_None; } // Also cleared manually by ItemAdd()! +}; + +// Status storage for the last submitted item +struct ImGuiLastItemData +{ + ImGuiID ID; + ImGuiItemFlags InFlags; // See ImGuiItemFlags_ + ImGuiItemStatusFlags StatusFlags; // See ImGuiItemStatusFlags_ + ImRect Rect; // Full rectangle + ImRect NavRect; // Navigation scoring rectangle (not displayed) + ImRect DisplayRect; // Display rectangle (only if ImGuiItemStatusFlags_HasDisplayRect is set) + + ImGuiLastItemData() { memset(this, 0, sizeof(*this)); } +}; + +struct IMGUI_API ImGuiStackSizes +{ + short SizeOfIDStack; + short SizeOfColorStack; + short SizeOfStyleVarStack; + short SizeOfFontStack; + short SizeOfFocusScopeStack; + short SizeOfGroupStack; + short SizeOfItemFlagsStack; + short SizeOfBeginPopupStack; + short SizeOfDisabledStack; + + ImGuiStackSizes() { memset(this, 0, sizeof(*this)); } + void SetToCurrentState(); + void CompareWithCurrentState(); +}; + +// Data saved for each window pushed into the stack +struct ImGuiWindowStackData +{ + ImGuiWindow *Window; + ImGuiLastItemData ParentLastItemDataBackup; + ImGuiStackSizes StackSizesOnBegin; // Store size of various stacks for asserting +}; + +struct ImGuiShrinkWidthItem +{ + int Index; + float Width; +}; + +struct ImGuiPtrOrIndex +{ + void *Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool. + int Index; // Usually index in a main pool. + + ImGuiPtrOrIndex(void *ptr) + { + Ptr = ptr; + Index = -1; + } + ImGuiPtrOrIndex(int index) + { + Ptr = NULL; + Index = index; + } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Inputs support +//----------------------------------------------------------------------------- + +typedef ImBitArray ImBitArrayForNamedKeys; + +enum ImGuiKeyPrivate_ +{ + ImGuiKey_LegacyNativeKey_BEGIN = 0, + ImGuiKey_LegacyNativeKey_END = 512, + ImGuiKey_Gamepad_BEGIN = ImGuiKey_GamepadStart, + ImGuiKey_Gamepad_END = ImGuiKey_GamepadRStickRight + 1 +}; + +enum ImGuiInputEventType +{ + ImGuiInputEventType_None = 0, + ImGuiInputEventType_MousePos, + ImGuiInputEventType_MouseWheel, + ImGuiInputEventType_MouseButton, + ImGuiInputEventType_MouseViewport, + ImGuiInputEventType_Key, + ImGuiInputEventType_Text, + ImGuiInputEventType_Focus, + ImGuiInputEventType_COUNT +}; + +enum ImGuiInputSource +{ + ImGuiInputSource_None = 0, + ImGuiInputSource_Mouse, + ImGuiInputSource_Keyboard, + ImGuiInputSource_Gamepad, + ImGuiInputSource_Clipboard, // Currently only used by InputText() + ImGuiInputSource_Nav, // Stored in g.ActiveIdSource only + ImGuiInputSource_COUNT +}; + +// FIXME: Structures in the union below need to be declared as anonymous unions appears to be an extension? +// Using ImVec2() would fail on Clang 'union member 'MousePos' has a non-trivial default constructor' +struct ImGuiInputEventMousePos +{ + float PosX, PosY; +}; +struct ImGuiInputEventMouseWheel +{ + float WheelX, WheelY; +}; +struct ImGuiInputEventMouseButton +{ + int Button; + bool Down; +}; +struct ImGuiInputEventMouseViewport +{ + ImGuiID HoveredViewportID; +}; +struct ImGuiInputEventKey +{ + ImGuiKey Key; + bool Down; + float AnalogValue; +}; +struct ImGuiInputEventText +{ + unsigned int Char; +}; +struct ImGuiInputEventAppFocused +{ + bool Focused; +}; + +struct ImGuiInputEvent +{ + ImGuiInputEventType Type; + ImGuiInputSource Source; + union + { + ImGuiInputEventMousePos MousePos; // if Type == ImGuiInputEventType_MousePos + ImGuiInputEventMouseWheel MouseWheel; // if Type == ImGuiInputEventType_MouseWheel + ImGuiInputEventMouseButton MouseButton; // if Type == ImGuiInputEventType_MouseButton + ImGuiInputEventMouseViewport MouseViewport; // if Type == ImGuiInputEventType_MouseViewport + ImGuiInputEventKey Key; // if Type == ImGuiInputEventType_Key + ImGuiInputEventText Text; // if Type == ImGuiInputEventType_Text + ImGuiInputEventAppFocused AppFocused; // if Type == ImGuiInputEventType_Focus + }; + bool AddedByTestEngine; + + ImGuiInputEvent() { memset(this, 0, sizeof(*this)); } +}; + +// FIXME-NAV: Clarify/expose various repeat delay/rate +enum ImGuiNavReadMode +{ + ImGuiNavReadMode_Down, + ImGuiNavReadMode_Pressed, + ImGuiNavReadMode_Released, + ImGuiNavReadMode_Repeat, + ImGuiNavReadMode_RepeatSlow, + ImGuiNavReadMode_RepeatFast +}; + +//----------------------------------------------------------------------------- +// [SECTION] Clipper support +//----------------------------------------------------------------------------- + +struct ImGuiListClipperRange +{ + int Min; + int Max; + bool PosToIndexConvert; // Begin/End are absolute position (will be converted to indices later) + ImS8 PosToIndexOffsetMin; // Add to Min after converting to indices + ImS8 PosToIndexOffsetMax; // Add to Min after converting to indices + + static ImGuiListClipperRange FromIndices(int min, int max) + { + ImGuiListClipperRange r = {min, max, false, 0, 0}; + return r; + } + static ImGuiListClipperRange FromPositions(float y1, float y2, int off_min, int off_max) + { + ImGuiListClipperRange r = {(int)y1, (int)y2, true, (ImS8)off_min, (ImS8)off_max}; + return r; + } +}; + +// Temporary clipper data, buffers shared/reused between instances +struct ImGuiListClipperData +{ + ImGuiListClipper *ListClipper; + float LossynessOffset; + int StepNo; + int ItemsFrozen; + ImVector Ranges; + + ImGuiListClipperData() { memset(this, 0, sizeof(*this)); } + void Reset(ImGuiListClipper *clipper) + { + ListClipper = clipper; + StepNo = ItemsFrozen = 0; + Ranges.resize(0); + } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Navigation support +//----------------------------------------------------------------------------- + +enum ImGuiActivateFlags_ +{ + ImGuiActivateFlags_None = 0, + ImGuiActivateFlags_PreferInput = 1 << 0, // Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default if keyboard is available. + ImGuiActivateFlags_PreferTweak = 1 << 1, // Favor activation for tweaking with arrows or gamepad (e.g. for Slider/Drag). Default if keyboard is not available. + ImGuiActivateFlags_TryToPreserveState = 1 << 2 // Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection) +}; + +// Early work-in-progress API for ScrollToItem() +enum ImGuiScrollFlags_ +{ + ImGuiScrollFlags_None = 0, + ImGuiScrollFlags_KeepVisibleEdgeX = 1 << 0, // If item is not visible: scroll as little as possible on X axis to bring item back into view [default for X axis] + ImGuiScrollFlags_KeepVisibleEdgeY = 1 << 1, // If item is not visible: scroll as little as possible on Y axis to bring item back into view [default for Y axis for windows that are already visible] + ImGuiScrollFlags_KeepVisibleCenterX = 1 << 2, // If item is not visible: scroll to make the item centered on X axis [rarely used] + ImGuiScrollFlags_KeepVisibleCenterY = 1 << 3, // If item is not visible: scroll to make the item centered on Y axis + ImGuiScrollFlags_AlwaysCenterX = 1 << 4, // Always center the result item on X axis [rarely used] + ImGuiScrollFlags_AlwaysCenterY = 1 << 5, // Always center the result item on Y axis [default for Y axis for appearing window) + ImGuiScrollFlags_NoScrollParent = 1 << 6, // Disable forwarding scrolling to parent window if required to keep item/rect visible (only scroll window the function was applied to). + ImGuiScrollFlags_MaskX_ = ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleCenterX | ImGuiScrollFlags_AlwaysCenterX, + ImGuiScrollFlags_MaskY_ = ImGuiScrollFlags_KeepVisibleEdgeY | ImGuiScrollFlags_KeepVisibleCenterY | ImGuiScrollFlags_AlwaysCenterY +}; + +enum ImGuiNavHighlightFlags_ +{ + ImGuiNavHighlightFlags_None = 0, + ImGuiNavHighlightFlags_TypeDefault = 1 << 0, + ImGuiNavHighlightFlags_TypeThin = 1 << 1, + ImGuiNavHighlightFlags_AlwaysDraw = 1 << 2, // Draw rectangular highlight if (g.NavId == id) _even_ when using the mouse. + ImGuiNavHighlightFlags_NoRounding = 1 << 3 +}; + +enum ImGuiNavDirSourceFlags_ +{ + ImGuiNavDirSourceFlags_None = 0, + ImGuiNavDirSourceFlags_RawKeyboard = 1 << 0, // Raw keyboard (not pulled from nav), facilitate use of some functions before we can unify nav and keys + ImGuiNavDirSourceFlags_Keyboard = 1 << 1, + ImGuiNavDirSourceFlags_PadDPad = 1 << 2, + ImGuiNavDirSourceFlags_PadLStick = 1 << 3 +}; + +enum ImGuiNavMoveFlags_ +{ + ImGuiNavMoveFlags_None = 0, + ImGuiNavMoveFlags_LoopX = 1 << 0, // On failed request, restart from opposite side + ImGuiNavMoveFlags_LoopY = 1 << 1, + ImGuiNavMoveFlags_WrapX = 1 << 2, // On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left) + ImGuiNavMoveFlags_WrapY = 1 << 3, // This is not super useful but provided for completeness + ImGuiNavMoveFlags_AllowCurrentNavId = 1 << 4, // Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place) + ImGuiNavMoveFlags_AlsoScoreVisibleSet = 1 << 5, // Store alternate result in NavMoveResultLocalVisible that only comprise elements that are already fully visible (used by PageUp/PageDown) + ImGuiNavMoveFlags_ScrollToEdgeY = 1 << 6, // Force scrolling to min/max (used by Home/End) // FIXME-NAV: Aim to remove or reword, probably unnecessary + ImGuiNavMoveFlags_Forwarded = 1 << 7, + ImGuiNavMoveFlags_DebugNoResult = 1 << 8, // Dummy scoring for debug purpose, don't apply result + ImGuiNavMoveFlags_FocusApi = 1 << 9, + ImGuiNavMoveFlags_Tabbing = 1 << 10, // == Focus + Activate if item is Inputable + DontChangeNavHighlight + ImGuiNavMoveFlags_Activate = 1 << 11, + ImGuiNavMoveFlags_DontSetNavHighlight = 1 << 12 // Do not alter the visible state of keyboard vs mouse nav highlight +}; + +enum ImGuiNavLayer +{ + ImGuiNavLayer_Main = 0, // Main scrolling layer + ImGuiNavLayer_Menu = 1, // Menu layer (access with Alt/ImGuiNavInput_Menu) + ImGuiNavLayer_COUNT +}; + +struct ImGuiNavItemData +{ + ImGuiWindow *Window; // Init,Move // Best candidate window (result->ItemWindow->RootWindowForNav == request->Window) + ImGuiID ID; // Init,Move // Best candidate item ID + ImGuiID FocusScopeId; // Init,Move // Best candidate focus scope ID + ImRect RectRel; // Init,Move // Best candidate bounding box in window relative space + ImGuiItemFlags InFlags; // ????,Move // Best candidate item flags + float DistBox; // Move // Best candidate box distance to current NavId + float DistCenter; // Move // Best candidate center distance to current NavId + float DistAxial; // Move // Best candidate axial distance to current NavId + + ImGuiNavItemData() { Clear(); } + void Clear() + { + Window = NULL; + ID = FocusScopeId = 0; + InFlags = 0; + DistBox = DistCenter = DistAxial = FLT_MAX; + } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Columns support +//----------------------------------------------------------------------------- + +// Flags for internal's BeginColumns(). Prefix using BeginTable() nowadays! +enum ImGuiOldColumnFlags_ +{ + ImGuiOldColumnFlags_None = 0, + ImGuiOldColumnFlags_NoBorder = 1 << 0, // Disable column dividers + ImGuiOldColumnFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers + ImGuiOldColumnFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns + ImGuiOldColumnFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window + ImGuiOldColumnFlags_GrowParentContentsSize = 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. + +// Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , + ImGuiColumnsFlags_None = ImGuiOldColumnFlags_None, + ImGuiColumnsFlags_NoBorder = ImGuiOldColumnFlags_NoBorder, + ImGuiColumnsFlags_NoResize = ImGuiOldColumnFlags_NoResize, + ImGuiColumnsFlags_NoPreserveWidths = ImGuiOldColumnFlags_NoPreserveWidths, + ImGuiColumnsFlags_NoForceWithinWindow = ImGuiOldColumnFlags_NoForceWithinWindow, + ImGuiColumnsFlags_GrowParentContentsSize = ImGuiOldColumnFlags_GrowParentContentsSize +#endif +}; + +struct ImGuiOldColumnData +{ + float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) + float OffsetNormBeforeResize; + ImGuiOldColumnFlags Flags; // Not exposed + ImRect ClipRect; + + ImGuiOldColumnData() { memset(this, 0, sizeof(*this)); } +}; + +struct ImGuiOldColumns +{ + ImGuiID ID; + ImGuiOldColumnFlags Flags; + bool IsFirstFrame; + bool IsBeingResized; + int Current; + int Count; + float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x + float LineMinY, LineMaxY; + float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns() + float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() + ImRect HostInitialClipRect; // Backup of ClipRect at the time of BeginColumns() + ImRect HostBackupClipRect; // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground() + ImRect HostBackupParentWorkRect; // Backup of WorkRect at the time of BeginColumns() + ImVector Columns; + ImDrawListSplitter Splitter; + + ImGuiOldColumns() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Multi-select support +//----------------------------------------------------------------------------- + +#ifdef IMGUI_HAS_MULTI_SELECT +// +#endif // #ifdef IMGUI_HAS_MULTI_SELECT + +//----------------------------------------------------------------------------- +// [SECTION] Docking support +//----------------------------------------------------------------------------- + +#ifdef IMGUI_HAS_DOCK + +// Extend ImGuiDockNodeFlags_ +enum ImGuiDockNodeFlagsPrivate_ +{ + // [Internal] + ImGuiDockNodeFlags_DockSpace = 1 << 10, // Local, Saved // A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. + ImGuiDockNodeFlags_CentralNode = 1 << 11, // Local, Saved // The central node has 2 main properties: stay visible when empty, only use "remaining" spaces from its neighbor. + ImGuiDockNodeFlags_NoTabBar = 1 << 12, // Local, Saved // Tab bar is completely unavailable. No triangle in the corner to enable it back. + ImGuiDockNodeFlags_HiddenTabBar = 1 << 13, // Local, Saved // Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) + ImGuiDockNodeFlags_NoWindowMenuButton = 1 << 14, // Local, Saved // Disable window/docking menu (that one that appears instead of the collapse button) + ImGuiDockNodeFlags_NoCloseButton = 1 << 15, // Local, Saved // + ImGuiDockNodeFlags_NoDocking = 1 << 16, // Local, Saved // Disable any form of docking in this dockspace or individual node. (On a whole dockspace, this pretty much defeat the purpose of using a dockspace at all). Note: when turned on, existing docked nodes will be preserved. + ImGuiDockNodeFlags_NoDockingSplitMe = 1 << 17, // [EXPERIMENTAL] Prevent another window/node from splitting this node. + ImGuiDockNodeFlags_NoDockingSplitOther = 1 << 18, // [EXPERIMENTAL] Prevent this node from splitting another window/node. + ImGuiDockNodeFlags_NoDockingOverMe = 1 << 19, // [EXPERIMENTAL] Prevent another window/node to be docked over this node. + ImGuiDockNodeFlags_NoDockingOverOther = 1 << 20, // [EXPERIMENTAL] Prevent this node to be docked over another window or non-empty node. + ImGuiDockNodeFlags_NoDockingOverEmpty = 1 << 21, // [EXPERIMENTAL] Prevent this node to be docked over an empty node (e.g. DockSpace with no other windows) + ImGuiDockNodeFlags_NoResizeX = 1 << 22, // [EXPERIMENTAL] + ImGuiDockNodeFlags_NoResizeY = 1 << 23, // [EXPERIMENTAL] + ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, + ImGuiDockNodeFlags_NoResizeFlagsMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY, + ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking, + ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace, // When splitting those flags are moved to the inheriting child, never duplicated + ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking +}; + +// Store the source authority (dock node vs window) of a field +enum ImGuiDataAuthority_ +{ + ImGuiDataAuthority_Auto, + ImGuiDataAuthority_DockNode, + ImGuiDataAuthority_Window +}; + +enum ImGuiDockNodeState +{ + ImGuiDockNodeState_Unknown, + ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow, + ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing, + ImGuiDockNodeState_HostWindowVisible +}; + +// sizeof() 156~192 +struct IMGUI_API ImGuiDockNode +{ + ImGuiID ID; + ImGuiDockNodeFlags SharedFlags; // (Write) Flags shared by all nodes of a same dockspace hierarchy (inherited from the root node) + ImGuiDockNodeFlags LocalFlags; // (Write) Flags specific to this node + ImGuiDockNodeFlags LocalFlagsInWindows; // (Write) Flags specific to this node, applied from windows + ImGuiDockNodeFlags MergedFlags; // (Read) Effective flags (== SharedFlags | LocalFlagsInNode | LocalFlagsInWindows) + ImGuiDockNodeState State; + ImGuiDockNode *ParentNode; + ImGuiDockNode *ChildNodes[2]; // [Split node only] Child nodes (left/right or top/bottom). Consider switching to an array. + ImVector Windows; // Note: unordered list! Iterate TabBar->Tabs for user-order. + ImGuiTabBar *TabBar; + ImVec2 Pos; // Current position + ImVec2 Size; // Current size + ImVec2 SizeRef; // [Split node only] Last explicitly written-to size (overridden when using a splitter affecting the node), used to calculate Size. + ImGuiAxis SplitAxis; // [Split node only] Split axis (X or Y) + ImGuiWindowClass WindowClass; // [Root node only] + ImU32 LastBgColor; + + ImGuiWindow *HostWindow; + ImGuiWindow *VisibleWindow; // Generally point to window which is ID is == SelectedTabID, but when CTRL+Tabbing this can be a different window. + ImGuiDockNode *CentralNode; // [Root node only] Pointer to central node. + ImGuiDockNode *OnlyNodeWithWindows; // [Root node only] Set when there is a single visible node within the hierarchy. + int CountNodeWithWindows; // [Root node only] + int LastFrameAlive; // Last frame number the node was updated or kept alive explicitly with DockSpace() + ImGuiDockNodeFlags_KeepAliveOnly + int LastFrameActive; // Last frame number the node was updated. + int LastFrameFocused; // Last frame number the node was focused. + ImGuiID LastFocusedNodeId; // [Root node only] Which of our child docking node (any ancestor in the hierarchy) was last focused. + ImGuiID SelectedTabId; // [Leaf node only] Which of our tab/window is selected. + ImGuiID WantCloseTabId; // [Leaf node only] Set when closing a specific tab/window. + ImGuiDataAuthority AuthorityForPos : 3; + ImGuiDataAuthority AuthorityForSize : 3; + ImGuiDataAuthority AuthorityForViewport : 3; + bool IsVisible : 1; // Set to false when the node is hidden (usually disabled as it has no active window) + bool IsFocused : 1; + bool IsBgDrawnThisFrame : 1; + bool HasCloseButton : 1; // Provide space for a close button (if any of the docked window has one). Note that button may be hidden on window without one. + bool HasWindowMenuButton : 1; + bool HasCentralNodeChild : 1; + bool WantCloseAll : 1; // Set when closing all tabs at once. + bool WantLockSizeOnce : 1; + bool WantMouseMove : 1; // After a node extraction we need to transition toward moving the newly created host window + bool WantHiddenTabBarUpdate : 1; + bool WantHiddenTabBarToggle : 1; + + ImGuiDockNode(ImGuiID id); + ~ImGuiDockNode(); + bool IsRootNode() const { return ParentNode == NULL; } + bool IsDockSpace() const { return (MergedFlags & ImGuiDockNodeFlags_DockSpace) != 0; } + bool IsFloatingNode() const { return ParentNode == NULL && (MergedFlags & ImGuiDockNodeFlags_DockSpace) == 0; } + bool IsCentralNode() const { return (MergedFlags & ImGuiDockNodeFlags_CentralNode) != 0; } + bool IsHiddenTabBar() const { return (MergedFlags & ImGuiDockNodeFlags_HiddenTabBar) != 0; } // Hidden tab bar can be shown back by clicking the small triangle + bool IsNoTabBar() const { return (MergedFlags & ImGuiDockNodeFlags_NoTabBar) != 0; } // Never show a tab bar + bool IsSplitNode() const { return ChildNodes[0] != NULL; } + bool IsLeafNode() const { return ChildNodes[0] == NULL; } + bool IsEmpty() const { return ChildNodes[0] == NULL && Windows.Size == 0; } + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } + + void SetLocalFlags(ImGuiDockNodeFlags flags) + { + LocalFlags = flags; + UpdateMergedFlags(); + } + void UpdateMergedFlags() { MergedFlags = SharedFlags | LocalFlags | LocalFlagsInWindows; } +}; + +// List of colors that are stored at the time of Begin() into Docked Windows. +// We currently store the packed colors in a simple array window->DockStyle.Colors[]. +// A better solution may involve appending into a log of colors in ImGuiContext + store offsets into those arrays in ImGuiWindow, +// but it would be more complex as we'd need to double-buffer both as e.g. drop target may refer to window from last frame. +enum ImGuiWindowDockStyleCol +{ + ImGuiWindowDockStyleCol_Text, + ImGuiWindowDockStyleCol_Tab, + ImGuiWindowDockStyleCol_TabHovered, + ImGuiWindowDockStyleCol_TabActive, + ImGuiWindowDockStyleCol_TabUnfocused, + ImGuiWindowDockStyleCol_TabUnfocusedActive, + ImGuiWindowDockStyleCol_COUNT +}; + +struct ImGuiWindowDockStyle +{ + ImU32 Colors[ImGuiWindowDockStyleCol_COUNT]; +}; + +struct ImGuiDockContext +{ + ImGuiStorage Nodes; // Map ID -> ImGuiDockNode*: Active nodes + ImVector Requests; + ImVector NodesSettings; + bool WantFullRebuild; + ImGuiDockContext() { memset(this, 0, sizeof(*this)); } +}; + +#endif // #ifdef IMGUI_HAS_DOCK + +//----------------------------------------------------------------------------- +// [SECTION] Viewport support +//----------------------------------------------------------------------------- + +// ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!) +// Every instance of ImGuiViewport is in fact a ImGuiViewportP. +struct ImGuiViewportP : public ImGuiViewport +{ + int Idx; + int LastFrameActive; // Last frame number this viewport was activated by a window + int LastFrontMostStampCount; // Last stamp number from when a window hosted by this viewport was made front-most (by comparing this value between two viewport we have an implicit viewport z-order + ImGuiID LastNameHash; + ImVec2 LastPos; + float Alpha; // Window opacity (when dragging dockable windows/viewports we make them transparent) + float LastAlpha; + short PlatformMonitor; + bool PlatformWindowCreated; + ImGuiWindow *Window; // Set when the viewport is owned by a window (and ImGuiViewportFlags_CanHostOtherWindows is NOT set) + int DrawListsLastFrame[2]; // Last frame number the background (0) and foreground (1) draw lists were used + ImDrawList *DrawLists[2]; // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays. + ImDrawData DrawDataP; + ImDrawDataBuilder DrawDataBuilder; + ImVec2 LastPlatformPos; + ImVec2 LastPlatformSize; + ImVec2 LastRendererSize; + ImVec2 WorkOffsetMin; // Work Area: Offset from Pos to top-left corner of Work Area. Generally (0,0) or (0,+main_menu_bar_height). Work Area is Full Area but without menu-bars/status-bars (so WorkArea always fit inside Pos/Size!) + ImVec2 WorkOffsetMax; // Work Area: Offset from Pos+Size to bottom-right corner of Work Area. Generally (0,0) or (0,-status_bar_height). + ImVec2 BuildWorkOffsetMin; // Work Area: Offset being built during current frame. Generally >= 0.0f. + ImVec2 BuildWorkOffsetMax; // Work Area: Offset being built during current frame. Generally <= 0.0f. + + ImGuiViewportP() + { + Idx = -1; + LastFrameActive = DrawListsLastFrame[0] = DrawListsLastFrame[1] = LastFrontMostStampCount = -1; + LastNameHash = 0; + Alpha = LastAlpha = 1.0f; + PlatformMonitor = -1; + PlatformWindowCreated = false; + Window = NULL; + DrawLists[0] = DrawLists[1] = NULL; + LastPlatformPos = LastPlatformSize = LastRendererSize = ImVec2(FLT_MAX, FLT_MAX); + } + ~ImGuiViewportP() + { + if (DrawLists[0]) + IM_DELETE(DrawLists[0]); + if (DrawLists[1]) + IM_DELETE(DrawLists[1]); + } + void ClearRequestFlags() { PlatformRequestClose = PlatformRequestMove = PlatformRequestResize = false; } + + // Calculate work rect pos/size given a set of offset (we have 1 pair of offset for rect locked from last frame data, and 1 pair for currently building rect) + ImVec2 CalcWorkRectPos(const ImVec2 &off_min) const { return ImVec2(Pos.x + off_min.x, Pos.y + off_min.y); } + ImVec2 CalcWorkRectSize(const ImVec2 &off_min, const ImVec2 &off_max) const { return ImVec2(ImMax(0.0f, Size.x - off_min.x + off_max.x), ImMax(0.0f, Size.y - off_min.y + off_max.y)); } + void UpdateWorkRect() + { + WorkPos = CalcWorkRectPos(WorkOffsetMin); + WorkSize = CalcWorkRectSize(WorkOffsetMin, WorkOffsetMax); + } // Update public fields + + // Helpers to retrieve ImRect (we don't need to store BuildWorkRect as every access tend to change it, hence the code asymmetry) + ImRect GetMainRect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } + ImRect GetWorkRect() const { return ImRect(WorkPos.x, WorkPos.y, WorkPos.x + WorkSize.x, WorkPos.y + WorkSize.y); } + ImRect GetBuildWorkRect() const + { + ImVec2 pos = CalcWorkRectPos(BuildWorkOffsetMin); + ImVec2 size = CalcWorkRectSize(BuildWorkOffsetMin, BuildWorkOffsetMax); + return ImRect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); + } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Settings support +//----------------------------------------------------------------------------- + +// Windows data saved in imgui.ini file +// Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily. +// (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure) +struct ImGuiWindowSettings +{ + ImGuiID ID; + ImVec2ih Pos; // NB: Settings position are stored RELATIVE to the viewport! Whereas runtime ones are absolute positions. + ImVec2ih Size; + ImVec2ih ViewportPos; + ImGuiID ViewportId; + ImGuiID DockId; // ID of last known DockNode (even if the DockNode is invisible because it has only 1 active window), or 0 if none. + ImGuiID ClassId; // ID of window class if specified + short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. + bool Collapsed; + bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) + + ImGuiWindowSettings() + { + memset(this, 0, sizeof(*this)); + DockOrder = -1; + } + char *GetName() { return (char *)(this + 1); } +}; + +struct ImGuiSettingsHandler +{ + const char *TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' + ImGuiID TypeHash; // == ImHashStr(TypeName) + void (*ClearAllFn)(ImGuiContext *ctx, ImGuiSettingsHandler *handler); // Clear all settings data + void (*ReadInitFn)(ImGuiContext *ctx, ImGuiSettingsHandler *handler); // Read: Called before reading (in registration order) + void *(*ReadOpenFn)(ImGuiContext *ctx, ImGuiSettingsHandler *handler, const char *name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" + void (*ReadLineFn)(ImGuiContext *ctx, ImGuiSettingsHandler *handler, void *entry, const char *line); // Read: Called for every line of text within an ini entry + void (*ApplyAllFn)(ImGuiContext *ctx, ImGuiSettingsHandler *handler); // Read: Called after reading (in registration order) + void (*WriteAllFn)(ImGuiContext *ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *out_buf); // Write: Output every entries into 'out_buf' + void *UserData; + + ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Metrics, Debug Tools +//----------------------------------------------------------------------------- + +struct ImGuiMetricsConfig +{ + bool ShowStackTool; + bool ShowWindowsRects; + bool ShowWindowsBeginOrder; + bool ShowTablesRects; + bool ShowDrawCmdMesh; + bool ShowDrawCmdBoundingBoxes; + bool ShowDockingNodes; + int ShowWindowsRectsType; + int ShowTablesRectsType; + + ImGuiMetricsConfig() + { + ShowStackTool = false; + ShowWindowsRects = false; + ShowWindowsBeginOrder = false; + ShowTablesRects = false; + ShowDrawCmdMesh = true; + ShowDrawCmdBoundingBoxes = true; + ShowDockingNodes = false; + ShowWindowsRectsType = -1; + ShowTablesRectsType = -1; + } +}; + +struct ImGuiStackLevelInfo +{ + ImGuiID ID; + ImS8 QueryFrameCount; // >= 1: Query in progress + bool QuerySuccess; // Obtained result from DebugHookIdInfo() + ImGuiDataType DataType : 8; + char Desc[57]; // Arbitrarily sized buffer to hold a result (FIXME: could replace Results[] with a chunk stream?) FIXME: Now that we added CTRL+C this should be fixed. + + ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); } +}; + +// State for Stack tool queries +struct ImGuiStackTool +{ + int LastActiveFrame; + int StackLevel; // -1: query stack and resize Results, >= 0: individual stack level + ImGuiID QueryId; // ID to query details for + ImVector Results; + bool CopyToClipboardOnCtrlC; + float CopyToClipboardLastTime; + + ImGuiStackTool() + { + memset(this, 0, sizeof(*this)); + CopyToClipboardLastTime = -FLT_MAX; + } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Generic context hooks +//----------------------------------------------------------------------------- + +typedef void (*ImGuiContextHookCallback)(ImGuiContext *ctx, ImGuiContextHook *hook); +enum ImGuiContextHookType +{ + ImGuiContextHookType_NewFramePre, + ImGuiContextHookType_NewFramePost, + ImGuiContextHookType_EndFramePre, + ImGuiContextHookType_EndFramePost, + ImGuiContextHookType_RenderPre, + ImGuiContextHookType_RenderPost, + ImGuiContextHookType_Shutdown, + ImGuiContextHookType_PendingRemoval_ +}; + +struct ImGuiContextHook +{ + ImGuiID HookId; // A unique ID assigned by AddContextHook() + ImGuiContextHookType Type; + ImGuiID Owner; + ImGuiContextHookCallback Callback; + void *UserData; + + ImGuiContextHook() { memset(this, 0, sizeof(*this)); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiContext (main Dear ImGui context) +//----------------------------------------------------------------------------- + +struct ImGuiContext +{ + bool Initialized; + bool FontAtlasOwnedByContext; // IO.Fonts-> is owned by the ImGuiContext and will be destructed along with it. + ImGuiIO IO; + ImGuiPlatformIO PlatformIO; + ImVector InputEventsQueue; // Input events which will be tricked/written into IO structure. + ImVector InputEventsTrail; // Past input events processed in NewFrame(). This is to allow domain-specific application to access e.g mouse/pen trail. + ImGuiStyle Style; + ImGuiConfigFlags ConfigFlagsCurrFrame; // = g.IO.ConfigFlags at the time of NewFrame() + ImGuiConfigFlags ConfigFlagsLastFrame; + ImFont *Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() + float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. + float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. + ImDrawListSharedData DrawListSharedData; + double Time; + int FrameCount; + int FrameCountEnded; + int FrameCountPlatformEnded; + int FrameCountRendered; + bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame() + bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed + bool WithinEndChild; // Set within EndChild() + bool GcCompactAll; // Request full GC + bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log() + void *TestEngine; // Test engine user data + + // Windows state + ImVector Windows; // Windows, sorted in display order, back to front + ImVector WindowsFocusOrder; // Root windows, sorted in focus order, back to front. + ImVector WindowsTempSortBuffer; // Temporary buffer used in EndFrame() to reorder windows so parents are kept before their child + ImVector CurrentWindowStack; + ImGuiStorage WindowsById; // Map window's ImGuiID to ImGuiWindow* + int WindowsActiveCount; // Number of unique windows submitted by frame + ImVec2 WindowsHoverPadding; // Padding around resizable windows for which hovering on counts as hovering the window == ImMax(style.TouchExtraPadding, WINDOWS_HOVER_PADDING) + ImGuiWindow *CurrentWindow; // Window being drawn into + ImGuiWindow *HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. + ImGuiWindow *HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. + ImGuiDockNode *HoveredDockNode; // [Debug] Hovered dock node. + ImGuiWindow *MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindowDockTree. + ImGuiWindow *WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. + ImVec2 WheelingWindowRefMousePos; + float WheelingWindowTimer; + + // Item/widgets state and tracking information + ImGuiID DebugHookIdInfo; // Will call core hooks: DebugHookIdInfo() from GetID functions, used by Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line] + ImGuiID HoveredId; // Hovered widget, filled during the frame + ImGuiID HoveredIdPreviousFrame; + bool HoveredIdAllowOverlap; + bool HoveredIdUsingMouseWheel; // Hovered widget will use mouse wheel. Blocks scrolling the underlying window. + bool HoveredIdPreviousFrameUsingMouseWheel; + bool HoveredIdDisabled; // At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. + float HoveredIdTimer; // Measure contiguous hovering time + float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active + ImGuiID ActiveId; // Active widget + ImGuiID ActiveIdIsAlive; // Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) + float ActiveIdTimer; + bool ActiveIdIsJustActivated; // Set at the time of activation for one frame + bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) + bool ActiveIdNoClearOnFocusLoss; // Disable losing active id if the active id window gets unfocused. + bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. + bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state. + bool ActiveIdHasBeenEditedThisFrame; + ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) + ImGuiWindow *ActiveIdWindow; + ImGuiInputSource ActiveIdSource; // Activating with mouse or nav (gamepad/keyboard) + int ActiveIdMouseButton; + ImGuiID ActiveIdPreviousFrame; + bool ActiveIdPreviousFrameIsAlive; + bool ActiveIdPreviousFrameHasBeenEditedBefore; + ImGuiWindow *ActiveIdPreviousFrameWindow; + ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation. + float LastActiveIdTimer; // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. + + // Input Ownership + bool ActiveIdUsingMouseWheel; // Active widget will want to read mouse wheel. Blocks scrolling the underlying window. + ImU32 ActiveIdUsingNavDirMask; // Active widget will want to read those nav move requests (e.g. can activate a button and move away from it) + ImU32 ActiveIdUsingNavInputMask; // Active widget will want to read those nav inputs. + ImBitArrayForNamedKeys ActiveIdUsingKeyInputMask; // Active widget will want to read those key inputs. When we grow the ImGuiKey enum we'll need to either to order the enum to make useful keys come first, either redesign this into e.g. a small array. + + // Next window/item data + ImGuiItemFlags CurrentItemFlags; // == g.ItemFlagsStack.back() + ImGuiNextItemData NextItemData; // Storage for SetNextItem** functions + ImGuiLastItemData LastItemData; // Storage for last submitted item (setup by ItemAdd) + ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions + + // Shared stacks + ImVector ColorStack; // Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() + ImVector StyleVarStack; // Stack for PushStyleVar()/PopStyleVar() - inherited by Begin() + ImVector FontStack; // Stack for PushFont()/PopFont() - inherited by Begin() + ImVector FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() - not inherited by Begin(), unless child window + ImVector ItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() + ImVector GroupStack; // Stack for BeginGroup()/EndGroup() - not inherited by Begin() + ImVector OpenPopupStack; // Which popups are open (persistent) + ImVector BeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) + int BeginMenuCount; + + // Viewports + ImVector Viewports; // Active viewports (always 1+, and generally 1 unless multi-viewports are enabled). Each viewports hold their copy of ImDrawData. + float CurrentDpiScale; // == CurrentViewport->DpiScale + ImGuiViewportP *CurrentViewport; // We track changes of viewport (happening in Begin) so we can call Platform_OnChangedViewport() + ImGuiViewportP *MouseViewport; + ImGuiViewportP *MouseLastHoveredViewport; // Last known viewport that was hovered by mouse (even if we are not hovering any viewport any more) + honoring the _NoInputs flag. + ImGuiID PlatformLastFocusedViewportId; + ImGuiPlatformMonitor FallbackMonitor; // Virtual monitor used as fallback if backend doesn't provide monitor information. + int ViewportFrontMostStampCount; // Every time the front-most window changes, we stamp its viewport with an incrementing counter + + // Gamepad/keyboard Navigation + ImGuiWindow *NavWindow; // Focused window for navigation. Could be called 'FocusedWindow' + ImGuiID NavId; // Focused item for navigation + ImGuiID NavFocusScopeId; // Identify a selection scope (selection code often wants to "clear other items" when landing on an item of the selection set) + ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0, also set when calling ActivateItem() + ImGuiID NavActivateDownId; // ~~ IsNavInputDown(ImGuiNavInput_Activate) ? NavId : 0 + ImGuiID NavActivatePressedId; // ~~ IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0 + ImGuiID NavActivateInputId; // ~~ IsNavInputPressed(ImGuiNavInput_Input) ? NavId : 0; ImGuiActivateFlags_PreferInput will be set and NavActivateId will be 0. + ImGuiActivateFlags NavActivateFlags; + ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest). + ImGuiID NavJustMovedToFocusScopeId; // Just navigated to this focus scope id (result of a successfully MoveRequest). + ImGuiModFlags NavJustMovedToKeyMods; + ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame. + ImGuiActivateFlags NavNextActivateFlags; + ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard. + ImGuiNavLayer NavLayer; // Layer we are navigating on. For now the system is hard-coded for 0=main contents and 1=menu/title bar, may expose layers later. + bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRectRel is valid + bool NavMousePosDirty; // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default) + bool NavDisableHighlight; // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover) + bool NavDisableMouseHover; // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again. + + // Navigation: Init & Move Requests + bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd() + bool NavInitRequest; // Init request for appearing window to select first item + bool NavInitRequestFromMove; + ImGuiID NavInitResultId; // Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) + ImRect NavInitResultRectRel; // Init request result rectangle (relative to parent window) + bool NavMoveSubmitted; // Move request submitted, will process result on next NewFrame() + bool NavMoveScoringItems; // Move request submitted, still scoring incoming items + bool NavMoveForwardToNextFrame; + ImGuiNavMoveFlags NavMoveFlags; + ImGuiScrollFlags NavMoveScrollFlags; + ImGuiModFlags NavMoveKeyMods; + ImGuiDir NavMoveDir; // Direction of the move request (left/right/up/down) + ImGuiDir NavMoveDirForDebug; + ImGuiDir NavMoveClipDir; // FIXME-NAV: Describe the purpose of this better. Might want to rename? + ImRect NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->NavRectRel[], modified for directional navigation scoring. + ImRect NavScoringNoClipRect; // Some nav operations (such as PageUp/PageDown) enforce a region which clipper will attempt to always keep submitted + int NavScoringDebugCount; // Metrics for debugging + int NavTabbingDir; // Generally -1 or +1, 0 when tabbing without a nav id + int NavTabbingCounter; // >0 when counting items for tabbing + ImGuiNavItemData NavMoveResultLocal; // Best move request candidate within NavWindow + ImGuiNavItemData NavMoveResultLocalVisible; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag) + ImGuiNavItemData NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag) + ImGuiNavItemData NavTabbingResultFirst; // First tabbing request candidate within NavWindow and flattened hierarchy + + // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) + ImGuiWindow *NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! + ImGuiWindow *NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it. + ImGuiWindow *NavWindowingListWindow; // Internal window actually listing the CTRL+Tab contents + float NavWindowingTimer; + float NavWindowingHighlightAlpha; + bool NavWindowingToggleLayer; + + // Render + float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) + ImGuiMouseCursor MouseCursor; + + // Drag and Drop + bool DragDropActive; + bool DragDropWithinSource; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source. + bool DragDropWithinTarget; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target. + ImGuiDragDropFlags DragDropSourceFlags; + int DragDropSourceFrameCount; + int DragDropMouseButton; + ImGuiPayload DragDropPayload; + ImRect DragDropTargetRect; // Store rectangle of current target candidate (we favor small targets when overlapping) + ImGuiID DragDropTargetId; + ImGuiDragDropFlags DragDropAcceptFlags; + float DragDropAcceptIdCurrRectSurface; // Target item surface (we resolve overlapping targets by prioritizing the smaller surface) + ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload) + ImGuiID DragDropAcceptIdPrev; // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets) + int DragDropAcceptFrameCount; // Last time a target expressed a desire to accept the source + ImGuiID DragDropHoldJustPressedId; // Set when holding a payload just made ButtonBehavior() return a press. + ImVector DragDropPayloadBufHeap; // We don't expose the ImVector<> directly, ImGuiPayload only holds pointer+size + unsigned char DragDropPayloadBufLocal[16]; // Local buffer for small payloads + + // Clipper + int ClipperTempDataStacked; + ImVector ClipperTempData; + + // Tables + ImGuiTable *CurrentTable; + int TablesTempDataStacked; // Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) + ImVector TablesTempData; // Temporary table data (buffers reused/shared across instances, support nesting) + ImPool Tables; // Persistent table data + ImVector TablesLastTimeActive; // Last used timestamp of each tables (SOA, for efficient GC) + ImVector DrawChannelsTempMergeBuffer; + + // Tab bars + ImGuiTabBar *CurrentTabBar; + ImPool TabBars; + ImVector CurrentTabBarStack; + ImVector ShrinkWidthBuffer; + + // Widget state + ImVec2 MouseLastValidPos; + ImGuiInputTextState InputTextState; + ImFont InputTextPasswordFont; + ImGuiID TempInputId; // Temporary text input when CTRL+clicking on a slider, etc. + ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets + float ColorEditLastHue; // Backup of last Hue associated to LastColor, so we can restore Hue in lossy RGB<>HSV round trips + float ColorEditLastSat; // Backup of last Saturation associated to LastColor, so we can restore Saturation in lossy RGB<>HSV round trips + ImU32 ColorEditLastColor; // RGB value with alpha set to 0. + ImVec4 ColorPickerRef; // Initial/reference color at the time of opening the color picker. + ImGuiComboPreviewData ComboPreviewData; + float SliderCurrentAccum; // Accumulated slider delta when using navigation controls. + bool SliderCurrentAccumDirty; // Has the accumulated slider delta changed since last time we tried to apply it? + bool DragCurrentAccumDirty; + float DragCurrentAccum; // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings + float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio + float ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? + float DisabledAlphaBackup; // Backup for style.Alpha for BeginDisabled() + short DisabledStackSize; + short TooltipOverrideCount; + float TooltipSlowDelay; // Time before slow tooltips appears (FIXME: This is temporary until we merge in tooltip timer+priority work) + ImVector ClipboardHandlerData; // If no custom clipboard handler is defined + ImVector MenusIdSubmittedThisFrame; // A list of menu IDs that were rendered at least once + + // Platform support + ImGuiPlatformImeData PlatformImeData; // Data updated by current frame + ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data (when changing we will call io.SetPlatformImeDataFn + ImGuiID PlatformImeViewport; + char PlatformLocaleDecimalPoint; // '.' or *localeconv()->decimal_point + + // Extensions + // FIXME: We could provide an API to register one slot in an array held in ImGuiContext? + ImGuiDockContext DockContext; + + // Settings + bool SettingsLoaded; + float SettingsDirtyTimer; // Save .ini Settings to memory when time reaches zero + ImGuiTextBuffer SettingsIniData; // In memory .ini settings + ImVector SettingsHandlers; // List of .ini settings handlers + ImChunkStream SettingsWindows; // ImGuiWindow .ini settings entries + ImChunkStream SettingsTables; // ImGuiTable .ini settings entries + ImVector Hooks; // Hooks for extensions (e.g. test engine) + ImGuiID HookIdNext; // Next available HookId + + // Capture/Logging + bool LogEnabled; // Currently capturing + ImGuiLogType LogType; // Capture target + ImFileHandle LogFile; // If != NULL log to stdout/ file + ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. + const char *LogNextPrefix; + const char *LogNextSuffix; + float LogLinePosY; + bool LogLineFirstItem; + int LogDepthRef; + int LogDepthToExpand; + int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. + + // Debug Tools + bool DebugItemPickerActive; // Item picker is active (started with DebugStartItemPicker()) + ImGuiID DebugItemPickerBreakId; // Will call IM_DEBUG_BREAK() when encountering this ID + ImGuiMetricsConfig DebugMetricsConfig; + ImGuiStackTool DebugStackTool; + + // Misc + float FramerateSecPerFrame[120]; // Calculate estimate of framerate for user over the last 2 seconds. + int FramerateSecPerFrameIdx; + int FramerateSecPerFrameCount; + float FramerateSecPerFrameAccum; + int WantCaptureMouseNextFrame; // Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1. + int WantCaptureKeyboardNextFrame; // " + int WantTextInputNextFrame; + char TempBuffer[1024 * 3 + 1]; // Temporary text buffer + + ImGuiContext(ImFontAtlas *shared_font_atlas) + { + Initialized = false; + ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None; + FontAtlasOwnedByContext = shared_font_atlas ? false : true; + Font = NULL; + FontSize = FontBaseSize = 0.0f; + IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); + Time = 0.0f; + FrameCount = 0; + FrameCountEnded = FrameCountPlatformEnded = FrameCountRendered = -1; + WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false; + GcCompactAll = false; + TestEngineHookItems = false; + TestEngine = NULL; + + WindowsActiveCount = 0; + CurrentWindow = NULL; + HoveredWindow = NULL; + HoveredWindowUnderMovingWindow = NULL; + HoveredDockNode = NULL; + MovingWindow = NULL; + WheelingWindow = NULL; + WheelingWindowTimer = 0.0f; + + DebugHookIdInfo = 0; + HoveredId = HoveredIdPreviousFrame = 0; + HoveredIdAllowOverlap = false; + HoveredIdUsingMouseWheel = HoveredIdPreviousFrameUsingMouseWheel = false; + HoveredIdDisabled = false; + HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f; + ActiveId = 0; + ActiveIdIsAlive = 0; + ActiveIdTimer = 0.0f; + ActiveIdIsJustActivated = false; + ActiveIdAllowOverlap = false; + ActiveIdNoClearOnFocusLoss = false; + ActiveIdHasBeenPressedBefore = false; + ActiveIdHasBeenEditedBefore = false; + ActiveIdHasBeenEditedThisFrame = false; + ActiveIdClickOffset = ImVec2(-1, -1); + ActiveIdWindow = NULL; + ActiveIdSource = ImGuiInputSource_None; + ActiveIdMouseButton = -1; + ActiveIdPreviousFrame = 0; + ActiveIdPreviousFrameIsAlive = false; + ActiveIdPreviousFrameHasBeenEditedBefore = false; + ActiveIdPreviousFrameWindow = NULL; + LastActiveId = 0; + LastActiveIdTimer = 0.0f; + + ActiveIdUsingMouseWheel = false; + ActiveIdUsingNavDirMask = 0x00; + ActiveIdUsingNavInputMask = 0x00; + ActiveIdUsingKeyInputMask.ClearAllBits(); + + CurrentItemFlags = ImGuiItemFlags_None; + BeginMenuCount = 0; + + CurrentDpiScale = 0.0f; + CurrentViewport = NULL; + MouseViewport = MouseLastHoveredViewport = NULL; + PlatformLastFocusedViewportId = 0; + ViewportFrontMostStampCount = 0; + + NavWindow = NULL; + NavId = NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavActivateInputId = 0; + NavJustMovedToId = NavJustMovedToFocusScopeId = NavNextActivateId = 0; + NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None; + NavJustMovedToKeyMods = ImGuiModFlags_None; + NavInputSource = ImGuiInputSource_None; + NavLayer = ImGuiNavLayer_Main; + NavIdIsAlive = false; + NavMousePosDirty = false; + NavDisableHighlight = true; + NavDisableMouseHover = false; + NavAnyRequest = false; + NavInitRequest = false; + NavInitRequestFromMove = false; + NavInitResultId = 0; + NavMoveSubmitted = false; + NavMoveScoringItems = false; + NavMoveForwardToNextFrame = false; + NavMoveFlags = ImGuiNavMoveFlags_None; + NavMoveScrollFlags = ImGuiScrollFlags_None; + NavMoveKeyMods = ImGuiModFlags_None; + NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None; + NavScoringDebugCount = 0; + NavTabbingDir = 0; + NavTabbingCounter = 0; + + NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL; + NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f; + NavWindowingToggleLayer = false; + + DimBgRatio = 0.0f; + MouseCursor = ImGuiMouseCursor_Arrow; + + DragDropActive = DragDropWithinSource = DragDropWithinTarget = false; + DragDropSourceFlags = ImGuiDragDropFlags_None; + DragDropSourceFrameCount = -1; + DragDropMouseButton = -1; + DragDropTargetId = 0; + DragDropAcceptFlags = ImGuiDragDropFlags_None; + DragDropAcceptIdCurrRectSurface = 0.0f; + DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0; + DragDropAcceptFrameCount = -1; + DragDropHoldJustPressedId = 0; + memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal)); + + ClipperTempDataStacked = 0; + + CurrentTable = NULL; + TablesTempDataStacked = 0; + CurrentTabBar = NULL; + + TempInputId = 0; + ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_; + ColorEditLastHue = ColorEditLastSat = 0.0f; + ColorEditLastColor = 0; + SliderCurrentAccum = 0.0f; + SliderCurrentAccumDirty = false; + DragCurrentAccumDirty = false; + DragCurrentAccum = 0.0f; + DragSpeedDefaultRatio = 1.0f / 100.0f; + DisabledAlphaBackup = 0.0f; + DisabledStackSize = 0; + ScrollbarClickDeltaToGrabCenter = 0.0f; + TooltipOverrideCount = 0; + TooltipSlowDelay = 0.50f; + + PlatformImeData.InputPos = ImVec2(0.0f, 0.0f); + PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission + PlatformImeViewport = 0; + PlatformLocaleDecimalPoint = '.'; + + SettingsLoaded = false; + SettingsDirtyTimer = 0.0f; + HookIdNext = 0; + + LogEnabled = false; + LogType = ImGuiLogType_None; + LogNextPrefix = LogNextSuffix = NULL; + LogFile = NULL; + LogLinePosY = FLT_MAX; + LogLineFirstItem = false; + LogDepthRef = 0; + LogDepthToExpand = LogDepthToExpandDefault = 2; + + DebugItemPickerActive = false; + DebugItemPickerBreakId = 0; + + memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); + FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0; + FramerateSecPerFrameAccum = 0.0f; + WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1; + memset(TempBuffer, 0, sizeof(TempBuffer)); + } +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGuiWindowTempData, ImGuiWindow +//----------------------------------------------------------------------------- + +// Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. +// (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..) +// (This doesn't need a constructor because we zero-clear it as part of ImGuiWindow and all frame-temporary data are setup on Begin) +struct IMGUI_API ImGuiWindowTempData +{ + // Layout + ImVec2 CursorPos; // Current emitting position, in absolute coordinates. + ImVec2 CursorPosPrevLine; + ImVec2 CursorStartPos; // Initial position after Begin(), generally ~ window position + WindowPadding. + ImVec2 CursorMaxPos; // Used to implicitly calculate ContentSize at the beginning of next frame, for scrolling range and auto-resize. Always growing during the frame. + ImVec2 IdealMaxPos; // Used to implicitly calculate ContentSizeIdeal at the beginning of next frame, for auto-resize only. Always growing during the frame. + ImVec2 CurrLineSize; + ImVec2 PrevLineSize; + float CurrLineTextBaseOffset; // Baseline offset (0.0f by default on a new line, generally == style.FramePadding.y when a framed item has been added). + float PrevLineTextBaseOffset; + bool IsSameLine; + ImVec1 Indent; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + ImVec1 ColumnsOffset; // 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. + ImVec1 GroupOffset; + ImVec2 CursorStartPosLossyness; // Record the loss of precision of CursorStartPos due to really large scrolling amount. This is used by clipper to compensentate and fix the most common use case of large scroll area. + + // Keyboard/Gamepad navigation + ImGuiNavLayer NavLayerCurrent; // Current layer, 0..31 (we currently only use 0..1) + short NavLayersActiveMask; // Which layers have been written to (result from previous frame) + short NavLayersActiveMaskNext; // Which layers have been written to (accumulator for current frame) + ImGuiID NavFocusScopeIdCurrent; // Current focus scope ID while appending + bool NavHideHighlightOneFrame; + bool NavHasScroll; // Set when scrolling can be used (ScrollMax > 0.0f) + + // Miscellaneous + bool MenuBarAppending; // FIXME: Remove this + ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs. + ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items measurement + int TreeDepth; // Current tree depth. + ImU32 TreeJumpToParentOnPopMask; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31.. Could be turned into a ImU64 if necessary. + ImVector ChildWindows; + ImGuiStorage *StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state) + ImGuiOldColumns *CurrentColumns; // Current columns set + int CurrentTableIdx; // Current table index (into g.Tables) + ImGuiLayoutType LayoutType; + ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() + + // Local parameters stacks + // 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; // Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window). + float TextWrapPos; // Current text wrap pos. + ImVector ItemWidthStack; // Store item widths to restore (attention: .back() is not == ItemWidth) + ImVector TextWrapPosStack; // Store text wrap pos to restore (attention: .back() is not == TextWrapPos) +}; + +// Storage for one window +struct IMGUI_API ImGuiWindow +{ + char *Name; // Window name, owned by the window. + ImGuiID ID; // == ImHashStr(Name) + ImGuiWindowFlags Flags, FlagsPreviousFrame; // See enum ImGuiWindowFlags_ + ImGuiWindowClass WindowClass; // Advanced users only. Set with SetNextWindowClass() + ImGuiViewportP *Viewport; // Always set in Begin(). Inactive windows may have a NULL value here if their viewport was discarded. + ImGuiID ViewportId; // We backup the viewport id (since the viewport may disappear or never be created if the window is inactive) + ImVec2 ViewportPos; // We backup the viewport position (since the viewport may disappear or never be created if the window is inactive) + int ViewportAllowPlatformMonitorExtend; // Reset to -1 every frame (index is guaranteed to be valid between NewFrame..EndFrame), only used in the Appearing frame of a tooltip/popup to enforce clamping to a given monitor + ImVec2 Pos; // Position (always rounded-up to nearest pixel) + ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) + ImVec2 SizeFull; // Size when non collapsed + ImVec2 ContentSize; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. + ImVec2 ContentSizeIdeal; + ImVec2 ContentSizeExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). + ImVec2 WindowPadding; // Window padding at the time of Begin(). + float WindowRounding; // Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc. + float WindowBorderSize; // Window border size at the time of Begin(). + int NameBufLen; // Size of buffer storing Name. May be larger than strlen(Name)! + ImGuiID MoveId; // == window->GetID("#MOVE") + ImGuiID TabId; // == window->GetID("#TAB") + ImGuiID ChildId; // ID of corresponding item in parent window (for navigation to return from child window to parent window) + ImVec2 Scroll; + ImVec2 ScrollMax; + 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 + ImVec2 ScrollTargetEdgeSnapDist; // 0.0f = no snapping, >0.0f snapping threshold + ImVec2 ScrollbarSizes; // Size taken by each scrollbars on their smaller axis. Pay attention! ScrollbarSizes.x == width of the vertical scrollbar, ScrollbarSizes.y = height of the horizontal scrollbar. + bool ScrollbarX, ScrollbarY; // Are scrollbars visible? + bool ViewportOwned; + bool Active; // Set to true on Begin(), unless Collapsed + bool WasActive; + bool WriteAccessed; // Set to true when any widget access the current window + bool Collapsed; // Set when collapsing window to become only title-bar + bool WantCollapseToggle; + bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed) + bool Appearing; // Set during the frame where the window is appearing (or re-appearing) + bool Hidden; // Do not display (== HiddenFrames*** > 0) + bool IsFallbackWindow; // Set on the "Debug##Default" window. + bool IsExplicitChild; // Set when passed _ChildWindow, left to false by BeginDocked() + bool HasCloseButton; // Set when the window has a close button (p_open != NULL) + signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3) + short BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) + short BeginOrderWithinParent; // Begin() order within immediate parent window, if we are a child window. Otherwise 0. + short BeginOrderWithinContext; // Begin() order within entire imgui context. This is mostly used for debugging submission order related issues. + short FocusOrder; // Order within WindowsFocusOrder[], altered when windows are focused. + ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) + ImS8 AutoFitFramesX, AutoFitFramesY; + ImS8 AutoFitChildAxises; + bool AutoFitOnlyGrows; + ImGuiDir AutoPosLastDirection; + ImS8 HiddenFramesCanSkipItems; // Hide the window for N frames + ImS8 HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size + ImS8 HiddenFramesForRenderOnly; // Hide the window until frame N at Render() time only + ImS8 DisableInputsFrames; // Disable window interactions for N frames + ImGuiCond SetWindowPosAllowFlags : 8; // store acceptable condition flags for SetNextWindowPos() use. + ImGuiCond SetWindowSizeAllowFlags : 8; // store acceptable condition flags for SetNextWindowSize() use. + ImGuiCond SetWindowCollapsedAllowFlags : 8; // store acceptable condition flags for SetNextWindowCollapsed() use. + ImGuiCond SetWindowDockAllowFlags : 8; // store acceptable condition flags for SetNextWindowDock() use. + ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) + ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5f, 0.5f) for centering; ImVec2(1, 1) for bottom right. + + ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure) + ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. + + // The best way to understand what those rectangles are is to use the 'Metrics->Tools->Show Windows Rectangles' viewer. + // The main 'OuterRect', omitted as a field, is window->Rect(). + ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window. + ImRect InnerRect; // Inner rectangle (omit title bar, menu bar, scroll bar) + ImRect InnerClipRect; // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect. + ImRect WorkRect; // Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). + ImRect ParentWorkRect; // Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. // FIXME-WORKRECT: Could be a stack? + ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back(). + ImRect ContentRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. + ImVec2ih HitTestHoleSize; // Define an optional rectangular hole where mouse will pass-through the window. + ImVec2ih HitTestHoleOffset; + + int LastFrameActive; // Last frame number the window was Active. + int LastFrameJustFocused; // Last frame number the window was made Focused. + float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there) + float ItemWidthDefault; + ImGuiStorage StateStorage; + ImVector ColumnsStorage; + float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() + float FontDpiScale; + int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) + + ImDrawList *DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) + ImDrawList DrawListInst; + ImGuiWindow *ParentWindow; // If we are a child _or_ popup _or_ docked window, this is pointing to our parent. Otherwise NULL. + ImGuiWindow *ParentWindowInBeginStack; + ImGuiWindow *RootWindow; // Point to ourself or first ancestor that is not a child window. Doesn't cross through popups/dock nodes. + ImGuiWindow *RootWindowPopupTree; // Point to ourself or first ancestor that is not a child window. Cross through popups parent<>child. + ImGuiWindow *RootWindowDockTree; // Point to ourself or first ancestor that is not a child window. Cross through dock nodes. + ImGuiWindow *RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active. + ImGuiWindow *RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag. + + ImGuiWindow *NavLastChildNavWindow; // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) + ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1) + ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space + + int MemoryDrawListIdxCapacity; // Backup of last idx/vtx count, so when waking up the window we can preallocate and avoid iterative alloc/copy + int MemoryDrawListVtxCapacity; + bool MemoryCompacted; // Set when window extraneous data have been garbage collected + + // Docking + bool DockIsActive : 1; // When docking artifacts are actually visible. When this is set, DockNode is guaranteed to be != NULL. ~~ (DockNode != NULL) && (DockNode->Windows.Size > 1). + bool DockNodeIsVisible : 1; + bool DockTabIsVisible : 1; // Is our window visible this frame? ~~ is the corresponding tab selected? + bool DockTabWantClose : 1; + short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. + ImGuiWindowDockStyle DockStyle; + ImGuiDockNode *DockNode; // Which node are we docked into. Important: Prefer testing DockIsActive in many cases as this will still be set when the dock node is hidden. + ImGuiDockNode *DockNodeAsHost; // Which node are we owning (for parent windows) + ImGuiID DockId; // Backup of last valid DockNode->ID, so single window remember their dock node id even when they are not bound any more + ImGuiItemStatusFlags DockTabItemStatusFlags; + ImRect DockTabItemRect; + +public: + ImGuiWindow(ImGuiContext *context, const char *name); + ~ImGuiWindow(); + + ImGuiID GetID(const char *str, const char *str_end = NULL); + ImGuiID GetID(const void *ptr); + ImGuiID GetID(int n); + ImGuiID GetIDFromRectangle(const ImRect &r_abs); + + // We don't use g.FontSize because the window may be != g.CurrentWidow. + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } + float CalcFontSize() const + { + ImGuiContext &g = *GImGui; + float scale = g.FontBaseSize * FontWindowScale * FontDpiScale; + if (ParentWindow) + scale *= ParentWindow->FontWindowScale; + return scale; + } + float TitleBarHeight() const + { + ImGuiContext &g = *GImGui; + return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; + } + ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } + float MenuBarHeight() const + { + ImGuiContext &g = *GImGui; + return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.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()); + } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Tab bar, Tab item support +//----------------------------------------------------------------------------- + +// Extend ImGuiTabBarFlags_ +enum ImGuiTabBarFlagsPrivate_ +{ + ImGuiTabBarFlags_DockNode = 1 << 20, // Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around] + ImGuiTabBarFlags_IsFocused = 1 << 21, + ImGuiTabBarFlags_SaveSettings = 1 << 22 // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs +}; + +// Extend ImGuiTabItemFlags_ +enum ImGuiTabItemFlagsPrivate_ +{ + ImGuiTabItemFlags_SectionMask_ = ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing, + ImGuiTabItemFlags_NoCloseButton = 1 << 20, // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) + ImGuiTabItemFlags_Button = 1 << 21, // Used by TabItemButton, change the tab item behavior to mimic a button + ImGuiTabItemFlags_Unsorted = 1 << 22, // [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window. + ImGuiTabItemFlags_Preview = 1 << 23 // [Docking] Display tab shape for docking preview (height is adjusted slightly to compensate for the yet missing tab bar) +}; + +// Storage for one active tab item (sizeof() 48 bytes) +struct ImGuiTabItem +{ + ImGuiID ID; + ImGuiTabItemFlags Flags; + ImGuiWindow *Window; // When TabItem is part of a DockNode's TabBar, we hold on to a window. + int LastFrameVisible; + int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance + float Offset; // Position relative to beginning of tab + float Width; // Width currently displayed + float ContentWidth; // Width of label, stored during BeginTabItem() call + ImS32 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames + ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable + ImS16 IndexDuringLayout; // Index only used during TabBarLayout() + bool WantClose; // Marked as closed by SetTabItemClosed() + + ImGuiTabItem() + { + memset(this, 0, sizeof(*this)); + LastFrameVisible = LastFrameSelected = -1; + NameOffset = -1; + BeginOrder = IndexDuringLayout = -1; + } +}; + +// Storage for a tab bar (sizeof() 152 bytes) +struct IMGUI_API ImGuiTabBar +{ + ImVector Tabs; + ImGuiTabBarFlags Flags; + ImGuiID ID; // Zero for tab-bars used by docking + ImGuiID SelectedTabId; // Selected tab/window + ImGuiID NextSelectedTabId; // Next selected tab/window. Will also trigger a scrolling animation + ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for CTRL+TAB preview) + int CurrFrameVisible; + int PrevFrameVisible; + ImRect BarRect; + float CurrTabsContentsHeight; + float PrevTabsContentsHeight; // Record the height of contents submitted below the tab bar + float WidthAllTabs; // Actual width of all tabs (locked during layout) + float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped + float ScrollingAnim; + float ScrollingTarget; + float ScrollingTargetDistToVisibility; + float ScrollingSpeed; + float ScrollingRectMinX; + float ScrollingRectMaxX; + ImGuiID ReorderRequestTabId; + ImS16 ReorderRequestOffset; + ImS8 BeginCount; + bool WantLayout; + bool VisibleTabWasSubmitted; + bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame + ImS16 TabsActiveCount; // Number of tabs submitted this frame. + ImS16 LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() + float ItemSpacingY; + ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() + ImVec2 BackupCursorPos; + ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. + + ImGuiTabBar(); + int GetTabOrder(const ImGuiTabItem *tab) const { return Tabs.index_from_ptr(tab); } + const char *GetTabName(const ImGuiTabItem *tab) const + { + if (tab->Window) + return tab->Window->Name; + IM_ASSERT(tab->NameOffset != -1 && tab->NameOffset < TabsNames.Buf.Size); + return TabsNames.Buf.Data + tab->NameOffset; + } +}; + +//----------------------------------------------------------------------------- +// [SECTION] Table support +//----------------------------------------------------------------------------- + +#define IM_COL32_DISABLE IM_COL32(0, 0, 0, 1) // Special sentinel code which cannot be used as a regular color. +#define IMGUI_TABLE_MAX_COLUMNS 64 // sizeof(ImU64) * 8. This is solely because we frequently encode columns set in a ImU64. +#define IMGUI_TABLE_MAX_DRAW_CHANNELS (4 + 64 * 2) // See TableSetupDrawChannels() + +// Our current column maximum is 64 but we may raise that in the future. +typedef ImS8 ImGuiTableColumnIdx; +typedef ImU8 ImGuiTableDrawChannelIdx; + +// [Internal] sizeof() ~ 104 +// We use the terminology "Enabled" to refer to a column that is not Hidden by user/api. +// We use the terminology "Clipped" to refer to a column that is out of sight because of scrolling/clipping. +// This is in contrast with some user-facing api such as IsItemVisible() / IsRectVisible() which use "Visible" to mean "not clipped". +struct ImGuiTableColumn +{ + ImGuiTableColumnFlags Flags; // Flags after some patching (not directly same as provided by user). See ImGuiTableColumnFlags_ + float WidthGiven; // Final/actual width visible == (MaxX - MinX), locked in TableUpdateLayout(). May be > WidthRequest to honor minimum width, may be < WidthRequest to honor shrinking columns down in tight space. + float MinX; // Absolute positions + float MaxX; + float WidthRequest; // Master width absolute value when !(Flags & _WidthStretch). When Stretch this is derived every frame from StretchWeight in TableUpdateLayout() + float WidthAuto; // Automatic width + float StretchWeight; // Master width weight when (Flags & _WidthStretch). Often around ~1.0f initially. + float InitStretchWeightOrWidth; // Value passed to TableSetupColumn(). For Width it is a content width (_without padding_). + ImRect ClipRect; // Clipping rectangle for the column + ImGuiID UserID; // Optional, value passed to TableSetupColumn() + float WorkMinX; // Contents region min ~(MinX + CellPaddingX + CellSpacingX1) == cursor start position when entering column + float WorkMaxX; // Contents region max ~(MaxX - CellPaddingX - CellSpacingX2) + float ItemWidth; // Current item width for the column, preserved across rows + float ContentMaxXFrozen; // Contents maximum position for frozen rows (apart from headers), from which we can infer content width. + float ContentMaxXUnfrozen; + float ContentMaxXHeadersUsed; // Contents maximum position for headers rows (regardless of freezing). TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls + float ContentMaxXHeadersIdeal; + ImS16 NameOffset; // Offset into parent ColumnsNames[] + ImGuiTableColumnIdx DisplayOrder; // Index within Table's IndexToDisplayOrder[] (column may be reordered by users) + ImGuiTableColumnIdx IndexWithinEnabledSet; // Index within enabled/visible set (<= IndexToDisplayOrder) + ImGuiTableColumnIdx PrevEnabledColumn; // Index of prev enabled/visible column within Columns[], -1 if first enabled/visible column + ImGuiTableColumnIdx NextEnabledColumn; // Index of next enabled/visible column within Columns[], -1 if last enabled/visible column + ImGuiTableColumnIdx SortOrder; // Index of this column within sort specs, -1 if not sorting on this column, 0 for single-sort, may be >0 on multi-sort + ImGuiTableDrawChannelIdx DrawChannelCurrent; // Index within DrawSplitter.Channels[] + ImGuiTableDrawChannelIdx DrawChannelFrozen; // Draw channels for frozen rows (often headers) + ImGuiTableDrawChannelIdx DrawChannelUnfrozen; // Draw channels for unfrozen rows + bool IsEnabled; // IsUserEnabled && (Flags & ImGuiTableColumnFlags_Disabled) == 0 + bool IsUserEnabled; // Is the column not marked Hidden by the user? (unrelated to being off view, e.g. clipped by scrolling). + bool IsUserEnabledNextFrame; + bool IsVisibleX; // Is actually in view (e.g. overlapping the host window clipping rectangle, not scrolled). + bool IsVisibleY; + bool IsRequestOutput; // Return value for TableSetColumnIndex() / TableNextColumn(): whether we request user to output contents or not. + bool IsSkipItems; // Do we want item submissions to this column to be completely ignored (no layout will happen). + bool IsPreserveWidthAuto; + ImS8 NavLayerCurrent; // ImGuiNavLayer in 1 byte + ImU8 AutoFitQueue; // Queue of 8 values for the next 8 frames to request auto-fit + ImU8 CannotSkipItemsQueue; // Queue of 8 values for the next 8 frames to disable Clipped/SkipItem + ImU8 SortDirection : 2; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending + ImU8 SortDirectionsAvailCount : 2; // Number of available sort directions (0 to 3) + ImU8 SortDirectionsAvailMask : 4; // Mask of available sort directions (1-bit each) + ImU8 SortDirectionsAvailList; // Ordered of available sort directions (2-bits each) + + ImGuiTableColumn() + { + memset(this, 0, sizeof(*this)); + StretchWeight = WidthRequest = -1.0f; + NameOffset = -1; + DisplayOrder = IndexWithinEnabledSet = -1; + PrevEnabledColumn = NextEnabledColumn = -1; + SortOrder = -1; + SortDirection = ImGuiSortDirection_None; + DrawChannelCurrent = DrawChannelFrozen = DrawChannelUnfrozen = (ImU8)-1; + } +}; + +// Transient cell data stored per row. +// sizeof() ~ 6 +struct ImGuiTableCellData +{ + ImU32 BgColor; // Actual color + ImGuiTableColumnIdx Column; // Column number +}; + +// Per-instance data that needs preserving across frames (seemingly most others do not need to be preserved aside from debug needs, does that needs they could be moved to ImGuiTableTempData ?) +struct ImGuiTableInstanceData +{ + float LastOuterHeight; // Outer height from last frame // FIXME: multi-instance issue (#3955) + float LastFirstRowHeight; // Height of first row from last frame // FIXME: possible multi-instance issue? + + ImGuiTableInstanceData() { LastOuterHeight = LastFirstRowHeight = 0.0f; } +}; + +// FIXME-TABLE: more transient data could be stored in a per-stacked table structure: DrawSplitter, SortSpecs, incoming RowData +struct IMGUI_API ImGuiTable +{ + ImGuiID ID; + ImGuiTableFlags Flags; + void *RawData; // Single allocation to hold Columns[], DisplayOrderToIndex[] and RowCellData[] + ImGuiTableTempData *TempData; // Transient data while table is active. Point within g.CurrentTableStack[] + ImSpan Columns; // Point within RawData[] + ImSpan DisplayOrderToIndex; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1) + ImSpan RowCellData; // Point within RawData[]. Store cells background requests for current row. + ImU64 EnabledMaskByDisplayOrder; // Column DisplayOrder -> IsEnabled map + ImU64 EnabledMaskByIndex; // Column Index -> IsEnabled map (== not hidden by user/api) in a format adequate for iterating column without touching cold data + ImU64 VisibleMaskByIndex; // Column Index -> IsVisibleX|IsVisibleY map (== not hidden by user/api && not hidden by scrolling/cliprect) + ImU64 RequestOutputMaskByIndex; // Column Index -> IsVisible || AutoFit (== expect user to submit items) + ImGuiTableFlags SettingsLoadedFlags; // Which data were loaded from the .ini file (e.g. when order is not altered we won't save order) + int SettingsOffset; // Offset in g.SettingsTables + int LastFrameActive; + int ColumnsCount; // Number of columns declared in BeginTable() + int CurrentRow; + int CurrentColumn; + ImS16 InstanceCurrent; // Count of BeginTable() calls with same ID in the same frame (generally 0). This is a little bit similar to BeginCount for a window, but multiple table with same ID look are multiple tables, they are just synched. + ImS16 InstanceInteracted; // Mark which instance (generally 0) of the same ID is being interacted with + float RowPosY1; + float RowPosY2; + float RowMinHeight; // Height submitted to TableNextRow() + float RowTextBaseline; + float RowIndentOffsetX; + ImGuiTableRowFlags RowFlags : 16; // Current row flags, see ImGuiTableRowFlags_ + ImGuiTableRowFlags LastRowFlags : 16; + int RowBgColorCounter; // Counter for alternating background colors (can be fast-forwarded by e.g clipper), not same as CurrentRow because header rows typically don't increase this. + ImU32 RowBgColor[2]; // Background color override for current row. + ImU32 BorderColorStrong; + ImU32 BorderColorLight; + float BorderX1; + float BorderX2; + float HostIndentX; + float MinColumnWidth; + float OuterPaddingX; + float CellPaddingX; // Padding from each borders + float CellPaddingY; + float CellSpacingX1; // Spacing between non-bordered cells + float CellSpacingX2; + float InnerWidth; // User value passed to BeginTable(), see comments at the top of BeginTable() for details. + float ColumnsGivenWidth; // Sum of current column width + float ColumnsAutoFitWidth; // Sum of ideal column width in order nothing to be clipped, used for auto-fitting and content width submission in outer window + float ColumnsStretchSumWeights; // Sum of weight of all enabled stretching columns + float ResizedColumnNextWidth; + float ResizeLockMinContentsX2; // Lock minimum contents width while resizing down in order to not create feedback loops. But we allow growing the table. + float RefScale; // Reference scale to be able to rescale columns on font/dpi changes. + ImRect OuterRect; // Note: for non-scrolling table, OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). + ImRect InnerRect; // InnerRect but without decoration. As with OuterRect, for non-scrolling tables, InnerRect.Max.y is + ImRect WorkRect; + ImRect InnerClipRect; + ImRect BgClipRect; // We use this to cpu-clip cell background color fill, evolve during the frame as we cross frozen rows boundaries + ImRect Bg0ClipRectForDrawCmd; // Actual ImDrawCmd clip rect for BG0/1 channel. This tends to be == OuterWindow->ClipRect at BeginTable() because output in BG0/BG1 is cpu-clipped + ImRect Bg2ClipRectForDrawCmd; // Actual ImDrawCmd clip rect for BG2 channel. This tends to be a correct, tight-fit, because output to BG2 are done by widgets relying on regular ClipRect. + ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window. + ImRect HostBackupInnerClipRect; // Backup of InnerWindow->ClipRect during PushTableBackground()/PopTableBackground() + ImGuiWindow *OuterWindow; // Parent window for the table + ImGuiWindow *InnerWindow; // Window holding the table data (== OuterWindow or a child window) + ImGuiTextBuffer ColumnsNames; // Contiguous buffer holding columns names + ImDrawListSplitter *DrawSplitter; // Shortcut to TempData->DrawSplitter while in table. Isolate draw commands per columns to avoid switching clip rect constantly + ImGuiTableInstanceData InstanceDataFirst; + ImVector InstanceDataExtra; // FIXME-OPT: Using a small-vector pattern would be good. + ImGuiTableColumnSortSpecs SortSpecsSingle; + ImVector SortSpecsMulti; // FIXME-OPT: Using a small-vector pattern would be good. + ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs() + ImGuiTableColumnIdx SortSpecsCount; + ImGuiTableColumnIdx ColumnsEnabledCount; // Number of enabled columns (<= ColumnsCount) + ImGuiTableColumnIdx ColumnsEnabledFixedCount; // Number of enabled columns (<= ColumnsCount) + ImGuiTableColumnIdx DeclColumnsCount; // Count calls to TableSetupColumn() + ImGuiTableColumnIdx HoveredColumnBody; // Index of column whose visible region is being hovered. Important: == ColumnsCount when hovering empty region after the right-most column! + ImGuiTableColumnIdx HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing). + ImGuiTableColumnIdx AutoFitSingleColumn; // Index of single column requesting auto-fit. + ImGuiTableColumnIdx ResizedColumn; // Index of column being resized. Reset when InstanceCurrent==0. + ImGuiTableColumnIdx LastResizedColumn; // Index of column being resized from previous frame. + ImGuiTableColumnIdx HeldHeaderColumn; // Index of column header being held. + ImGuiTableColumnIdx ReorderColumn; // Index of column being reordered. (not cleared) + ImGuiTableColumnIdx ReorderColumnDir; // -1 or +1 + ImGuiTableColumnIdx LeftMostEnabledColumn; // Index of left-most non-hidden column. + ImGuiTableColumnIdx RightMostEnabledColumn; // Index of right-most non-hidden column. + ImGuiTableColumnIdx LeftMostStretchedColumn; // Index of left-most stretched column. + ImGuiTableColumnIdx RightMostStretchedColumn; // Index of right-most stretched column. + ImGuiTableColumnIdx ContextPopupColumn; // Column right-clicked on, of -1 if opening context menu from a neutral/empty spot + ImGuiTableColumnIdx FreezeRowsRequest; // Requested frozen rows count + ImGuiTableColumnIdx FreezeRowsCount; // Actual frozen row count (== FreezeRowsRequest, or == 0 when no scrolling offset) + ImGuiTableColumnIdx FreezeColumnsRequest; // Requested frozen columns count + ImGuiTableColumnIdx FreezeColumnsCount; // Actual frozen columns count (== FreezeColumnsRequest, or == 0 when no scrolling offset) + ImGuiTableColumnIdx RowCellDataCurrent; // Index of current RowCellData[] entry in current row + ImGuiTableDrawChannelIdx DummyDrawChannel; // Redirect non-visible columns here. + ImGuiTableDrawChannelIdx Bg2DrawChannelCurrent; // For Selectable() and other widgets drawing across columns after the freezing line. Index within DrawSplitter.Channels[] + ImGuiTableDrawChannelIdx Bg2DrawChannelUnfrozen; + bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. + bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). + bool IsInitializing; + bool IsSortSpecsDirty; + bool IsUsingHeaders; // Set when the first row had the ImGuiTableRowFlags_Headers flag. + bool IsContextPopupOpen; // Set when default context menu is open (also see: ContextPopupColumn, InstanceInteracted). + bool IsSettingsRequestLoad; + bool IsSettingsDirty; // Set when table settings have changed and needs to be reported into ImGuiTableSetttings data. + bool IsDefaultDisplayOrder; // Set when display order is unchanged from default (DisplayOrder contains 0...Count-1) + bool IsResetAllRequest; + bool IsResetDisplayOrderRequest; + bool IsUnfrozenRows; // Set when we got past the frozen row. + bool IsDefaultSizingPolicy; // Set if user didn't explicitly set a sizing policy in BeginTable() + bool MemoryCompacted; + bool HostSkipItems; // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis + + ImGuiTable() + { + memset(this, 0, sizeof(*this)); + LastFrameActive = -1; + } + ~ImGuiTable() { IM_FREE(RawData); } +}; + +// Transient data that are only needed between BeginTable() and EndTable(), those buffers are shared (1 per level of stacked table). +// - Accessing those requires chasing an extra pointer so for very frequently used data we leave them in the main table structure. +// - We also leave out of this structure data that tend to be particularly useful for debugging/metrics. +struct IMGUI_API ImGuiTableTempData +{ + int TableIndex; // Index in g.Tables.Buf[] pool + float LastTimeActive; // Last timestamp this structure was used + + ImVec2 UserOuterSize; // outer_size.x passed to BeginTable() + ImDrawListSplitter DrawSplitter; + + ImRect HostBackupWorkRect; // Backup of InnerWindow->WorkRect at the end of BeginTable() + ImRect HostBackupParentWorkRect; // Backup of InnerWindow->ParentWorkRect at the end of BeginTable() + ImVec2 HostBackupPrevLineSize; // Backup of InnerWindow->DC.PrevLineSize at the end of BeginTable() + ImVec2 HostBackupCurrLineSize; // Backup of InnerWindow->DC.CurrLineSize at the end of BeginTable() + ImVec2 HostBackupCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable() + ImVec1 HostBackupColumnsOffset; // Backup of OuterWindow->DC.ColumnsOffset at the end of BeginTable() + float HostBackupItemWidth; // Backup of OuterWindow->DC.ItemWidth at the end of BeginTable() + int HostBackupItemWidthStackSize; // Backup of OuterWindow->DC.ItemWidthStack.Size at the end of BeginTable() + + ImGuiTableTempData() + { + memset(this, 0, sizeof(*this)); + LastTimeActive = -1.0f; + } +}; + +// sizeof() ~ 12 +struct ImGuiTableColumnSettings +{ + float WidthOrWeight; + ImGuiID UserID; + ImGuiTableColumnIdx Index; + ImGuiTableColumnIdx DisplayOrder; + ImGuiTableColumnIdx SortOrder; + ImU8 SortDirection : 2; + ImU8 IsEnabled : 1; // "Visible" in ini file + ImU8 IsStretch : 1; + + ImGuiTableColumnSettings() + { + WidthOrWeight = 0.0f; + UserID = 0; + Index = -1; + DisplayOrder = SortOrder = -1; + SortDirection = ImGuiSortDirection_None; + IsEnabled = 1; + IsStretch = 0; + } +}; + +// This is designed to be stored in a single ImChunkStream (1 header followed by N ImGuiTableColumnSettings, etc.) +struct ImGuiTableSettings +{ + ImGuiID ID; // Set to 0 to invalidate/delete the setting + ImGuiTableFlags SaveFlags; // Indicate data we want to save using the Resizable/Reorderable/Sortable/Hideable flags (could be using its own flags..) + float RefScale; // Reference scale to be able to rescale columns on font/dpi changes. + ImGuiTableColumnIdx ColumnsCount; + ImGuiTableColumnIdx ColumnsCountMax; // Maximum number of columns this settings instance can store, we can recycle a settings instance with lower number of columns but not higher + bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) + + ImGuiTableSettings() { memset(this, 0, sizeof(*this)); } + ImGuiTableColumnSettings *GetColumnSettings() { return (ImGuiTableColumnSettings *)(this + 1); } +}; + +//----------------------------------------------------------------------------- +// [SECTION] ImGui internal API +// No guarantee of forward compatibility here! +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // Windows + // 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::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. + inline ImGuiWindow *GetCurrentWindowRead() + { + ImGuiContext &g = *GImGui; + return g.CurrentWindow; + } + inline ImGuiWindow *GetCurrentWindow() + { + ImGuiContext &g = *GImGui; + g.CurrentWindow->WriteAccessed = true; + return g.CurrentWindow; + } + IMGUI_API ImGuiWindow *FindWindowByID(ImGuiID id); + IMGUI_API ImGuiWindow *FindWindowByName(const char *name); + IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow *window, ImGuiWindowFlags flags, ImGuiWindow *parent_window); + IMGUI_API ImVec2 CalcWindowNextAutoFitSize(ImGuiWindow *window); + IMGUI_API bool IsWindowChildOf(ImGuiWindow *window, ImGuiWindow *potential_parent, bool popup_hierarchy, bool dock_hierarchy); + IMGUI_API bool IsWindowWithinBeginStackOf(ImGuiWindow *window, ImGuiWindow *potential_parent); + IMGUI_API bool IsWindowAbove(ImGuiWindow *potential_above, ImGuiWindow *potential_below); + IMGUI_API bool IsWindowNavFocusable(ImGuiWindow *window); + IMGUI_API void SetWindowPos(ImGuiWindow *window, const ImVec2 &pos, ImGuiCond cond = 0); + IMGUI_API void SetWindowSize(ImGuiWindow *window, const ImVec2 &size, ImGuiCond cond = 0); + IMGUI_API void SetWindowCollapsed(ImGuiWindow *window, bool collapsed, ImGuiCond cond = 0); + IMGUI_API void SetWindowHitTestHole(ImGuiWindow *window, const ImVec2 &pos, const ImVec2 &size); + inline ImRect WindowRectAbsToRel(ImGuiWindow *window, const ImRect &r) + { + ImVec2 off = window->DC.CursorStartPos; + return ImRect(r.Min.x - off.x, r.Min.y - off.y, r.Max.x - off.x, r.Max.y - off.y); + } + inline ImRect WindowRectRelToAbs(ImGuiWindow *window, const ImRect &r) + { + ImVec2 off = window->DC.CursorStartPos; + return ImRect(r.Min.x + off.x, r.Min.y + off.y, r.Max.x + off.x, r.Max.y + off.y); + } + + // Windows: Display Order and Focus Order + IMGUI_API void FocusWindow(ImGuiWindow *window); + IMGUI_API void FocusTopMostWindowUnderOne(ImGuiWindow *under_this_window, ImGuiWindow *ignore_window); + IMGUI_API void BringWindowToFocusFront(ImGuiWindow *window); + IMGUI_API void BringWindowToDisplayFront(ImGuiWindow *window); + IMGUI_API void BringWindowToDisplayBack(ImGuiWindow *window); + IMGUI_API void BringWindowToDisplayBehind(ImGuiWindow *window, ImGuiWindow *above_window); + IMGUI_API int FindWindowDisplayIndex(ImGuiWindow *window); + IMGUI_API ImGuiWindow *FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow *window); + + // Fonts, drawing + IMGUI_API void SetCurrentFont(ImFont *font); + inline ImFont *GetDefaultFont() + { + ImGuiContext &g = *GImGui; + return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; + } + inline ImDrawList *GetForegroundDrawList(ImGuiWindow *window) { return GetForegroundDrawList(window->Viewport); } + + // Init + IMGUI_API void Initialize(); + IMGUI_API void Shutdown(); // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext(). + + // NewFrame + IMGUI_API void UpdateInputEvents(bool trickle_fast_inputs); + IMGUI_API void UpdateHoveredWindowAndCaptureFlags(); + IMGUI_API void StartMouseMovingWindow(ImGuiWindow *window); + IMGUI_API void StartMouseMovingWindowOrNode(ImGuiWindow *window, ImGuiDockNode *node, bool undock_floating_node); + IMGUI_API void UpdateMouseMovingWindowNewFrame(); + IMGUI_API void UpdateMouseMovingWindowEndFrame(); + + // Generic context hooks + IMGUI_API ImGuiID AddContextHook(ImGuiContext *context, const ImGuiContextHook *hook); + IMGUI_API void RemoveContextHook(ImGuiContext *context, ImGuiID hook_to_remove); + IMGUI_API void CallContextHooks(ImGuiContext *context, ImGuiContextHookType type); + + // Viewports + IMGUI_API void TranslateWindowsInViewport(ImGuiViewportP *viewport, const ImVec2 &old_pos, const ImVec2 &new_pos); + IMGUI_API void ScaleWindowsInViewport(ImGuiViewportP *viewport, float scale); + IMGUI_API void DestroyPlatformWindow(ImGuiViewportP *viewport); + IMGUI_API void SetWindowViewport(ImGuiWindow *window, ImGuiViewportP *viewport); + IMGUI_API void SetCurrentViewport(ImGuiWindow *window, ImGuiViewportP *viewport); + IMGUI_API const ImGuiPlatformMonitor *GetViewportPlatformMonitor(ImGuiViewport *viewport); + IMGUI_API ImGuiViewportP *FindHoveredViewportFromPlatformWindowStack(const ImVec2 &mouse_platform_pos); + + // Settings + IMGUI_API void MarkIniSettingsDirty(); + IMGUI_API void MarkIniSettingsDirty(ImGuiWindow *window); + IMGUI_API void ClearIniSettings(); + IMGUI_API ImGuiWindowSettings *CreateNewWindowSettings(const char *name); + IMGUI_API ImGuiWindowSettings *FindWindowSettings(ImGuiID id); + IMGUI_API ImGuiWindowSettings *FindOrCreateWindowSettings(const char *name); + IMGUI_API void AddSettingsHandler(const ImGuiSettingsHandler *handler); + IMGUI_API void RemoveSettingsHandler(const char *type_name); + IMGUI_API ImGuiSettingsHandler *FindSettingsHandler(const char *type_name); + + // Scrolling + IMGUI_API void SetNextWindowScroll(const ImVec2 &scroll); // Use -1.0f on one axis to leave as-is + IMGUI_API void SetScrollX(ImGuiWindow *window, float scroll_x); + IMGUI_API void SetScrollY(ImGuiWindow *window, float scroll_y); + IMGUI_API void SetScrollFromPosX(ImGuiWindow *window, float local_x, float center_x_ratio); + IMGUI_API void SetScrollFromPosY(ImGuiWindow *window, float local_y, float center_y_ratio); + + // Early work-in-progress API (ScrollToItem() will become public) + IMGUI_API void ScrollToItem(ImGuiScrollFlags flags = 0); + IMGUI_API void ScrollToRect(ImGuiWindow *window, const ImRect &rect, ImGuiScrollFlags flags = 0); + IMGUI_API ImVec2 ScrollToRectEx(ImGuiWindow *window, const ImRect &rect, ImGuiScrollFlags flags = 0); + // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline void ScrollToBringRectIntoView(ImGuiWindow *window, const ImRect &rect) { ScrollToRect(window, rect, ImGuiScrollFlags_KeepVisibleEdgeY); } + // #endif + + // Basic Accessors + inline ImGuiID GetItemID() + { + ImGuiContext &g = *GImGui; + return g.LastItemData.ID; + } // Get ID of last item (~~ often same ImGui::GetID(label) beforehand) + inline ImGuiItemStatusFlags GetItemStatusFlags() + { + ImGuiContext &g = *GImGui; + return g.LastItemData.StatusFlags; + } + inline ImGuiItemFlags GetItemFlags() + { + ImGuiContext &g = *GImGui; + return g.LastItemData.InFlags; + } + inline ImGuiID GetActiveID() + { + ImGuiContext &g = *GImGui; + return g.ActiveId; + } + inline ImGuiID GetFocusID() + { + ImGuiContext &g = *GImGui; + return g.NavId; + } + IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow *window); + IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow *window); + IMGUI_API void ClearActiveID(); + IMGUI_API ImGuiID GetHoveredID(); + IMGUI_API void SetHoveredID(ImGuiID id); + IMGUI_API void KeepAliveID(ImGuiID id); + IMGUI_API void MarkItemEdited(ImGuiID id); // Mark data associated to given item as "edited", used by IsItemDeactivatedAfterEdit() function. + IMGUI_API void PushOverrideID(ImGuiID id); // Push given value as-is at the top of the ID stack (whereas PushID combines old and new hashes) + IMGUI_API ImGuiID GetIDWithSeed(const char *str_id_begin, const char *str_id_end, ImGuiID seed); + + // Basic Helpers for widget code + IMGUI_API void ItemSize(const ImVec2 &size, float text_baseline_y = -1.0f); + inline void ItemSize(const ImRect &bb, float text_baseline_y = -1.0f) { ItemSize(bb.GetSize(), text_baseline_y); } // FIXME: This is a misleading API since we expect CursorPos to be bb.Min. + IMGUI_API bool ItemAdd(const ImRect &bb, ImGuiID id, const ImRect *nav_bb = NULL, ImGuiItemFlags extra_flags = 0); + IMGUI_API bool ItemHoverable(const ImRect &bb, ImGuiID id); + IMGUI_API bool IsClippedEx(const ImRect &bb, ImGuiID id); + IMGUI_API void SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags status_flags, const ImRect &item_rect); + IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); + IMGUI_API float CalcWrapWidthForPos(const ImVec2 &pos, float wrap_pos_x); + IMGUI_API void PushMultiItemsWidths(int components, float width_full); + IMGUI_API bool IsItemToggledSelection(); // Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) + IMGUI_API ImVec2 GetContentRegionMaxAbs(); + IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem *items, int count, float width_excess); + + // Parameter stacks + IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); + IMGUI_API void PopItemFlag(); + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // Currently refactoring focus/nav/tabbing system + // If you have old/custom copy-and-pasted widgets that used FocusableItemRegister(): + // (Old) IMGUI_VERSION_NUM < 18209: using 'ItemAdd(....)' and 'bool tab_focused = FocusableItemRegister(...)' + // (Old) IMGUI_VERSION_NUM >= 18209: using 'ItemAdd(..., ImGuiItemAddFlags_Focusable)' and 'bool tab_focused = (GetItemStatusFlags() & ImGuiItemStatusFlags_Focused) != 0' + // (New) IMGUI_VERSION_NUM >= 18413: using 'ItemAdd(..., ImGuiItemFlags_Inputable)' and 'bool tab_focused = (GetItemStatusFlags() & ImGuiItemStatusFlags_FocusedTabbing) != 0 || g.NavActivateInputId == id' (WIP) + // Widget code are simplified as there's no need to call FocusableItemUnregister() while managing the transition from regular widget to TempInputText() + inline bool FocusableItemRegister(ImGuiWindow *window, ImGuiID id) + { + IM_ASSERT(0); + IM_UNUSED(window); + IM_UNUSED(id); + return false; + } // -> pass ImGuiItemAddFlags_Inputable flag to ItemAdd() + inline void FocusableItemUnregister(ImGuiWindow *window) + { + IM_ASSERT(0); + IM_UNUSED(window); + } // -> unnecessary: TempInputText() uses ImGuiInputTextFlags_MergedItem +#endif + + // Logging/Capture + IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. + IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer + IMGUI_API void LogRenderedText(const ImVec2 *ref_pos, const char *text, const char *text_end = NULL); + IMGUI_API void LogSetNextTextDecoration(const char *prefix, const char *suffix); + + // Popups, Modals, Tooltips + IMGUI_API bool BeginChildEx(const char *name, ImGuiID id, const ImVec2 &size_arg, bool border, ImGuiWindowFlags flags); + IMGUI_API void OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags = ImGuiPopupFlags_None); + IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); + IMGUI_API void ClosePopupsOverWindow(ImGuiWindow *ref_window, bool restore_focus_to_window_under_popup); + IMGUI_API void ClosePopupsExceptModals(); + IMGUI_API bool IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags); + IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); + IMGUI_API void BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags); + IMGUI_API ImRect GetPopupAllowedExtentRect(ImGuiWindow *window); + IMGUI_API ImGuiWindow *GetTopMostPopupModal(); + IMGUI_API ImGuiWindow *GetTopMostAndVisiblePopupModal(); + IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow *window); + IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2 &ref_pos, const ImVec2 &size, ImGuiDir *last_dir, const ImRect &r_outer, const ImRect &r_avoid, ImGuiPopupPositionPolicy policy); + + // Menus + IMGUI_API bool BeginViewportSideBar(const char *name, ImGuiViewport *viewport, ImGuiDir dir, float size, ImGuiWindowFlags window_flags); + IMGUI_API bool BeginMenuEx(const char *label, const char *icon, bool enabled = true); + IMGUI_API bool MenuItemEx(const char *label, const char *icon, const char *shortcut = NULL, bool selected = false, bool enabled = true); + + // Combos + IMGUI_API bool BeginComboPopup(ImGuiID popup_id, const ImRect &bb, ImGuiComboFlags flags); + IMGUI_API bool BeginComboPreview(); + IMGUI_API void EndComboPreview(); + + // Gamepad/Keyboard Navigation + IMGUI_API void NavInitWindow(ImGuiWindow *window, bool force_reinit); + IMGUI_API void NavInitRequestApplyResult(); + IMGUI_API bool NavMoveRequestButNoResultYet(); + IMGUI_API void NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); + IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); + IMGUI_API void NavMoveRequestResolveWithLastItem(ImGuiNavItemData *result); + IMGUI_API void NavMoveRequestCancel(); + IMGUI_API void NavMoveRequestApplyResult(); + IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow *window, ImGuiNavMoveFlags move_flags); + IMGUI_API const char *GetNavInputName(ImGuiNavInput n); + IMGUI_API float GetNavInputAmount(ImGuiNavInput n, ImGuiNavReadMode mode); + IMGUI_API ImVec2 GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiNavReadMode mode, float slow_factor = 0.0f, float fast_factor = 0.0f); + IMGUI_API int CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate); + IMGUI_API void ActivateItem(ImGuiID id); // Remotely activate a button, checkbox, tree node etc. given its unique ID. activation is queued and processed on the next frame when the item is encountered again. + IMGUI_API void SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect &rect_rel); + + // Focus Scope (WIP) + // This is generally used to identify a selection set (multiple of which may be in the same window), as selection + // patterns generally need to react (e.g. clear selection) when landing on an item of the set. + IMGUI_API void PushFocusScope(ImGuiID id); + IMGUI_API void PopFocusScope(); + inline ImGuiID GetFocusedFocusScope() + { + ImGuiContext &g = *GImGui; + return g.NavFocusScopeId; + } // Focus scope which is actually active + inline ImGuiID GetFocusScope() + { + ImGuiContext &g = *GImGui; + return g.CurrentWindow->DC.NavFocusScopeIdCurrent; + } // Focus scope we are outputting into, set by PushFocusScope() + + // Inputs + // FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. + inline bool IsNamedKey(ImGuiKey key) { return key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END; } + inline bool IsLegacyKey(ImGuiKey key) { return key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_LegacyNativeKey_END; } + inline bool IsGamepadKey(ImGuiKey key) { return key >= ImGuiKey_Gamepad_BEGIN && key < ImGuiKey_Gamepad_END; } + IMGUI_API ImGuiKeyData *GetKeyData(ImGuiKey key); + IMGUI_API void SetItemUsingMouseWheel(); + IMGUI_API void SetActiveIdUsingNavAndKeys(); + inline bool IsActiveIdUsingNavDir(ImGuiDir dir) + { + ImGuiContext &g = *GImGui; + return (g.ActiveIdUsingNavDirMask & (1 << dir)) != 0; + } + inline bool IsActiveIdUsingNavInput(ImGuiNavInput input) + { + ImGuiContext &g = *GImGui; + return (g.ActiveIdUsingNavInputMask & (1 << input)) != 0; + } + inline bool IsActiveIdUsingKey(ImGuiKey key) + { + ImGuiContext &g = *GImGui; + return g.ActiveIdUsingKeyInputMask[key]; + } + inline void SetActiveIdUsingKey(ImGuiKey key) + { + ImGuiContext &g = *GImGui; + g.ActiveIdUsingKeyInputMask.SetBit(key); + } + IMGUI_API bool IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold = -1.0f); + inline bool IsNavInputDown(ImGuiNavInput n) + { + ImGuiContext &g = *GImGui; + return g.IO.NavInputs[n] > 0.0f; + } + inline bool IsNavInputTest(ImGuiNavInput n, ImGuiNavReadMode rm) { return (GetNavInputAmount(n, rm) > 0.0f); } + IMGUI_API ImGuiModFlags GetMergedModFlags(); +#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO + inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) + { + IM_ASSERT(IsNamedKey(key)); + return IsKeyPressed(key, repeat); + } // [removed in 1.87] +#endif + + // Docking + // (some functions are only declared in imgui.cpp, see Docking section) + IMGUI_API void DockContextInitialize(ImGuiContext *ctx); + IMGUI_API void DockContextShutdown(ImGuiContext *ctx); + IMGUI_API void DockContextClearNodes(ImGuiContext *ctx, ImGuiID root_id, bool clear_settings_refs); // Use root_id==0 to clear all + IMGUI_API void DockContextRebuildNodes(ImGuiContext *ctx); + IMGUI_API void DockContextNewFrameUpdateUndocking(ImGuiContext *ctx); + IMGUI_API void DockContextNewFrameUpdateDocking(ImGuiContext *ctx); + IMGUI_API void DockContextEndFrame(ImGuiContext *ctx); + IMGUI_API ImGuiID DockContextGenNodeID(ImGuiContext *ctx); + IMGUI_API void DockContextQueueDock(ImGuiContext *ctx, ImGuiWindow *target, ImGuiDockNode *target_node, ImGuiWindow *payload, ImGuiDir split_dir, float split_ratio, bool split_outer); + IMGUI_API void DockContextQueueUndockWindow(ImGuiContext *ctx, ImGuiWindow *window); + IMGUI_API void DockContextQueueUndockNode(ImGuiContext *ctx, ImGuiDockNode *node); + IMGUI_API bool DockContextCalcDropPosForDocking(ImGuiWindow *target, ImGuiDockNode *target_node, ImGuiWindow *payload, ImGuiDir split_dir, bool split_outer, ImVec2 *out_pos); + IMGUI_API bool DockNodeBeginAmendTabBar(ImGuiDockNode *node); + IMGUI_API void DockNodeEndAmendTabBar(); + inline ImGuiDockNode *DockNodeGetRootNode(ImGuiDockNode *node) + { + while (node->ParentNode) + node = node->ParentNode; + return node; + } + inline bool DockNodeIsInHierarchyOf(ImGuiDockNode *node, ImGuiDockNode *parent) + { + while (node) + { + if (node == parent) + return true; + node = node->ParentNode; + } + return false; + } + inline int DockNodeGetDepth(const ImGuiDockNode *node) + { + int depth = 0; + while (node->ParentNode) + { + node = node->ParentNode; + depth++; + } + return depth; + } + inline ImGuiID DockNodeGetWindowMenuButtonId(const ImGuiDockNode *node) { return ImHashStr("#COLLAPSE", 0, node->ID); } + inline ImGuiDockNode *GetWindowDockNode() + { + ImGuiContext &g = *GImGui; + return g.CurrentWindow->DockNode; + } + IMGUI_API bool GetWindowAlwaysWantOwnTabBar(ImGuiWindow *window); + IMGUI_API void BeginDocked(ImGuiWindow *window, bool *p_open); + IMGUI_API void BeginDockableDragDropSource(ImGuiWindow *window); + IMGUI_API void BeginDockableDragDropTarget(ImGuiWindow *window); + IMGUI_API void SetWindowDock(ImGuiWindow *window, ImGuiID dock_id, ImGuiCond cond); + + // Docking - Builder function needs to be generally called before the node is used/submitted. + // - The DockBuilderXXX functions are designed to _eventually_ become a public API, but it is too early to expose it and guarantee stability. + // - Do not hold on ImGuiDockNode* pointers! They may be invalidated by any split/merge/remove operation and every frame. + // - To create a DockSpace() node, make sure to set the ImGuiDockNodeFlags_DockSpace flag when calling DockBuilderAddNode(). + // You can create dockspace nodes (attached to a window) _or_ floating nodes (carry its own window) with this API. + // - DockBuilderSplitNode() create 2 child nodes within 1 node. The initial node becomes a parent node. + // - If you intend to split the node immediately after creation using DockBuilderSplitNode(), make sure + // to call DockBuilderSetNodeSize() beforehand. If you don't, the resulting split sizes may not be reliable. + // - Call DockBuilderFinish() after you are done. + IMGUI_API void DockBuilderDockWindow(const char *window_name, ImGuiID node_id); + IMGUI_API ImGuiDockNode *DockBuilderGetNode(ImGuiID node_id); + inline ImGuiDockNode *DockBuilderGetCentralNode(ImGuiID node_id) + { + ImGuiDockNode *node = DockBuilderGetNode(node_id); + if (!node) + return NULL; + return DockNodeGetRootNode(node)->CentralNode; + } + IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id = 0, ImGuiDockNodeFlags flags = 0); + IMGUI_API void DockBuilderRemoveNode(ImGuiID node_id); // Remove node and all its child, undock all windows + IMGUI_API void DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_settings_refs = true); + IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the remaining root node (node_id). + IMGUI_API void DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos); + IMGUI_API void DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size); + IMGUI_API ImGuiID DockBuilderSplitNode(ImGuiID node_id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID *out_id_at_dir, ImGuiID *out_id_at_opposite_dir); // Create 2 child nodes in this parent node. + IMGUI_API void DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector *in_window_remap_pairs); + IMGUI_API void DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector *out_node_remap_pairs); + IMGUI_API void DockBuilderCopyWindowSettings(const char *src_name, const char *dst_name); + IMGUI_API void DockBuilderFinish(ImGuiID node_id); + + // Drag and Drop + IMGUI_API bool BeginDragDropTargetCustom(const ImRect &bb, ImGuiID id); + IMGUI_API void ClearDragDrop(); + IMGUI_API bool IsDragDropPayloadBeingAccepted(); + + // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) + IMGUI_API void SetWindowClipRectBeforeSetChannel(ImGuiWindow *window, const ImRect &clip_rect); + IMGUI_API void BeginColumns(const char *str_id, int count, ImGuiOldColumnFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). + IMGUI_API void EndColumns(); // close columns + IMGUI_API void PushColumnClipRect(int column_index); + IMGUI_API void PushColumnsBackground(); + IMGUI_API void PopColumnsBackground(); + IMGUI_API ImGuiID GetColumnsID(const char *str_id, int count); + IMGUI_API ImGuiOldColumns *FindOrCreateColumns(ImGuiWindow *window, ImGuiID id); + IMGUI_API float GetColumnOffsetFromNorm(const ImGuiOldColumns *columns, float offset_norm); + IMGUI_API float GetColumnNormFromOffset(const ImGuiOldColumns *columns, float offset); + + // Tables: Candidates for public API + IMGUI_API void TableOpenContextMenu(int column_n = -1); + IMGUI_API void TableSetColumnWidth(int column_n, float width); + IMGUI_API void TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs); + IMGUI_API int TableGetHoveredColumn(); // May use (TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) instead. Return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. + IMGUI_API float TableGetHeaderRowHeight(); + IMGUI_API void TablePushBackgroundChannel(); + IMGUI_API void TablePopBackgroundChannel(); + + // Tables: Internals + inline ImGuiTable *GetCurrentTable() + { + ImGuiContext &g = *GImGui; + return g.CurrentTable; + } + IMGUI_API ImGuiTable *TableFindByID(ImGuiID id); + IMGUI_API bool BeginTableEx(const char *name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2 &outer_size = ImVec2(0, 0), float inner_width = 0.0f); + IMGUI_API void TableBeginInitMemory(ImGuiTable *table, int columns_count); + IMGUI_API void TableBeginApplyRequests(ImGuiTable *table); + IMGUI_API void TableSetupDrawChannels(ImGuiTable *table); + IMGUI_API void TableUpdateLayout(ImGuiTable *table); + IMGUI_API void TableUpdateBorders(ImGuiTable *table); + IMGUI_API void TableUpdateColumnsWeightFromWidth(ImGuiTable *table); + IMGUI_API void TableDrawBorders(ImGuiTable *table); + IMGUI_API void TableDrawContextMenu(ImGuiTable *table); + IMGUI_API void TableMergeDrawChannels(ImGuiTable *table); + inline ImGuiTableInstanceData *TableGetInstanceData(ImGuiTable *table, int instance_no) + { + if (instance_no == 0) + return &table->InstanceDataFirst; + return &table->InstanceDataExtra[instance_no - 1]; + } + IMGUI_API void TableSortSpecsSanitize(ImGuiTable *table); + IMGUI_API void TableSortSpecsBuild(ImGuiTable *table); + IMGUI_API ImGuiSortDirection TableGetColumnNextSortDirection(ImGuiTableColumn *column); + IMGUI_API void TableFixColumnSortDirection(ImGuiTable *table, ImGuiTableColumn *column); + IMGUI_API float TableGetColumnWidthAuto(ImGuiTable *table, ImGuiTableColumn *column); + IMGUI_API void TableBeginRow(ImGuiTable *table); + IMGUI_API void TableEndRow(ImGuiTable *table); + IMGUI_API void TableBeginCell(ImGuiTable *table, int column_n); + IMGUI_API void TableEndCell(ImGuiTable *table); + IMGUI_API ImRect TableGetCellBgRect(const ImGuiTable *table, int column_n); + IMGUI_API const char *TableGetColumnName(const ImGuiTable *table, int column_n); + IMGUI_API ImGuiID TableGetColumnResizeID(const ImGuiTable *table, int column_n, int instance_no = 0); + IMGUI_API float TableGetMaxColumnWidth(const ImGuiTable *table, int column_n); + IMGUI_API void TableSetColumnWidthAutoSingle(ImGuiTable *table, int column_n); + IMGUI_API void TableSetColumnWidthAutoAll(ImGuiTable *table); + IMGUI_API void TableRemove(ImGuiTable *table); + IMGUI_API void TableGcCompactTransientBuffers(ImGuiTable *table); + IMGUI_API void TableGcCompactTransientBuffers(ImGuiTableTempData *table); + IMGUI_API void TableGcCompactSettings(); + + // Tables: Settings + IMGUI_API void TableLoadSettings(ImGuiTable *table); + IMGUI_API void TableSaveSettings(ImGuiTable *table); + IMGUI_API void TableResetSettings(ImGuiTable *table); + IMGUI_API ImGuiTableSettings *TableGetBoundSettings(ImGuiTable *table); + IMGUI_API void TableSettingsAddSettingsHandler(); + IMGUI_API ImGuiTableSettings *TableSettingsCreate(ImGuiID id, int columns_count); + IMGUI_API ImGuiTableSettings *TableSettingsFindByID(ImGuiID id); + + // Tab Bars + IMGUI_API bool BeginTabBarEx(ImGuiTabBar *tab_bar, const ImRect &bb, ImGuiTabBarFlags flags, ImGuiDockNode *dock_node); + IMGUI_API ImGuiTabItem *TabBarFindTabByID(ImGuiTabBar *tab_bar, ImGuiID tab_id); + IMGUI_API ImGuiTabItem *TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar *tab_bar); + IMGUI_API void TabBarAddTab(ImGuiTabBar *tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow *window); + IMGUI_API void TabBarRemoveTab(ImGuiTabBar *tab_bar, ImGuiID tab_id); + IMGUI_API void TabBarCloseTab(ImGuiTabBar *tab_bar, ImGuiTabItem *tab); + IMGUI_API void TabBarQueueReorder(ImGuiTabBar *tab_bar, const ImGuiTabItem *tab, int offset); + IMGUI_API void TabBarQueueReorderFromMousePos(ImGuiTabBar *tab_bar, const ImGuiTabItem *tab, ImVec2 mouse_pos); + IMGUI_API bool TabBarProcessReorder(ImGuiTabBar *tab_bar); + IMGUI_API bool TabItemEx(ImGuiTabBar *tab_bar, const char *label, bool *p_open, ImGuiTabItemFlags flags, ImGuiWindow *docked_window); + IMGUI_API ImVec2 TabItemCalcSize(const char *label, bool has_close_button); + IMGUI_API void TabItemBackground(ImDrawList *draw_list, const ImRect &bb, ImGuiTabItemFlags flags, ImU32 col); + IMGUI_API void TabItemLabelAndCloseButton(ImDrawList *draw_list, const ImRect &bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char *label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool *out_just_closed, bool *out_text_clipped); + + // Render helpers + // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT. + // NB: All position are in absolute pixels coordinates (we are never using window coordinates internally) + IMGUI_API void RenderText(ImVec2 pos, const char *text, const char *text_end = NULL, bool hide_text_after_hash = true); + IMGUI_API void RenderTextWrapped(ImVec2 pos, const char *text, const char *text_end, float wrap_width); + IMGUI_API void RenderTextClipped(const ImVec2 &pos_min, const ImVec2 &pos_max, const char *text, const char *text_end, const ImVec2 *text_size_if_known, const ImVec2 &align = ImVec2(0, 0), const ImRect *clip_rect = NULL); + IMGUI_API void RenderTextClippedEx(ImDrawList *draw_list, const ImVec2 &pos_min, const ImVec2 &pos_max, const char *text, const char *text_end, const ImVec2 *text_size_if_known, const ImVec2 &align = ImVec2(0, 0), const ImRect *clip_rect = NULL); + IMGUI_API void RenderTextEllipsis(ImDrawList *draw_list, const ImVec2 &pos_min, const ImVec2 &pos_max, float clip_max_x, float ellipsis_max_x, const char *text, const char *text_end, const ImVec2 *text_size_if_known); + IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); + IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f); + IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImDrawList *draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0); + IMGUI_API void RenderNavHighlight(const ImRect &bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_TypeDefault); // Navigation highlight + IMGUI_API const char *FindRenderedTextEnd(const char *text, const char *text_end = NULL); // Find the optional ## from which we stop displaying text. + IMGUI_API void RenderMouseCursor(ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow); + + // Render helpers (those functions don't access any ImGui state!) + IMGUI_API void RenderArrow(ImDrawList *draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f); + IMGUI_API void RenderBullet(ImDrawList *draw_list, ImVec2 pos, ImU32 col); + IMGUI_API void RenderCheckMark(ImDrawList *draw_list, ImVec2 pos, ImU32 col, float sz); + IMGUI_API void RenderArrowPointingAt(ImDrawList *draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); + IMGUI_API void RenderArrowDockMenu(ImDrawList *draw_list, ImVec2 p_min, float sz, ImU32 col); + IMGUI_API void RenderRectFilledRangeH(ImDrawList *draw_list, const ImRect &rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding); + IMGUI_API void RenderRectFilledWithHole(ImDrawList *draw_list, const ImRect &outer, const ImRect &inner, ImU32 col, float rounding); + IMGUI_API ImDrawFlags CalcRoundingFlagsForRectInRect(const ImRect &r_in, const ImRect &r_outer, float threshold); + + // Widgets + IMGUI_API void TextEx(const char *text, const char *text_end = NULL, ImGuiTextFlags flags = 0); + IMGUI_API bool ButtonEx(const char *label, const ImVec2 &size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); + IMGUI_API bool CloseButton(ImGuiID id, const ImVec2 &pos); + IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2 &pos, ImGuiDockNode *dock_node); + IMGUI_API bool ArrowButtonEx(const char *str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); + IMGUI_API void Scrollbar(ImGuiAxis axis); + IMGUI_API bool ScrollbarEx(const ImRect &bb, ImGuiID id, ImGuiAxis axis, ImS64 *p_scroll_v, ImS64 avail_v, ImS64 contents_v, ImDrawFlags flags); + IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2 &size, const ImVec2 &uv0, const ImVec2 &uv1, const ImVec2 &padding, const ImVec4 &bg_col, const ImVec4 &tint_col); + IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow *window, ImGuiAxis axis); + IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow *window, ImGuiAxis axis); + IMGUI_API ImGuiID GetWindowResizeCornerID(ImGuiWindow *window, int n); // 0..3: corners + IMGUI_API ImGuiID GetWindowResizeBorderID(ImGuiWindow *window, ImGuiDir dir); + IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags); + IMGUI_API bool CheckboxFlags(const char *label, ImS64 *flags, ImS64 flags_value); + IMGUI_API bool CheckboxFlags(const char *label, ImU64 *flags, ImU64 flags_value); + + // Widgets low-level behaviors + IMGUI_API bool ButtonBehavior(const ImRect &bb, ImGuiID id, bool *out_hovered, bool *out_held, ImGuiButtonFlags flags = 0); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void *p_v, float v_speed, const void *p_min, const void *p_max, const char *format, ImGuiSliderFlags flags); + IMGUI_API bool SliderBehavior(const ImRect &bb, ImGuiID id, ImGuiDataType data_type, void *p_v, const void *p_min, const void *p_max, const char *format, ImGuiSliderFlags flags, ImRect *out_grab_bb); + IMGUI_API bool SplitterBehavior(const ImRect &bb, ImGuiID id, ImGuiAxis axis, float *size1, float *size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f, ImU32 bg_col = 0); + IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char *label, const char *label_end = NULL); + IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextItemOpen() data, if any. May return true when logging + IMGUI_API void TreePushOverrideID(ImGuiID id); + + // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. + // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). + // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " + template + IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); + template + IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); + template + IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T *v, float v_speed, T v_min, T v_max, const char *format, ImGuiSliderFlags flags); + template + IMGUI_API bool SliderBehaviorT(const ImRect &bb, ImGuiID id, ImGuiDataType data_type, T *v, T v_min, T v_max, const char *format, ImGuiSliderFlags flags, ImRect *out_grab_bb); + template + IMGUI_API T RoundScalarWithFormatT(const char *format, ImGuiDataType data_type, T v); + template + IMGUI_API bool CheckboxFlagsT(const char *label, T *flags, T flags_value); + + // Data type helpers + IMGUI_API const ImGuiDataTypeInfo *DataTypeGetInfo(ImGuiDataType data_type); + IMGUI_API int DataTypeFormatString(char *buf, int buf_size, ImGuiDataType data_type, const void *p_data, const char *format); + IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void *output, const void *arg_1, const void *arg_2); + IMGUI_API bool DataTypeApplyFromText(const char *buf, ImGuiDataType data_type, void *p_data, const char *format); + IMGUI_API int DataTypeCompare(ImGuiDataType data_type, const void *arg_1, const void *arg_2); + IMGUI_API bool DataTypeClamp(ImGuiDataType data_type, void *p_data, const void *p_min, const void *p_max); + + // InputText + IMGUI_API bool InputTextEx(const char *label, const char *hint, char *buf, int buf_size, const ImVec2 &size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void *user_data = NULL); + IMGUI_API bool TempInputText(const ImRect &bb, ImGuiID id, const char *label, char *buf, int buf_size, ImGuiInputTextFlags flags); + IMGUI_API bool TempInputScalar(const ImRect &bb, ImGuiID id, const char *label, ImGuiDataType data_type, void *p_data, const char *format, const void *p_clamp_min = NULL, const void *p_clamp_max = NULL); + inline bool TempInputIsActive(ImGuiID id) + { + ImGuiContext &g = *GImGui; + return (g.ActiveId == id && g.TempInputId == id); + } + inline ImGuiInputTextState *GetInputTextState(ImGuiID id) + { + ImGuiContext &g = *GImGui; + return (g.InputTextState.ID == id) ? &g.InputTextState : NULL; + } // Get input text state if active + + // Color + IMGUI_API void ColorTooltip(const char *text, const float *col, ImGuiColorEditFlags flags); + IMGUI_API void ColorEditOptionsPopup(const float *col, ImGuiColorEditFlags flags); + IMGUI_API void ColorPickerOptionsPopup(const float *ref_col, ImGuiColorEditFlags flags); + + // Plot + IMGUI_API int 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 frame_size); + + // Shade functions (write over already created vertices) + IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList *draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1); + IMGUI_API void ShadeVertsLinearUV(ImDrawList *draw_list, int vert_start_idx, int vert_end_idx, const ImVec2 &a, const ImVec2 &b, const ImVec2 &uv_a, const ImVec2 &uv_b, bool clamp); + + // Garbage collection + IMGUI_API void GcCompactTransientMiscBuffers(); + IMGUI_API void GcCompactTransientWindowBuffers(ImGuiWindow *window); + IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow *window); + + // Debug Tools + IMGUI_API void ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void *user_data = NULL); + IMGUI_API void ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void *user_data = NULL); + inline void DebugDrawItemRect(ImU32 col = IM_COL32(255, 0, 0, 255)) + { + ImGuiContext &g = *GImGui; + ImGuiWindow *window = g.CurrentWindow; + GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col); + } + inline void DebugStartItemPicker() + { + ImGuiContext &g = *GImGui; + g.DebugItemPickerActive = true; + } + + IMGUI_API void ShowFontAtlas(ImFontAtlas *atlas); + IMGUI_API void DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void *data_id, const void *data_id_end); + IMGUI_API void DebugNodeColumns(ImGuiOldColumns *columns); + IMGUI_API void DebugNodeDockNode(ImGuiDockNode *node, const char *label); + IMGUI_API void DebugNodeDrawList(ImGuiWindow *window, ImGuiViewportP *viewport, const ImDrawList *draw_list, const char *label); + IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList *out_draw_list, const ImDrawList *draw_list, const ImDrawCmd *draw_cmd, bool show_mesh, bool show_aabb); + IMGUI_API void DebugNodeFont(ImFont *font); + IMGUI_API void DebugNodeFontGlyph(ImFont *font, const ImFontGlyph *glyph); + IMGUI_API void DebugNodeStorage(ImGuiStorage *storage, const char *label); + IMGUI_API void DebugNodeTabBar(ImGuiTabBar *tab_bar, const char *label); + IMGUI_API void DebugNodeTable(ImGuiTable *table); + IMGUI_API void DebugNodeTableSettings(ImGuiTableSettings *settings); + IMGUI_API void DebugNodeWindow(ImGuiWindow *window, const char *label); + IMGUI_API void DebugNodeWindowSettings(ImGuiWindowSettings *settings); + IMGUI_API void DebugNodeWindowsList(ImVector *windows, const char *label); + IMGUI_API void DebugNodeWindowsListByBeginStackParent(ImGuiWindow **windows, int windows_size, ImGuiWindow *parent_in_begin_stack); + IMGUI_API void DebugNodeViewport(ImGuiViewportP *viewport); + IMGUI_API void DebugRenderViewportThumbnail(ImDrawList *draw_list, ImGuiViewportP *viewport, const ImRect &bb); + +} // namespace ImGui + +//----------------------------------------------------------------------------- +// [SECTION] ImFontAtlas internal API +//----------------------------------------------------------------------------- + +// This structure is likely to evolve as we add support for incremental atlas updates +struct ImFontBuilderIO +{ + bool (*FontBuilder_Build)(ImFontAtlas *atlas); +}; + +// Helper for font builder +#ifdef IMGUI_ENABLE_STB_TRUETYPE +IMGUI_API const ImFontBuilderIO *ImFontAtlasGetBuilderForStbTruetype(); +#endif +IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas *atlas); +IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas *atlas, ImFont *font, ImFontConfig *font_config, float ascent, float descent); +IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas *atlas, void *stbrp_context_opaque); +IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas *atlas); +IMGUI_API void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas *atlas, int x, int y, int w, int h, const char *in_str, char in_marker_char, unsigned char in_marker_pixel_value); +IMGUI_API void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas *atlas, int x, int y, int w, int h, const char *in_str, char in_marker_char, unsigned int in_marker_pixel_value); +IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor); +IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char *pixels, int x, int y, int w, int h, int stride); + +//----------------------------------------------------------------------------- +// [SECTION] Test Engine specific hooks (imgui_test_engine) +//----------------------------------------------------------------------------- + +#ifdef IMGUI_ENABLE_TEST_ENGINE +extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext *ctx, const ImRect &bb, ImGuiID id); +extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext *ctx, ImGuiID id, const char *label, ImGuiItemStatusFlags flags); +extern void ImGuiTestEngineHook_Log(ImGuiContext *ctx, const char *fmt, ...); +extern const char *ImGuiTestEngine_FindItemDebugLabel(ImGuiContext *ctx, ImGuiID id); + +#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) \ + if (g.TestEngineHookItems) \ + ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register item bounding box +#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) \ + if (g.TestEngineHookItems) \ + ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional) +#define IMGUI_TEST_ENGINE_LOG(_FMT, ...) \ + if (g.TestEngineHookItems) \ + ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log +#else +#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) ((void)0) +#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ((void)g) +#endif + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/src/editors/xrEUI/imgui_tables.cpp b/src/editors/xrEUI/imgui_tables.cpp new file mode 100644 index 00000000000..bf04f44b548 --- /dev/null +++ b/src/editors/xrEUI/imgui_tables.cpp @@ -0,0 +1,4068 @@ +// dear imgui, v1.88 WIP +// (tables and columns code) + +/* + +Index of this file: + +// [SECTION] Commentary +// [SECTION] Header mess +// [SECTION] Tables: Main code +// [SECTION] Tables: Simple accessors +// [SECTION] Tables: Row changes +// [SECTION] Tables: Columns changes +// [SECTION] Tables: Columns width management +// [SECTION] Tables: Drawing +// [SECTION] Tables: Sorting +// [SECTION] Tables: Headers +// [SECTION] Tables: Context Menu +// [SECTION] Tables: Settings (.ini data) +// [SECTION] Tables: Garbage Collection +// [SECTION] Tables: Debugging +// [SECTION] Columns, BeginColumns, EndColumns, etc. + +*/ + +// Navigating this file: +// - In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. +// - With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. + +//----------------------------------------------------------------------------- +// [SECTION] Commentary +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Typical tables call flow: (root level is generally public API): +//----------------------------------------------------------------------------- +// - BeginTable() user begin into a table +// | BeginChild() - (if ScrollX/ScrollY is set) +// | TableBeginInitMemory() - first time table is used +// | TableResetSettings() - on settings reset +// | TableLoadSettings() - on settings load +// | TableBeginApplyRequests() - apply queued resizing/reordering/hiding requests +// | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame) +// | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width +// - TableSetupColumn() user submit columns details (optional) +// - TableSetupScrollFreeze() user submit scroll freeze information (optional) +//----------------------------------------------------------------------------- +// - TableUpdateLayout() [Internal] followup to BeginTable(): setup everything: widths, columns positions, clipping rectangles. Automatically called by the FIRST call to TableNextRow() or TableHeadersRow(). +// | TableSetupDrawChannels() - setup ImDrawList channels +// | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission +// | TableDrawContextMenu() - draw right-click context menu +//----------------------------------------------------------------------------- +// - TableHeadersRow() or TableHeader() user submit a headers row (optional) +// | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction +// | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu +// - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers) +// - TableNextRow() user begin into a new row (also automatically called by TableHeadersRow()) +// | TableEndRow() - finish existing row +// | TableBeginRow() - add a new row +// - TableSetColumnIndex() / TableNextColumn() user begin into a cell +// | TableEndCell() - close existing column/cell +// | TableBeginCell() - enter into current column/cell +// - [...] user emit contents +//----------------------------------------------------------------------------- +// - EndTable() user ends the table +// | TableDrawBorders() - draw outer borders, inner vertical borders +// | TableMergeDrawChannels() - merge draw channels if clipping isn't required +// | EndChild() - (if ScrollX/ScrollY is set) +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// TABLE SIZING +//----------------------------------------------------------------------------- +// (Read carefully because this is subtle but it does make sense!) +//----------------------------------------------------------------------------- +// About 'outer_size': +// Its meaning needs to differ slightly depending on if we are using ScrollX/ScrollY flags. +// Default value is ImVec2(0.0f, 0.0f). +// X +// - outer_size.x <= 0.0f -> Right-align from window/work-rect right-most edge. With -FLT_MIN or 0.0f will align exactly on right-most edge. +// - outer_size.x > 0.0f -> Set Fixed width. +// Y with ScrollX/ScrollY disabled: we output table directly in current window +// - outer_size.y < 0.0f -> Bottom-align (but will auto extend, unless _NoHostExtendY is set). Not meaningful is parent window can vertically scroll. +// - outer_size.y = 0.0f -> No minimum height (but will auto extend, unless _NoHostExtendY is set) +// - outer_size.y > 0.0f -> Set Minimum height (but will auto extend, unless _NoHostExtenY is set) +// Y with ScrollX/ScrollY enabled: using a child window for scrolling +// - outer_size.y < 0.0f -> Bottom-align. Not meaningful is parent window can vertically scroll. +// - outer_size.y = 0.0f -> Bottom-align, consistent with BeginChild(). Not recommended unless table is last item in parent window. +// - outer_size.y > 0.0f -> Set Exact height. Recommended when using Scrolling on any axis. +//----------------------------------------------------------------------------- +// Outer size is also affected by the NoHostExtendX/NoHostExtendY flags. +// Important to that note how the two flags have slightly different behaviors! +// - ImGuiTableFlags_NoHostExtendX -> Make outer width auto-fit to columns (overriding outer_size.x value). Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. +// - ImGuiTableFlags_NoHostExtendY -> Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY is disabled. Data below the limit will be clipped and not visible. +// In theory ImGuiTableFlags_NoHostExtendY could be the default and any non-scrolling tables with outer_size.y != 0.0f would use exact height. +// This would be consistent but perhaps less useful and more confusing (as vertically clipped items are not easily noticeable) +//----------------------------------------------------------------------------- +// About 'inner_width': +// With ScrollX disabled: +// - inner_width -> *ignored* +// With ScrollX enabled: +// - inner_width < 0.0f -> *illegal* fit in known width (right align from outer_size.x) <-- weird +// - inner_width = 0.0f -> fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns. +// - inner_width > 0.0f -> override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space! +//----------------------------------------------------------------------------- +// Details: +// - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept +// of "available space" doesn't make sense. +// - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding +// of what the value does. +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// COLUMNS SIZING POLICIES +//----------------------------------------------------------------------------- +// About overriding column sizing policy and width/weight with TableSetupColumn(): +// We use a default parameter of 'init_width_or_weight == -1'. +// - with ImGuiTableColumnFlags_WidthFixed, init_width <= 0 (default) --> width is automatic +// - with ImGuiTableColumnFlags_WidthFixed, init_width > 0 (explicit) --> width is custom +// - with ImGuiTableColumnFlags_WidthStretch, init_weight <= 0 (default) --> weight is 1.0f +// - with ImGuiTableColumnFlags_WidthStretch, init_weight > 0 (explicit) --> weight is custom +// Widths are specified _without_ CellPadding. If you specify a width of 100.0f, the column will be cover (100.0f + Padding * 2.0f) +// and you can fit a 100.0f wide item in it without clipping and with full padding. +//----------------------------------------------------------------------------- +// About default sizing policy (if you don't specify a ImGuiTableColumnFlags_WidthXXXX flag) +// - with Table policy ImGuiTableFlags_SizingFixedFit --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is equal to contents width +// - with Table policy ImGuiTableFlags_SizingFixedSame --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is max of all contents width +// - with Table policy ImGuiTableFlags_SizingStretchSame --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is 1.0f +// - with Table policy ImGuiTableFlags_SizingStretchWeight --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is proportional to contents +// Default Width and default Weight can be overridden when calling TableSetupColumn(). +//----------------------------------------------------------------------------- +// About mixing Fixed/Auto and Stretch columns together: +// - the typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +// - using mixed policies with ScrollX does not make much sense, as using Stretch columns with ScrollX does not make much sense in the first place! +// that is, unless 'inner_width' is passed to BeginTable() to explicitly provide a total width to layout columns in. +// - when using ImGuiTableFlags_SizingFixedSame with mixed columns, only the Fixed/Auto columns will match their widths to the width of the maximum contents. +// - when using ImGuiTableFlags_SizingStretchSame with mixed columns, only the Stretch columns will match their weight/widths. +//----------------------------------------------------------------------------- +// About using column width: +// If a column is manual resizable or has a width specified with TableSetupColumn(): +// - you may use GetContentRegionAvail().x to query the width available in a given column. +// - right-side alignment features such as SetNextItemWidth(-x) or PushItemWidth(-x) will rely on this width. +// If the column is not resizable and has no width specified with TableSetupColumn(): +// - its width will be automatic and be set to the max of items submitted. +// - therefore you generally cannot have ALL items of the columns use e.g. SetNextItemWidth(-FLT_MIN). +// - but if the column has one or more items of known/fixed size, this will become the reference width used by SetNextItemWidth(-FLT_MIN). +//----------------------------------------------------------------------------- + + +//----------------------------------------------------------------------------- +// TABLES CLIPPING/CULLING +//----------------------------------------------------------------------------- +// About clipping/culling of Rows in Tables: +// - For large numbers of rows, it is recommended you use ImGuiListClipper to only submit visible rows. +// ImGuiListClipper is reliant on the fact that rows are of equal height. +// See 'Demo->Tables->Vertical Scrolling' or 'Demo->Tables->Advanced' for a demo of using the clipper. +// - Note that auto-resizing columns don't play well with using the clipper. +// By default a table with _ScrollX but without _Resizable will have column auto-resize. +// So, if you want to use the clipper, make sure to either enable _Resizable, either setup columns width explicitly with _WidthFixed. +//----------------------------------------------------------------------------- +// About clipping/culling of Columns in Tables: +// - Both TableSetColumnIndex() and TableNextColumn() return true when the column is visible or performing +// width measurements. Otherwise, you may skip submitting the contents of a cell/column, BUT ONLY if you know +// it is not going to contribute to row height. +// In many situations, you may skip submitting contents for every column but one (e.g. the first one). +// - Case A: column is not hidden by user, and at least partially in sight (most common case). +// - Case B: column is clipped / out of sight (because of scrolling or parent ClipRect): TableNextColumn() return false as a hint but we still allow layout output. +// - Case C: column is hidden explicitly by the user (e.g. via the context menu, or _DefaultHide column flag, etc.). +// +// [A] [B] [C] +// TableNextColumn(): true false false -> [userland] when TableNextColumn() / TableSetColumnIndex() return false, user can skip submitting items but only if the column doesn't contribute to row height. +// SkipItems: false false true -> [internal] when SkipItems is true, most widgets will early out if submitted, resulting is no layout output. +// ClipRect: normal zero-width zero-width -> [internal] when ClipRect is zero, ItemAdd() will return false and most widgets will early out mid-way. +// ImDrawList output: normal dummy dummy -> [internal] when using the dummy channel, ImDrawList submissions (if any) will be wasted (because cliprect is zero-width anyway). +// +// - We need to distinguish those cases because non-hidden columns that are clipped outside of scrolling bounds should still contribute their height to the row. +// However, in the majority of cases, the contribution to row height is the same for all columns, or the tallest cells are known by the programmer. +//----------------------------------------------------------------------------- +// About clipping/culling of whole Tables: +// - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false. +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// [SECTION] Header mess +//----------------------------------------------------------------------------- + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif +#include "imgui_internal.h" + +// System includes +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later +#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types +#endif +#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). +#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') +#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif + +//----------------------------------------------------------------------------- +// [SECTION] Tables: Main code +//----------------------------------------------------------------------------- +// - TableFixFlags() [Internal] +// - TableFindByID() [Internal] +// - BeginTable() +// - BeginTableEx() [Internal] +// - TableBeginInitMemory() [Internal] +// - TableBeginApplyRequests() [Internal] +// - TableSetupColumnFlags() [Internal] +// - TableUpdateLayout() [Internal] +// - TableUpdateBorders() [Internal] +// - EndTable() +// - TableSetupColumn() +// - TableSetupScrollFreeze() +//----------------------------------------------------------------------------- + +// Configuration +static const int TABLE_DRAW_CHANNEL_BG0 = 0; +static const int TABLE_DRAW_CHANNEL_BG2_FROZEN = 1; +static const int TABLE_DRAW_CHANNEL_NOCLIP = 2; // When using ImGuiTableFlags_NoClip (this becomes the last visible channel) +static const float TABLE_BORDER_SIZE = 1.0f; // FIXME-TABLE: Currently hard-coded because of clipping assumptions with outer borders rendering. +static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders. +static const float TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06f; // Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped. + +// Helper +inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags, ImGuiWindow* outer_window) +{ + // Adjust flags: set default sizing policy + if ((flags & ImGuiTableFlags_SizingMask_) == 0) + flags |= ((flags & ImGuiTableFlags_ScrollX) || (outer_window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) ? ImGuiTableFlags_SizingFixedFit : ImGuiTableFlags_SizingStretchSame; + + // Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags_SizingFixedSame + if ((flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame) + flags |= ImGuiTableFlags_NoKeepColumnsVisible; + + // Adjust flags: enforce borders when resizable + if (flags & ImGuiTableFlags_Resizable) + flags |= ImGuiTableFlags_BordersInnerV; + + // Adjust flags: disable NoHostExtendX/NoHostExtendY if we have any scrolling going on + if (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) + flags &= ~(ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_NoHostExtendY); + + // Adjust flags: NoBordersInBodyUntilResize takes priority over NoBordersInBody + if (flags & ImGuiTableFlags_NoBordersInBodyUntilResize) + flags &= ~ImGuiTableFlags_NoBordersInBody; + + // Adjust flags: disable saved settings if there's nothing to save + if ((flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Sortable)) == 0) + flags |= ImGuiTableFlags_NoSavedSettings; + + // Inherit _NoSavedSettings from top-level window (child windows always have _NoSavedSettings set) + if (outer_window->RootWindow->Flags & ImGuiWindowFlags_NoSavedSettings) + flags |= ImGuiTableFlags_NoSavedSettings; + + return flags; +} + +ImGuiTable* ImGui::TableFindByID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return g.Tables.GetByKey(id); +} + +// Read about "TABLE SIZING" at the top of this file. +bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) +{ + ImGuiID id = GetID(str_id); + return BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width); +} + +bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* outer_window = GetCurrentWindow(); + if (outer_window->SkipItems) // Consistent with other tables + beneficial side effect that assert on miscalling EndTable() will be more visible. + return false; + + // Sanity checks + IM_ASSERT(columns_count > 0 && columns_count <= IMGUI_TABLE_MAX_COLUMNS && "Only 1..64 columns allowed!"); + if (flags & ImGuiTableFlags_ScrollX) + IM_ASSERT(inner_width >= 0.0f); + + // If an outer size is specified ahead we will be able to early out when not visible. Exact clipping rules may evolve. + const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0; + const ImVec2 avail_size = GetContentRegionAvail(); + ImVec2 actual_outer_size = CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f); + ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size); + if (use_child_window && IsClippedEx(outer_rect, 0)) + { + ItemSize(outer_rect); + return false; + } + + // Acquire storage for the table + ImGuiTable* table = g.Tables.GetOrAddByKey(id); + const int instance_no = (table->LastFrameActive != g.FrameCount) ? 0 : table->InstanceCurrent + 1; + const ImGuiID instance_id = id + instance_no; + const ImGuiTableFlags table_last_flags = table->Flags; + if (instance_no > 0) + IM_ASSERT(table->ColumnsCount == columns_count && "BeginTable(): Cannot change columns count mid-frame while preserving same ID"); + + // Acquire temporary buffers + const int table_idx = g.Tables.GetIndex(table); + if (++g.TablesTempDataStacked > g.TablesTempData.Size) + g.TablesTempData.resize(g.TablesTempDataStacked, ImGuiTableTempData()); + ImGuiTableTempData* temp_data = table->TempData = &g.TablesTempData[g.TablesTempDataStacked - 1]; + temp_data->TableIndex = table_idx; + table->DrawSplitter = &table->TempData->DrawSplitter; + table->DrawSplitter->Clear(); + + // Fix flags + table->IsDefaultSizingPolicy = (flags & ImGuiTableFlags_SizingMask_) == 0; + flags = TableFixFlags(flags, outer_window); + + // Initialize + table->ID = id; + table->Flags = flags; + table->InstanceCurrent = (ImS16)instance_no; + table->LastFrameActive = g.FrameCount; + table->OuterWindow = table->InnerWindow = outer_window; + table->ColumnsCount = columns_count; + table->IsLayoutLocked = false; + table->InnerWidth = inner_width; + temp_data->UserOuterSize = outer_size; + if (instance_no > 0 && table->InstanceDataExtra.Size < instance_no) + table->InstanceDataExtra.push_back(ImGuiTableInstanceData()); + + // When not using a child window, WorkRect.Max will grow as we append contents. + if (use_child_window) + { + // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent + // (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing) + ImVec2 override_content_size(FLT_MAX, FLT_MAX); + if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY)) + override_content_size.y = FLT_MIN; + + // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and + // never lead to any scrolling). We don't handle inner_width < 0.0f, we could potentially use it to right-align + // based on the right side of the child window work rect, which would require knowing ahead if we are going to + // have decoration taking horizontal spaces (typically a vertical scrollbar). + if ((flags & ImGuiTableFlags_ScrollX) && inner_width > 0.0f) + override_content_size.x = inner_width; + + if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX) + SetNextWindowContentSize(ImVec2(override_content_size.x != FLT_MAX ? override_content_size.x : 0.0f, override_content_size.y != FLT_MAX ? override_content_size.y : 0.0f)); + + // Reset scroll if we are reactivating it + if ((table_last_flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) == 0) + SetNextWindowScroll(ImVec2(0.0f, 0.0f)); + + // Create scrolling region (without border and zero window padding) + ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None; + BeginChildEx(name, instance_id, outer_rect.GetSize(), false, child_flags); + table->InnerWindow = g.CurrentWindow; + table->WorkRect = table->InnerWindow->WorkRect; + table->OuterRect = table->InnerWindow->Rect(); + table->InnerRect = table->InnerWindow->InnerRect; + IM_ASSERT(table->InnerWindow->WindowPadding.x == 0.0f && table->InnerWindow->WindowPadding.y == 0.0f && table->InnerWindow->WindowBorderSize == 0.0f); + } + else + { + // For non-scrolling tables, WorkRect == OuterRect == InnerRect. + // But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable(). + table->WorkRect = table->OuterRect = table->InnerRect = outer_rect; + } + + // Push a standardized ID for both child-using and not-child-using tables + PushOverrideID(instance_id); + + // Backup a copy of host window members we will modify + ImGuiWindow* inner_window = table->InnerWindow; + table->HostIndentX = inner_window->DC.Indent.x; + table->HostClipRect = inner_window->ClipRect; + table->HostSkipItems = inner_window->SkipItems; + temp_data->HostBackupWorkRect = inner_window->WorkRect; + temp_data->HostBackupParentWorkRect = inner_window->ParentWorkRect; + temp_data->HostBackupColumnsOffset = outer_window->DC.ColumnsOffset; + temp_data->HostBackupPrevLineSize = inner_window->DC.PrevLineSize; + temp_data->HostBackupCurrLineSize = inner_window->DC.CurrLineSize; + temp_data->HostBackupCursorMaxPos = inner_window->DC.CursorMaxPos; + temp_data->HostBackupItemWidth = outer_window->DC.ItemWidth; + temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size; + inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + + // Padding and Spacing + // - None ........Content..... Pad .....Content........ + // - PadOuter | Pad ..Content..... Pad .....Content.. Pad | + // - PadInner ........Content.. Pad | Pad ..Content........ + // - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad | + const bool pad_outer_x = (flags & ImGuiTableFlags_NoPadOuterX) ? false : (flags & ImGuiTableFlags_PadOuterX) ? true : (flags & ImGuiTableFlags_BordersOuterV) != 0; + const bool pad_inner_x = (flags & ImGuiTableFlags_NoPadInnerX) ? false : true; + const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? TABLE_BORDER_SIZE : 0.0f; + const float inner_spacing_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) == 0) ? g.Style.CellPadding.x : 0.0f; + const float inner_padding_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) != 0) ? g.Style.CellPadding.x : 0.0f; + table->CellSpacingX1 = inner_spacing_explicit + inner_spacing_for_border; + table->CellSpacingX2 = inner_spacing_explicit; + table->CellPaddingX = inner_padding_explicit; + table->CellPaddingY = g.Style.CellPadding.y; + + const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; + const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f; + table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX; + + table->CurrentColumn = -1; + table->CurrentRow = -1; + table->RowBgColorCounter = 0; + table->LastRowFlags = ImGuiTableRowFlags_None; + table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; + table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width + table->InnerClipRect.ClipWithFull(table->HostClipRect); + table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : inner_window->ClipRect.Max.y; + + table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow + table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow() + table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any + table->FreezeColumnsRequest = table->FreezeColumnsCount = 0; + table->IsUnfrozenRows = true; + table->DeclColumnsCount = 0; + + // Using opaque colors facilitate overlapping elements of the grid + table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong); + table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight); + + // Make table current + g.CurrentTable = table; + outer_window->DC.CurrentTableIdx = table_idx; + if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly. + inner_window->DC.CurrentTableIdx = table_idx; + + if ((table_last_flags & ImGuiTableFlags_Reorderable) && (flags & ImGuiTableFlags_Reorderable) == 0) + table->IsResetDisplayOrderRequest = true; + + // Mark as used + if (table_idx >= g.TablesLastTimeActive.Size) + g.TablesLastTimeActive.resize(table_idx + 1, -1.0f); + g.TablesLastTimeActive[table_idx] = (float)g.Time; + temp_data->LastTimeActive = (float)g.Time; + table->MemoryCompacted = false; + + // Setup memory buffer (clear data if columns count changed) + ImGuiTableColumn* old_columns_to_preserve = NULL; + void* old_columns_raw_data = NULL; + const int old_columns_count = table->Columns.size(); + if (old_columns_count != 0 && old_columns_count != columns_count) + { + // Attempt to preserve width on column count change (#4046) + old_columns_to_preserve = table->Columns.Data; + old_columns_raw_data = table->RawData; + table->RawData = NULL; + } + if (table->RawData == NULL) + { + TableBeginInitMemory(table, columns_count); + table->IsInitializing = table->IsSettingsRequestLoad = true; + } + if (table->IsResetAllRequest) + TableResetSettings(table); + if (table->IsInitializing) + { + // Initialize + table->SettingsOffset = -1; + table->IsSortSpecsDirty = true; + table->InstanceInteracted = -1; + table->ContextPopupColumn = -1; + table->ReorderColumn = table->ResizedColumn = table->LastResizedColumn = -1; + table->AutoFitSingleColumn = -1; + table->HoveredColumnBody = table->HoveredColumnBorder = -1; + for (int n = 0; n < columns_count; n++) + { + ImGuiTableColumn* column = &table->Columns[n]; + if (old_columns_to_preserve && n < old_columns_count) + { + // FIXME: We don't attempt to preserve column order in this path. + *column = old_columns_to_preserve[n]; + } + else + { + float width_auto = column->WidthAuto; + *column = ImGuiTableColumn(); + column->WidthAuto = width_auto; + column->IsPreserveWidthAuto = true; // Preserve WidthAuto when reinitializing a live table: not technically necessary but remove a visible flicker + column->IsEnabled = column->IsUserEnabled = column->IsUserEnabledNextFrame = true; + } + column->DisplayOrder = table->DisplayOrderToIndex[n] = (ImGuiTableColumnIdx)n; + } + } + if (old_columns_raw_data) + IM_FREE(old_columns_raw_data); + + // Load settings + if (table->IsSettingsRequestLoad) + TableLoadSettings(table); + + // Handle DPI/font resize + // This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well. + // It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition. + // FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory. + // This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path. + const float new_ref_scale_unit = g.FontSize; // g.Font->GetCharAdvance('A') ? + if (table->RefScale != 0.0f && table->RefScale != new_ref_scale_unit) + { + const float scale_factor = new_ref_scale_unit / table->RefScale; + //IMGUI_DEBUG_LOG("[table] %08X RefScaleUnit %.3f -> %.3f, scaling width by %.3f\n", table->ID, table->RefScaleUnit, new_ref_scale_unit, scale_factor); + for (int n = 0; n < columns_count; n++) + table->Columns[n].WidthRequest = table->Columns[n].WidthRequest * scale_factor; + } + table->RefScale = new_ref_scale_unit; + + // Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call.. + // This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user. + // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. + inner_window->SkipItems = true; + + // Clear names + // At this point the ->NameOffset field of each column will be invalid until TableUpdateLayout() or the first call to TableSetupColumn() + if (table->ColumnsNames.Buf.Size > 0) + table->ColumnsNames.Buf.resize(0); + + // Apply queued resizing/reordering/hiding requests + TableBeginApplyRequests(table); + + return true; +} + +// For reference, the average total _allocation count_ for a table is: +// + 0 (for ImGuiTable instance, we are pooling allocations in g.Tables) +// + 1 (for table->RawData allocated below) +// + 1 (for table->ColumnsNames, if names are used) +// Shared allocations per number of nested tables +// + 1 (for table->Splitter._Channels) +// + 2 * active_channels_count (for ImDrawCmd and ImDrawIdx buffers inside channels) +// Where active_channels_count is variable but often == columns_count or columns_count + 1, see TableSetupDrawChannels() for details. +// Unused channels don't perform their +2 allocations. +void ImGui::TableBeginInitMemory(ImGuiTable* table, int columns_count) +{ + // Allocate single buffer for our arrays + ImSpanAllocator<3> span_allocator; + span_allocator.Reserve(0, columns_count * sizeof(ImGuiTableColumn)); + span_allocator.Reserve(1, columns_count * sizeof(ImGuiTableColumnIdx)); + span_allocator.Reserve(2, columns_count * sizeof(ImGuiTableCellData), 4); + table->RawData = IM_ALLOC(span_allocator.GetArenaSizeInBytes()); + memset(table->RawData, 0, span_allocator.GetArenaSizeInBytes()); + span_allocator.SetArenaBasePtr(table->RawData); + span_allocator.GetSpan(0, &table->Columns); + span_allocator.GetSpan(1, &table->DisplayOrderToIndex); + span_allocator.GetSpan(2, &table->RowCellData); +} + +// Apply queued resizing/reordering/hiding requests +void ImGui::TableBeginApplyRequests(ImGuiTable* table) +{ + // Handle resizing request + // (We process this at the first TableBegin of the frame) + // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling? + if (table->InstanceCurrent == 0) + { + if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX) + TableSetColumnWidth(table->ResizedColumn, table->ResizedColumnNextWidth); + table->LastResizedColumn = table->ResizedColumn; + table->ResizedColumnNextWidth = FLT_MAX; + table->ResizedColumn = -1; + + // Process auto-fit for single column, which is a special case for stretch columns and fixed columns with FixedSame policy. + // FIXME-TABLE: Would be nice to redistribute available stretch space accordingly to other weights, instead of giving it all to siblings. + if (table->AutoFitSingleColumn != -1) + { + TableSetColumnWidth(table->AutoFitSingleColumn, table->Columns[table->AutoFitSingleColumn].WidthAuto); + table->AutoFitSingleColumn = -1; + } + } + + // Handle reordering request + // Note: we don't clear ReorderColumn after handling the request. + if (table->InstanceCurrent == 0) + { + if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1) + table->ReorderColumn = -1; + table->HeldHeaderColumn = -1; + if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0) + { + // We need to handle reordering across hidden columns. + // In the configuration below, moving C to the right of E will lead to: + // ... C [D] E ---> ... [D] E C (Column name/index) + // ... 2 3 4 ... 2 3 4 (Display order) + const int reorder_dir = table->ReorderColumnDir; + IM_ASSERT(reorder_dir == -1 || reorder_dir == +1); + IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable); + ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn]; + ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevEnabledColumn : src_column->NextEnabledColumn]; + IM_UNUSED(dst_column); + const int src_order = src_column->DisplayOrder; + const int dst_order = dst_column->DisplayOrder; + src_column->DisplayOrder = (ImGuiTableColumnIdx)dst_order; + for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir) + table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImGuiTableColumnIdx)reorder_dir; + IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir); + + // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[], + // rebuild the later from the former. + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n; + table->ReorderColumnDir = 0; + table->IsSettingsDirty = true; + } + } + + // Handle display order reset request + if (table->IsResetDisplayOrderRequest) + { + for (int n = 0; n < table->ColumnsCount; n++) + table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n; + table->IsResetDisplayOrderRequest = false; + table->IsSettingsDirty = true; + } +} + +// Adjust flags: default width mode + stretch columns are not allowed when auto extending +static void TableSetupColumnFlags(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags flags_in) +{ + ImGuiTableColumnFlags flags = flags_in; + + // Sizing Policy + if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0) + { + const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_); + if (table_sizing_policy == ImGuiTableFlags_SizingFixedFit || table_sizing_policy == ImGuiTableFlags_SizingFixedSame) + flags |= ImGuiTableColumnFlags_WidthFixed; + else + flags |= ImGuiTableColumnFlags_WidthStretch; + } + else + { + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_WidthMask_)); // Check that only 1 of each set is used. + } + + // Resize + if ((table->Flags & ImGuiTableFlags_Resizable) == 0) + flags |= ImGuiTableColumnFlags_NoResize; + + // Sorting + if ((flags & ImGuiTableColumnFlags_NoSortAscending) && (flags & ImGuiTableColumnFlags_NoSortDescending)) + flags |= ImGuiTableColumnFlags_NoSort; + + // Indentation + if ((flags & ImGuiTableColumnFlags_IndentMask_) == 0) + flags |= (table->Columns.index_from_ptr(column) == 0) ? ImGuiTableColumnFlags_IndentEnable : ImGuiTableColumnFlags_IndentDisable; + + // Alignment + //if ((flags & ImGuiTableColumnFlags_AlignMask_) == 0) + // flags |= ImGuiTableColumnFlags_AlignCenter; + //IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_AlignMask_)); // Check that only 1 of each set is used. + + // Preserve status flags + column->Flags = flags | (column->Flags & ImGuiTableColumnFlags_StatusMask_); + + // Build an ordered list of available sort directions + column->SortDirectionsAvailCount = column->SortDirectionsAvailMask = column->SortDirectionsAvailList = 0; + if (table->Flags & ImGuiTableFlags_Sortable) + { + int count = 0, mask = 0, list = 0; + if ((flags & ImGuiTableColumnFlags_PreferSortAscending) != 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; } + if ((flags & ImGuiTableColumnFlags_PreferSortDescending) != 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; } + if ((flags & ImGuiTableColumnFlags_PreferSortAscending) == 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; } + if ((flags & ImGuiTableColumnFlags_PreferSortDescending) == 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; } + if ((table->Flags & ImGuiTableFlags_SortTristate) || count == 0) { mask |= 1 << ImGuiSortDirection_None; count++; } + column->SortDirectionsAvailList = (ImU8)list; + column->SortDirectionsAvailMask = (ImU8)mask; + column->SortDirectionsAvailCount = (ImU8)count; + ImGui::TableFixColumnSortDirection(table, column); + } +} + +// Layout columns for the frame. This is in essence the followup to BeginTable(). +// Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() to be called first. +// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns. +// Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns? +void ImGui::TableUpdateLayout(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(table->IsLayoutLocked == false); + + const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_); + table->IsDefaultDisplayOrder = true; + table->ColumnsEnabledCount = 0; + table->EnabledMaskByIndex = 0x00; + table->EnabledMaskByDisplayOrder = 0x00; + table->LeftMostEnabledColumn = -1; + table->MinColumnWidth = ImMax(1.0f, g.Style.FramePadding.x * 1.0f); // g.Style.ColumnsMinSpacing; // FIXME-TABLE + + // [Part 1] Apply/lock Enabled and Order states. Calculate auto/ideal width for columns. Count fixed/stretch columns. + // Process columns in their visible orders as we are building the Prev/Next indices. + int count_fixed = 0; // Number of columns that have fixed sizing policies + int count_stretch = 0; // Number of columns that have stretch sizing policies + int prev_visible_column_idx = -1; + bool has_auto_fit_request = false; + bool has_resizable = false; + float stretch_sum_width_auto = 0.0f; + float fixed_max_width_auto = 0.0f; + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + const int column_n = table->DisplayOrderToIndex[order_n]; + if (column_n != order_n) + table->IsDefaultDisplayOrder = false; + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Clear column setup if not submitted by user. Currently we make it mandatory to call TableSetupColumn() every frame. + // It would easily work without but we're not ready to guarantee it since e.g. names need resubmission anyway. + // We take a slight shortcut but in theory we could be calling TableSetupColumn() here with dummy values, it should yield the same effect. + if (table->DeclColumnsCount <= column_n) + { + TableSetupColumnFlags(table, column, ImGuiTableColumnFlags_None); + column->NameOffset = -1; + column->UserID = 0; + column->InitStretchWeightOrWidth = -1.0f; + } + + // Update Enabled state, mark settings and sort specs dirty + if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide)) + column->IsUserEnabledNextFrame = true; + if (column->IsUserEnabled != column->IsUserEnabledNextFrame) + { + column->IsUserEnabled = column->IsUserEnabledNextFrame; + table->IsSettingsDirty = true; + } + column->IsEnabled = column->IsUserEnabled && (column->Flags & ImGuiTableColumnFlags_Disabled) == 0; + + if (column->SortOrder != -1 && !column->IsEnabled) + table->IsSortSpecsDirty = true; + if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_SortMulti)) + table->IsSortSpecsDirty = true; + + // Auto-fit unsized columns + const bool start_auto_fit = (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? (column->WidthRequest < 0.0f) : (column->StretchWeight < 0.0f); + if (start_auto_fit) + column->AutoFitQueue = column->CannotSkipItemsQueue = (1 << 3) - 1; // Fit for three frames + + if (!column->IsEnabled) + { + column->IndexWithinEnabledSet = -1; + continue; + } + + // Mark as enabled and link to previous/next enabled column + column->PrevEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx; + column->NextEnabledColumn = -1; + if (prev_visible_column_idx != -1) + table->Columns[prev_visible_column_idx].NextEnabledColumn = (ImGuiTableColumnIdx)column_n; + else + table->LeftMostEnabledColumn = (ImGuiTableColumnIdx)column_n; + column->IndexWithinEnabledSet = table->ColumnsEnabledCount++; + table->EnabledMaskByIndex |= (ImU64)1 << column_n; + table->EnabledMaskByDisplayOrder |= (ImU64)1 << column->DisplayOrder; + prev_visible_column_idx = column_n; + IM_ASSERT(column->IndexWithinEnabledSet <= column->DisplayOrder); + + // Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping) + // Combine width from regular rows + width from headers unless requested not to. + if (!column->IsPreserveWidthAuto) + column->WidthAuto = TableGetColumnWidthAuto(table, column); + + // Non-resizable columns keep their requested width (apply user value regardless of IsPreserveWidthAuto) + const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0; + if (column_is_resizable) + has_resizable = true; + if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f && !column_is_resizable) + column->WidthAuto = column->InitStretchWeightOrWidth; + + if (column->AutoFitQueue != 0x00) + has_auto_fit_request = true; + if (column->Flags & ImGuiTableColumnFlags_WidthStretch) + { + stretch_sum_width_auto += column->WidthAuto; + count_stretch++; + } + else + { + fixed_max_width_auto = ImMax(fixed_max_width_auto, column->WidthAuto); + count_fixed++; + } + } + if ((table->Flags & ImGuiTableFlags_Sortable) && table->SortSpecsCount == 0 && !(table->Flags & ImGuiTableFlags_SortTristate)) + table->IsSortSpecsDirty = true; + table->RightMostEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx; + IM_ASSERT(table->LeftMostEnabledColumn >= 0 && table->RightMostEnabledColumn >= 0); + + // [Part 2] Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible + // to avoid the column fitting having to wait until the first visible frame of the child container (may or not be a good thing). + // FIXME-TABLE: for always auto-resizing columns may not want to do that all the time. + if (has_auto_fit_request && table->OuterWindow != table->InnerWindow) + table->InnerWindow->SkipItems = false; + if (has_auto_fit_request) + table->IsSettingsDirty = true; + + // [Part 3] Fix column flags and record a few extra information. + float sum_width_requests = 0.0f; // Sum of all width for fixed and auto-resize columns, excluding width contributed by Stretch columns but including spacing/padding. + float stretch_sum_weights = 0.0f; // Sum of all weights for stretch columns. + table->LeftMostStretchedColumn = table->RightMostStretchedColumn = -1; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + if (!(table->EnabledMaskByIndex & ((ImU64)1 << column_n))) + continue; + ImGuiTableColumn* column = &table->Columns[column_n]; + + const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0; + if (column->Flags & ImGuiTableColumnFlags_WidthFixed) + { + // Apply same widths policy + float width_auto = column->WidthAuto; + if (table_sizing_policy == ImGuiTableFlags_SizingFixedSame && (column->AutoFitQueue != 0x00 || !column_is_resizable)) + width_auto = fixed_max_width_auto; + + // Apply automatic width + // Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!) + if (column->AutoFitQueue != 0x00) + column->WidthRequest = width_auto; + else if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !column_is_resizable && (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n))) + column->WidthRequest = width_auto; + + // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets + // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very + // large height (= first frame scrollbar display very off + clipper would skip lots of items). + // This is merely making the side-effect less extreme, but doesn't properly fixes it. + // FIXME: Move this to ->WidthGiven to avoid temporary lossyless? + // FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller. + if (column->AutoFitQueue > 0x01 && table->IsInitializing && !column->IsPreserveWidthAuto) + column->WidthRequest = ImMax(column->WidthRequest, table->MinColumnWidth * 4.0f); // FIXME-TABLE: Another constant/scale? + sum_width_requests += column->WidthRequest; + } + else + { + // Initialize stretch weight + if (column->AutoFitQueue != 0x00 || column->StretchWeight < 0.0f || !column_is_resizable) + { + if (column->InitStretchWeightOrWidth > 0.0f) + column->StretchWeight = column->InitStretchWeightOrWidth; + else if (table_sizing_policy == ImGuiTableFlags_SizingStretchProp) + column->StretchWeight = (column->WidthAuto / stretch_sum_width_auto) * count_stretch; + else + column->StretchWeight = 1.0f; + } + + stretch_sum_weights += column->StretchWeight; + if (table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder > column->DisplayOrder) + table->LeftMostStretchedColumn = (ImGuiTableColumnIdx)column_n; + if (table->RightMostStretchedColumn == -1 || table->Columns[table->RightMostStretchedColumn].DisplayOrder < column->DisplayOrder) + table->RightMostStretchedColumn = (ImGuiTableColumnIdx)column_n; + } + column->IsPreserveWidthAuto = false; + sum_width_requests += table->CellPaddingX * 2.0f; + } + table->ColumnsEnabledFixedCount = (ImGuiTableColumnIdx)count_fixed; + table->ColumnsStretchSumWeights = stretch_sum_weights; + + // [Part 4] Apply final widths based on requested widths + const ImRect work_rect = table->WorkRect; + const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1); + const float width_avail = ((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) ? table->InnerClipRect.GetWidth() : work_rect.GetWidth(); + const float width_avail_for_stretched_columns = width_avail - width_spacings - sum_width_requests; + float width_remaining_for_stretched_columns = width_avail_for_stretched_columns; + table->ColumnsGivenWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + if (!(table->EnabledMaskByIndex & ((ImU64)1 << column_n))) + continue; + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Allocate width for stretched/weighted columns (StretchWeight gets converted into WidthRequest) + if (column->Flags & ImGuiTableColumnFlags_WidthStretch) + { + float weight_ratio = column->StretchWeight / stretch_sum_weights; + column->WidthRequest = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, table->MinColumnWidth) + 0.01f); + width_remaining_for_stretched_columns -= column->WidthRequest; + } + + // [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column + // See additional comments in TableSetColumnWidth(). + if (column->NextEnabledColumn == -1 && table->LeftMostStretchedColumn != -1) + column->Flags |= ImGuiTableColumnFlags_NoDirectResize_; + + // Assign final width, record width in case we will need to shrink + column->WidthGiven = ImFloor(ImMax(column->WidthRequest, table->MinColumnWidth)); + table->ColumnsGivenWidth += column->WidthGiven; + } + + // [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0f * number of Stretch column). + // Using right-to-left distribution (more likely to match resizing cursor). + if (width_remaining_for_stretched_columns >= 1.0f && !(table->Flags & ImGuiTableFlags_PreciseWidths)) + for (int order_n = table->ColumnsCount - 1; stretch_sum_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--) + { + if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n))) + continue; + ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]]; + if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + continue; + column->WidthRequest += 1.0f; + column->WidthGiven += 1.0f; + width_remaining_for_stretched_columns -= 1.0f; + } + + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + table->HoveredColumnBody = -1; + table->HoveredColumnBorder = -1; + const ImRect mouse_hit_rect(table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.Max.x, ImMax(table->OuterRect.Max.y, table->OuterRect.Min.y + table_instance->LastOuterHeight)); + const bool is_hovering_table = ItemHoverable(mouse_hit_rect, 0); + + // [Part 6] Setup final position, offset, skip/clip states and clipping rectangles, detect hovered column + // Process columns in their visible orders as we are comparing the visible order and adjusting host_clip_rect while looping. + int visible_n = 0; + bool offset_x_frozen = (table->FreezeColumnsCount > 0); + float offset_x = ((table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x) + table->OuterPaddingX - table->CellSpacingX1; + ImRect host_clip_rect = table->InnerClipRect; + //host_clip_rect.Max.x += table->CellPaddingX + table->CellSpacingX2; + table->VisibleMaskByIndex = 0x00; + table->RequestOutputMaskByIndex = 0x00; + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + const int column_n = table->DisplayOrderToIndex[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + + column->NavLayerCurrent = (ImS8)((table->FreezeRowsCount > 0 || column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main); + + if (offset_x_frozen && table->FreezeColumnsCount == visible_n) + { + offset_x += work_rect.Min.x - table->OuterRect.Min.x; + offset_x_frozen = false; + } + + // Clear status flags + column->Flags &= ~ImGuiTableColumnFlags_StatusMask_; + + if ((table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)) == 0) + { + // Hidden column: clear a few fields and we are done with it for the remainder of the function. + // We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper. + column->MinX = column->MaxX = column->WorkMinX = column->ClipRect.Min.x = column->ClipRect.Max.x = offset_x; + column->WidthGiven = 0.0f; + column->ClipRect.Min.y = work_rect.Min.y; + column->ClipRect.Max.y = FLT_MAX; + column->ClipRect.ClipWithFull(host_clip_rect); + column->IsVisibleX = column->IsVisibleY = column->IsRequestOutput = false; + column->IsSkipItems = true; + column->ItemWidth = 1.0f; + continue; + } + + // Detect hovered column + if (is_hovering_table && g.IO.MousePos.x >= column->ClipRect.Min.x && g.IO.MousePos.x < column->ClipRect.Max.x) + table->HoveredColumnBody = (ImGuiTableColumnIdx)column_n; + + // Lock start position + column->MinX = offset_x; + + // Lock width based on start position and minimum/maximum width for this position + float max_width = TableGetMaxColumnWidth(table, column_n); + column->WidthGiven = ImMin(column->WidthGiven, max_width); + column->WidthGiven = ImMax(column->WidthGiven, ImMin(column->WidthRequest, table->MinColumnWidth)); + column->MaxX = offset_x + column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f; + + // Lock other positions + // - ClipRect.Min.x: Because merging draw commands doesn't compare min boundaries, we make ClipRect.Min.x match left bounds to be consistent regardless of merging. + // - ClipRect.Max.x: using WorkMaxX instead of MaxX (aka including padding) makes things more consistent when resizing down, tho slightly detrimental to visibility in very-small column. + // - ClipRect.Max.x: using MaxX makes it easier for header to receive hover highlight with no discontinuity and display sorting arrow. + // - FIXME-TABLE: We want equal width columns to have equal (ClipRect.Max.x - WorkMinX) width, which means ClipRect.max.x cannot stray off host_clip_rect.Max.x else right-most column may appear shorter. + column->WorkMinX = column->MinX + table->CellPaddingX + table->CellSpacingX1; + column->WorkMaxX = column->MaxX - table->CellPaddingX - table->CellSpacingX2; // Expected max + column->ItemWidth = ImFloor(column->WidthGiven * 0.65f); + column->ClipRect.Min.x = column->MinX; + column->ClipRect.Min.y = work_rect.Min.y; + column->ClipRect.Max.x = column->MaxX; //column->WorkMaxX; + column->ClipRect.Max.y = FLT_MAX; + column->ClipRect.ClipWithFull(host_clip_rect); + + // Mark column as Clipped (not in sight) + // Note that scrolling tables (where inner_window != outer_window) handle Y clipped earlier in BeginTable() so IsVisibleY really only applies to non-scrolling tables. + // FIXME-TABLE: Because InnerClipRect.Max.y is conservatively ==outer_window->ClipRect.Max.y, we never can mark columns _Above_ the scroll line as not IsVisibleY. + // Taking advantage of LastOuterHeight would yield good results there... + // FIXME-TABLE: Y clipping is disabled because it effectively means not submitting will reduce contents width which is fed to outer_window->DC.CursorMaxPos.x, + // and this may be used (e.g. typically by outer_window using AlwaysAutoResize or outer_window's horizontal scrollbar, but could be something else). + // Possible solution to preserve last known content width for clipped column. Test 'table_reported_size' fails when enabling Y clipping and window is resized small. + column->IsVisibleX = (column->ClipRect.Max.x > column->ClipRect.Min.x); + column->IsVisibleY = true; // (column->ClipRect.Max.y > column->ClipRect.Min.y); + const bool is_visible = column->IsVisibleX; //&& column->IsVisibleY; + if (is_visible) + table->VisibleMaskByIndex |= ((ImU64)1 << column_n); + + // Mark column as requesting output from user. Note that fixed + non-resizable sets are auto-fitting at all times and therefore always request output. + column->IsRequestOutput = is_visible || column->AutoFitQueue != 0 || column->CannotSkipItemsQueue != 0; + if (column->IsRequestOutput) + table->RequestOutputMaskByIndex |= ((ImU64)1 << column_n); + + // Mark column as SkipItems (ignoring all items/layout) + column->IsSkipItems = !column->IsEnabled || table->HostSkipItems; + if (column->IsSkipItems) + IM_ASSERT(!is_visible); + + // Update status flags + column->Flags |= ImGuiTableColumnFlags_IsEnabled; + if (is_visible) + column->Flags |= ImGuiTableColumnFlags_IsVisible; + if (column->SortOrder != -1) + column->Flags |= ImGuiTableColumnFlags_IsSorted; + if (table->HoveredColumnBody == column_n) + column->Flags |= ImGuiTableColumnFlags_IsHovered; + + // Alignment + // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in + // many cases (to be able to honor this we might be able to store a log of cells width, per row, for + // visible rows, but nav/programmatic scroll would have visible artifacts.) + //if (column->Flags & ImGuiTableColumnFlags_AlignRight) + // column->WorkMinX = ImMax(column->WorkMinX, column->MaxX - column->ContentWidthRowsUnfrozen); + //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter) + // column->WorkMinX = ImLerp(column->WorkMinX, ImMax(column->StartX, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f); + + // Reset content width variables + column->ContentMaxXFrozen = column->ContentMaxXUnfrozen = column->WorkMinX; + column->ContentMaxXHeadersUsed = column->ContentMaxXHeadersIdeal = column->WorkMinX; + + // Don't decrement auto-fit counters until container window got a chance to submit its items + if (table->HostSkipItems == false) + { + column->AutoFitQueue >>= 1; + column->CannotSkipItemsQueue >>= 1; + } + + if (visible_n < table->FreezeColumnsCount) + host_clip_rect.Min.x = ImClamp(column->MaxX + TABLE_BORDER_SIZE, host_clip_rect.Min.x, host_clip_rect.Max.x); + + offset_x += column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f; + visible_n++; + } + + // [Part 7] Detect/store when we are hovering the unused space after the right-most column (so e.g. context menus can react on it) + // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either + // because of using _WidthAuto/_WidthStretch). This will hide the resizing option from the context menu. + const float unused_x1 = ImMax(table->WorkRect.Min.x, table->Columns[table->RightMostEnabledColumn].ClipRect.Max.x); + if (is_hovering_table && table->HoveredColumnBody == -1) + { + if (g.IO.MousePos.x >= unused_x1) + table->HoveredColumnBody = (ImGuiTableColumnIdx)table->ColumnsCount; + } + if (has_resizable == false && (table->Flags & ImGuiTableFlags_Resizable)) + table->Flags &= ~ImGuiTableFlags_Resizable; + + // [Part 8] Lock actual OuterRect/WorkRect right-most position. + // This is done late to handle the case of fixed-columns tables not claiming more widths that they need. + // Because of this we are careful with uses of WorkRect and InnerClipRect before this point. + if (table->RightMostStretchedColumn != -1) + table->Flags &= ~ImGuiTableFlags_NoHostExtendX; + if (table->Flags & ImGuiTableFlags_NoHostExtendX) + { + table->OuterRect.Max.x = table->WorkRect.Max.x = unused_x1; + table->InnerClipRect.Max.x = ImMin(table->InnerClipRect.Max.x, unused_x1); + } + table->InnerWindow->ParentWorkRect = table->WorkRect; + table->BorderX1 = table->InnerClipRect.Min.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : -1.0f); + table->BorderX2 = table->InnerClipRect.Max.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : +1.0f); + + // [Part 9] Allocate draw channels and setup background cliprect + TableSetupDrawChannels(table); + + // [Part 10] Hit testing on borders + if (table->Flags & ImGuiTableFlags_Resizable) + TableUpdateBorders(table); + table_instance->LastFirstRowHeight = 0.0f; + table->IsLayoutLocked = true; + table->IsUsingHeaders = false; + + // [Part 11] Context menu + if (table->IsContextPopupOpen && table->InstanceCurrent == table->InstanceInteracted) + { + const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID); + if (BeginPopupEx(context_menu_id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings)) + { + TableDrawContextMenu(table); + EndPopup(); + } + else + { + table->IsContextPopupOpen = false; + } + } + + // [Part 13] Sanitize and build sort specs before we have a change to use them for display. + // This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change) + if (table->IsSortSpecsDirty && (table->Flags & ImGuiTableFlags_Sortable)) + TableSortSpecsBuild(table); + + // Initial state + ImGuiWindow* inner_window = table->InnerWindow; + if (table->Flags & ImGuiTableFlags_NoClip) + table->DrawSplitter->SetCurrentChannel(inner_window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP); + else + inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false); +} + +// Process hit-testing on resizing borders. Actual size change will be applied in EndTable() +// - Set table->HoveredColumnBorder with a short delay/timer to reduce feedback noise +// - Submit ahead of table contents and header, use ImGuiButtonFlags_AllowItemOverlap to prioritize widgets +// overlapping the same area. +void ImGui::TableUpdateBorders(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable); + + // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and + // use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not + // really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height). + // Actual columns highlight/render will be performed in EndTable() and not be affected. + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS; + const float hit_y1 = table->OuterRect.Min.y; + const float hit_y2_body = ImMax(table->OuterRect.Max.y, hit_y1 + table_instance->LastOuterHeight); + const float hit_y2_head = hit_y1 + table_instance->LastFirstRowHeight; + + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n))) + continue; + + const int column_n = table->DisplayOrderToIndex[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) + continue; + + // ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders() + const float border_y2_hit = (table->Flags & ImGuiTableFlags_NoBordersInBody) ? hit_y2_head : hit_y2_body; + if ((table->Flags & ImGuiTableFlags_NoBordersInBody) && table->IsUsingHeaders == false) + continue; + + if (!column->IsVisibleX && table->LastResizedColumn != column_n) + continue; + + ImGuiID column_id = TableGetColumnResizeID(table, column_n, table->InstanceCurrent); + ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, border_y2_hit); + //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100)); + KeepAliveID(column_id); + + bool hovered = false, held = false; + bool pressed = ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_NoNavFocus); + if (pressed && IsMouseDoubleClicked(0)) + { + TableSetColumnWidthAutoSingle(table, column_n); + ClearActiveID(); + held = hovered = false; + } + if (held) + { + if (table->LastResizedColumn == -1) + table->ResizeLockMinContentsX2 = table->RightMostEnabledColumn != -1 ? table->Columns[table->RightMostEnabledColumn].MaxX : -FLT_MAX; + table->ResizedColumn = (ImGuiTableColumnIdx)column_n; + table->InstanceInteracted = table->InstanceCurrent; + } + if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held) + { + table->HoveredColumnBorder = (ImGuiTableColumnIdx)column_n; + SetMouseCursor(ImGuiMouseCursor_ResizeEW); + } + } +} + +void ImGui::EndTable() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL && "Only call EndTable() if BeginTable() returns true!"); + + // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some + // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) + //IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?"); + + // If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our + // code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc. + if (!table->IsLayoutLocked) + TableUpdateLayout(table); + + const ImGuiTableFlags flags = table->Flags; + ImGuiWindow* inner_window = table->InnerWindow; + ImGuiWindow* outer_window = table->OuterWindow; + ImGuiTableTempData* temp_data = table->TempData; + IM_ASSERT(inner_window == g.CurrentWindow); + IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow); + + if (table->IsInsideRow) + TableEndRow(table); + + // Context menu in columns body + if (flags & ImGuiTableFlags_ContextMenuInBody) + if (table->HoveredColumnBody != -1 && !IsAnyItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) + TableOpenContextMenu((int)table->HoveredColumnBody); + + // Finalize table height + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + inner_window->DC.PrevLineSize = temp_data->HostBackupPrevLineSize; + inner_window->DC.CurrLineSize = temp_data->HostBackupCurrLineSize; + inner_window->DC.CursorMaxPos = temp_data->HostBackupCursorMaxPos; + const float inner_content_max_y = table->RowPosY2; + IM_ASSERT(table->RowPosY2 == inner_window->DC.CursorPos.y); + if (inner_window != outer_window) + inner_window->DC.CursorMaxPos.y = inner_content_max_y; + else if (!(flags & ImGuiTableFlags_NoHostExtendY)) + table->OuterRect.Max.y = table->InnerRect.Max.y = ImMax(table->OuterRect.Max.y, inner_content_max_y); // Patch OuterRect/InnerRect height + table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y); + table_instance->LastOuterHeight = table->OuterRect.GetHeight(); + + // Setup inner scrolling range + // FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window->DC.CursorMaxPos.y, + // but since the later is likely to be impossible to do we'd rather update both axises together. + if (table->Flags & ImGuiTableFlags_ScrollX) + { + const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; + float max_pos_x = table->InnerWindow->DC.CursorMaxPos.x; + if (table->RightMostEnabledColumn != -1) + max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border); + if (table->ResizedColumn != -1) + max_pos_x = ImMax(max_pos_x, table->ResizeLockMinContentsX2); + table->InnerWindow->DC.CursorMaxPos.x = max_pos_x; + } + + // Pop clipping rect + if (!(flags & ImGuiTableFlags_NoClip)) + inner_window->DrawList->PopClipRect(); + inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back(); + + // Draw borders + if ((flags & ImGuiTableFlags_Borders) != 0) + TableDrawBorders(table); + +#if 0 + // Strip out dummy channel draw calls + // We have no way to prevent user submitting direct ImDrawList calls into a hidden column (but ImGui:: calls will be clipped out) + // Pros: remove draw calls which will have no effect. since they'll have zero-size cliprect they may be early out anyway. + // Cons: making it harder for users watching metrics/debugger to spot the wasted vertices. + if (table->DummyDrawChannel != (ImGuiTableColumnIdx)-1) + { + ImDrawChannel* dummy_channel = &table->DrawSplitter._Channels[table->DummyDrawChannel]; + dummy_channel->_CmdBuffer.resize(0); + dummy_channel->_IdxBuffer.resize(0); + } +#endif + + // Flatten channels and merge draw calls + ImDrawListSplitter* splitter = table->DrawSplitter; + splitter->SetCurrentChannel(inner_window->DrawList, 0); + if ((table->Flags & ImGuiTableFlags_NoClip) == 0) + TableMergeDrawChannels(table); + splitter->Merge(inner_window->DrawList); + + // Update ColumnsAutoFitWidth to get us ahead for host using our size to auto-resize without waiting for next BeginTable() + float auto_fit_width_for_fixed = 0.0f; + float auto_fit_width_for_stretched = 0.0f; + float auto_fit_width_for_stretched_min = 0.0f; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if (table->EnabledMaskByIndex & ((ImU64)1 << column_n)) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + float column_width_request = ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !(column->Flags & ImGuiTableColumnFlags_NoResize)) ? column->WidthRequest : TableGetColumnWidthAuto(table, column); + if (column->Flags & ImGuiTableColumnFlags_WidthFixed) + auto_fit_width_for_fixed += column_width_request; + else + auto_fit_width_for_stretched += column_width_request; + if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) && (column->Flags & ImGuiTableColumnFlags_NoResize) != 0) + auto_fit_width_for_stretched_min = ImMax(auto_fit_width_for_stretched_min, column_width_request / (column->StretchWeight / table->ColumnsStretchSumWeights)); + } + const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1); + table->ColumnsAutoFitWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount + auto_fit_width_for_fixed + ImMax(auto_fit_width_for_stretched, auto_fit_width_for_stretched_min); + + // Update scroll + if ((table->Flags & ImGuiTableFlags_ScrollX) == 0 && inner_window != outer_window) + { + inner_window->Scroll.x = 0.0f; + } + else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceCurrent) + { + // When releasing a column being resized, scroll to keep the resulting column in sight + const float neighbor_width_to_keep_visible = table->MinColumnWidth + table->CellPaddingX * 2.0f; + ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn]; + if (column->MaxX < table->InnerClipRect.Min.x) + SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x - neighbor_width_to_keep_visible, 1.0f); + else if (column->MaxX > table->InnerClipRect.Max.x) + SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x + neighbor_width_to_keep_visible, 1.0f); + } + + // Apply resizing/dragging at the end of the frame + if (table->ResizedColumn != -1 && table->InstanceCurrent == table->InstanceInteracted) + { + ImGuiTableColumn* column = &table->Columns[table->ResizedColumn]; + const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + TABLE_RESIZE_SEPARATOR_HALF_THICKNESS); + const float new_width = ImFloor(new_x2 - column->MinX - table->CellSpacingX1 - table->CellPaddingX * 2.0f); + table->ResizedColumnNextWidth = new_width; + } + + // Pop from id stack + IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table->ID + table->InstanceCurrent, "Mismatching PushID/PopID!"); + IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, "Too many PopItemWidth!"); + PopID(); + + // Restore window data that we modified + const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos; + inner_window->WorkRect = temp_data->HostBackupWorkRect; + inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect; + inner_window->SkipItems = table->HostSkipItems; + outer_window->DC.CursorPos = table->OuterRect.Min; + outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth; + outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize; + outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset; + + // Layout in outer window + // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding + // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414) + if (inner_window != outer_window) + { + EndChild(); + } + else + { + ItemSize(table->OuterRect.GetSize()); + ItemAdd(table->OuterRect, 0); + } + + // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar + if (table->Flags & ImGuiTableFlags_NoHostExtendX) + { + // FIXME-TABLE: Could we remove this section? + // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents + IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0); + outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth); + } + else if (temp_data->UserOuterSize.x <= 0.0f) + { + const float decoration_size = (table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f; + outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - temp_data->UserOuterSize.x); + outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth)); + } + else + { + outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x); + } + if (temp_data->UserOuterSize.y <= 0.0f) + { + const float decoration_size = (table->Flags & ImGuiTableFlags_ScrollY) ? inner_window->ScrollbarSizes.y : 0.0f; + outer_window->DC.IdealMaxPos.y = ImMax(outer_window->DC.IdealMaxPos.y, inner_content_max_y + decoration_size - temp_data->UserOuterSize.y); + outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, ImMin(table->OuterRect.Max.y, inner_content_max_y)); + } + else + { + // OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set) + outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, table->OuterRect.Max.y); + } + + // Save settings + if (table->IsSettingsDirty) + TableSaveSettings(table); + table->IsInitializing = false; + + // Clear or restore current table, if any + IM_ASSERT(g.CurrentWindow == outer_window && g.CurrentTable == table); + IM_ASSERT(g.TablesTempDataStacked > 0); + temp_data = (--g.TablesTempDataStacked > 0) ? &g.TablesTempData[g.TablesTempDataStacked - 1] : NULL; + g.CurrentTable = temp_data ? g.Tables.GetByIndex(temp_data->TableIndex) : NULL; + if (g.CurrentTable) + { + g.CurrentTable->TempData = temp_data; + g.CurrentTable->DrawSplitter = &temp_data->DrawSplitter; + } + outer_window->DC.CurrentTableIdx = g.CurrentTable ? g.Tables.GetIndex(g.CurrentTable) : -1; +} + +// See "COLUMN SIZING POLICIES" comments at the top of this file +// If (init_width_or_weight <= 0.0f) it is ignored +void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!"); + IM_ASSERT(table->IsLayoutLocked == false && "Need to call call TableSetupColumn() before first row!"); + IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && "Illegal to pass StatusMask values to TableSetupColumn()"); + if (table->DeclColumnsCount >= table->ColumnsCount) + { + IM_ASSERT_USER_ERROR(table->DeclColumnsCount < table->ColumnsCount, "Called TableSetupColumn() too many times!"); + return; + } + + ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount]; + table->DeclColumnsCount++; + + // Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa. + // Give a grace to users of ImGuiTableFlags_ScrollX. + if (table->IsDefaultSizingPolicy && (flags & ImGuiTableColumnFlags_WidthMask_) == 0 && (flags & ImGuiTableFlags_ScrollX) == 0) + IM_ASSERT(init_width_or_weight <= 0.0f && "Can only specify width/weight if sizing policy is set explicitly in either Table or Column."); + + // When passing a width automatically enforce WidthFixed policy + // (whereas TableSetupColumnFlags would default to WidthAuto if table is not Resizable) + if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0 && init_width_or_weight > 0.0f) + if ((table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedFit || (table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame) + flags |= ImGuiTableColumnFlags_WidthFixed; + + TableSetupColumnFlags(table, column, flags); + column->UserID = user_id; + flags = column->Flags; + + // Initialize defaults + column->InitStretchWeightOrWidth = init_width_or_weight; + if (table->IsInitializing) + { + // Init width or weight + if (column->WidthRequest < 0.0f && column->StretchWeight < 0.0f) + { + if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) + column->WidthRequest = init_width_or_weight; + if (flags & ImGuiTableColumnFlags_WidthStretch) + column->StretchWeight = (init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f; + + // Disable auto-fit if an explicit width/weight has been specified + if (init_width_or_weight > 0.0f) + column->AutoFitQueue = 0x00; + } + + // Init default visibility/sort state + if ((flags & ImGuiTableColumnFlags_DefaultHide) && (table->SettingsLoadedFlags & ImGuiTableFlags_Hideable) == 0) + column->IsUserEnabled = column->IsUserEnabledNextFrame = false; + if (flags & ImGuiTableColumnFlags_DefaultSort && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0) + { + column->SortOrder = 0; // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs. + column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending); + } + } + + // Store name (append with zero-terminator in contiguous buffer) + column->NameOffset = -1; + if (label != NULL && label[0] != 0) + { + column->NameOffset = (ImS16)table->ColumnsNames.size(); + table->ColumnsNames.append(label, label + strlen(label) + 1); + } +} + +// [Public] +void ImGui::TableSetupScrollFreeze(int columns, int rows) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!"); + IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!"); + IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS); + IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit + + table->FreezeColumnsRequest = (table->Flags & ImGuiTableFlags_ScrollX) ? (ImGuiTableColumnIdx)ImMin(columns, table->ColumnsCount) : 0; + table->FreezeColumnsCount = (table->InnerWindow->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0; + table->FreezeRowsRequest = (table->Flags & ImGuiTableFlags_ScrollY) ? (ImGuiTableColumnIdx)rows : 0; + table->FreezeRowsCount = (table->InnerWindow->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0; + table->IsUnfrozenRows = (table->FreezeRowsCount == 0); // Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it.b + + // Ensure frozen columns are ordered in their section. We still allow multiple frozen columns to be reordered. + // FIXME-TABLE: This work for preserving 2143 into 21|43. How about 4321 turning into 21|43? (preserve relative order in each section) + for (int column_n = 0; column_n < table->FreezeColumnsRequest; column_n++) + { + int order_n = table->DisplayOrderToIndex[column_n]; + if (order_n != column_n && order_n >= table->FreezeColumnsRequest) + { + ImSwap(table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder, table->Columns[table->DisplayOrderToIndex[column_n]].DisplayOrder); + ImSwap(table->DisplayOrderToIndex[order_n], table->DisplayOrderToIndex[column_n]); + } + } +} + +//----------------------------------------------------------------------------- +// [SECTION] Tables: Simple accessors +//----------------------------------------------------------------------------- +// - TableGetColumnCount() +// - TableGetColumnName() +// - TableGetColumnName() [Internal] +// - TableSetColumnEnabled() +// - TableGetColumnFlags() +// - TableGetCellBgRect() [Internal] +// - TableGetColumnResizeID() [Internal] +// - TableGetHoveredColumn() [Internal] +// - TableSetBgColor() +//----------------------------------------------------------------------------- + +int ImGui::TableGetColumnCount() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + return table ? table->ColumnsCount : 0; +} + +const char* ImGui::TableGetColumnName(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return NULL; + if (column_n < 0) + column_n = table->CurrentColumn; + return TableGetColumnName(table, column_n); +} + +const char* ImGui::TableGetColumnName(const ImGuiTable* table, int column_n) +{ + if (table->IsLayoutLocked == false && column_n >= table->DeclColumnsCount) + return ""; // NameOffset is invalid at this point + const ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->NameOffset == -1) + return ""; + return &table->ColumnsNames.Buf[column->NameOffset]; +} + +// Change user accessible enabled/disabled state of a column (often perceived as "showing/hiding" from users point of view) +// Note that end-user can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody) +// - Require table to have the ImGuiTableFlags_Hideable flag because we are manipulating user accessible state. +// - Request will be applied during next layout, which happens on the first call to TableNextRow() after BeginTable(). +// - For the getter you can test (TableGetColumnFlags() & ImGuiTableColumnFlags_IsEnabled) != 0. +// - Alternative: the ImGuiTableColumnFlags_Disabled is an overriding/master disable flag which will also hide the column from context menu. +void ImGui::TableSetColumnEnabled(int column_n, bool enabled) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL); + if (!table) + return; + IM_ASSERT(table->Flags & ImGuiTableFlags_Hideable); // See comments above + if (column_n < 0) + column_n = table->CurrentColumn; + IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount); + ImGuiTableColumn* column = &table->Columns[column_n]; + column->IsUserEnabledNextFrame = enabled; +} + +// We allow querying for an extra column in order to poll the IsHovered state of the right-most section +ImGuiTableColumnFlags ImGui::TableGetColumnFlags(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return ImGuiTableColumnFlags_None; + if (column_n < 0) + column_n = table->CurrentColumn; + if (column_n == table->ColumnsCount) + return (table->HoveredColumnBody == column_n) ? ImGuiTableColumnFlags_IsHovered : ImGuiTableColumnFlags_None; + return table->Columns[column_n].Flags; +} + +// Return the cell rectangle based on currently known height. +// - Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations. +// The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it, or in TableEndRow() when we locked that height. +// - Important: if ImGuiTableFlags_PadOuterX is set but ImGuiTableFlags_PadInnerX is not set, the outer-most left and right +// columns report a small offset so their CellBgRect can extend up to the outer border. +// FIXME: But the rendering code in TableEndRow() nullifies that with clamping required for scrolling. +ImRect ImGui::TableGetCellBgRect(const ImGuiTable* table, int column_n) +{ + const ImGuiTableColumn* column = &table->Columns[column_n]; + float x1 = column->MinX; + float x2 = column->MaxX; + //if (column->PrevEnabledColumn == -1) + // x1 -= table->OuterPaddingX; + //if (column->NextEnabledColumn == -1) + // x2 += table->OuterPaddingX; + x1 = ImMax(x1, table->WorkRect.Min.x); + x2 = ImMin(x2, table->WorkRect.Max.x); + return ImRect(x1, table->RowPosY1, x2, table->RowPosY2); +} + +// Return the resizing ID for the right-side of the given column. +ImGuiID ImGui::TableGetColumnResizeID(const ImGuiTable* table, int column_n, int instance_no) +{ + IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount); + ImGuiID id = table->ID + 1 + (instance_no * table->ColumnsCount) + column_n; + return id; +} + +// Return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. +int ImGui::TableGetHoveredColumn() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return -1; + return (int)table->HoveredColumnBody; +} + +void ImGui::TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(target != ImGuiTableBgTarget_None); + + if (color == IM_COL32_DISABLE) + color = 0; + + // We cannot draw neither the cell or row background immediately as we don't know the row height at this point in time. + switch (target) + { + case ImGuiTableBgTarget_CellBg: + { + if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard + return; + if (column_n == -1) + column_n = table->CurrentColumn; + if ((table->VisibleMaskByIndex & ((ImU64)1 << column_n)) == 0) + return; + if (table->RowCellDataCurrent < 0 || table->RowCellData[table->RowCellDataCurrent].Column != column_n) + table->RowCellDataCurrent++; + ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCurrent]; + cell_data->BgColor = color; + cell_data->Column = (ImGuiTableColumnIdx)column_n; + break; + } + case ImGuiTableBgTarget_RowBg0: + case ImGuiTableBgTarget_RowBg1: + { + if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard + return; + IM_ASSERT(column_n == -1); + int bg_idx = (target == ImGuiTableBgTarget_RowBg1) ? 1 : 0; + table->RowBgColor[bg_idx] = color; + break; + } + default: + IM_ASSERT(0); + } +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Row changes +//------------------------------------------------------------------------- +// - TableGetRowIndex() +// - TableNextRow() +// - TableBeginRow() [Internal] +// - TableEndRow() [Internal] +//------------------------------------------------------------------------- + +// [Public] Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows +int ImGui::TableGetRowIndex() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return 0; + return table->CurrentRow; +} + +// [Public] Starts into the first cell of a new row +void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float row_min_height) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + if (!table->IsLayoutLocked) + TableUpdateLayout(table); + if (table->IsInsideRow) + TableEndRow(table); + + table->LastRowFlags = table->RowFlags; + table->RowFlags = row_flags; + table->RowMinHeight = row_min_height; + TableBeginRow(table); + + // We honor min_row_height requested by user, but cannot guarantee per-row maximum height, + // because that would essentially require a unique clipping rectangle per-cell. + table->RowPosY2 += table->CellPaddingY * 2.0f; + table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + row_min_height); + + // Disable output until user calls TableNextColumn() + table->InnerWindow->SkipItems = true; +} + +// [Internal] Called by TableNextRow() +void ImGui::TableBeginRow(ImGuiTable* table) +{ + ImGuiWindow* window = table->InnerWindow; + IM_ASSERT(!table->IsInsideRow); + + // New row + table->CurrentRow++; + table->CurrentColumn = -1; + table->RowBgColor[0] = table->RowBgColor[1] = IM_COL32_DISABLE; + table->RowCellDataCurrent = -1; + table->IsInsideRow = true; + + // Begin frozen rows + float next_y1 = table->RowPosY2; + if (table->CurrentRow == 0 && table->FreezeRowsCount > 0) + next_y1 = window->DC.CursorPos.y = table->OuterRect.Min.y; + + table->RowPosY1 = table->RowPosY2 = next_y1; + table->RowTextBaseline = 0.0f; + table->RowIndentOffsetX = window->DC.Indent.x - table->HostIndentX; // Lock indent + window->DC.PrevLineTextBaseOffset = 0.0f; + window->DC.CursorMaxPos.y = next_y1; + + // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging. + if (table->RowFlags & ImGuiTableRowFlags_Headers) + { + TableSetBgColor(ImGuiTableBgTarget_RowBg0, GetColorU32(ImGuiCol_TableHeaderBg)); + if (table->CurrentRow == 0) + table->IsUsingHeaders = true; + } +} + +// [Internal] Called by TableNextRow() +void ImGui::TableEndRow(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(window == table->InnerWindow); + IM_ASSERT(table->IsInsideRow); + + if (table->CurrentColumn != -1) + TableEndCell(table); + + // Logging + if (g.LogEnabled) + LogRenderedText(NULL, "|"); + + // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is + // likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding. + window->DC.CursorPos.y = table->RowPosY2; + + // Row background fill + const float bg_y1 = table->RowPosY1; + const float bg_y2 = table->RowPosY2; + const bool unfreeze_rows_actual = (table->CurrentRow + 1 == table->FreezeRowsCount); + const bool unfreeze_rows_request = (table->CurrentRow + 1 == table->FreezeRowsRequest); + if (table->CurrentRow == 0) + TableGetInstanceData(table, table->InstanceCurrent)->LastFirstRowHeight = bg_y2 - bg_y1; + + const bool is_visible = (bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y); + if (is_visible) + { + // Decide of background color for the row + ImU32 bg_col0 = 0; + ImU32 bg_col1 = 0; + if (table->RowBgColor[0] != IM_COL32_DISABLE) + bg_col0 = table->RowBgColor[0]; + else if (table->Flags & ImGuiTableFlags_RowBg) + bg_col0 = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg); + if (table->RowBgColor[1] != IM_COL32_DISABLE) + bg_col1 = table->RowBgColor[1]; + + // Decide of top border color + ImU32 border_col = 0; + const float border_size = TABLE_BORDER_SIZE; + if (table->CurrentRow > 0 || table->InnerWindow == table->OuterWindow) + if (table->Flags & ImGuiTableFlags_BordersInnerH) + border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight; + + const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0; + const bool draw_strong_bottom_border = unfreeze_rows_actual; + if ((bg_col0 | bg_col1 | border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color) + { + // In theory we could call SetWindowClipRectBeforeSetChannel() but since we know TableEndRow() is + // always followed by a change of clipping rectangle we perform the smallest overwrite possible here. + if ((table->Flags & ImGuiTableFlags_NoClip) == 0) + window->DrawList->_CmdHeader.ClipRect = table->Bg0ClipRectForDrawCmd.ToVec4(); + table->DrawSplitter->SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_BG0); + } + + // Draw row background + // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle + if (bg_col0 || bg_col1) + { + ImRect row_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2); + row_rect.ClipWith(table->BgClipRect); + if (bg_col0 != 0 && row_rect.Min.y < row_rect.Max.y) + window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col0); + if (bg_col1 != 0 && row_rect.Min.y < row_rect.Max.y) + window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col1); + } + + // Draw cell background color + if (draw_cell_bg_color) + { + ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCurrent]; + for (ImGuiTableCellData* cell_data = &table->RowCellData[0]; cell_data <= cell_data_end; cell_data++) + { + // As we render the BG here we need to clip things (for layout we would not) + // FIXME: This cancels the OuterPadding addition done by TableGetCellBgRect(), need to keep it while rendering correctly while scrolling. + const ImGuiTableColumn* column = &table->Columns[cell_data->Column]; + ImRect cell_bg_rect = TableGetCellBgRect(table, cell_data->Column); + cell_bg_rect.ClipWith(table->BgClipRect); + cell_bg_rect.Min.x = ImMax(cell_bg_rect.Min.x, column->ClipRect.Min.x); // So that first column after frozen one gets clipped when scrolling + cell_bg_rect.Max.x = ImMin(cell_bg_rect.Max.x, column->MaxX); + window->DrawList->AddRectFilled(cell_bg_rect.Min, cell_bg_rect.Max, cell_data->BgColor); + } + } + + // Draw top border + if (border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y) + window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y1), ImVec2(table->BorderX2, bg_y1), border_col, border_size); + + // Draw bottom border at the row unfreezing mark (always strong) + if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y) + window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong, border_size); + } + + // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) + // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and + // get the new cursor position. + if (unfreeze_rows_request) + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + column->NavLayerCurrent = (ImS8)((column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main); + } + if (unfreeze_rows_actual) + { + IM_ASSERT(table->IsUnfrozenRows == false); + table->IsUnfrozenRows = true; + + // BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect + float y0 = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y); + table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(y0, window->InnerClipRect.Max.y); + table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = window->InnerClipRect.Max.y; + table->Bg2DrawChannelCurrent = table->Bg2DrawChannelUnfrozen; + IM_ASSERT(table->Bg2ClipRectForDrawCmd.Min.y <= table->Bg2ClipRectForDrawCmd.Max.y); + + float row_height = table->RowPosY2 - table->RowPosY1; + table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y; + table->RowPosY1 = table->RowPosY2 - row_height; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + column->DrawChannelCurrent = column->DrawChannelUnfrozen; + column->ClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y; + } + + // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y + SetWindowClipRectBeforeSetChannel(window, table->Columns[0].ClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[0].DrawChannelCurrent); + } + + if (!(table->RowFlags & ImGuiTableRowFlags_Headers)) + table->RowBgColorCounter++; + table->IsInsideRow = false; +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Columns changes +//------------------------------------------------------------------------- +// - TableGetColumnIndex() +// - TableSetColumnIndex() +// - TableNextColumn() +// - TableBeginCell() [Internal] +// - TableEndCell() [Internal] +//------------------------------------------------------------------------- + +int ImGui::TableGetColumnIndex() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return 0; + return table->CurrentColumn; +} + +// [Public] Append into a specific column +bool ImGui::TableSetColumnIndex(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return false; + + if (table->CurrentColumn != column_n) + { + if (table->CurrentColumn != -1) + TableEndCell(table); + IM_ASSERT(column_n >= 0 && table->ColumnsCount); + TableBeginCell(table, column_n); + } + + // Return whether the column is visible. User may choose to skip submitting items based on this return value, + // however they shouldn't skip submitting for columns that may have the tallest contribution to row height. + return (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)) != 0; +} + +// [Public] Append into the next column, wrap and create a new row when already on last column +bool ImGui::TableNextColumn() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return false; + + if (table->IsInsideRow && table->CurrentColumn + 1 < table->ColumnsCount) + { + if (table->CurrentColumn != -1) + TableEndCell(table); + TableBeginCell(table, table->CurrentColumn + 1); + } + else + { + TableNextRow(); + TableBeginCell(table, 0); + } + + // Return whether the column is visible. User may choose to skip submitting items based on this return value, + // however they shouldn't skip submitting for columns that may have the tallest contribution to row height. + int column_n = table->CurrentColumn; + return (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)) != 0; +} + + +// [Internal] Called by TableSetColumnIndex()/TableNextColumn() +// This is called very frequently, so we need to be mindful of unnecessary overhead. +// FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns. +void ImGui::TableBeginCell(ImGuiTable* table, int column_n) +{ + ImGuiTableColumn* column = &table->Columns[column_n]; + ImGuiWindow* window = table->InnerWindow; + table->CurrentColumn = column_n; + + // Start position is roughly ~~ CellRect.Min + CellPadding + Indent + float start_x = column->WorkMinX; + if (column->Flags & ImGuiTableColumnFlags_IndentEnable) + start_x += table->RowIndentOffsetX; // ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row. + + window->DC.CursorPos.x = start_x; + window->DC.CursorPos.y = table->RowPosY1 + table->CellPaddingY; + window->DC.CursorMaxPos.x = window->DC.CursorPos.x; + window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT + window->DC.CurrLineTextBaseOffset = table->RowTextBaseline; + window->DC.NavLayerCurrent = (ImGuiNavLayer)column->NavLayerCurrent; + + window->WorkRect.Min.y = window->DC.CursorPos.y; + window->WorkRect.Min.x = column->WorkMinX; + window->WorkRect.Max.x = column->WorkMaxX; + window->DC.ItemWidth = column->ItemWidth; + + // To allow ImGuiListClipper to function we propagate our row height + if (!column->IsEnabled) + window->DC.CursorPos.y = ImMax(window->DC.CursorPos.y, table->RowPosY2); + + window->SkipItems = column->IsSkipItems; + if (column->IsSkipItems) + { + ImGuiContext& g = *GImGui; + g.LastItemData.ID = 0; + g.LastItemData.StatusFlags = 0; + } + + if (table->Flags & ImGuiTableFlags_NoClip) + { + // FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed. + table->DrawSplitter->SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP); + //IM_ASSERT(table->DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP); + } + else + { + // FIXME-TABLE: Could avoid this if draw channel is dummy channel? + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); + } + + // Logging + ImGuiContext& g = *GImGui; + if (g.LogEnabled && !column->IsSkipItems) + { + LogRenderedText(&window->DC.CursorPos, "|"); + g.LogLinePosY = FLT_MAX; + } +} + +// [Internal] Called by TableNextRow()/TableSetColumnIndex()/TableNextColumn() +void ImGui::TableEndCell(ImGuiTable* table) +{ + ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + ImGuiWindow* window = table->InnerWindow; + + // Report maximum position so we can infer content size per column. + float* p_max_pos_x; + if (table->RowFlags & ImGuiTableRowFlags_Headers) + p_max_pos_x = &column->ContentMaxXHeadersUsed; // Useful in case user submit contents in header row that is not a TableHeader() call + else + p_max_pos_x = table->IsUnfrozenRows ? &column->ContentMaxXUnfrozen : &column->ContentMaxXFrozen; + *p_max_pos_x = ImMax(*p_max_pos_x, window->DC.CursorMaxPos.x); + table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y + table->CellPaddingY); + column->ItemWidth = window->DC.ItemWidth; + + // Propagate text baseline for the entire row + // FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one. + table->RowTextBaseline = ImMax(table->RowTextBaseline, window->DC.PrevLineTextBaseOffset); +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Columns width management +//------------------------------------------------------------------------- +// - TableGetMaxColumnWidth() [Internal] +// - TableGetColumnWidthAuto() [Internal] +// - TableSetColumnWidth() +// - TableSetColumnWidthAutoSingle() [Internal] +// - TableSetColumnWidthAutoAll() [Internal] +// - TableUpdateColumnsWeightFromWidth() [Internal] +//------------------------------------------------------------------------- + +// Maximum column content width given current layout. Use column->MinX so this value on a per-column basis. +float ImGui::TableGetMaxColumnWidth(const ImGuiTable* table, int column_n) +{ + const ImGuiTableColumn* column = &table->Columns[column_n]; + float max_width = FLT_MAX; + const float min_column_distance = table->MinColumnWidth + table->CellPaddingX * 2.0f + table->CellSpacingX1 + table->CellSpacingX2; + if (table->Flags & ImGuiTableFlags_ScrollX) + { + // Frozen columns can't reach beyond visible width else scrolling will naturally break. + // (we use DisplayOrder as within a set of multiple frozen column reordering is possible) + if (column->DisplayOrder < table->FreezeColumnsRequest) + { + max_width = (table->InnerClipRect.Max.x - (table->FreezeColumnsRequest - column->DisplayOrder) * min_column_distance) - column->MinX; + max_width = max_width - table->OuterPaddingX - table->CellPaddingX - table->CellSpacingX2; + } + } + else if ((table->Flags & ImGuiTableFlags_NoKeepColumnsVisible) == 0) + { + // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make + // sure they are all visible. Because of this we also know that all of the columns will always fit in + // table->WorkRect and therefore in table->InnerRect (because ScrollX is off) + // FIXME-TABLE: This is solved incorrectly but also quite a difficult problem to fix as we also want ClipRect width to match. + // See "table_width_distrib" and "table_width_keep_visible" tests + max_width = table->WorkRect.Max.x - (table->ColumnsEnabledCount - column->IndexWithinEnabledSet - 1) * min_column_distance - column->MinX; + //max_width -= table->CellSpacingX1; + max_width -= table->CellSpacingX2; + max_width -= table->CellPaddingX * 2.0f; + max_width -= table->OuterPaddingX; + } + return max_width; +} + +// Note this is meant to be stored in column->WidthAuto, please generally use the WidthAuto field +float ImGui::TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column) +{ + const float content_width_body = ImMax(column->ContentMaxXFrozen, column->ContentMaxXUnfrozen) - column->WorkMinX; + const float content_width_headers = column->ContentMaxXHeadersIdeal - column->WorkMinX; + float width_auto = content_width_body; + if (!(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth)) + width_auto = ImMax(width_auto, content_width_headers); + + // Non-resizable fixed columns preserve their requested width + if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f) + if (!(table->Flags & ImGuiTableFlags_Resizable) || (column->Flags & ImGuiTableColumnFlags_NoResize)) + width_auto = column->InitStretchWeightOrWidth; + + return ImMax(width_auto, table->MinColumnWidth); +} + +// 'width' = inner column width, without padding +void ImGui::TableSetColumnWidth(int column_n, float width) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL && table->IsLayoutLocked == false); + IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount); + ImGuiTableColumn* column_0 = &table->Columns[column_n]; + float column_0_width = width; + + // Apply constraints early + // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded) + IM_ASSERT(table->MinColumnWidth > 0.0f); + const float min_width = table->MinColumnWidth; + const float max_width = ImMax(min_width, TableGetMaxColumnWidth(table, column_n)); + column_0_width = ImClamp(column_0_width, min_width, max_width); + if (column_0->WidthGiven == column_0_width || column_0->WidthRequest == column_0_width) + return; + + //IMGUI_DEBUG_LOG("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthGiven, column_0_width); + ImGuiTableColumn* column_1 = (column_0->NextEnabledColumn != -1) ? &table->Columns[column_0->NextEnabledColumn] : NULL; + + // In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns. + // - All fixed: easy. + // - All stretch: easy. + // - One or more fixed + one stretch: easy. + // - One or more fixed + more than one stretch: tricky. + // Qt when manual resize is enabled only support a single _trailing_ stretch column. + + // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1. + // FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user. + // Scenarios: + // - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset. + // - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered. + // - F1 F2 W3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size. + // - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + // - W1 W2 W3 resize from W1| or W2| --> ok + // - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + // - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1) + // - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1) + // - W1 W2 F3 resize from W1| or W2| --> ok + // - W1 F2 W3 resize from W1| or F2| --> ok + // - F1 W2 F3 resize from W2| --> ok + // - F1 W3 F2 resize from W3| --> ok + // - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move. + // - W1 F2 F3 resize from F2| --> ok + // All resizes from a Wx columns are locking other columns. + + // Possible improvements: + // - W1 W2 W3 resize W1| --> to not be stuck, both W2 and W3 would stretch down. Seems possible to fix. Would be most beneficial to simplify resize of all-weighted columns. + // - W3 F1 F2 resize W3| --> to not be stuck past F1|, both F1 and F2 would need to stretch down, which would be lossy or ambiguous. Seems hard to fix. + + // [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout(). + + // If we have all Fixed columns OR resizing a Fixed column that doesn't come after a Stretch one, we can do an offsetting resize. + // This is the preferred resize path + if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed) + if (!column_1 || table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder >= column_0->DisplayOrder) + { + column_0->WidthRequest = column_0_width; + table->IsSettingsDirty = true; + return; + } + + // We can also use previous column if there's no next one (this is used when doing an auto-fit on the right-most stretch column) + if (column_1 == NULL) + column_1 = (column_0->PrevEnabledColumn != -1) ? &table->Columns[column_0->PrevEnabledColumn] : NULL; + if (column_1 == NULL) + return; + + // Resizing from right-side of a Stretch column before a Fixed column forward sizing to left-side of fixed column. + // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b) + float column_1_width = ImMax(column_1->WidthRequest - (column_0_width - column_0->WidthRequest), min_width); + column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width; + IM_ASSERT(column_0_width > 0.0f && column_1_width > 0.0f); + column_0->WidthRequest = column_0_width; + column_1->WidthRequest = column_1_width; + if ((column_0->Flags | column_1->Flags) & ImGuiTableColumnFlags_WidthStretch) + TableUpdateColumnsWeightFromWidth(table); + table->IsSettingsDirty = true; +} + +// Disable clipping then auto-fit, will take 2 frames +// (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns) +void ImGui::TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n) +{ + // Single auto width uses auto-fit + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!column->IsEnabled) + return; + column->CannotSkipItemsQueue = (1 << 0); + table->AutoFitSingleColumn = (ImGuiTableColumnIdx)column_n; +} + +void ImGui::TableSetColumnWidthAutoAll(ImGuiTable* table) +{ + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) // Cannot reset weight of hidden stretch column + continue; + column->CannotSkipItemsQueue = (1 << 0); + column->AutoFitQueue = (1 << 1); + } +} + +void ImGui::TableUpdateColumnsWeightFromWidth(ImGuiTable* table) +{ + IM_ASSERT(table->LeftMostStretchedColumn != -1 && table->RightMostStretchedColumn != -1); + + // Measure existing quantity + float visible_weight = 0.0f; + float visible_width = 0.0f; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + continue; + IM_ASSERT(column->StretchWeight > 0.0f); + visible_weight += column->StretchWeight; + visible_width += column->WidthRequest; + } + IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f); + + // Apply new weights + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + continue; + column->StretchWeight = (column->WidthRequest / visible_width) * visible_weight; + IM_ASSERT(column->StretchWeight > 0.0f); + } +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Drawing +//------------------------------------------------------------------------- +// - TablePushBackgroundChannel() [Internal] +// - TablePopBackgroundChannel() [Internal] +// - TableSetupDrawChannels() [Internal] +// - TableMergeDrawChannels() [Internal] +// - TableDrawBorders() [Internal] +//------------------------------------------------------------------------- + +// Bg2 is used by Selectable (and possibly other widgets) to render to the background. +// Unlike our Bg0/1 channel which we uses for RowBg/CellBg/Borders and where we guarantee all shapes to be CPU-clipped, the Bg2 channel being widgets-facing will rely on regular ClipRect. +void ImGui::TablePushBackgroundChannel() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiTable* table = g.CurrentTable; + + // Optimization: avoid SetCurrentChannel() + PushClipRect() + table->HostBackupInnerClipRect = window->ClipRect; + SetWindowClipRectBeforeSetChannel(window, table->Bg2ClipRectForDrawCmd); + table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Bg2DrawChannelCurrent); +} + +void ImGui::TablePopBackgroundChannel() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiTable* table = g.CurrentTable; + ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + SetWindowClipRectBeforeSetChannel(window, table->HostBackupInnerClipRect); + table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); +} + +// Allocate draw channels. Called by TableUpdateLayout() +// - We allocate them following storage order instead of display order so reordering columns won't needlessly +// increase overall dormant memory cost. +// - We isolate headers draw commands in their own channels instead of just altering clip rects. +// This is in order to facilitate merging of draw commands. +// - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels. +// - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other +// channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged. +// - We allocate 1 or 2 background draw channels. This is because we know TablePushBackgroundChannel() is only used for +// horizontal spanning. If we allowed vertical spanning we'd need one background draw channel per merge group (1-4). +// Draw channel allocation (before merging): +// - NoClip --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call) +// - Clip --> 2+D+N channels +// - FreezeRows --> 2+D+N*2 (unless scrolling value is zero) +// - FreezeRows || FreezeColunns --> 3+D+N*2 (unless scrolling value is zero) +// Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0. +void ImGui::TableSetupDrawChannels(ImGuiTable* table) +{ + const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1; + const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClip) ? 1 : table->ColumnsEnabledCount; + const int channels_for_bg = 1 + 1 * freeze_row_multiplier; + const int channels_for_dummy = (table->ColumnsEnabledCount < table->ColumnsCount || table->VisibleMaskByIndex != table->EnabledMaskByIndex) ? +1 : 0; + const int channels_total = channels_for_bg + (channels_for_row * freeze_row_multiplier) + channels_for_dummy; + table->DrawSplitter->Split(table->InnerWindow->DrawList, channels_total); + table->DummyDrawChannel = (ImGuiTableDrawChannelIdx)((channels_for_dummy > 0) ? channels_total - 1 : -1); + table->Bg2DrawChannelCurrent = TABLE_DRAW_CHANNEL_BG2_FROZEN; + table->Bg2DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)((table->FreezeRowsCount > 0) ? 2 + channels_for_row : TABLE_DRAW_CHANNEL_BG2_FROZEN); + + int draw_channel_current = 2; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->IsVisibleX && column->IsVisibleY) + { + column->DrawChannelFrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current); + column->DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row + 1 : 0)); + if (!(table->Flags & ImGuiTableFlags_NoClip)) + draw_channel_current++; + } + else + { + column->DrawChannelFrozen = column->DrawChannelUnfrozen = table->DummyDrawChannel; + } + column->DrawChannelCurrent = column->DrawChannelFrozen; + } + + // Initial draw cmd starts with a BgClipRect that matches the one of its host, to facilitate merge draw commands by default. + // All our cell highlight are manually clipped with BgClipRect. When unfreezing it will be made smaller to fit scrolling rect. + // (This technically isn't part of setting up draw channels, but is reasonably related to be done here) + table->BgClipRect = table->InnerClipRect; + table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect; + table->Bg2ClipRectForDrawCmd = table->HostClipRect; + IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y); +} + +// This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable(). +// For simplicity we call it TableMergeDrawChannels() but in fact it only reorder channels + overwrite ClipRect, +// actual merging is done by table->DrawSplitter.Merge() which is called right after TableMergeDrawChannels(). +// +// Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve +// this we merge their clip rect and make them contiguous in the channel list, so they can be merged +// by the call to DrawSplitter.Merge() following to the call to this function. +// We reorder draw commands by arranging them into a maximum of 4 distinct groups: +// +// 1 group: 2 groups: 2 groups: 4 groups: +// [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze +// [ .. ] or no scroll [ 2. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll +// +// Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled). +// When the contents of a column didn't stray off its limit, we move its channels into the corresponding group +// based on its position (within frozen rows/columns groups or not). +// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect. +// This function assume that each column are pointing to a distinct draw channel, +// otherwise merge_group->ChannelsCount will not match set bit count of merge_group->ChannelsMask. +// +// Column channels will not be merged into one of the 1-4 groups in the following cases: +// - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value). +// Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds +// matches, by e.g. calling SetCursorScreenPos(). +// - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here.. +// we could do better but it's going to be rare and probably not worth the hassle. +// Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. +// +// This function is particularly tricky to understand.. take a breath. +void ImGui::TableMergeDrawChannels(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + ImDrawListSplitter* splitter = table->DrawSplitter; + const bool has_freeze_v = (table->FreezeRowsCount > 0); + const bool has_freeze_h = (table->FreezeColumnsCount > 0); + IM_ASSERT(splitter->_Current == 0); + + // Track which groups we are going to attempt to merge, and which channels goes into each group. + struct MergeGroup + { + ImRect ClipRect; + int ChannelsCount; + ImBitArray ChannelsMask; + + MergeGroup() { ChannelsCount = 0; } + }; + int merge_group_mask = 0x00; + MergeGroup merge_groups[4]; + + // 1. Scan channels and take note of those which can be merged + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + if ((table->VisibleMaskByIndex & ((ImU64)1 << column_n)) == 0) + continue; + ImGuiTableColumn* column = &table->Columns[column_n]; + + const int merge_group_sub_count = has_freeze_v ? 2 : 1; + for (int merge_group_sub_n = 0; merge_group_sub_n < merge_group_sub_count; merge_group_sub_n++) + { + const int channel_no = (merge_group_sub_n == 0) ? column->DrawChannelFrozen : column->DrawChannelUnfrozen; + + // Don't attempt to merge if there are multiple draw calls within the column + ImDrawChannel* src_channel = &splitter->_Channels[channel_no]; + if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0 && src_channel->_CmdBuffer.back().UserCallback != NULL) // Equivalent of PopUnusedDrawCmd() + src_channel->_CmdBuffer.pop_back(); + if (src_channel->_CmdBuffer.Size != 1) + continue; + + // Find out the width of this merge group and check if it will fit in our column + // (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it) + if (!(column->Flags & ImGuiTableColumnFlags_NoClip)) + { + float content_max_x; + if (!has_freeze_v) + content_max_x = ImMax(column->ContentMaxXUnfrozen, column->ContentMaxXHeadersUsed); // No row freeze + else if (merge_group_sub_n == 0) + content_max_x = ImMax(column->ContentMaxXFrozen, column->ContentMaxXHeadersUsed); // Row freeze: use width before freeze + else + content_max_x = column->ContentMaxXUnfrozen; // Row freeze: use width after freeze + if (content_max_x > column->ClipRect.Max.x) + continue; + } + + const int merge_group_n = (has_freeze_h && column_n < table->FreezeColumnsCount ? 0 : 1) + (has_freeze_v && merge_group_sub_n == 0 ? 0 : 2); + IM_ASSERT(channel_no < IMGUI_TABLE_MAX_DRAW_CHANNELS); + MergeGroup* merge_group = &merge_groups[merge_group_n]; + if (merge_group->ChannelsCount == 0) + merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); + merge_group->ChannelsMask.SetBit(channel_no); + merge_group->ChannelsCount++; + merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect); + merge_group_mask |= (1 << merge_group_n); + } + + // Invalidate current draw channel + // (we don't clear DrawChannelFrozen/DrawChannelUnfrozen solely to facilitate debugging/later inspection of data) + column->DrawChannelCurrent = (ImGuiTableDrawChannelIdx)-1; + } + + // [DEBUG] Display merge groups +#if 0 + if (g.IO.KeyShift) + for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++) + { + MergeGroup* merge_group = &merge_groups[merge_group_n]; + if (merge_group->ChannelsCount == 0) + continue; + char buf[32]; + ImFormatString(buf, 32, "MG%d:%d", merge_group_n, merge_group->ChannelsCount); + ImVec2 text_pos = merge_group->ClipRect.Min + ImVec2(4, 4); + ImVec2 text_size = CalcTextSize(buf, NULL); + GetForegroundDrawList()->AddRectFilled(text_pos, text_pos + text_size, IM_COL32(0, 0, 0, 255)); + GetForegroundDrawList()->AddText(text_pos, IM_COL32(255, 255, 0, 255), buf, NULL); + GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 255, 0, 255)); + } +#endif + + // 2. Rewrite channel list in our preferred order + if (merge_group_mask != 0) + { + // We skip channel 0 (Bg0/Bg1) and 1 (Bg2 frozen) from the shuffling since they won't move - see channels allocation in TableSetupDrawChannels(). + const int LEADING_DRAW_CHANNELS = 2; + g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - LEADING_DRAW_CHANNELS); // Use shared temporary storage so the allocation gets amortized + ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data; + ImBitArray remaining_mask; // We need 132-bit of storage + remaining_mask.SetBitRange(LEADING_DRAW_CHANNELS, splitter->_Count); + remaining_mask.ClearBit(table->Bg2DrawChannelUnfrozen); + IM_ASSERT(has_freeze_v == false || table->Bg2DrawChannelUnfrozen != TABLE_DRAW_CHANNEL_BG2_FROZEN); + int remaining_count = splitter->_Count - (has_freeze_v ? LEADING_DRAW_CHANNELS + 1 : LEADING_DRAW_CHANNELS); + //ImRect host_rect = (table->InnerWindow == table->OuterWindow) ? table->InnerClipRect : table->HostClipRect; + ImRect host_rect = table->HostClipRect; + for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++) + { + if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount) + { + MergeGroup* merge_group = &merge_groups[merge_group_n]; + ImRect merge_clip_rect = merge_group->ClipRect; + + // Extend outer-most clip limits to match those of host, so draw calls can be merged even if + // outer-most columns have some outer padding offsetting them from their parent ClipRect. + // The principal cases this is dealing with are: + // - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge + // - Columns can use padding and have left-most ClipRect.Min.x and right-most ClipRect.Max.x != from host ClipRect -> will extend and match host ClipRect -> will merge + // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit + // within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect. + if ((merge_group_n & 1) == 0 || !has_freeze_h) + merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x); + if ((merge_group_n & 2) == 0 || !has_freeze_v) + merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, host_rect.Min.y); + if ((merge_group_n & 1) != 0) + merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, host_rect.Max.x); + if ((merge_group_n & 2) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0) + merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y); +#if 0 + GetOverlayDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, 0, 1.0f); + GetOverlayDrawList()->AddLine(merge_group->ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200)); + GetOverlayDrawList()->AddLine(merge_group->ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200)); +#endif + remaining_count -= merge_group->ChannelsCount; + for (int n = 0; n < IM_ARRAYSIZE(remaining_mask.Storage); n++) + remaining_mask.Storage[n] &= ~merge_group->ChannelsMask.Storage[n]; + for (int n = 0; n < splitter->_Count && merge_channels_count != 0; n++) + { + // Copy + overwrite new clip rect + if (!merge_group->ChannelsMask.TestBit(n)) + continue; + merge_group->ChannelsMask.ClearBit(n); + merge_channels_count--; + + ImDrawChannel* channel = &splitter->_Channels[n]; + IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect))); + channel->_CmdBuffer[0].ClipRect = merge_clip_rect.ToVec4(); + memcpy(dst_tmp++, channel, sizeof(ImDrawChannel)); + } + } + + // Make sure Bg2DrawChannelUnfrozen appears in the middle of our groups (whereas Bg0/Bg1 and Bg2 frozen are fixed to 0 and 1) + if (merge_group_n == 1 && has_freeze_v) + memcpy(dst_tmp++, &splitter->_Channels[table->Bg2DrawChannelUnfrozen], sizeof(ImDrawChannel)); + } + + // Append unmergeable channels that we didn't reorder at the end of the list + for (int n = 0; n < splitter->_Count && remaining_count != 0; n++) + { + if (!remaining_mask.TestBit(n)) + continue; + ImDrawChannel* channel = &splitter->_Channels[n]; + memcpy(dst_tmp++, channel, sizeof(ImDrawChannel)); + remaining_count--; + } + IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size); + memcpy(splitter->_Channels.Data + LEADING_DRAW_CHANNELS, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - LEADING_DRAW_CHANNELS) * sizeof(ImDrawChannel)); + } +} + +// FIXME-TABLE: This is a mess, need to redesign how we render borders (as some are also done in TableEndRow) +void ImGui::TableDrawBorders(ImGuiTable* table) +{ + ImGuiWindow* inner_window = table->InnerWindow; + if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect)) + return; + + ImDrawList* inner_drawlist = inner_window->DrawList; + table->DrawSplitter->SetCurrentChannel(inner_drawlist, TABLE_DRAW_CHANNEL_BG0); + inner_drawlist->PushClipRect(table->Bg0ClipRectForDrawCmd.Min, table->Bg0ClipRectForDrawCmd.Max, false); + + // Draw inner border and resizing feedback + ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); + const float border_size = TABLE_BORDER_SIZE; + const float draw_y1 = table->InnerRect.Min.y; + const float draw_y2_body = table->InnerRect.Max.y; + const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastFirstRowHeight) : draw_y1; + if (table->Flags & ImGuiTableFlags_BordersInnerV) + { + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n))) + continue; + + const int column_n = table->DisplayOrderToIndex[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + const bool is_hovered = (table->HoveredColumnBorder == column_n); + const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent); + const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0; + const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1); + if (column->MaxX > table->InnerClipRect.Max.x && !is_resized) + continue; + + // Decide whether right-most column is visible + if (column->NextEnabledColumn == -1 && !is_resizable) + if ((table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame || (table->Flags & ImGuiTableFlags_NoHostExtendX)) + continue; + if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. + continue; + + // Draw in outer window so right-most column won't be clipped + // Always draw full height border when being resized/hovered, or on the delimitation of frozen column scrolling. + ImU32 col; + float draw_y2; + if (is_hovered || is_resized || is_frozen_separator) + { + draw_y2 = draw_y2_body; + col = is_resized ? GetColorU32(ImGuiCol_SeparatorActive) : is_hovered ? GetColorU32(ImGuiCol_SeparatorHovered) : table->BorderColorStrong; + } + else + { + draw_y2 = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? draw_y2_head : draw_y2_body; + col = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? table->BorderColorStrong : table->BorderColorLight; + } + + if (draw_y2 > draw_y1) + inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, border_size); + } + } + + // Draw outer border + // FIXME: could use AddRect or explicit VLine/HLine helper? + if (table->Flags & ImGuiTableFlags_BordersOuter) + { + // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call + // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their + // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part + // of it in inner window, and the part that's over scrollbars in the outer window..) + // Either solution currently won't allow us to use a larger border size: the border would clipped. + const ImRect outer_border = table->OuterRect; + const ImU32 outer_col = table->BorderColorStrong; + if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) + { + inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, 0, border_size); + } + else if (table->Flags & ImGuiTableFlags_BordersOuterV) + { + inner_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Min.x, outer_border.Max.y), outer_col, border_size); + inner_drawlist->AddLine(ImVec2(outer_border.Max.x, outer_border.Min.y), outer_border.Max, outer_col, border_size); + } + else if (table->Flags & ImGuiTableFlags_BordersOuterH) + { + inner_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Max.x, outer_border.Min.y), outer_col, border_size); + inner_drawlist->AddLine(ImVec2(outer_border.Min.x, outer_border.Max.y), outer_border.Max, outer_col, border_size); + } + } + if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y) + { + // Draw bottom-most row border + const float border_y = table->RowPosY2; + if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y) + inner_drawlist->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderColorLight, border_size); + } + + inner_drawlist->PopClipRect(); +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Sorting +//------------------------------------------------------------------------- +// - TableGetSortSpecs() +// - TableFixColumnSortDirection() [Internal] +// - TableGetColumnNextSortDirection() [Internal] +// - TableSetColumnSortDirection() [Internal] +// - TableSortSpecsSanitize() [Internal] +// - TableSortSpecsBuild() [Internal] +//------------------------------------------------------------------------- + +// Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set) +// You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since +// last call, or the first time. +// Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()! +ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL); + + if (!(table->Flags & ImGuiTableFlags_Sortable)) + return NULL; + + // Require layout (in case TableHeadersRow() hasn't been called) as it may alter IsSortSpecsDirty in some paths. + if (!table->IsLayoutLocked) + TableUpdateLayout(table); + + TableSortSpecsBuild(table); + + return &table->SortSpecs; +} + +static inline ImGuiSortDirection TableGetColumnAvailSortDirection(ImGuiTableColumn* column, int n) +{ + IM_ASSERT(n < column->SortDirectionsAvailCount); + return (column->SortDirectionsAvailList >> (n << 1)) & 0x03; +} + +// Fix sort direction if currently set on a value which is unavailable (e.g. activating NoSortAscending/NoSortDescending) +void ImGui::TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column) +{ + if (column->SortOrder == -1 || (column->SortDirectionsAvailMask & (1 << column->SortDirection)) != 0) + return; + column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0); + table->IsSortSpecsDirty = true; +} + +// Calculate next sort direction that would be set after clicking the column +// - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click. +// - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op. +IM_STATIC_ASSERT(ImGuiSortDirection_None == 0 && ImGuiSortDirection_Ascending == 1 && ImGuiSortDirection_Descending == 2); +ImGuiSortDirection ImGui::TableGetColumnNextSortDirection(ImGuiTableColumn* column) +{ + IM_ASSERT(column->SortDirectionsAvailCount > 0); + if (column->SortOrder == -1) + return TableGetColumnAvailSortDirection(column, 0); + for (int n = 0; n < 3; n++) + if (column->SortDirection == TableGetColumnAvailSortDirection(column, n)) + return TableGetColumnAvailSortDirection(column, (n + 1) % column->SortDirectionsAvailCount); + IM_ASSERT(0); + return ImGuiSortDirection_None; +} + +// Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert +// the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code. +void ImGui::TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + if (!(table->Flags & ImGuiTableFlags_SortMulti)) + append_to_sort_specs = false; + if (!(table->Flags & ImGuiTableFlags_SortTristate)) + IM_ASSERT(sort_direction != ImGuiSortDirection_None); + + ImGuiTableColumnIdx sort_order_max = 0; + if (append_to_sort_specs) + for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) + sort_order_max = ImMax(sort_order_max, table->Columns[other_column_n].SortOrder); + + ImGuiTableColumn* column = &table->Columns[column_n]; + column->SortDirection = (ImU8)sort_direction; + if (column->SortDirection == ImGuiSortDirection_None) + column->SortOrder = -1; + else if (column->SortOrder == -1 || !append_to_sort_specs) + column->SortOrder = append_to_sort_specs ? sort_order_max + 1 : 0; + + for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) + { + ImGuiTableColumn* other_column = &table->Columns[other_column_n]; + if (other_column != column && !append_to_sort_specs) + other_column->SortOrder = -1; + TableFixColumnSortDirection(table, other_column); + } + table->IsSettingsDirty = true; + table->IsSortSpecsDirty = true; +} + +void ImGui::TableSortSpecsSanitize(ImGuiTable* table) +{ + IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable); + + // Clear SortOrder from hidden column and verify that there's no gap or duplicate. + int sort_order_count = 0; + ImU64 sort_order_mask = 0x00; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->SortOrder != -1 && !column->IsEnabled) + column->SortOrder = -1; + if (column->SortOrder == -1) + continue; + sort_order_count++; + sort_order_mask |= ((ImU64)1 << column->SortOrder); + IM_ASSERT(sort_order_count < (int)sizeof(sort_order_mask) * 8); + } + + const bool need_fix_linearize = ((ImU64)1 << sort_order_count) != (sort_order_mask + 1); + const bool need_fix_single_sort_order = (sort_order_count > 1) && !(table->Flags & ImGuiTableFlags_SortMulti); + if (need_fix_linearize || need_fix_single_sort_order) + { + ImU64 fixed_mask = 0x00; + for (int sort_n = 0; sort_n < sort_order_count; sort_n++) + { + // Fix: Rewrite sort order fields if needed so they have no gap or duplicate. + // (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1) + int column_with_smallest_sort_order = -1; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if ((fixed_mask & ((ImU64)1 << (ImU64)column_n)) == 0 && table->Columns[column_n].SortOrder != -1) + if (column_with_smallest_sort_order == -1 || table->Columns[column_n].SortOrder < table->Columns[column_with_smallest_sort_order].SortOrder) + column_with_smallest_sort_order = column_n; + IM_ASSERT(column_with_smallest_sort_order != -1); + fixed_mask |= ((ImU64)1 << column_with_smallest_sort_order); + table->Columns[column_with_smallest_sort_order].SortOrder = (ImGuiTableColumnIdx)sort_n; + + // Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set. + if (need_fix_single_sort_order) + { + sort_order_count = 1; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if (column_n != column_with_smallest_sort_order) + table->Columns[column_n].SortOrder = -1; + break; + } + } + } + + // Fallback default sort order (if no column had the ImGuiTableColumnFlags_DefaultSort flag) + if (sort_order_count == 0 && !(table->Flags & ImGuiTableFlags_SortTristate)) + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_NoSort)) + { + sort_order_count = 1; + column->SortOrder = 0; + column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0); + break; + } + } + + table->SortSpecsCount = (ImGuiTableColumnIdx)sort_order_count; +} + +void ImGui::TableSortSpecsBuild(ImGuiTable* table) +{ + bool dirty = table->IsSortSpecsDirty; + if (dirty) + { + TableSortSpecsSanitize(table); + table->SortSpecsMulti.resize(table->SortSpecsCount <= 1 ? 0 : table->SortSpecsCount); + table->SortSpecs.SpecsDirty = true; // Mark as dirty for user + table->IsSortSpecsDirty = false; // Mark as not dirty for us + } + + // Write output + ImGuiTableColumnSortSpecs* sort_specs = (table->SortSpecsCount == 0) ? NULL : (table->SortSpecsCount == 1) ? &table->SortSpecsSingle : table->SortSpecsMulti.Data; + if (dirty && sort_specs != NULL) + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->SortOrder == -1) + continue; + IM_ASSERT(column->SortOrder < table->SortSpecsCount); + ImGuiTableColumnSortSpecs* sort_spec = &sort_specs[column->SortOrder]; + sort_spec->ColumnUserID = column->UserID; + sort_spec->ColumnIndex = (ImGuiTableColumnIdx)column_n; + sort_spec->SortOrder = (ImGuiTableColumnIdx)column->SortOrder; + sort_spec->SortDirection = column->SortDirection; + } + + table->SortSpecs.Specs = sort_specs; + table->SortSpecs.SpecsCount = table->SortSpecsCount; +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Headers +//------------------------------------------------------------------------- +// - TableGetHeaderRowHeight() [Internal] +// - TableHeadersRow() +// - TableHeader() +//------------------------------------------------------------------------- + +float ImGui::TableGetHeaderRowHeight() +{ + // Caring for a minor edge case: + // Calculate row height, for the unlikely case that some labels may be taller than others. + // If we didn't do that, uneven header height would highlight but smaller one before the tallest wouldn't catch input for all height. + // In your custom header row you may omit this all together and just call TableNextRow() without a height... + float row_height = GetTextLineHeight(); + int columns_count = TableGetColumnCount(); + for (int column_n = 0; column_n < columns_count; column_n++) + { + ImGuiTableColumnFlags flags = TableGetColumnFlags(column_n); + if ((flags & ImGuiTableColumnFlags_IsEnabled) && !(flags & ImGuiTableColumnFlags_NoHeaderLabel)) + row_height = ImMax(row_height, CalcTextSize(TableGetColumnName(column_n)).y); + } + row_height += GetStyle().CellPadding.y * 2.0f; + return row_height; +} + +// [Public] This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). +// The intent is that advanced users willing to create customized headers would not need to use this helper +// and can create their own! For example: TableHeader() may be preceeded by Checkbox() or other custom widgets. +// See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this. +// This code is constructed to not make much use of internal functions, as it is intended to be a template to copy. +// FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public. +void ImGui::TableHeadersRow() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL && "Need to call TableHeadersRow() after BeginTable()!"); + + // Layout if not already done (this is automatically done by TableNextRow, we do it here solely to facilitate stepping in debugger as it is frequent to step in TableUpdateLayout) + if (!table->IsLayoutLocked) + TableUpdateLayout(table); + + // Open row + const float row_y1 = GetCursorScreenPos().y; + const float row_height = TableGetHeaderRowHeight(); + TableNextRow(ImGuiTableRowFlags_Headers, row_height); + if (table->HostSkipItems) // Merely an optimization, you may skip in your own code. + return; + + const int columns_count = TableGetColumnCount(); + for (int column_n = 0; column_n < columns_count; column_n++) + { + if (!TableSetColumnIndex(column_n)) + continue; + + // Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them) + // - in your own code you may omit the PushID/PopID all-together, provided you know they won't collide + // - table->InstanceCurrent is only >0 when we use multiple BeginTable/EndTable calls with same identifier. + const char* name = (TableGetColumnFlags(column_n) & ImGuiTableColumnFlags_NoHeaderLabel) ? "" : TableGetColumnName(column_n); + PushID(table->InstanceCurrent * table->ColumnsCount + column_n); + TableHeader(name); + PopID(); + } + + // Allow opening popup from the right-most section after the last column. + ImVec2 mouse_pos = ImGui::GetMousePos(); + if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count) + if (mouse_pos.y >= row_y1 && mouse_pos.y < row_y1 + row_height) + TableOpenContextMenu(-1); // Will open a non-column-specific popup. +} + +// Emit a column header (text + optional sort order) +// We cpu-clip text here so that all columns headers can be merged into a same draw call. +// Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader() +void ImGui::TableHeader(const char* label) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL && "Need to call TableHeader() after BeginTable()!"); + IM_ASSERT(table->CurrentColumn != -1); + const int column_n = table->CurrentColumn; + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Label + if (label == NULL) + label = ""; + const char* label_end = FindRenderedTextEnd(label); + ImVec2 label_size = CalcTextSize(label, label_end, true); + ImVec2 label_pos = window->DC.CursorPos; + + // If we already got a row height, there's use that. + // FIXME-TABLE: Padding problem if the correct outer-padding CellBgRect strays off our ClipRect? + ImRect cell_r = TableGetCellBgRect(table, column_n); + float label_height = ImMax(label_size.y, table->RowMinHeight - table->CellPaddingY * 2.0f); + + // Calculate ideal size for sort order arrow + float w_arrow = 0.0f; + float w_sort_text = 0.0f; + char sort_order_suf[4] = ""; + const float ARROW_SCALE = 0.65f; + if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort)) + { + w_arrow = ImFloor(g.FontSize * ARROW_SCALE + g.Style.FramePadding.x); + if (column->SortOrder > 0) + { + ImFormatString(sort_order_suf, IM_ARRAYSIZE(sort_order_suf), "%d", column->SortOrder + 1); + w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x; + } + } + + // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering for merging. + float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow; + column->ContentMaxXHeadersUsed = ImMax(column->ContentMaxXHeadersUsed, column->WorkMaxX); + column->ContentMaxXHeadersIdeal = ImMax(column->ContentMaxXHeadersIdeal, max_pos_x); + + // Keep header highlighted when context menu is open. + const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceCurrent); + ImGuiID id = window->GetID(label); + ImRect bb(cell_r.Min.x, cell_r.Min.y, cell_r.Max.x, ImMax(cell_r.Max.y, cell_r.Min.y + label_height + g.Style.CellPadding.y * 2.0f)); + ItemSize(ImVec2(0.0f, label_height)); // Don't declare unclipped width, it'll be fed ContentMaxPosHeadersIdeal + if (!ItemAdd(bb, id)) + return; + + //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG] + //GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG] + + // Using AllowItemOverlap mode because we cover the whole cell, and we want user to be able to submit subsequent items. + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_AllowItemOverlap); + if (g.ActiveId != id) + SetItemAllowOverlap(); + if (held || hovered || selected) + { + const ImU32 col = GetColorU32(held ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + //RenderFrame(bb.Min, bb.Max, col, false, 0.0f); + TableSetBgColor(ImGuiTableBgTarget_CellBg, col, table->CurrentColumn); + } + else + { + // Submit single cell bg color in the case we didn't submit a full header row + if ((table->RowFlags & ImGuiTableRowFlags_Headers) == 0) + TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_TableHeaderBg), table->CurrentColumn); + } + RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding); + if (held) + table->HeldHeaderColumn = (ImGuiTableColumnIdx)column_n; + window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f; + + // Drag and drop to re-order columns. + // FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone. + if (held && (table->Flags & ImGuiTableFlags_Reorderable) && IsMouseDragging(0) && !g.DragDropActive) + { + // While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x + table->ReorderColumn = (ImGuiTableColumnIdx)column_n; + table->InstanceInteracted = table->InstanceCurrent; + + // We don't reorder: through the frozen<>unfrozen line, or through a column that is marked with ImGuiTableColumnFlags_NoReorder. + if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x) + if (ImGuiTableColumn* prev_column = (column->PrevEnabledColumn != -1) ? &table->Columns[column->PrevEnabledColumn] : NULL) + if (!((column->Flags | prev_column->Flags) & ImGuiTableColumnFlags_NoReorder)) + if ((column->IndexWithinEnabledSet < table->FreezeColumnsRequest) == (prev_column->IndexWithinEnabledSet < table->FreezeColumnsRequest)) + table->ReorderColumnDir = -1; + if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x) + if (ImGuiTableColumn* next_column = (column->NextEnabledColumn != -1) ? &table->Columns[column->NextEnabledColumn] : NULL) + if (!((column->Flags | next_column->Flags) & ImGuiTableColumnFlags_NoReorder)) + if ((column->IndexWithinEnabledSet < table->FreezeColumnsRequest) == (next_column->IndexWithinEnabledSet < table->FreezeColumnsRequest)) + table->ReorderColumnDir = +1; + } + + // Sort order arrow + const float ellipsis_max = cell_r.Max.x - w_arrow - w_sort_text; + if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort)) + { + if (column->SortOrder != -1) + { + float x = ImMax(cell_r.Min.x, cell_r.Max.x - w_arrow - w_sort_text); + float y = label_pos.y; + if (column->SortOrder > 0) + { + PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text, 0.70f)); + RenderText(ImVec2(x + g.Style.ItemInnerSpacing.x, y), sort_order_suf); + PopStyleColor(); + x += w_sort_text; + } + RenderArrow(window->DrawList, ImVec2(x, y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE); + } + + // Handle clicking on column header to adjust Sort Order + if (pressed && table->ReorderColumn != column_n) + { + ImGuiSortDirection sort_direction = TableGetColumnNextSortDirection(column); + TableSetColumnSortDirection(column_n, sort_direction, g.IO.KeyShift); + } + } + + // Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will + // be merged into a single draw call. + //window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE); + RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, label_pos.y + label_height + g.Style.FramePadding.y), ellipsis_max, ellipsis_max, label, label_end, &label_size); + + const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x); + if (text_clipped && hovered && g.HoveredIdNotActiveTimer > g.TooltipSlowDelay) + SetTooltip("%.*s", (int)(label_end - label), label); + + // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden + if (IsMouseReleased(1) && IsItemHovered()) + TableOpenContextMenu(column_n); +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Context Menu +//------------------------------------------------------------------------- +// - TableOpenContextMenu() [Internal] +// - TableDrawContextMenu() [Internal] +//------------------------------------------------------------------------- + +// Use -1 to open menu not specific to a given column. +void ImGui::TableOpenContextMenu(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (column_n == -1 && table->CurrentColumn != -1) // When called within a column automatically use this one (for consistency) + column_n = table->CurrentColumn; + if (column_n == table->ColumnsCount) // To facilitate using with TableGetHoveredColumn() + column_n = -1; + IM_ASSERT(column_n >= -1 && column_n < table->ColumnsCount); + if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + { + table->IsContextPopupOpen = true; + table->ContextPopupColumn = (ImGuiTableColumnIdx)column_n; + table->InstanceInteracted = table->InstanceCurrent; + const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID); + OpenPopupEx(context_menu_id, ImGuiPopupFlags_None); + } +} + +// Output context menu into current window (generally a popup) +// FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data? +void ImGui::TableDrawContextMenu(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + bool want_separator = false; + const int column_n = (table->ContextPopupColumn >= 0 && table->ContextPopupColumn < table->ColumnsCount) ? table->ContextPopupColumn : -1; + ImGuiTableColumn* column = (column_n != -1) ? &table->Columns[column_n] : NULL; + + // Sizing + if (table->Flags & ImGuiTableFlags_Resizable) + { + if (column != NULL) + { + const bool can_resize = !(column->Flags & ImGuiTableColumnFlags_NoResize) && column->IsEnabled; + if (MenuItem("Size column to fit###SizeOne", NULL, false, can_resize)) + TableSetColumnWidthAutoSingle(table, column_n); + } + + const char* size_all_desc; + if (table->ColumnsEnabledFixedCount == table->ColumnsEnabledCount && (table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame) + size_all_desc = "Size all columns to fit###SizeAll"; // All fixed + else + size_all_desc = "Size all columns to default###SizeAll"; // All stretch or mixed + if (MenuItem(size_all_desc, NULL)) + TableSetColumnWidthAutoAll(table); + want_separator = true; + } + + // Ordering + if (table->Flags & ImGuiTableFlags_Reorderable) + { + if (MenuItem("Reset order", NULL, false, !table->IsDefaultDisplayOrder)) + table->IsResetDisplayOrderRequest = true; + want_separator = true; + } + + // Reset all (should work but seems unnecessary/noisy to expose?) + //if (MenuItem("Reset all")) + // table->IsResetAllRequest = true; + + // Sorting + // (modify TableOpenContextMenu() to add _Sortable flag if enabling this) +#if 0 + if ((table->Flags & ImGuiTableFlags_Sortable) && column != NULL && (column->Flags & ImGuiTableColumnFlags_NoSort) == 0) + { + if (want_separator) + Separator(); + want_separator = true; + + bool append_to_sort_specs = g.IO.KeyShift; + if (MenuItem("Sort in Ascending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Ascending, (column->Flags & ImGuiTableColumnFlags_NoSortAscending) == 0)) + TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Ascending, append_to_sort_specs); + if (MenuItem("Sort in Descending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Descending, (column->Flags & ImGuiTableColumnFlags_NoSortDescending) == 0)) + TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Descending, append_to_sort_specs); + } +#endif + + // Hiding / Visibility + if (table->Flags & ImGuiTableFlags_Hideable) + { + if (want_separator) + Separator(); + want_separator = true; + + PushItemFlag(ImGuiItemFlags_SelectableDontClosePopup, true); + for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) + { + ImGuiTableColumn* other_column = &table->Columns[other_column_n]; + if (other_column->Flags & ImGuiTableColumnFlags_Disabled) + continue; + + const char* name = TableGetColumnName(table, other_column_n); + if (name == NULL || name[0] == 0) + name = ""; + + // Make sure we can't hide the last active column + bool menu_item_active = (other_column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true; + if (other_column->IsUserEnabled && table->ColumnsEnabledCount <= 1) + menu_item_active = false; + if (MenuItem(name, NULL, other_column->IsUserEnabled, menu_item_active)) + other_column->IsUserEnabledNextFrame = !other_column->IsUserEnabled; + } + PopItemFlag(); + } +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Settings (.ini data) +//------------------------------------------------------------------------- +// FIXME: The binding/finding/creating flow are too confusing. +//------------------------------------------------------------------------- +// - TableSettingsInit() [Internal] +// - TableSettingsCalcChunkSize() [Internal] +// - TableSettingsCreate() [Internal] +// - TableSettingsFindByID() [Internal] +// - TableGetBoundSettings() [Internal] +// - TableResetSettings() +// - TableSaveSettings() [Internal] +// - TableLoadSettings() [Internal] +// - TableSettingsHandler_ClearAll() [Internal] +// - TableSettingsHandler_ApplyAll() [Internal] +// - TableSettingsHandler_ReadOpen() [Internal] +// - TableSettingsHandler_ReadLine() [Internal] +// - TableSettingsHandler_WriteAll() [Internal] +// - TableSettingsInstallHandler() [Internal] +//------------------------------------------------------------------------- +// [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings. +// [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table. +// [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty. +// [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file. +//------------------------------------------------------------------------- + +// Clear and initialize empty settings instance +static void TableSettingsInit(ImGuiTableSettings* settings, ImGuiID id, int columns_count, int columns_count_max) +{ + IM_PLACEMENT_NEW(settings) ImGuiTableSettings(); + ImGuiTableColumnSettings* settings_column = settings->GetColumnSettings(); + for (int n = 0; n < columns_count_max; n++, settings_column++) + IM_PLACEMENT_NEW(settings_column) ImGuiTableColumnSettings(); + settings->ID = id; + settings->ColumnsCount = (ImGuiTableColumnIdx)columns_count; + settings->ColumnsCountMax = (ImGuiTableColumnIdx)columns_count_max; + settings->WantApply = true; +} + +static size_t TableSettingsCalcChunkSize(int columns_count) +{ + return sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings); +} + +ImGuiTableSettings* ImGui::TableSettingsCreate(ImGuiID id, int columns_count) +{ + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(TableSettingsCalcChunkSize(columns_count)); + TableSettingsInit(settings, id, columns_count, columns_count); + return settings; +} + +// Find existing settings +ImGuiTableSettings* ImGui::TableSettingsFindByID(ImGuiID id) +{ + // FIXME-OPT: Might want to store a lookup map for this? + ImGuiContext& g = *GImGui; + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + if (settings->ID == id) + return settings; + return NULL; +} + +// Get settings for a given table, NULL if none +ImGuiTableSettings* ImGui::TableGetBoundSettings(ImGuiTable* table) +{ + if (table->SettingsOffset != -1) + { + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset); + IM_ASSERT(settings->ID == table->ID); + if (settings->ColumnsCountMax >= table->ColumnsCount) + return settings; // OK + settings->ID = 0; // Invalidate storage, we won't fit because of a count change + } + return NULL; +} + +// Restore initial state of table (with or without saved settings) +void ImGui::TableResetSettings(ImGuiTable* table) +{ + table->IsInitializing = table->IsSettingsDirty = true; + table->IsResetAllRequest = false; + table->IsSettingsRequestLoad = false; // Don't reload from ini + table->SettingsLoadedFlags = ImGuiTableFlags_None; // Mark as nothing loaded so our initialized data becomes authoritative +} + +void ImGui::TableSaveSettings(ImGuiTable* table) +{ + table->IsSettingsDirty = false; + if (table->Flags & ImGuiTableFlags_NoSavedSettings) + return; + + // Bind or create settings data + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = TableGetBoundSettings(table); + if (settings == NULL) + { + settings = TableSettingsCreate(table->ID, table->ColumnsCount); + table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings); + } + settings->ColumnsCount = (ImGuiTableColumnIdx)table->ColumnsCount; + + // Serialize ImGuiTable/ImGuiTableColumn into ImGuiTableSettings/ImGuiTableColumnSettings + IM_ASSERT(settings->ID == table->ID); + IM_ASSERT(settings->ColumnsCount == table->ColumnsCount && settings->ColumnsCountMax >= settings->ColumnsCount); + ImGuiTableColumn* column = table->Columns.Data; + ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); + + bool save_ref_scale = false; + settings->SaveFlags = ImGuiTableFlags_None; + for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++) + { + const float width_or_weight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? column->StretchWeight : column->WidthRequest; + column_settings->WidthOrWeight = width_or_weight; + column_settings->Index = (ImGuiTableColumnIdx)n; + column_settings->DisplayOrder = column->DisplayOrder; + column_settings->SortOrder = column->SortOrder; + column_settings->SortDirection = column->SortDirection; + column_settings->IsEnabled = column->IsUserEnabled; + column_settings->IsStretch = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0; + if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) == 0) + save_ref_scale = true; + + // We skip saving some data in the .ini file when they are unnecessary to restore our state. + // Note that fixed width where initial width was derived from auto-fit will always be saved as InitStretchWeightOrWidth will be 0.0f. + // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present. + if (width_or_weight != column->InitStretchWeightOrWidth) + settings->SaveFlags |= ImGuiTableFlags_Resizable; + if (column->DisplayOrder != n) + settings->SaveFlags |= ImGuiTableFlags_Reorderable; + if (column->SortOrder != -1) + settings->SaveFlags |= ImGuiTableFlags_Sortable; + if (column->IsUserEnabled != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0)) + settings->SaveFlags |= ImGuiTableFlags_Hideable; + } + settings->SaveFlags &= table->Flags; + settings->RefScale = save_ref_scale ? table->RefScale : 0.0f; + + MarkIniSettingsDirty(); +} + +void ImGui::TableLoadSettings(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + table->IsSettingsRequestLoad = false; + if (table->Flags & ImGuiTableFlags_NoSavedSettings) + return; + + // Bind settings + ImGuiTableSettings* settings; + if (table->SettingsOffset == -1) + { + settings = TableSettingsFindByID(table->ID); + if (settings == NULL) + return; + if (settings->ColumnsCount != table->ColumnsCount) // Allow settings if columns count changed. We could otherwise decide to return... + table->IsSettingsDirty = true; + table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings); + } + else + { + settings = TableGetBoundSettings(table); + } + + table->SettingsLoadedFlags = settings->SaveFlags; + table->RefScale = settings->RefScale; + + // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn + ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); + ImU64 display_order_mask = 0; + for (int data_n = 0; data_n < settings->ColumnsCount; data_n++, column_settings++) + { + int column_n = column_settings->Index; + if (column_n < 0 || column_n >= table->ColumnsCount) + continue; + + ImGuiTableColumn* column = &table->Columns[column_n]; + if (settings->SaveFlags & ImGuiTableFlags_Resizable) + { + if (column_settings->IsStretch) + column->StretchWeight = column_settings->WidthOrWeight; + else + column->WidthRequest = column_settings->WidthOrWeight; + column->AutoFitQueue = 0x00; + } + if (settings->SaveFlags & ImGuiTableFlags_Reorderable) + column->DisplayOrder = column_settings->DisplayOrder; + else + column->DisplayOrder = (ImGuiTableColumnIdx)column_n; + display_order_mask |= (ImU64)1 << column->DisplayOrder; + column->IsUserEnabled = column->IsUserEnabledNextFrame = column_settings->IsEnabled; + column->SortOrder = column_settings->SortOrder; + column->SortDirection = column_settings->SortDirection; + } + + // Validate and fix invalid display order data + const ImU64 expected_display_order_mask = (settings->ColumnsCount == 64) ? ~0 : ((ImU64)1 << settings->ColumnsCount) - 1; + if (display_order_mask != expected_display_order_mask) + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + table->Columns[column_n].DisplayOrder = (ImGuiTableColumnIdx)column_n; + + // Rebuild index + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n; +} + +static void TableSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (int i = 0; i != g.Tables.GetMapSize(); i++) + if (ImGuiTable* table = g.Tables.TryGetMapData(i)) + table->SettingsOffset = -1; + g.SettingsTables.clear(); +} + +// Apply to existing windows (if any) +static void TableSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (int i = 0; i != g.Tables.GetMapSize(); i++) + if (ImGuiTable* table = g.Tables.TryGetMapData(i)) + { + table->IsSettingsRequestLoad = true; + table->SettingsOffset = -1; + } +} + +static void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) +{ + ImGuiID id = 0; + int columns_count = 0; + if (sscanf(name, "0x%08X,%d", &id, &columns_count) < 2) + return NULL; + + if (ImGuiTableSettings* settings = ImGui::TableSettingsFindByID(id)) + { + if (settings->ColumnsCountMax >= columns_count) + { + TableSettingsInit(settings, id, columns_count, settings->ColumnsCountMax); // Recycle + return settings; + } + settings->ID = 0; // Invalidate storage, we won't fit because of a count change + } + return ImGui::TableSettingsCreate(id, columns_count); +} + +static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) +{ + // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" + ImGuiTableSettings* settings = (ImGuiTableSettings*)entry; + float f = 0.0f; + int column_n = 0, r = 0, n = 0; + + if (sscanf(line, "RefScale=%f", &f) == 1) { settings->RefScale = f; return; } + + if (sscanf(line, "Column %d%n", &column_n, &r) == 1) + { + if (column_n < 0 || column_n >= settings->ColumnsCount) + return; + line = ImStrSkipBlank(line + r); + char c = 0; + ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n; + column->Index = (ImGuiTableColumnIdx)column_n; + if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r)==1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; } + if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = (float)n; column->IsStretch = 0; settings->SaveFlags |= ImGuiTableFlags_Resizable; } + if (sscanf(line, "Weight=%f%n", &f, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = f; column->IsStretch = 1; settings->SaveFlags |= ImGuiTableFlags_Resizable; } + if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->IsEnabled = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; } + if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImGuiTableColumnIdx)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; } + if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImGuiTableColumnIdx)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; } + } +} + +static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) +{ + ImGuiContext& g = *ctx; + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + { + if (settings->ID == 0) // Skip ditched settings + continue; + + // TableSaveSettings() may clear some of those flags when we establish that the data can be stripped + // (e.g. Order was unchanged) + const bool save_size = (settings->SaveFlags & ImGuiTableFlags_Resizable) != 0; + const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0; + const bool save_order = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0; + const bool save_sort = (settings->SaveFlags & ImGuiTableFlags_Sortable) != 0; + if (!save_size && !save_visible && !save_order && !save_sort) + continue; + + buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve + buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount); + if (settings->RefScale != 0.0f) + buf->appendf("RefScale=%g\n", settings->RefScale); + ImGuiTableColumnSettings* column = settings->GetColumnSettings(); + for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++) + { + // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" + bool save_column = column->UserID != 0 || save_size || save_visible || save_order || (save_sort && column->SortOrder != -1); + if (!save_column) + continue; + buf->appendf("Column %-2d", column_n); + if (column->UserID != 0) buf->appendf(" UserID=%08X", column->UserID); + if (save_size && column->IsStretch) buf->appendf(" Weight=%.4f", column->WidthOrWeight); + if (save_size && !column->IsStretch) buf->appendf(" Width=%d", (int)column->WidthOrWeight); + if (save_visible) buf->appendf(" Visible=%d", column->IsEnabled); + if (save_order) buf->appendf(" Order=%d", column->DisplayOrder); + if (save_sort && column->SortOrder != -1) buf->appendf(" Sort=%d%c", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^'); + buf->append("\n"); + } + buf->append("\n"); + } +} + +void ImGui::TableSettingsAddSettingsHandler() +{ + ImGuiSettingsHandler ini_handler; + ini_handler.TypeName = "Table"; + ini_handler.TypeHash = ImHashStr("Table"); + ini_handler.ClearAllFn = TableSettingsHandler_ClearAll; + ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen; + ini_handler.ReadLineFn = TableSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = TableSettingsHandler_ApplyAll; + ini_handler.WriteAllFn = TableSettingsHandler_WriteAll; + AddSettingsHandler(&ini_handler); +} + +//------------------------------------------------------------------------- +// [SECTION] Tables: Garbage Collection +//------------------------------------------------------------------------- +// - TableRemove() [Internal] +// - TableGcCompactTransientBuffers() [Internal] +// - TableGcCompactSettings() [Internal] +//------------------------------------------------------------------------- + +// Remove Table (currently only used by TestEngine) +void ImGui::TableRemove(ImGuiTable* table) +{ + //IMGUI_DEBUG_LOG("TableRemove() id=0x%08X\n", table->ID); + ImGuiContext& g = *GImGui; + int table_idx = g.Tables.GetIndex(table); + //memset(table->RawData.Data, 0, table->RawData.size_in_bytes()); + //memset(table, 0, sizeof(ImGuiTable)); + g.Tables.Remove(table->ID, table); + g.TablesLastTimeActive[table_idx] = -1.0f; +} + +// Free up/compact internal Table buffers for when it gets unused +void ImGui::TableGcCompactTransientBuffers(ImGuiTable* table) +{ + //IMGUI_DEBUG_LOG("TableGcCompactTransientBuffers() id=0x%08X\n", table->ID); + ImGuiContext& g = *GImGui; + IM_ASSERT(table->MemoryCompacted == false); + table->SortSpecs.Specs = NULL; + table->SortSpecsMulti.clear(); + table->IsSortSpecsDirty = true; // FIXME: shouldn't have to leak into user performing a sort + table->ColumnsNames.clear(); + table->MemoryCompacted = true; + for (int n = 0; n < table->ColumnsCount; n++) + table->Columns[n].NameOffset = -1; + g.TablesLastTimeActive[g.Tables.GetIndex(table)] = -1.0f; +} + +void ImGui::TableGcCompactTransientBuffers(ImGuiTableTempData* temp_data) +{ + temp_data->DrawSplitter.ClearFreeMemory(); + temp_data->LastTimeActive = -1.0f; +} + +// Compact and remove unused settings data (currently only used by TestEngine) +void ImGui::TableGcCompactSettings() +{ + ImGuiContext& g = *GImGui; + int required_memory = 0; + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + if (settings->ID != 0) + required_memory += (int)TableSettingsCalcChunkSize(settings->ColumnsCount); + if (required_memory == g.SettingsTables.Buf.Size) + return; + ImChunkStream new_chunk_stream; + new_chunk_stream.Buf.reserve(required_memory); + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + if (settings->ID != 0) + memcpy(new_chunk_stream.alloc_chunk(TableSettingsCalcChunkSize(settings->ColumnsCount)), settings, TableSettingsCalcChunkSize(settings->ColumnsCount)); + g.SettingsTables.swap(new_chunk_stream); +} + + +//------------------------------------------------------------------------- +// [SECTION] Tables: Debugging +//------------------------------------------------------------------------- +// - DebugNodeTable() [Internal] +//------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_METRICS_WINDOW + +static const char* DebugNodeTableGetSizingPolicyDesc(ImGuiTableFlags sizing_policy) +{ + sizing_policy &= ImGuiTableFlags_SizingMask_; + if (sizing_policy == ImGuiTableFlags_SizingFixedFit) { return "FixedFit"; } + if (sizing_policy == ImGuiTableFlags_SizingFixedSame) { return "FixedSame"; } + if (sizing_policy == ImGuiTableFlags_SizingStretchProp) { return "StretchProp"; } + if (sizing_policy == ImGuiTableFlags_SizingStretchSame) { return "StretchSame"; } + return "N/A"; +} + +void ImGui::DebugNodeTable(ImGuiTable* table) +{ + char buf[512]; + char* p = buf; + const char* buf_end = buf + IM_ARRAYSIZE(buf); + const bool is_active = (table->LastFrameActive >= ImGui::GetFrameCount() - 2); // Note that fully clipped early out scrolling tables will appear as inactive here. + ImFormatString(p, buf_end - p, "Table 0x%08X (%d columns, in '%s')%s", table->ID, table->ColumnsCount, table->OuterWindow->Name, is_active ? "" : " *Inactive*"); + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + bool open = TreeNode(table, "%s", buf); + if (!is_active) { PopStyleColor(); } + if (IsItemHovered()) + GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255)); + if (IsItemVisible() && table->HoveredColumnBody != -1) + GetForegroundDrawList()->AddRect(GetItemRectMin(), GetItemRectMax(), IM_COL32(255, 255, 0, 255)); + if (!open) + return; + if (table->InstanceCurrent > 0) + ImGui::Text("** %d instances of same table! Some data below will refer to last instance.", table->InstanceCurrent + 1); + bool clear_settings = SmallButton("Clear settings"); + BulletText("OuterRect: Pos: (%.1f,%.1f) Size: (%.1f,%.1f) Sizing: '%s'", table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.GetWidth(), table->OuterRect.GetHeight(), DebugNodeTableGetSizingPolicyDesc(table->Flags)); + BulletText("ColumnsGivenWidth: %.1f, ColumnsAutoFitWidth: %.1f, InnerWidth: %.1f%s", table->ColumnsGivenWidth, table->ColumnsAutoFitWidth, table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : ""); + BulletText("CellPaddingX: %.1f, CellSpacingX: %.1f/%.1f, OuterPaddingX: %.1f", table->CellPaddingX, table->CellSpacingX1, table->CellSpacingX2, table->OuterPaddingX); + BulletText("HoveredColumnBody: %d, HoveredColumnBorder: %d", table->HoveredColumnBody, table->HoveredColumnBorder); + BulletText("ResizedColumn: %d, ReorderColumn: %d, HeldHeaderColumn: %d", table->ResizedColumn, table->ReorderColumn, table->HeldHeaderColumn); + //BulletText("BgDrawChannels: %d/%d", 0, table->BgDrawChannelUnfrozen); + float sum_weights = 0.0f; + for (int n = 0; n < table->ColumnsCount; n++) + if (table->Columns[n].Flags & ImGuiTableColumnFlags_WidthStretch) + sum_weights += table->Columns[n].StretchWeight; + for (int n = 0; n < table->ColumnsCount; n++) + { + ImGuiTableColumn* column = &table->Columns[n]; + const char* name = TableGetColumnName(table, n); + ImFormatString(buf, IM_ARRAYSIZE(buf), + "Column %d order %d '%s': offset %+.2f to %+.2f%s\n" + "Enabled: %d, VisibleX/Y: %d/%d, RequestOutput: %d, SkipItems: %d, DrawChannels: %d,%d\n" + "WidthGiven: %.1f, Request/Auto: %.1f/%.1f, StretchWeight: %.3f (%.1f%%)\n" + "MinX: %.1f, MaxX: %.1f (%+.1f), ClipRect: %.1f to %.1f (+%.1f)\n" + "ContentWidth: %.1f,%.1f, HeadersUsed/Ideal %.1f/%.1f\n" + "Sort: %d%s, UserID: 0x%08X, Flags: 0x%04X: %s%s%s..", + n, column->DisplayOrder, name, column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, (n < table->FreezeColumnsRequest) ? " (Frozen)" : "", + column->IsEnabled, column->IsVisibleX, column->IsVisibleY, column->IsRequestOutput, column->IsSkipItems, column->DrawChannelFrozen, column->DrawChannelUnfrozen, + column->WidthGiven, column->WidthRequest, column->WidthAuto, column->StretchWeight, column->StretchWeight > 0.0f ? (column->StretchWeight / sum_weights) * 100.0f : 0.0f, + column->MinX, column->MaxX, column->MaxX - column->MinX, column->ClipRect.Min.x, column->ClipRect.Max.x, column->ClipRect.Max.x - column->ClipRect.Min.x, + column->ContentMaxXFrozen - column->WorkMinX, column->ContentMaxXUnfrozen - column->WorkMinX, column->ContentMaxXHeadersUsed - column->WorkMinX, column->ContentMaxXHeadersIdeal - column->WorkMinX, + column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? " (Asc)" : (column->SortDirection == ImGuiSortDirection_Descending) ? " (Des)" : "", column->UserID, column->Flags, + (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "", + (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "", + (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : ""); + Bullet(); + Selectable(buf); + if (IsItemHovered()) + { + ImRect r(column->MinX, table->OuterRect.Min.y, column->MaxX, table->OuterRect.Max.y); + GetForegroundDrawList()->AddRect(r.Min, r.Max, IM_COL32(255, 255, 0, 255)); + } + } + if (ImGuiTableSettings* settings = TableGetBoundSettings(table)) + DebugNodeTableSettings(settings); + if (clear_settings) + table->IsResetAllRequest = true; + TreePop(); +} + +void ImGui::DebugNodeTableSettings(ImGuiTableSettings* settings) +{ + if (!TreeNode((void*)(intptr_t)settings->ID, "Settings 0x%08X (%d columns)", settings->ID, settings->ColumnsCount)) + return; + BulletText("SaveFlags: 0x%08X", settings->SaveFlags); + BulletText("ColumnsCount: %d (max %d)", settings->ColumnsCount, settings->ColumnsCountMax); + for (int n = 0; n < settings->ColumnsCount; n++) + { + ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n]; + ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? (ImGuiSortDirection)column_settings->SortDirection : ImGuiSortDirection_None; + BulletText("Column %d Order %d SortOrder %d %s Vis %d %s %7.3f UserID 0x%08X", + n, column_settings->DisplayOrder, column_settings->SortOrder, + (sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---", + column_settings->IsEnabled, column_settings->IsStretch ? "Weight" : "Width ", column_settings->WidthOrWeight, column_settings->UserID); + } + TreePop(); +} + +#else // #ifndef IMGUI_DISABLE_METRICS_WINDOW + +void ImGui::DebugNodeTable(ImGuiTable*) {} +void ImGui::DebugNodeTableSettings(ImGuiTableSettings*) {} + +#endif + + +//------------------------------------------------------------------------- +// [SECTION] Columns, BeginColumns, EndColumns, etc. +// (This is a legacy API, prefer using BeginTable/EndTable!) +//------------------------------------------------------------------------- +// FIXME: sizing is lossy when columns width is very small (default width may turn negative etc.) +//------------------------------------------------------------------------- +// - SetWindowClipRectBeforeSetChannel() [Internal] +// - GetColumnIndex() +// - GetColumnsCount() +// - GetColumnOffset() +// - GetColumnWidth() +// - SetColumnOffset() +// - SetColumnWidth() +// - PushColumnClipRect() [Internal] +// - PushColumnsBackground() [Internal] +// - PopColumnsBackground() [Internal] +// - FindOrCreateColumns() [Internal] +// - GetColumnsID() [Internal] +// - BeginColumns() +// - NextColumn() +// - EndColumns() +// - Columns() +//------------------------------------------------------------------------- + +// [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences, +// they would meddle many times with the underlying ImDrawCmd. +// Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let +// the subsequent single call to SetCurrentChannel() does it things once. +void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect) +{ + ImVec4 clip_rect_vec4 = clip_rect.ToVec4(); + window->ClipRect = clip_rect; + window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4; + window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4; +} + +int ImGui::GetColumnIndex() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0; +} + +int ImGui::GetColumnsCount() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1; +} + +float ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm) +{ + return offset_norm * (columns->OffMaxX - columns->OffMinX); +} + +float ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset) +{ + return offset / (columns->OffMaxX - columns->OffMinX); +} + +static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f; + +static float GetDraggedColumnOffset(ImGuiOldColumns* columns, int column_index) +{ + // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. + IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); + + float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x; + x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); + if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths)) + x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); + + return x; +} + +float ImGui::GetColumnOffset(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns == NULL) + return 0.0f; + + if (column_index < 0) + column_index = columns->Current; + IM_ASSERT(column_index < columns->Columns.Size); + + const float t = columns->Columns[column_index].OffsetNorm; + const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t); + return x_offset; +} + +static float GetColumnWidthEx(ImGuiOldColumns* columns, int column_index, bool before_resize = false) +{ + if (column_index < 0) + column_index = columns->Current; + + float offset_norm; + if (before_resize) + offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize; + else + offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm; + return ImGui::GetColumnOffsetFromNorm(columns, offset_norm); +} + +float ImGui::GetColumnWidth(int column_index) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns == NULL) + return GetContentRegionAvail().x; + + if (column_index < 0) + column_index = columns->Current; + return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm); +} + +void ImGui::SetColumnOffset(int column_index, float offset) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiOldColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + IM_ASSERT(column_index < columns->Columns.Size); + + const bool preserve_width = !(columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1); + const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; + + if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow)) + offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); + columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX); + + if (preserve_width) + SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); +} + +void ImGui::SetColumnWidth(int column_index, float width) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width); +} + +void ImGui::PushColumnClipRect(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (column_index < 0) + column_index = columns->Current; + + ImGuiOldColumnData* column = &columns->Columns[column_index]; + PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); +} + +// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) +void ImGui::PushColumnsBackground() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns->Count == 1) + return; + + // Optimization: avoid SetCurrentChannel() + PushClipRect() + columns->HostBackupClipRect = window->ClipRect; + SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, 0); +} + +void ImGui::PopColumnsBackground() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns->Count == 1) + return; + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); +} + +ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) +{ + // We have few columns per window so for now we don't need bother much with turning this into a faster lookup. + for (int n = 0; n < window->ColumnsStorage.Size; n++) + if (window->ColumnsStorage[n].ID == id) + return &window->ColumnsStorage[n]; + + window->ColumnsStorage.push_back(ImGuiOldColumns()); + ImGuiOldColumns* columns = &window->ColumnsStorage.back(); + columns->ID = id; + return columns; +} + +ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) +{ + ImGuiWindow* window = GetCurrentWindow(); + + // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. + PushID(0x11223347 + (str_id ? 0 : columns_count)); + ImGuiID id = window->GetID(str_id ? str_id : "columns"); + PopID(); + + return id; +} + +void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + IM_ASSERT(columns_count >= 1); + IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported + + // Acquire storage for the columns set + ImGuiID id = GetColumnsID(str_id, columns_count); + ImGuiOldColumns* columns = FindOrCreateColumns(window, id); + IM_ASSERT(columns->ID == id); + columns->Current = 0; + columns->Count = columns_count; + columns->Flags = flags; + window->DC.CurrentColumns = columns; + + columns->HostCursorPosY = window->DC.CursorPos.y; + columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; + columns->HostInitialClipRect = window->ClipRect; + columns->HostBackupParentWorkRect = window->ParentWorkRect; + window->ParentWorkRect = window->WorkRect; + + // Set state for first column + // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect + const float column_padding = g.Style.ItemSpacing.x; + const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize)); + const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f); + const float max_2 = window->WorkRect.Max.x + half_clip_extend_x; + columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f); + columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f); + columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; + + // Clear data if columns count changed + if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) + columns->Columns.resize(0); + + // Initialize default widths + columns->IsFirstFrame = (columns->Columns.Size == 0); + if (columns->Columns.Size == 0) + { + columns->Columns.reserve(columns_count + 1); + for (int n = 0; n < columns_count + 1; n++) + { + ImGuiOldColumnData column; + column.OffsetNorm = n / (float)columns_count; + columns->Columns.push_back(column); + } + } + + for (int n = 0; n < columns_count; n++) + { + // Compute clipping rectangle + ImGuiOldColumnData* column = &columns->Columns[n]; + float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n)); + float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f); + column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); + column->ClipRect.ClipWithFull(window->ClipRect); + } + + if (columns->Count > 1) + { + columns->Splitter.Split(window->DrawList, 1 + columns->Count); + columns->Splitter.SetCurrentChannel(window->DrawList, 1); + PushColumnClipRect(0); + } + + // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user. + float offset_0 = GetColumnOffset(columns->Current); + float offset_1 = GetColumnOffset(columns->Current + 1); + float width = offset_1 - offset_0; + PushItemWidth(width * 0.65f); + window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); + window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; +} + +void ImGui::NextColumn() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems || window->DC.CurrentColumns == NULL) + return; + + ImGuiContext& g = *GImGui; + ImGuiOldColumns* columns = window->DC.CurrentColumns; + + if (columns->Count == 1) + { + window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + IM_ASSERT(columns->Current == 0); + return; + } + + // Next column + if (++columns->Current == columns->Count) + columns->Current = 0; + + PopItemWidth(); + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect() + // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), + ImGuiOldColumnData* column = &columns->Columns[columns->Current]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); + + const float column_padding = g.Style.ItemSpacing.x; + columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); + if (columns->Current > 0) + { + // Columns 1+ ignore IndentX (by canceling it out) + // FIXME-COLUMNS: Unnecessary, could be locked? + window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding; + } + else + { + // New row/line: column 0 honor IndentX. + window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); + columns->LineMinY = columns->LineMaxY; + } + window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + window->DC.CursorPos.y = columns->LineMinY; + window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrLineTextBaseOffset = 0.0f; + + // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. + float offset_0 = GetColumnOffset(columns->Current); + float offset_1 = GetColumnOffset(columns->Current + 1); + float width = offset_1 - offset_0; + PushItemWidth(width * 0.65f); + window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; +} + +void ImGui::EndColumns() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + PopItemWidth(); + if (columns->Count > 1) + { + PopClipRect(); + columns->Splitter.Merge(window->DrawList); + } + + const ImGuiOldColumnFlags flags = columns->Flags; + columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); + window->DC.CursorPos.y = columns->LineMaxY; + if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize)) + window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent + + // Draw columns borders and handle resize + // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy + bool is_being_resized = false; + if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems) + { + // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. + const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y); + const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y); + int dragging_column = -1; + for (int n = 1; n < columns->Count; n++) + { + ImGuiOldColumnData* column = &columns->Columns[n]; + float x = window->Pos.x + GetColumnOffset(n); + const ImGuiID column_id = columns->ID + ImGuiID(n); + const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH; + const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2)); + KeepAliveID(column_id); + if (IsClippedEx(column_hit_rect, column_id)) // FIXME: Can be removed or replaced with a lower-level test + continue; + + bool hovered = false, held = false; + if (!(flags & ImGuiOldColumnFlags_NoResize)) + { + ButtonBehavior(column_hit_rect, column_id, &hovered, &held); + if (hovered || held) + g.MouseCursor = ImGuiMouseCursor_ResizeEW; + if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize)) + dragging_column = n; + } + + // Draw column + const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); + const float xi = IM_FLOOR(x); + window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col); + } + + // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. + if (dragging_column != -1) + { + if (!columns->IsBeingResized) + for (int n = 0; n < columns->Count + 1; n++) + columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; + columns->IsBeingResized = is_being_resized = true; + float x = GetDraggedColumnOffset(columns, dragging_column); + SetColumnOffset(dragging_column, x); + } + } + columns->IsBeingResized = is_being_resized; + + window->WorkRect = window->ParentWorkRect; + window->ParentWorkRect = columns->HostBackupParentWorkRect; + window->DC.CurrentColumns = NULL; + window->DC.ColumnsOffset.x = 0.0f; + window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); +} + +void ImGui::Columns(int columns_count, const char* id, bool border) +{ + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(columns_count >= 1); + + ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder); + //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) + return; + + if (columns != NULL) + EndColumns(); + + if (columns_count != 1) + BeginColumns(id, columns_count, flags); +} + +//------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/src/editors/xrEUI/imgui_user.cpp b/src/editors/xrEUI/imgui_user.cpp new file mode 100644 index 00000000000..39414cef2ea --- /dev/null +++ b/src/editors/xrEUI/imgui_user.cpp @@ -0,0 +1,72 @@ +#include "stdafx.h" +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif +#include "imgui_internal.h" +float ImGui::GetWindowBarHeight() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->MenuBarHeight(); +} +bool ImGui::OpenPopupOnItemClick2(const char* str_id, ImGuiPopupFlags popup_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); + if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + { + ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) + OpenPopupEx(id, popup_flags); + return true; + } + return false; +} + +bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int dec, ImGuiInputTextFlags flags) +{ + string_path Format; + xr_sprintf(Format, "%%.%df", dec); + return InputFloat(label, v, step, step_fast, Format, flags); +} + +bool ImGui::InputFloat2(const char* label, float v[2], int dec, ImGuiInputTextFlags flags) +{ + string_path Format; + xr_sprintf(Format, "%%.%df", dec); + return InputFloat2(label, v, Format, flags); +} + +bool ImGui::InputFloat3(const char* label, float v[3], int dec, ImGuiInputTextFlags flags) +{ + string_path Format; + xr_sprintf(Format, "%%.%df", dec); + return InputFloat3(label, v, Format, flags); +} + +bool ImGui::InputFloat4(const char* label, float v[4], int dec, ImGuiInputTextFlags flags) +{ + string_path Format; + xr_sprintf(Format, "%%.%df", dec); + return InputFloat4(label, v, Format, flags); +} +bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags, bool open_always) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + const ImGuiID id = window->GetID(name); + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) + { + if (open_always) + { + OpenPopupEx(id); + } + } + return ImGui::BeginPopupModal(name, p_open, flags); +} + +IMGUI_API bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags) +{ + return ArrowButtonEx(str_id, dir, size, flags); +} diff --git a/src/editors/xrEUI/imgui_user.h b/src/editors/xrEUI/imgui_user.h new file mode 100644 index 00000000000..92fd82dfdc9 --- /dev/null +++ b/src/editors/xrEUI/imgui_user.h @@ -0,0 +1,32 @@ +#pragma once +#ifndef XREUI_EXPORTS +enum ImGuiItemFlags_ +{ + ImGuiItemFlags_None = 0, + ImGuiItemFlags_NoTabStop = 1 << 0, // false // Disable keyboard tabbing (FIXME: should merge with _NoNav) + ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. + ImGuiItemFlags_Disabled = 1 << 2, // false // Disable interactions but doesn't affect visuals. See BeginDisabled()/EndDisabled(). See github.com/ocornut/imgui/issues/211 + ImGuiItemFlags_NoNav = 1 << 3, // false // Disable keyboard/gamepad directional navigation (FIXME: should merge with _NoTabStop) + ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false // Disable item being a candidate for default focus (e.g. used by title bar items) + ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // Disable MenuItem/Selectable() automatically closing their popup window + ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) + ImGuiItemFlags_ReadOnly = 1 << 7, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. + ImGuiItemFlags_Inputable = 1 << 8 // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. + +}; +#endif +namespace ImGui +{ + IMGUI_API float GetWindowBarHeight(); + IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); + IMGUI_API bool OpenPopupOnItemClick2(const char* str_id, ImGuiPopupFlags popup_flags); + + IMGUI_API bool InputFloat(const char* label, float* v, float step, float step_fast, int dec, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat2(const char* label, float v[2], int dec, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat3(const char* label, float v[3], int dec, ImGuiInputTextFlags flags = 0); + IMGUI_API bool InputFloat4(const char* label, float v[4], int dec, ImGuiInputTextFlags flags = 0); + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags, bool open_always); + IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags); + IMGUI_API void PushItemFlag(int option, bool enabled); + IMGUI_API void PopItemFlag(); +} \ No newline at end of file diff --git a/src/editors/xrEUI/imgui_widgets.cpp b/src/editors/xrEUI/imgui_widgets.cpp new file mode 100644 index 00000000000..8e006188039 --- /dev/null +++ b/src/editors/xrEUI/imgui_widgets.cpp @@ -0,0 +1,8440 @@ +// dear imgui, v1.88 WIP +// (widgets code) + +/* + +Index of this file: + +// [SECTION] Forward Declarations +// [SECTION] Widgets: Text, etc. +// [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.) +// [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.) +// [SECTION] Widgets: ComboBox +// [SECTION] Data Type and Data Formatting Helpers +// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +// [SECTION] Widgets: InputText, InputTextMultiline +// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +// [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +// [SECTION] Widgets: Selectable +// [SECTION] Widgets: ListBox +// [SECTION] Widgets: PlotLines, PlotHistogram +// [SECTION] Widgets: Value helpers +// [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc. +// [SECTION] Widgets: BeginTabBar, EndTabBar, etc. +// [SECTION] Widgets: BeginTabItem, EndTabItem, etc. +// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. + +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif +#include "imgui_internal.h" + +// System includes +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +//------------------------------------------------------------------------- +// Warnings +//------------------------------------------------------------------------- + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later +#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types +#endif +#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2). +#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') +#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#pragma GCC diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#endif + +//------------------------------------------------------------------------- +// Data +//------------------------------------------------------------------------- + +// Widgets +static const float DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70f; // Time for drag-hold to activate items accepting the ImGuiButtonFlags_PressedOnDragDropHold button behavior. +static const float DRAG_MOUSE_THRESHOLD_FACTOR = 0.50f; // Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags. + +// Those MIN/MAX values are not define because we need to point to them +static const signed char IM_S8_MIN = -128; +static const signed char IM_S8_MAX = 127; +static const unsigned char IM_U8_MIN = 0; +static const unsigned char IM_U8_MAX = 0xFF; +static const signed short IM_S16_MIN = -32768; +static const signed short IM_S16_MAX = 32767; +static const unsigned short IM_U16_MIN = 0; +static const unsigned short IM_U16_MAX = 0xFFFF; +static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000); +static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF) +static const ImU32 IM_U32_MIN = 0; +static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF) +#ifdef LLONG_MIN +static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll); +static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll); +#else +static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1; +static const ImS64 IM_S64_MAX = 9223372036854775807LL; +#endif +static const ImU64 IM_U64_MIN = 0; +#ifdef ULLONG_MAX +static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull); +#else +static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); +#endif + +//------------------------------------------------------------------------- +// [SECTION] Forward Declarations +//------------------------------------------------------------------------- + +// For InputTextEx() +static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, ImGuiInputSource input_source); +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Text, etc. +//------------------------------------------------------------------------- +// - TextEx() [Internal] +// - TextUnformatted() +// - Text() +// - TextV() +// - TextColored() +// - TextColoredV() +// - TextDisabled() +// - TextDisabledV() +// - TextWrapped() +// - TextWrappedV() +// - LabelText() +// - LabelTextV() +// - BulletText() +// - BulletTextV() +//------------------------------------------------------------------------- + +void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ImGuiContext& g = *GImGui; + + // Accept null ranges + if (text == text_end) + text = text_end = ""; + + // Calculate length + const char* text_begin = text; + if (text_end == NULL) + text_end = text + strlen(text); // FIXME-OPT + + const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + const float wrap_pos_x = window->DC.TextWrapPos; + const bool wrap_enabled = (wrap_pos_x >= 0.0f); + if (text_end - text <= 2000 || wrap_enabled) + { + // Common case + const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; + const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); + + ImRect bb(text_pos, text_pos + text_size); + ItemSize(text_size, 0.0f); + if (!ItemAdd(bb, 0)) + return; + + // Render (we don't hide text after ## in this end-user function) + RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); + } + else + { + // Long text! + // Perform manual coarse clipping to optimize for long multi-line text + // - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. + // - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. + // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop. + const char* line = text; + const float line_height = GetTextLineHeight(); + ImVec2 text_size(0, 0); + + // Lines to skip (can't skip when logging text) + ImVec2 pos = text_pos; + if (!g.LogEnabled) + { + int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height); + if (lines_skippable > 0) + { + int lines_skipped = 0; + while (line < text_end && lines_skipped < lines_skippable) + { + const char* line_end = (const char*)memchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) + text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + } + + // Lines to render + if (line < text_end) + { + ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); + while (line < text_end) + { + if (IsClippedEx(line_rect, 0)) + break; + + const char* line_end = (const char*)memchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); + RenderText(pos, line, line_end, false); + line = line_end + 1; + line_rect.Min.y += line_height; + line_rect.Max.y += line_height; + pos.y += line_height; + } + + // Count remaining lines + int lines_skipped = 0; + while (line < text_end) + { + const char* line_end = (const char*)memchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) + text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + text_size.y = (pos - text_pos).y; + + ImRect bb(text_pos, text_pos + text_size); + ItemSize(text_size, 0.0f); + ItemAdd(bb, 0); + } +} + +void ImGui::TextUnformatted(const char* text, const char* text_end) +{ + TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText); +} + +void ImGui::Text(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextV(fmt, args); + va_end(args); +} + +void ImGui::TextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + // FIXME-OPT: Handle the %s shortcut? + ImGuiContext& g = *GImGui; + const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + TextEx(g.TempBuffer, text_end, ImGuiTextFlags_NoWidthForLargeClippedText); +} + +void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextColoredV(col, fmt, args); + va_end(args); +} + +void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) +{ + PushStyleColor(ImGuiCol_Text, col); + if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0) + TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting + else + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextDisabled(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextDisabledV(fmt, args); + va_end(args); +} + +void ImGui::TextDisabledV(const char* fmt, va_list args) +{ + ImGuiContext& g = *GImGui; + PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0) + TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting + else + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextWrapped(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextWrappedV(fmt, args); + va_end(args); +} + +void ImGui::TextWrappedV(const char* fmt, va_list args) +{ + ImGuiContext& g = *GImGui; + bool need_backup = (g.CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set + if (need_backup) + PushTextWrapPos(0.0f); + if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0) + TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting + else + TextV(fmt, args); + if (need_backup) + PopTextWrapPos(); +} + +void ImGui::LabelText(const char* label, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + LabelTextV(label, fmt, args); + va_end(args); +} + +// Add a label+text combo aligned to other label+value widgets +void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float w = CalcItemWidth(); + + const char* value_text_begin = &g.TempBuffer[0]; + const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + const ImVec2 value_size = CalcTextSize(value_text_begin, value_text_end, false); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const ImVec2 pos = window->DC.CursorPos; + const ImRect value_bb(pos, pos + ImVec2(w, value_size.y + style.FramePadding.y * 2)); + const ImRect total_bb(pos, pos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), ImMax(value_size.y, label_size.y) + style.FramePadding.y * 2)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, 0)) + return; + + // Render + RenderTextClipped(value_bb.Min + style.FramePadding, value_bb.Max, value_text_begin, value_text_end, &value_size, ImVec2(0.0f, 0.0f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); +} + +void ImGui::BulletText(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + BulletTextV(fmt, args); + va_end(args); +} + +// Text with a little bullet aligned to the typical tree node. +void ImGui::BulletTextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const char* text_begin = g.TempBuffer; + const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); + const ImVec2 total_size = ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x * 2) : 0.0f), label_size.y); // Empty text doesn't add padding + ImVec2 pos = window->DC.CursorPos; + pos.y += window->DC.CurrLineTextBaseOffset; + ItemSize(total_size, 0.0f); + const ImRect bb(pos, pos + total_size); + if (!ItemAdd(bb, 0)) + return; + + // Render + ImU32 text_col = GetColorU32(ImGuiCol_Text); + RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, g.FontSize * 0.5f), text_col); + RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Main +//------------------------------------------------------------------------- +// - ButtonBehavior() [Internal] +// - Button() +// - SmallButton() +// - InvisibleButton() +// - ArrowButton() +// - CloseButton() [Internal] +// - CollapseButton() [Internal] +// - GetWindowScrollbarID() [Internal] +// - GetWindowScrollbarRect() [Internal] +// - Scrollbar() [Internal] +// - ScrollbarEx() [Internal] +// - Image() +// - ImageButton() +// - Checkbox() +// - CheckboxFlagsT() [Internal] +// - CheckboxFlags() +// - RadioButton() +// - ProgressBar() +// - Bullet() +//------------------------------------------------------------------------- + +// The ButtonBehavior() function is key to many interactions and used by many/most widgets. +// Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags_), +// this code is a little complex. +// By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags_PressedOnClickRelease button behavior. +// See the series of events below and the corresponding state reported by dear imgui: +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+0 (mouse is outside bb) - - - - - - +// Frame N+1 (mouse moves inside bb) - true - - - - +// Frame N+2 (mouse button is down) - true true true - true +// Frame N+3 (mouse button is down) - true true - - - +// Frame N+4 (mouse moves outside bb) - - true - - - +// Frame N+5 (mouse moves inside bb) - true true - - - +// Frame N+6 (mouse button is released) true true - - true - +// Frame N+7 (mouse button is released) - true - - - - +// Frame N+8 (mouse moves outside bb) - - - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+2 (mouse button is down) true true true true - true +// Frame N+3 (mouse button is down) - true true - - - +// Frame N+6 (mouse button is released) - true - - true - +// Frame N+7 (mouse button is released) - true - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+2 (mouse button is down) - true - - - true +// Frame N+3 (mouse button is down) - true - - - - +// Frame N+6 (mouse button is released) true true - - - - +// Frame N+7 (mouse button is released) - true - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+0 (mouse button is down) - true - - - true +// Frame N+1 (mouse button is down) - true - - - - +// Frame N+2 (mouse button is released) - true - - - - +// Frame N+3 (mouse button is released) - true - - - - +// Frame N+4 (mouse button is down) true true true true - true +// Frame N+5 (mouse button is down) - true true - - - +// Frame N+6 (mouse button is released) - true - - true - +// Frame N+7 (mouse button is released) - true - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// Note that some combinations are supported, +// - PressedOnDragDropHold can generally be associated with any flag. +// - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported. +//------------------------------------------------------------------------------------------------------------------------------------------------ +// The behavior of the return-value changes when ImGuiButtonFlags_Repeat is set: +// Repeat+ Repeat+ Repeat+ Repeat+ +// PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick +//------------------------------------------------------------------------------------------------------------------------------------------------- +// Frame N+0 (mouse button is down) - true - true +// ... - - - - +// Frame N + RepeatDelay true true - true +// ... - - - - +// Frame N + RepeatDelay + RepeatRate*N true true - true +//------------------------------------------------------------------------------------------------------------------------------------------------- + +bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Default only reacts to left mouse button + if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0) + flags |= ImGuiButtonFlags_MouseButtonDefault_; + + // Default behavior requires click + release inside bounding box + if ((flags & ImGuiButtonFlags_PressedOnMask_) == 0) + flags |= ImGuiButtonFlags_PressedOnDefault_; + + ImGuiWindow* backup_hovered_window = g.HoveredWindow; + const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindowDockTree == window->RootWindowDockTree; + if (flatten_hovered_children) + g.HoveredWindow = window; + +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (id != 0 && g.LastItemData.ID != id) + IMGUI_TEST_ENGINE_ITEM_ADD(bb, id); +#endif + + bool pressed = false; + bool hovered = ItemHoverable(bb, id); + + // Drag source doesn't report as hovered + if (hovered && g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover)) + hovered = false; + + // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button + if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers)) + if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + { + hovered = true; + SetHoveredID(id); + if (g.HoveredIdTimer - g.IO.DeltaTime <= DRAGDROP_HOLD_TO_OPEN_TIMER && g.HoveredIdTimer >= DRAGDROP_HOLD_TO_OPEN_TIMER) + { + pressed = true; + g.DragDropHoldJustPressedId = id; + FocusWindow(window); + } + } + + if (flatten_hovered_children) + g.HoveredWindow = backup_hovered_window; + + // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one. + if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0)) + hovered = false; + + // Mouse handling + if (hovered) + { + if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) + { + // Poll buttons + int mouse_button_clicked = -1; + if ((flags & ImGuiButtonFlags_MouseButtonLeft) && g.IO.MouseClicked[0]) { mouse_button_clicked = 0; } + else if ((flags & ImGuiButtonFlags_MouseButtonRight) && g.IO.MouseClicked[1]) { mouse_button_clicked = 1; } + else if ((flags & ImGuiButtonFlags_MouseButtonMiddle) && g.IO.MouseClicked[2]) { mouse_button_clicked = 2; } + + if (mouse_button_clicked != -1 && g.ActiveId != id) + { + if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere)) + { + SetActiveID(id, window); + g.ActiveIdMouseButton = mouse_button_clicked; + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + SetFocusID(id, window); + FocusWindow(window); + } + if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2)) + { + pressed = true; + if (flags & ImGuiButtonFlags_NoHoldingActiveId) + ClearActiveID(); + else + SetActiveID(id, window); // Hold on ID + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + SetFocusID(id, window); + g.ActiveIdMouseButton = mouse_button_clicked; + FocusWindow(window); + } + } + if (flags & ImGuiButtonFlags_PressedOnRelease) + { + int mouse_button_released = -1; + if ((flags & ImGuiButtonFlags_MouseButtonLeft) && g.IO.MouseReleased[0]) { mouse_button_released = 0; } + else if ((flags & ImGuiButtonFlags_MouseButtonRight) && g.IO.MouseReleased[1]) { mouse_button_released = 1; } + else if ((flags & ImGuiButtonFlags_MouseButtonMiddle) && g.IO.MouseReleased[2]) { mouse_button_released = 2; } + if (mouse_button_released != -1) + { + const bool has_repeated_at_least_once = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay; // Repeat mode trumps on release behavior + if (!has_repeated_at_least_once) + pressed = true; + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + SetFocusID(id, window); + ClearActiveID(); + } + } + + // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). + // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. + if (g.ActiveId == id && (flags & ImGuiButtonFlags_Repeat)) + if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && IsMouseClicked(g.ActiveIdMouseButton, true)) + pressed = true; + } + + if (pressed) + g.NavDisableHighlight = true; + } + + // Gamepad/Keyboard navigation + // We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse. + if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId)) + if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus)) + hovered = true; + if (g.NavActivateDownId == id) + { + bool nav_activated_by_code = (g.NavActivateId == id); + bool nav_activated_by_inputs = IsNavInputTest(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiNavReadMode_Repeat : ImGuiNavReadMode_Pressed); + if (nav_activated_by_code || nav_activated_by_inputs) + { + // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button. + pressed = true; + SetActiveID(id, window); + g.ActiveIdSource = ImGuiInputSource_Nav; + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + SetFocusID(id, window); + } + } + + // Process while held + bool held = false; + if (g.ActiveId == id) + { + if (g.ActiveIdSource == ImGuiInputSource_Mouse) + { + if (g.ActiveIdIsJustActivated) + g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; + + const int mouse_button = g.ActiveIdMouseButton; + IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT); + if (g.IO.MouseDown[mouse_button]) + { + held = true; + } + else + { + bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0; + bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0; + if ((release_in || release_anywhere) && !g.DragDropActive) + { + // Report as pressed when releasing the mouse (this is the most common path) + bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseReleased[mouse_button] && g.IO.MouseClickedLastCount[mouse_button] == 2; + bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps + if (!is_double_click_release && !is_repeating_already) + pressed = true; + } + ClearActiveID(); + } + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + g.NavDisableHighlight = true; + } + else if (g.ActiveIdSource == ImGuiInputSource_Nav) + { + // When activated using Nav, we hold on the ActiveID until activation button is released + if (g.NavActivateDownId != id) + ClearActiveID(); + } + if (pressed) + g.ActiveIdHasBeenPressedBefore = true; + } + + if (out_hovered) *out_hovered = hovered; + if (out_held) *out_held = held; + + return pressed; +} + +bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + ImVec2 pos = window->DC.CursorPos; + if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) + pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y; + ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + + const ImRect bb(pos, pos + size); + ItemSize(size, style.FramePadding.y); + if (!ItemAdd(bb, id)) + return false; + + if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat) + flags |= ImGuiButtonFlags_Repeat; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderNavHighlight(bb, id); + RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); + + if (g.LogEnabled) + LogSetNextTextDecoration("[", "]"); + RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); + + // Automatically close popups + //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // CloseCurrentPopup(); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return pressed; +} + +bool ImGui::Button(const char* label, const ImVec2& size_arg) +{ + return ButtonEx(label, size_arg, ImGuiButtonFlags_None); +} + +// Small buttons fits within text without additional vertical spacing. +bool ImGui::SmallButton(const char* label) +{ + ImGuiContext& g = *GImGui; + float backup_padding_y = g.Style.FramePadding.y; + g.Style.FramePadding.y = 0.0f; + bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine); + g.Style.FramePadding.y = backup_padding_y; + return pressed; +} + +// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. +// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) +bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiButtonFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + // Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size. + IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f); + + const ImGuiID id = window->GetID(str_id); + ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(size); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags); + return pressed; +} + +bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiID id = window->GetID(str_id); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + const float default_size = GetFrameHeight(); + ItemSize(size, (size.y >= default_size) ? g.Style.FramePadding.y : -1.0f); + if (!ItemAdd(bb, id)) + return false; + + if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat) + flags |= ImGuiButtonFlags_Repeat; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + + // Render + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 text_col = GetColorU32(ImGuiCol_Text); + RenderNavHighlight(bb, id); + RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding); + RenderArrow(window->DrawList, bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), text_col, dir); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags); + return pressed; +} + +bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir) +{ + float sz = GetFrameHeight(); + return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None); +} + +// Button to close a window +bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // Tweak 1: Shrink hit-testing area if button covers an abnormally large proportion of the visible region. That's in order to facilitate moving the window away. (#3825) + // This may better be applied as a general hit-rect reduction mechanism for all widgets to ensure the area to move window is always accessible? + const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f); + ImRect bb_interact = bb; + const float area_to_visible_ratio = window->OuterRectClipped.GetArea() / bb.GetArea(); + if (area_to_visible_ratio < 1.5f) + bb_interact.Expand(ImFloor(bb_interact.GetSize() * -0.25f)); + + // Tweak 2: We intentionally allow interaction when clipped so that a mechanical Alt,Right,Activate sequence can always close a window. + // (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible). + bool is_clipped = !ItemAdd(bb_interact, id); + + bool hovered, held; + bool pressed = ButtonBehavior(bb_interact, id, &hovered, &held); + if (is_clipped) + return pressed; + + // Render + // FIXME: Clarify this mess + ImU32 col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered); + ImVec2 center = bb.GetCenter(); + if (hovered) + window->DrawList->AddCircleFilled(center, ImMax(2.0f, g.FontSize * 0.5f + 1.0f), col, 12); + + float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; + ImU32 cross_col = GetColorU32(ImGuiCol_Text); + center -= ImVec2(0.5f, 0.5f); + window->DrawList->AddLine(center + ImVec2(+cross_extent, +cross_extent), center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f); + window->DrawList->AddLine(center + ImVec2(+cross_extent, -cross_extent), center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f); + + return pressed; +} + +// The Collapse button also functions as a Dock Menu button. +bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_node) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f); + ItemAdd(bb, id); + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); + + // Render + //bool is_dock_menu = (window->DockNodeAsHost && !window->Collapsed); + ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + ImU32 text_col = GetColorU32(ImGuiCol_Text); + if (hovered || held) + window->DrawList->AddCircleFilled(bb.GetCenter() + ImVec2(0,-0.5f), g.FontSize * 0.5f + 1.0f, bg_col, 12); + + if (dock_node) + RenderArrowDockMenu(window->DrawList, bb.Min + g.Style.FramePadding, g.FontSize, text_col); + else + RenderArrow(window->DrawList, bb.Min + g.Style.FramePadding, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); + + // Switch to moving the window after mouse is moved beyond the initial drag threshold + if (IsItemActive() && IsMouseDragging(0)) + StartMouseMovingWindowOrNode(window, dock_node, true); + + return pressed; +} + +ImGuiID ImGui::GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis) +{ + return window->GetID(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY"); +} + +// Return scrollbar rectangle, must only be called for corresponding axis if window->ScrollbarX/Y is set. +ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis) +{ + const ImRect outer_rect = window->Rect(); + const ImRect inner_rect = window->InnerRect; + const float border_size = window->WindowBorderSize; + const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar) + IM_ASSERT(scrollbar_size > 0.0f); + if (axis == ImGuiAxis_X) + return ImRect(inner_rect.Min.x, ImMax(outer_rect.Min.y, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x, outer_rect.Max.y); + else + return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y, outer_rect.Max.x, inner_rect.Max.y); +} + +void ImGui::Scrollbar(ImGuiAxis axis) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + const ImGuiID id = GetWindowScrollbarID(window, axis); + KeepAliveID(id); + + // Calculate scrollbar bounding box + ImRect bb = GetWindowScrollbarRect(window, axis); + ImDrawFlags rounding_corners = ImDrawFlags_RoundCornersNone; + if (axis == ImGuiAxis_X) + { + rounding_corners |= ImDrawFlags_RoundCornersBottomLeft; + if (!window->ScrollbarY) + rounding_corners |= ImDrawFlags_RoundCornersBottomRight; + } + else + { + if ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) + rounding_corners |= ImDrawFlags_RoundCornersTopRight; + if (!window->ScrollbarX) + rounding_corners |= ImDrawFlags_RoundCornersBottomRight; + } + float size_avail = window->InnerRect.Max[axis] - window->InnerRect.Min[axis]; + float size_contents = window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f; + ImS64 scroll = (ImS64)window->Scroll[axis]; + ScrollbarEx(bb, id, axis, &scroll, (ImS64)size_avail, (ImS64)size_contents, rounding_corners); + window->Scroll[axis] = (float)scroll; +} + +// Vertical/Horizontal scrollbar +// The entire piece of code below is rather confusing because: +// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) +// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar +// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. +// Still, the code should probably be made simpler.. +bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 size_avail_v, ImS64 size_contents_v, ImDrawFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + const float bb_frame_width = bb_frame.GetWidth(); + const float bb_frame_height = bb_frame.GetHeight(); + if (bb_frame_width <= 0.0f || bb_frame_height <= 0.0f) + return false; + + // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the window resize grab) + float alpha = 1.0f; + if ((axis == ImGuiAxis_Y) && bb_frame_height < g.FontSize + g.Style.FramePadding.y * 2.0f) + alpha = ImSaturate((bb_frame_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f)); + if (alpha <= 0.0f) + return false; + + const ImGuiStyle& style = g.Style; + const bool allow_interaction = (alpha >= 1.0f); + + ImRect bb = bb_frame; + bb.Expand(ImVec2(-ImClamp(IM_FLOOR((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp(IM_FLOOR((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f))); + + // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar) + const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight(); + + // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount) + // But we maintain a minimum size in pixel to allow for the user to still aim inside. + IM_ASSERT(ImMax(size_contents_v, size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. + const ImS64 win_size_v = ImMax(ImMax(size_contents_v, size_avail_v), (ImS64)1); + const float grab_h_pixels = ImClamp(scrollbar_size_v * ((float)size_avail_v / (float)win_size_v), style.GrabMinSize, scrollbar_size_v); + const float grab_h_norm = grab_h_pixels / scrollbar_size_v; + + // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). + bool held = false; + bool hovered = false; + ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus); + + const ImS64 scroll_max = ImMax((ImS64)1, size_contents_v - size_avail_v); + float scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max); + float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Grab position in normalized space + if (held && allow_interaction && grab_h_norm < 1.0f) + { + const float scrollbar_pos_v = bb.Min[axis]; + const float mouse_pos_v = g.IO.MousePos[axis]; + + // Click position in scrollbar normalized space (0.0f->1.0f) + const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); + SetHoveredID(id); + + bool seek_absolute = false; + if (g.ActiveIdIsJustActivated) + { + // On initial click calculate the distance between mouse and the center of the grab + seek_absolute = (clicked_v_norm < grab_v_norm || clicked_v_norm > grab_v_norm + grab_h_norm); + if (seek_absolute) + g.ScrollbarClickDeltaToGrabCenter = 0.0f; + else + g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f; + } + + // Apply scroll (p_scroll_v will generally point on one member of window->Scroll) + // It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position + const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm)); + *p_scroll_v = (ImS64)(scroll_v_norm * scroll_max); + + // Update values for rendering + scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max); + grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; + + // Update distance to grab now that we have seeked and saturated + if (seek_absolute) + g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f; + } + + // Render + const ImU32 bg_col = GetColorU32(ImGuiCol_ScrollbarBg); + const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha); + window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, flags); + ImRect grab_rect; + if (axis == ImGuiAxis_X) + grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y); + else + grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels); + window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding); + + return held; +} + +void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + if (border_col.w > 0.0f) + bb.Max += ImVec2(2, 2); + ItemSize(bb); + if (!ItemAdd(bb, 0)) + return; + + if (border_col.w > 0.0f) + { + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f); + window->DrawList->AddImage(user_texture_id, bb.Min + ImVec2(1, 1), bb.Max - ImVec2(1, 1), uv0, uv1, GetColorU32(tint_col)); + } + else + { + window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col)); + } +} + +// ImageButton() is flawed as 'id' is always derived from 'texture_id' (see #2464 #1390) +// We provide this internal helper to write your own variant while we figure out how to redesign the public ImageButton() API. +bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2); + ItemSize(bb); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderNavHighlight(bb, id); + RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding)); + if (bg_col.w > 0.0f) + window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); + window->DrawList->AddImage(texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); + + return pressed; +} + +// frame_padding < 0: uses FramePadding from style (default) +// frame_padding = 0: no framing +// frame_padding > 0: set framing size +bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + // Default to using texture ID as ID. User can still push string/integer prefixes. + PushID((void*)(intptr_t)user_texture_id); + const ImGuiID id = window->GetID("#image"); + PopID(); + + const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : g.Style.FramePadding; + return ImageButtonEx(id, user_texture_id, size, uv0, uv1, padding, bg_col, tint_col); +} + +bool ImGui::Checkbox(const char* label, bool* v) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const float square_sz = GetFrameHeight(); + const ImVec2 pos = window->DC.CursorPos; + const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id)) + { + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); + return false; + } + + bool hovered, held; + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + if (pressed) + { + *v = !(*v); + MarkItemEdited(id); + } + + const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); + RenderNavHighlight(total_bb, id); + RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); + ImU32 check_col = GetColorU32(ImGuiCol_CheckMark); + bool mixed_value = (g.LastItemData.InFlags & ImGuiItemFlags_MixedValue) != 0; + if (mixed_value) + { + // Undocumented tristate/mixed/indeterminate checkbox (#2644) + // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox) + ImVec2 pad(ImMax(1.0f, IM_FLOOR(square_sz / 3.6f)), ImMax(1.0f, IM_FLOOR(square_sz / 3.6f))); + window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding); + } + else if (*v) + { + const float pad = ImMax(1.0f, IM_FLOOR(square_sz / 6.0f)); + RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f); + } + + ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y); + if (g.LogEnabled) + LogRenderedText(&label_pos, mixed_value ? "[~]" : *v ? "[x]" : "[ ]"); + if (label_size.x > 0.0f) + RenderText(label_pos, label); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); + return pressed; +} + +template +bool ImGui::CheckboxFlagsT(const char* label, T* flags, T flags_value) +{ + bool all_on = (*flags & flags_value) == flags_value; + bool any_on = (*flags & flags_value) != 0; + bool pressed; + if (!all_on && any_on) + { + ImGuiContext& g = *GImGui; + ImGuiItemFlags backup_item_flags = g.CurrentItemFlags; + g.CurrentItemFlags |= ImGuiItemFlags_MixedValue; + pressed = Checkbox(label, &all_on); + g.CurrentItemFlags = backup_item_flags; + } + else + { + pressed = Checkbox(label, &all_on); + + } + if (pressed) + { + if (all_on) + *flags |= flags_value; + else + *flags &= ~flags_value; + } + return pressed; +} + +bool ImGui::CheckboxFlags(const char* label, int* flags, int flags_value) +{ + return CheckboxFlagsT(label, flags, flags_value); +} + +bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) +{ + return CheckboxFlagsT(label, flags, flags_value); +} + +bool ImGui::CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value) +{ + return CheckboxFlagsT(label, flags, flags_value); +} + +bool ImGui::CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value) +{ + return CheckboxFlagsT(label, flags, flags_value); +} + +bool ImGui::RadioButton(const char* label, bool active) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const float square_sz = GetFrameHeight(); + const ImVec2 pos = window->DC.CursorPos; + const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); + const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id)) + return false; + + ImVec2 center = check_bb.GetCenter(); + center.x = IM_ROUND(center.x); + center.y = IM_ROUND(center.y); + const float radius = (square_sz - 1.0f) * 0.5f; + + bool hovered, held; + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + if (pressed) + MarkItemEdited(id); + + RenderNavHighlight(total_bb, id); + window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); + if (active) + { + const float pad = ImMax(1.0f, IM_FLOOR(square_sz / 6.0f)); + window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark), 16); + } + + if (style.FrameBorderSize > 0.0f) + { + window->DrawList->AddCircle(center + ImVec2(1, 1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize); + window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize); + } + + ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y); + if (g.LogEnabled) + LogRenderedText(&label_pos, active ? "(x)" : "( )"); + if (label_size.x > 0.0f) + RenderText(label_pos, label); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return pressed; +} + +// FIXME: This would work nicely if it was a public template, e.g. 'template RadioButton(const char* label, T* v, T v_button)', but I'm not sure how we would expose it.. +bool ImGui::RadioButton(const char* label, int* v, int v_button) +{ + const bool pressed = RadioButton(label, *v == v_button); + if (pressed) + *v = v_button; + return pressed; +} + +// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size +void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + ImVec2 pos = window->DC.CursorPos; + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0f); + ImRect bb(pos, pos + size); + ItemSize(size, style.FramePadding.y); + if (!ItemAdd(bb, 0)) + return; + + // Render + fraction = ImSaturate(fraction); + RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize)); + const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y); + RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding); + + // Default displaying the fraction as percentage string, but user can override it + char overlay_buf[32]; + if (!overlay) + { + ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction * 100 + 0.01f); + overlay = overlay_buf; + } + + ImVec2 overlay_size = CalcTextSize(overlay, NULL); + if (overlay_size.x > 0.0f) + RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f, 0.5f), &bb); +} + +void ImGui::Bullet() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); + ItemSize(bb); + if (!ItemAdd(bb, 0)) + { + SameLine(0, style.FramePadding.x * 2); + return; + } + + // Render and stay on same line + ImU32 text_col = GetColorU32(ImGuiCol_Text); + RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, line_height * 0.5f), text_col); + SameLine(0, style.FramePadding.x * 2.0f); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Low-level Layout helpers +//------------------------------------------------------------------------- +// - Spacing() +// - Dummy() +// - NewLine() +// - AlignTextToFramePadding() +// - SeparatorEx() [Internal] +// - Separator() +// - SplitterBehavior() [Internal] +// - ShrinkWidths() [Internal] +//------------------------------------------------------------------------- + +void ImGui::Spacing() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ItemSize(ImVec2(0, 0)); +} + +void ImGui::Dummy(const ImVec2& size) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(size); + ItemAdd(bb, 0); +} + +void ImGui::NewLine() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiLayoutType backup_layout_type = window->DC.LayoutType; + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.IsSameLine = false; + if (window->DC.CurrLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + ItemSize(ImVec2(0, 0)); + else + ItemSize(ImVec2(0.0f, g.FontSize)); + window->DC.LayoutType = backup_layout_type; +} + +void ImGui::AlignTextToFramePadding() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + window->DC.CurrLineSize.y = ImMax(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2); + window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y); +} + +// Horizontal/vertical separating line +void ImGui::SeparatorEx(ImGuiSeparatorFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected + + float thickness_draw = 1.0f; + float thickness_layout = 0.0f; + if (flags & ImGuiSeparatorFlags_Vertical) + { + // Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout. + float y1 = window->DC.CursorPos.y; + float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y; + const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness_draw, y2)); + ItemSize(ImVec2(thickness_layout, 0.0f)); + if (!ItemAdd(bb, 0)) + return; + + // Draw + window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator)); + if (g.LogEnabled) + LogText(" |"); + } + else if (flags & ImGuiSeparatorFlags_Horizontal) + { + // Horizontal Separator + float x1 = window->Pos.x; + float x2 = window->Pos.x + window->Size.x; + + // FIXME-WORKRECT: old hack (#205) until we decide of consistent behavior with WorkRect/Indent and Separator + if (g.GroupStack.Size > 0 && g.GroupStack.back().WindowID == window->ID) + x1 += window->DC.Indent.x; + + // FIXME-WORKRECT: In theory we should simply be using WorkRect.Min.x/Max.x everywhere but it isn't aesthetically what we want, + // need to introduce a variant of WorkRect for that purpose. (#4787) + if (ImGuiTable* table = g.CurrentTable) + { + x1 = table->Columns[table->CurrentColumn].MinX; + x2 = table->Columns[table->CurrentColumn].MaxX; + } + + ImGuiOldColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL; + if (columns) + PushColumnsBackground(); + + // We don't provide our width to the layout so that it doesn't get feed back into AutoFit + // FIXME: This prevents ->CursorMaxPos based bounding box evaluation from working (e.g. TableEndCell) + const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + thickness_draw)); + ItemSize(ImVec2(0.0f, thickness_layout)); + const bool item_visible = ItemAdd(bb, 0); + if (item_visible) + { + // Draw + window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x, bb.Min.y), GetColorU32(ImGuiCol_Separator)); + if (g.LogEnabled) + LogRenderedText(&bb.Min, "--------------------------------\n"); + + } + if (columns) + { + PopColumnsBackground(); + columns->LineMinY = window->DC.CursorPos.y; + } + } +} + +void ImGui::Separator() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + // Those flags should eventually be overridable by the user + ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal; + flags |= ImGuiSeparatorFlags_SpanAllColumns; // NB: this only applies to legacy Columns() api as they relied on Separator() a lot. + SeparatorEx(flags); +} + +// Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise. +bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend, float hover_visibility_delay, ImU32 bg_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags; + g.CurrentItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus; + bool item_add = ItemAdd(bb, id); + g.CurrentItemFlags = item_flags_backup; + if (!item_add) + return false; + + bool hovered, held; + ImRect bb_interact = bb; + bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f)); + ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap); + if (hovered) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect; // for IsItemHovered(), because bb_interact is larger than bb + if (g.ActiveId != id) + SetItemAllowOverlap(); + + if (held || (hovered && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay)) + SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW); + + ImRect bb_render = bb; + if (held) + { + ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min; + float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x; + + // Minimum pane size + float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1); + float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2); + if (mouse_delta < -size_1_maximum_delta) + mouse_delta = -size_1_maximum_delta; + if (mouse_delta > size_2_maximum_delta) + mouse_delta = size_2_maximum_delta; + + // Apply resize + if (mouse_delta != 0.0f) + { + if (mouse_delta < 0.0f) + IM_ASSERT(*size1 + mouse_delta >= min_size1); + if (mouse_delta > 0.0f) + IM_ASSERT(*size2 - mouse_delta >= min_size2); + *size1 += mouse_delta; + *size2 -= mouse_delta; + bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta)); + MarkItemEdited(id); + } + } + + // Render at new position + if (bg_col & IM_COL32_A_MASK) + window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, bg_col, 0.0f); + const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); + window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, 0.0f); + + return held; +} + +static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs) +{ + const ImGuiShrinkWidthItem* a = (const ImGuiShrinkWidthItem*)lhs; + const ImGuiShrinkWidthItem* b = (const ImGuiShrinkWidthItem*)rhs; + if (int d = (int)(b->Width - a->Width)) + return d; + return (b->Index - a->Index); +} + +// Shrink excess width from a set of item, by removing width from the larger items first. +// Set items Width to -1.0f to disable shrinking this item. +void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess) +{ + if (count == 1) + { + if (items[0].Width >= 0.0f) + items[0].Width = ImMax(items[0].Width - width_excess, 1.0f); + return; + } + ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); + int count_same_width = 1; + while (width_excess > 0.0f && count_same_width < count) + { + while (count_same_width < count && items[0].Width <= items[count_same_width].Width) + count_same_width++; + float max_width_to_remove_per_item = (count_same_width < count && items[count_same_width].Width >= 0.0f) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f); + if (max_width_to_remove_per_item <= 0.0f) + break; + float width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item); + for (int item_n = 0; item_n < count_same_width; item_n++) + items[item_n].Width -= width_to_remove_per_item; + width_excess -= width_to_remove_per_item * count_same_width; + } + + // Round width and redistribute remainder left-to-right (could make it an option of the function?) + // Ensure that e.g. the right-most tab of a shrunk tab-bar always reaches exactly at the same distance from the right-most edge of the tab bar separator. + width_excess = 0.0f; + for (int n = 0; n < count; n++) + { + float width_rounded = ImFloor(items[n].Width); + width_excess += items[n].Width - width_rounded; + items[n].Width = width_rounded; + } + if (width_excess > 0.0f) + for (int n = 0; n < count; n++) + if (items[n].Index < (int)(width_excess + 0.01f)) + items[n].Width += 1.0f; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: ComboBox +//------------------------------------------------------------------------- +// - CalcMaxPopupHeightFromItemCount() [Internal] +// - BeginCombo() +// - BeginComboPopup() [Internal] +// - EndCombo() +// - BeginComboPreview() [Internal] +// - EndComboPreview() [Internal] +// - Combo() +//------------------------------------------------------------------------- + +static float CalcMaxPopupHeightFromItemCount(int items_count) +{ + ImGuiContext& g = *GImGui; + if (items_count <= 0) + return FLT_MAX; + return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2); +} + +bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + ImGuiNextWindowDataFlags backup_next_window_data_flags = g.NextWindowData.Flags; + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together + + const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight(); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : CalcItemWidth(); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); + const ImRect total_bb(bb.Min, bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &bb)) + return false; + + // Open on click + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + const ImGuiID popup_id = ImHashStr("##ComboPopup", 0, id); + bool popup_open = IsPopupOpen(popup_id, ImGuiPopupFlags_None); + if (pressed && !popup_open) + { + OpenPopupEx(popup_id, ImGuiPopupFlags_None); + popup_open = true; + } + + // Render shape + const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + const float value_x2 = ImMax(bb.Min.x, bb.Max.x - arrow_size); + RenderNavHighlight(bb, id); + if (!(flags & ImGuiComboFlags_NoPreview)) + window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersLeft); + if (!(flags & ImGuiComboFlags_NoArrowButton)) + { + ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + ImU32 text_col = GetColorU32(ImGuiCol_Text); + window->DrawList->AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersRight); + if (value_x2 + arrow_size - style.FramePadding.x <= bb.Max.x) + RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f); + } + RenderFrameBorder(bb.Min, bb.Max, style.FrameRounding); + + // Custom preview + if (flags & ImGuiComboFlags_CustomPreview) + { + g.ComboPreviewData.PreviewRect = ImRect(bb.Min.x, bb.Min.y, value_x2, bb.Max.y); + IM_ASSERT(preview_value == NULL || preview_value[0] == 0); + preview_value = NULL; + } + + // Render preview and label + if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview)) + { + if (g.LogEnabled) + LogSetNextTextDecoration("{", "}"); + RenderTextClipped(bb.Min + style.FramePadding, ImVec2(value_x2, bb.Max.y), preview_value, NULL, NULL); + } + if (label_size.x > 0) + RenderText(ImVec2(bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y), label); + + if (!popup_open) + return false; + + g.NextWindowData.Flags = backup_next_window_data_flags; + return BeginComboPopup(popup_id, bb, flags); +} + +bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags) +{ + ImGuiContext& g = *GImGui; + if (!IsPopupOpen(popup_id, ImGuiPopupFlags_None)) + { + g.NextWindowData.ClearFlags(); + return false; + } + + // Set popup size + float w = bb.GetWidth(); + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) + { + g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w); + } + else + { + if ((flags & ImGuiComboFlags_HeightMask_) == 0) + flags |= ImGuiComboFlags_HeightRegular; + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one + int popup_max_height_in_items = -1; + if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8; + else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4; + else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20; + SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); + } + + // This is essentially a specialized version of BeginPopupEx() + char name[16]; + ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth + + // Set position given a custom constraint (peak into expected window size so we can position it) + // FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function? + // FIXME: This might be moved to Begin() or at least around the same spot where Tooltips and other Popups are calling FindBestWindowPosForPopupEx()? + if (ImGuiWindow* popup_window = FindWindowByName(name)) + if (popup_window->WasActive) + { + // Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us. + ImVec2 size_expected = CalcWindowNextAutoFitSize(popup_window); + popup_window->AutoPosLastDirection = (flags & ImGuiComboFlags_PopupAlignLeft) ? ImGuiDir_Left : ImGuiDir_Down; // Left = "Below, Toward Left", Down = "Below, Toward Right (default)" + ImRect r_outer = GetPopupAllowedExtentRect(popup_window); + ImVec2 pos = FindBestWindowPosForPopupEx(bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, bb, ImGuiPopupPositionPolicy_ComboBox); + SetNextWindowPos(pos); + } + + // We don't use BeginPopupEx() solely because we have a custom name string, which we could make an argument to BeginPopupEx() + ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove; + PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(g.Style.FramePadding.x, g.Style.WindowPadding.y)); // Horizontally align ourselves with the framed text + bool ret = Begin(name, NULL, window_flags); + PopStyleVar(); + if (!ret) + { + EndPopup(); + IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above + return false; + } + return true; +} + +void ImGui::EndCombo() +{ + EndPopup(); +} + +// Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements +// (Experimental, see GitHub issues: #1658, #4168) +bool ImGui::BeginComboPreview() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiComboPreviewData* preview_data = &g.ComboPreviewData; + + if (window->SkipItems || !window->ClipRect.Overlaps(g.LastItemData.Rect)) // FIXME: Because we don't have a ImGuiItemStatusFlags_Visible flag to test last ItemAdd() result + return false; + IM_ASSERT(g.LastItemData.Rect.Min.x == preview_data->PreviewRect.Min.x && g.LastItemData.Rect.Min.y == preview_data->PreviewRect.Min.y); // Didn't call after BeginCombo/EndCombo block or forgot to pass ImGuiComboFlags_CustomPreview flag? + if (!window->ClipRect.Contains(preview_data->PreviewRect)) // Narrower test (optional) + return false; + + // FIXME: This could be contained in a PushWorkRect() api + preview_data->BackupCursorPos = window->DC.CursorPos; + preview_data->BackupCursorMaxPos = window->DC.CursorMaxPos; + preview_data->BackupCursorPosPrevLine = window->DC.CursorPosPrevLine; + preview_data->BackupPrevLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; + preview_data->BackupLayout = window->DC.LayoutType; + window->DC.CursorPos = preview_data->PreviewRect.Min + g.Style.FramePadding; + window->DC.CursorMaxPos = window->DC.CursorPos; + window->DC.LayoutType = ImGuiLayoutType_Horizontal; + window->DC.IsSameLine = false; + PushClipRect(preview_data->PreviewRect.Min, preview_data->PreviewRect.Max, true); + + return true; +} + +void ImGui::EndComboPreview() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiComboPreviewData* preview_data = &g.ComboPreviewData; + + // FIXME: Using CursorMaxPos approximation instead of correct AABB which we will store in ImDrawCmd in the future + ImDrawList* draw_list = window->DrawList; + if (window->DC.CursorMaxPos.x < preview_data->PreviewRect.Max.x && window->DC.CursorMaxPos.y < preview_data->PreviewRect.Max.y) + if (draw_list->CmdBuffer.Size > 1) // Unlikely case that the PushClipRect() didn't create a command + { + draw_list->_CmdHeader.ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 2].ClipRect; + draw_list->_TryMergeDrawCmds(); + } + PopClipRect(); + window->DC.CursorPos = preview_data->BackupCursorPos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, preview_data->BackupCursorMaxPos); + window->DC.CursorPosPrevLine = preview_data->BackupCursorPosPrevLine; + window->DC.PrevLineTextBaseOffset = preview_data->BackupPrevLineTextBaseOffset; + window->DC.LayoutType = preview_data->BackupLayout; + window->DC.IsSameLine = false; + preview_data->PreviewRect = ImRect(); +} + +// Getter for the old Combo() API: const char*[] +static bool Items_ArrayGetter(void* data, int idx, const char** out_text) +{ + const char* const* items = (const char* const*)data; + if (out_text) + *out_text = items[idx]; + return true; +} + +// Getter for the old Combo() API: "item1\0item2\0item3\0" +static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) +{ + // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited. + const char* items_separated_by_zeros = (const char*)data; + int items_count = 0; + const char* p = items_separated_by_zeros; + while (*p) + { + if (idx == items_count) + break; + p += strlen(p) + 1; + items_count++; + } + if (!*p) + return false; + if (out_text) + *out_text = p; + return true; +} + +// Old API, prefer using BeginCombo() nowadays if you can. +bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items) +{ + ImGuiContext& g = *GImGui; + + // Call the getter to obtain the preview string which is a parameter to BeginCombo() + const char* preview_value = NULL; + if (*current_item >= 0 && *current_item < items_count) + items_getter(data, *current_item, &preview_value); + + // The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here. + if (popup_max_height_in_items != -1 && !(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)) + SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); + + if (!BeginCombo(label, preview_value, ImGuiComboFlags_None)) + return false; + + // Display items + // FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed) + bool value_changed = false; + for (int i = 0; i < items_count; i++) + { + PushID(i); + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + if (Selectable(item_text, item_selected)) + { + value_changed = true; + *current_item = i; + } + if (item_selected) + SetItemDefaultFocus(); + PopID(); + } + + EndCombo(); + + if (value_changed) + MarkItemEdited(g.LastItemData.ID); + + return value_changed; +} + +// Combo box helper allowing to pass an array of strings. +bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items) +{ + const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); + return value_changed; +} + +// Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0" +bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) +{ + int items_count = 0; + const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open + while (*p) + { + p += strlen(p) + 1; + items_count++; + } + bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); + return value_changed; +} + +//------------------------------------------------------------------------- +// [SECTION] Data Type and Data Formatting Helpers [Internal] +//------------------------------------------------------------------------- +// - PatchFormatStringFloatToInt() +// - DataTypeGetInfo() +// - DataTypeFormatString() +// - DataTypeApplyOp() +// - DataTypeApplyOpFromText() +// - DataTypeClamp() +// - GetMinimumStepAtDecimalPrecision +// - RoundScalarWithFormat<>() +//------------------------------------------------------------------------- + +static const ImGuiDataTypeInfo GDataTypeInfo[] = +{ + { sizeof(char), "S8", "%d", "%d" }, // ImGuiDataType_S8 + { sizeof(unsigned char), "U8", "%u", "%u" }, + { sizeof(short), "S16", "%d", "%d" }, // ImGuiDataType_S16 + { sizeof(unsigned short), "U16", "%u", "%u" }, + { sizeof(int), "S32", "%d", "%d" }, // ImGuiDataType_S32 + { sizeof(unsigned int), "U32", "%u", "%u" }, +#ifdef _MSC_VER + { sizeof(ImS64), "S64", "%I64d","%I64d" }, // ImGuiDataType_S64 + { sizeof(ImU64), "U64", "%I64u","%I64u" }, +#else + { sizeof(ImS64), "S64", "%lld", "%lld" }, // ImGuiDataType_S64 + { sizeof(ImU64), "U64", "%llu", "%llu" }, +#endif + { sizeof(float), "float", "%.3f","%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg) + { sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double +}; +IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT); + +// FIXME-LEGACY: Prior to 1.61 our DragInt() function internally used floats and because of this the compile-time default value for format was "%.0f". +// Even though we changed the compile-time default, we expect users to have carried %f around, which would break the display of DragInt() calls. +// To honor backward compatibility we are rewriting the format string, unless IMGUI_DISABLE_OBSOLETE_FUNCTIONS is enabled. What could possibly go wrong?! +static const char* PatchFormatStringFloatToInt(const char* fmt) +{ + if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '0' && fmt[3] == 'f' && fmt[4] == 0) // Fast legacy path for "%.0f" which is expected to be the most common case. + return "%d"; + const char* fmt_start = ImParseFormatFindStart(fmt); // Find % (if any, and ignore %%) + const char* fmt_end = ImParseFormatFindEnd(fmt_start); // Find end of format specifier, which itself is an exercise of confidence/recklessness (because snprintf is dependent on libc or user). + if (fmt_end > fmt_start && fmt_end[-1] == 'f') + { +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + if (fmt_start == fmt && fmt_end[0] == 0) + return "%d"; + ImGuiContext& g = *GImGui; + ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%.*s%%d%s", (int)(fmt_start - fmt), fmt, fmt_end); // Honor leading and trailing decorations, but lose alignment/precision. + return g.TempBuffer; +#else + IM_ASSERT(0 && "DragInt(): Invalid format string!"); // Old versions used a default parameter of "%.0f", please replace with e.g. "%d" +#endif + } + return fmt; +} + +const ImGuiDataTypeInfo* ImGui::DataTypeGetInfo(ImGuiDataType data_type) +{ + IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); + return &GDataTypeInfo[data_type]; +} + +int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format) +{ + // Signedness doesn't matter when pushing integer arguments + if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32) + return ImFormatString(buf, buf_size, format, *(const ImU32*)p_data); + if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64) + return ImFormatString(buf, buf_size, format, *(const ImU64*)p_data); + if (data_type == ImGuiDataType_Float) + return ImFormatString(buf, buf_size, format, *(const float*)p_data); + if (data_type == ImGuiDataType_Double) + return ImFormatString(buf, buf_size, format, *(const double*)p_data); + if (data_type == ImGuiDataType_S8) + return ImFormatString(buf, buf_size, format, *(const ImS8*)p_data); + if (data_type == ImGuiDataType_U8) + return ImFormatString(buf, buf_size, format, *(const ImU8*)p_data); + if (data_type == ImGuiDataType_S16) + return ImFormatString(buf, buf_size, format, *(const ImS16*)p_data); + if (data_type == ImGuiDataType_U16) + return ImFormatString(buf, buf_size, format, *(const ImU16*)p_data); + IM_ASSERT(0); + return 0; +} + +void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg1, const void* arg2) +{ + IM_ASSERT(op == '+' || op == '-'); + switch (data_type) + { + case ImGuiDataType_S8: + if (op == '+') { *(ImS8*)output = ImAddClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); } + if (op == '-') { *(ImS8*)output = ImSubClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); } + return; + case ImGuiDataType_U8: + if (op == '+') { *(ImU8*)output = ImAddClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); } + if (op == '-') { *(ImU8*)output = ImSubClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); } + return; + case ImGuiDataType_S16: + if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); } + if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); } + return; + case ImGuiDataType_U16: + if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); } + if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); } + return; + case ImGuiDataType_S32: + if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); } + if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); } + return; + case ImGuiDataType_U32: + if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); } + if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); } + return; + case ImGuiDataType_S64: + if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); } + if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); } + return; + case ImGuiDataType_U64: + if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); } + if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); } + return; + case ImGuiDataType_Float: + if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; } + if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; } + return; + case ImGuiDataType_Double: + if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; } + if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; } + return; + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); +} + +// User can input math operators (e.g. +100) to edit a numerical values. +// NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess.. +bool ImGui::DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format) +{ + while (ImCharIsBlankA(*buf)) + buf++; + if (!buf[0]) + return false; + + // Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all. + const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type); + ImGuiDataTypeTempStorage data_backup; + memcpy(&data_backup, p_data, type_info->Size); + + // Sanitize format + // For float/double we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in, so force them into %f and %lf + char format_sanitized[32]; + if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) + format = type_info->ScanFmt; + else + format = ImParseFormatSanitizeForScanning(format, format_sanitized, IM_ARRAYSIZE(format_sanitized)); + + // Small types need a 32-bit buffer to receive the result from scanf() + int v32 = 0; + if (sscanf(buf, format, type_info->Size >= 4 ? p_data : &v32) < 1) + return false; + if (type_info->Size < 4) + { + if (data_type == ImGuiDataType_S8) + *(ImS8*)p_data = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX); + else if (data_type == ImGuiDataType_U8) + *(ImU8*)p_data = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX); + else if (data_type == ImGuiDataType_S16) + *(ImS16*)p_data = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX); + else if (data_type == ImGuiDataType_U16) + *(ImU16*)p_data = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX); + else + IM_ASSERT(0); + } + + return memcmp(&data_backup, p_data, type_info->Size) != 0; +} + +template +static int DataTypeCompareT(const T* lhs, const T* rhs) +{ + if (*lhs < *rhs) return -1; + if (*lhs > *rhs) return +1; + return 0; +} + +int ImGui::DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2) +{ + switch (data_type) + { + case ImGuiDataType_S8: return DataTypeCompareT((const ImS8* )arg_1, (const ImS8* )arg_2); + case ImGuiDataType_U8: return DataTypeCompareT((const ImU8* )arg_1, (const ImU8* )arg_2); + case ImGuiDataType_S16: return DataTypeCompareT((const ImS16* )arg_1, (const ImS16* )arg_2); + case ImGuiDataType_U16: return DataTypeCompareT((const ImU16* )arg_1, (const ImU16* )arg_2); + case ImGuiDataType_S32: return DataTypeCompareT((const ImS32* )arg_1, (const ImS32* )arg_2); + case ImGuiDataType_U32: return DataTypeCompareT((const ImU32* )arg_1, (const ImU32* )arg_2); + case ImGuiDataType_S64: return DataTypeCompareT((const ImS64* )arg_1, (const ImS64* )arg_2); + case ImGuiDataType_U64: return DataTypeCompareT((const ImU64* )arg_1, (const ImU64* )arg_2); + case ImGuiDataType_Float: return DataTypeCompareT((const float* )arg_1, (const float* )arg_2); + case ImGuiDataType_Double: return DataTypeCompareT((const double*)arg_1, (const double*)arg_2); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return 0; +} + +template +static bool DataTypeClampT(T* v, const T* v_min, const T* v_max) +{ + // Clamp, both sides are optional, return true if modified + if (v_min && *v < *v_min) { *v = *v_min; return true; } + if (v_max && *v > *v_max) { *v = *v_max; return true; } + return false; +} + +bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max) +{ + switch (data_type) + { + case ImGuiDataType_S8: return DataTypeClampT((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max); + case ImGuiDataType_U8: return DataTypeClampT((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max); + case ImGuiDataType_S16: return DataTypeClampT((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max); + case ImGuiDataType_U16: return DataTypeClampT((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max); + case ImGuiDataType_S32: return DataTypeClampT((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max); + case ImGuiDataType_U32: return DataTypeClampT((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max); + case ImGuiDataType_S64: return DataTypeClampT((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max); + case ImGuiDataType_U64: return DataTypeClampT((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max); + case ImGuiDataType_Float: return DataTypeClampT((float* )p_data, (const float* )p_min, (const float* )p_max); + case ImGuiDataType_Double: return DataTypeClampT((double*)p_data, (const double*)p_min, (const double*)p_max); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return false; +} + +static float GetMinimumStepAtDecimalPrecision(int decimal_precision) +{ + static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; + if (decimal_precision < 0) + return FLT_MIN; + return (decimal_precision < IM_ARRAYSIZE(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision); +} + +template +TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v) +{ + IM_UNUSED(data_type); + IM_ASSERT(data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const char* fmt_start = ImParseFormatFindStart(format); + if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string + return v; + + // Sanitize format + char fmt_sanitized[32]; + ImParseFormatSanitizeForPrinting(fmt_start, fmt_sanitized, IM_ARRAYSIZE(fmt_sanitized)); + fmt_start = fmt_sanitized; + + // Format value with our rounding, and read back + char v_str[64]; + ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v); + const char* p = v_str; + while (*p == ' ') + p++; + v = (TYPE)ImAtof(p); + + return v; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +//------------------------------------------------------------------------- +// - DragBehaviorT<>() [Internal] +// - DragBehavior() [Internal] +// - DragScalar() +// - DragScalarN() +// - DragFloat() +// - DragFloat2() +// - DragFloat3() +// - DragFloat4() +// - DragFloatRange2() +// - DragInt() +// - DragInt2() +// - DragInt3() +// - DragInt4() +// - DragIntRange2() +//------------------------------------------------------------------------- + +// This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) +template +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiContext& g = *GImGui; + const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const bool is_clamped = (v_min < v_max); + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0; + const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); + + // Default tweak speed + if (v_speed == 0.0f && is_clamped && (v_max - v_min < FLT_MAX)) + v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio); + + // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings + float adjust_delta = 0.0f; + if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR)) + { + adjust_delta = g.IO.MouseDelta[axis]; + if (g.IO.KeyAlt) + adjust_delta *= 1.0f / 100.0f; + if (g.IO.KeyShift) + adjust_delta *= 10.0f; + } + else if (g.ActiveIdSource == ImGuiInputSource_Nav) + { + const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0; + adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiNavReadMode_RepeatFast, 1.0f / 10.0f, 10.0f)[axis]; + v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision)); + } + adjust_delta *= v_speed; + + // For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter. + if (axis == ImGuiAxis_Y) + adjust_delta = -adjust_delta; + + // For logarithmic use our range is effectively 0..1 so scale the delta into that range + if (is_logarithmic && (v_max - v_min < FLT_MAX) && ((v_max - v_min) > 0.000001f)) // Epsilon to avoid /0 + adjust_delta /= (float)(v_max - v_min); + + // Clear current value on activation + // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300. + bool is_just_activated = g.ActiveIdIsJustActivated; + bool is_already_past_limits_and_pushing_outward = is_clamped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); + if (is_just_activated || is_already_past_limits_and_pushing_outward) + { + g.DragCurrentAccum = 0.0f; + g.DragCurrentAccumDirty = false; + } + else if (adjust_delta != 0.0f) + { + g.DragCurrentAccum += adjust_delta; + g.DragCurrentAccumDirty = true; + } + + if (!g.DragCurrentAccumDirty) + return false; + + TYPE v_cur = *v; + FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; + + float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense) + if (is_logarithmic) + { + // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. + const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1; + logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); + + // Convert to parametric space, apply delta, convert back + float v_old_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + float v_new_parametric = v_old_parametric + g.DragCurrentAccum; + v_cur = ScaleValueFromRatioT(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + v_old_ref_for_accum_remainder = v_old_parametric; + } + else + { + v_cur += (SIGNEDTYPE)g.DragCurrentAccum; + } + + // Round to user desired precision based on format string + if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat)) + v_cur = RoundScalarWithFormatT(format, data_type, v_cur); + + // Preserve remainder after rounding has been applied. This also allow slow tweaking of values. + g.DragCurrentAccumDirty = false; + if (is_logarithmic) + { + // Convert to parametric space, apply delta, convert back + float v_new_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); + } + else + { + g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v); + } + + // Lose zero sign for float/double + if (v_cur == (TYPE)-0) + v_cur = (TYPE)0; + + // Clamp values (+ handle overflow/wrap-around for integer types) + if (*v != v_cur && is_clamped) + { + if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_floating_point)) + v_cur = v_min; + if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_floating_point)) + v_cur = v_max; + } + + // Apply result + if (*v == v_cur) + return false; + *v = v_cur; + return true; +} + +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +{ + // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); + + ImGuiContext& g = *GImGui; + if (g.ActiveId == id) + { + if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0]) + ClearActiveID(); + else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) + ClearActiveID(); + } + if (g.ActiveId != id) + return false; + if ((g.LastItemData.InFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly)) + return false; + + switch (data_type) + { + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN, p_max ? *(const ImS8*)p_max : IM_S8_MAX, format, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN, p_max ? *(const ImU8*)p_max : IM_U8_MAX, format, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } + case ImGuiDataType_S32: return DragBehaviorT(data_type, (ImS32*)p_v, v_speed, p_min ? *(const ImS32* )p_min : IM_S32_MIN, p_max ? *(const ImS32* )p_max : IM_S32_MAX, format, flags); + case ImGuiDataType_U32: return DragBehaviorT(data_type, (ImU32*)p_v, v_speed, p_min ? *(const ImU32* )p_min : IM_U32_MIN, p_max ? *(const ImU32* )p_max : IM_U32_MAX, format, flags); + case ImGuiDataType_S64: return DragBehaviorT(data_type, (ImS64*)p_v, v_speed, p_min ? *(const ImS64* )p_min : IM_S64_MIN, p_max ? *(const ImS64* )p_max : IM_S64_MAX, format, flags); + case ImGuiDataType_U64: return DragBehaviorT(data_type, (ImU64*)p_v, v_speed, p_min ? *(const ImU64* )p_min : IM_U64_MIN, p_max ? *(const ImU64* )p_max : IM_U64_MAX, format, flags); + case ImGuiDataType_Float: return DragBehaviorT(data_type, (float*)p_v, v_speed, p_min ? *(const float* )p_min : -FLT_MAX, p_max ? *(const float* )p_max : FLT_MAX, format, flags); + case ImGuiDataType_Double: return DragBehaviorT(data_type, (double*)p_v, v_speed, p_min ? *(const double*)p_min : -DBL_MAX, p_max ? *(const double*)p_max : DBL_MAX, format, flags); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return false; +} + +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. +// Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0; + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0)) + return false; + + // Default format string when passing NULL + if (format == NULL) + format = DataTypeGetInfo(data_type)->PrintFmt; + else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.) + format = PatchFormatStringFloatToInt(format); + + // Tabbing or CTRL-clicking on Drag turns it into an InputText + const bool hovered = ItemHoverable(frame_bb, id); + bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); + if (!temp_input_is_active) + { + const bool input_requested_by_tabbing = temp_input_allowed && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_FocusedByTabbing) != 0; + const bool clicked = (hovered && g.IO.MouseClicked[0]); + const bool double_clicked = (hovered && g.IO.MouseClickedCount[0] == 2); + if (input_requested_by_tabbing || clicked || double_clicked || g.NavActivateId == id || g.NavActivateInputId == id) + { + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); + if (temp_input_allowed) + if (input_requested_by_tabbing || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavActivateInputId == id) + temp_input_is_active = true; + } + + // Experimental: simple click (without moving) turns Drag into an InputText + if (g.IO.ConfigDragClickToInputText && temp_input_allowed && !temp_input_is_active) + if (g.ActiveId == id && hovered && g.IO.MouseReleased[0] && !IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR)) + { + g.NavActivateId = g.NavActivateInputId = id; + g.NavActivateFlags = ImGuiActivateFlags_PreferInput; + temp_input_is_active = true; + } + } + + if (temp_input_is_active) + { + // Only clamp CTRL+Click input when ImGuiSliderFlags_AlwaysClamp is set + const bool is_clamp_input = (flags & ImGuiSliderFlags_AlwaysClamp) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0); + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); + } + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderNavHighlight(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); + + // Drag behavior + const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, flags); + if (value_changed) + MarkItemEdited(id); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format); + if (g.LogEnabled) + LogSetNextTextDecoration("{", "}"); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return value_changed; +} + +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components, CalcItemWidth()); + size_t type_size = GDataTypeInfo[data_type].Size; + for (int i = 0; i < components; i++) + { + PushID(i); + if (i > 0) + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags); + PopID(); + PopItemWidth(); + p_data = (void*)((char*)p_data + type_size); + } + PopID(); + + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0, g.Style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + + EndGroup(); + return value_changed; +} + +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); +} + +// NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2, CalcItemWidth()); + + float min_min = (v_min >= v_max) ? -FLT_MAX : v_min; + float min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0); + bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min_min, &min_max, format, min_flags); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + float max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + float max_max = (v_min >= v_max) ? FLT_MAX : v_max; + ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0); + value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &max_min, &max_max, format_max ? format_max : format, max_flags); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextEx(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +// NB: v_speed is float to allow adjusting the drag speed with more precision +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags); +} + +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); +} + +// NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2, CalcItemWidth()); + + int min_min = (v_min >= v_max) ? INT_MIN : v_min; + int min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0); + bool value_changed = DragInt("##min", v_current_min, v_speed, min_min, min_max, format, min_flags); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + int max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + int max_max = (v_min >= v_max) ? INT_MAX : v_max; + ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0); + value_changed |= DragInt("##max", v_current_max, v_speed, max_min, max_max, format_max ? format_max : format, max_flags); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextEx(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +// Obsolete versions with power parameter. See https://github.com/ocornut/imgui/issues/3361 for details. +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +{ + ImGuiSliderFlags drag_flags = ImGuiSliderFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); + IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds + drag_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths + } + return DragScalar(label, data_type, p_data, v_speed, p_min, p_max, format, drag_flags); +} + +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +{ + ImGuiSliderFlags drag_flags = ImGuiSliderFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); + IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds + drag_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths + } + return DragScalarN(label, data_type, p_data, components, v_speed, p_min, p_max, format, drag_flags); +} + +#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +//------------------------------------------------------------------------- +// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +//------------------------------------------------------------------------- +// - ScaleRatioFromValueT<> [Internal] +// - ScaleValueFromRatioT<> [Internal] +// - SliderBehaviorT<>() [Internal] +// - SliderBehavior() [Internal] +// - SliderScalar() +// - SliderScalarN() +// - SliderFloat() +// - SliderFloat2() +// - SliderFloat3() +// - SliderFloat4() +// - SliderAngle() +// - SliderInt() +// - SliderInt2() +// - SliderInt3() +// - SliderInt4() +// - VSliderScalar() +// - VSliderFloat() +// - VSliderInt() +//------------------------------------------------------------------------- + +// Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT) +template +float ImGui::ScaleRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize) +{ + if (v_min == v_max) + return 0.0f; + IM_UNUSED(data_type); + + const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); + if (is_logarithmic) + { + bool flipped = v_max < v_min; + + if (flipped) // Handle the case where the range is backwards + ImSwap(v_min, v_max); + + // Fudge min/max to avoid getting close to log(0) + FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; + FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; + + // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) + if ((v_min == 0.0f) && (v_max < 0.0f)) + v_min_fudged = -logarithmic_zero_epsilon; + else if ((v_max == 0.0f) && (v_min < 0.0f)) + v_max_fudged = -logarithmic_zero_epsilon; + + float result; + + if (v_clamped <= v_min_fudged) + result = 0.0f; // Workaround for values that are in-range but below our fudge + else if (v_clamped >= v_max_fudged) + result = 1.0f; // Workaround for values that are in-range but above our fudge + else if ((v_min * v_max) < 0.0f) // Range crosses zero, so split into two portions + { + float zero_point_center = (-(float)v_min) / ((float)v_max - (float)v_min); // The zero point in parametric space. There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine) + float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize; + float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize; + if (v == 0.0f) + result = zero_point_center; // Special case for exactly zero + else if (v < 0.0f) + result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point_snap_L; + else + result = zero_point_snap_R + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - zero_point_snap_R)); + } + else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider + result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged)); + else + result = (float)(ImLog((FLOATTYPE)v_clamped / v_min_fudged) / ImLog(v_max_fudged / v_min_fudged)); + + return flipped ? (1.0f - result) : result; + } + + // Linear slider + return (float)((FLOATTYPE)(SIGNEDTYPE)(v_clamped - v_min) / (FLOATTYPE)(SIGNEDTYPE)(v_max - v_min)); +} + +// Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT) +template +TYPE ImGui::ScaleValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize) +{ + if (v_min == v_max) + return v_min; + const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); + + TYPE result; + if (is_logarithmic) + { + // We special-case the extents because otherwise our fudging can lead to "mathematically correct" but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value + if (t <= 0.0f) + result = v_min; + else if (t >= 1.0f) + result = v_max; + else + { + bool flipped = v_max < v_min; // Check if range is "backwards" + + // Fudge min/max to avoid getting silly results close to zero + FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; + FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; + + if (flipped) + ImSwap(v_min_fudged, v_max_fudged); + + // Awkward special case - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) + if ((v_max == 0.0f) && (v_min < 0.0f)) + v_max_fudged = -logarithmic_zero_epsilon; + + float t_with_flip = flipped ? (1.0f - t) : t; // t, but flipped if necessary to account for us flipping the range + + if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts + { + float zero_point_center = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space + float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize; + float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize; + if (t_with_flip >= zero_point_snap_L && t_with_flip <= zero_point_snap_R) + result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) + else if (t_with_flip < zero_point_center) + result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point_snap_L)))); + else + result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - zero_point_snap_R) / (1.0f - zero_point_snap_R)))); + } + else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider + result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip))); + else + result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip)); + } + } + else + { + // Linear slider + if (is_floating_point) + { + result = ImLerp(v_min, v_max, t); + } + else + { + // - For integer values we want the clicking position to match the grab box so we round above + // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. + // - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64 + // range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits. + if (t < 1.0) + { + FLOATTYPE v_new_off_f = (SIGNEDTYPE)(v_max - v_min) * t; + result = (TYPE)((SIGNEDTYPE)v_min + (SIGNEDTYPE)(v_new_off_f + (FLOATTYPE)(v_min > v_max ? -0.5 : 0.5))); + } + else + { + result = v_max; + } + } + } + + return result; +} + +// FIXME: Move more of the code into SliderBehavior() +template +bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0; + const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); + + const float grab_padding = 2.0f; + const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f; + float grab_sz = style.GrabMinSize; + SIGNEDTYPE v_range = (v_min < v_max ? v_max - v_min : v_min - v_max); + if (!is_floating_point && v_range >= 0) // v_range < 0 may happen on integer overflows + grab_sz = ImMax((float)(slider_sz / (v_range + 1)), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit + grab_sz = ImMin(grab_sz, slider_sz); + const float slider_usable_sz = slider_sz - grab_sz; + const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f; + const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f; + + float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + float zero_deadzone_halfsize = 0.0f; // Only valid when is_logarithmic is true + if (is_logarithmic) + { + // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. + const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1; + logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); + zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f); + } + + // Process interacting with the slider + bool value_changed = false; + if (g.ActiveId == id) + { + bool set_new_value = false; + float clicked_t = 0.0f; + if (g.ActiveIdSource == ImGuiInputSource_Mouse) + { + if (!g.IO.MouseDown[0]) + { + ClearActiveID(); + } + else + { + const float mouse_abs_pos = g.IO.MousePos[axis]; + clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f; + if (axis == ImGuiAxis_Y) + clicked_t = 1.0f - clicked_t; + set_new_value = true; + } + } + else if (g.ActiveIdSource == ImGuiInputSource_Nav) + { + if (g.ActiveIdIsJustActivated) + { + g.SliderCurrentAccum = 0.0f; // Reset any stored nav delta upon activation + g.SliderCurrentAccumDirty = false; + } + + const ImVec2 input_delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiNavReadMode_RepeatFast, 0.0f, 0.0f); + float input_delta = (axis == ImGuiAxis_X) ? input_delta2.x : -input_delta2.y; + if (input_delta != 0.0f) + { + const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0; + if (decimal_precision > 0) + { + input_delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds + if (IsNavInputDown(ImGuiNavInput_TweakSlow)) + input_delta /= 10.0f; + } + else + { + if ((v_range >= -100.0f && v_range <= 100.0f) || IsNavInputDown(ImGuiNavInput_TweakSlow)) + input_delta = ((input_delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps + else + input_delta /= 100.0f; + } + if (IsNavInputDown(ImGuiNavInput_TweakFast)) + input_delta *= 10.0f; + + g.SliderCurrentAccum += input_delta; + g.SliderCurrentAccumDirty = true; + } + + float delta = g.SliderCurrentAccum; + if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) + { + ClearActiveID(); + } + else if (g.SliderCurrentAccumDirty) + { + clicked_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + + if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits + { + set_new_value = false; + g.SliderCurrentAccum = 0.0f; // If pushing up against the limits, don't continue to accumulate + } + else + { + set_new_value = true; + float old_clicked_t = clicked_t; + clicked_t = ImSaturate(clicked_t + delta); + + // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator + TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat)) + v_new = RoundScalarWithFormatT(format, data_type, v_new); + float new_clicked_t = ScaleRatioFromValueT(data_type, v_new, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + + if (delta > 0) + g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta); + else + g.SliderCurrentAccum -= ImMax(new_clicked_t - old_clicked_t, delta); + } + + g.SliderCurrentAccumDirty = false; + } + } + + if (set_new_value) + { + TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + + // Round to user desired precision based on format string + if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat)) + v_new = RoundScalarWithFormatT(format, data_type, v_new); + + // Apply result + if (*v != v_new) + { + *v = v_new; + value_changed = true; + } + } + } + + if (slider_sz < 1.0f) + { + *out_grab_bb = ImRect(bb.Min, bb.Min); + } + else + { + // Output grab position so it can be displayed by the caller + float grab_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + if (axis == ImGuiAxis_Y) + grab_t = 1.0f - grab_t; + const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); + if (axis == ImGuiAxis_X) + *out_grab_bb = ImRect(grab_pos - grab_sz * 0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz * 0.5f, bb.Max.y - grab_padding); + else + *out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz * 0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz * 0.5f); + } + + return value_changed; +} + +// For 32-bit and larger types, slider bounds are limited to half the natural type range. +// So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. +// It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. +bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb) +{ + // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flag! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); + + ImGuiContext& g = *GImGui; + if ((g.LastItemData.InFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly)) + return false; + + switch (data_type) + { + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min, *(const ImS8*)p_max, format, flags, out_grab_bb); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)p_min, *(const ImU8*)p_max, format, flags, out_grab_bb); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } + case ImGuiDataType_S32: + IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN / 2 && *(const ImS32*)p_max <= IM_S32_MAX / 2); + return SliderBehaviorT(bb, id, data_type, (ImS32*)p_v, *(const ImS32*)p_min, *(const ImS32*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_U32: + IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX / 2); + return SliderBehaviorT(bb, id, data_type, (ImU32*)p_v, *(const ImU32*)p_min, *(const ImU32*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_S64: + IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN / 2 && *(const ImS64*)p_max <= IM_S64_MAX / 2); + return SliderBehaviorT(bb, id, data_type, (ImS64*)p_v, *(const ImS64*)p_min, *(const ImS64*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_U64: + IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX / 2); + return SliderBehaviorT(bb, id, data_type, (ImU64*)p_v, *(const ImU64*)p_min, *(const ImU64*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_Float: + IM_ASSERT(*(const float*)p_min >= -FLT_MAX / 2.0f && *(const float*)p_max <= FLT_MAX / 2.0f); + return SliderBehaviorT(bb, id, data_type, (float*)p_v, *(const float*)p_min, *(const float*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_Double: + IM_ASSERT(*(const double*)p_min >= -DBL_MAX / 2.0f && *(const double*)p_max <= DBL_MAX / 2.0f); + return SliderBehaviorT(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, flags, out_grab_bb); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return false; +} + +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. +// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0; + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0)) + return false; + + // Default format string when passing NULL + if (format == NULL) + format = DataTypeGetInfo(data_type)->PrintFmt; + else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.) + format = PatchFormatStringFloatToInt(format); + + // Tabbing or CTRL-clicking on Slider turns it into an input box + const bool hovered = ItemHoverable(frame_bb, id); + bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); + if (!temp_input_is_active) + { + const bool input_requested_by_tabbing = temp_input_allowed && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_FocusedByTabbing) != 0; + const bool clicked = (hovered && g.IO.MouseClicked[0]); + if (input_requested_by_tabbing || clicked || g.NavActivateId == id || g.NavActivateInputId == id) + { + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); + if (temp_input_allowed && (input_requested_by_tabbing || (clicked && g.IO.KeyCtrl) || g.NavActivateInputId == id)) + temp_input_is_active = true; + } + } + + if (temp_input_is_active) + { + // Only clamp CTRL+Click input when ImGuiSliderFlags_AlwaysClamp is set + const bool is_clamp_input = (flags & ImGuiSliderFlags_AlwaysClamp) != 0; + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); + } + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderNavHighlight(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding); + + // Slider behavior + ImRect grab_bb; + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags, &grab_bb); + if (value_changed) + MarkItemEdited(id); + + // Render grab + if (grab_bb.Max.x > grab_bb.Min.x) + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format); + if (g.LogEnabled) + LogSetNextTextDecoration("{", "}"); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return value_changed; +} + +// Add multiple sliders on 1 line for compact edition of multiple components +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components, CalcItemWidth()); + size_t type_size = GDataTypeInfo[data_type].Size; + for (int i = 0; i < components; i++) + { + PushID(i); + if (i > 0) + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags); + PopID(); + PopItemWidth(); + v = (void*)((char*)v + type_size); + } + PopID(); + + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0, g.Style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + + EndGroup(); + return value_changed; +} + +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags) +{ + if (format == NULL) + format = "%.0f deg"; + float v_deg = (*v_rad) * 360.0f / (2 * IM_PI); + bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, flags); + *v_rad = v_deg * (2 * IM_PI) / 360.0f; + return value_changed; +} + +bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags); +} + +bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags); +} + +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); + const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(frame_bb, id)) + return false; + + // Default format string when passing NULL + if (format == NULL) + format = DataTypeGetInfo(data_type)->PrintFmt; + else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.) + format = PatchFormatStringFloatToInt(format); + + const bool hovered = ItemHoverable(frame_bb, id); + if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavActivateInputId == id) + { + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); + } + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderNavHighlight(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding); + + // Slider behavior + ImRect grab_bb; + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags | ImGuiSliderFlags_Vertical, &grab_bb); + if (value_changed) + MarkItemEdited(id); + + // Render grab + if (grab_bb.Max.y > grab_bb.Min.y) + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + // For the vertical slider we allow centered text to overlap the frame padding + char value_buf[64]; + const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.0f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + return value_changed; +} + +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) +{ + return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); +} + +bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) +{ + return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +// Obsolete versions with power parameter. See https://github.com/ocornut/imgui/issues/3361 for details. +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +{ + ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); + slider_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths + } + return SliderScalar(label, data_type, p_data, p_min, p_max, format, slider_flags); +} + +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) +{ + ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); + slider_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths + } + return SliderScalarN(label, data_type, v, components, v_min, v_max, format, slider_flags); +} + +#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +//------------------------------------------------------------------------- +// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +//------------------------------------------------------------------------- +// - ImParseFormatFindStart() [Internal] +// - ImParseFormatFindEnd() [Internal] +// - ImParseFormatTrimDecorations() [Internal] +// - ImParseFormatSanitizeForPrinting() [Internal] +// - ImParseFormatSanitizeForScanning() [Internal] +// - ImParseFormatPrecision() [Internal] +// - TempInputTextScalar() [Internal] +// - InputScalar() +// - InputScalarN() +// - InputFloat() +// - InputFloat2() +// - InputFloat3() +// - InputFloat4() +// - InputInt() +// - InputInt2() +// - InputInt3() +// - InputInt4() +// - InputDouble() +//------------------------------------------------------------------------- + +// We don't use strchr() because our strings are usually very short and often start with '%' +const char* ImParseFormatFindStart(const char* fmt) +{ + while (char c = fmt[0]) + { + if (c == '%' && fmt[1] != '%') + return fmt; + else if (c == '%') + fmt++; + fmt++; + } + return fmt; +} + +const char* ImParseFormatFindEnd(const char* fmt) +{ + // Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format. + if (fmt[0] != '%') + return fmt; + const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A')); + const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a')); + for (char c; (c = *fmt) != 0; fmt++) + { + if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0) + return fmt + 1; + if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0) + return fmt + 1; + } + return fmt; +} + +// Extract the format out of a format string with leading or trailing decorations +// fmt = "blah blah" -> return fmt +// fmt = "%.3f" -> return fmt +// fmt = "hello %.3f" -> return fmt + 6 +// fmt = "%.3f hello" -> return buf written with "%.3f" +const char* ImParseFormatTrimDecorations(const char* fmt, char* buf, size_t buf_size) +{ + const char* fmt_start = ImParseFormatFindStart(fmt); + if (fmt_start[0] != '%') + return fmt; + const char* fmt_end = ImParseFormatFindEnd(fmt_start); + if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data. + return fmt_start; + ImStrncpy(buf, fmt_start, ImMin((size_t)(fmt_end - fmt_start) + 1, buf_size)); + return buf; +} + +// Sanitize format +// - Zero terminate so extra characters after format (e.g. "%f123") don't confuse atof/atoi +// - stb_sprintf.h supports several new modifiers which format numbers in a way that also makes them incompatible atof/atoi. +void ImParseFormatSanitizeForPrinting(const char* fmt_in, char* fmt_out, size_t fmt_out_size) +{ + const char* fmt_end = ImParseFormatFindEnd(fmt_in); + IM_UNUSED(fmt_out_size); + IM_ASSERT((size_t)(fmt_end - fmt_in + 1) < fmt_out_size); // Format is too long, let us know if this happens to you! + while (fmt_in < fmt_end) + { + char c = *fmt_in++; + if (c != '\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '. + *(fmt_out++) = c; + } + *fmt_out = 0; // Zero-terminate +} + +// - For scanning we need to remove all width and precision fields "%3.7f" -> "%f". BUT don't strip types like "%I64d" which includes digits. ! "%07I64d" -> "%I64d" +const char* ImParseFormatSanitizeForScanning(const char* fmt_in, char* fmt_out, size_t fmt_out_size) +{ + const char* fmt_end = ImParseFormatFindEnd(fmt_in); + const char* fmt_out_begin = fmt_out; + IM_UNUSED(fmt_out_size); + IM_ASSERT((size_t)(fmt_end - fmt_in + 1) < fmt_out_size); // Format is too long, let us know if this happens to you! + bool has_type = false; + while (fmt_in < fmt_end) + { + char c = *fmt_in++; + if (!has_type && ((c >= '0' && c <= '9') || c == '.')) + continue; + has_type |= ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); // Stop skipping digits + if (c != '\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '. + *(fmt_out++) = c; + } + *fmt_out = 0; // Zero-terminate + return fmt_out_begin; +} + +template +static const char* ImAtoi(const char* src, TYPE* output) +{ + int negative = 0; + if (*src == '-') { negative = 1; src++; } + if (*src == '+') { src++; } + TYPE v = 0; + while (*src >= '0' && *src <= '9') + v = (v * 10) + (*src++ - '0'); + *output = negative ? -v : v; + return src; +} + +// Parse display precision back from the display format string +// FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed. +int ImParseFormatPrecision(const char* fmt, int default_precision) +{ + fmt = ImParseFormatFindStart(fmt); + if (fmt[0] != '%') + return default_precision; + fmt++; + while (*fmt >= '0' && *fmt <= '9') + fmt++; + int precision = INT_MAX; + if (*fmt == '.') + { + fmt = ImAtoi(fmt + 1, &precision); + if (precision < 0 || precision > 99) + precision = default_precision; + } + if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation + precision = -1; + if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX) + precision = -1; + return (precision == INT_MAX) ? default_precision : precision; +} + +// Create text input in place of another active widget (e.g. used when doing a CTRL+Click on drag/slider widgets) +// FIXME: Facilitate using this in variety of other situations. +bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags) +{ + // On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id. + // We clear ActiveID on the first frame to allow the InputText() taking it back. + ImGuiContext& g = *GImGui; + const bool init = (g.TempInputId != id); + if (init) + ClearActiveID(); + + g.CurrentWindow->DC.CursorPos = bb.Min; + bool value_changed = InputTextEx(label, NULL, buf, buf_size, bb.GetSize(), flags | ImGuiInputTextFlags_MergedItem); + if (init) + { + // First frame we started displaying the InputText widget, we expect it to take the active id. + IM_ASSERT(g.ActiveId == id); + g.TempInputId = g.ActiveId; + } + return value_changed; +} + +static inline ImGuiInputTextFlags InputScalar_DefaultCharsFilter(ImGuiDataType data_type, const char* format) +{ + if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) + return ImGuiInputTextFlags_CharsScientific; + const char format_last_char = format[0] ? format[strlen(format) - 1] : 0; + return (format_last_char == 'x' || format_last_char == 'X') ? ImGuiInputTextFlags_CharsHexadecimal : ImGuiInputTextFlags_CharsDecimal; +} + +// Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags_AlwaysClamp flag is set! +// This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. +// However this may not be ideal for all uses, as some user code may break on out of bound values. +bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) +{ + char fmt_buf[32]; + char data_buf[32]; + format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf)); + DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format); + ImStrTrimBlanks(data_buf); + + ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; + flags |= InputScalar_DefaultCharsFilter(data_type, format); + + bool value_changed = false; + if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags)) + { + // Backup old value + size_t data_type_size = DataTypeGetInfo(data_type)->Size; + ImGuiDataTypeTempStorage data_backup; + memcpy(&data_backup, p_data, data_type_size); + + // Apply new value (or operations) then clamp + DataTypeApplyFromText(data_buf, data_type, p_data, format); + if (p_clamp_min || p_clamp_max) + { + if (p_clamp_min && p_clamp_max && DataTypeCompare(data_type, p_clamp_min, p_clamp_max) > 0) + ImSwap(p_clamp_min, p_clamp_max); + DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max); + } + + // Only mark as edited if new value is different + value_changed = memcmp(&data_backup, p_data, data_type_size) != 0; + if (value_changed) + MarkItemEdited(id); + } + return value_changed; +} + +// Note: p_data, p_step, p_step_fast are _pointers_ to a memory address holding the data. For an Input widget, p_step and p_step_fast are optional. +// Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + + if (format == NULL) + format = DataTypeGetInfo(data_type)->PrintFmt; + + char buf[64]; + DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, p_data, format); + + // Testing ActiveId as a minor optimization as filtering is not needed until active + if (g.ActiveId == 0 && (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0) + flags |= InputScalar_DefaultCharsFilter(data_type, format); + flags |= ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselves by comparing the actual data rather than the string. + + bool value_changed = false; + if (p_step != NULL) + { + const float button_size = GetFrameHeight(); + + BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() + PushID(label); + SetNextItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)); + if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view + value_changed = DataTypeApplyFromText(buf, data_type, p_data, format); + + // Step buttons + const ImVec2 backup_frame_padding = style.FramePadding; + style.FramePadding.x = style.FramePadding.y; + ImGuiButtonFlags button_flags = ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups; + if (flags & ImGuiInputTextFlags_ReadOnly) + BeginDisabled(); + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("-", ImVec2(button_size, button_size), button_flags)) + { + DataTypeApplyOp(data_type, '-', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step); + value_changed = true; + } + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("+", ImVec2(button_size, button_size), button_flags)) + { + DataTypeApplyOp(data_type, '+', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step); + value_changed = true; + } + if (flags & ImGuiInputTextFlags_ReadOnly) + EndDisabled(); + + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0, style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + style.FramePadding = backup_frame_padding; + + PopID(); + EndGroup(); + } + else + { + if (InputText(label, buf, IM_ARRAYSIZE(buf), flags)) + value_changed = DataTypeApplyFromText(buf, data_type, p_data, format); + } + if (value_changed) + MarkItemEdited(g.LastItemData.ID); + + return value_changed; +} + +bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components, CalcItemWidth()); + size_t type_size = GDataTypeInfo[data_type].Size; + for (int i = 0; i < components; i++) + { + PushID(i); + if (i > 0) + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= InputScalar("", data_type, p_data, p_step, p_step_fast, format, flags); + PopID(); + PopItemWidth(); + p_data = (void*)((char*)p_data + type_size); + } + PopID(); + + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0.0f, g.Style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + + EndGroup(); + return value_changed; +} + +bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags) +{ + flags |= ImGuiInputTextFlags_CharsScientific; + return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step > 0.0f ? &step : NULL), (void*)(step_fast > 0.0f ? &step_fast : NULL), format, flags); +} + +bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags); +} + +bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags); +} + +bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags); +} + +bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags) +{ + // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. + const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; + return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step > 0 ? &step : NULL), (void*)(step_fast > 0 ? &step_fast : NULL), format, flags); +} + +bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", flags); +} + +bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", flags); +} + +bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags) +{ + return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", flags); +} + +bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags) +{ + flags |= ImGuiInputTextFlags_CharsScientific; + return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step > 0.0 ? &step : NULL), (void*)(step_fast > 0.0 ? &step_fast : NULL), format, flags); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint +//------------------------------------------------------------------------- +// - InputText() +// - InputTextWithHint() +// - InputTextMultiline() +// - InputTextGetCharInfo() [Internal] +// - InputTextReindexLines() [Internal] +// - InputTextReindexLinesRange() [Internal] +// - InputTextEx() [Internal] +//------------------------------------------------------------------------- + +bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() + return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); +} + +bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); +} + +bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() + return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); +} + +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) +{ + int line_count = 0; + const char* s = text_begin; + while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding + if (c == '\n') + line_count++; + s--; + if (s[0] != '\n' && s[0] != '\r') + line_count++; + *out_text_end = s; + return line_count; +} + +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) +{ + ImGuiContext& g = *GImGui; + ImFont* font = g.Font; + const float line_height = g.FontSize; + const float scale = line_height / font->FontSize; + + ImVec2 text_size = ImVec2(0, 0); + float line_width = 0.0f; + + const ImWchar* s = text_begin; + while (s < text_end) + { + unsigned int c = (unsigned int)(*s++); + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + if (stop_on_new_line) + break; + continue; + } + if (c == '\r') + continue; + + const float char_width = font->GetCharAdvance((ImWchar)c) * scale; + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (out_offset) + *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n + + if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + +// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) +namespace ImStb +{ + +static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->CurLenW; } +static ImWchar STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { return obj->TextW[idx]; } +static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx + char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *GImGui; return g.Font->GetCharAdvance(c) * (g.FontSize / g.Font->FontSize); } +static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x200000 ? 0 : key; } +static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; +static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx) +{ + const ImWchar* text = obj->TextW.Data; + const ImWchar* text_remaining = NULL; + const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true); + r->x0 = 0.0f; + r->x1 = size.x; + r->baseline_y_delta = size.y; + r->ymin = 0.0f; + r->ymax = size.y; + r->num_chars = (int)(text_remaining - (text + line_start_idx)); +} + +// When ImGuiInputTextFlags_Password is set, we don't want actions such as CTRL+Arrow to leak the fact that underlying data are blanks or separators. +static bool is_separator(unsigned int c) { return ImCharIsBlankW(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|' || c=='\n' || c=='\r'; } +static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx) { if (obj->Flags & ImGuiInputTextFlags_Password) return 0; return idx > 0 ? (is_separator(obj->TextW[idx - 1]) && !is_separator(obj->TextW[idx]) ) : 1; } +static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx) { if (obj->Flags & ImGuiInputTextFlags_Password) return 0; return idx > 0 ? (!is_separator(obj->TextW[idx - 1]) && is_separator(obj->TextW[idx])) : 1; } +static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } +static int STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } +#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h +#ifdef __APPLE__ // FIXME: Move setting to IO structure +#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_MAC +#else +static int STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } +#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_WIN +#endif + +static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n) +{ + ImWchar* dst = obj->TextW.Data + pos; + + // We maintain our buffer length in both UTF-8 and wchar formats + obj->Edited = true; + obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); + obj->CurLenW -= n; + + // Offset remaining text (FIXME-OPT: Use memmove) + const ImWchar* src = obj->TextW.Data + pos + n; + while (ImWchar c = *src++) + *dst++ = c; + *dst = '\0'; +} + +static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const ImWchar* new_text, int new_text_len) +{ + const bool is_resizable = (obj->Flags & ImGuiInputTextFlags_CallbackResize) != 0; + const int text_len = obj->CurLenW; + IM_ASSERT(pos <= text_len); + + const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len); + if (!is_resizable && (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufCapacityA)) + return false; + + // Grow internal buffer if needed + if (new_text_len + text_len + 1 > obj->TextW.Size) + { + if (!is_resizable) + return false; + IM_ASSERT(text_len < obj->TextW.Size); + obj->TextW.resize(text_len + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1); + } + + ImWchar* text = obj->TextW.Data; + if (pos != text_len) + memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); + memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); + + obj->Edited = true; + obj->CurLenW += new_text_len; + obj->CurLenA += new_text_len_utf8; + obj->TextW[obj->CurLenW] = '\0'; + + return true; +} + +// We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) +#define STB_TEXTEDIT_K_LEFT 0x200000 // keyboard input to move cursor left +#define STB_TEXTEDIT_K_RIGHT 0x200001 // keyboard input to move cursor right +#define STB_TEXTEDIT_K_UP 0x200002 // keyboard input to move cursor up +#define STB_TEXTEDIT_K_DOWN 0x200003 // keyboard input to move cursor down +#define STB_TEXTEDIT_K_LINESTART 0x200004 // keyboard input to move cursor to start of line +#define STB_TEXTEDIT_K_LINEEND 0x200005 // keyboard input to move cursor to end of line +#define STB_TEXTEDIT_K_TEXTSTART 0x200006 // keyboard input to move cursor to start of text +#define STB_TEXTEDIT_K_TEXTEND 0x200007 // keyboard input to move cursor to end of text +#define STB_TEXTEDIT_K_DELETE 0x200008 // keyboard input to delete selection or character under cursor +#define STB_TEXTEDIT_K_BACKSPACE 0x200009 // keyboard input to delete selection or character left of cursor +#define STB_TEXTEDIT_K_UNDO 0x20000A // keyboard input to perform undo +#define STB_TEXTEDIT_K_REDO 0x20000B // keyboard input to perform redo +#define STB_TEXTEDIT_K_WORDLEFT 0x20000C // keyboard input to move cursor left one word +#define STB_TEXTEDIT_K_WORDRIGHT 0x20000D // keyboard input to move cursor right one word +#define STB_TEXTEDIT_K_PGUP 0x20000E // keyboard input to move cursor up a page +#define STB_TEXTEDIT_K_PGDOWN 0x20000F // keyboard input to move cursor down a page +#define STB_TEXTEDIT_K_SHIFT 0x400000 + +#define STB_TEXTEDIT_IMPLEMENTATION +#include "imstb_textedit.h" + +// stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling +// the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?) +static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* state, const STB_TEXTEDIT_CHARTYPE* text, int text_len) +{ + stb_text_makeundo_replace(str, state, 0, str->CurLenW, text_len); + ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->CurLenW); + if (text_len <= 0) + return; + if (ImStb::STB_TEXTEDIT_INSERTCHARS(str, 0, text, text_len)) + { + state->cursor = text_len; + state->has_preferred_x = 0; + return; + } + IM_ASSERT(0); // Failed to insert character, normally shouldn't happen because of how we currently use stb_textedit_replace() +} + +} // namespace ImStb + +void ImGuiInputTextState::OnKeyPressed(int key) +{ + stb_textedit_key(this, &Stb, key); + CursorFollow = true; + CursorAnimReset(); +} + +ImGuiInputTextCallbackData::ImGuiInputTextCallbackData() +{ + memset(this, 0, sizeof(*this)); +} + +// Public API to manipulate UTF-8 text +// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) +// FIXME: The existence of this rarely exercised code path is a bit of a nuisance. +void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count) +{ + IM_ASSERT(pos + bytes_count <= BufTextLen); + char* dst = Buf + pos; + const char* src = Buf + pos + bytes_count; + while (char c = *src++) + *dst++ = c; + *dst = '\0'; + + if (CursorPos >= pos + bytes_count) + CursorPos -= bytes_count; + else if (CursorPos >= pos) + CursorPos = pos; + SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen -= bytes_count; +} + +void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) +{ + const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; + const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); + if (new_text_len + BufTextLen >= BufSize) + { + if (!is_resizable) + return; + + // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the mildly similar code (until we remove the U16 buffer altogether!) + ImGuiContext& g = *GImGui; + ImGuiInputTextState* edit_state = &g.InputTextState; + IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID); + IM_ASSERT(Buf == edit_state->TextA.Data); + int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; + edit_state->TextA.reserve(new_buf_size + 1); + Buf = edit_state->TextA.Data; + BufSize = edit_state->BufCapacityA = new_buf_size; + } + + if (BufTextLen != pos) + memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); + memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); + Buf[BufTextLen + new_text_len] = '\0'; + + if (CursorPos >= pos) + CursorPos += new_text_len; + SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen += new_text_len; +} + +// Return false to discard a character. +static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, ImGuiInputSource input_source) +{ + IM_ASSERT(input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Clipboard); + unsigned int c = *p_char; + + // Filter non-printable (NB: isprint is unreliable! see #2467) + bool apply_named_filters = true; + if (c < 0x20) + { + bool pass = false; + pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline)); // Note that an Enter KEY will emit \r and be ignored (we poll for KEY in InputText() code) + pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput)); + if (!pass) + return false; + apply_named_filters = false; // Override named filters below so newline and tabs can still be inserted. + } + + if (input_source != ImGuiInputSource_Clipboard) + { + // We ignore Ascii representation of delete (emitted from Backspace on OSX, see #2578, #2817) + if (c == 127) + return false; + + // Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME) + if (c >= 0xE000 && c <= 0xF8FF) + return false; + } + + // Filter Unicode ranges we are not handling in this build + if (c > IM_UNICODE_CODEPOINT_MAX) + return false; + + // Generic named filters + if (apply_named_filters && (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific))) + { + // The libc allows overriding locale, with e.g. 'setlocale(LC_NUMERIC, "de_DE.UTF-8");' which affect the output/input of printf/scanf to use e.g. ',' instead of '.'. + // The standard mandate that programs starts in the "C" locale where the decimal point is '.'. + // We don't really intend to provide widespread support for it, but out of empathy for people stuck with using odd API, we support the bare minimum aka overriding the decimal point. + // Change the default decimal_point with: + // ImGui::GetCurrentContext()->PlatformLocaleDecimalPoint = *localeconv()->decimal_point; + // Users of non-default decimal point (in particular ',') may be affected by word-selection logic (is_word_boundary_from_right/is_word_boundary_from_left) functions. + ImGuiContext& g = *GImGui; + const unsigned c_decimal_point = (unsigned int)g.PlatformLocaleDecimalPoint; + + // Allow 0-9 . - + * / + if (flags & ImGuiInputTextFlags_CharsDecimal) + if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/')) + return false; + + // Allow 0-9 . - + * / e E + if (flags & ImGuiInputTextFlags_CharsScientific) + if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E')) + return false; + + // Allow 0-9 a-F A-F + if (flags & ImGuiInputTextFlags_CharsHexadecimal) + if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) + return false; + + // Turn a-z into A-Z + if (flags & ImGuiInputTextFlags_CharsUppercase) + if (c >= 'a' && c <= 'z') + *p_char = (c += (unsigned int)('A' - 'a')); + + if (flags & ImGuiInputTextFlags_CharsNoBlank) + if (ImCharIsBlankW(c)) + return false; + } + + // Custom callback filter + if (flags & ImGuiInputTextFlags_CallbackCharFilter) + { + ImGuiInputTextCallbackData callback_data; + memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData)); + callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; + callback_data.EventChar = (ImWchar)c; + callback_data.Flags = flags; + callback_data.UserData = user_data; + if (callback(&callback_data) != 0) + return false; + *p_char = callback_data.EventChar; + if (!callback_data.EventChar) + return false; + } + + return true; +} + +// Edit a string of text +// - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!". +// This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match +// Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator. +// - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect. +// - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h +// (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are +// doing UTF8 > U16 > UTF8 conversions on the go to easily interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188) +bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + IM_ASSERT(buf != NULL && buf_size >= 0); + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) + + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + const ImGuiStyle& style = g.Style; + + const bool RENDER_SELECTION_WHEN_INACTIVE = false; + const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; + const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0; + const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; + const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0; + const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0; + if (is_resizable) + IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag! + + if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope (including the scrollbar) + BeginGroup(); + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? g.FontSize * 8.0f : label_size.y) + style.FramePadding.y * 2.0f); // Arbitrary default of 8 lines high for multi-line + const ImVec2 total_size = ImVec2(frame_size.x + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), frame_size.y); + + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + const ImRect total_bb(frame_bb.Min, frame_bb.Min + total_size); + + ImGuiWindow* draw_window = window; + ImVec2 inner_size = frame_size; + ImGuiItemStatusFlags item_status_flags = 0; + ImGuiLastItemData item_data_backup; + if (is_multiline) + { + ImVec2 backup_pos = window->DC.CursorPos; + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable)) + { + EndGroup(); + return false; + } + item_status_flags = g.LastItemData.StatusFlags; + item_data_backup = g.LastItemData; + window->DC.CursorPos = backup_pos; + + // We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug. + // FIXME-NAV: Pressing NavActivate will trigger general child activation right before triggering our own below. Harmless but bizarre. + PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]); + PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); + PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); + PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Ensure no clip rect so mouse hover can reach FramePadding edges + bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), true, ImGuiWindowFlags_NoMove); + PopStyleVar(3); + PopStyleColor(); + if (!child_visible) + { + EndChild(); + EndGroup(); + return false; + } + draw_window = g.CurrentWindow; // Child window + draw_window->DC.NavLayersActiveMaskNext |= (1 << draw_window->DC.NavLayerCurrent); // This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it. + draw_window->DC.CursorPos += style.FramePadding; + inner_size.x -= draw_window->ScrollbarSizes.x; + } + else + { + // Support for internal ImGuiInputTextFlags_MergedItem flag, which could be redesigned as an ItemFlags if needed (with test performed in ItemAdd) + ItemSize(total_bb, style.FramePadding.y); + if (!(flags & ImGuiInputTextFlags_MergedItem)) + if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable)) + return false; + item_status_flags = g.LastItemData.StatusFlags; + } + const bool hovered = ItemHoverable(frame_bb, id); + if (hovered) + g.MouseCursor = ImGuiMouseCursor_TextInput; + + // We are only allowed to access the state if we are already the active widget. + ImGuiInputTextState* state = GetInputTextState(id); + + const bool input_requested_by_tabbing = (item_status_flags & ImGuiItemStatusFlags_FocusedByTabbing) != 0; + const bool input_requested_by_nav = (g.ActiveId != id) && ((g.NavActivateInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_Keyboard)); + + const bool user_clicked = hovered && io.MouseClicked[0]; + const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetWindowScrollbarID(draw_window, ImGuiAxis_Y); + const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetWindowScrollbarID(draw_window, ImGuiAxis_Y); + bool clear_active_id = false; + bool select_all = false; + + float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX; + + const bool init_changed_specs = (state != NULL && state->Stb.single_line != !is_multiline); + const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav || input_requested_by_tabbing); + const bool init_state = (init_make_active || user_scroll_active); + if ((init_state && g.ActiveId != id) || init_changed_specs) + { + // Access state even if we don't own it yet. + state = &g.InputTextState; + state->CursorAnimReset(); + + // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) + // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) + const int buf_len = (int)strlen(buf); + state->InitialTextA.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string. + memcpy(state->InitialTextA.Data, buf, buf_len + 1); + + // Start edition + const char* buf_end = NULL; + state->TextW.resize(buf_size + 1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string. + state->TextA.resize(0); + state->TextAIsValid = false; // TextA is not valid yet (we will display buf until then) + state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end); + state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. + + // Preserve cursor position and undo/redo stack if we come back to same widget + // FIXME: For non-readonly widgets we might be able to require that TextAIsValid && TextA == buf ? (untested) and discard undo stack if user buffer has changed. + const bool recycle_state = (state->ID == id && !init_changed_specs); + if (recycle_state) + { + // Recycle existing cursor/selection/undo stack but clamp position + // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. + state->CursorClamp(); + } + else + { + state->ID = id; + state->ScrollX = 0.0f; + stb_textedit_initialize_state(&state->Stb, !is_multiline); + } + + if (!is_multiline) + { + if (flags & ImGuiInputTextFlags_AutoSelectAll) + select_all = true; + if (input_requested_by_nav && (!recycle_state || !(g.NavActivateFlags & ImGuiActivateFlags_TryToPreserveState))) + select_all = true; + if (input_requested_by_tabbing || (user_clicked && io.KeyCtrl)) + select_all = true; + } + + if (flags & ImGuiInputTextFlags_AlwaysOverwrite) + state->Stb.insert_mode = 1; // stb field name is indeed incorrect (see #2863) + } + + if (g.ActiveId != id && init_make_active) + { + IM_ASSERT(state && state->ID == id); + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + + // Declare our inputs + IM_ASSERT(ImGuiNavInput_COUNT < 32); + g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); + if (is_multiline || (flags & ImGuiInputTextFlags_CallbackHistory)) + g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); + g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); + SetActiveIdUsingKey(ImGuiKey_Home); + SetActiveIdUsingKey(ImGuiKey_End); + if (is_multiline) + { + SetActiveIdUsingKey(ImGuiKey_PageUp); + SetActiveIdUsingKey(ImGuiKey_PageDown); + } + if (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) // Disable keyboard tabbing out as we will use the \t character. + { + SetActiveIdUsingKey(ImGuiKey_Tab); + } + } + + // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function) + if (g.ActiveId == id && state == NULL) + ClearActiveID(); + + // Release focus when we click outside + if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560 + clear_active_id = true; + + // Lock the decision of whether we are going to take the path displaying the cursor or selection + const bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active); + bool render_selection = state && (state->HasSelection() || select_all) && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); + bool value_changed = false; + bool enter_pressed = false; + + // When read-only we always use the live data passed to the function + // FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :( + if (is_readonly && state != NULL && (render_cursor || render_selection)) + { + const char* buf_end = NULL; + state->TextW.resize(buf_size + 1); + state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end); + state->CurLenA = (int)(buf_end - buf); + state->CursorClamp(); + render_selection &= state->HasSelection(); + } + + // Select the buffer to render. + const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid; + const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0); + + // Password pushes a temporary font with only a fallback glyph + if (is_password && !is_displaying_hint) + { + const ImFontGlyph* glyph = g.Font->FindGlyph('*'); + ImFont* password_font = &g.InputTextPasswordFont; + password_font->FontSize = g.Font->FontSize; + password_font->Scale = g.Font->Scale; + password_font->Ascent = g.Font->Ascent; + password_font->Descent = g.Font->Descent; + password_font->ContainerAtlas = g.Font->ContainerAtlas; + password_font->FallbackGlyph = glyph; + password_font->FallbackAdvanceX = glyph->AdvanceX; + IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty()); + PushFont(password_font); + } + + // Process mouse inputs and character inputs + int backup_current_text_length = 0; + if (g.ActiveId == id) + { + IM_ASSERT(state != NULL); + backup_current_text_length = state->CurLenA; + state->Edited = false; + state->BufCapacityA = buf_size; + state->Flags = flags; + + // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. + // Down the line we should have a cleaner library-wide concept of Selected vs Active. + g.ActiveIdAllowOverlap = !io.MouseDown[0]; + g.WantTextInputNextFrame = 1; + + // Edit in progress + const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->ScrollX; + const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y) : (g.FontSize * 0.5f)); + + const bool is_osx = io.ConfigMacOSXBehaviors; + if (select_all) + { + state->SelectAll(); + state->SelectedAllMouseLock = true; + } + else if (hovered && io.MouseClickedCount[0] >= 2 && !io.KeyShift) + { + stb_textedit_click(state, &state->Stb, mouse_x, mouse_y); + const int multiclick_count = (io.MouseClickedCount[0] - 2); + if ((multiclick_count % 2) == 0) + { + // Double-click: Select word + // We always use the "Mac" word advance for double-click select vs CTRL+Right which use the platform dependent variant: + // FIXME: There are likely many ways to improve this behavior, but there's no "right" behavior (depends on use-case, software, OS) + const bool is_bol = (state->Stb.cursor == 0) || ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb.cursor - 1) == '\n'; + if (STB_TEXT_HAS_SELECTION(&state->Stb) || !is_bol) + state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); + //state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); + if (!STB_TEXT_HAS_SELECTION(&state->Stb)) + ImStb::stb_textedit_prep_selection_at_cursor(&state->Stb); + state->Stb.cursor = ImStb::STB_TEXTEDIT_MOVEWORDRIGHT_MAC(state, state->Stb.cursor); + state->Stb.select_end = state->Stb.cursor; + ImStb::stb_textedit_clamp(state, &state->Stb); + } + else + { + // Triple-click: Select line + const bool is_eol = ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb.cursor) == '\n'; + state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART); + state->OnKeyPressed(STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT); + state->OnKeyPressed(STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT); + if (!is_eol && is_multiline) + { + ImSwap(state->Stb.select_start, state->Stb.select_end); + state->Stb.cursor = state->Stb.select_end; + } + state->CursorFollow = false; + } + state->CursorAnimReset(); + } + else if (io.MouseClicked[0] && !state->SelectedAllMouseLock) + { + // FIXME: unselect on late click could be done release? + if (hovered) + { + stb_textedit_click(state, &state->Stb, mouse_x, mouse_y); + state->CursorAnimReset(); + } + } + else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) + { + stb_textedit_drag(state, &state->Stb, mouse_x, mouse_y); + state->CursorAnimReset(); + state->CursorFollow = true; + } + if (state->SelectedAllMouseLock && !io.MouseDown[0]) + state->SelectedAllMouseLock = false; + + // We except backends to emit a Tab key but some also emit a Tab character which we ignore (#2467, #1336) + // (For Tab and Enter: Win32/SFML/Allegro are sending both keys and chars, GLFW and SDL are only sending keys. For Space they all send all threes) + const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper); + if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressed(ImGuiKey_Tab) && !ignore_char_inputs && !io.KeyShift && !is_readonly) + { + unsigned int c = '\t'; // Insert TAB + if (InputTextFilterCharacter(&c, flags, callback, callback_user_data, ImGuiInputSource_Keyboard)) + state->OnKeyPressed((int)c); + } + + // Process regular text input (before we check for Return because using some IME will effectively send a Return?) + // We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. + if (io.InputQueueCharacters.Size > 0) + { + if (!ignore_char_inputs && !is_readonly && !input_requested_by_nav) + for (int n = 0; n < io.InputQueueCharacters.Size; n++) + { + // Insert character if they pass filtering + unsigned int c = (unsigned int)io.InputQueueCharacters[n]; + if (c == '\t') // Skip Tab, see above. + continue; + if (InputTextFilterCharacter(&c, flags, callback, callback_user_data, ImGuiInputSource_Keyboard)) + state->OnKeyPressed((int)c); + } + + // Consume characters + io.InputQueueCharacters.resize(0); + } + } + + // Process other shortcuts/key-presses + bool cancel_edit = false; + if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id) + { + IM_ASSERT(state != NULL); + + const int row_count_per_page = ImMax((int)((inner_size.y - style.FramePadding.y) / g.FontSize), 1); + state->Stb.row_count_per_page = row_count_per_page; + + const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); + const bool is_osx = io.ConfigMacOSXBehaviors; + const bool is_osx_shift_shortcut = is_osx && (io.KeyMods == (ImGuiModFlags_Super | ImGuiModFlags_Shift)); + const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl + const bool is_startend_key_down = is_osx && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End + const bool is_ctrl_key_only = (io.KeyMods == ImGuiModFlags_Ctrl); + const bool is_shift_key_only = (io.KeyMods == ImGuiModFlags_Shift); + const bool is_shortcut_key = g.IO.ConfigMacOSXBehaviors ? (io.KeyMods == ImGuiModFlags_Super) : (io.KeyMods == ImGuiModFlags_Ctrl); + + const bool is_cut = ((is_shortcut_key && IsKeyPressed(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressed(ImGuiKey_Delete))) && !is_readonly && !is_password && (!is_multiline || state->HasSelection()); + const bool is_copy = ((is_shortcut_key && IsKeyPressed(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressed(ImGuiKey_Insert))) && !is_password && (!is_multiline || state->HasSelection()); + const bool is_paste = ((is_shortcut_key && IsKeyPressed(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressed(ImGuiKey_Insert))) && !is_readonly; + const bool is_undo = ((is_shortcut_key && IsKeyPressed(ImGuiKey_Z)) && !is_readonly && is_undoable); + const bool is_redo = ((is_shortcut_key && IsKeyPressed(ImGuiKey_Y)) || (is_osx_shift_shortcut && IsKeyPressed(ImGuiKey_Z))) && !is_readonly && is_undoable; + + // We allow validate/cancel with Nav source (gamepad) to makes it easier to undo an accidental NavInput press with no keyboard wired, but otherwise it isn't very useful. + const bool is_validate_enter = IsKeyPressed(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_KeypadEnter); + const bool is_validate_nav = (IsNavInputTest(ImGuiNavInput_Activate, ImGuiNavReadMode_Pressed) && !IsKeyPressed(ImGuiKey_Space)) || IsNavInputTest(ImGuiNavInput_Input, ImGuiNavReadMode_Pressed); + const bool is_cancel = IsKeyPressed(ImGuiKey_Escape) || IsNavInputTest(ImGuiNavInput_Cancel, ImGuiNavReadMode_Pressed); + + if (IsKeyPressed(ImGuiKey_LeftArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } + else if (IsKeyPressed(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } + else if (IsKeyPressed(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } + else if (IsKeyPressed(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } + else if (IsKeyPressed(ImGuiKey_PageUp) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGUP | k_mask); scroll_y -= row_count_per_page * g.FontSize; } + else if (IsKeyPressed(ImGuiKey_PageDown) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGDOWN | k_mask); scroll_y += row_count_per_page * g.FontSize; } + else if (IsKeyPressed(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } + else if (IsKeyPressed(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } + else if (IsKeyPressed(ImGuiKey_Delete) && !is_readonly && !is_cut) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } + else if (IsKeyPressed(ImGuiKey_Backspace) && !is_readonly) + { + if (!state->HasSelection()) + { + if (is_wordmove_key_down) + state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT); + else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) + state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT); + } + state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); + } + else if (is_validate_enter) + { + bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; + if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) + { + enter_pressed = clear_active_id = true; + } + else if (!is_readonly) + { + unsigned int c = '\n'; // Insert new line + if (InputTextFilterCharacter(&c, flags, callback, callback_user_data, ImGuiInputSource_Keyboard)) + state->OnKeyPressed((int)c); + } + } + else if (is_validate_nav) + { + IM_ASSERT(!is_validate_enter); + enter_pressed = clear_active_id = true; + } + else if (is_cancel) + { + clear_active_id = cancel_edit = true; + } + else if (is_undo || is_redo) + { + state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO); + state->ClearSelection(); + } + else if (is_shortcut_key && IsKeyPressed(ImGuiKey_A)) + { + state->SelectAll(); + state->CursorFollow = true; + } + else if (is_cut || is_copy) + { + // Cut, Copy + if (io.SetClipboardTextFn) + { + const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0; + const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW; + const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1; + char* clipboard_data = (char*)IM_ALLOC(clipboard_data_len * sizeof(char)); + ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie); + SetClipboardText(clipboard_data); + MemFree(clipboard_data); + } + if (is_cut) + { + if (!state->HasSelection()) + state->SelectAll(); + state->CursorFollow = true; + stb_textedit_cut(state, &state->Stb); + } + } + else if (is_paste) + { + if (const char* clipboard = GetClipboardText()) + { + // Filter pasted buffer + const int clipboard_len = (int)strlen(clipboard); + ImWchar* clipboard_filtered = (ImWchar*)IM_ALLOC((clipboard_len + 1) * sizeof(ImWchar)); + int clipboard_filtered_len = 0; + for (const char* s = clipboard; *s; ) + { + unsigned int c; + s += ImTextCharFromUtf8(&c, s, NULL); + if (c == 0) + break; + if (!InputTextFilterCharacter(&c, flags, callback, callback_user_data, ImGuiInputSource_Clipboard)) + continue; + clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; + } + clipboard_filtered[clipboard_filtered_len] = 0; + if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation + { + stb_textedit_paste(state, &state->Stb, clipboard_filtered, clipboard_filtered_len); + state->CursorFollow = true; + } + MemFree(clipboard_filtered); + } + } + + // Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame. + render_selection |= state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); + } + + // Process callbacks and apply result back to user's buffer. + const char* apply_new_text = NULL; + int apply_new_text_length = 0; + if (g.ActiveId == id) + { + IM_ASSERT(state != NULL); + if (cancel_edit) + { + // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents. + if (!is_readonly && strcmp(buf, state->InitialTextA.Data) != 0) + { + // Push records into the undo stack so we can CTRL+Z the revert operation itself + apply_new_text = state->InitialTextA.Data; + apply_new_text_length = state->InitialTextA.Size - 1; + ImVector w_text; + if (apply_new_text_length > 0) + { + w_text.resize(ImTextCountCharsFromUtf8(apply_new_text, apply_new_text + apply_new_text_length) + 1); + ImTextStrFromUtf8(w_text.Data, w_text.Size, apply_new_text, apply_new_text + apply_new_text_length); + } + stb_textedit_replace(state, &state->Stb, w_text.Data, (apply_new_text_length > 0) ? (w_text.Size - 1) : 0); + } + } + + // Apply ASCII value + if (!is_readonly) + { + state->TextAIsValid = true; + state->TextA.resize(state->TextW.Size * 4 + 1); + ImTextStrToUtf8(state->TextA.Data, state->TextA.Size, state->TextW.Data, NULL); + } + + // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame. + // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. + // This also allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage (please note that if you use this property along ImGuiInputTextFlags_CallbackResize you can end up with your temporary string object unnecessarily allocating once a frame, either store your string data, either if you don't then don't use ImGuiInputTextFlags_CallbackResize). + const bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0); + if (apply_edit_back_to_user_buffer) + { + // Apply new value immediately - copy modified buffer back + // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer + // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. + // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. + + // User callback + if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_CallbackAlways)) != 0) + { + IM_ASSERT(callback != NULL); + + // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. + ImGuiInputTextFlags event_flag = 0; + ImGuiKey event_key = ImGuiKey_None; + if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressed(ImGuiKey_Tab)) + { + event_flag = ImGuiInputTextFlags_CallbackCompletion; + event_key = ImGuiKey_Tab; + } + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_UpArrow)) + { + event_flag = ImGuiInputTextFlags_CallbackHistory; + event_key = ImGuiKey_UpArrow; + } + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_DownArrow)) + { + event_flag = ImGuiInputTextFlags_CallbackHistory; + event_key = ImGuiKey_DownArrow; + } + else if ((flags & ImGuiInputTextFlags_CallbackEdit) && state->Edited) + { + event_flag = ImGuiInputTextFlags_CallbackEdit; + } + else if (flags & ImGuiInputTextFlags_CallbackAlways) + { + event_flag = ImGuiInputTextFlags_CallbackAlways; + } + + if (event_flag) + { + ImGuiInputTextCallbackData callback_data; + memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData)); + callback_data.EventFlag = event_flag; + callback_data.Flags = flags; + callback_data.UserData = callback_user_data; + + char* callback_buf = is_readonly ? buf : state->TextA.Data; + callback_data.EventKey = event_key; + callback_data.Buf = callback_buf; + callback_data.BufTextLen = state->CurLenA; + callback_data.BufSize = state->BufCapacityA; + callback_data.BufDirty = false; + + // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) + ImWchar* text = state->TextW.Data; + const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + state->Stb.cursor); + const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_start); + const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_end); + + // Call user code + callback(&callback_data); + + // Read back what user may have modified + callback_buf = is_readonly ? buf : state->TextA.Data; // Pointer may have been invalidated by a resize callback + IM_ASSERT(callback_data.Buf == callback_buf); // Invalid to modify those fields + IM_ASSERT(callback_data.BufSize == state->BufCapacityA); + IM_ASSERT(callback_data.Flags == flags); + const bool buf_dirty = callback_data.BufDirty; + if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; } + if (callback_data.SelectionStart != utf8_selection_start || buf_dirty) { state->Stb.select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb.cursor : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } + if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty) { state->Stb.select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb.select_start : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } + if (buf_dirty) + { + IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! + if (callback_data.BufTextLen > backup_current_text_length && is_resizable) + state->TextW.resize(state->TextW.Size + (callback_data.BufTextLen - backup_current_text_length)); + state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, callback_data.Buf, NULL); + state->CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() + state->CursorAnimReset(); + } + } + } + + // Will copy result string if modified + if (!is_readonly && strcmp(state->TextA.Data, buf) != 0) + { + apply_new_text = state->TextA.Data; + apply_new_text_length = state->CurLenA; + } + } + + // Clear temporary user storage + state->Flags = ImGuiInputTextFlags_None; + } + + // Copy result to user buffer. This can currently only happen when (g.ActiveId == id) + if (apply_new_text != NULL) + { + // We cannot test for 'backup_current_text_length != apply_new_text_length' here because we have no guarantee that the size + // of our owned buffer matches the size of the string object held by the user, and by design we allow InputText() to be used + // without any storage on user's side. + IM_ASSERT(apply_new_text_length >= 0); + if (is_resizable) + { + ImGuiInputTextCallbackData callback_data; + callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize; + callback_data.Flags = flags; + callback_data.Buf = buf; + callback_data.BufTextLen = apply_new_text_length; + callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1); + callback_data.UserData = callback_user_data; + callback(&callback_data); + buf = callback_data.Buf; + buf_size = callback_data.BufSize; + apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1); + IM_ASSERT(apply_new_text_length <= buf_size); + } + //IMGUI_DEBUG_LOG("InputText(\"%s\"): apply_new_text length %d\n", label, apply_new_text_length); + + // If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size. + ImStrncpy(buf, apply_new_text, ImMin(apply_new_text_length + 1, buf_size)); + value_changed = true; + } + + // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value) + if (clear_active_id && g.ActiveId == id) + ClearActiveID(); + + // Render frame + if (!is_multiline) + { + RenderNavHighlight(frame_bb, id); + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + } + + const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size + ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; + ImVec2 text_size(0.0f, 0.0f); + + // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line + // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. + // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. + const int buf_display_max_length = 2 * 1024 * 1024; + const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595 + const char* buf_display_end = NULL; // We have specialized paths below for setting the length + if (is_displaying_hint) + { + buf_display = hint; + buf_display_end = hint + strlen(hint); + } + + // Render text. We currently only render selection when the widget is active or while scrolling. + // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. + if (render_cursor || render_selection) + { + IM_ASSERT(state != NULL); + if (!is_displaying_hint) + buf_display_end = buf_display + state->CurLenA; + + // Render text (with cursor and selection) + // This is going to be messy. We need to: + // - Display the text (this alone can be more easily clipped) + // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) + // - Measure text height (for scrollbar) + // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) + // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. + const ImWchar* text_begin = state->TextW.Data; + ImVec2 cursor_offset, select_start_offset; + + { + // Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions. + const ImWchar* searches_input_ptr[2] = { NULL, NULL }; + int searches_result_line_no[2] = { -1000, -1000 }; + int searches_remaining = 0; + if (render_cursor) + { + searches_input_ptr[0] = text_begin + state->Stb.cursor; + searches_result_line_no[0] = -1; + searches_remaining++; + } + if (render_selection) + { + searches_input_ptr[1] = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); + searches_result_line_no[1] = -1; + searches_remaining++; + } + + // Iterate all lines to find our line numbers + // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter. + searches_remaining += is_multiline ? 1 : 0; + int line_count = 0; + //for (const ImWchar* s = text_begin; (s = (const ImWchar*)wcschr((const wchar_t*)s, (wchar_t)'\n')) != NULL; s++) // FIXME-OPT: Could use this when wchar_t are 16-bit + for (const ImWchar* s = text_begin; *s != 0; s++) + if (*s == '\n') + { + line_count++; + if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; } + if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; } + } + line_count++; + if (searches_result_line_no[0] == -1) + searches_result_line_no[0] = line_count; + if (searches_result_line_no[1] == -1) + searches_result_line_no[1] = line_count; + + // Calculate 2d position by finding the beginning of the line and measuring distance + cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x; + cursor_offset.y = searches_result_line_no[0] * g.FontSize; + if (searches_result_line_no[1] >= 0) + { + select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x; + select_start_offset.y = searches_result_line_no[1] * g.FontSize; + } + + // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224) + if (is_multiline) + text_size = ImVec2(inner_size.x, line_count * g.FontSize); + } + + // Scroll + if (render_cursor && state->CursorFollow) + { + // Horizontal scroll in chunks of quarter width + if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) + { + const float scroll_increment_x = inner_size.x * 0.25f; + const float visible_width = inner_size.x - style.FramePadding.x; + if (cursor_offset.x < state->ScrollX) + state->ScrollX = IM_FLOOR(ImMax(0.0f, cursor_offset.x - scroll_increment_x)); + else if (cursor_offset.x - visible_width >= state->ScrollX) + state->ScrollX = IM_FLOOR(cursor_offset.x - visible_width + scroll_increment_x); + } + else + { + state->ScrollX = 0.0f; + } + + // Vertical scroll + if (is_multiline) + { + // Test if cursor is vertically visible + if (cursor_offset.y - g.FontSize < scroll_y) + scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); + else if (cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0f) >= scroll_y) + scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f; + const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f); + scroll_y = ImClamp(scroll_y, 0.0f, scroll_max_y); + draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag + draw_window->Scroll.y = scroll_y; + } + + state->CursorFollow = false; + } + + // Draw selection + const ImVec2 draw_scroll = ImVec2(state->ScrollX, 0.0f); + if (render_selection) + { + const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); + const ImWchar* text_selected_end = text_begin + ImMax(state->Stb.select_start, state->Stb.select_end); + + ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. + float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. + float bg_offy_dn = is_multiline ? 0.0f : 2.0f; + ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll; + for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) + { + if (rect_pos.y > clip_rect.w + g.FontSize) + break; + if (rect_pos.y < clip_rect.y) + { + //p = (const ImWchar*)wmemchr((const wchar_t*)p, '\n', text_selected_end - p); // FIXME-OPT: Could use this when wchar_t are 16-bit + //p = p ? p + 1 : text_selected_end; + while (p < text_selected_end) + if (*p++ == '\n') + break; + } + else + { + ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); + if (rect_size.x <= 0.0f) rect_size.x = IM_FLOOR(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines + ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn)); + rect.ClipWith(clip_rect); + if (rect.Overlaps(clip_rect)) + draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); + } + rect_pos.x = draw_pos.x - draw_scroll.x; + rect_pos.y += g.FontSize; + } + } + + // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash. + if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) + { + ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); + } + + // Draw blinking cursor + if (render_cursor) + { + state->CursorAnim += io.DeltaTime; + bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f; + ImVec2 cursor_screen_pos = ImFloor(draw_pos + cursor_offset - draw_scroll); + ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); + if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); + + // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) + if (!is_readonly) + { + g.PlatformImeData.WantVisible = true; + g.PlatformImeData.InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); + g.PlatformImeData.InputLineHeight = g.FontSize; + g.PlatformImeViewport = window->Viewport->ID; + } + } + } + else + { + // Render text only (no selection, no cursor) + if (is_multiline) + text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width + else if (!is_displaying_hint && g.ActiveId == id) + buf_display_end = buf_display + state->CurLenA; + else if (!is_displaying_hint) + buf_display_end = buf_display + strlen(buf_display); + + if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) + { + ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); + } + } + + if (is_password && !is_displaying_hint) + PopFont(); + + if (is_multiline) + { + // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (ref issue #4761)... + Dummy(ImVec2(text_size.x, text_size.y + style.FramePadding.y)); + ImGuiItemFlags backup_item_flags = g.CurrentItemFlags; + g.CurrentItemFlags |= ImGuiItemFlags_Inputable | ImGuiItemFlags_NoTabStop; + EndChild(); + item_data_backup.StatusFlags |= (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredWindow); + g.CurrentItemFlags = backup_item_flags; + + // ...and then we need to undo the group overriding last item data, which gets a bit messy as EndGroup() tries to forward scrollbar being active... + // FIXME: This quite messy/tricky, should attempt to get rid of the child window. + EndGroup(); + if (g.LastItemData.ID == 0) + { + g.LastItemData.ID = id; + g.LastItemData.InFlags = item_data_backup.InFlags; + g.LastItemData.StatusFlags = item_data_backup.StatusFlags; + } + } + + // Log as text + if (g.LogEnabled && (!is_password || is_displaying_hint)) + { + LogSetNextTextDecoration("{", "}"); + LogRenderedText(&draw_pos, buf_display, buf_display_end); + } + + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + if (value_changed && !(flags & ImGuiInputTextFlags_NoMarkEdited)) + MarkItemEdited(id); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) + return enter_pressed; + else + return value_changed; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +//------------------------------------------------------------------------- +// - ColorEdit3() +// - ColorEdit4() +// - ColorPicker3() +// - RenderColorRectWithAlphaCheckerboard() [Internal] +// - ColorPicker4() +// - ColorButton() +// - SetColorEditOptions() +// - ColorTooltip() [Internal] +// - ColorEditOptionsPopup() [Internal] +// - ColorPickerOptionsPopup() [Internal] +//------------------------------------------------------------------------- + +bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags) +{ + return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha); +} + +// ColorEdit supports RGB and HSV inputs. In case of RGB input resulting color may have undefined hue and/or saturation. +// Since widget displays both RGB and HSV values we must preserve hue and saturation to prevent these values resetting. +static void ColorEditRestoreHS(const float* col, float* H, float* S, float* V) +{ + // This check is optional. Suppose we have two color widgets side by side, both widgets display different colors, but both colors have hue and/or saturation undefined. + // With color check: hue/saturation is preserved in one widget. Editing color in one widget would reset hue/saturation in another one. + // Without color check: common hue/saturation would be displayed in all widgets that have hue/saturation undefined. + // g.ColorEditLastColor is stored as ImU32 RGB value: this essentially gives us color equality check with reduced precision. + // Tiny external color changes would not be detected and this check would still pass. This is OK, since we only restore hue/saturation _only_ if they are undefined, + // therefore this change flipping hue/saturation from undefined to a very tiny value would still be represented in color picker. + ImGuiContext& g = *GImGui; + if (g.ColorEditLastColor != ImGui::ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0))) + return; + + // When S == 0, H is undefined. + // When H == 1 it wraps around to 0. + if (*S == 0.0f || (*H == 0.0f && g.ColorEditLastHue == 1)) + *H = g.ColorEditLastHue; + + // When V == 0, S is undefined. + if (*V == 0.0f) + *S = g.ColorEditLastSat; +} + +// Edit colors components (each component in 0.0f..1.0f range). +// See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. +// With typical options: Left-click on color square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item. +bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float square_sz = GetFrameHeight(); + const float w_full = CalcItemWidth(); + const float w_button = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x); + const float w_inputs = w_full - w_button; + const char* label_display_end = FindRenderedTextEnd(label); + g.NextItemData.ClearFlags(); + + BeginGroup(); + PushID(label); + + // If we're not showing any slider there's no point in doing any HSV conversions + const ImGuiColorEditFlags flags_untouched = flags; + if (flags & ImGuiColorEditFlags_NoInputs) + flags = (flags & (~ImGuiColorEditFlags_DisplayMask_)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions; + + // Context menu: display and modify options (before defaults are applied) + if (!(flags & ImGuiColorEditFlags_NoOptions)) + ColorEditOptionsPopup(col, flags); + + // Read stored options + if (!(flags & ImGuiColorEditFlags_DisplayMask_)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DisplayMask_); + if (!(flags & ImGuiColorEditFlags_DataTypeMask_)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DataTypeMask_); + if (!(flags & ImGuiColorEditFlags_PickerMask_)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_); + if (!(flags & ImGuiColorEditFlags_InputMask_)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_InputMask_); + flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_)); + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check that only 1 is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check that only 1 is selected + + const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0; + const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0; + const int components = alpha ? 4 : 3; + + // Convert to the formats we need + float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f }; + if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB)) + ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV)) + { + // Hue is lost when converting from greyscale rgb (saturation=0). Restore it. + ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); + ColorEditRestoreHS(col, &f[0], &f[1], &f[2]); + } + int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; + + bool value_changed = false; + bool value_changed_as_float = false; + + const ImVec2 pos = window->DC.CursorPos; + const float inputs_offset_x = (style.ColorButtonPosition == ImGuiDir_Left) ? w_button : 0.0f; + window->DC.CursorPos.x = pos.x + inputs_offset_x; + + if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) + { + // RGB/HSV 0..255 Sliders + const float w_item_one = ImMax(1.0f, IM_FLOOR((w_inputs - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components)); + const float w_item_last = ImMax(1.0f, IM_FLOOR(w_inputs - (w_item_one + style.ItemInnerSpacing.x) * (components - 1))); + + const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); + static const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; + static const char* fmt_table_int[3][4] = + { + { "%3d", "%3d", "%3d", "%3d" }, // Short display + { "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA + { "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA + }; + static const char* fmt_table_float[3][4] = + { + { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display + { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA + { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA + }; + const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1; + + for (int n = 0; n < components; n++) + { + if (n > 0) + SameLine(0, style.ItemInnerSpacing.x); + SetNextItemWidth((n + 1 < components) ? w_item_one : w_item_last); + + // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0. + if (flags & ImGuiColorEditFlags_Float) + { + value_changed |= DragFloat(ids[n], &f[n], 1.0f / 255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); + value_changed_as_float |= value_changed; + } + else + { + value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]); + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + } + } + else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) + { + // RGB Hexadecimal Input + char buf[64]; + if (alpha) + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255)); + else + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255)); + SetNextItemWidth(w_inputs); + if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) + { + value_changed = true; + char* p = buf; + while (*p == '#' || ImCharIsBlankA(*p)) + p++; + i[0] = i[1] = i[2] = 0; + i[3] = 0xFF; // alpha default to 255 is not parsed by scanf (e.g. inputting #FFFFFF omitting alpha) + int r; + if (alpha) + r = sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned) + else + r = sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); + IM_UNUSED(r); // Fixes C6031: Return value ignored: 'sscanf'. + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + } + + ImGuiWindow* picker_active_window = NULL; + if (!(flags & ImGuiColorEditFlags_NoSmallPreview)) + { + const float button_offset_x = ((flags & ImGuiColorEditFlags_NoInputs) || (style.ColorButtonPosition == ImGuiDir_Left)) ? 0.0f : w_inputs + style.ItemInnerSpacing.x; + window->DC.CursorPos = ImVec2(pos.x + button_offset_x, pos.y); + + const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f); + if (ColorButton("##ColorButton", col_v4, flags)) + { + if (!(flags & ImGuiColorEditFlags_NoPicker)) + { + // Store current color and open a picker + g.ColorPickerRef = col_v4; + OpenPopup("picker"); + SetNextWindowPos(g.LastItemData.Rect.GetBL() + ImVec2(0.0f, style.ItemSpacing.y)); + } + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + + if (BeginPopup("picker")) + { + picker_active_window = g.CurrentWindow; + if (label != label_display_end) + { + TextEx(label, label_display_end); + Spacing(); + } + ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; + ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; + SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? + value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); + EndPopup(); + } + } + + if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel)) + { + SameLine(0.0f, style.ItemInnerSpacing.x); + TextEx(label, label_display_end); + } + + // Convert back + if (value_changed && picker_active_window == NULL) + { + if (!value_changed_as_float) + for (int n = 0; n < 4; n++) + f[n] = i[n] / 255.0f; + if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB)) + { + g.ColorEditLastHue = f[0]; + g.ColorEditLastSat = f[1]; + ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + g.ColorEditLastColor = ColorConvertFloat4ToU32(ImVec4(f[0], f[1], f[2], 0)); + } + if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV)) + ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); + + col[0] = f[0]; + col[1] = f[1]; + col[2] = f[2]; + if (alpha) + col[3] = f[3]; + } + + PopID(); + EndGroup(); + + // Drag and Drop Target + // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test. + if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget()) + { + bool accepted_drag_drop = false; + if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) + { + memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512 + value_changed = accepted_drag_drop = true; + } + if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) + { + memcpy((float*)col, payload->Data, sizeof(float) * components); + value_changed = accepted_drag_drop = true; + } + + // Drag-drop payloads are always RGB + if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV)) + ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]); + EndDragDropTarget(); + } + + // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4(). + if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window) + g.LastItemData.ID = g.ActiveId; + + if (value_changed) + MarkItemEdited(g.LastItemData.ID); + + return value_changed; +} + +bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags) +{ + float col4[4] = { col[0], col[1], col[2], 1.0f }; + if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha)) + return false; + col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2]; + return true; +} + +// Helper for ColorPicker4() +static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha) +{ + ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8)); +} + +// Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. +// (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.) +// FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) +// FIXME: this is trying to be aware of style.Alpha but not fully correct. Also, the color wheel will have overlapping glitches with (style.Alpha < 1.0) +bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImDrawList* draw_list = window->DrawList; + ImGuiStyle& style = g.Style; + ImGuiIO& io = g.IO; + + const float width = CalcItemWidth(); + g.NextItemData.ClearFlags(); + + PushID(label); + BeginGroup(); + + if (!(flags & ImGuiColorEditFlags_NoSidePreview)) + flags |= ImGuiColorEditFlags_NoSmallPreview; + + // Context menu: display and store options. + if (!(flags & ImGuiColorEditFlags_NoOptions)) + ColorPickerOptionsPopup(col, flags); + + // Read stored options + if (!(flags & ImGuiColorEditFlags_PickerMask_)) + flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_PickerMask_; + if (!(flags & ImGuiColorEditFlags_InputMask_)) + flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_InputMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_InputMask_; + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check that only 1 is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check that only 1 is selected + if (!(flags & ImGuiColorEditFlags_NoOptions)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar); + + // Setup + int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4; + bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha); + ImVec2 picker_pos = window->DC.CursorPos; + float square_sz = GetFrameHeight(); + float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars + float sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box + float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x; + float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x; + float bars_triangles_half_sz = IM_FLOOR(bars_width * 0.20f); + + float backup_initial_col[4]; + memcpy(backup_initial_col, col, components * sizeof(float)); + + float wheel_thickness = sv_picker_size * 0.08f; + float wheel_r_outer = sv_picker_size * 0.50f; + float wheel_r_inner = wheel_r_outer - wheel_thickness; + ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size * 0.5f); + + // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic. + float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f); + ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point. + ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point. + ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point. + + float H = col[0], S = col[1], V = col[2]; + float R = col[0], G = col[1], B = col[2]; + if (flags & ImGuiColorEditFlags_InputRGB) + { + // Hue is lost when converting from greyscale rgb (saturation=0). Restore it. + ColorConvertRGBtoHSV(R, G, B, H, S, V); + ColorEditRestoreHS(col, &H, &S, &V); + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + ColorConvertHSVtoRGB(H, S, V, R, G, B); + } + + bool value_changed = false, value_changed_h = false, value_changed_sv = false; + + PushItemFlag(ImGuiItemFlags_NoNav, true); + if (flags & ImGuiColorEditFlags_PickerHueWheel) + { + // Hue wheel + SV triangle logic + InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size)); + if (IsItemActive()) + { + ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center; + ImVec2 current_off = g.IO.MousePos - wheel_center; + float initial_dist2 = ImLengthSqr(initial_off); + if (initial_dist2 >= (wheel_r_inner - 1) * (wheel_r_inner - 1) && initial_dist2 <= (wheel_r_outer + 1) * (wheel_r_outer + 1)) + { + // Interactive with Hue wheel + H = ImAtan2(current_off.y, current_off.x) / IM_PI * 0.5f; + if (H < 0.0f) + H += 1.0f; + value_changed = value_changed_h = true; + } + float cos_hue_angle = ImCos(-H * 2.0f * IM_PI); + float sin_hue_angle = ImSin(-H * 2.0f * IM_PI); + if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle))) + { + // Interacting with SV triangle + ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle); + if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated)) + current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated); + float uu, vv, ww; + ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww); + V = ImClamp(1.0f - vv, 0.0001f, 1.0f); + S = ImClamp(uu / V, 0.0001f, 1.0f); + value_changed = value_changed_sv = true; + } + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + } + else if (flags & ImGuiColorEditFlags_PickerHueBar) + { + // SV rectangle logic + InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size)); + if (IsItemActive()) + { + S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size - 1)); + V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); + + // Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square. + if (g.ColorEditLastColor == ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0))) + H = g.ColorEditLastHue; + value_changed = value_changed_sv = true; + } + if (!(flags & ImGuiColorEditFlags_NoOptions)) + OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight); + + // Hue bar logic + SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y)); + InvisibleButton("hue", ImVec2(bars_width, sv_picker_size)); + if (IsItemActive()) + { + H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); + value_changed = value_changed_h = true; + } + } + + // Alpha bar logic + if (alpha_bar) + { + SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y)); + InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size)); + if (IsItemActive()) + { + col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); + value_changed = true; + } + } + PopItemFlag(); // ImGuiItemFlags_NoNav + + if (!(flags & ImGuiColorEditFlags_NoSidePreview)) + { + SameLine(0, style.ItemInnerSpacing.x); + BeginGroup(); + } + + if (!(flags & ImGuiColorEditFlags_NoLabel)) + { + const char* label_display_end = FindRenderedTextEnd(label); + if (label != label_display_end) + { + if ((flags & ImGuiColorEditFlags_NoSidePreview)) + SameLine(0, style.ItemInnerSpacing.x); + TextEx(label, label_display_end); + } + } + + if (!(flags & ImGuiColorEditFlags_NoSidePreview)) + { + PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); + ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + if ((flags & ImGuiColorEditFlags_NoLabel)) + Text("Current"); + + ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip; + ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)); + if (ref_col != NULL) + { + Text("Original"); + ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]); + if (ColorButton("##original", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2))) + { + memcpy(col, ref_col, components * sizeof(float)); + value_changed = true; + } + } + PopItemFlag(); + EndGroup(); + } + + // Convert back color to RGB + if (value_changed_h || value_changed_sv) + { + if (flags & ImGuiColorEditFlags_InputRGB) + { + ColorConvertHSVtoRGB(H, S, V, col[0], col[1], col[2]); + g.ColorEditLastHue = H; + g.ColorEditLastSat = S; + g.ColorEditLastColor = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0)); + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + col[0] = H; + col[1] = S; + col[2] = V; + } + } + + // R,G,B and H,S,V slider color editor + bool value_changed_fix_hue_wrap = false; + if ((flags & ImGuiColorEditFlags_NoInputs) == 0) + { + PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x); + ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf; + ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker; + if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags_DisplayMask_) == 0) + if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB)) + { + // FIXME: Hackily differentiating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget. + // For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050) + value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap); + value_changed = true; + } + if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags_DisplayMask_) == 0) + value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_DisplayHSV); + if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags_DisplayMask_) == 0) + value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_DisplayHex); + PopItemWidth(); + } + + // Try to cancel hue wrap (after ColorEdit4 call), if any + if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB)) + { + float new_H, new_S, new_V; + ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V); + if (new_H <= 0 && H > 0) + { + if (new_V <= 0 && V != new_V) + ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]); + else if (new_S <= 0) + ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]); + } + } + + if (value_changed) + { + if (flags & ImGuiColorEditFlags_InputRGB) + { + R = col[0]; + G = col[1]; + B = col[2]; + ColorConvertRGBtoHSV(R, G, B, H, S, V); + ColorEditRestoreHS(col, &H, &S, &V); // Fix local Hue as display below will use it immediately. + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + H = col[0]; + S = col[1]; + V = col[2]; + ColorConvertHSVtoRGB(H, S, V, R, G, B); + } + } + + const int style_alpha8 = IM_F32_TO_INT8_SAT(style.Alpha); + const ImU32 col_black = IM_COL32(0,0,0,style_alpha8); + const ImU32 col_white = IM_COL32(255,255,255,style_alpha8); + const ImU32 col_midgrey = IM_COL32(128,128,128,style_alpha8); + const ImU32 col_hues[6 + 1] = { IM_COL32(255,0,0,style_alpha8), IM_COL32(255,255,0,style_alpha8), IM_COL32(0,255,0,style_alpha8), IM_COL32(0,255,255,style_alpha8), IM_COL32(0,0,255,style_alpha8), IM_COL32(255,0,255,style_alpha8), IM_COL32(255,0,0,style_alpha8) }; + + ImVec4 hue_color_f(1, 1, 1, style.Alpha); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z); + ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f); + ImU32 user_col32_striped_of_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, style.Alpha)); // Important: this is still including the main rendering/style alpha!! + + ImVec2 sv_cursor_pos; + + if (flags & ImGuiColorEditFlags_PickerHueWheel) + { + // Render Hue Wheel + const float aeps = 0.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out). + const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12); + for (int n = 0; n < 6; n++) + { + const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps; + const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps; + const int vert_start_idx = draw_list->VtxBuffer.Size; + draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc); + draw_list->PathStroke(col_white, 0, wheel_thickness); + const int vert_end_idx = draw_list->VtxBuffer.Size; + + // Paint colors over existing vertices + ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner); + ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner); + ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n + 1]); + } + + // Render Cursor + preview on Hue Wheel + float cos_hue_angle = ImCos(H * 2.0f * IM_PI); + float sin_hue_angle = ImSin(H * 2.0f * IM_PI); + ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f); + float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f; + int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32); + draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments); + draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad + 1, col_midgrey, hue_cursor_segments); + draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, col_white, hue_cursor_segments); + + // Render SV triangle (rotated according to hue) + ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle); + ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle); + ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle); + ImVec2 uv_white = GetFontTexUvWhitePixel(); + draw_list->PrimReserve(6, 6); + draw_list->PrimVtx(tra, uv_white, hue_color32); + draw_list->PrimVtx(trb, uv_white, hue_color32); + draw_list->PrimVtx(trc, uv_white, col_white); + draw_list->PrimVtx(tra, uv_white, 0); + draw_list->PrimVtx(trb, uv_white, col_black); + draw_list->PrimVtx(trc, uv_white, 0); + draw_list->AddTriangle(tra, trb, trc, col_midgrey, 1.5f); + sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V)); + } + else if (flags & ImGuiColorEditFlags_PickerHueBar) + { + // Render SV Square + draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), col_white, hue_color32, hue_color32, col_white); + draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black); + RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0f); + sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much + sv_cursor_pos.y = ImClamp(IM_ROUND(picker_pos.y + ImSaturate(1 - V) * sv_picker_size), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2); + + // Render Hue Bar + for (int i = 0; i < 6; ++i) + draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), col_hues[i], col_hues[i], col_hues[i + 1], col_hues[i + 1]); + float bar0_line_y = IM_ROUND(picker_pos.y + H * sv_picker_size); + RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f); + RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha); + } + + // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range) + float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f; + draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, 12); + draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, 12); + draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, 12); + + // Render alpha bar + if (alpha_bar) + { + float alpha = ImSaturate(col[3]); + ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size); + RenderColorRectWithAlphaCheckerboard(draw_list, bar1_bb.Min, bar1_bb.Max, 0, bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f)); + draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, user_col32_striped_of_alpha, user_col32_striped_of_alpha, user_col32_striped_of_alpha & ~IM_COL32_A_MASK, user_col32_striped_of_alpha & ~IM_COL32_A_MASK); + float bar1_line_y = IM_ROUND(picker_pos.y + (1.0f - alpha) * sv_picker_size); + RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f); + RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha); + } + + EndGroup(); + + if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0) + value_changed = false; + if (value_changed) + MarkItemEdited(g.LastItemData.ID); + + PopID(); + + return value_changed; +} + +// A little color square. Return true when clicked. +// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. +// 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. +// Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set. +bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiID id = window->GetID(desc_id); + const float default_size = GetFrameHeight(); + const ImVec2 size(size_arg.x == 0.0f ? default_size : size_arg.x, size_arg.y == 0.0f ? default_size : size_arg.y); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f); + if (!ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + if (flags & ImGuiColorEditFlags_NoAlpha) + flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf); + + ImVec4 col_rgb = col; + if (flags & ImGuiColorEditFlags_InputHSV) + ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z); + + ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f); + float grid_step = ImMin(size.x, size.y) / 2.99f; + float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f); + ImRect bb_inner = bb; + float off = 0.0f; + if ((flags & ImGuiColorEditFlags_NoBorder) == 0) + { + off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts. + bb_inner.Expand(off); + } + if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f) + { + float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f); + RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawFlags_RoundCornersRight); + window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundCornersLeft); + } + else + { + // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha + ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha; + if (col_source.w < 1.0f) + RenderColorRectWithAlphaCheckerboard(window->DrawList, bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding); + else + window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding); + } + RenderNavHighlight(bb, id); + if ((flags & ImGuiColorEditFlags_NoBorder) == 0) + { + if (g.Style.FrameBorderSize > 0.0f) + RenderFrameBorder(bb.Min, bb.Max, rounding); + else + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border + } + + // Drag and Drop Source + // NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test. + if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource()) + { + if (flags & ImGuiColorEditFlags_NoAlpha) + SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once); + else + SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once); + ColorButton(desc_id, col, flags); + SameLine(); + TextEx("Color"); + EndDragDropSource(); + } + + // Tooltip + if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered) + ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)); + + return pressed; +} + +// Initialize/override default color options +void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) +{ + ImGuiContext& g = *GImGui; + if ((flags & ImGuiColorEditFlags_DisplayMask_) == 0) + flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DisplayMask_; + if ((flags & ImGuiColorEditFlags_DataTypeMask_) == 0) + flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DataTypeMask_; + if ((flags & ImGuiColorEditFlags_PickerMask_) == 0) + flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_PickerMask_; + if ((flags & ImGuiColorEditFlags_InputMask_) == 0) + flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_InputMask_; + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DataTypeMask_)); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check only 1 option is selected + g.ColorEditOptions = flags; +} + +// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. +void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags) +{ + ImGuiContext& g = *GImGui; + + BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None); + const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text; + if (text_end > text) + { + TextEx(text, text_end); + Separator(); + } + + ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2); + ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); + ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz); + SameLine(); + if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags_InputMask_)) + { + if (flags & ImGuiColorEditFlags_NoAlpha) + Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]); + else + Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]); + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + if (flags & ImGuiColorEditFlags_NoAlpha) + Text("H: %.3f, S: %.3f, V: %.3f", col[0], col[1], col[2]); + else + Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col[0], col[1], col[2], col[3]); + } + EndTooltip(); +} + +void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) +{ + bool allow_opt_inputs = !(flags & ImGuiColorEditFlags_DisplayMask_); + bool allow_opt_datatype = !(flags & ImGuiColorEditFlags_DataTypeMask_); + if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context")) + return; + ImGuiContext& g = *GImGui; + ImGuiColorEditFlags opts = g.ColorEditOptions; + if (allow_opt_inputs) + { + if (RadioButton("RGB", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayRGB; + if (RadioButton("HSV", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHSV; + if (RadioButton("Hex", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHex; + } + if (allow_opt_datatype) + { + if (allow_opt_inputs) Separator(); + if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Uint8; + if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Float; + } + + if (allow_opt_inputs || allow_opt_datatype) + Separator(); + if (Button("Copy as..", ImVec2(-1, 0))) + OpenPopup("Copy"); + if (BeginPopup("Copy")) + { + int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); + char buf[64]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + if (Selectable(buf)) + SetClipboardText(buf); + ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca); + if (Selectable(buf)) + SetClipboardText(buf); + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", cr, cg, cb); + if (Selectable(buf)) + SetClipboardText(buf); + if (!(flags & ImGuiColorEditFlags_NoAlpha)) + { + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", cr, cg, cb, ca); + if (Selectable(buf)) + SetClipboardText(buf); + } + EndPopup(); + } + + g.ColorEditOptions = opts; + EndPopup(); +} + +void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags) +{ + bool allow_opt_picker = !(flags & ImGuiColorEditFlags_PickerMask_); + bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar); + if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context")) + return; + ImGuiContext& g = *GImGui; + if (allow_opt_picker) + { + ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function + PushItemWidth(picker_size.x); + for (int picker_type = 0; picker_type < 2; picker_type++) + { + // Draw small/thumbnail version of each picker type (over an invisible button for selection) + if (picker_type > 0) Separator(); + PushID(picker_type); + ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoSidePreview | (flags & ImGuiColorEditFlags_NoAlpha); + if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar; + if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel; + ImVec2 backup_pos = GetCursorScreenPos(); + if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup + g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags_PickerMask_) | (picker_flags & ImGuiColorEditFlags_PickerMask_); + SetCursorScreenPos(backup_pos); + ImVec4 previewing_ref_col; + memcpy(&previewing_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4)); + ColorPicker4("##previewing_picker", &previewing_ref_col.x, picker_flags); + PopID(); + } + PopItemWidth(); + } + if (allow_opt_alpha_bar) + { + if (allow_opt_picker) Separator(); + CheckboxFlags("Alpha Bar", &g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar); + } + EndPopup(); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +//------------------------------------------------------------------------- +// - TreeNode() +// - TreeNodeV() +// - TreeNodeEx() +// - TreeNodeExV() +// - TreeNodeBehavior() [Internal] +// - TreePush() +// - TreePop() +// - GetTreeNodeToLabelSpacing() +// - SetNextItemOpen() +// - CollapsingHeader() +//------------------------------------------------------------------------- + +bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const char* label) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + return TreeNodeBehavior(window->GetID(label), 0, label, NULL); +} + +bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) +{ + return TreeNodeExV(str_id, 0, fmt, args); +} + +bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) +{ + return TreeNodeExV(ptr_id, 0, fmt, args); +} + +bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + return TreeNodeBehavior(window->GetID(label), flags, label, NULL); +} + +bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end); +} + +bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end); +} + +bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) +{ + if (flags & ImGuiTreeNodeFlags_Leaf) + return true; + + // We only write to the tree storage if the user clicks (or explicitly use the SetNextItemOpen function) + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiStorage* storage = window->DC.StateStorage; + + bool is_open; + if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasOpen) + { + if (g.NextItemData.OpenCond & ImGuiCond_Always) + { + is_open = g.NextItemData.OpenVal; + storage->SetInt(id, is_open); + } + else + { + // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently. + const int stored_value = storage->GetInt(id, -1); + if (stored_value == -1) + { + is_open = g.NextItemData.OpenVal; + storage->SetInt(id, is_open); + } + else + { + is_open = stored_value != 0; + } + } + } + else + { + is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; + } + + // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). + // NB- If we are above max depth we still allow manually opened nodes to be logged. + if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand) + is_open = true; + + return is_open; +} + +bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; + const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, ImMin(window->DC.CurrLineTextBaseOffset, style.FramePadding.y)); + + if (!label_end) + label_end = FindRenderedTextEnd(label); + const ImVec2 label_size = CalcTextSize(label, label_end, false); + + // We vertically grow up to current line height up the typical widget height. + const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2); + ImRect frame_bb; + frame_bb.Min.x = (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x; + frame_bb.Min.y = window->DC.CursorPos.y; + frame_bb.Max.x = window->WorkRect.Max.x; + frame_bb.Max.y = window->DC.CursorPos.y + frame_height; + if (display_frame) + { + // Framed header expand a little outside the default padding, to the edge of InnerClipRect + // (FIXME: May remove this at some point and make InnerClipRect align with WindowPadding.x instead of WindowPadding.x*0.5f) + frame_bb.Min.x -= IM_FLOOR(window->WindowPadding.x * 0.5f - 1.0f); + frame_bb.Max.x += IM_FLOOR(window->WindowPadding.x * 0.5f); + } + + const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapser arrow width + Spacing + const float text_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it + const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x * 2 : 0.0f); // Include collapser + ImVec2 text_pos(window->DC.CursorPos.x + text_offset_x, window->DC.CursorPos.y + text_offset_y); + ItemSize(ImVec2(text_width, frame_height), padding.y); + + // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing + ImRect interact_bb = frame_bb; + if (!display_frame && (flags & (ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth)) == 0) + interact_bb.Max.x = frame_bb.Min.x + text_width + style.ItemSpacing.x * 2.0f; + + // Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child. + // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). + // This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero. + const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0; + bool is_open = TreeNodeBehaviorIsOpen(id, flags); + if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + window->DC.TreeJumpToParentOnPopMask |= (1 << window->DC.TreeDepth); + + bool item_add = ItemAdd(interact_bb, id); + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; + g.LastItemData.DisplayRect = frame_bb; + + if (!item_add) + { + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushOverrideID(id); + IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); + return is_open; + } + + ImGuiButtonFlags button_flags = ImGuiTreeNodeFlags_None; + if (flags & ImGuiTreeNodeFlags_AllowItemOverlap) + button_flags |= ImGuiButtonFlags_AllowItemOverlap; + if (!is_leaf) + button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; + + // We allow clicking on the arrow section with keyboard modifiers held, in order to easily + // allow browsing a tree while preserving selection with code implementing multi-selection patterns. + // When clicking on the rest of the tree node we always disallow keyboard modifiers. + const float arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x; + const float arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0f) + style.TouchExtraPadding.x; + const bool is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 && g.IO.MousePos.x < arrow_hit_x2); + if (window != g.HoveredWindow || !is_mouse_x_over_arrow) + button_flags |= ImGuiButtonFlags_NoKeyModifiers; + + // Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags. + // Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support. + // - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0) + // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0) + // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1) + // - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1) + // - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0) + // It is rather standard that arrow click react on Down rather than Up. + // We set ImGuiButtonFlags_PressedOnClickRelease on OpenOnDoubleClick because we want the item to be active on the initial MouseDown in order for drag and drop to work. + if (is_mouse_x_over_arrow) + button_flags |= ImGuiButtonFlags_PressedOnClick; + else if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; + else + button_flags |= ImGuiButtonFlags_PressedOnClickRelease; + + bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0; + const bool was_selected = selected; + + bool hovered, held; + bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); + bool toggled = false; + if (!is_leaf) + { + if (pressed && g.DragDropHoldJustPressedId != id) + { + if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id)) + toggled = true; + if (flags & ImGuiTreeNodeFlags_OpenOnArrow) + toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job + if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2) + toggled = true; + } + else if (pressed && g.DragDropHoldJustPressedId == id) + { + IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold); + if (!is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again. + toggled = true; + } + + if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open) + { + toggled = true; + NavMoveRequestCancel(); + } + if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority? + { + toggled = true; + NavMoveRequestCancel(); + } + + if (toggled) + { + is_open = !is_open; + window->DC.StateStorage->SetInt(id, is_open); + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen; + } + } + if (flags & ImGuiTreeNodeFlags_AllowItemOverlap) + SetItemAllowOverlap(); + + // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger. + if (selected != was_selected) //-V547 + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection; + + // Render + const ImU32 text_col = GetColorU32(ImGuiCol_Text); + ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin; + if (display_frame) + { + // Framed type + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding); + RenderNavHighlight(frame_bb, id, nav_highlight_flags); + if (flags & ImGuiTreeNodeFlags_Bullet) + RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col); + else if (!is_leaf) + RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f); + else // Leaf without bullet, left-adjusted text + text_pos.x -= text_offset_x; + if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton) + frame_bb.Max.x -= g.FontSize + style.FramePadding.x; + + if (g.LogEnabled) + LogSetNextTextDecoration("###", "###"); + RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); + } + else + { + // Unframed typed for tree nodes + if (hovered || selected) + { + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false); + } + RenderNavHighlight(frame_bb, id, nav_highlight_flags); + if (flags & ImGuiTreeNodeFlags_Bullet) + RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col); + else if (!is_leaf) + RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f); + if (g.LogEnabled) + LogSetNextTextDecoration(">", NULL); + RenderText(text_pos, label, label_end, false); + } + + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushOverrideID(id); + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); + return is_open; +} + +void ImGui::TreePush(const char* str_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + PushID(str_id); +} + +void ImGui::TreePush(const void* ptr_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + PushID(ptr_id); +} + +void ImGui::TreePushOverrideID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + Indent(); + window->DC.TreeDepth++; + PushOverrideID(id); +} + +void ImGui::TreePop() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + Unindent(); + + window->DC.TreeDepth--; + ImU32 tree_depth_mask = (1 << window->DC.TreeDepth); + + // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled) + if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) + if (g.NavIdIsAlive && (window->DC.TreeJumpToParentOnPopMask & tree_depth_mask)) + { + SetNavID(window->IDStack.back(), g.NavLayer, 0, ImRect()); + NavMoveRequestCancel(); + } + window->DC.TreeJumpToParentOnPopMask &= tree_depth_mask - 1; + + IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much. + PopID(); +} + +// Horizontal distance preceding label when using TreeNode() or Bullet() +float ImGui::GetTreeNodeToLabelSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + (g.Style.FramePadding.x * 2.0f); +} + +// Set next TreeNode/CollapsingHeader open state. +void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond) +{ + ImGuiContext& g = *GImGui; + if (g.CurrentWindow->SkipItems) + return; + g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasOpen; + g.NextItemData.OpenVal = is_open; + g.NextItemData.OpenCond = cond ? cond : ImGuiCond_Always; +} + +// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). +// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). +bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader, label); +} + +// p_visible == NULL : regular collapsing header +// p_visible != NULL && *p_visible == true : show a small close button on the corner of the header, clicking the button will set *p_visible = false +// p_visible != NULL && *p_visible == false : do not show the header at all +// Do not mistake this with the Open state of the header itself, which you can adjust with SetNextItemOpen() or ImGuiTreeNodeFlags_DefaultOpen. +bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + if (p_visible && !*p_visible) + return false; + + ImGuiID id = window->GetID(label); + flags |= ImGuiTreeNodeFlags_CollapsingHeader; + if (p_visible) + flags |= ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_ClipLabelForTrailingButton; + bool is_open = TreeNodeBehavior(id, flags, label); + if (p_visible != NULL) + { + // Create a small overlapping close button + // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + // FIXME: CloseButton can overlap into text, need find a way to clip the text somehow. + ImGuiContext& g = *GImGui; + ImGuiLastItemData last_item_backup = g.LastItemData; + float button_size = g.FontSize; + float button_x = ImMax(g.LastItemData.Rect.Min.x, g.LastItemData.Rect.Max.x - g.Style.FramePadding.x * 2.0f - button_size); + float button_y = g.LastItemData.Rect.Min.y; + ImGuiID close_button_id = GetIDWithSeed("#CLOSE", NULL, id); + if (CloseButton(close_button_id, ImVec2(button_x, button_y))) + *p_visible = false; + g.LastItemData = last_item_backup; + } + + return is_open; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Selectable +//------------------------------------------------------------------------- +// - Selectable() +//------------------------------------------------------------------------- + +// Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image. +// But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id. +// With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowItemOverlap are also frequently used flags. +// FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported. +bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + // Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle. + ImGuiID id = window->GetID(label); + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); + ImVec2 pos = window->DC.CursorPos; + pos.y += window->DC.CurrLineTextBaseOffset; + ItemSize(size, 0.0f); + + // Fill horizontal space + // We don't support (size < 0.0f) in Selectable() because the ItemSpacing extension would make explicitly right-aligned sizes not visibly match other widgets. + const bool span_all_columns = (flags & ImGuiSelectableFlags_SpanAllColumns) != 0; + const float min_x = span_all_columns ? window->ParentWorkRect.Min.x : pos.x; + const float max_x = span_all_columns ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x; + if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth)) + size.x = ImMax(label_size.x, max_x - min_x); + + // Text stays at the submission position, but bounding box may be extended on both sides + const ImVec2 text_min = pos; + const ImVec2 text_max(min_x + size.x, pos.y + size.y); + + // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable. + ImRect bb(min_x, pos.y, text_max.x, text_max.y); + if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0) + { + const float spacing_x = span_all_columns ? 0.0f : style.ItemSpacing.x; + const float spacing_y = style.ItemSpacing.y; + const float spacing_L = IM_FLOOR(spacing_x * 0.50f); + const float spacing_U = IM_FLOOR(spacing_y * 0.50f); + bb.Min.x -= spacing_L; + bb.Min.y -= spacing_U; + bb.Max.x += (spacing_x - spacing_L); + bb.Max.y += (spacing_y - spacing_U); + } + //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)); } + + // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackground for every Selectable.. + const float backup_clip_rect_min_x = window->ClipRect.Min.x; + const float backup_clip_rect_max_x = window->ClipRect.Max.x; + if (span_all_columns) + { + window->ClipRect.Min.x = window->ParentWorkRect.Min.x; + window->ClipRect.Max.x = window->ParentWorkRect.Max.x; + } + + const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0; + const bool item_add = ItemAdd(bb, id, NULL, disabled_item ? ImGuiItemFlags_Disabled : ImGuiItemFlags_None); + if (span_all_columns) + { + window->ClipRect.Min.x = backup_clip_rect_min_x; + window->ClipRect.Max.x = backup_clip_rect_max_x; + } + + if (!item_add) + return false; + + const bool disabled_global = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0; + if (disabled_item && !disabled_global) // Only testing this as an optimization + BeginDisabled(); + + // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only, + // which would be advantageous since most selectable are not selected. + if (span_all_columns && window->DC.CurrentColumns) + PushColumnsBackground(); + else if (span_all_columns && g.CurrentTable) + TablePushBackgroundChannel(); + + // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries + ImGuiButtonFlags button_flags = 0; + if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; } + if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; } + if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; } + if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; } + if (flags & ImGuiSelectableFlags_AllowItemOverlap) { button_flags |= ImGuiButtonFlags_AllowItemOverlap; } + + const bool was_selected = selected; + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); + + // Auto-select when moved into + // - This will be more fully fleshed in the range-select branch + // - This is not exposed as it won't nicely work with some user side handling of shift/control + // - We cannot do 'if (g.NavJustMovedToId != id) { selected = false; pressed = was_selected; }' for two reasons + // - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope()) + // - (2) usage will fail with clipped items + // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API. + if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == window->DC.NavFocusScopeIdCurrent) + if (g.NavJustMovedToId == id) + selected = pressed = true; + + // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard + if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover))) + { + if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent) + { + SetNavID(id, window->DC.NavLayerCurrent, window->DC.NavFocusScopeIdCurrent, WindowRectAbsToRel(window, bb)); // (bb == NavRect) + g.NavDisableHighlight = true; + } + } + if (pressed) + MarkItemEdited(id); + + if (flags & ImGuiSelectableFlags_AllowItemOverlap) + SetItemAllowOverlap(); + + // In this branch, Selectable() cannot toggle the selection so this will never trigger. + if (selected != was_selected) //-V547 + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection; + + // Render + if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld)) + hovered = true; + if (hovered || selected) + { + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(bb.Min, bb.Max, col, false, 0.0f); + } + RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding); + + if (span_all_columns && window->DC.CurrentColumns) + PopColumnsBackground(); + else if (span_all_columns && g.CurrentTable) + TablePopBackgroundChannel(); + + RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb); + + // Automatically close popups + if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(g.LastItemData.InFlags & ImGuiItemFlags_SelectableDontClosePopup)) + CloseCurrentPopup(); + + if (disabled_item && !disabled_global) + EndDisabled(); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + return pressed; //-V1020 +} + +bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +{ + if (Selectable(label, *p_selected, flags, size_arg)) + { + *p_selected = !*p_selected; + return true; + } + return false; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: ListBox +//------------------------------------------------------------------------- +// - BeginListBox() +// - EndListBox() +// - ListBox() +//------------------------------------------------------------------------- + +// Tip: To have a list filling the entire window width, use size.x = -FLT_MIN and pass an non-visible label e.g. "##empty" +// Tip: If your vertical size is calculated from an item count (e.g. 10 * item_height) consider adding a fractional part to facilitate seeing scrolling boundaries (e.g. 10.25 * item_height). +bool ImGui::BeginListBox(const char* label, const ImVec2& size_arg) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + // Size default to hold ~7.25 items. + // Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. + ImVec2 size = ImFloor(CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.25f + style.FramePadding.y * 2.0f)); + ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); + ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + g.NextItemData.ClearFlags(); + + if (!IsRectVisible(bb.Min, bb.Max)) + { + ItemSize(bb.GetSize(), style.FramePadding.y); + ItemAdd(bb, 0, &frame_bb); + return false; + } + + // FIXME-OPT: We could omit the BeginGroup() if label_size.x but would need to omit the EndGroup() as well. + BeginGroup(); + if (label_size.x > 0.0f) + { + ImVec2 label_pos = ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y); + RenderText(label_pos, label); + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, label_pos + label_size); + } + + BeginChildFrame(id, frame_bb.GetSize()); + return true; +} + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS +// OBSOLETED in 1.81 (from February 2021) +bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items) +{ + // If height_in_items == -1, default height is maximum 7. + ImGuiContext& g = *GImGui; + float height_in_items_f = (height_in_items < 0 ? ImMin(items_count, 7) : height_in_items) + 0.25f; + ImVec2 size; + size.x = 0.0f; + size.y = GetTextLineHeightWithSpacing() * height_in_items_f + g.Style.FramePadding.y * 2.0f; + return BeginListBox(label, size); +} +#endif + +void ImGui::EndListBox() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) && "Mismatched BeginListBox/EndListBox calls. Did you test the return value of BeginListBox?"); + IM_UNUSED(window); + + EndChildFrame(); + EndGroup(); // This is only required to be able to do IsItemXXX query on the whole ListBox including label +} + +bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items) +{ + const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); + return value_changed; +} + +// This is merely a helper around BeginListBox(), EndListBox(). +// Considering using those directly to submit custom data or store selection differently. +bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) +{ + ImGuiContext& g = *GImGui; + + // Calculate size from "height_in_items" + if (height_in_items < 0) + height_in_items = ImMin(items_count, 7); + float height_in_items_f = height_in_items + 0.25f; + ImVec2 size(0.0f, ImFloor(GetTextLineHeightWithSpacing() * height_in_items_f + g.Style.FramePadding.y * 2.0f)); + + if (!BeginListBox(label, size)) + return false; + + // Assume all items have even height (= 1 line of text). If you need items of different height, + // you can create a custom version of ListBox() in your code without using the clipper. + bool value_changed = false; + ImGuiListClipper clipper; + clipper.Begin(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + { + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + + PushID(i); + const bool item_selected = (i == *current_item); + if (Selectable(item_text, item_selected)) + { + *current_item = i; + value_changed = true; + } + if (item_selected) + SetItemDefaultFocus(); + PopID(); + } + EndListBox(); + + if (value_changed) + MarkItemEdited(g.LastItemData.ID); + + return value_changed; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: PlotLines, PlotHistogram +//------------------------------------------------------------------------- +// - PlotEx() [Internal] +// - PlotLines() +// - PlotHistogram() +//------------------------------------------------------------------------- +// Plot/Graph widgets are not very good. +// Consider writing your own, or using a third-party one, see: +// - ImPlot https://github.com/epezent/implot +// - others https://github.com/ocornut/imgui/wiki/Useful-Extensions +//------------------------------------------------------------------------- + +int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return -1; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + if (frame_size.x == 0.0f) + frame_size.x = CalcItemWidth(); + if (frame_size.y == 0.0f) + frame_size.y = label_size.y + (style.FramePadding.y * 2); + + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, 0, &frame_bb)) + return -1; + const bool hovered = ItemHoverable(frame_bb, id); + + // Determine scale from values if not specified + if (scale_min == FLT_MAX || scale_max == FLT_MAX) + { + float v_min = FLT_MAX; + float v_max = -FLT_MAX; + for (int i = 0; i < values_count; i++) + { + const float v = values_getter(data, i); + if (v != v) // Ignore NaN values + continue; + v_min = ImMin(v_min, v); + v_max = ImMax(v_max, v); + } + if (scale_min == FLT_MAX) + scale_min = v_min; + if (scale_max == FLT_MAX) + scale_max = v_max; + } + + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + + const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1; + int idx_hovered = -1; + if (values_count >= values_count_min) + { + int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + + // Tooltip on hover + if (hovered && inner_bb.Contains(g.IO.MousePos)) + { + const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); + const int v_idx = (int)(t * item_count); + IM_ASSERT(v_idx >= 0 && v_idx < values_count); + + const float v0 = values_getter(data, (v_idx + values_offset) % values_count); + const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); + if (plot_type == ImGuiPlotType_Lines) + SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx + 1, v1); + else if (plot_type == ImGuiPlotType_Histogram) + SetTooltip("%d: %8.4g", v_idx, v0); + idx_hovered = v_idx; + } + + const float t_step = 1.0f / (float)res_w; + const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min)); + + float v0 = values_getter(data, (0 + values_offset) % values_count); + float t0 = 0.0f; + ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle + float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (1 + scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands + + const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); + const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); + + for (int n = 0; n < res_w; n++) + { + const float t1 = t0 + t_step; + const int v1_idx = (int)(t0 * item_count + 0.5f); + IM_ASSERT(v1_idx >= 0 && v1_idx < values_count); + const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); + const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) ); + + // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. + ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); + ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t)); + if (plot_type == ImGuiPlotType_Lines) + { + window->DrawList->AddLine(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base); + } + else if (plot_type == ImGuiPlotType_Histogram) + { + if (pos1.x >= pos0.x + 2.0f) + pos1.x -= 1.0f; + window->DrawList->AddRectFilled(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base); + } + + t0 = t1; + tp0 = tp1; + } + } + + // Text overlay + if (overlay_text) + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f, 0.0f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); + + // Return hovered index or -1 if none are hovered. + // This is currently not exposed in the public API because we need a larger redesign of the whole thing, but in the short-term we are making it available in PlotEx(). + return idx_hovered; +} + +struct ImGuiPlotArrayGetterData +{ + const float* Values; + int Stride; + + ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } +}; + +static float Plot_ArrayGetter(void* data, int idx) +{ + ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; + const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); + return v; +} + +void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Value helpers +// Those is not very useful, legacy API. +//------------------------------------------------------------------------- +// - Value() +//------------------------------------------------------------------------- + +void ImGui::Value(const char* prefix, bool b) +{ + Text("%s: %s", prefix, (b ? "true" : "false")); +} + +void ImGui::Value(const char* prefix, int v) +{ + Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, unsigned int v) +{ + Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, float v, const char* float_format) +{ + if (float_format) + { + char fmt[64]; + ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); + Text(fmt, prefix, v); + } + else + { + Text("%s: %.3f", prefix, v); + } +} + +//------------------------------------------------------------------------- +// [SECTION] MenuItem, BeginMenu, EndMenu, etc. +//------------------------------------------------------------------------- +// - ImGuiMenuColumns [Internal] +// - BeginMenuBar() +// - EndMenuBar() +// - BeginMainMenuBar() +// - EndMainMenuBar() +// - BeginMenu() +// - EndMenu() +// - MenuItemEx() [Internal] +// - MenuItem() +//------------------------------------------------------------------------- + +// Helpers for internal use +void ImGuiMenuColumns::Update(float spacing, bool window_reappearing) +{ + if (window_reappearing) + memset(Widths, 0, sizeof(Widths)); + Spacing = (ImU16)spacing; + CalcNextTotalWidth(true); + memset(Widths, 0, sizeof(Widths)); + TotalWidth = NextTotalWidth; + NextTotalWidth = 0; +} + +void ImGuiMenuColumns::CalcNextTotalWidth(bool update_offsets) +{ + ImU16 offset = 0; + bool want_spacing = false; + for (int i = 0; i < IM_ARRAYSIZE(Widths); i++) + { + ImU16 width = Widths[i]; + if (want_spacing && width > 0) + offset += Spacing; + want_spacing |= (width > 0); + if (update_offsets) + { + if (i == 1) { OffsetLabel = offset; } + if (i == 2) { OffsetShortcut = offset; } + if (i == 3) { OffsetMark = offset; } + } + offset += width; + } + NextTotalWidth = offset; +} + +float ImGuiMenuColumns::DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark) +{ + Widths[0] = ImMax(Widths[0], (ImU16)w_icon); + Widths[1] = ImMax(Widths[1], (ImU16)w_label); + Widths[2] = ImMax(Widths[2], (ImU16)w_shortcut); + Widths[3] = ImMax(Widths[3], (ImU16)w_mark); + CalcNextTotalWidth(false); + return (float)ImMax(TotalWidth, NextTotalWidth); +} + +// FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere.. +// Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer. +// Ideally we also want this to be responsible for claiming space out of the main window scrolling rectangle, in which case ImGuiWindowFlags_MenuBar will become unnecessary. +// Then later the same system could be used for multiple menu-bars, scrollbars, side-bars. +bool ImGui::BeginMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + if (!(window->Flags & ImGuiWindowFlags_MenuBar)) + return false; + + IM_ASSERT(!window->DC.MenuBarAppending); + BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore + PushID("##menubar"); + + // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect. + // We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy. + ImRect bar_rect = window->MenuBarRect(); + ImRect clip_rect(IM_ROUND(bar_rect.Min.x + window->WindowBorderSize), IM_ROUND(bar_rect.Min.y + window->WindowBorderSize), IM_ROUND(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, window->WindowBorderSize))), IM_ROUND(bar_rect.Max.y)); + clip_rect.ClipWith(window->OuterRectClipped); + PushClipRect(clip_rect.Min, clip_rect.Max, false); + + // We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags). + window->DC.CursorPos = window->DC.CursorMaxPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y); + window->DC.LayoutType = ImGuiLayoutType_Horizontal; + window->DC.IsSameLine = false; + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + window->DC.MenuBarAppending = true; + AlignTextToFramePadding(); + return true; +} + +void ImGui::EndMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ImGuiContext& g = *GImGui; + + // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings. + if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) + { + // Try to find out if the request is for one of our child menu + ImGuiWindow* nav_earliest_child = g.NavWindow; + while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu)) + nav_earliest_child = nav_earliest_child->ParentWindow; + if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0) + { + // To do so we claim focus back, restore NavId and then process the movement request for yet another frame. + // This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth bothering) + const ImGuiNavLayer layer = ImGuiNavLayer_Menu; + IM_ASSERT(window->DC.NavLayersActiveMaskNext & (1 << layer)); // Sanity check + FocusWindow(window); + SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]); + g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection. + g.NavDisableMouseHover = g.NavMousePosDirty = true; + NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); // Repeat + } + } + + IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'" + IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); + IM_ASSERT(window->DC.MenuBarAppending); + PopClipRect(); + PopID(); + window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->Pos.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos. + g.GroupStack.back().EmitItem = false; + EndGroup(); // Restore position on layer 0 + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.IsSameLine = false; + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + window->DC.MenuBarAppending = false; +} + +// Important: calling order matters! +// FIXME: Somehow overlapping with docking tech. +// FIXME: The "rect-cut" aspect of this could be formalized into a lower-level helper (rect-cut: https://halt.software/dead-simple-layouts) +bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, ImGuiDir dir, float axis_size, ImGuiWindowFlags window_flags) +{ + IM_ASSERT(dir != ImGuiDir_None); + + ImGuiWindow* bar_window = FindWindowByName(name); + ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)(viewport_p ? viewport_p : GetMainViewport()); + if (bar_window == NULL || bar_window->BeginCount == 0) + { + // Calculate and set window size/position + ImRect avail_rect = viewport->GetBuildWorkRect(); + ImGuiAxis axis = (dir == ImGuiDir_Up || dir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X; + ImVec2 pos = avail_rect.Min; + if (dir == ImGuiDir_Right || dir == ImGuiDir_Down) + pos[axis] = avail_rect.Max[axis] - axis_size; + ImVec2 size = avail_rect.GetSize(); + size[axis] = axis_size; + SetNextWindowPos(pos); + SetNextWindowSize(size); + + // Report our size into work area (for next frame) using actual window size + if (dir == ImGuiDir_Up || dir == ImGuiDir_Left) + viewport->BuildWorkOffsetMin[axis] += axis_size; + else if (dir == ImGuiDir_Down || dir == ImGuiDir_Right) + viewport->BuildWorkOffsetMax[axis] -= axis_size; + } + + window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking; + SetNextWindowViewport(viewport->ID); // Enforce viewport so we don't create our own viewport when ImGuiConfigFlags_ViewportsNoMerge is set. + PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0)); // Lift normal size constraint + bool is_open = Begin(name, NULL, window_flags); + PopStyleVar(2); + + return is_open; +} + +bool ImGui::BeginMainMenuBar() +{ + ImGuiContext& g = *GImGui; + ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport(); + + // Notify of viewport change so GetFrameHeight() can be accurate in case of DPI change + SetCurrentViewport(NULL, viewport); + + // For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set. + // FIXME: This could be generalized as an opt-in way to clamp window->DC.CursorStartPos to avoid SafeArea? + // FIXME: Consider removing support for safe area down the line... it's messy. Nowadays consoles have support for TV calibration in OS settings. + g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f)); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar; + float height = GetFrameHeight(); + bool is_open = BeginViewportSideBar("##MainMenuBar", viewport, ImGuiDir_Up, height, window_flags); + g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f); + + if (is_open) + BeginMenuBar(); + else + End(); + return is_open; +} + +void ImGui::EndMainMenuBar() +{ + EndMenuBar(); + + // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window + // FIXME: With this strategy we won't be able to restore a NULL focus. + ImGuiContext& g = *GImGui; + if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest) + FocusTopMostWindowUnderOne(g.NavWindow, NULL); + + End(); +} + +static bool IsRootOfOpenMenuSet() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if ((g.OpenPopupStack.Size <= g.BeginPopupStack.Size) || (window->Flags & ImGuiWindowFlags_ChildMenu)) + return false; + + // Initially we used 'OpenParentId' to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) based on parent ID. + // This would however prevent the use of e.g. PuhsID() user code submitting menus. + // Previously this worked between popup and a first child menu because the first child menu always had the _ChildWindow flag, + // making hovering on parent popup possible while first child menu was focused - but this was generally a bug with other side effects. + // Instead we don't treat Popup specifically (in order to consistently support menu features in them), maybe the first child menu of a Popup + // doesn't have the _ChildWindow flag, and we rely on this IsRootOfOpenMenuSet() check to allow hovering between root window/popup and first chilld menu. + const ImGuiPopupData* upper_popup = &g.OpenPopupStack[g.BeginPopupStack.Size]; + return (/*upper_popup->OpenParentId == window->IDStack.back() &&*/ upper_popup->Window && (upper_popup->Window->Flags & ImGuiWindowFlags_ChildMenu)); +} + +bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + bool menu_is_open = IsPopupOpen(id, ImGuiPopupFlags_None); + + // Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu) + // The first menu in a hierarchy isn't so hovering doesn't get accross (otherwise e.g. resizing borders with ImGuiButtonFlags_FlattenChildren would react), but top-most BeginMenu() will bypass that limitation. + ImGuiWindowFlags flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus; + if (window->Flags & ImGuiWindowFlags_ChildMenu) + flags |= ImGuiWindowFlags_ChildWindow; + + // If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin(). + // We are relying on a O(N) search - so O(N log N) over the frame - which seems like the most efficient for the expected small amount of BeginMenu() calls per frame. + // If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used. + if (g.MenusIdSubmittedThisFrame.contains(id)) + { + if (menu_is_open) + menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + else + g.NextWindowData.ClearFlags(); // we behave like Begin() and need to consume those values + return menu_is_open; + } + + // Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu + g.MenusIdSubmittedThisFrame.push_back(id); + + ImVec2 label_size = CalcTextSize(label, NULL, true); + + // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent without always being a Child window) + const bool menuset_is_open = IsRootOfOpenMenuSet(); + ImGuiWindow* backed_nav_window = g.NavWindow; + if (menuset_is_open) + g.NavWindow = window; + + // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu, + // However the final position is going to be different! It is chosen by FindBestWindowPosForPopup(). + // e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering. + ImVec2 popup_pos, pos = window->DC.CursorPos; + PushID(label); + if (!enabled) + BeginDisabled(); + const ImGuiMenuColumns* offsets = &window->DC.MenuColumns; + bool pressed; + const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_DontClosePopups; + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + { + // Menu inside an horizontal menu bar + // Selectable extend their highlight by half ItemSpacing in each direction. + // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin() + popup_pos = ImVec2(pos.x - 1.0f - IM_FLOOR(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight()); + window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * 0.5f); + PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y)); + float w = label_size.x; + ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + pressed = Selectable("", menu_is_open, selectable_flags, ImVec2(w, 0.0f)); + RenderText(text_pos, label); + PopStyleVar(); + window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). + } + else + { + // Menu inside a regular/vertical menu + // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f. + // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system. + popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); + float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f; + float checkmark_w = IM_FLOOR(g.FontSize * 1.20f); + float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, 0.0f, checkmark_w); // Feedback to next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w); + ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + pressed = Selectable("", menu_is_open, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, 0.0f)); + RenderText(text_pos, label); + if (icon_w > 0.0f) + RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon); + RenderArrow(window->DrawList, pos + ImVec2(offsets->OffsetMark + extra_w + g.FontSize * 0.30f, 0.0f), GetColorU32(ImGuiCol_Text), ImGuiDir_Right); + } + if (!enabled) + EndDisabled(); + + const bool hovered = (g.HoveredId == id) && enabled && !g.NavDisableMouseHover; + if (menuset_is_open) + g.NavWindow = backed_nav_window; + + bool want_open = false; + bool want_close = false; + if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) + { + // Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu + // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. + bool moving_toward_child_menu = false; + ImGuiWindow* child_menu_window = (g.BeginPopupStack.Size < g.OpenPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].SourceWindow == window) ? g.OpenPopupStack[g.BeginPopupStack.Size].Window : NULL; + if (g.HoveredWindow == window && child_menu_window != NULL && !(window->Flags & ImGuiWindowFlags_MenuBar)) + { + float ref_unit = g.FontSize; // FIXME-DPI + ImRect next_window_rect = child_menu_window->Rect(); + ImVec2 ta = (g.IO.MousePos - g.IO.MouseDelta); + ImVec2 tb = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); + ImVec2 tc = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); + float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, ref_unit * 0.5f, ref_unit * 2.5f); // add a bit of extra slack. + ta.x += (window->Pos.x < child_menu_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues (FIXME: ??) + tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -ref_unit * 8.0f); // triangle has maximum height to limit the slope and the bias toward large sub-menus + tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +ref_unit * 8.0f); + moving_toward_child_menu = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos); + //GetForegroundDrawList()->AddTriangleFilled(ta, tb, tc, moving_toward_other_child_menu ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); // [DEBUG] + } + + // The 'HovereWindow == window' check creates an inconsistency (e.g. moving away from menu slowly tends to hit same window, whereas moving away fast does not) + // But we also need to not close the top-menu menu when moving over void. Perhaps we should extend the triangle check to a larger polygon. + // (Remember to test this on BeginPopup("A")->BeginMenu("B") sequence which behaves slightly differently as B isn't a Child of A and hovering isn't shared.) + if (menu_is_open && !hovered && g.HoveredWindow == window && !moving_toward_child_menu) + want_close = true; + + // Open + if (!menu_is_open && pressed) // Click/activate to open + want_open = true; + else if (!menu_is_open && hovered && !moving_toward_child_menu) // Hover to open + want_open = true; + if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open + { + want_open = true; + NavMoveRequestCancel(); + } + } + else + { + // Menu bar + if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it + { + want_close = true; + want_open = menu_is_open = false; + } + else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others + { + want_open = true; + } + else if (g.NavId == id && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open + { + want_open = true; + NavMoveRequestCancel(); + } + } + + if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' + want_close = true; + if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None)) + ClosePopupToLevel(g.BeginPopupStack.Size, true); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0)); + PopID(); + + if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size) + { + // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame. + OpenPopup(label); + return false; + } + + menu_is_open |= want_open; + if (want_open) + OpenPopup(label); + + if (menu_is_open) + { + SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: this is super misleading! The value will serve as reference for FindBestWindowPosForPopup(), not actual pos. + PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding + menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + PopStyleVar(); + } + else + { + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values + } + + return menu_is_open; +} + +bool ImGui::BeginMenu(const char* label, bool enabled) +{ + return BeginMenuEx(label, NULL, enabled); +} + +void ImGui::EndMenu() +{ + // Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu). + // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs. + // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical) + if (g.NavWindow && (g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow == window) + { + ClosePopupToLevel(g.BeginPopupStack.Size, true); + NavMoveRequestCancel(); + } + + EndPopup(); +} + +bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut, bool selected, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + ImVec2 pos = window->DC.CursorPos; + ImVec2 label_size = CalcTextSize(label, NULL, true); + + const bool menuset_is_open = IsRootOfOpenMenuSet(); + ImGuiWindow* backed_nav_window = g.NavWindow; + if (menuset_is_open) + g.NavWindow = window; + + // We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73), + // but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only. + bool pressed; + PushID(label); + if (!enabled) + BeginDisabled(); + + const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_SelectOnRelease | ImGuiSelectableFlags_SetNavIdOnHover; + const ImGuiMenuColumns* offsets = &window->DC.MenuColumns; + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + { + // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful + // Note that in this situation: we don't render the shortcut, we render a highlight instead of the selected tick mark. + float w = label_size.x; + window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * 0.5f); + ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); + PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y)); + pressed = Selectable("", selected, selectable_flags, ImVec2(w, 0.0f)); + PopStyleVar(); + RenderText(text_pos, label); + window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). + } + else + { + // Menu item inside a vertical menu + // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f. + // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system. + float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f; + float shortcut_w = (shortcut && shortcut[0]) ? CalcTextSize(shortcut, NULL).x : 0.0f; + float checkmark_w = IM_FLOOR(g.FontSize * 1.20f); + float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w); // Feedback for next frame + float stretch_w = ImMax(0.0f, GetContentRegionAvail().x - min_w); + pressed = Selectable("", false, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, 0.0f)); + RenderText(pos + ImVec2(offsets->OffsetLabel, 0.0f), label); + if (icon_w > 0.0f) + RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon); + if (shortcut_w > 0.0f) + { + PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); + RenderText(pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false); + PopStyleColor(); + } + if (selected) + RenderCheckMark(window->DrawList, pos + ImVec2(offsets->OffsetMark + stretch_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(ImGuiCol_Text), g.FontSize * 0.866f); + } + IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0)); + if (!enabled) + EndDisabled(); + PopID(); + if (menuset_is_open) + g.NavWindow = backed_nav_window; + + return pressed; +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) +{ + return MenuItemEx(label, NULL, shortcut, selected, enabled); +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) +{ + if (MenuItemEx(label, NULL, shortcut, p_selected ? *p_selected : false, enabled)) + { + if (p_selected) + *p_selected = !*p_selected; + return true; + } + return false; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: BeginTabBar, EndTabBar, etc. +//------------------------------------------------------------------------- +// - BeginTabBar() +// - BeginTabBarEx() [Internal] +// - EndTabBar() +// - TabBarLayout() [Internal] +// - TabBarCalcTabID() [Internal] +// - TabBarCalcMaxTabWidth() [Internal] +// - TabBarFindTabById() [Internal] +// - TabBarAddTab() [Internal] +// - TabBarRemoveTab() [Internal] +// - TabBarCloseTab() [Internal] +// - TabBarScrollClamp() [Internal] +// - TabBarScrollToTab() [Internal] +// - TabBarQueueChangeTabOrder() [Internal] +// - TabBarScrollingButtons() [Internal] +// - TabBarTabListPopupButton() [Internal] +//------------------------------------------------------------------------- + +struct ImGuiTabBarSection +{ + int TabCount; // Number of tabs in this section. + float Width; // Sum of width of tabs in this section (after shrinking down) + float Spacing; // Horizontal spacing at the end of the section. + + ImGuiTabBarSection() { memset(this, 0, sizeof(*this)); } +}; + +namespace ImGui +{ + static void TabBarLayout(ImGuiTabBar* tab_bar); + static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window); + static float TabBarCalcMaxTabWidth(); + static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling); + static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections); + static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar); + static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar); +} + +ImGuiTabBar::ImGuiTabBar() +{ + memset(this, 0, sizeof(*this)); + CurrFrameVisible = PrevFrameVisible = -1; + LastTabItemIdx = -1; +} + +static inline int TabItemGetSectionIdx(const ImGuiTabItem* tab) +{ + return (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; +} + +static int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs) +{ + const ImGuiTabItem* a = (const ImGuiTabItem*)lhs; + const ImGuiTabItem* b = (const ImGuiTabItem*)rhs; + const int a_section = TabItemGetSectionIdx(a); + const int b_section = TabItemGetSectionIdx(b); + if (a_section != b_section) + return a_section - b_section; + return (int)(a->IndexDuringLayout - b->IndexDuringLayout); +} + +static int IMGUI_CDECL TabItemComparerByBeginOrder(const void* lhs, const void* rhs) +{ + const ImGuiTabItem* a = (const ImGuiTabItem*)lhs; + const ImGuiTabItem* b = (const ImGuiTabItem*)rhs; + return (int)(a->BeginOrder - b->BeginOrder); +} + +static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref) +{ + ImGuiContext& g = *GImGui; + return ref.Ptr ? (ImGuiTabBar*)ref.Ptr : g.TabBars.GetByIndex(ref.Index); +} + +static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + if (g.TabBars.Contains(tab_bar)) + return ImGuiPtrOrIndex(g.TabBars.GetIndex(tab_bar)); + return ImGuiPtrOrIndex(tab_bar); +} + +bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + ImGuiID id = window->GetID(str_id); + ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id); + ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); + tab_bar->ID = id; + return BeginTabBarEx(tab_bar, tab_bar_bb, flags | ImGuiTabBarFlags_IsFocused, NULL); +} + +bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags, ImGuiDockNode* dock_node) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + if ((flags & ImGuiTabBarFlags_DockNode) == 0) + PushOverrideID(tab_bar->ID); + + // Add to stack + g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar)); + g.CurrentTabBar = tab_bar; + + // Append with multiple BeginTabBar()/EndTabBar() pairs. + tab_bar->BackupCursorPos = window->DC.CursorPos; + if (tab_bar->CurrFrameVisible == g.FrameCount) + { + window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY); + tab_bar->BeginCount++; + return true; + } + + // Ensure correct ordering when toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable + if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (tab_bar->TabsAddedNew && !(flags & ImGuiTabBarFlags_Reorderable))) + if ((flags & ImGuiTabBarFlags_DockNode) == 0) // FIXME: TabBar with DockNode can now be hybrid + ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); + tab_bar->TabsAddedNew = false; + + // Flags + if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) + flags |= ImGuiTabBarFlags_FittingPolicyDefault_; + + tab_bar->Flags = flags; + tab_bar->BarRect = tab_bar_bb; + tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab() + tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible; + tab_bar->CurrFrameVisible = g.FrameCount; + tab_bar->PrevTabsContentsHeight = tab_bar->CurrTabsContentsHeight; + tab_bar->CurrTabsContentsHeight = 0.0f; + tab_bar->ItemSpacingY = g.Style.ItemSpacing.y; + tab_bar->FramePadding = g.Style.FramePadding; + tab_bar->TabsActiveCount = 0; + tab_bar->BeginCount = 1; + + // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap + window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY); + + // Draw separator + const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive); + const float y = tab_bar->BarRect.Max.y - 1.0f; + if (dock_node != NULL) + { + const float separator_min_x = dock_node->Pos.x + window->WindowBorderSize; + const float separator_max_x = dock_node->Pos.x + dock_node->Size.x - window->WindowBorderSize; + window->DrawList->AddLine(ImVec2(separator_min_x, y), ImVec2(separator_max_x, y), col, 1.0f); + } + else + { + const float separator_min_x = tab_bar->BarRect.Min.x - IM_FLOOR(window->WindowPadding.x * 0.5f); + const float separator_max_x = tab_bar->BarRect.Max.x + IM_FLOOR(window->WindowPadding.x * 0.5f); + window->DrawList->AddLine(ImVec2(separator_min_x, y), ImVec2(separator_max_x, y), col, 1.0f); + } + return true; +} + +void ImGui::EndTabBar() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + if (tab_bar == NULL) + { + IM_ASSERT_USER_ERROR(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!"); + return; + } + + // Fallback in case no TabItem have been submitted + if (tab_bar->WantLayout) + TabBarLayout(tab_bar); + + // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). + const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); + if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing) + { + tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight); + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight; + } + else + { + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->PrevTabsContentsHeight; + } + if (tab_bar->BeginCount > 1) + window->DC.CursorPos = tab_bar->BackupCursorPos; + + if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) + PopID(); + + g.CurrentTabBarStack.pop_back(); + g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back()); +} + +// This is called only once a frame before by the first call to ItemTab() +// The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions. +static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + tab_bar->WantLayout = false; + + // Garbage collect by compacting list + // Detect if we need to sort out tab list (e.g. in rare case where a tab changed section) + int tab_dst_n = 0; + bool need_sort_by_section = false; + ImGuiTabBarSection sections[3]; // Layout sections: Leading, Central, Trailing + for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; + if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose) + { + // Remove tab + if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; } + if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; } + if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; } + continue; + } + if (tab_dst_n != tab_src_n) + tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n]; + + tab = &tab_bar->Tabs[tab_dst_n]; + tab->IndexDuringLayout = (ImS16)tab_dst_n; + + // We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another) + int curr_tab_section_n = TabItemGetSectionIdx(tab); + if (tab_dst_n > 0) + { + ImGuiTabItem* prev_tab = &tab_bar->Tabs[tab_dst_n - 1]; + int prev_tab_section_n = TabItemGetSectionIdx(prev_tab); + if (curr_tab_section_n == 0 && prev_tab_section_n != 0) + need_sort_by_section = true; + if (prev_tab_section_n == 2 && curr_tab_section_n != 2) + need_sort_by_section = true; + } + + sections[curr_tab_section_n].TabCount++; + tab_dst_n++; + } + if (tab_bar->Tabs.Size != tab_dst_n) + tab_bar->Tabs.resize(tab_dst_n); + + if (need_sort_by_section) + ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerBySection); + + // Calculate spacing between sections + sections[0].Spacing = sections[0].TabCount > 0 && (sections[1].TabCount + sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + sections[1].Spacing = sections[1].TabCount > 0 && sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + + // Setup next selected tab + ImGuiID scroll_to_tab_id = 0; + if (tab_bar->NextSelectedTabId) + { + tab_bar->SelectedTabId = tab_bar->NextSelectedTabId; + tab_bar->NextSelectedTabId = 0; + scroll_to_tab_id = tab_bar->SelectedTabId; + } + + // Process order change request (we could probably process it when requested but it's just saner to do it in a single spot). + if (tab_bar->ReorderRequestTabId != 0) + { + if (TabBarProcessReorder(tab_bar)) + if (tab_bar->ReorderRequestTabId == tab_bar->SelectedTabId) + scroll_to_tab_id = tab_bar->ReorderRequestTabId; + tab_bar->ReorderRequestTabId = 0; + } + + // Tab List Popup (will alter tab_bar->BarRect and therefore the available width!) + const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0; + if (tab_list_popup_button) + if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x! + scroll_to_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; + + // Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central + // (whereas our tabs are stored as: leading, central, trailing) + int shrink_buffer_indexes[3] = { 0, sections[0].TabCount + sections[2].TabCount, sections[0].TabCount }; + g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); + + // Compute ideal tabs widths + store them into shrink buffer + ImGuiTabItem* most_recently_selected_tab = NULL; + int curr_section_n = -1; + bool found_selected_tab_id = false; + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible); + + if ((most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) && !(tab->Flags & ImGuiTabItemFlags_Button)) + most_recently_selected_tab = tab; + if (tab->ID == tab_bar->SelectedTabId) + found_selected_tab_id = true; + if (scroll_to_tab_id == 0 && g.NavJustMovedToId == tab->ID) + scroll_to_tab_id = tab->ID; + + // Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar. + // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet, + // and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window. + const char* tab_name = tab_bar->GetTabName(tab); + const bool has_close_button = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) == 0; + tab->ContentWidth = TabItemCalcSize(tab_name, has_close_button).x; + + int section_n = TabItemGetSectionIdx(tab); + ImGuiTabBarSection* section = §ions[section_n]; + section->Width += tab->ContentWidth + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f); + curr_section_n = section_n; + + // Store data so we can build an array sorted by width if we need to shrink tabs down + IM_MSVC_WARNING_SUPPRESS(6385); + int shrink_buffer_index = shrink_buffer_indexes[section_n]++; + g.ShrinkWidthBuffer[shrink_buffer_index].Index = tab_n; + g.ShrinkWidthBuffer[shrink_buffer_index].Width = tab->ContentWidth; + + IM_ASSERT(tab->ContentWidth > 0.0f); + tab->Width = tab->ContentWidth; + } + + // Compute total ideal width (used for e.g. auto-resizing a window) + tab_bar->WidthAllTabsIdeal = 0.0f; + for (int section_n = 0; section_n < 3; section_n++) + tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing; + + // Horizontal scrolling buttons + // (note that TabBarScrollButtons() will alter BarRect.Max.x) + if ((tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll)) + if (ImGuiTabItem* scroll_and_select_tab = TabBarScrollingButtons(tab_bar)) + { + scroll_to_tab_id = scroll_and_select_tab->ID; + if ((scroll_and_select_tab->Flags & ImGuiTabItemFlags_Button) == 0) + tab_bar->SelectedTabId = scroll_to_tab_id; + } + + // Shrink widths if full tabs don't fit in their allocated space + float section_0_w = sections[0].Width + sections[0].Spacing; + float section_1_w = sections[1].Width + sections[1].Spacing; + float section_2_w = sections[2].Width + sections[2].Spacing; + bool central_section_is_visible = (section_0_w + section_2_w) < tab_bar->BarRect.GetWidth(); + float width_excess; + if (central_section_is_visible) + width_excess = ImMax(section_1_w - (tab_bar->BarRect.GetWidth() - section_0_w - section_2_w), 0.0f); // Excess used to shrink central section + else + width_excess = (section_0_w + section_2_w) - tab_bar->BarRect.GetWidth(); // Excess used to shrink leading/trailing section + + // With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore + if (width_excess > 0.0f && ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown) || !central_section_is_visible)) + { + int shrink_data_count = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount); + int shrink_data_offset = (central_section_is_visible ? sections[0].TabCount + sections[2].TabCount : 0); + ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess); + + // Apply shrunk values into tabs and sections + for (int tab_n = shrink_data_offset; tab_n < shrink_data_offset + shrink_data_count; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index]; + float shrinked_width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width); + if (shrinked_width < 0.0f) + continue; + + int section_n = TabItemGetSectionIdx(tab); + sections[section_n].Width -= (tab->Width - shrinked_width); + tab->Width = shrinked_width; + } + } + + // Layout all active tabs + int section_tab_index = 0; + float tab_offset = 0.0f; + tab_bar->WidthAllTabs = 0.0f; + for (int section_n = 0; section_n < 3; section_n++) + { + ImGuiTabBarSection* section = §ions[section_n]; + if (section_n == 2) + tab_offset = ImMin(ImMax(0.0f, tab_bar->BarRect.GetWidth() - section->Width), tab_offset); + + for (int tab_n = 0; tab_n < section->TabCount; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[section_tab_index + tab_n]; + tab->Offset = tab_offset; + tab->NameOffset = -1; + tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); + } + tab_bar->WidthAllTabs += ImMax(section->Width + section->Spacing, 0.0f); + tab_offset += section->Spacing; + section_tab_index += section->TabCount; + } + + // Clear name buffers + tab_bar->TabsNames.Buf.resize(0); + + // If we have lost the selected tab, select the next most recently active one + if (found_selected_tab_id == false) + tab_bar->SelectedTabId = 0; + if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL) + scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID; + + // Lock in visible tab + tab_bar->VisibleTabId = tab_bar->SelectedTabId; + tab_bar->VisibleTabWasSubmitted = false; + + // CTRL+TAB can override visible tab temporarily + if (g.NavWindowingTarget != NULL && g.NavWindowingTarget->DockNode && g.NavWindowingTarget->DockNode->TabBar == tab_bar) + tab_bar->VisibleTabId = scroll_to_tab_id = g.NavWindowingTarget->ID; + + // Update scrolling + if (scroll_to_tab_id != 0) + TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections); + tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim); + tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget); + if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget) + { + // Scrolling speed adjust itself so we can always reach our target in 1/3 seconds. + // Teleport if we are aiming far off the visible line + tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize); + tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f); + const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize); + tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed); + } + else + { + tab_bar->ScrollingSpeed = 0.0f; + } + tab_bar->ScrollingRectMinX = tab_bar->BarRect.Min.x + sections[0].Width + sections[0].Spacing; + tab_bar->ScrollingRectMaxX = tab_bar->BarRect.Max.x - sections[2].Width - sections[1].Spacing; + + // Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame) + ImGuiWindow* window = g.CurrentWindow; + window->DC.CursorPos = tab_bar->BarRect.Min; + ItemSize(ImVec2(tab_bar->WidthAllTabs, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); + window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, tab_bar->BarRect.Min.x + tab_bar->WidthAllTabsIdeal); +} + +// Dockable uses Name/ID in the global namespace. Non-dockable items use the ID stack. +static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window) +{ + if (docked_window != NULL) + { + IM_UNUSED(tab_bar); + IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode); + ImGuiID id = docked_window->TabId; + KeepAliveID(id); + return id; + } + else + { + ImGuiWindow* window = GImGui->CurrentWindow; + return window->GetID(label); + } +} + +static float ImGui::TabBarCalcMaxTabWidth() +{ + ImGuiContext& g = *GImGui; + return g.FontSize * 20.0f; +} + +ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id) +{ + if (tab_id != 0) + for (int n = 0; n < tab_bar->Tabs.Size; n++) + if (tab_bar->Tabs[n].ID == tab_id) + return &tab_bar->Tabs[n]; + return NULL; +} + +// FIXME: See references to #2304 in TODO.txt +ImGuiTabItem* ImGui::TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar) +{ + ImGuiTabItem* most_recently_selected_tab = NULL; + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) + if (tab->Window && tab->Window->WasActive) + most_recently_selected_tab = tab; + } + return most_recently_selected_tab; +} + +// The purpose of this call is to register tab in advance so we can control their order at the time they appear. +// Otherwise calling this is unnecessary as tabs are appending as needed by the BeginTabItem() function. +void ImGui::TabBarAddTab(ImGuiTabBar* tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(TabBarFindTabByID(tab_bar, window->TabId) == NULL); + IM_ASSERT(g.CurrentTabBar != tab_bar); // Can't work while the tab bar is active as our tab doesn't have an X offset yet, in theory we could/should test something like (tab_bar->CurrFrameVisible < g.FrameCount) but we'd need to solve why triggers the commented early-out assert in BeginTabBarEx() (probably dock node going from implicit to explicit in same frame) + + if (!window->HasCloseButton) + tab_flags |= ImGuiTabItemFlags_NoCloseButton; // Set _NoCloseButton immediately because it will be used for first-frame width calculation. + + ImGuiTabItem new_tab; + new_tab.ID = window->TabId; + new_tab.Flags = tab_flags; + new_tab.LastFrameVisible = tab_bar->CurrFrameVisible; // Required so BeginTabBar() doesn't ditch the tab + if (new_tab.LastFrameVisible == -1) + new_tab.LastFrameVisible = g.FrameCount - 1; + new_tab.Window = window; // Required so tab bar layout can compute the tab width before tab submission + tab_bar->Tabs.push_back(new_tab); +} + +// The *TabId fields be already set by the docking system _before_ the actual TabItem was created, so we clear them regardless. +void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id) +{ + if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) + tab_bar->Tabs.erase(tab); + if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; } + if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; } + if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; } +} + +// Called on manual closure attempt +void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) +{ + IM_ASSERT(!(tab->Flags & ImGuiTabItemFlags_Button)); + if (!(tab->Flags & ImGuiTabItemFlags_UnsavedDocument)) + { + // This will remove a frame of lag for selecting another tab on closure. + // However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure + tab->WantClose = true; + if (tab_bar->VisibleTabId == tab->ID) + { + tab->LastFrameVisible = -1; + tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0; + } + } + else + { + // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup) + if (tab_bar->VisibleTabId != tab->ID) + tab_bar->NextSelectedTabId = tab->ID; + } +} + +static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling) +{ + scrolling = ImMin(scrolling, tab_bar->WidthAllTabs - tab_bar->BarRect.GetWidth()); + return ImMax(scrolling, 0.0f); +} + +// Note: we may scroll to tab that are not selected! e.g. using keyboard arrow keys +static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections) +{ + ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id); + if (tab == NULL) + return; + if (tab->Flags & ImGuiTabItemFlags_SectionMask_) + return; + + ImGuiContext& g = *GImGui; + float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) + int order = tab_bar->GetTabOrder(tab); + + // Scrolling happens only in the central section (leading/trailing sections are not scrolling) + // FIXME: This is all confusing. + float scrollable_width = tab_bar->BarRect.GetWidth() - sections[0].Width - sections[2].Width - sections[1].Spacing; + + // We make all tabs positions all relative Sections[0].Width to make code simpler + float tab_x1 = tab->Offset - sections[0].Width + (order > sections[0].TabCount - 1 ? -margin : 0.0f); + float tab_x2 = tab->Offset - sections[0].Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - sections[2].TabCount ? margin : 1.0f); + tab_bar->ScrollingTargetDistToVisibility = 0.0f; + if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= scrollable_width)) + { + // Scroll to the left + tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f); + tab_bar->ScrollingTarget = tab_x1; + } + else if (tab_bar->ScrollingTarget < tab_x2 - scrollable_width) + { + // Scroll to the right + tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - scrollable_width) - tab_bar->ScrollingAnim, 0.0f); + tab_bar->ScrollingTarget = tab_x2 - scrollable_width; + } +} + +void ImGui::TabBarQueueReorder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int offset) +{ + IM_ASSERT(offset != 0); + IM_ASSERT(tab_bar->ReorderRequestTabId == 0); + tab_bar->ReorderRequestTabId = tab->ID; + tab_bar->ReorderRequestOffset = (ImS16)offset; +} + +void ImGui::TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, const ImGuiTabItem* src_tab, ImVec2 mouse_pos) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(tab_bar->ReorderRequestTabId == 0); + if ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) == 0) + return; + + const bool is_central_section = (src_tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0; + const float bar_offset = tab_bar->BarRect.Min.x - (is_central_section ? tab_bar->ScrollingTarget : 0); + + // Count number of contiguous tabs we are crossing over + const int dir = (bar_offset + src_tab->Offset) > mouse_pos.x ? -1 : +1; + const int src_idx = tab_bar->Tabs.index_from_ptr(src_tab); + int dst_idx = src_idx; + for (int i = src_idx; i >= 0 && i < tab_bar->Tabs.Size; i += dir) + { + // Reordered tabs must share the same section + const ImGuiTabItem* dst_tab = &tab_bar->Tabs[i]; + if (dst_tab->Flags & ImGuiTabItemFlags_NoReorder) + break; + if ((dst_tab->Flags & ImGuiTabItemFlags_SectionMask_) != (src_tab->Flags & ImGuiTabItemFlags_SectionMask_)) + break; + dst_idx = i; + + // Include spacing after tab, so when mouse cursor is between tabs we would not continue checking further tabs that are not hovered. + const float x1 = bar_offset + dst_tab->Offset - g.Style.ItemInnerSpacing.x; + const float x2 = bar_offset + dst_tab->Offset + dst_tab->Width + g.Style.ItemInnerSpacing.x; + //GetForegroundDrawList()->AddRect(ImVec2(x1, tab_bar->BarRect.Min.y), ImVec2(x2, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255)); + if ((dir < 0 && mouse_pos.x > x1) || (dir > 0 && mouse_pos.x < x2)) + break; + } + + if (dst_idx != src_idx) + TabBarQueueReorder(tab_bar, src_tab, dst_idx - src_idx); +} + +bool ImGui::TabBarProcessReorder(ImGuiTabBar* tab_bar) +{ + ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId); + if (tab1 == NULL || (tab1->Flags & ImGuiTabItemFlags_NoReorder)) + return false; + + //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools + int tab2_order = tab_bar->GetTabOrder(tab1) + tab_bar->ReorderRequestOffset; + if (tab2_order < 0 || tab2_order >= tab_bar->Tabs.Size) + return false; + + // Reordered tabs must share the same section + // (Note: TabBarQueueReorderFromMousePos() also has a similar test but since we allow direct calls to TabBarQueueReorder() we do it here too) + ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order]; + if (tab2->Flags & ImGuiTabItemFlags_NoReorder) + return false; + if ((tab1->Flags & ImGuiTabItemFlags_SectionMask_) != (tab2->Flags & ImGuiTabItemFlags_SectionMask_)) + return false; + + ImGuiTabItem item_tmp = *tab1; + ImGuiTabItem* src_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 + 1 : tab2; + ImGuiTabItem* dst_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 : tab2 + 1; + const int move_count = (tab_bar->ReorderRequestOffset > 0) ? tab_bar->ReorderRequestOffset : -tab_bar->ReorderRequestOffset; + memmove(dst_tab, src_tab, move_count * sizeof(ImGuiTabItem)); + *tab2 = item_tmp; + + if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings) + MarkIniSettingsDirty(); + return true; +} + +static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f); + const float scrolling_buttons_width = arrow_button_size.x * 2.0f; + + const ImVec2 backup_cursor_pos = window->DC.CursorPos; + //window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255)); + + int select_dir = 0; + ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text]; + arrow_col.w *= 0.5f; + + PushStyleColor(ImGuiCol_Text, arrow_col); + PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + const float backup_repeat_delay = g.IO.KeyRepeatDelay; + const float backup_repeat_rate = g.IO.KeyRepeatRate; + g.IO.KeyRepeatDelay = 0.250f; + g.IO.KeyRepeatRate = 0.200f; + float x = ImMax(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.x - scrolling_buttons_width); + window->DC.CursorPos = ImVec2(x, tab_bar->BarRect.Min.y); + if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat)) + select_dir = -1; + window->DC.CursorPos = ImVec2(x + arrow_button_size.x, tab_bar->BarRect.Min.y); + if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat)) + select_dir = +1; + PopStyleColor(2); + g.IO.KeyRepeatRate = backup_repeat_rate; + g.IO.KeyRepeatDelay = backup_repeat_delay; + + ImGuiTabItem* tab_to_scroll_to = NULL; + if (select_dir != 0) + if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) + { + int selected_order = tab_bar->GetTabOrder(tab_item); + int target_order = selected_order + select_dir; + + // Skip tab item buttons until another tab item is found or end is reached + while (tab_to_scroll_to == NULL) + { + // If we are at the end of the list, still scroll to make our tab visible + tab_to_scroll_to = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; + + // Cross through buttons + // (even if first/last item is a button, return it so we can update the scroll) + if (tab_to_scroll_to->Flags & ImGuiTabItemFlags_Button) + { + target_order += select_dir; + selected_order += select_dir; + tab_to_scroll_to = (target_order < 0 || target_order >= tab_bar->Tabs.Size) ? tab_to_scroll_to : NULL; + } + } + } + window->DC.CursorPos = backup_cursor_pos; + tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f; + + return tab_to_scroll_to; +} + +static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + // We use g.Style.FramePadding.y to match the square ArrowButton size + const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y; + const ImVec2 backup_cursor_pos = window->DC.CursorPos; + window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y); + tab_bar->BarRect.Min.x += tab_list_popup_button_width; + + ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text]; + arrow_col.w *= 0.5f; + PushStyleColor(ImGuiCol_Text, arrow_col); + PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_HeightLargest); + PopStyleColor(2); + + ImGuiTabItem* tab_to_select = NULL; + if (open) + { + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + if (tab->Flags & ImGuiTabItemFlags_Button) + continue; + + const char* tab_name = tab_bar->GetTabName(tab); + if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID)) + tab_to_select = tab; + } + EndCombo(); + } + + window->DC.CursorPos = backup_cursor_pos; + return tab_to_select; +} + +//------------------------------------------------------------------------- +// [SECTION] Widgets: BeginTabItem, EndTabItem, etc. +//------------------------------------------------------------------------- +// - BeginTabItem() +// - EndTabItem() +// - TabItemButton() +// - TabItemEx() [Internal] +// - SetTabItemClosed() +// - TabItemCalcSize() [Internal] +// - TabItemBackground() [Internal] +// - TabItemLabelAndCloseButton() [Internal] +//------------------------------------------------------------------------- + +bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + if (tab_bar == NULL) + { + IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!"); + return false; + } + IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! + + bool ret = TabItemEx(tab_bar, label, p_open, flags, NULL); + if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; + PushOverrideID(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label) + } + return ret; +} + +void ImGui::EndTabItem() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + if (tab_bar == NULL) + { + IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); + return; + } + IM_ASSERT(tab_bar->LastTabItemIdx >= 0); + ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; + if (!(tab->Flags & ImGuiTabItemFlags_NoPushId)) + PopID(); +} + +bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + if (tab_bar == NULL) + { + IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); + return false; + } + return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder, NULL); +} + +bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window) +{ + // Layout whole tab bar if not already done + if (tab_bar->WantLayout) + TabBarLayout(tab_bar); + + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + const ImGuiStyle& style = g.Style; + const ImGuiID id = TabBarCalcTabID(tab_bar, label, docked_window); + + // If the user called us with *p_open == false, we early out and don't render. + // We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); + if (p_open && !*p_open) + { + ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus); + return false; + } + + IM_ASSERT(!p_open || !(flags & ImGuiTabItemFlags_Button)); + IM_ASSERT((flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) != (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)); // Can't use both Leading and Trailing + + // Store into ImGuiTabItemFlags_NoCloseButton, also honor ImGuiTabItemFlags_NoCloseButton passed by user (although not documented) + if (flags & ImGuiTabItemFlags_NoCloseButton) + p_open = NULL; + else if (p_open == NULL) + flags |= ImGuiTabItemFlags_NoCloseButton; + + // Calculate tab contents size + ImVec2 size = TabItemCalcSize(label, p_open != NULL); + + // Acquire tab data + ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, id); + bool tab_is_new = false; + if (tab == NULL) + { + tab_bar->Tabs.push_back(ImGuiTabItem()); + tab = &tab_bar->Tabs.back(); + tab->ID = id; + tab->Width = size.x; + tab_bar->TabsAddedNew = true; + tab_is_new = true; + } + tab_bar->LastTabItemIdx = (ImS16)tab_bar->Tabs.index_from_ptr(tab); + tab->ContentWidth = size.x; + tab->BeginOrder = tab_bar->TabsActiveCount++; + + const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); + const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0; + const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount); + const bool is_tab_button = (flags & ImGuiTabItemFlags_Button) != 0; + tab->LastFrameVisible = g.FrameCount; + tab->Flags = flags; + tab->Window = docked_window; + + // Append name with zero-terminator + // (regular tabs are permitted in a DockNode tab bar, but window tabs not permitted in a non-DockNode tab bar) + if (tab->Window != NULL) + { + IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode); + tab->NameOffset = -1; + } + else + { + IM_ASSERT(tab->Window == NULL); + tab->NameOffset = (ImS32)tab_bar->TabsNames.size(); + tab_bar->TabsNames.append(label, label + strlen(label) + 1); // Append name _with_ the zero-terminator. + } + + // Update selected tab + if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0) + if (!tab_bar_appearing || tab_bar->SelectedTabId == 0) + if (!is_tab_button) + tab_bar->NextSelectedTabId = id; // New tabs gets activated + if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // SetSelected can only be passed on explicit tab bar + if (!is_tab_button) + tab_bar->NextSelectedTabId = id; + + // Lock visibility + // (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!) + bool tab_contents_visible = (tab_bar->VisibleTabId == id); + if (tab_contents_visible) + tab_bar->VisibleTabWasSubmitted = true; + + // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches + if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing && docked_window == NULL) + if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) + tab_contents_visible = true; + + // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted + // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. + if (tab_appearing && (!tab_bar_appearing || tab_is_new)) + { + ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus); + if (is_tab_button) + return false; + return tab_contents_visible; + } + + if (tab_bar->SelectedTabId == id) + tab->LastFrameSelected = g.FrameCount; + + // Backup current layout position + const ImVec2 backup_main_cursor_pos = window->DC.CursorPos; + + // Layout + const bool is_central_section = (tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0; + size.x = tab->Width; + if (is_central_section) + window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(IM_FLOOR(tab->Offset - tab_bar->ScrollingAnim), 0.0f); + else + window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(tab->Offset, 0.0f); + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, pos + size); + + // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) + const bool want_clip_rect = is_central_section && (bb.Min.x < tab_bar->ScrollingRectMinX || bb.Max.x > tab_bar->ScrollingRectMaxX); + if (want_clip_rect) + PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->ScrollingRectMinX), bb.Min.y - 1), ImVec2(tab_bar->ScrollingRectMaxX, bb.Max.y), true); + + ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos; + ItemSize(bb.GetSize(), style.FramePadding.y); + window->DC.CursorMaxPos = backup_cursor_max_pos; + + if (!ItemAdd(bb, id)) + { + if (want_clip_rect) + PopClipRect(); + window->DC.CursorPos = backup_main_cursor_pos; + return tab_contents_visible; + } + + // Click to Select a tab + ImGuiButtonFlags button_flags = ((is_tab_button ? ImGuiButtonFlags_PressedOnClickRelease : ImGuiButtonFlags_PressedOnClick) | ImGuiButtonFlags_AllowItemOverlap); + if (g.DragDropActive && !g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW)) // FIXME: May be an opt-in property of the payload to disable this + button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); + if (pressed && !is_tab_button) + tab_bar->NextSelectedTabId = id; + + // Transfer active id window so the active id is not owned by the dock host (as StartMouseMovingWindow() + // will only do it on the drag). This allows FocusWindow() to be more conservative in how it clears active id. + if (held && docked_window && g.ActiveId == id && g.ActiveIdIsJustActivated) + g.ActiveIdWindow = docked_window; + + // Allow the close button to overlap unless we are dragging (in which case we don't want any overlapping tabs to be hovered) + if (g.ActiveId != id) + SetItemAllowOverlap(); + + // Drag and drop a single floating window node moves it + ImGuiDockNode* node = docked_window ? docked_window->DockNode : NULL; + const bool single_floating_window_node = node && node->IsFloatingNode() && (node->Windows.Size == 1); + if (held && single_floating_window_node && IsMouseDragging(0, 0.0f)) + { + // Move + StartMouseMovingWindow(docked_window); + } + else if (held && !tab_appearing && IsMouseDragging(0)) + { + // Drag and drop: re-order tabs + int drag_dir = 0; + float drag_distance_from_edge_x = 0.0f; + if (!g.DragDropActive && ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (docked_window != NULL))) + { + // While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x + if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x) + { + drag_dir = -1; + drag_distance_from_edge_x = bb.Min.x - g.IO.MousePos.x; + TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos); + } + else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x) + { + drag_dir = +1; + drag_distance_from_edge_x = g.IO.MousePos.x - bb.Max.x; + TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos); + } + } + + // Extract a Dockable window out of it's tab bar + if (docked_window != NULL && !(docked_window->Flags & ImGuiWindowFlags_NoMove)) + { + // We use a variable threshold to distinguish dragging tabs within a tab bar and extracting them out of the tab bar + bool undocking_tab = (g.DragDropActive && g.DragDropPayload.SourceId == id); + if (!undocking_tab) //&& (!g.IO.ConfigDockingWithShift || g.IO.KeyShift) + { + float threshold_base = g.FontSize; + float threshold_x = (threshold_base * 2.2f); + float threshold_y = (threshold_base * 1.5f) + ImClamp((ImFabs(g.IO.MouseDragMaxDistanceAbs[0].x) - threshold_base * 2.0f) * 0.20f, 0.0f, threshold_base * 4.0f); + //GetForegroundDrawList()->AddRect(ImVec2(bb.Min.x - threshold_x, bb.Min.y - threshold_y), ImVec2(bb.Max.x + threshold_x, bb.Max.y + threshold_y), IM_COL32_WHITE); // [DEBUG] + + float distance_from_edge_y = ImMax(bb.Min.y - g.IO.MousePos.y, g.IO.MousePos.y - bb.Max.y); + if (distance_from_edge_y >= threshold_y) + undocking_tab = true; + if (drag_distance_from_edge_x > threshold_x) + if ((drag_dir < 0 && tab_bar->GetTabOrder(tab) == 0) || (drag_dir > 0 && tab_bar->GetTabOrder(tab) == tab_bar->Tabs.Size - 1)) + undocking_tab = true; + } + + if (undocking_tab) + { + // Undock + // FIXME: refactor to share more code with e.g. StartMouseMovingWindow + DockContextQueueUndockWindow(&g, docked_window); + g.MovingWindow = docked_window; + SetActiveID(g.MovingWindow->MoveId, g.MovingWindow); + g.ActiveIdClickOffset -= g.MovingWindow->Pos - bb.Min; + g.ActiveIdNoClearOnFocusLoss = true; + SetActiveIdUsingNavAndKeys(); + } + } + } + +#if 0 + if (hovered && g.HoveredIdNotActiveTimer > TOOLTIP_DELAY && bb.GetWidth() < tab->ContentWidth) + { + // Enlarge tab display when hovering + bb.Max.x = bb.Min.x + IM_FLOOR(ImLerp(bb.GetWidth(), tab->ContentWidth, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f))); + display_draw_list = GetForegroundDrawList(window); + TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive)); + } +#endif + + // Render tab shape + ImDrawList* display_draw_list = window->DrawList; + const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabUnfocused)); + TabItemBackground(display_draw_list, bb, flags, tab_col); + RenderNavHighlight(bb, id); + + // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. + const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); + if (hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1))) + if (!is_tab_button) + tab_bar->NextSelectedTabId = id; + + if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) + flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; + + // Render tab label, process close button + const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, docked_window ? docked_window->ID : id) : 0; + bool just_closed; + bool text_clipped; + TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible, &just_closed, &text_clipped); + if (just_closed && p_open != NULL) + { + *p_open = false; + TabBarCloseTab(tab_bar, tab); + } + + // Forward Hovered state so IsItemHovered() after Begin() can work (even though we are technically hovering our parent) + // That state is copied to window->DockTabItemStatusFlags by our caller. + if (docked_window && (hovered || g.HoveredId == close_button_id)) + g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow; + + // Restore main window position so user can draw there + if (want_clip_rect) + PopClipRect(); + window->DC.CursorPos = backup_main_cursor_pos; + + // Tooltip + // (Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer-> seems ok) + // (We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar, which g.HoveredId ignores) + // FIXME: This is a mess. + // FIXME: We may want disabled tab to still display the tooltip? + if (text_clipped && g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > g.TooltipSlowDelay && IsItemHovered()) + if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip)) + SetTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label); + + IM_ASSERT(!is_tab_button || !(tab_bar->SelectedTabId == tab->ID && is_tab_button)); // TabItemButton should not be selected + if (is_tab_button) + return pressed; + return tab_contents_visible; +} + +// [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. +// To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar(). +// Tabs closed by the close button will automatically be flagged to avoid this issue. +void ImGui::SetTabItemClosed(const char* label) +{ + ImGuiContext& g = *GImGui; + bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode); + if (is_within_manual_tab_bar) + { + ImGuiTabBar* tab_bar = g.CurrentTabBar; + ImGuiID tab_id = TabBarCalcTabID(tab_bar, label, NULL); + if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) + tab->WantClose = true; // Will be processed by next call to TabBarLayout() + } + else if (ImGuiWindow* window = FindWindowByName(label)) + { + if (window->DockIsActive) + if (ImGuiDockNode* node = window->DockNode) + { + ImGuiID tab_id = TabBarCalcTabID(node->TabBar, label, window); + TabBarRemoveTab(node->TabBar, tab_id); + window->DockTabWantClose = true; + } + } +} + +ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button) +{ + ImGuiContext& g = *GImGui; + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f); + if (has_close_button) + size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle. + else + size.x += g.Style.FramePadding.x + 1.0f; + return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y); +} + +void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col) +{ + // While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it. + ImGuiContext& g = *GImGui; + const float width = bb.GetWidth(); + IM_UNUSED(flags); + IM_ASSERT(width > 0.0f); + const float rounding = ImMax(0.0f, ImMin((flags & ImGuiTabItemFlags_Button) ? g.Style.FrameRounding : g.Style.TabRounding, width * 0.5f - 1.0f)); + const float y1 = bb.Min.y + 1.0f; + const float y2 = bb.Max.y + ((flags & ImGuiTabItemFlags_Preview) ? 0.0f : -1.0f); + draw_list->PathLineTo(ImVec2(bb.Min.x, y2)); + draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9); + draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12); + draw_list->PathLineTo(ImVec2(bb.Max.x, y2)); + draw_list->PathFillConvex(col); + if (g.Style.TabBorderSize > 0.0f) + { + draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2)); + draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9); + draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12); + draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2)); + draw_list->PathStroke(GetColorU32(ImGuiCol_Border), 0, g.Style.TabBorderSize); + } +} + +// Render text label (with custom clipping) + Unsaved Document marker + Close Button logic +// We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. +void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped) +{ + ImGuiContext& g = *GImGui; + ImVec2 label_size = CalcTextSize(label, NULL, true); + + if (out_just_closed) + *out_just_closed = false; + if (out_text_clipped) + *out_text_clipped = false; + + if (bb.GetWidth() <= 1.0f) + return; + + // In Style V2 we'll have full override of all colors per state (e.g. focused, selected) + // But right now if you want to alter text color of tabs this is what you need to do. +#if 0 + const float backup_alpha = g.Style.Alpha; + if (!is_contents_visible) + g.Style.Alpha *= 0.7f; +#endif + + // Render text label (with clipping + alpha gradient) + unsaved marker + ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y); + ImRect text_ellipsis_clip_bb = text_pixel_clip_bb; + + // Return clipped state ignoring the close button + if (out_text_clipped) + { + *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_pixel_clip_bb.Max.x; + //draw_list->AddCircle(text_ellipsis_clip_bb.Min, 3.0f, *out_text_clipped ? IM_COL32(255, 0, 0, 255) : IM_COL32(0, 255, 0, 255)); + } + + const float button_sz = g.FontSize; + const ImVec2 button_pos(ImMax(bb.Min.x, bb.Max.x - frame_padding.x * 2.0f - button_sz), bb.Min.y); + + // Close Button & Unsaved Marker + // We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap() + // 'hovered' will be true when hovering the Tab but NOT when hovering the close button + // 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button + // 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false + bool close_button_pressed = false; + bool close_button_visible = false; + if (close_button_id != 0) + if (is_contents_visible || bb.GetWidth() >= ImMax(button_sz, g.Style.TabMinWidthForCloseButton)) + if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id) + close_button_visible = true; + bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x); + + if (close_button_visible) + { + ImGuiLastItemData last_item_backup = g.LastItemData; + PushStyleVar(ImGuiStyleVar_FramePadding, frame_padding); + if (CloseButton(close_button_id, button_pos)) + close_button_pressed = true; + PopStyleVar(); + g.LastItemData = last_item_backup; + + // Close with middle mouse button + if (!(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2)) + close_button_pressed = true; + } + else if (unsaved_marker_visible) + { + const ImRect bullet_bb(button_pos, button_pos + ImVec2(button_sz, button_sz) + g.Style.FramePadding * 2.0f); + RenderBullet(draw_list, bullet_bb.GetCenter(), GetColorU32(ImGuiCol_Text)); + } + + // This is all rather complicated + // (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position) + // FIXME: if FramePadding is noticeably large, ellipsis_max_x will be wrong here (e.g. #3497), maybe for consistency that parameter of RenderTextEllipsis() shouldn't exist.. + float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f; + if (close_button_visible || unsaved_marker_visible) + { + text_pixel_clip_bb.Max.x -= close_button_visible ? (button_sz) : (button_sz * 0.80f); + text_ellipsis_clip_bb.Max.x -= unsaved_marker_visible ? (button_sz * 0.80f) : 0.0f; + ellipsis_max_x = text_pixel_clip_bb.Max.x; + } + RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size); + +#if 0 + if (!is_contents_visible) + g.Style.Alpha = backup_alpha; +#endif + + if (out_just_closed) + *out_just_closed = close_button_pressed; +} + + +#endif // #ifndef IMGUI_DISABLE diff --git a/src/editors/xrEUI/imstb_rectpack.h b/src/editors/xrEUI/imstb_rectpack.h new file mode 100644 index 00000000000..2ac5e2d1af7 --- /dev/null +++ b/src/editors/xrEUI/imstb_rectpack.h @@ -0,0 +1,662 @@ +// [DEAR IMGUI] +// This is a slightly modified version of stb_rect_pack.h 1.01. +// Grep for [DEAR IMGUI] to find the changes. +// +// stb_rect_pack.h - v1.01 - public domain - rectangle packing +// Sean Barrett 2014 +// +// Useful for e.g. packing rectangular textures into an atlas. +// Does not do rotation. +// +// Before #including, +// +// #define STB_RECT_PACK_IMPLEMENTATION +// +// in the file that you want to have the implementation. +// +// Not necessarily the awesomest packing method, but better than +// the totally naive one in stb_truetype (which is primarily what +// this is meant to replace). +// +// Has only had a few tests run, may have issues. +// +// More docs to come. +// +// No memory allocations; uses qsort() and assert() from stdlib. +// Can override those by defining STBRP_SORT and STBRP_ASSERT. +// +// This library currently uses the Skyline Bottom-Left algorithm. +// +// Please note: better rectangle packers are welcome! Please +// implement them to the same API, but with a different init +// function. +// +// Credits +// +// Library +// Sean Barrett +// Minor features +// Martins Mozeiko +// github:IntellectualKitty +// +// Bugfixes / warning fixes +// Jeremy Jaussaud +// Fabian Giesen +// +// Version history: +// +// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section +// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles +// 0.99 (2019-02-07) warning fixes +// 0.11 (2017-03-03) return packing success/fail result +// 0.10 (2016-10-25) remove cast-away-const to avoid warnings +// 0.09 (2016-08-27) fix compiler warnings +// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) +// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) +// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort +// 0.05: added STBRP_ASSERT to allow replacing assert +// 0.04: fixed minor bug in STBRP_LARGE_RECTS support +// 0.01: initial release +// +// LICENSE +// +// See end of file for license information. + +////////////////////////////////////////////////////////////////////////////// +// +// INCLUDE SECTION +// + +#ifndef STB_INCLUDE_STB_RECT_PACK_H +#define STB_INCLUDE_STB_RECT_PACK_H + +#define STB_RECT_PACK_VERSION 1 + +#ifdef STBRP_STATIC +#define STBRP_DEF static +#else +#define STBRP_DEF extern +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + + typedef struct stbrp_context stbrp_context; + typedef struct stbrp_node stbrp_node; + typedef struct stbrp_rect stbrp_rect; + + typedef int stbrp_coord; + +#define STBRP__MAXVAL 0x7fffffff + // Mostly for internal use, but this is the maximum supported coordinate value. + + STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects); + // Assign packed locations to rectangles. The rectangles are of type + // 'stbrp_rect' defined below, stored in the array 'rects', and there + // are 'num_rects' many of them. + // + // Rectangles which are successfully packed have the 'was_packed' flag + // set to a non-zero value and 'x' and 'y' store the minimum location + // on each axis (i.e. bottom-left in cartesian coordinates, top-left + // if you imagine y increasing downwards). Rectangles which do not fit + // have the 'was_packed' flag set to 0. + // + // You should not try to access the 'rects' array from another thread + // while this function is running, as the function temporarily reorders + // the array while it executes. + // + // To pack into another rectangle, you need to call stbrp_init_target + // again. To continue packing into the same rectangle, you can call + // this function again. Calling this multiple times with multiple rect + // arrays will probably produce worse packing results than calling it + // a single time with the full rectangle array, but the option is + // available. + // + // The function returns 1 if all of the rectangles were successfully + // packed and 0 otherwise. + + struct stbrp_rect + { + // reserved for your use: + int id; + + // input: + stbrp_coord w, h; + + // output: + stbrp_coord x, y; + int was_packed; // non-zero if valid packing + + }; // 16 bytes, nominally + + STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes); + // Initialize a rectangle packer to: + // pack a rectangle that is 'width' by 'height' in dimensions + // using temporary storage provided by the array 'nodes', which is 'num_nodes' long + // + // You must call this function every time you start packing into a new target. + // + // There is no "shutdown" function. The 'nodes' memory must stay valid for + // the following stbrp_pack_rects() call (or calls), but can be freed after + // the call (or calls) finish. + // + // Note: to guarantee best results, either: + // 1. make sure 'num_nodes' >= 'width' + // or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1' + // + // If you don't do either of the above things, widths will be quantized to multiples + // of small integers to guarantee the algorithm doesn't run out of temporary storage. + // + // If you do #2, then the non-quantized algorithm will be used, but the algorithm + // may run out of temporary storage and be unable to pack some rectangles. + + STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem); + // Optionally call this function after init but before doing any packing to + // change the handling of the out-of-temp-memory scenario, described above. + // If you call init again, this will be reset to the default (false). + + STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic); + // Optionally select which packing heuristic the library should use. Different + // heuristics will produce better/worse results for different data sets. + // If you call init again, this will be reset to the default. + + enum + { + STBRP_HEURISTIC_Skyline_default = 0, + STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default, + STBRP_HEURISTIC_Skyline_BF_sortHeight + }; + + ////////////////////////////////////////////////////////////////////////////// + // + // the details of the following structures don't matter to you, but they must + // be visible so you can handle the memory allocations for them + + struct stbrp_node + { + stbrp_coord x, y; + stbrp_node *next; + }; + + struct stbrp_context + { + int width; + int height; + int align; + int init_mode; + int heuristic; + int num_nodes; + stbrp_node *active_head; + stbrp_node *free_head; + stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' + }; + +#ifdef __cplusplus +} +#endif + +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// IMPLEMENTATION SECTION +// + +#ifdef STB_RECT_PACK_IMPLEMENTATION +#ifndef STBRP_SORT +#include +#define STBRP_SORT qsort +#endif + +#ifndef STBRP_ASSERT +#include +#define STBRP_ASSERT assert +#endif + +#ifdef _MSC_VER +#define STBRP__NOTUSED(v) (void)(v) +#define STBRP__CDECL __cdecl +#else +#define STBRP__NOTUSED(v) (void)sizeof(v) +#define STBRP__CDECL +#endif + +enum +{ + STBRP__INIT_skyline = 1 +}; + +STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic) +{ + switch (context->init_mode) + { + case STBRP__INIT_skyline: + STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight); + context->heuristic = heuristic; + break; + default: + STBRP_ASSERT(0); + } +} + +STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem) +{ + if (allow_out_of_mem) + // if it's ok to run out of memory, then don't bother aligning them; + // this gives better packing, but may fail due to OOM (even though + // the rectangles easily fit). @TODO a smarter approach would be to only + // quantize once we've hit OOM, then we could get rid of this parameter. + context->align = 1; + else + { + // if it's not ok to run out of memory, then quantize the widths + // so that num_nodes is always enough nodes. + // + // I.e. num_nodes * align >= width + // align >= width / num_nodes + // align = ceil(width/num_nodes) + + context->align = (context->width + context->num_nodes - 1) / context->num_nodes; + } +} + +STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes) +{ + int i; + + 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; + context->extra[1].y = (1 << 30); + context->extra[1].next = NULL; +} + +// find minimum y position if it starts at x1 +static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) +{ + stbrp_node *node = first; + int x1 = x0 + width; + int min_y, visited_width, waste_area; + + STBRP__NOTUSED(c); + + STBRP_ASSERT(first->x <= x0); + +#if 0 + // skip in case we're past the node + while (node->next->x <= x0) + ++node; +#else + STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency +#endif + + STBRP_ASSERT(node->x <= x0); + + min_y = 0; + waste_area = 0; + visited_width = 0; + while (node->x < x1) + { + if (node->y > min_y) + { + // raise min_y higher. + // we've accounted for all waste up to min_y, + // but we'll now add more waste for everything we've visted + waste_area += visited_width * (node->y - min_y); + min_y = node->y; + // the first time through, visited_width might be reduced + if (node->x < x0) + visited_width += node->next->x - x0; + else + visited_width += node->next->x - node->x; + } + else + { + // add waste area + int under_width = node->next->x - node->x; + if (under_width + visited_width > width) + under_width = width - visited_width; + waste_area += under_width * (min_y - node->y); + visited_width += under_width; + } + node = node->next; + } + + *pwaste = waste_area; + return min_y; +} + +typedef struct +{ + int x, y; + stbrp_node **prev_link; +} stbrp__findresult; + +static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height) +{ + int best_waste = (1 << 30), best_x, best_y = (1 << 30); + stbrp__findresult fr; + stbrp_node **prev, *node, *tail, **best = NULL; + + // align to multiple of c->align + width = (width + c->align - 1); + width -= width % c->align; + STBRP_ASSERT(width % c->align == 0); + + // if it can't possibly fit, bail immediately + if (width > c->width || height > c->height) + { + fr.prev_link = NULL; + fr.x = fr.y = 0; + return fr; + } + + 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); [DEAR IMGUI] + best_y = y; + best_waste = waste; + best = prev; + } + } + } + tail = tail->next; + } + } + + fr.prev_link = best; + fr.x = best_x; + fr.y = best_y; + return fr; +} + +static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height) +{ + // find best position according to heuristic + stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height); + stbrp_node *node, *cur; + + // bail if: + // 1. it failed + // 2. the best node doesn't fit (we don't always check this) + // 3. we're out of memory + if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) + { + res.prev_link = NULL; + return res; + } + + // on success, create new node + node = context->free_head; + node->x = (stbrp_coord)res.x; + node->y = (stbrp_coord)(res.y + height); + + context->free_head = node->next; + + // insert the new node into the right starting point, and + // let 'cur' point to the remaining nodes needing to be + // stiched back in + + cur = *res.prev_link; + if (cur->x < res.x) + { + // preserve the existing one, so start testing with the next one + stbrp_node *next = cur->next; + cur->next = node; + cur = next; + } + else + { + *res.prev_link = node; + } + + // from here, traverse cur and free the nodes, until we get to one + // that shouldn't be freed + while (cur->next && cur->next->x <= res.x + width) + { + stbrp_node *next = cur->next; + // move the current node to the free list + cur->next = context->free_head; + context->free_head = cur; + cur = next; + } + + // stitch the list back in + node->next = cur; + + if (cur->x < res.x + width) + cur->x = (stbrp_coord)(res.x + width); + +#ifdef _DEBUG + cur = context->active_head; + while (cur->x < context->width) + { + STBRP_ASSERT(cur->x < cur->next->x); + cur = cur->next; + } + STBRP_ASSERT(cur->next == NULL); + + { + int count = 0; + cur = context->active_head; + while (cur) + { + cur = cur->next; + ++count; + } + cur = context->free_head; + while (cur) + { + cur = cur->next; + ++count; + } + STBRP_ASSERT(count == context->num_nodes + 2); + } +#endif + + return res; +} + +static int STBRP__CDECL rect_height_compare(const void *a, const void *b) +{ + const stbrp_rect *p = (const stbrp_rect *)a; + const stbrp_rect *q = (const stbrp_rect *)b; + if (p->h > q->h) + return -1; + if (p->h < q->h) + return 1; + return (p->w > q->w) ? -1 : (p->w < q->w); +} + +static int STBRP__CDECL rect_original_order(const void *a, const void *b) +{ + const stbrp_rect *p = (const stbrp_rect *)a; + const stbrp_rect *q = (const stbrp_rect *)b; + return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); +} + +STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects) +{ + int i, all_rects_packed = 1; + + // we use the 'was_packed' field internally to allow sorting/unsorting + for (i = 0; i < num_rects; ++i) + { + rects[i].was_packed = i; + } + + // sort according to heuristic + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); + + for (i = 0; i < num_rects; ++i) + { + if (rects[i].w == 0 || rects[i].h == 0) + { + rects[i].x = rects[i].y = 0; // empty rect needs no space + } + else + { + stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); + if (fr.prev_link) + { + rects[i].x = (stbrp_coord)fr.x; + rects[i].y = (stbrp_coord)fr.y; + } + else + { + rects[i].x = rects[i].y = STBRP__MAXVAL; + } + } + } + + // unsort + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); + + // set was_packed flags and all_rects_packed status + for (i = 0; i < num_rects; ++i) + { + rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL); + if (!rects[i].was_packed) + all_rects_packed = 0; + } + + // return the all_rects_packed status + return all_rects_packed; +} +#endif + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/src/editors/xrEUI/imstb_textedit.h b/src/editors/xrEUI/imstb_textedit.h new file mode 100644 index 00000000000..75a159dac73 --- /dev/null +++ b/src/editors/xrEUI/imstb_textedit.h @@ -0,0 +1,1447 @@ +// [DEAR IMGUI] +// This is a slightly modified version of stb_textedit.h 1.14. +// Those changes would need to be pushed into nothings/stb: +// - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) +// Grep for [DEAR IMGUI] to find the changes. + +// stb_textedit.h - v1.14 - public domain - Sean Barrett +// Development of this library was sponsored by RAD Game Tools +// +// This C header file implements the guts of a multi-line text-editing +// widget; you implement display, word-wrapping, and low-level string +// insertion/deletion, and stb_textedit will map user inputs into +// insertions & deletions, plus updates to the cursor position, +// selection state, and undo state. +// +// It is intended for use in games and other systems that need to build +// their own custom widgets and which do not have heavy text-editing +// requirements (this library is not recommended for use for editing large +// texts, as its performance does not scale and it has limited undo). +// +// Non-trivial behaviors are modelled after Windows text controls. +// +// +// LICENSE +// +// See end of file for license information. +// +// +// DEPENDENCIES +// +// Uses the C runtime function 'memmove', which you can override +// by defining STB_TEXTEDIT_memmove before the implementation. +// Uses no other functions. Performs no runtime allocations. +// +// +// VERSION HISTORY +// +// 1.14 (2021-07-11) page up/down, various fixes +// 1.13 (2019-02-07) fix bug in undo size management +// 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash +// 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield +// 1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual +// 1.9 (2016-08-27) customizable move-by-word +// 1.8 (2016-04-02) better keyboard handling when mouse button is down +// 1.7 (2015-09-13) change y range handling in case baseline is non-0 +// 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove +// 1.5 (2014-09-10) add support for secondary keys for OS X +// 1.4 (2014-08-17) fix signed/unsigned warnings +// 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary +// 1.2 (2014-05-27) fix some RAD types that had crept into the new code +// 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) +// 1.0 (2012-07-26) improve documentation, initial public release +// 0.3 (2012-02-24) bugfixes, single-line mode; insert mode +// 0.2 (2011-11-28) fixes to undo/redo +// 0.1 (2010-07-08) initial version +// +// ADDITIONAL CONTRIBUTORS +// +// Ulf Winklemann: move-by-word in 1.1 +// Fabian Giesen: secondary key inputs in 1.5 +// Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6 +// Louis Schnellbach: page up/down in 1.14 +// +// Bugfixes: +// Scott Graham +// Daniel Keller +// Omar Cornut +// Dan Thompson +// +// USAGE +// +// This file behaves differently depending on what symbols you define +// before including it. +// +// +// Header-file mode: +// +// If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this, +// it will operate in "header file" mode. In this mode, it declares a +// single public symbol, STB_TexteditState, which encapsulates the current +// state of a text widget (except for the string, which you will store +// separately). +// +// To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a +// primitive type that defines a single character (e.g. char, wchar_t, etc). +// +// To save space or increase undo-ability, you can optionally define the +// following things that are used by the undo system: +// +// STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position +// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow +// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer +// +// If you don't define these, they are set to permissive types and +// moderate sizes. The undo system does no memory allocations, so +// it grows STB_TexteditState by the worst-case storage which is (in bytes): +// +// [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATECOUNT +// + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHARCOUNT +// +// +// Implementation mode: +// +// If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it +// will compile the implementation of the text edit widget, depending +// on a large number of symbols which must be defined before the include. +// +// The implementation is defined only as static functions. You will then +// need to provide your own APIs in the same file which will access the +// static functions. +// +// The basic concept is that you provide a "string" object which +// behaves like an array of characters. stb_textedit uses indices to +// refer to positions in the string, implicitly representing positions +// in the displayed textedit. This is true for both plain text and +// rich text; even with rich text stb_truetype interacts with your +// code as if there was an array of all the displayed characters. +// +// Symbols that must be the same in header-file and implementation mode: +// +// STB_TEXTEDIT_CHARTYPE the character type +// STB_TEXTEDIT_POSITIONTYPE small type that is a valid cursor position +// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow +// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer +// +// Symbols you must define for implementation mode: +// +// STB_TEXTEDIT_STRING the type of object representing a string being edited, +// typically this is a wrapper object with other data you need +// +// STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) +// STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters +// starting from character #n (see discussion below) +// STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character +// to the xpos of the i+1'th char for a line of characters +// starting at character #n (i.e. accounts for kerning +// with previous char) +// STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character +// (return type is int, -1 means not valid to insert) +// STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based +// STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize +// as manually wordwrapping for end-of-line positioning +// +// STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i +// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) +// +// STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key +// +// STB_TEXTEDIT_K_LEFT keyboard input to move cursor left +// STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right +// STB_TEXTEDIT_K_UP keyboard input to move cursor up +// STB_TEXTEDIT_K_DOWN keyboard input to move cursor down +// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page +// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page +// STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME +// STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END +// STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME +// STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END +// STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor +// STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor +// STB_TEXTEDIT_K_UNDO keyboard input to perform undo +// STB_TEXTEDIT_K_REDO keyboard input to perform redo +// +// Optional: +// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode +// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), +// required for default WORDLEFT/WORDRIGHT handlers +// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to +// STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to +// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT +// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line +// STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line +// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text +// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text +// +// Keyboard input must be encoded as a single integer value; e.g. a character code +// and some bitflags that represent shift states. to simplify the interface, SHIFT must +// be a bitflag, so we can test the shifted state of cursor movements to allow selection, +// i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. +// +// You can encode other things, such as CONTROL or ALT, in additional bits, and +// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, +// my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN +// bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit, +// and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the +// API below. The control keys will only match WM_KEYDOWN events because of the +// keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN +// bit so it only decodes WM_CHAR events. +// +// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed +// row of characters assuming they start on the i'th character--the width and +// the height and the number of characters consumed. This allows this library +// to traverse the entire layout incrementally. You need to compute word-wrapping +// here. +// +// Each textfield keeps its own insert mode state, which is not how normal +// applications work. To keep an app-wide insert mode, update/copy the +// "insert_mode" field of STB_TexteditState before/after calling API functions. +// +// API +// +// void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) +// +// void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +// void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +// int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +// int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) +// void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key) +// +// Each of these functions potentially updates the string and updates the +// state. +// +// initialize_state: +// set the textedit state to a known good default state when initially +// constructing the textedit. +// +// click: +// call this with the mouse x,y on a mouse down; it will update the cursor +// and reset the selection start/end to the cursor point. the x,y must +// be relative to the text widget, with (0,0) being the top left. +// +// drag: +// call this with the mouse x,y on a mouse drag/up; it will update the +// cursor and the selection end point +// +// cut: +// call this to delete the current selection; returns true if there was +// one. you should FIRST copy the current selection to the system paste buffer. +// (To copy, just copy the current selection out of the string yourself.) +// +// paste: +// call this to paste text at the current cursor point or over the current +// selection if there is one. +// +// key: +// call this for keyboard inputs sent to the textfield. you can use it +// for "key down" events or for "translated" key events. if you need to +// do both (as in Win32), or distinguish Unicode characters from control +// inputs, set a high bit to distinguish the two; then you can define the +// various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit +// set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is +// clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to +// anything other type you wante before including. +// +// +// When rendering, you can read the cursor position and selection state from +// the STB_TexteditState. +// +// +// Notes: +// +// This is designed to be usable in IMGUI, so it allows for the possibility of +// running in an IMGUI that has NOT cached the multi-line layout. For this +// reason, it provides an interface that is compatible with computing the +// layout incrementally--we try to make sure we make as few passes through +// as possible. (For example, to locate the mouse pointer in the text, we +// could define functions that return the X and Y positions of characters +// and binary search Y and then X, but if we're doing dynamic layout this +// will run the layout algorithm many times, so instead we manually search +// forward in one pass. Similar logic applies to e.g. up-arrow and +// down-arrow movement.) +// +// If it's run in a widget that *has* cached the layout, then this is less +// efficient, but it's not horrible on modern computers. But you wouldn't +// want to edit million-line files with it. + + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Header-file mode +//// +//// + +#ifndef INCLUDE_STB_TEXTEDIT_H +#define INCLUDE_STB_TEXTEDIT_H + +//////////////////////////////////////////////////////////////////////// +// +// STB_TexteditState +// +// Definition of STB_TexteditState which you should store +// per-textfield; it includes cursor position, selection state, +// and undo state. +// + +#ifndef STB_TEXTEDIT_UNDOSTATECOUNT +#define STB_TEXTEDIT_UNDOSTATECOUNT 99 +#endif +#ifndef STB_TEXTEDIT_UNDOCHARCOUNT +#define STB_TEXTEDIT_UNDOCHARCOUNT 999 +#endif +#ifndef STB_TEXTEDIT_CHARTYPE +#define STB_TEXTEDIT_CHARTYPE int +#endif +#ifndef STB_TEXTEDIT_POSITIONTYPE +#define STB_TEXTEDIT_POSITIONTYPE int +#endif + +typedef struct +{ + // private data + STB_TEXTEDIT_POSITIONTYPE where; + STB_TEXTEDIT_POSITIONTYPE insert_length; + STB_TEXTEDIT_POSITIONTYPE delete_length; + int char_storage; +} StbUndoRecord; + +typedef struct +{ + // private data + StbUndoRecord undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT]; + STB_TEXTEDIT_CHARTYPE undo_char[STB_TEXTEDIT_UNDOCHARCOUNT]; + short undo_point, redo_point; + int undo_char_point, redo_char_point; +} StbUndoState; + +typedef struct +{ + ///////////////////// + // + // public data + // + + int cursor; + // position of the text cursor within the string + + int select_start; // selection start point + int select_end; + // selection start and end point in characters; if equal, no selection. + // note that start may be less than or greater than end (e.g. when + // dragging the mouse, start is where the initial click was, and you + // can drag in either direction) + + unsigned char insert_mode; + // each textfield keeps its own insert mode state. to keep an app-wide + // insert mode, copy this value in/out of the app state + + int row_count_per_page; + // page size in number of row. + // this value MUST be set to >0 for pageup or pagedown in multilines documents. + + ///////////////////// + // + // private data + // + unsigned char cursor_at_end_of_line; // not implemented yet + unsigned char initialized; + unsigned char has_preferred_x; + unsigned char single_line; + unsigned char padding1, padding2, padding3; + float preferred_x; // this determines where the cursor up/down tries to seek to along x + StbUndoState undostate; +} STB_TexteditState; + + +//////////////////////////////////////////////////////////////////////// +// +// StbTexteditRow +// +// Result of layout query, used by stb_textedit to determine where +// the text in each row is. + +// result of layout query +typedef struct +{ + float x0,x1; // starting x location, end x location (allows for align=right, etc) + float baseline_y_delta; // position of baseline relative to previous row's baseline + float ymin,ymax; // height of row above and below baseline + int num_chars; +} StbTexteditRow; +#endif //INCLUDE_STB_TEXTEDIT_H + + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Implementation mode +//// +//// + + +// implementation isn't include-guarded, since it might have indirectly +// included just the "header" portion +#ifdef STB_TEXTEDIT_IMPLEMENTATION + +#ifndef STB_TEXTEDIT_memmove +#include +#define STB_TEXTEDIT_memmove memmove +#endif + + +///////////////////////////////////////////////////////////////////////////// +// +// Mouse input handling +// + +// traverse the layout to locate the nearest character to a display position +static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) +{ + StbTexteditRow r; + int n = STB_TEXTEDIT_STRINGLEN(str); + float base_y = 0, prev_x; + int i=0, k; + + r.x0 = r.x1 = 0; + r.ymin = r.ymax = 0; + r.num_chars = 0; + + // search rows to find one that straddles 'y' + while (i < n) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (r.num_chars <= 0) + return n; + + if (i==0 && y < base_y + r.ymin) + return 0; + + if (y < base_y + r.ymax) + break; + + i += r.num_chars; + base_y += r.baseline_y_delta; + } + + // below all text, return 'after' last character + if (i >= n) + return n; + + // check if it's before the beginning of the line + if (x < r.x0) + return i; + + // check if it's before the end of the line + if (x < r.x1) { + // search characters in row for one that straddles 'x' + prev_x = r.x0; + for (k=0; k < r.num_chars; ++k) { + float w = STB_TEXTEDIT_GETWIDTH(str, i, k); + if (x < prev_x+w) { + if (x < prev_x+w/2) + return k+i; + else + return k+i+1; + } + prev_x += w; + } + // shouldn't happen, but if it does, fall through to end-of-line case + } + + // if the last character is a newline, return that. otherwise return 'after' the last character + if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE) + return i+r.num_chars-1; + else + return i+r.num_chars; +} + +// API click: on mouse down, move the cursor to the clicked location, and reset the selection +static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +{ + // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse + // goes off the top or bottom of the text + if( state->single_line ) + { + StbTexteditRow r; + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + y = r.ymin; + } + + state->cursor = stb_text_locate_coord(str, x, y); + state->select_start = state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; +} + +// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location +static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +{ + int p = 0; + + // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse + // goes off the top or bottom of the text + if( state->single_line ) + { + StbTexteditRow r; + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + y = r.ymin; + } + + if (state->select_start == state->select_end) + state->select_start = state->cursor; + + p = stb_text_locate_coord(str, x, y); + state->cursor = state->select_end = p; +} + +///////////////////////////////////////////////////////////////////////////// +// +// Keyboard input handling +// + +// forward declarations +static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length); +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length); +static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length); + +typedef struct +{ + float x,y; // position of n'th character + float height; // height of line + int first_char, length; // first char of row, and length + int prev_first; // first char of previous row +} StbFindState; + +// find the x/y location of a character, and remember info about the previous row in +// case we get a move-up event (for page up, we'll have to rescan) +static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line) +{ + StbTexteditRow r; + int prev_start = 0; + int z = STB_TEXTEDIT_STRINGLEN(str); + int i=0, first; + + if (n == z) { + // if it's at the end, then find the last line -- simpler than trying to + // explicitly handle this case in the regular code + if (single_line) { + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + find->y = 0; + find->first_char = 0; + find->length = z; + find->height = r.ymax - r.ymin; + find->x = r.x1; + } else { + find->y = 0; + find->x = 0; + find->height = 1; + while (i < z) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + prev_start = i; + i += r.num_chars; + } + find->first_char = i; + find->length = 0; + find->prev_first = prev_start; + } + return; + } + + // search rows to find the one that straddles character n + find->y = 0; + + for(;;) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (n < i + r.num_chars) + break; + prev_start = i; + i += r.num_chars; + find->y += r.baseline_y_delta; + } + + find->first_char = first = i; + find->length = r.num_chars; + find->height = r.ymax - r.ymin; + find->prev_first = prev_start; + + // now scan to find xpos + find->x = r.x0; + for (i=0; first+i < n; ++i) + find->x += STB_TEXTEDIT_GETWIDTH(str, first, i); +} + +#define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) + +// make the selection/cursor state valid if client altered the string +static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + int n = STB_TEXTEDIT_STRINGLEN(str); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start > n) state->select_start = n; + if (state->select_end > n) state->select_end = n; + // if clamping forced them to be equal, move the cursor to match + if (state->select_start == state->select_end) + state->cursor = state->select_start; + } + if (state->cursor > n) state->cursor = n; +} + +// delete characters while updating undo +static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len) +{ + stb_text_makeundo_delete(str, state, where, len); + STB_TEXTEDIT_DELETECHARS(str, where, len); + state->has_preferred_x = 0; +} + +// delete the section +static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + stb_textedit_clamp(str, state); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start < state->select_end) { + stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start); + state->select_end = state->cursor = state->select_start; + } else { + stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end); + state->select_start = state->cursor = state->select_end; + } + state->has_preferred_x = 0; + } +} + +// canoncialize the selection so start <= end +static void stb_textedit_sortselection(STB_TexteditState *state) +{ + if (state->select_end < state->select_start) { + int temp = state->select_end; + state->select_end = state->select_start; + state->select_start = temp; + } +} + +// move cursor to first character of selection +static void stb_textedit_move_to_first(STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + state->cursor = state->select_start; + state->select_end = state->select_start; + state->has_preferred_x = 0; + } +} + +// move cursor to last character of selection +static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->select_start = state->select_end; + state->has_preferred_x = 0; + } +} + +#ifdef STB_TEXTEDIT_IS_SPACE +static int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx ) +{ + return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1; +} + +#ifndef STB_TEXTEDIT_MOVEWORDLEFT +static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c ) +{ + --c; // always move at least one character + while( c >= 0 && !is_word_boundary( str, c ) ) + --c; + + if( c < 0 ) + c = 0; + + return c; +} +#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous +#endif + +#ifndef STB_TEXTEDIT_MOVEWORDRIGHT +static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c ) +{ + const int len = STB_TEXTEDIT_STRINGLEN(str); + ++c; // always move at least one character + while( c < len && !is_word_boundary( str, c ) ) + ++c; + + if( c > len ) + c = len; + + return c; +} +#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next +#endif + +#endif + +// update selection and cursor to match each other +static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) +{ + if (!STB_TEXT_HAS_SELECTION(state)) + state->select_start = state->select_end = state->cursor; + else + state->cursor = state->select_end; +} + +// API cut: delete selection +static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_delete_selection(str,state); // implicitly clamps + state->has_preferred_x = 0; + return 1; + } + return 0; +} + +// API paste: replace existing selection with passed-in text +static int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) +{ + // if there's a selection, the paste should delete it + stb_textedit_clamp(str, state); + stb_textedit_delete_selection(str,state); + // try to insert the characters + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) { + stb_text_makeundo_insert(state, state->cursor, len); + state->cursor += len; + state->has_preferred_x = 0; + return 1; + } + // note: paste failure will leave deleted selection, may be restored with an undo (see https://github.com/nothings/stb/issues/734 for details) + return 0; +} + +#ifndef STB_TEXTEDIT_KEYTYPE +#define STB_TEXTEDIT_KEYTYPE int +#endif + +// API key: process a keyboard input +static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key) +{ +retry: + switch (key) { + default: { + int c = STB_TEXTEDIT_KEYTOTEXT(key); + if (c > 0) { + STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c; + + // can't add newline in single-line mode + if (c == '\n' && state->single_line) + break; + + if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { + stb_text_makeundo_replace(str, state, state->cursor, 1, 1); + STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { + ++state->cursor; + state->has_preferred_x = 0; + } + } else { + stb_textedit_delete_selection(str,state); // implicitly clamps + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { + stb_text_makeundo_insert(state, state->cursor, 1); + ++state->cursor; + state->has_preferred_x = 0; + } + } + } + break; + } + +#ifdef STB_TEXTEDIT_K_INSERT + case STB_TEXTEDIT_K_INSERT: + state->insert_mode = !state->insert_mode; + break; +#endif + + case STB_TEXTEDIT_K_UNDO: + stb_text_undo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_REDO: + stb_text_redo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT: + // if currently there's a selection, move cursor to start of selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else + if (state->cursor > 0) + --state->cursor; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_RIGHT: + // if currently there's a selection, move cursor to end of selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else + ++state->cursor; + stb_textedit_clamp(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + // move selection left + if (state->select_end > 0) + --state->select_end; + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_MOVEWORDLEFT + case STB_TEXTEDIT_K_WORDLEFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); + stb_textedit_clamp( str, state ); + } + break; + + case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT: + if( !STB_TEXT_HAS_SELECTION( state ) ) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); + state->select_end = state->cursor; + + stb_textedit_clamp( str, state ); + break; +#endif + +#ifdef STB_TEXTEDIT_MOVEWORDRIGHT + case STB_TEXTEDIT_K_WORDRIGHT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + stb_textedit_clamp( str, state ); + } + break; + + case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: + if( !STB_TEXT_HAS_SELECTION( state ) ) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + state->select_end = state->cursor; + + stb_textedit_clamp( str, state ); + break; +#endif + + case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + // move selection right + ++state->select_end; + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_DOWN: + case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: + case STB_TEXTEDIT_K_PGDOWN: + case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN; + int row_count = is_page ? state->row_count_per_page : 1; + + if (!is_page && state->single_line) { + // on windows, up&down in single-line behave like left&right + key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + + for (j = 0; j < row_count; ++j) { + float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; + int start = find.first_char + find.length; + + if (find.length == 0) + break; + + // [DEAR IMGUI] + // going down while being on the last line shouldn't bring us to that line end + if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE) + break; + + // now find character position down a row + state->cursor = start; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i=0; i < row.num_chars; ++i) { + float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); + #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) + break; + #endif + x += dx; + if (x > goal_x) + break; + ++state->cursor; + } + stb_textedit_clamp(str, state); + + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + + // go to next line + find.first_char = find.first_char + find.length; + find.length = row.num_chars; + } + break; + } + + case STB_TEXTEDIT_K_UP: + case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: + case STB_TEXTEDIT_K_PGUP: + case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP; + int row_count = is_page ? state->row_count_per_page : 1; + + if (!is_page && state->single_line) { + // on windows, up&down become left&right + key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + + for (j = 0; j < row_count; ++j) { + float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; + + // can only go up if there's a previous row + if (find.prev_first == find.first_char) + break; + + // now find character position up a row + state->cursor = find.prev_first; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i=0; i < row.num_chars; ++i) { + float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); + #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) + break; + #endif + x += dx; + if (x > goal_x) + break; + ++state->cursor; + } + stb_textedit_clamp(str, state); + + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + + // go to previous line + // (we need to scan previous line the hard way. maybe we could expose this as a new API function?) + prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0; + while (prev_scan > 0 && STB_TEXTEDIT_GETCHAR(str, prev_scan - 1) != STB_TEXTEDIT_NEWLINE) + --prev_scan; + find.first_char = find.prev_first; + find.prev_first = prev_scan; + } + break; + } + + case STB_TEXTEDIT_K_DELETE: + case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + int n = STB_TEXTEDIT_STRINGLEN(str); + if (state->cursor < n) + stb_textedit_delete(str, state, state->cursor, 1); + } + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_BACKSPACE: + case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + stb_textedit_clamp(str, state); + if (state->cursor > 0) { + stb_textedit_delete(str, state, state->cursor-1, 1); + --state->cursor; + } + } + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2: +#endif + case STB_TEXTEDIT_K_TEXTSTART: + state->cursor = state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2: +#endif + case STB_TEXTEDIT_K_TEXTEND: + state->cursor = STB_TEXTEDIT_STRINGLEN(str); + state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); + state->has_preferred_x = 0; + break; + + +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2: +#endif + case STB_TEXTEDIT_K_LINESTART: + stb_textedit_clamp(str, state); + stb_textedit_move_to_first(state); + if (state->single_line) + state->cursor = 0; + else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) + --state->cursor; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2: +#endif + case STB_TEXTEDIT_K_LINEEND: { + int n = STB_TEXTEDIT_STRINGLEN(str); + stb_textedit_clamp(str, state); + stb_textedit_move_to_first(state); + if (state->single_line) + state->cursor = n; + else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) + ++state->cursor; + state->has_preferred_x = 0; + break; + } + +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + if (state->single_line) + state->cursor = 0; + else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) + --state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { + int n = STB_TEXTEDIT_STRINGLEN(str); + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + if (state->single_line) + state->cursor = n; + else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) + ++state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; + break; + } + } +} + +///////////////////////////////////////////////////////////////////////////// +// +// Undo processing +// +// @OPTIMIZE: the undo/redo buffer should be circular + +static void stb_textedit_flush_redo(StbUndoState *state) +{ + state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; + state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; +} + +// discard the oldest entry in the undo list +static void stb_textedit_discard_undo(StbUndoState *state) +{ + if (state->undo_point > 0) { + // if the 0th undo state has characters, clean those up + if (state->undo_rec[0].char_storage >= 0) { + int n = state->undo_rec[0].insert_length, i; + // delete n characters from all other records + state->undo_char_point -= n; + STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); + for (i=0; i < state->undo_point; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it + } + --state->undo_point; + STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0]))); + } +} + +// discard the oldest entry in the redo list--it's bad if this +// ever happens, but because undo & redo have to store the actual +// characters in different cases, the redo character buffer can +// fill up even though the undo buffer didn't +static void stb_textedit_discard_redo(StbUndoState *state) +{ + int k = STB_TEXTEDIT_UNDOSTATECOUNT-1; + + if (state->redo_point <= k) { + // if the k'th undo state has characters, clean those up + if (state->undo_rec[k].char_storage >= 0) { + int n = state->undo_rec[k].insert_length, i; + // move the remaining redo character data to the end of the buffer + state->redo_char_point += n; + STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); + // adjust the position of all the other records to account for above memmove + for (i=state->redo_point; i < k; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage += n; + } + // now move all the redo records towards the end of the buffer; the first one is at 'redo_point' + // [DEAR IMGUI] + size_t move_size = (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0])); + const char* buf_begin = (char*)state->undo_rec; (void)buf_begin; + const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end; + IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin); + IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end); + STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size); + + // now move redo_point to point to the new one + ++state->redo_point; + } +} + +static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars) +{ + // any time we create a new undo record, we discard redo + stb_textedit_flush_redo(state); + + // if we have no free records, we have to make room, by sliding the + // existing records down + if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + stb_textedit_discard_undo(state); + + // if the characters to store won't possibly fit in the buffer, we can't undo + if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) { + state->undo_point = 0; + state->undo_char_point = 0; + return NULL; + } + + // if we don't have enough free characters in the buffer, we have to make room + while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT) + stb_textedit_discard_undo(state); + + return &state->undo_rec[state->undo_point++]; +} + +static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len) +{ + StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); + if (r == NULL) + return NULL; + + r->where = pos; + r->insert_length = (STB_TEXTEDIT_POSITIONTYPE) insert_len; + r->delete_length = (STB_TEXTEDIT_POSITIONTYPE) delete_len; + + if (insert_len == 0) { + r->char_storage = -1; + return NULL; + } else { + r->char_storage = state->undo_char_point; + state->undo_char_point += insert_len; + return &state->undo_char[r->char_storage]; + } +} + +static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord u, *r; + if (s->undo_point == 0) + return; + + // we need to do two things: apply the undo record, and create a redo record + u = s->undo_rec[s->undo_point-1]; + r = &s->undo_rec[s->redo_point-1]; + r->char_storage = -1; + + r->insert_length = u.delete_length; + r->delete_length = u.insert_length; + r->where = u.where; + + if (u.delete_length) { + // if the undo record says to delete characters, then the redo record will + // need to re-insert the characters that get deleted, so we need to store + // them. + + // there are three cases: + // there's enough room to store the characters + // characters stored for *redoing* don't leave room for redo + // characters stored for *undoing* don't leave room for redo + // if the last is true, we have to bail + + if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) { + // the undo records take up too much character space; there's no space to store the redo characters + r->insert_length = 0; + } else { + int i; + + // there's definitely room to store the characters eventually + while (s->undo_char_point + u.delete_length > s->redo_char_point) { + // should never happen: + if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + return; + // there's currently not enough room, so discard a redo record + stb_textedit_discard_redo(s); + } + r = &s->undo_rec[s->redo_point-1]; + + r->char_storage = s->redo_char_point - u.delete_length; + s->redo_char_point = s->redo_char_point - u.delete_length; + + // now save the characters + for (i=0; i < u.delete_length; ++i) + s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i); + } + + // now we can carry out the deletion + STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length); + } + + // check type of recorded action: + if (u.insert_length) { + // easy case: was a deletion, so we need to insert n characters + STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); + s->undo_char_point -= u.insert_length; + } + + state->cursor = u.where + u.insert_length; + + s->undo_point--; + s->redo_point--; +} + +static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord *u, r; + if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + return; + + // we need to do two things: apply the redo record, and create an undo record + u = &s->undo_rec[s->undo_point]; + r = s->undo_rec[s->redo_point]; + + // we KNOW there must be room for the undo record, because the redo record + // was derived from an undo record + + u->delete_length = r.insert_length; + u->insert_length = r.delete_length; + u->where = r.where; + u->char_storage = -1; + + if (r.delete_length) { + // the redo record requires us to delete characters, so the undo record + // needs to store the characters + + if (s->undo_char_point + u->insert_length > s->redo_char_point) { + u->insert_length = 0; + u->delete_length = 0; + } else { + int i; + u->char_storage = s->undo_char_point; + s->undo_char_point = s->undo_char_point + u->insert_length; + + // now save the characters + for (i=0; i < u->insert_length; ++i) + s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i); + } + + STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length); + } + + if (r.insert_length) { + // easy case: need to insert n characters + STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); + s->redo_char_point += r.insert_length; + } + + state->cursor = r.where + r.insert_length; + + s->undo_point++; + s->redo_point++; +} + +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length) +{ + stb_text_createundo(&state->undostate, where, 0, length); +} + +static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length) +{ + int i; + STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0); + if (p) { + for (i=0; i < length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); + } +} + +static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length) +{ + int i; + STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length); + if (p) { + for (i=0; i < old_length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); + } +} + +// reset the state to default +static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line) +{ + state->undostate.undo_point = 0; + state->undostate.undo_char_point = 0; + state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; + state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; + state->select_end = state->select_start = 0; + state->cursor = 0; + state->has_preferred_x = 0; + state->preferred_x = 0; + state->cursor_at_end_of_line = 0; + state->initialized = 1; + state->single_line = (unsigned char) is_single_line; + state->insert_mode = 0; + state->row_count_per_page = 0; +} + +// API initialize +static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) +{ + stb_textedit_clear_state(state, is_single_line); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len) +{ + return stb_textedit_paste_internal(str, state, (STB_TEXTEDIT_CHARTYPE *) ctext, len); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif//STB_TEXTEDIT_IMPLEMENTATION + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/src/editors/xrEUI/imstb_truetype.h b/src/editors/xrEUI/imstb_truetype.h new file mode 100644 index 00000000000..643d37899e4 --- /dev/null +++ b/src/editors/xrEUI/imstb_truetype.h @@ -0,0 +1,5085 @@ +// [DEAR IMGUI] +// This is a slightly modified version of stb_truetype.h 1.26. +// Mostly fixing for compiler and static analyzer warnings. +// Grep for [DEAR IMGUI] to find the changes. + +// stb_truetype.h - v1.26 - public domain +// authored from 2009-2021 by Sean Barrett / RAD Game Tools +// +// ======================================================================= +// +// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES +// +// This library does no range checking of the offsets found in the file, +// meaning an attacker can use it to read arbitrary memory. +// +// ======================================================================= +// +// This library processes TrueType files: +// parse files +// extract glyph metrics +// extract glyph shapes +// render glyphs to one-channel bitmaps with antialiasing (box filter) +// render glyphs to one-channel SDF bitmaps (signed-distance field/function) +// +// Todo: +// non-MS cmaps +// crashproof on bad data +// hinting? (no longer patented) +// cleartype-style AA? +// optimize: use simple memory allocator for intermediates +// optimize: build edge-list directly from curves +// optimize: rasterize directly from curves? +// +// ADDITIONAL CONTRIBUTORS +// +// Mikko Mononen: compound shape support, more cmap formats +// Tor Andersson: kerning, subpixel rendering +// Dougall Johnson: OpenType / Type 2 font handling +// Daniel Ribeiro Maciel: basic GPOS-based kerning +// +// Misc other: +// Ryan Gordon +// Simon Glass +// github:IntellectualKitty +// Imanol Celaya +// Daniel Ribeiro Maciel +// +// Bug/warning reports/fixes: +// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe +// Cass Everitt Martins Mozeiko github:aloucks +// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam +// Brian Hook Omar Cornut github:vassvik +// Walter van Niftrik Ryan Griege +// David Gow Peter LaValle +// David Given Sergey Popov +// Ivan-Assen Ivanov Giumo X. Clanjor +// Anthony Pesch Higor Euripedes +// Johan Duparc Thomas Fields +// Hou Qiming Derek Vinyard +// Rob Loach Cort Stratton +// Kenney Phillis Jr. Brian Costabile +// Ken Voskuil (kaesve) +// +// VERSION HISTORY +// +// 1.26 (2021-08-28) fix broken rasterizer +// 1.25 (2021-07-11) many fixes +// 1.24 (2020-02-05) fix warning +// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) +// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined +// 1.21 (2019-02-25) fix warning +// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() +// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// variant PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// +// Full history can be found at the end of this file. +// +// LICENSE +// +// See end of file for license information. +// +// USAGE +// +// Include this file in whatever places need to refer to it. In ONE C/C++ +// file, write: +// #define STB_TRUETYPE_IMPLEMENTATION +// before the #include of this file. This expands out the actual +// implementation into that C/C++ file. +// +// To make the implementation private to the file that generates the implementation, +// #define STBTT_STATIC +// +// Simple 3D API (don't ship this, but it's fine for tools and quick start) +// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture +// stbtt_GetBakedQuad() -- compute quad to draw for a given char +// +// Improved 3D API (more shippable): +// #include "stb_rect_pack.h" -- optional, but you really want it +// stbtt_PackBegin() +// stbtt_PackSetOversampling() -- for improved quality on small fonts +// stbtt_PackFontRanges() -- pack and renders +// stbtt_PackEnd() +// stbtt_GetPackedQuad() +// +// "Load" a font file from a memory buffer (you have to keep the buffer loaded) +// stbtt_InitFont() +// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections +// +// Render a unicode codepoint to a bitmap +// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap +// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide +// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be +// +// Character advance/positioning +// stbtt_GetCodepointHMetrics() +// stbtt_GetFontVMetrics() +// stbtt_GetFontVMetricsOS2() +// stbtt_GetCodepointKernAdvance() +// +// Starting with version 1.06, the rasterizer was replaced with a new, +// faster and generally-more-precise rasterizer. The new rasterizer more +// accurately measures pixel coverage for anti-aliasing, except in the case +// where multiple shapes overlap, in which case it overestimates the AA pixel +// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If +// this turns out to be a problem, you can re-enable the old rasterizer with +// #define STBTT_RASTERIZER_VERSION 1 +// which will incur about a 15% speed hit. +// +// ADDITIONAL DOCUMENTATION +// +// Immediately after this block comment are a series of sample programs. +// +// After the sample programs is the "header file" section. This section +// includes documentation for each API function. +// +// Some important concepts to understand to use this library: +// +// Codepoint +// Characters are defined by unicode codepoints, e.g. 65 is +// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is +// the hiragana for "ma". +// +// Glyph +// A visual character shape (every codepoint is rendered as +// some glyph) +// +// Glyph index +// A font-specific integer ID representing a glyph +// +// Baseline +// Glyph shapes are defined relative to a baseline, which is the +// bottom of uppercase characters. Characters extend both above +// and below the baseline. +// +// Current Point +// As you draw text to the screen, you keep track of a "current point" +// which is the origin of each character. The current point's vertical +// position is the baseline. Even "baked fonts" use this model. +// +// Vertical Font Metrics +// The vertical qualities of the font, used to vertically position +// and space the characters. See docs for stbtt_GetFontVMetrics. +// +// Font Size in Pixels or Points +// The preferred interface for specifying font sizes in stb_truetype +// is to specify how tall the font's vertical extent should be in pixels. +// If that sounds good enough, skip the next paragraph. +// +// Most font APIs instead use "points", which are a common typographic +// measurement for describing font size, defined as 72 points per inch. +// stb_truetype provides a point API for compatibility. However, true +// "per inch" conventions don't make much sense on computer displays +// since different monitors have different number of pixels per +// inch. For example, Windows traditionally uses a convention that +// there are 96 pixels per inch, thus making 'inch' measurements have +// nothing to do with inches, and thus effectively defining a point to +// be 1.333 pixels. Additionally, the TrueType font data provides +// an explicit scale factor to scale a given font's glyphs to points, +// but the author has observed that this scale factor is often wrong +// for non-commercial fonts, thus making fonts scaled in points +// according to the TrueType spec incoherently sized in practice. +// +// DETAILED USAGE: +// +// Scale: +// Select how high you want the font to be, in points or pixels. +// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute +// a scale factor SF that will be used by all other functions. +// +// Baseline: +// You need to select a y-coordinate that is the baseline of where +// your text will appear. Call GetFontBoundingBox to get the baseline-relative +// bounding box for all characters. SF*-y0 will be the distance in pixels +// that the worst-case character could extend above the baseline, so if +// you want the top edge of characters to appear at the top of the +// screen where y=0, then you would set the baseline to SF*-y0. +// +// Current point: +// Set the current point where the first character will appear. The +// first character could extend left of the current point; this is font +// dependent. You can either choose a current point that is the leftmost +// point and hope, or add some padding, or check the bounding box or +// left-side-bearing of the first character to be displayed and set +// the current point based on that. +// +// Displaying a character: +// Compute the bounding box of the character. It will contain signed values +// relative to . I.e. if it returns x0,y0,x1,y1, +// then the character should be displayed in the rectangle from +// to = 32 && *text < 128) { + stbtt_aligned_quad q; + stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 + glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0); + glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0); + glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1); + glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1); + } + ++text; + } + glEnd(); +} +#endif +// +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program (this compiles): get a single bitmap, print as ASCII art +// +#if 0 +#include +#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation +#include "stb_truetype.h" + +char ttf_buffer[1<<25]; + +int main(int argc, char **argv) +{ + stbtt_fontinfo font; + unsigned char *bitmap; + int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); + + fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); + + stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); + bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); + + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) + putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); + putchar('\n'); + } + return 0; +} +#endif +// +// Output: +// +// .ii. +// @@@@@@. +// V@Mio@@o +// :i. V@V +// :oM@@M +// :@@@MM@M +// @@o o@M +// :@@. M@M +// @@@o@@@@ +// :M@@V:@@. +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program: print "Hello World!" banner, with bugs +// +#if 0 +char buffer[24<<20]; +unsigned char screen[20][79]; + +int main(int arg, char **argv) +{ + stbtt_fontinfo font; + int i,j,ascent,baseline,ch=0; + float scale, xpos=2; // leave a little padding in case the character extends left + char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness + + fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); + stbtt_InitFont(&font, buffer, 0); + + scale = stbtt_ScaleForPixelHeight(&font, 15); + stbtt_GetFontVMetrics(&font, &ascent,0,0); + baseline = (int) (ascent*scale); + + while (text[ch]) { + int advance,lsb,x0,y0,x1,y1; + float x_shift = xpos - (float) floor(xpos); + stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); + stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); + stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); + // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong + // because this API is really for baking character bitmaps into textures. if you want to render + // a sequence of characters, you really need to render each bitmap to a temp buffer, then + // "alpha blend" that into the working buffer + xpos += (advance * scale); + if (text[ch+1]) + xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); + ++ch; + } + + for (j=0; j < 20; ++j) { + for (i=0; i < 78; ++i) + putchar(" .:ioVM@"[screen[j][i]>>5]); + putchar('\n'); + } + + return 0; +} +#endif + + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +//// +//// INTEGRATION WITH YOUR CODEBASE +//// +//// The following sections allow you to supply alternate definitions +//// of C library functions used by stb_truetype, e.g. if you don't +//// link with the C runtime library. + +#ifdef STB_TRUETYPE_IMPLEMENTATION + // #define your own (u)stbtt_int8/16/32 before including to override this + #ifndef stbtt_uint8 + typedef unsigned char stbtt_uint8; + typedef signed char stbtt_int8; + typedef unsigned short stbtt_uint16; + typedef signed short stbtt_int16; + typedef unsigned int stbtt_uint32; + typedef signed int stbtt_int32; + #endif + + typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; + typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; + + // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h + #ifndef STBTT_ifloor + #include + #define STBTT_ifloor(x) ((int) floor(x)) + #define STBTT_iceil(x) ((int) ceil(x)) + #endif + + #ifndef STBTT_sqrt + #include + #define STBTT_sqrt(x) sqrt(x) + #define STBTT_pow(x,y) pow(x,y) + #endif + + #ifndef STBTT_fmod + #include + #define STBTT_fmod(x,y) fmod(x,y) + #endif + + #ifndef STBTT_cos + #include + #define STBTT_cos(x) cos(x) + #define STBTT_acos(x) acos(x) + #endif + + #ifndef STBTT_fabs + #include + #define STBTT_fabs(x) fabs(x) + #endif + + // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h + #ifndef STBTT_malloc + #include + #define STBTT_malloc(x,u) ((void)(u),malloc(x)) + #define STBTT_free(x,u) ((void)(u),free(x)) + #endif + + #ifndef STBTT_assert + #include + #define STBTT_assert(x) assert(x) + #endif + + #ifndef STBTT_strlen + #include + #define STBTT_strlen(x) strlen(x) + #endif + + #ifndef STBTT_memcpy + #include + #define STBTT_memcpy memcpy + #define STBTT_memset memset + #endif +#endif + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// INTERFACE +//// +//// + +#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ +#define __STB_INCLUDE_STB_TRUETYPE_H__ + +#ifdef STBTT_STATIC +#define STBTT_DEF static +#else +#define STBTT_DEF extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// private structure +typedef struct +{ + unsigned char *data; + int cursor; + int size; +} stbtt__buf; + +////////////////////////////////////////////////////////////////////////////// +// +// TEXTURE BAKING API +// +// If you use this API, you only have to call two functions ever. +// + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; +} stbtt_bakedchar; + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata); // you allocate this, it's num_chars long +// if return is positive, the first unused row of the bitmap +// if return is negative, returns the negative of the number of characters that fit +// if return is 0, no characters fit and no rows were used +// This uses a very crappy packing. + +typedef struct +{ + float x0,y0,s0,t0; // top-left + float x1,y1,s1,t1; // bottom-right +} stbtt_aligned_quad; + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier +// Call GetBakedQuad with char_index = 'character - first_char', and it +// creates the quad you need to draw and advances the current position. +// +// The coordinate system used assumes y increases downwards. +// +// Characters will extend both above and below the current position; +// see discussion of "BASELINE" above. +// +// It's inefficient; you might want to c&p it and optimize it. + +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); +// Query the font vertical metrics without having to create a font first. + + +////////////////////////////////////////////////////////////////////////////// +// +// NEW TEXTURE BAKING API +// +// This provides options for packing multiple fonts into one atlas, not +// perfectly but better than nothing. + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; + float xoff2,yoff2; +} stbtt_packedchar; + +typedef struct stbtt_pack_context stbtt_pack_context; +typedef struct stbtt_fontinfo stbtt_fontinfo; +#ifndef STB_RECT_PACK_VERSION +typedef struct stbrp_rect stbrp_rect; +#endif + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); +// Initializes a packing context stored in the passed-in stbtt_pack_context. +// Future calls using this context will pack characters into the bitmap passed +// in here: a 1-channel bitmap that is width * height. stride_in_bytes is +// the distance from one row to the next (or 0 to mean they are packed tightly +// together). "padding" is the amount of padding to leave between each +// character (normally you want '1' for bitmaps you'll use as textures with +// bilinear filtering). +// +// Returns 0 on failure, 1 on success. + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); +// Cleans up the packing context and frees all memory. + +#define STBTT_POINT_SIZE(x) (-(x)) + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); +// Creates character bitmaps from the font_index'th font found in fontdata (use +// font_index=0 if you don't know what that is). It creates num_chars_in_range +// bitmaps for characters with unicode values starting at first_unicode_char_in_range +// and increasing. Data for how to render them is stored in chardata_for_range; +// pass these to stbtt_GetPackedQuad to get back renderable quads. +// +// font_size is the full height of the character from ascender to descender, +// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed +// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() +// and pass that result as 'font_size': +// ..., 20 , ... // font max minus min y is 20 pixels tall +// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall + +typedef struct +{ + float font_size; + int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint + int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int num_chars; + stbtt_packedchar *chardata_for_range; // output + unsigned char h_oversample, v_oversample; // don't set these, they're used internally +} stbtt_pack_range; + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); +// Creates character bitmaps from multiple ranges of characters stored in +// ranges. This will usually create a better-packed bitmap than multiple +// calls to stbtt_PackFontRange. Note that you can call this multiple +// times within a single PackBegin/PackEnd. + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); +// Oversampling a font increases the quality by allowing higher-quality subpixel +// positioning, and is especially valuable at smaller text sizes. +// +// This function sets the amount of oversampling for all following calls to +// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given +// pack context. The default (no oversampling) is achieved by h_oversample=1 +// and v_oversample=1. The total number of pixels required is +// h_oversample*v_oversample larger than the default; for example, 2x2 +// oversampling requires 4x the storage of 1x1. For best results, render +// oversampled textures with bilinear filtering. Look at the readme in +// stb/tests/oversample for information about oversampled fonts +// +// To use with PackFontRangesGather etc., you must set it before calls +// call to PackFontRangesGatherRects. + +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); +// If skip != 0, this tells stb_truetype to skip any codepoints for which +// there is no corresponding glyph. If skip=0, which is the default, then +// codepoints without a glyph recived the font's "missing character" glyph, +// typically an empty box by convention. + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int align_to_integer); + +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +// Calling these functions in sequence is roughly equivalent to calling +// stbtt_PackFontRanges(). If you more control over the packing of multiple +// fonts, or if you want to pack custom data into a font texture, take a look +// at the source to of stbtt_PackFontRanges() and create a custom version +// using these functions, e.g. call GatherRects multiple times, +// building up a single array of rects, then call PackRects once, +// then call RenderIntoRects repeatedly. This may result in a +// better packing than calling PackFontRanges multiple times +// (or it may not). + +// this is an opaque structure that you shouldn't mess with which holds +// all the context needed from PackBegin to PackEnd. +struct stbtt_pack_context { + void *user_allocator_context; + void *pack_info; + int width; + int height; + int stride_in_bytes; + int padding; + int skip_missing; + unsigned int h_oversample, v_oversample; + unsigned char *pixels; + void *nodes; +}; + +////////////////////////////////////////////////////////////////////////////// +// +// FONT LOADING +// +// + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); +// This function will determine the number of fonts in a font file. TrueType +// collection (.ttc) files may contain multiple fonts, while TrueType font +// (.ttf) files only contain one font. The number of fonts can be used for +// indexing with the previous function where the index is between zero and one +// less than the total fonts. If an error occurs, -1 is returned. + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); +// Each .ttf/.ttc file may have more than one font. Each font has a sequential +// index number starting from 0. Call this function to get the font offset for +// a given index; it returns -1 if the index is out of range. A regular .ttf +// file will only define one font and it always be at offset 0, so it will +// return '0' for index 0, and -1 for all other indices. + +// The following structure is defined publicly so you can declare one on +// the stack or as a global or etc, but you should treat it as opaque. +struct stbtt_fontinfo +{ + void * userdata; + unsigned char * data; // pointer to .ttf file + int fontstart; // offset of start of font + + int numGlyphs; // number of glyphs, needed for range checking + + int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf + int index_map; // a cmap mapping for our chosen character encoding + int indexToLocFormat; // format needed to map from glyph index to glyph + + stbtt__buf cff; // cff font data + stbtt__buf charstrings; // the charstring index + stbtt__buf gsubrs; // global charstring subroutines index + stbtt__buf subrs; // private charstring subroutines index + stbtt__buf fontdicts; // array of font dicts + stbtt__buf fdselect; // map from glyph to fontdict +}; + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); +// Given an offset into the file that defines a font, this function builds +// the necessary cached info for the rest of the system. You must allocate +// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't +// need to do anything special to free it, because the contents are pure +// value data with no additional data structures. Returns 0 on failure. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER TO GLYPH-INDEX CONVERSIOn + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); +// If you're going to perform multiple operations on the same character +// and you want a speed-up, call this function with the character you're +// going to process, then use glyph-based functions instead of the +// codepoint-based functions. +// Returns 0 if the character codepoint is not defined in the font. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER PROPERTIES +// + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose "height" is 'pixels' tall. +// Height is measured as the distance from the highest ascender to the lowest +// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics +// and computing: +// scale = pixels / (ascent - descent) +// so if you prefer to measure height by the ascent only, use a similar calculation. + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose EM size is mapped to +// 'pixels' tall. This is probably what traditional APIs compute, but +// I'm not positive. + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); +// ascent is the coordinate above the baseline the font extends; descent +// is the coordinate below the baseline the font extends (i.e. it is typically negative) +// lineGap is the spacing between one row's descent and the next row's ascent... +// so you should advance the vertical position by "*ascent - *descent + *lineGap" +// these are expressed in unscaled coordinates, so you must multiply by +// the scale factor for a given size + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); +// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 +// table (specific to MS/Windows TTF files). +// +// Returns 1 on success (table present), 0 on failure. + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); +// the bounding box around all possible characters + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); +// leftSideBearing is the offset from the current horizontal position to the left edge of the character +// advanceWidth is the offset from the current horizontal position to the next horizontal position +// these are expressed in unscaled coordinates + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); +// an additional amount to add to the 'advance' value between ch1 and ch2 + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); +// Gets the bounding box of the visible part of the glyph, in unscaled coordinates + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); +// as above, but takes one or more glyph indices for greater efficiency + +typedef struct stbtt_kerningentry +{ + int glyph1; // use stbtt_FindGlyphIndex + int glyph2; + int advance; +} stbtt_kerningentry; + +STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); +STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); +// Retrieves a complete list of all of the kerning pairs provided by the font +// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. +// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) + +////////////////////////////////////////////////////////////////////////////// +// +// GLYPH SHAPES (you probably don't need these, but they have to go before +// the bitmaps for C declaration-order reasons) +// + +#ifndef STBTT_vmove // you can predefine these to use different values (but why?) + enum { + STBTT_vmove=1, + STBTT_vline, + STBTT_vcurve, + STBTT_vcubic + }; +#endif + +#ifndef stbtt_vertex // you can predefine this to use different values + // (we share this with other code at RAD) + #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file + typedef struct + { + stbtt_vertex_type x,y,cx,cy,cx1,cy1; + unsigned char type,padding; + } stbtt_vertex; +#endif + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); +// returns non-zero if nothing is drawn for this glyph + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); +// returns # of vertices and fills *vertices with the pointer to them +// these are expressed in "unscaled" coordinates +// +// The shape is a series of contours. Each one starts with +// a STBTT_moveto, then consists of a series of mixed +// STBTT_lineto and STBTT_curveto segments. A lineto +// draws a line from previous endpoint to its x,y; a curveto +// draws a quadratic bezier from previous endpoint to +// its x,y, using cx,cy as the bezier control point. + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); +// frees the data allocated above + +STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl); +STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); +STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); +// fills svg with the character's SVG data. +// returns data size or 0 if SVG not found. + +////////////////////////////////////////////////////////////////////////////// +// +// BITMAP RENDERING +// + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); +// frees the bitmap allocated below + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// allocates a large-enough single-channel 8bpp bitmap and renders the +// specified character/glyph at the specified scale into it, with +// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). +// *width & *height are filled out with the width & height of the bitmap, +// which is stored left-to-right, top-to-bottom. +// +// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); +// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap +// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap +// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the +// width and height and positioning info for it first. + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); +// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); +// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering +// is performed (see stbtt_PackSetOversampling) + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +// get the bbox of the bitmap centered around the glyph origin; so the +// bitmap width is ix1-ix0, height is iy1-iy0, and location to place +// the bitmap top left is (leftSideBearing*scale,iy0). +// (Note that the bitmap uses y-increases-down, but the shape uses +// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); +// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel +// shift for the character + +// the following functions are equivalent to the above functions, but operate +// on glyph indices instead of Unicode codepoints (for efficiency) +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); + + +// @TODO: don't expose this structure +typedef struct +{ + int w,h,stride; + unsigned char *pixels; +} stbtt__bitmap; + +// rasterize a shape with quadratic beziers into a bitmap +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into + float flatness_in_pixels, // allowable error of curve in pixels + stbtt_vertex *vertices, // array of vertices defining shape + int num_verts, // number of vertices in above array + float scale_x, float scale_y, // scale applied to input vertices + float shift_x, float shift_y, // translation applied to input vertices + int x_off, int y_off, // another translation applied to input + int invert, // if non-zero, vertically flip shape + void *userdata); // context for to STBTT_MALLOC + +////////////////////////////////////////////////////////////////////////////// +// +// Signed Distance Function (or Field) rendering + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); +// frees the SDF bitmap allocated below + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +// These functions compute a discretized SDF field for a single character, suitable for storing +// in a single-channel texture, sampling with bilinear filtering, and testing against +// larger than some threshold to produce scalable fonts. +// info -- the font +// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap +// glyph/codepoint -- the character to generate the SDF for +// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), +// which allows effects like bit outlines +// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) +// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) +// if positive, > onedge_value is inside; if negative, < onedge_value is inside +// width,height -- output height & width of the SDF bitmap (including padding) +// xoff,yoff -- output origin of the character +// return value -- a 2D array of bytes 0..255, width*height in size +// +// pixel_dist_scale & onedge_value are a scale & bias that allows you to make +// optimal use of the limited 0..255 for your application, trading off precision +// and special effects. SDF values outside the range 0..255 are clamped to 0..255. +// +// Example: +// scale = stbtt_ScaleForPixelHeight(22) +// padding = 5 +// onedge_value = 180 +// pixel_dist_scale = 180/5.0 = 36.0 +// +// This will create an SDF bitmap in which the character is about 22 pixels +// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled +// shape, sample the SDF at each pixel and fill the pixel if the SDF value +// is greater than or equal to 180/255. (You'll actually want to antialias, +// which is beyond the scope of this example.) Additionally, you can compute +// offset outlines (e.g. to stroke the character border inside & outside, +// or only outside). For example, to fill outside the character up to 3 SDF +// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above +// choice of variables maps a range from 5 pixels outside the shape to +// 2 pixels inside the shape to 0..255; this is intended primarily for apply +// outside effects only (the interior range is needed to allow proper +// antialiasing of the font at *smaller* sizes) +// +// The function computes the SDF analytically at each SDF pixel, not by e.g. +// building a higher-res bitmap and approximating it. In theory the quality +// should be as high as possible for an SDF of this size & representation, but +// unclear if this is true in practice (perhaps building a higher-res bitmap +// and computing from that can allow drop-out prevention). +// +// The algorithm has not been optimized at all, so expect it to be slow +// if computing lots of characters or very large sizes. + + + +////////////////////////////////////////////////////////////////////////////// +// +// Finding the right font... +// +// You should really just solve this offline, keep your own tables +// of what font is what, and don't try to get it out of the .ttf file. +// That's because getting it out of the .ttf file is really hard, because +// the names in the file can appear in many possible encodings, in many +// possible languages, and e.g. if you need a case-insensitive comparison, +// the details of that depend on the encoding & language in a complex way +// (actually underspecified in truetype, but also gigantic). +// +// But you can use the provided functions in two possible ways: +// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on +// unicode-encoded names to try to find the font you want; +// you can run this before calling stbtt_InitFont() +// +// stbtt_GetFontNameString() lets you get any of the various strings +// from the file yourself and do your own comparisons on them. +// You have to have called stbtt_InitFont() first. + + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); +// returns the offset (not index) of the font that matches, or -1 if none +// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". +// if you use any other flag, use a font name like "Arial"; this checks +// the 'macStyle' header field; i don't know if fonts set this consistently +#define STBTT_MACSTYLE_DONTCARE 0 +#define STBTT_MACSTYLE_BOLD 1 +#define STBTT_MACSTYLE_ITALIC 2 +#define STBTT_MACSTYLE_UNDERSCORE 4 +#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); +// returns 1/0 whether the first string interpreted as utf8 is identical to +// the second string interpreted as big-endian utf16... useful for strings from next func + +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); +// returns the string (which may be big-endian double byte, e.g. for unicode) +// and puts the length in bytes in *length. +// +// some of the values for the IDs are below; for more see the truetype spec: +// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html +// http://www.microsoft.com/typography/otspec/name.htm + +enum { // platformID + STBTT_PLATFORM_ID_UNICODE =0, + STBTT_PLATFORM_ID_MAC =1, + STBTT_PLATFORM_ID_ISO =2, + STBTT_PLATFORM_ID_MICROSOFT =3 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_UNICODE + STBTT_UNICODE_EID_UNICODE_1_0 =0, + STBTT_UNICODE_EID_UNICODE_1_1 =1, + STBTT_UNICODE_EID_ISO_10646 =2, + STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, + STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT + STBTT_MS_EID_SYMBOL =0, + STBTT_MS_EID_UNICODE_BMP =1, + STBTT_MS_EID_SHIFTJIS =2, + STBTT_MS_EID_UNICODE_FULL =10 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes + STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, + STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, + STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, + STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 +}; + +enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... + // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs + STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, + STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, + STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, + STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, + STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, + STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D +}; + +enum { // languageID for STBTT_PLATFORM_ID_MAC + STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, + STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, + STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, + STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , + STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , + STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, + STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 +}; + +#ifdef __cplusplus +} +#endif + +#endif // __STB_INCLUDE_STB_TRUETYPE_H__ + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// IMPLEMENTATION +//// +//// + +#ifdef STB_TRUETYPE_IMPLEMENTATION + +#ifndef STBTT_MAX_OVERSAMPLE +#define STBTT_MAX_OVERSAMPLE 8 +#endif + +#if STBTT_MAX_OVERSAMPLE > 255 +#error "STBTT_MAX_OVERSAMPLE cannot be > 255" +#endif + +typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; + +#ifndef STBTT_RASTERIZER_VERSION +#define STBTT_RASTERIZER_VERSION 2 +#endif + +#ifdef _MSC_VER +#define STBTT__NOTUSED(v) (void)(v) +#else +#define STBTT__NOTUSED(v) (void)sizeof(v) +#endif + +////////////////////////////////////////////////////////////////////////// +// +// stbtt__buf helpers to parse data from file +// + +static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor++]; +} + +static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor]; +} + +static void stbtt__buf_seek(stbtt__buf *b, int o) +{ + STBTT_assert(!(o > b->size || o < 0)); + b->cursor = (o > b->size || o < 0) ? b->size : o; +} + +static void stbtt__buf_skip(stbtt__buf *b, int o) +{ + stbtt__buf_seek(b, b->cursor + o); +} + +static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) +{ + stbtt_uint32 v = 0; + int i; + STBTT_assert(n >= 1 && n <= 4); + for (i = 0; i < n; i++) + v = (v << 8) | stbtt__buf_get8(b); + return v; +} + +static stbtt__buf stbtt__new_buf(const void *p, size_t size) +{ + stbtt__buf r; + STBTT_assert(size < 0x40000000); + r.data = (stbtt_uint8*) p; + r.size = (int) size; + r.cursor = 0; + return r; +} + +#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) +#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) + +static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) +{ + stbtt__buf r = stbtt__new_buf(NULL, 0); + if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; + r.data = b->data + o; + r.size = s; + return r; +} + +static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) +{ + int count, start, offsize; + start = b->cursor; + count = stbtt__buf_get16(b); + if (count) { + offsize = stbtt__buf_get8(b); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(b, offsize * count); + stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); + } + return stbtt__buf_range(b, start, b->cursor - start); +} + +static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) +{ + int b0 = stbtt__buf_get8(b); + if (b0 >= 32 && b0 <= 246) return b0 - 139; + else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; + else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; + else if (b0 == 28) return stbtt__buf_get16(b); + else if (b0 == 29) return stbtt__buf_get32(b); + STBTT_assert(0); + return 0; +} + +static void stbtt__cff_skip_operand(stbtt__buf *b) { + int v, b0 = stbtt__buf_peek8(b); + STBTT_assert(b0 >= 28); + if (b0 == 30) { + stbtt__buf_skip(b, 1); + while (b->cursor < b->size) { + v = stbtt__buf_get8(b); + if ((v & 0xF) == 0xF || (v >> 4) == 0xF) + break; + } + } else { + stbtt__cff_int(b); + } +} + +static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) +{ + stbtt__buf_seek(b, 0); + while (b->cursor < b->size) { + int start = b->cursor, end, op; + while (stbtt__buf_peek8(b) >= 28) + stbtt__cff_skip_operand(b); + end = b->cursor; + op = stbtt__buf_get8(b); + if (op == 12) op = stbtt__buf_get8(b) | 0x100; + if (op == key) return stbtt__buf_range(b, start, end-start); + } + return stbtt__buf_range(b, 0, 0); +} + +static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) +{ + int i; + stbtt__buf operands = stbtt__dict_get(b, key); + for (i = 0; i < outcount && operands.cursor < operands.size; i++) + out[i] = stbtt__cff_int(&operands); +} + +static int stbtt__cff_index_count(stbtt__buf *b) +{ + stbtt__buf_seek(b, 0); + return stbtt__buf_get16(b); +} + +static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) +{ + int count, offsize, start, end; + stbtt__buf_seek(&b, 0); + count = stbtt__buf_get16(&b); + offsize = stbtt__buf_get8(&b); + STBTT_assert(i >= 0 && i < count); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(&b, i*offsize); + start = stbtt__buf_get(&b, offsize); + end = stbtt__buf_get(&b, offsize); + return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); +} + +////////////////////////////////////////////////////////////////////////// +// +// accessors to parse data from file +// + +// on platforms that don't allow misaligned reads, if we want to allow +// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE + +#define ttBYTE(p) (* (stbtt_uint8 *) (p)) +#define ttCHAR(p) (* (stbtt_int8 *) (p)) +#define ttFixed(p) ttLONG(p) + +static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } +static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } + +#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) +#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) + +static int stbtt__isfont(stbtt_uint8 *font) +{ + // check the version number + if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 + if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! + if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF + if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 + if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts + return 0; +} + +// @OPTIMIZE: binary search +static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) +{ + stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); + stbtt_uint32 tabledir = fontstart + 12; + stbtt_int32 i; + for (i=0; i < num_tables; ++i) { + stbtt_uint32 loc = tabledir + 16*i; + if (stbtt_tag(data+loc+0, tag)) + return ttULONG(data+loc+8); + } + return 0; +} + +static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) +{ + // if it's just a font, there's only one valid index + if (stbtt__isfont(font_collection)) + return index == 0 ? 0 : -1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + stbtt_int32 n = ttLONG(font_collection+8); + if (index >= n) + return -1; + return ttULONG(font_collection+12+index*4); + } + } + return -1; +} + +static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) +{ + // if it's just a font, there's only one valid font + if (stbtt__isfont(font_collection)) + return 1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + return ttLONG(font_collection+8); + } + } + return 0; +} + +static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) +{ + stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; + stbtt__buf pdict; + stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); + if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); + pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); + stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); + if (!subrsoff) return stbtt__new_buf(NULL, 0); + stbtt__buf_seek(&cff, private_loc[1]+subrsoff); + return stbtt__cff_get_index(&cff); +} + +// since most people won't use this, find this table the first time it's needed +static int stbtt__get_svg(stbtt_fontinfo *info) +{ + stbtt_uint32 t; + if (info->svg < 0) { + t = stbtt__find_table(info->data, info->fontstart, "SVG "); + if (t) { + stbtt_uint32 offset = ttULONG(info->data + t + 2); + info->svg = t + offset; + } else { + info->svg = 0; + } + } + return info->svg; +} + +static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) +{ + stbtt_uint32 cmap, t; + stbtt_int32 i,numTables; + + info->data = data; + info->fontstart = fontstart; + info->cff = stbtt__new_buf(NULL, 0); + + cmap = stbtt__find_table(data, fontstart, "cmap"); // required + info->loca = stbtt__find_table(data, fontstart, "loca"); // required + info->head = stbtt__find_table(data, fontstart, "head"); // required + info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required + info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required + info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required + info->kern = stbtt__find_table(data, fontstart, "kern"); // not required + info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required + + if (!cmap || !info->head || !info->hhea || !info->hmtx) + return 0; + if (info->glyf) { + // required for truetype + if (!info->loca) return 0; + } else { + // initialization for CFF / Type2 fonts (OTF) + stbtt__buf b, topdict, topdictidx; + stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; + stbtt_uint32 cff; + + cff = stbtt__find_table(data, fontstart, "CFF "); + if (!cff) return 0; + + info->fontdicts = stbtt__new_buf(NULL, 0); + info->fdselect = stbtt__new_buf(NULL, 0); + + // @TODO this should use size from table (not 512MB) + info->cff = stbtt__new_buf(data+cff, 512*1024*1024); + b = info->cff; + + // read the header + stbtt__buf_skip(&b, 2); + stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize + + // @TODO the name INDEX could list multiple fonts, + // but we just use the first one. + stbtt__cff_get_index(&b); // name INDEX + topdictidx = stbtt__cff_get_index(&b); + topdict = stbtt__cff_index_get(topdictidx, 0); + stbtt__cff_get_index(&b); // string INDEX + info->gsubrs = stbtt__cff_get_index(&b); + + stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); + stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); + stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); + stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); + info->subrs = stbtt__get_subrs(b, topdict); + + // we only support Type 2 charstrings + if (cstype != 2) return 0; + if (charstrings == 0) return 0; + + if (fdarrayoff) { + // looks like a CID font + if (!fdselectoff) return 0; + stbtt__buf_seek(&b, fdarrayoff); + info->fontdicts = stbtt__cff_get_index(&b); + info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); + } + + stbtt__buf_seek(&b, charstrings); + info->charstrings = stbtt__cff_get_index(&b); + } + + t = stbtt__find_table(data, fontstart, "maxp"); + if (t) + info->numGlyphs = ttUSHORT(data+t+4); + else + info->numGlyphs = 0xffff; + + info->svg = -1; + + // find a cmap encoding table we understand *now* to avoid searching + // later. (todo: could make this installable) + // the same regardless of glyph. + numTables = ttUSHORT(data + cmap + 2); + info->index_map = 0; + for (i=0; i < numTables; ++i) { + stbtt_uint32 encoding_record = cmap + 4 + 8 * i; + // find an encoding we understand: + switch(ttUSHORT(data+encoding_record)) { + case STBTT_PLATFORM_ID_MICROSOFT: + switch (ttUSHORT(data+encoding_record+2)) { + case STBTT_MS_EID_UNICODE_BMP: + case STBTT_MS_EID_UNICODE_FULL: + // MS/Unicode + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + break; + case STBTT_PLATFORM_ID_UNICODE: + // Mac/iOS has these + // all the encodingIDs are unicode, so we don't bother to check it + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + } + if (info->index_map == 0) + return 0; + + info->indexToLocFormat = ttUSHORT(data+info->head + 50); + return 1; +} + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) +{ + stbtt_uint8 *data = info->data; + stbtt_uint32 index_map = info->index_map; + + stbtt_uint16 format = ttUSHORT(data + index_map + 0); + if (format == 0) { // apple byte encoding + stbtt_int32 bytes = ttUSHORT(data + index_map + 2); + if (unicode_codepoint < bytes-6) + return ttBYTE(data + index_map + 6 + unicode_codepoint); + return 0; + } else if (format == 6) { + stbtt_uint32 first = ttUSHORT(data + index_map + 6); + stbtt_uint32 count = ttUSHORT(data + index_map + 8); + if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) + return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); + return 0; + } else if (format == 2) { + STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean + return 0; + } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges + stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; + stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; + stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); + stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; + + // do a binary search of the segments + stbtt_uint32 endCount = index_map + 14; + stbtt_uint32 search = endCount; + + if (unicode_codepoint > 0xffff) + return 0; + + // they lie from endCount .. endCount + segCount + // but searchRange is the nearest power of two, so... + if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) + search += rangeShift*2; + + // now decrement to bias correctly to find smallest + search -= 2; + while (entrySelector) { + stbtt_uint16 end; + searchRange >>= 1; + end = ttUSHORT(data + search + searchRange*2); + if (unicode_codepoint > end) + search += searchRange*2; + --entrySelector; + } + search += 2; + + { + stbtt_uint16 offset, start, last; + stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); + + start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); + last = ttUSHORT(data + endCount + 2*item); + if (unicode_codepoint < start || unicode_codepoint > last) + return 0; + + offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); + if (offset == 0) + return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); + + return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + } + } else if (format == 12 || format == 13) { + stbtt_uint32 ngroups = ttULONG(data+index_map+12); + stbtt_int32 low,high; + low = 0; high = (stbtt_int32)ngroups; + // Binary search the right group. + while (low < high) { + stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high + stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); + stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); + if ((stbtt_uint32) unicode_codepoint < start_char) + high = mid; + else if ((stbtt_uint32) unicode_codepoint > end_char) + low = mid+1; + else { + stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); + if (format == 12) + return start_glyph + unicode_codepoint-start_char; + else // format == 13 + return start_glyph; + } + } + return 0; // not found + } + // @TODO + STBTT_assert(0); + return 0; +} + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) +{ + return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); +} + +static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) +{ + v->type = type; + v->x = (stbtt_int16) x; + v->y = (stbtt_int16) y; + v->cx = (stbtt_int16) cx; + v->cy = (stbtt_int16) cy; +} + +static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) +{ + int g1,g2; + + STBTT_assert(!info->cff.size); + + if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range + if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format + + if (info->indexToLocFormat == 0) { + g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; + g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; + } else { + g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); + g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); + } + + return g1==g2 ? -1 : g1; // if length is 0, return -1 +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); + +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + if (info->cff.size) { + stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + } else { + int g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 0; + + if (x0) *x0 = ttSHORT(info->data + g + 2); + if (y0) *y0 = ttSHORT(info->data + g + 4); + if (x1) *x1 = ttSHORT(info->data + g + 6); + if (y1) *y1 = ttSHORT(info->data + g + 8); + } + return 1; +} + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) +{ + return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); +} + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt_int16 numberOfContours; + int g; + if (info->cff.size) + return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; + g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 1; + numberOfContours = ttSHORT(info->data + g); + return numberOfContours == 0; +} + +static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, + stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) +{ + if (start_off) { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); + } + return num_vertices; +} + +static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + stbtt_int16 numberOfContours; + stbtt_uint8 *endPtsOfContours; + stbtt_uint8 *data = info->data; + stbtt_vertex *vertices=0; + int num_vertices=0; + int g = stbtt__GetGlyfOffset(info, glyph_index); + + *pvertices = NULL; + + if (g < 0) return 0; + + numberOfContours = ttSHORT(data + g); + + if (numberOfContours > 0) { + stbtt_uint8 flags=0,flagcount; + stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; + stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; + stbtt_uint8 *points; + endPtsOfContours = (data + g + 10); + ins = ttUSHORT(data + g + 10 + numberOfContours * 2); + points = data + g + 10 + numberOfContours * 2 + 2 + ins; + + n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); + + m = n + 2*numberOfContours; // a loose bound on how many vertices we might need + vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); + if (vertices == 0) + return 0; + + next_move = 0; + flagcount=0; + + // in first pass, we load uninterpreted data into the allocated array + // above, shifted to the end of the array so we won't overwrite it when + // we create our final data starting from the front + + off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated + + // first load flags + + for (i=0; i < n; ++i) { + if (flagcount == 0) { + flags = *points++; + if (flags & 8) + flagcount = *points++; + } else + --flagcount; + vertices[off+i].type = flags; + } + + // now load x coordinates + x=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 2) { + stbtt_int16 dx = *points++; + x += (flags & 16) ? dx : -dx; // ??? + } else { + if (!(flags & 16)) { + x = x + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].x = (stbtt_int16) x; + } + + // now load y coordinates + y=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 4) { + stbtt_int16 dy = *points++; + y += (flags & 32) ? dy : -dy; // ??? + } else { + if (!(flags & 32)) { + y = y + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].y = (stbtt_int16) y; + } + + // now convert them to our format + num_vertices=0; + sx = sy = cx = cy = scx = scy = 0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + x = (stbtt_int16) vertices[off+i].x; + y = (stbtt_int16) vertices[off+i].y; + + if (next_move == i) { + if (i != 0) + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + + // now start the new one + start_off = !(flags & 1); + if (start_off) { + // if we start off with an off-curve point, then when we need to find a point on the curve + // where we can start, and we need to save some state for when we wraparound. + scx = x; + scy = y; + if (!(vertices[off+i+1].type & 1)) { + // next point is also a curve point, so interpolate an on-point curve + sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; + sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; + } else { + // otherwise just use the next point as our start point + sx = (stbtt_int32) vertices[off+i+1].x; + sy = (stbtt_int32) vertices[off+i+1].y; + ++i; // we're using point i+1 as the starting point, so skip it + } + } else { + sx = x; + sy = y; + } + stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); + was_off = 0; + next_move = 1 + ttUSHORT(endPtsOfContours+j*2); + ++j; + } else { + if (!(flags & 1)) { // if it's a curve + if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); + cx = x; + cy = y; + was_off = 1; + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); + was_off = 0; + } + } + } + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + } else if (numberOfContours < 0) { + // Compound shapes. + int more = 1; + stbtt_uint8 *comp = data + g + 10; + num_vertices = 0; + vertices = 0; + while (more) { + stbtt_uint16 flags, gidx; + int comp_num_verts = 0, i; + stbtt_vertex *comp_verts = 0, *tmp = 0; + float mtx[6] = {1,0,0,1,0,0}, m, n; + + flags = ttSHORT(comp); comp+=2; + gidx = ttSHORT(comp); comp+=2; + + if (flags & 2) { // XY values + if (flags & 1) { // shorts + mtx[4] = ttSHORT(comp); comp+=2; + mtx[5] = ttSHORT(comp); comp+=2; + } else { + mtx[4] = ttCHAR(comp); comp+=1; + mtx[5] = ttCHAR(comp); comp+=1; + } + } + else { + // @TODO handle matching point + STBTT_assert(0); + } + if (flags & (1<<3)) { // WE_HAVE_A_SCALE + mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } + + // Find transformation scales. + m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); + n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); + + // Get indexed glyph. + comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); + if (comp_num_verts > 0) { + // Transform vertices. + for (i = 0; i < comp_num_verts; ++i) { + stbtt_vertex* v = &comp_verts[i]; + stbtt_vertex_type x,y; + x=v->x; y=v->y; + v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + x=v->cx; y=v->cy; + v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + } + // Append vertices. + tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); + if (!tmp) { + if (vertices) STBTT_free(vertices, info->userdata); + if (comp_verts) STBTT_free(comp_verts, info->userdata); + return 0; + } + if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); + STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); + if (vertices) STBTT_free(vertices, info->userdata); + vertices = tmp; + STBTT_free(comp_verts, info->userdata); + num_vertices += comp_num_verts; + } + // More components ? + more = flags & (1<<5); + } + } else { + // numberOfCounters == 0, do nothing + } + + *pvertices = vertices; + return num_vertices; +} + +typedef struct +{ + int bounds; + int started; + float first_x, first_y; + float x, y; + stbtt_int32 min_x, max_x, min_y, max_y; + + stbtt_vertex *pvertices; + int num_vertices; +} stbtt__csctx; + +#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} + +static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) +{ + if (x > c->max_x || !c->started) c->max_x = x; + if (y > c->max_y || !c->started) c->max_y = y; + if (x < c->min_x || !c->started) c->min_x = x; + if (y < c->min_y || !c->started) c->min_y = y; + c->started = 1; +} + +static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) +{ + if (c->bounds) { + stbtt__track_vertex(c, x, y); + if (type == STBTT_vcubic) { + stbtt__track_vertex(c, cx, cy); + stbtt__track_vertex(c, cx1, cy1); + } + } else { + stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); + c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; + c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; + } + c->num_vertices++; +} + +static void stbtt__csctx_close_shape(stbtt__csctx *ctx) +{ + if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) +{ + stbtt__csctx_close_shape(ctx); + ctx->first_x = ctx->x = ctx->x + dx; + ctx->first_y = ctx->y = ctx->y + dy; + stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) +{ + ctx->x += dx; + ctx->y += dy; + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) +{ + float cx1 = ctx->x + dx1; + float cy1 = ctx->y + dy1; + float cx2 = cx1 + dx2; + float cy2 = cy1 + dy2; + ctx->x = cx2 + dx3; + ctx->y = cy2 + dy3; + stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); +} + +static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) +{ + int count = stbtt__cff_index_count(&idx); + int bias = 107; + if (count >= 33900) + bias = 32768; + else if (count >= 1240) + bias = 1131; + n += bias; + if (n < 0 || n >= count) + return stbtt__new_buf(NULL, 0); + return stbtt__cff_index_get(idx, n); +} + +static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt__buf fdselect = info->fdselect; + int nranges, start, end, v, fmt, fdselector = -1, i; + + stbtt__buf_seek(&fdselect, 0); + fmt = stbtt__buf_get8(&fdselect); + if (fmt == 0) { + // untested + stbtt__buf_skip(&fdselect, glyph_index); + fdselector = stbtt__buf_get8(&fdselect); + } else if (fmt == 3) { + nranges = stbtt__buf_get16(&fdselect); + start = stbtt__buf_get16(&fdselect); + for (i = 0; i < nranges; i++) { + v = stbtt__buf_get8(&fdselect); + end = stbtt__buf_get16(&fdselect); + if (glyph_index >= start && glyph_index < end) { + fdselector = v; + break; + } + start = end; + } + } + if (fdselector == -1) stbtt__new_buf(NULL, 0); + return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); +} + +static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) +{ + int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; + int has_subrs = 0, clear_stack; + float s[48]; + stbtt__buf subr_stack[10], subrs = info->subrs, b; + float f; + +#define STBTT__CSERR(s) (0) + + // this currently ignores the initial width value, which isn't needed if we have hmtx + b = stbtt__cff_index_get(info->charstrings, glyph_index); + while (b.cursor < b.size) { + i = 0; + clear_stack = 1; + b0 = stbtt__buf_get8(&b); + switch (b0) { + // @TODO implement hinting + case 0x13: // hintmask + case 0x14: // cntrmask + if (in_header) + maskbits += (sp / 2); // implicit "vstem" + in_header = 0; + stbtt__buf_skip(&b, (maskbits + 7) / 8); + break; + + case 0x01: // hstem + case 0x03: // vstem + case 0x12: // hstemhm + case 0x17: // vstemhm + maskbits += (sp / 2); + break; + + case 0x15: // rmoveto + in_header = 0; + if (sp < 2) return STBTT__CSERR("rmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); + break; + case 0x04: // vmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("vmoveto stack"); + stbtt__csctx_rmove_to(c, 0, s[sp-1]); + break; + case 0x16: // hmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("hmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-1], 0); + break; + + case 0x05: // rlineto + if (sp < 2) return STBTT__CSERR("rlineto stack"); + for (; i + 1 < sp; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical + // starting from a different place. + + case 0x07: // vlineto + if (sp < 1) return STBTT__CSERR("vlineto stack"); + goto vlineto; + case 0x06: // hlineto + if (sp < 1) return STBTT__CSERR("hlineto stack"); + for (;;) { + if (i >= sp) break; + stbtt__csctx_rline_to(c, s[i], 0); + i++; + vlineto: + if (i >= sp) break; + stbtt__csctx_rline_to(c, 0, s[i]); + i++; + } + break; + + case 0x1F: // hvcurveto + if (sp < 4) return STBTT__CSERR("hvcurveto stack"); + goto hvcurveto; + case 0x1E: // vhcurveto + if (sp < 4) return STBTT__CSERR("vhcurveto stack"); + for (;;) { + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); + i += 4; + hvcurveto: + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); + i += 4; + } + break; + + case 0x08: // rrcurveto + if (sp < 6) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x18: // rcurveline + if (sp < 8) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp - 2; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + case 0x19: // rlinecurve + if (sp < 8) return STBTT__CSERR("rlinecurve stack"); + for (; i + 1 < sp - 6; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x1A: // vvcurveto + case 0x1B: // hhcurveto + if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); + f = 0.0; + if (sp & 1) { f = s[i]; i++; } + for (; i + 3 < sp; i += 4) { + if (b0 == 0x1B) + stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); + else + stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); + f = 0.0; + } + break; + + case 0x0A: // callsubr + if (!has_subrs) { + if (info->fdselect.size) + subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); + has_subrs = 1; + } + // FALLTHROUGH + case 0x1D: // callgsubr + if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); + v = (int) s[--sp]; + if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); + subr_stack[subr_stack_height++] = b; + b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); + if (b.size == 0) return STBTT__CSERR("subr not found"); + b.cursor = 0; + clear_stack = 0; + break; + + case 0x0B: // return + if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); + b = subr_stack[--subr_stack_height]; + clear_stack = 0; + break; + + case 0x0E: // endchar + stbtt__csctx_close_shape(c); + return 1; + + case 0x0C: { // two-byte escape + float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; + float dx, dy; + int b1 = stbtt__buf_get8(&b); + switch (b1) { + // @TODO These "flex" implementations ignore the flex-depth and resolution, + // and always draw beziers. + case 0x22: // hflex + if (sp < 7) return STBTT__CSERR("hflex stack"); + dx1 = s[0]; + dx2 = s[1]; + dy2 = s[2]; + dx3 = s[3]; + dx4 = s[4]; + dx5 = s[5]; + dx6 = s[6]; + stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); + break; + + case 0x23: // flex + if (sp < 13) return STBTT__CSERR("flex stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = s[10]; + dy6 = s[11]; + //fd is s[12] + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + case 0x24: // hflex1 + if (sp < 9) return STBTT__CSERR("hflex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dx4 = s[5]; + dx5 = s[6]; + dy5 = s[7]; + dx6 = s[8]; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); + break; + + case 0x25: // flex1 + if (sp < 11) return STBTT__CSERR("flex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = dy6 = s[10]; + dx = dx1+dx2+dx3+dx4+dx5; + dy = dy1+dy2+dy3+dy4+dy5; + if (STBTT_fabs(dx) > STBTT_fabs(dy)) + dy6 = -dy; + else + dx6 = -dx; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + default: + return STBTT__CSERR("unimplemented"); + } + } break; + + default: + if (b0 != 255 && b0 != 28 && b0 < 32) + return STBTT__CSERR("reserved operator"); + + // push immediate + if (b0 == 255) { + f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; + } else { + stbtt__buf_skip(&b, -1); + f = (float)(stbtt_int16)stbtt__cff_int(&b); + } + if (sp >= 48) return STBTT__CSERR("push stack overflow"); + s[sp++] = f; + clear_stack = 0; + break; + } + if (clear_stack) sp = 0; + } + return STBTT__CSERR("no endchar"); + +#undef STBTT__CSERR +} + +static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + // runs the charstring twice, once to count and once to output (to avoid realloc) + stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); + stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); + if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { + *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); + output_ctx.pvertices = *pvertices; + if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { + STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); + return output_ctx.num_vertices; + } + } + *pvertices = NULL; + return 0; +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + stbtt__csctx c = STBTT__CSCTX_INIT(1); + int r = stbtt__run_charstring(info, glyph_index, &c); + if (x0) *x0 = r ? c.min_x : 0; + if (y0) *y0 = r ? c.min_y : 0; + if (x1) *x1 = r ? c.max_x : 0; + if (y1) *y1 = r ? c.max_y : 0; + return r ? c.num_vertices : 0; +} + +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + if (!info->cff.size) + return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); + else + return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); +} + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) +{ + stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); + if (glyph_index < numOfLongHorMetrics) { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); + } else { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); + } +} + +STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) +{ + stbtt_uint8 *data = info->data + info->kern; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + return ttUSHORT(data+10); +} + +STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length) +{ + stbtt_uint8 *data = info->data + info->kern; + int k, length; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + length = ttUSHORT(data+10); + if (table_length < length) + length = table_length; + + for (k = 0; k < length; k++) + { + table[k].glyph1 = ttUSHORT(data+18+(k*6)); + table[k].glyph2 = ttUSHORT(data+20+(k*6)); + table[k].advance = ttSHORT(data+22+(k*6)); + } + + return length; +} + +static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint8 *data = info->data + info->kern; + stbtt_uint32 needle, straw; + int l, r, m; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + l = 0; + r = ttUSHORT(data+10) - 1; + needle = glyph1 << 16 | glyph2; + while (l <= r) { + m = (l + r) >> 1; + straw = ttULONG(data+18+(m*6)); // note: unaligned read + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else + return ttSHORT(data+22+(m*6)); + } + return 0; +} + +static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) +{ + stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); + switch (coverageFormat) { + case 1: { + stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); + + // Binary search. + stbtt_int32 l=0, r=glyphCount-1, m; + int straw, needle=glyph; + while (l <= r) { + stbtt_uint8 *glyphArray = coverageTable + 4; + stbtt_uint16 glyphID; + m = (l + r) >> 1; + glyphID = ttUSHORT(glyphArray + 2 * m); + straw = glyphID; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + return m; + } + } + break; + } + + case 2: { + stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); + stbtt_uint8 *rangeArray = coverageTable + 4; + + // Binary search. + stbtt_int32 l=0, r=rangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *rangeRecord; + m = (l + r) >> 1; + rangeRecord = rangeArray + 6 * m; + strawStart = ttUSHORT(rangeRecord); + strawEnd = ttUSHORT(rangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else { + stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); + return startCoverageIndex + glyph - strawStart; + } + } + break; + } + + default: return -1; // unsupported + } + + return -1; +} + +static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) +{ + stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); + switch (classDefFormat) + { + case 1: { + stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); + stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); + stbtt_uint8 *classDef1ValueArray = classDefTable + 6; + + if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) + return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); + break; + } + + case 2: { + stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); + stbtt_uint8 *classRangeRecords = classDefTable + 4; + + // Binary search. + stbtt_int32 l=0, r=classRangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *classRangeRecord; + m = (l + r) >> 1; + classRangeRecord = classRangeRecords + 6 * m; + strawStart = ttUSHORT(classRangeRecord); + strawEnd = ttUSHORT(classRangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else + return (stbtt_int32)ttUSHORT(classRangeRecord + 4); + } + break; + } + + default: + return -1; // Unsupported definition type, return an error. + } + + // "All glyphs not assigned to a class fall into class 0". (OpenType spec) + return 0; +} + +// Define to STBTT_assert(x) if you want to break on unimplemented formats. +#define STBTT_GPOS_TODO_assert(x) + +static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint16 lookupListOffset; + stbtt_uint8 *lookupList; + stbtt_uint16 lookupCount; + stbtt_uint8 *data; + stbtt_int32 i, sti; + + if (!info->gpos) return 0; + + data = info->data + info->gpos; + + if (ttUSHORT(data+0) != 1) return 0; // Major version 1 + if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 + + lookupListOffset = ttUSHORT(data+8); + lookupList = data + lookupListOffset; + lookupCount = ttUSHORT(lookupList); + + for (i=0; i= pairSetCount) return 0; + + needle=glyph2; + r=pairValueCount-1; + l=0; + + // Binary search. + while (l <= r) { + stbtt_uint16 secondGlyph; + stbtt_uint8 *pairValue; + m = (l + r) >> 1; + pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; + secondGlyph = ttUSHORT(pairValue); + straw = secondGlyph; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + stbtt_int16 xAdvance = ttSHORT(pairValue + 2); + return xAdvance; + } + } + } else + return 0; + break; + } + + case 2: { + stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); + stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); + if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats? + stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); + stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); + int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); + int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); + + stbtt_uint16 class1Count = ttUSHORT(table + 12); + stbtt_uint16 class2Count = ttUSHORT(table + 14); + stbtt_uint8 *class1Records, *class2Records; + stbtt_int16 xAdvance; + + if (glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed + if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed + + class1Records = table + 16; + class2Records = class1Records + 2 * (glyph1class * class2Count); + xAdvance = ttSHORT(class2Records + 2 * glyph2class); + return xAdvance; + } else + return 0; + break; + } + + default: + return 0; // Unsupported position format + } + } + } + + return 0; +} + +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) +{ + int xAdvance = 0; + + if (info->gpos) + xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); + else if (info->kern) + xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); + + return xAdvance; +} + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) +{ + if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs + return 0; + return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); +} + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) +{ + stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); +} + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) +{ + if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); + if (descent) *descent = ttSHORT(info->data+info->hhea + 6); + if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); +} + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) +{ + int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); + if (!tab) + return 0; + if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); + if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); + if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); + return 1; +} + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) +{ + *x0 = ttSHORT(info->data + info->head + 36); + *y0 = ttSHORT(info->data + info->head + 38); + *x1 = ttSHORT(info->data + info->head + 40); + *y1 = ttSHORT(info->data + info->head + 42); +} + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) +{ + int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); + return (float) height / fheight; +} + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) +{ + int unitsPerEm = ttUSHORT(info->data + info->head + 18); + return pixels / unitsPerEm; +} + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) +{ + STBTT_free(v, info->userdata); +} + +STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl) +{ + int i; + stbtt_uint8 *data = info->data; + stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info); + + int numEntries = ttUSHORT(svg_doc_list); + stbtt_uint8 *svg_docs = svg_doc_list + 2; + + for(i=0; i= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2))) + return svg_doc; + } + return 0; +} + +STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg) +{ + stbtt_uint8 *data = info->data; + stbtt_uint8 *svg_doc; + + if (info->svg == 0) + return 0; + + svg_doc = stbtt_FindSVGDoc(info, gl); + if (svg_doc != NULL) { + *svg = (char *) data + info->svg + ttULONG(svg_doc + 4); + return ttULONG(svg_doc + 8); + } else { + return 0; + } +} + +STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg) +{ + return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg); +} + +////////////////////////////////////////////////////////////////////////////// +// +// antialiasing software rasterizer +// + +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning + if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { + // e.g. space character + if (ix0) *ix0 = 0; + if (iy0) *iy0 = 0; + if (ix1) *ix1 = 0; + if (iy1) *iy1 = 0; + } else { + // move to integral bboxes (treating pixels as little squares, what pixels get touched)? + if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); + if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); + if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); + if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); + } +} + +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); +} + +////////////////////////////////////////////////////////////////////////////// +// +// Rasterizer + +typedef struct stbtt__hheap_chunk +{ + struct stbtt__hheap_chunk *next; +} stbtt__hheap_chunk; + +typedef struct stbtt__hheap +{ + struct stbtt__hheap_chunk *head; + void *first_free; + int num_remaining_in_head_chunk; +} stbtt__hheap; + +static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) +{ + if (hh->first_free) { + void *p = hh->first_free; + hh->first_free = * (void **) p; + return p; + } else { + if (hh->num_remaining_in_head_chunk == 0) { + int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); + stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); + if (c == NULL) + return NULL; + c->next = hh->head; + hh->head = c; + hh->num_remaining_in_head_chunk = count; + } + --hh->num_remaining_in_head_chunk; + return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; + } +} + +static void stbtt__hheap_free(stbtt__hheap *hh, void *p) +{ + *(void **) p = hh->first_free; + hh->first_free = p; +} + +static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) +{ + stbtt__hheap_chunk *c = hh->head; + while (c) { + stbtt__hheap_chunk *n = c->next; + STBTT_free(c, userdata); + c = n; + } +} + +typedef struct stbtt__edge { + float x0,y0, x1,y1; + int invert; +} stbtt__edge; + + +typedef struct stbtt__active_edge +{ + struct stbtt__active_edge *next; + #if STBTT_RASTERIZER_VERSION==1 + int x,dx; + float ey; + int direction; + #elif STBTT_RASTERIZER_VERSION==2 + float fx,fdx,fdy; + float direction; + float sy; + float ey; + #else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" + #endif +} stbtt__active_edge; + +#if STBTT_RASTERIZER_VERSION == 1 +#define STBTT_FIXSHIFT 10 +#define STBTT_FIX (1 << STBTT_FIXSHIFT) +#define STBTT_FIXMASK (STBTT_FIX-1) + +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + if (!z) return z; + + // round dx down to avoid overshooting + if (dxdy < 0) + z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); + else + z->dx = STBTT_ifloor(STBTT_FIX * dxdy); + + z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount + z->x -= off_x * STBTT_FIX; + + z->ey = e->y1; + z->next = 0; + z->direction = e->invert ? 1 : -1; + return z; +} +#elif STBTT_RASTERIZER_VERSION == 2 +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + //STBTT_assert(e->y0 <= start_point); + if (!z) return z; + z->fdx = dxdy; + z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; + z->fx = e->x0 + dxdy * (start_point - e->y0); + z->fx -= off_x; + z->direction = e->invert ? 1.0f : -1.0f; + z->sy = e->y0; + z->ey = e->y1; + z->next = 0; + return z; +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#if STBTT_RASTERIZER_VERSION == 1 +// note: this routine clips fills that extend off the edges... ideally this +// wouldn't happen, but it could happen if the truetype glyph bounding boxes +// are wrong, or if the user supplies a too-small bitmap +static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) +{ + // non-zero winding fill + int x0=0, w=0; + + while (e) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w += e->direction; + } else { + int x1 = e->x; w += e->direction; + // if we went to zero, we need to draw + if (w == 0) { + int i = x0 >> STBTT_FIXSHIFT; + int j = x1 >> STBTT_FIXSHIFT; + + if (i < len && j >= 0) { + if (i == j) { + // x0,x1 are the same pixel, so compute combined coverage + scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); + } else { + if (i >= 0) // add antialiasing for x0 + scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); + else + i = -1; // clip + + if (j < len) // add antialiasing for x1 + scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); + else + j = len; // clip + + for (++i; i < j; ++i) // fill pixels between x0 and x1 + scanline[i] = scanline[i] + (stbtt_uint8) max_weight; + } + } + } + } + + e = e->next; + } +} + +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0; + int max_weight = (255 / vsubsample); // weight per vertical scanline + int s; // vertical subsample index + unsigned char scanline_data[512], *scanline; + + if (result->w > 512) + scanline = (unsigned char *) STBTT_malloc(result->w, userdata); + else + scanline = scanline_data; + + y = off_y * vsubsample; + e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; + + while (j < result->h) { + STBTT_memset(scanline, 0, result->w); + for (s=0; s < vsubsample; ++s) { + // find center of pixel for this scanline + float scan_y = y + 0.5f; + stbtt__active_edge **step = &active; + + // update all active edges; + // remove all active edges that terminate before the center of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + z->x += z->dx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + } + + // resort the list if needed + for(;;) { + int changed=0; + step = &active; + while (*step && (*step)->next) { + if ((*step)->x > (*step)->next->x) { + stbtt__active_edge *t = *step; + stbtt__active_edge *q = t->next; + + t->next = q->next; + q->next = t; + *step = q; + changed = 1; + } + step = &(*step)->next; + } + if (!changed) break; + } + + // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline + while (e->y0 <= scan_y) { + if (e->y1 > scan_y) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); + if (z != NULL) { + // find insertion point + if (active == NULL) + active = z; + else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + stbtt__active_edge *p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } + } + } + ++e; + } + + // now process all active edges in XOR fashion + if (active) + stbtt__fill_active_edges(scanline, result->w, active, max_weight); + + ++y; + } + STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} + +#elif STBTT_RASTERIZER_VERSION == 2 + +// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +// (i.e. it has already been clipped to those) +static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) +{ + if (y0 == y1) return; + STBTT_assert(y0 < y1); + STBTT_assert(e->sy <= e->ey); + if (y0 > e->ey) return; + if (y1 < e->sy) return; + if (y0 < e->sy) { + x0 += (x1-x0) * (e->sy - y0) / (y1-y0); + y0 = e->sy; + } + if (y1 > e->ey) { + x1 += (x1-x0) * (e->ey - y1) / (y1-y0); + y1 = e->ey; + } + + if (x0 == x) + STBTT_assert(x1 <= x+1); + else if (x0 == x+1) + STBTT_assert(x1 >= x); + else if (x0 <= x) + STBTT_assert(x1 <= x); + else if (x0 >= x+1) + STBTT_assert(x1 >= x+1); + else + STBTT_assert(x1 >= x && x1 <= x+1); + + if (x0 <= x && x1 <= x) + scanline[x] += e->direction * (y1-y0); + else if (x0 >= x+1 && x1 >= x+1) + ; + else { + STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); + scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position + } +} + +static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width) +{ + STBTT_assert(top_width >= 0); + STBTT_assert(bottom_width >= 0); + return (top_width + bottom_width) / 2.0f * height; +} + +static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1) +{ + return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0); +} + +static float stbtt__sized_triangle_area(float height, float width) +{ + return height * width / 2; +} + +static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) +{ + float y_bottom = y_top+1; + + while (e) { + // brute force every pixel + + // compute intersection points with top & bottom + STBTT_assert(e->ey >= y_top); + + if (e->fdx == 0) { + float x0 = e->fx; + if (x0 < len) { + if (x0 >= 0) { + stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); + stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); + } else { + stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); + } + } + } else { + float x0 = e->fx; + float dx = e->fdx; + float xb = x0 + dx; + float x_top, x_bottom; + float sy0,sy1; + float dy = e->fdy; + STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); + + // compute endpoints of line segment clipped to this scanline (if the + // line segment starts on this scanline. x0 is the intersection of the + // line with y_top, but that may be off the line segment. + if (e->sy > y_top) { + x_top = x0 + dx * (e->sy - y_top); + sy0 = e->sy; + } else { + x_top = x0; + sy0 = y_top; + } + if (e->ey < y_bottom) { + x_bottom = x0 + dx * (e->ey - y_top); + sy1 = e->ey; + } else { + x_bottom = xb; + sy1 = y_bottom; + } + + if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { + // from here on, we don't have to range check x values + + if ((int) x_top == (int) x_bottom) { + float height; + // simple case, only spans one pixel + int x = (int) x_top; + height = (sy1 - sy0) * e->direction; + STBTT_assert(x >= 0 && x < len); + scanline[x] += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f); + scanline_fill[x] += height; // everything right of this pixel is filled + } else { + int x,x1,x2; + float y_crossing, y_final, step, sign, area; + // covers 2+ pixels + if (x_top > x_bottom) { + // flip scanline vertically; signed area is the same + float t; + sy0 = y_bottom - (sy0 - y_top); + sy1 = y_bottom - (sy1 - y_top); + t = sy0, sy0 = sy1, sy1 = t; + t = x_bottom, x_bottom = x_top, x_top = t; + dx = -dx; + dy = -dy; + t = x0, x0 = xb, xb = t; + } + STBTT_assert(dy >= 0); + STBTT_assert(dx >= 0); + + x1 = (int) x_top; + x2 = (int) x_bottom; + // compute intersection with y axis at x1+1 + y_crossing = y_top + dy * (x1+1 - x0); + + // compute intersection with y axis at x2 + y_final = y_top + dy * (x2 - x0); + + // x1 x_top x2 x_bottom + // y_top +------|-----+------------+------------+--------|---+------------+ + // | | | | | | + // | | | | | | + // sy0 | Txxxxx|............|............|............|............| + // y_crossing | *xxxxx.......|............|............|............| + // | | xxxxx..|............|............|............| + // | | /- xx*xxxx........|............|............| + // | | dy < | xxxxxx..|............|............| + // y_final | | \- | xx*xxx.........|............| + // sy1 | | | | xxxxxB...|............| + // | | | | | | + // | | | | | | + // y_bottom +------------+------------+------------+------------+------------+ + // + // goal is to measure the area covered by '.' in each pixel + + // if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 + // @TODO: maybe test against sy1 rather than y_bottom? + if (y_crossing > y_bottom) + y_crossing = y_bottom; + + sign = e->direction; + + // area of the rectangle covered from sy0..y_crossing + area = sign * (y_crossing-sy0); + + // area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing) + scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top); + + // check if final y_crossing is blown up; no test case for this + if (y_final > y_bottom) { + int denom = (x2 - (x1+1)); + y_final = y_bottom; + if (denom != 0) { // [DEAR IMGUI] Avoid div by zero (https://github.com/nothings/stb/issues/1316) + dy = (y_final - y_crossing ) / denom; // if denom=0, y_final = y_crossing, so y_final <= y_bottom + } + } + + // in second pixel, area covered by line segment found in first pixel + // is always a rectangle 1 wide * the height of that line segment; this + // is exactly what the variable 'area' stores. it also gets a contribution + // from the line segment within it. the THIRD pixel will get the first + // pixel's rectangle contribution, the second pixel's rectangle contribution, + // and its own contribution. the 'own contribution' is the same in every pixel except + // the leftmost and rightmost, a trapezoid that slides down in each pixel. + // the second pixel's contribution to the third pixel will be the + // rectangle 1 wide times the height change in the second pixel, which is dy. + + step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x, + // which multiplied by 1-pixel-width is how much pixel area changes for each step in x + // so the area advances by 'step' every time + + for (x = x1+1; x < x2; ++x) { + scanline[x] += area + step/2; // area of trapezoid is 1*step/2 + area += step; + } + STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down + STBTT_assert(sy1 > y_final-0.01f); + + // area covered in the last pixel is the rectangle from all the pixels to the left, + // plus the trapezoid filled by the line segment in this pixel all the way to the right edge + scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f); + + // the rest of the line is filled based on the total height of the line segment in this pixel + scanline_fill[x2] += sign * (sy1-sy0); + } + } else { + // if edge goes outside of box we're drawing, we require + // clipping logic. since this does not match the intended use + // of this library, we use a different, very slow brute + // force implementation + // note though that this does happen some of the time because + // x_top and x_bottom can be extrapolated at the top & bottom of + // the shape and actually lie outside the bounding box + int x; + for (x=0; x < len; ++x) { + // cases: + // + // there can be up to two intersections with the pixel. any intersection + // with left or right edges can be handled by splitting into two (or three) + // regions. intersections with top & bottom do not necessitate case-wise logic. + // + // the old way of doing this found the intersections with the left & right edges, + // then used some simple logic to produce up to three segments in sorted order + // from top-to-bottom. however, this had a problem: if an x edge was epsilon + // across the x border, then the corresponding y position might not be distinct + // from the other y segment, and it might ignored as an empty segment. to avoid + // that, we need to explicitly produce segments based on x positions. + + // rename variables to clearly-defined pairs + float y0 = y_top; + float x1 = (float) (x); + float x2 = (float) (x+1); + float x3 = xb; + float y3 = y_bottom; + + // x = e->x + e->dx * (y-y_top) + // (y-y_top) = (x - e->x) / e->dx + // y = (x - e->x) / e->dx + y_top + float y1 = (x - x0) / dx + y_top; + float y2 = (x+1 - x0) / dx + y_top; + + if (x0 < x1 && x3 > x2) { // three segments descending down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x1 && x0 > x2) { // three segments descending down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else { // one segment + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); + } + } + } + } + e = e->next; + } +} + +// directly AA rasterize edges w/o supersampling +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0, i; + float scanline_data[129], *scanline, *scanline2; + + STBTT__NOTUSED(vsubsample); + + if (result->w > 64) + scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); + else + scanline = scanline_data; + + scanline2 = scanline + result->w; + + y = off_y; + e[n].y0 = (float) (off_y + result->h) + 1; + + while (j < result->h) { + // find center of pixel for this scanline + float scan_y_top = y + 0.0f; + float scan_y_bottom = y + 1.0f; + stbtt__active_edge **step = &active; + + STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); + STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); + + // update all active edges; + // remove all active edges that terminate before the top of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y_top) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + step = &((*step)->next); // advance through list + } + } + + // insert all edges that start before the bottom of this scanline + while (e->y0 <= scan_y_bottom) { + if (e->y0 != e->y1) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); + if (z != NULL) { + if (j == 0 && off_y != 0) { + if (z->ey < scan_y_top) { + // this can happen due to subpixel positioning and some kind of fp rounding error i think + z->ey = scan_y_top; + } + } + STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds + // insert at front + z->next = active; + active = z; + } + } + ++e; + } + + // now process all active edges + if (active) + stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); + + { + float sum = 0; + for (i=0; i < result->w; ++i) { + float k; + int m; + sum += scanline2[i]; + k = scanline[i] + sum; + k = (float) STBTT_fabs(k)*255 + 0.5f; + m = (int) k; + if (m > 255) m = 255; + result->pixels[j*result->stride + i] = (unsigned char) m; + } + } + // advance all the edges + step = &active; + while (*step) { + stbtt__active_edge *z = *step; + z->fx += z->fdx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + + ++y; + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) + +static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) +{ + int i,j; + for (i=1; i < n; ++i) { + stbtt__edge t = p[i], *a = &t; + j = i; + while (j > 0) { + stbtt__edge *b = &p[j-1]; + int c = STBTT__COMPARE(a,b); + if (!c) break; + p[j] = p[j-1]; + --j; + } + if (i != j) + p[j] = t; + } +} + +static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) +{ + /* threshold for transitioning to insertion sort */ + while (n > 12) { + stbtt__edge t; + int c01,c12,c,m,i,j; + + /* compute median of three */ + m = n >> 1; + c01 = STBTT__COMPARE(&p[0],&p[m]); + c12 = STBTT__COMPARE(&p[m],&p[n-1]); + /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ + if (c01 != c12) { + /* otherwise, we'll need to swap something else to middle */ + int z; + c = STBTT__COMPARE(&p[0],&p[n-1]); + /* 0>mid && midn => n; 0 0 */ + /* 0n: 0>n => 0; 0 n */ + z = (c == c12) ? 0 : n-1; + t = p[z]; + p[z] = p[m]; + p[m] = t; + } + /* now p[m] is the median-of-three */ + /* swap it to the beginning so it won't move around */ + t = p[0]; + p[0] = p[m]; + p[m] = t; + + /* partition loop */ + i=1; + j=n-1; + for(;;) { + /* handling of equality is crucial here */ + /* for sentinels & efficiency with duplicates */ + for (;;++i) { + if (!STBTT__COMPARE(&p[i], &p[0])) break; + } + for (;;--j) { + if (!STBTT__COMPARE(&p[0], &p[j])) break; + } + /* make sure we haven't crossed */ + if (i >= j) break; + t = p[i]; + p[i] = p[j]; + p[j] = t; + + ++i; + --j; + } + /* recurse on smaller side, iterate on larger */ + if (j < (n-i)) { + stbtt__sort_edges_quicksort(p,j); + p = p+i; + n = n-i; + } else { + stbtt__sort_edges_quicksort(p+i, n-i); + n = j; + } + } +} + +static void stbtt__sort_edges(stbtt__edge *p, int n) +{ + stbtt__sort_edges_quicksort(p, n); + stbtt__sort_edges_ins_sort(p, n); +} + +typedef struct +{ + float x,y; +} stbtt__point; + +static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) +{ + float y_scale_inv = invert ? -scale_y : scale_y; + stbtt__edge *e; + int n,i,j,k,m; +#if STBTT_RASTERIZER_VERSION == 1 + int vsubsample = result->h < 8 ? 15 : 5; +#elif STBTT_RASTERIZER_VERSION == 2 + int vsubsample = 1; +#else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + // vsubsample should divide 255 evenly; otherwise we won't reach full opacity + + // now we have to blow out the windings into explicit edge lists + n = 0; + for (i=0; i < windings; ++i) + n += wcount[i]; + + e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel + if (e == 0) return; + n = 0; + + m=0; + for (i=0; i < windings; ++i) { + stbtt__point *p = pts + m; + m += wcount[i]; + j = wcount[i]-1; + for (k=0; k < wcount[i]; j=k++) { + int a=k,b=j; + // skip the edge if horizontal + if (p[j].y == p[k].y) + continue; + // add edge from j to k to the list + e[n].invert = 0; + if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { + e[n].invert = 1; + a=j,b=k; + } + e[n].x0 = p[a].x * scale_x + shift_x; + e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; + e[n].x1 = p[b].x * scale_x + shift_x; + e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; + ++n; + } + } + + // now sort the edges by their highest point (should snap to integer, and then by x) + //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + stbtt__sort_edges(e, n); + + // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule + stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); + + STBTT_free(e, userdata); +} + +static void stbtt__add_point(stbtt__point *points, int n, float x, float y) +{ + if (!points) return; // during first pass, it's unallocated + points[n].x = x; + points[n].y = y; +} + +// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching +static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) +{ + // midpoint + float mx = (x0 + 2*x1 + x2)/4; + float my = (y0 + 2*y1 + y2)/4; + // versus directly drawn line + float dx = (x0+x2)/2 - mx; + float dy = (y0+y2)/2 - my; + if (n > 16) // 65536 segments on one curve better be enough! + return 1; + if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA + stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x2,y2); + *num_points = *num_points+1; + } + return 1; +} + +static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) +{ + // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough + float dx0 = x1-x0; + float dy0 = y1-y0; + float dx1 = x2-x1; + float dy1 = y2-y1; + float dx2 = x3-x2; + float dy2 = y3-y2; + float dx = x3-x0; + float dy = y3-y0; + float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); + float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); + float flatness_squared = longlen*longlen-shortlen*shortlen; + + if (n > 16) // 65536 segments on one curve better be enough! + return; + + if (flatness_squared > objspace_flatness_squared) { + float x01 = (x0+x1)/2; + float y01 = (y0+y1)/2; + float x12 = (x1+x2)/2; + float y12 = (y1+y2)/2; + float x23 = (x2+x3)/2; + float y23 = (y2+y3)/2; + + float xa = (x01+x12)/2; + float ya = (y01+y12)/2; + float xb = (x12+x23)/2; + float yb = (y12+y23)/2; + + float mx = (xa+xb)/2; + float my = (ya+yb)/2; + + stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x3,y3); + *num_points = *num_points+1; + } +} + +// returns number of contours +static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) +{ + stbtt__point *points=0; + int num_points=0; + + float objspace_flatness_squared = objspace_flatness * objspace_flatness; + int i,n=0,start=0, pass; + + // count how many "moves" there are to get the contour count + for (i=0; i < num_verts; ++i) + if (vertices[i].type == STBTT_vmove) + ++n; + + *num_contours = n; + if (n == 0) return 0; + + *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); + + if (*contour_lengths == 0) { + *num_contours = 0; + return 0; + } + + // make two passes through the points so we don't need to realloc + for (pass=0; pass < 2; ++pass) { + float x=0,y=0; + if (pass == 1) { + points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); + if (points == NULL) goto error; + } + num_points = 0; + n= -1; + for (i=0; i < num_verts; ++i) { + switch (vertices[i].type) { + case STBTT_vmove: + // start the next contour + if (n >= 0) + (*contour_lengths)[n] = num_points - start; + ++n; + start = num_points; + + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x,y); + break; + case STBTT_vline: + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x, y); + break; + case STBTT_vcurve: + stbtt__tesselate_curve(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + case STBTT_vcubic: + stbtt__tesselate_cubic(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].cx1, vertices[i].cy1, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + } + } + (*contour_lengths)[n] = num_points - start; + } + + return points; +error: + STBTT_free(points, userdata); + STBTT_free(*contour_lengths, userdata); + *contour_lengths = 0; + *num_contours = 0; + return NULL; +} + +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) +{ + float scale = scale_x > scale_y ? scale_y : scale_x; + int winding_count = 0; + int *winding_lengths = NULL; + stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); + if (windings) { + stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); + STBTT_free(winding_lengths, userdata); + STBTT_free(windings, userdata); + } +} + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + int ix0,iy0,ix1,iy1; + stbtt__bitmap gbm; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + + if (scale_x == 0) scale_x = scale_y; + if (scale_y == 0) { + if (scale_x == 0) { + STBTT_free(vertices, info->userdata); + return NULL; + } + scale_y = scale_x; + } + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); + + // now we get the size + gbm.w = (ix1 - ix0); + gbm.h = (iy1 - iy0); + gbm.pixels = NULL; // in case we error + + if (width ) *width = gbm.w; + if (height) *height = gbm.h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + if (gbm.w && gbm.h) { + gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); + if (gbm.pixels) { + gbm.stride = gbm.w; + + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); + } + } + STBTT_free(vertices, info->userdata); + return gbm.pixels; +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) +{ + int ix0,iy0; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + stbtt__bitmap gbm; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); + gbm.pixels = output; + gbm.w = out_w; + gbm.h = out_h; + gbm.stride = out_stride; + + if (gbm.w && gbm.h) + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); + + STBTT_free(vertices, info->userdata); +} + +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) +{ + stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); +} + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-CRAPPY packing to keep source code small + +static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata) +{ + float scale; + int x,y,bottom_y, i; + stbtt_fontinfo f; + f.userdata = NULL; + if (!stbtt_InitFont(&f, data, offset)) + return -1; + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + x=y=1; + bottom_y = 1; + + scale = stbtt_ScaleForPixelHeight(&f, pixel_height); + + for (i=0; i < num_chars; ++i) { + int advance, lsb, x0,y0,x1,y1,gw,gh; + int g = stbtt_FindGlyphIndex(&f, first_char + i); + stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); + stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); + gw = x1-x0; + gh = y1-y0; + if (x + gw + 1 >= pw) + y = bottom_y, x = 1; // advance to next row + if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row + return -i; + STBTT_assert(x+gw < pw); + STBTT_assert(y+gh < ph); + stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); + chardata[i].x0 = (stbtt_int16) x; + chardata[i].y0 = (stbtt_int16) y; + chardata[i].x1 = (stbtt_int16) (x + gw); + chardata[i].y1 = (stbtt_int16) (y + gh); + chardata[i].xadvance = scale * advance; + chardata[i].xoff = (float) x0; + chardata[i].yoff = (float) y0; + x = x + gw + 1; + if (y+gh+1 > bottom_y) + bottom_y = y+gh+1; + } + return bottom_y; +} + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) +{ + float d3d_bias = opengl_fillrule ? 0 : -0.5f; + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_bakedchar *b = chardata + char_index; + int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); + int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); + + q->x0 = round_x + d3d_bias; + q->y0 = round_y + d3d_bias; + q->x1 = round_x + b->x1 - b->x0 + d3d_bias; + q->y1 = round_y + b->y1 - b->y0 + d3d_bias; + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// rectangle packing replacement routines if you don't have stb_rect_pack.h +// + +#ifndef STB_RECT_PACK_VERSION + +typedef int stbrp_coord; + +//////////////////////////////////////////////////////////////////////////////////// +// // +// // +// COMPILER WARNING ?!?!? // +// // +// // +// if you get a compile warning due to these symbols being defined more than // +// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // +// // +//////////////////////////////////////////////////////////////////////////////////// + +typedef struct +{ + int width,height; + int x,y,bottom_y; +} stbrp_context; + +typedef struct +{ + unsigned char x; +} stbrp_node; + +struct stbrp_rect +{ + stbrp_coord x,y; + int id,w,h,was_packed; +}; + +static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) +{ + con->width = pw; + con->height = ph; + con->x = 0; + con->y = 0; + con->bottom_y = 0; + STBTT__NOTUSED(nodes); + STBTT__NOTUSED(num_nodes); +} + +static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) +{ + int i; + for (i=0; i < num_rects; ++i) { + if (con->x + rects[i].w > con->width) { + con->x = 0; + con->y = con->bottom_y; + } + if (con->y + rects[i].h > con->height) + break; + rects[i].x = con->x; + rects[i].y = con->y; + rects[i].was_packed = 1; + con->x += rects[i].w; + if (con->y + rects[i].h > con->bottom_y) + con->bottom_y = con->y + rects[i].h; + } + for ( ; i < num_rects; ++i) + rects[i].was_packed = 0; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If +// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) +{ + stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); + int num_nodes = pw - padding; + stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); + + if (context == NULL || nodes == NULL) { + if (context != NULL) STBTT_free(context, alloc_context); + if (nodes != NULL) STBTT_free(nodes , alloc_context); + return 0; + } + + spc->user_allocator_context = alloc_context; + spc->width = pw; + spc->height = ph; + spc->pixels = pixels; + spc->pack_info = context; + spc->nodes = nodes; + spc->padding = padding; + spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; + spc->h_oversample = 1; + spc->v_oversample = 1; + spc->skip_missing = 0; + + stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); + + if (pixels) + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + + return 1; +} + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) +{ + STBTT_free(spc->nodes , spc->user_allocator_context); + STBTT_free(spc->pack_info, spc->user_allocator_context); +} + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) +{ + STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); + STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); + if (h_oversample <= STBTT_MAX_OVERSAMPLE) + spc->h_oversample = h_oversample; + if (v_oversample <= STBTT_MAX_OVERSAMPLE) + spc->v_oversample = v_oversample; +} + +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) +{ + spc->skip_missing = skip; +} + +#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) + +static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_w = w - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < h; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < w; ++i) { + STBTT_assert(pixels[i] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i] = (unsigned char) (total / kernel_width); + } + + pixels += stride_in_bytes; + } +} + +static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_h = h - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < w; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < h; ++i) { + STBTT_assert(pixels[i*stride_in_bytes] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + + pixels += 1; + } +} + +static float stbtt__oversample_shift(int oversample) +{ + if (!oversample) + return 0.0f; + + // The prefilter is a box filter of width "oversample", + // which shifts phase by (oversample - 1)/2 pixels in + // oversampled space. We want to shift in the opposite + // direction to counter this. + return (float)-(oversample - 1) / (2.0f * (float)oversample); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k; + int missing_glyph_added = 0; + + k=0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + ranges[i].h_oversample = (unsigned char) spc->h_oversample; + ranges[i].v_oversample = (unsigned char) spc->v_oversample; + for (j=0; j < ranges[i].num_chars; ++j) { + int x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) { + rects[k].w = rects[k].h = 0; + } else { + stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + &x0,&y0,&x1,&y1); + rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); + rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + if (glyph == 0) + missing_glyph_added = 1; + } + ++k; + } + } + + return k; +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, + output, + out_w - (prefilter_x - 1), + out_h - (prefilter_y - 1), + out_stride, + scale_x, + scale_y, + shift_x, + shift_y, + glyph); + + if (prefilter_x > 1) + stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); + + if (prefilter_y > 1) + stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); + + *sub_x = stbtt__oversample_shift(prefilter_x); + *sub_y = stbtt__oversample_shift(prefilter_y); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k, missing_glyph = -1, return_value = 1; + + // save current values + int old_h_over = spc->h_oversample; + int old_v_over = spc->v_oversample; + + k = 0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + float recip_h,recip_v,sub_x,sub_y; + spc->h_oversample = ranges[i].h_oversample; + spc->v_oversample = ranges[i].v_oversample; + recip_h = 1.0f / spc->h_oversample; + recip_v = 1.0f / spc->v_oversample; + sub_x = stbtt__oversample_shift(spc->h_oversample); + sub_y = stbtt__oversample_shift(spc->v_oversample); + for (j=0; j < ranges[i].num_chars; ++j) { + stbrp_rect *r = &rects[k]; + if (r->was_packed && r->w != 0 && r->h != 0) { + stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; + int advance, lsb, x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + stbrp_coord pad = (stbrp_coord) spc->padding; + + // pad on left and top + r->x += pad; + r->y += pad; + r->w -= pad; + r->h -= pad; + stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); + stbtt_GetGlyphBitmapBox(info, glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + &x0,&y0,&x1,&y1); + stbtt_MakeGlyphBitmapSubpixel(info, + spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w - spc->h_oversample+1, + r->h - spc->v_oversample+1, + spc->stride_in_bytes, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + glyph); + + if (spc->h_oversample > 1) + stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->h_oversample); + + if (spc->v_oversample > 1) + stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->v_oversample); + + bc->x0 = (stbtt_int16) r->x; + bc->y0 = (stbtt_int16) r->y; + bc->x1 = (stbtt_int16) (r->x + r->w); + bc->y1 = (stbtt_int16) (r->y + r->h); + bc->xadvance = scale * advance; + bc->xoff = (float) x0 * recip_h + sub_x; + bc->yoff = (float) y0 * recip_v + sub_y; + bc->xoff2 = (x0 + r->w) * recip_h + sub_x; + bc->yoff2 = (y0 + r->h) * recip_v + sub_y; + + if (glyph == 0) + missing_glyph = j; + } else if (spc->skip_missing) { + return_value = 0; + } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { + ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; + } else { + return_value = 0; // if any fail, report failure + } + + ++k; + } + } + + // restore original values + spc->h_oversample = old_h_over; + spc->v_oversample = old_v_over; + + return return_value; +} + +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) +{ + stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); +} + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) +{ + stbtt_fontinfo info; + int i, j, n, return_value; // [DEAR IMGUI] removed = 1; + //stbrp_context *context = (stbrp_context *) spc->pack_info; + stbrp_rect *rects; + + // flag all characters as NOT packed + for (i=0; i < num_ranges; ++i) + for (j=0; j < ranges[i].num_chars; ++j) + ranges[i].chardata_for_range[j].x0 = + ranges[i].chardata_for_range[j].y0 = + ranges[i].chardata_for_range[j].x1 = + ranges[i].chardata_for_range[j].y1 = 0; + + n = 0; + for (i=0; i < num_ranges; ++i) + n += ranges[i].num_chars; + + rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); + if (rects == NULL) + return 0; + + info.userdata = spc->user_allocator_context; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); + + n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); + + stbtt_PackFontRangesPackRects(spc, rects, n); + + return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); + + STBTT_free(rects, spc->user_allocator_context); + return return_value; +} + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) +{ + stbtt_pack_range range; + range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; + range.array_of_unicode_codepoints = NULL; + range.num_chars = num_chars_in_range; + range.chardata_for_range = chardata_for_range; + range.font_size = font_size; + return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); +} + +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) +{ + int i_ascent, i_descent, i_lineGap; + float scale; + stbtt_fontinfo info; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); + scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); + stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); + *ascent = (float) i_ascent * scale; + *descent = (float) i_descent * scale; + *lineGap = (float) i_lineGap * scale; +} + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) +{ + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_packedchar *b = chardata + char_index; + + if (align_to_integer) { + float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); + float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); + q->x0 = x; + q->y0 = y; + q->x1 = x + b->xoff2 - b->xoff; + q->y1 = y + b->yoff2 - b->yoff; + } else { + q->x0 = *xpos + b->xoff; + q->y0 = *ypos + b->yoff; + q->x1 = *xpos + b->xoff2; + q->y1 = *ypos + b->yoff2; + } + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// sdf computation +// + +#define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) +#define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) + +static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) +{ + float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; + float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; + float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; + float roperp = orig[1]*ray[0] - orig[0]*ray[1]; + + float a = q0perp - 2*q1perp + q2perp; + float b = q1perp - q0perp; + float c = q0perp - roperp; + + float s0 = 0., s1 = 0.; + int num_s = 0; + + if (a != 0.0) { + float discr = b*b - a*c; + if (discr > 0.0) { + float rcpna = -1 / a; + float d = (float) STBTT_sqrt(discr); + s0 = (b+d) * rcpna; + s1 = (b-d) * rcpna; + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { + if (num_s == 0) s0 = s1; + ++num_s; + } + } + } else { + // 2*b*s + c = 0 + // s = -c / (2*b) + s0 = c / (-2 * b); + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + } + + if (num_s == 0) + return 0; + else { + float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); + float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; + + float q0d = q0[0]*rayn_x + q0[1]*rayn_y; + float q1d = q1[0]*rayn_x + q1[1]*rayn_y; + float q2d = q2[0]*rayn_x + q2[1]*rayn_y; + float rod = orig[0]*rayn_x + orig[1]*rayn_y; + + float q10d = q1d - q0d; + float q20d = q2d - q0d; + float q0rd = q0d - rod; + + hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; + hits[0][1] = a*s0+b; + + if (num_s > 1) { + hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; + hits[1][1] = a*s1+b; + return 2; + } else { + return 1; + } + } +} + +static int equal(float *a, float *b) +{ + return (a[0] == b[0] && a[1] == b[1]); +} + +static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) +{ + int i; + float orig[2], ray[2] = { 1, 0 }; + float y_frac; + int winding = 0; + + // make sure y never passes through a vertex of the shape + y_frac = (float) STBTT_fmod(y, 1.0f); + if (y_frac < 0.01f) + y += 0.01f; + else if (y_frac > 0.99f) + y -= 0.01f; + + orig[0] = x; + orig[1] = y; + + // test a ray from (-infinity,y) to (x,y) + for (i=0; i < nverts; ++i) { + if (verts[i].type == STBTT_vline) { + int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; + int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } + if (verts[i].type == STBTT_vcurve) { + int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; + int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; + int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; + int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); + int by = STBTT_max(y0,STBTT_max(y1,y2)); + if (y > ay && y < by && x > ax) { + float q0[2],q1[2],q2[2]; + float hits[2][2]; + q0[0] = (float)x0; + q0[1] = (float)y0; + q1[0] = (float)x1; + q1[1] = (float)y1; + q2[0] = (float)x2; + q2[1] = (float)y2; + if (equal(q0,q1) || equal(q1,q2)) { + x0 = (int)verts[i-1].x; + y0 = (int)verts[i-1].y; + x1 = (int)verts[i ].x; + y1 = (int)verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } else { + int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); + if (num_hits >= 1) + if (hits[0][0] < 0) + winding += (hits[0][1] < 0 ? -1 : 1); + if (num_hits >= 2) + if (hits[1][0] < 0) + winding += (hits[1][1] < 0 ? -1 : 1); + } + } + } + } + return winding; +} + +static float stbtt__cuberoot( float x ) +{ + if (x<0) + return -(float) STBTT_pow(-x,1.0f/3.0f); + else + return (float) STBTT_pow( x,1.0f/3.0f); +} + +// x^3 + a*x^2 + b*x + c = 0 +static int stbtt__solve_cubic(float a, float b, float c, float* r) +{ + float s = -a / 3; + float p = b - a*a / 3; + float q = a * (2*a*a - 9*b) / 27 + c; + float p3 = p*p*p; + float d = q*q + 4*p3 / 27; + if (d >= 0) { + float z = (float) STBTT_sqrt(d); + float u = (-q + z) / 2; + float v = (-q - z) / 2; + u = stbtt__cuberoot(u); + v = stbtt__cuberoot(v); + r[0] = s + u + v; + return 1; + } else { + float u = (float) STBTT_sqrt(-p/3); + float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative + float m = (float) STBTT_cos(v); + float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; + r[0] = s + u * 2 * m; + r[1] = s - u * (m + n); + r[2] = s - u * (m - n); + + //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? + //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); + //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); + return 3; + } +} + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + float scale_x = scale, scale_y = scale; + int ix0,iy0,ix1,iy1; + int w,h; + unsigned char *data; + + if (scale == 0) return NULL; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); + + // if empty, return NULL + if (ix0 == ix1 || iy0 == iy1) + return NULL; + + ix0 -= padding; + iy0 -= padding; + ix1 += padding; + iy1 += padding; + + w = (ix1 - ix0); + h = (iy1 - iy0); + + if (width ) *width = w; + if (height) *height = h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + // invert for y-downwards bitmaps + scale_y = -scale_y; + + { + int x,y,i,j; + float *precompute; + stbtt_vertex *verts; + int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); + data = (unsigned char *) STBTT_malloc(w * h, info->userdata); + precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); + + for (i=0,j=num_verts-1; i < num_verts; j=i++) { + if (verts[i].type == STBTT_vline) { + float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; + float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; + float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); + precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; + } else if (verts[i].type == STBTT_vcurve) { + float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; + float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; + float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; + float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; + float len2 = bx*bx + by*by; + if (len2 != 0.0f) + precompute[i] = 1.0f / (bx*bx + by*by); + else + precompute[i] = 0.0f; + } else + precompute[i] = 0.0f; + } + + for (y=iy0; y < iy1; ++y) { + for (x=ix0; x < ix1; ++x) { + float val; + float min_dist = 999999.0f; + float sx = (float) x + 0.5f; + float sy = (float) y + 0.5f; + float x_gspace = (sx / scale_x); + float y_gspace = (sy / scale_y); + + int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path + + for (i=0; i < num_verts; ++i) { + float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; + + if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) { + float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; + + float dist,dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); + if (dist2 < min_dist*min_dist) + min_dist = (float) STBTT_sqrt(dist2); + + // coarse culling against bbox + //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && + // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) + dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; + STBTT_assert(i != 0); + if (dist < min_dist) { + // check position along line + // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) + // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) + float dx = x1-x0, dy = y1-y0; + float px = x0-sx, py = y0-sy; + // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy + // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve + float t = -(px*dx + py*dy) / (dx*dx + dy*dy); + if (t >= 0.0f && t <= 1.0f) + min_dist = dist; + } + } else if (verts[i].type == STBTT_vcurve) { + float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; + float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; + float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); + float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); + float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); + float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); + // coarse culling against bbox to avoid computing cubic unnecessarily + if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { + int num=0; + float ax = x1-x0, ay = y1-y0; + float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; + float mx = x0 - sx, my = y0 - sy; + float res[3] = {0.f,0.f,0.f}; + float px,py,t,it,dist2; + float a_inv = precompute[i]; + if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula + float a = 3*(ax*bx + ay*by); + float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); + float c = mx*ax+my*ay; + if (a == 0.0) { // if a is 0, it's linear + if (b != 0.0) { + res[num++] = -c/b; + } + } else { + float discriminant = b*b - 4*a*c; + if (discriminant < 0) + num = 0; + else { + float root = (float) STBTT_sqrt(discriminant); + res[0] = (-b - root)/(2*a); + res[1] = (-b + root)/(2*a); + num = 2; // don't bother distinguishing 1-solution case, as code below will still work + } + } + } else { + float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point + float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; + float d = (mx*ax+my*ay) * a_inv; + num = stbtt__solve_cubic(b, c, d, res); + } + dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); + if (dist2 < min_dist*min_dist) + min_dist = (float) STBTT_sqrt(dist2); + + if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { + t = res[0], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { + t = res[1], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { + t = res[2], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + } + } + } + if (winding == 0) + min_dist = -min_dist; // if outside the shape, value is negative + val = onedge_value + pixel_dist_scale * min_dist; + if (val < 0) + val = 0; + else if (val > 255) + val = 255; + data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; + } + } + STBTT_free(precompute, info->userdata); + STBTT_free(verts, info->userdata); + } + return data; +} + +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +////////////////////////////////////////////////////////////////////////////// +// +// font name matching -- recommended not to use this +// + +// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string +static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) +{ + stbtt_int32 i=0; + + // convert utf16 to utf8 and compare the results while converting + while (len2) { + stbtt_uint16 ch = s2[0]*256 + s2[1]; + if (ch < 0x80) { + if (i >= len1) return -1; + if (s1[i++] != ch) return -1; + } else if (ch < 0x800) { + if (i+1 >= len1) return -1; + if (s1[i++] != 0xc0 + (ch >> 6)) return -1; + if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; + } else if (ch >= 0xd800 && ch < 0xdc00) { + stbtt_uint32 c; + stbtt_uint16 ch2 = s2[2]*256 + s2[3]; + if (i+3 >= len1) return -1; + c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; + if (s1[i++] != 0xf0 + (c >> 18)) return -1; + if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; + s2 += 2; // plus another 2 below + len2 -= 2; + } else if (ch >= 0xdc00 && ch < 0xe000) { + return -1; + } else { + if (i+2 >= len1) return -1; + if (s1[i++] != 0xe0 + (ch >> 12)) return -1; + if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; + } + s2 += 2; + len2 -= 2; + } + return i; +} + +static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) +{ + return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); +} + +// returns results in whatever encoding you request... but note that 2-byte encodings +// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) +{ + stbtt_int32 i,count,stringOffset; + stbtt_uint8 *fc = font->data; + stbtt_uint32 offset = font->fontstart; + stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return NULL; + + count = ttUSHORT(fc+nm+2); + stringOffset = nm + ttUSHORT(fc+nm+4); + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) + && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { + *length = ttUSHORT(fc+loc+8); + return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); + } + } + return NULL; +} + +static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) +{ + stbtt_int32 i; + stbtt_int32 count = ttUSHORT(fc+nm+2); + stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); + + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + stbtt_int32 id = ttUSHORT(fc+loc+6); + if (id == target_id) { + // find the encoding + stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); + + // is this a Unicode encoding? + if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { + stbtt_int32 slen = ttUSHORT(fc+loc+8); + stbtt_int32 off = ttUSHORT(fc+loc+10); + + // check if there's a prefix match + stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); + if (matchlen >= 0) { + // check for target_id+1 immediately following, with same encoding & language + if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { + slen = ttUSHORT(fc+loc+12+8); + off = ttUSHORT(fc+loc+12+10); + if (slen == 0) { + if (matchlen == nlen) + return 1; + } else if (matchlen < nlen && name[matchlen] == ' ') { + ++matchlen; + if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) + return 1; + } + } else { + // if nothing immediately following + if (matchlen == nlen) + return 1; + } + } + } + + // @TODO handle other encodings + } + } + return 0; +} + +static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) +{ + stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); + stbtt_uint32 nm,hd; + if (!stbtt__isfont(fc+offset)) return 0; + + // check italics/bold/underline flags in macStyle... + if (flags) { + hd = stbtt__find_table(fc, offset, "head"); + if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; + } + + nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return 0; + + if (flags) { + // if we checked the macStyle flags, then just check the family and ignore the subfamily + if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } else { + if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } + + return 0; +} + +static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) +{ + stbtt_int32 i; + for (i=0;;++i) { + stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); + if (off < 0) return off; + if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) + return off; + } +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, + float pixel_height, unsigned char *pixels, int pw, int ph, + int first_char, int num_chars, stbtt_bakedchar *chardata) +{ + return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); +} + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) +{ + return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); +} + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) +{ + return stbtt_GetNumberOfFonts_internal((unsigned char *) data); +} + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) +{ + return stbtt_InitFont_internal(info, (unsigned char *) data, offset); +} + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) +{ + return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); +} + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) +{ + return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif // STB_TRUETYPE_IMPLEMENTATION + + +// FULL VERSION HISTORY +// +// 1.25 (2021-07-11) many fixes +// 1.24 (2020-02-05) fix warning +// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) +// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined +// 1.21 (2019-02-25) fix warning +// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() +// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) allow user-defined fabs() replacement +// fix memory leak if fontsize=0.0 +// fix warning from duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// allow PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ +// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match +// non-oversampled; STBTT_POINT_SIZE for packed case only +// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling +// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) +// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID +// 0.8b (2014-07-07) fix a warning +// 0.8 (2014-05-25) fix a few more warnings +// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back +// 0.6c (2012-07-24) improve documentation +// 0.6b (2012-07-20) fix a few more warnings +// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, +// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty +// 0.5 (2011-12-09) bugfixes: +// subpixel glyph renderer computed wrong bounding box +// first vertex of shape can be off-curve (FreeSans) +// 0.4b (2011-12-03) fixed an error in the font baking example +// 0.4 (2011-12-01) kerning, subpixel rendering (tor) +// bugfixes for: +// codepoint-to-glyph conversion using table fmt=12 +// codepoint-to-glyph conversion using table fmt=4 +// stbtt_GetBakedQuad with non-square texture (Zer) +// updated Hello World! sample to use kerning and subpixel +// fixed some warnings +// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) +// userdata, malloc-from-userdata, non-zero fill (stb) +// 0.2 (2009-03-11) Fix unsigned/signed char warnings +// 0.1 (2009-03-09) First public release +// + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/src/editors/xrEUI/spectrum.cpp b/src/editors/xrEUI/spectrum.cpp new file mode 100644 index 00000000000..64d81c9512f --- /dev/null +++ b/src/editors/xrEUI/spectrum.cpp @@ -0,0 +1,37426 @@ +#include "stdafx.h" +#include "spectrum.h" + +#include "imgui.h" + +namespace ImGui +{ + namespace Spectrum + { + extern const unsigned int SourceSansProRegular_compressed_size = 149392; + extern const unsigned int SourceSansProRegular_compressed_data[]; // defined later in the file + + void LoadFont(float size) + { + ImGuiIO &io = ImGui::GetIO(); + ImFont *font = io.Fonts->AddFontFromMemoryCompressedTTF(SourceSansProRegular_compressed_data, SourceSansProRegular_compressed_size, size); + assert(font != nullptr); + io.FontDefault = font; + } + + void StyleColorsSpectrum() + { + //MessageBox(0, L"spec", 0, 0); + ImGuiStyle *style = &ImGui::GetStyle(); + style->GrabRounding = 4.0f; + + ImVec4 *colors = style->Colors; + colors[ImGuiCol_Text] = ColorConvertU32ToFloat4(Spectrum::GRAY800); // text on hovered controls is gray900 + colors[ImGuiCol_TextDisabled] = ColorConvertU32ToFloat4(Spectrum::GRAY500); + colors[ImGuiCol_WindowBg] = ColorConvertU32ToFloat4(Spectrum::GRAY100); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ColorConvertU32ToFloat4(Spectrum::GRAY50); // not sure about this. Note: applies to tooltips too. + colors[ImGuiCol_Border] = ColorConvertU32ToFloat4(Spectrum::GRAY300); + colors[ImGuiCol_BorderShadow] = ColorConvertU32ToFloat4(Spectrum::Static::NONE); // We don't want shadows. Ever. + colors[ImGuiCol_FrameBg] = ColorConvertU32ToFloat4(Spectrum::GRAY75); // this isnt right, spectrum does not do this, but it's a good fallback + colors[ImGuiCol_FrameBgHovered] = ColorConvertU32ToFloat4(Spectrum::GRAY50); + colors[ImGuiCol_FrameBgActive] = ColorConvertU32ToFloat4(Spectrum::GRAY200); + colors[ImGuiCol_TitleBg] = ColorConvertU32ToFloat4(Spectrum::GRAY300); // those titlebar values are totally made up, spectrum does not have this. + colors[ImGuiCol_TitleBgActive] = ColorConvertU32ToFloat4(Spectrum::GRAY200); + colors[ImGuiCol_TitleBgCollapsed] = ColorConvertU32ToFloat4(Spectrum::GRAY400); + colors[ImGuiCol_MenuBarBg] = ColorConvertU32ToFloat4(Spectrum::GRAY100); + colors[ImGuiCol_ScrollbarBg] = ColorConvertU32ToFloat4(Spectrum::GRAY100); // same as regular background + colors[ImGuiCol_ScrollbarGrab] = ColorConvertU32ToFloat4(Spectrum::GRAY400); + colors[ImGuiCol_ScrollbarGrabHovered] = ColorConvertU32ToFloat4(Spectrum::GRAY600); + colors[ImGuiCol_ScrollbarGrabActive] = ColorConvertU32ToFloat4(Spectrum::GRAY700); + colors[ImGuiCol_CheckMark] = ColorConvertU32ToFloat4(Spectrum::BLUE500); + colors[ImGuiCol_SliderGrab] = ColorConvertU32ToFloat4(Spectrum::GRAY700); + colors[ImGuiCol_SliderGrabActive] = ColorConvertU32ToFloat4(Spectrum::GRAY800); + colors[ImGuiCol_Button] = ColorConvertU32ToFloat4(Spectrum::GRAY75); // match default button to Spectrum's 'Action Button'. + colors[ImGuiCol_ButtonHovered] = ColorConvertU32ToFloat4(Spectrum::GRAY50); + colors[ImGuiCol_ButtonActive] = ColorConvertU32ToFloat4(Spectrum::GRAY200); + colors[ImGuiCol_Header] = ColorConvertU32ToFloat4(Spectrum::BLUE400); + colors[ImGuiCol_HeaderHovered] = ColorConvertU32ToFloat4(Spectrum::BLUE500); + colors[ImGuiCol_HeaderActive] = ColorConvertU32ToFloat4(Spectrum::BLUE600); + colors[ImGuiCol_Separator] = ColorConvertU32ToFloat4(Spectrum::GRAY400); + colors[ImGuiCol_SeparatorHovered] = ColorConvertU32ToFloat4(Spectrum::GRAY600); + colors[ImGuiCol_SeparatorActive] = ColorConvertU32ToFloat4(Spectrum::GRAY700); + colors[ImGuiCol_ResizeGrip] = ColorConvertU32ToFloat4(Spectrum::GRAY400); + colors[ImGuiCol_ResizeGripHovered] = ColorConvertU32ToFloat4(Spectrum::GRAY600); + colors[ImGuiCol_ResizeGripActive] = ColorConvertU32ToFloat4(Spectrum::GRAY700); + colors[ImGuiCol_PlotLines] = ColorConvertU32ToFloat4(Spectrum::BLUE400); + colors[ImGuiCol_PlotLinesHovered] = ColorConvertU32ToFloat4(Spectrum::BLUE600); + colors[ImGuiCol_PlotHistogram] = ColorConvertU32ToFloat4(Spectrum::BLUE400); + colors[ImGuiCol_PlotHistogramHovered] = ColorConvertU32ToFloat4(Spectrum::BLUE600); + colors[ImGuiCol_TextSelectedBg] = ColorConvertU32ToFloat4((Spectrum::BLUE400 & 0x00FFFFFF) | 0x33000000); + colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_NavHighlight] = ColorConvertU32ToFloat4((Spectrum::GRAY900 & 0x00FFFFFF) | 0x0A000000); + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); + } + + const unsigned int SourceSansProRegular_compressed_data[149392 / 4] = + { + 0x0000bc57, + 0x00000000, + 0x7ce00300, + 0x00000400, + 0x00010037, + 0x000f0000, + 0x00030080, + 0x53414270, + 0x5d1e6545, + 0x2d0200bd, + 0x241582fc, + 0x49534446, + 0x24078247, + 0xe0030001, + 0x08078274, + 0x4447083c, + 0x21f74645, + 0x020092fb, + 0x0000442e, + 0x50478c03, + 0xfa43534f, + 0x0200f527, + 0x0100d031, + 0x53477a5c, + 0x44854255, + 0x03001043, + 0x00004c8e, + 0x534f2852, + 0xdf5d322f, + 0x0000a3d5, + 0x3f827801, + 0x63602808, + 0x9f70616d, + 0x00f401ce, + 0x00b02000, + 0x67c23600, + 0x4366796c, + 0x00aa6e1d, + 0x00e46600, + 0x685e7401, + 0x16646165, + 0x82d2007d, + 0x217f832b, + 0x10826836, + 0x0d840a22, + 0x01213b82, + 0x28138234, + 0x746d6824, + 0x1676d078, + 0x2f4f82ec, + 0x1e0000d8, + 0x636f6cd8, + 0xeb2b4c61, + 0x570000f3, + 0x0f299f82, + 0x78616d6e, + 0x00ce0770, + 0x201f82f6, + 0x2b2f8258, + 0x6d616e20, + 0x17884e65, + 0xdb01008c, + 0x082caf82, + 0x736f7014, + 0xcf2a5974, + 0xe301000e, + 0x4a231f82, + 0x820100a3, + 0x0b022e25, + 0x9f24a285, + 0x3c0f5f17, + 0x030300f5, + 0x241182e8, + 0xa05dd800, + 0x2a0784a1, + 0xfe29115e, + 0x08dbfe3a, + 0x82c8036f, + 0x0003230f, + 0x00850002, + 0xfd820120, + 0xeffed826, + 0x98080000, + 0x3a221f82, + 0x49846f08, + 0x05841b85, + 0x83b60721, + 0x26058211, + 0x000c008c, + 0x8e070066, + 0x0004301f, + 0x02030003, + 0x00900109, + 0x02000005, + 0x8258028a, + 0x854b2034, + 0x5e012507, + 0x23013200, + 0x0b2c1582, + 0x04030305, + 0x04020203, + 0xf7020060, + 0x03201f82, + 0x02840382, + 0x42444137, + 0x0040004f, + 0x02ffff20, + 0x0006ffee, + 0x01d80300, + 0x01002011, + 0x231c839f, + 0x9402e601, + 0x20200782, + 0x8d235d82, + 0x82005900, + 0x830220b5, + 0x004c280b, + 0x003b025a, + 0x82670234, + 0x000f2407, + 0x82ee015a, + 0x82692007, + 0x828c200f, + 0x8207200b, + 0x00e02403, + 0x8243021f, + 0x82e62007, + 0x82d72017, + 0x82872003, + 0x82982003, + 0x8636201f, + 0x82392007, + 0x00162b07, + 0x0018022a, + 0x0085021c, + 0x8b820257, + 0x00120329, + 0x00010217, + 0x82dc010f, + 0x001b2487, + 0x82f8012d, + 0x0029322f, + 0x00c80152, + 0x002b022e, + 0x00f0012f, + 0x0024012e, + 0x2017821e, + 0x3683822d, + 0x00f60052, + 0xfff70045, + 0x00ef01d8, + 0x00ff0052, + 0x003d0352, + 0x82230252, + 0x841e2003, + 0x8452202f, + 0x825b2033, + 0x00a3263f, + 0x0052011c, + 0x2c338218, + 0x00d3014b, + 0x00ce020c, + 0x00be0118, + 0x210b830e, + 0xa782a901, + 0x03dacf83, + 0x00360323, + 0x25038708, + 0x1e005b02, + 0xfb824c02, + 0x20073f41, + 0x8be3823b, + 0x82672003, + 0x24038b1b, + 0x0221007e, + 0x0563410f, + 0x4f2007aa, + 0xab412b9b, + 0x82692008, + 0x20039b7b, + 0x8b77828c, + 0x00af2a03, + 0xff070120, + 0x000701fd, + 0x2007824e, + 0x200382f0, + 0x200382d3, + 0x200382ec, + 0x201382fe, + 0x2113854b, + 0x0b824000, + 0x03824d20, + 0x03852b20, + 0x01f2ff22, + 0x21060b42, + 0x4f824302, + 0x22051342, + 0x42e6014f, + 0x0789051b, + 0x84ffff21, + 0xffe9240b, + 0x42d702fa, + 0x37420633, + 0x42872007, + 0x0793063f, + 0xc3829820, + 0x322203c1, + 0x47844f03, + 0x98023723, + 0x20039300, + 0x22178234, + 0x82360234, + 0x9a392087, + 0x00162303, + 0x0397022a, + 0x5b009b26, + 0x1c001802, + 0x8523039c, + 0xbb025700, + 0x82932003, + 0x8603933f, + 0x12032353, + 0x038b1700, + 0xffdc0123, + 0x23039bff, + 0x2d001b02, + 0x7e2c0390, + 0x47022100, + 0x92025a00, + 0x7b023a00, + 0x0e260782, + 0xf8015a00, + 0x03ae3400, + 0x2fab1420, + 0x00110323, + 0x2703873a, + 0x08002002, + 0x52002902, + 0x01230383, + 0x8f2e00c8, + 0x3d022503, + 0x2b022f00, + 0x0121038d, + 0xad2782f0, + 0x9c112003, + 0x06834433, + 0x2d20c382, + 0xa7820397, + 0x038e5220, + 0xf6000828, + 0xf600edff, + 0x07824400, + 0x0382e120, + 0x0382cf20, + 0x0382ea20, + 0x0f85f720, + 0x85380021, + 0x2600211b, + 0x03820782, + 0x82e0ff21, + 0x44522007, + 0x012307df, + 0x875200ef, + 0xff002503, + 0x09014700, + 0x6a220f82, + 0x0b825200, + 0x03823220, + 0xff210782, + 0x260782f7, + 0xff17010c, + 0x453d03f7, + 0x0f45050b, + 0x00232108, + 0x92051745, + 0x01032707, + 0x1e023f00, + 0x03aa2e00, + 0x2b971820, + 0xa2470321, + 0x822b2047, + 0x845b20b7, + 0x011a2403, + 0x8243005b, + 0x82522003, + 0x85422003, + 0xf4ff2503, + 0x1c00a301, + 0x02210397, + 0x23378240, + 0x01180052, + 0x02200395, + 0x2307e345, + 0x4b002002, + 0xce2303dc, + 0x8a021800, + 0xd3012303, + 0x039c0c00, + 0x1f00a923, + 0x25038e01, + 0x35002102, + 0x97412b02, + 0xf7002f05, + 0xed01d8ff, + 0x00024500, + 0x30024b00, + 0x17842700, + 0xeb823520, + 0x2e00cb26, + 0x0900d201, + 0x2307cf42, + 0x2500f001, + 0x2f281f82, + 0x5200fc01, + 0x2f004d03, + 0x9c280f84, + 0xb8012500, + 0xc8013200, + 0x22201b82, + 0x1d222f82, + 0x2f88ebff, + 0x0f82f120, + 0x02219b82, + 0x20578223, + 0x836b8220, + 0x82322003, + 0x001d2857, + 0x00550109, + 0x82ff002e, + 0xff562a0b, + 0xff6001e6, + 0xff4f01f3, + 0x210f83fd, + 0x13823902, + 0x5f829b20, + 0x4d003d23, + 0x24038503, + 0xff230252, + 0x224382ec, + 0x821f0252, + 0x00c82c1b, + 0x00ff0119, + 0x001e0210, + 0x82bb022e, + 0x00c12403, + 0x82a80233, + 0xff5b2367, + 0x038801fd, + 0x4c222782, + 0xb3425100, + 0x00a32208, + 0x82e3841c, + 0x5201259b, + 0x28021800, + 0x4d200382, + 0x2225d782, + 0x12022800, + 0x09934700, + 0x0129ab82, + 0x01ffff9f, + 0x011f00a9, + 0x220382c9, + 0x830300a9, + 0xa1012b6b, + 0xa101feff, + 0xab011400, + 0x03820800, + 0x81011432, + 0xf8001d00, + 0x0d024000, + 0x41023b00, + 0x37031e00, + 0x40240382, + 0x52021e00, + 0x6f240782, + 0x57011e00, + 0x57228f82, + 0x07862500, + 0x57011824, + 0x0b82fbff, + 0x03821420, + 0x13892620, + 0x2e202384, + 0x1a200f82, + 0x2e241386, + 0x5a008702, + 0xa60f3b44, + 0xa61e200f, + 0x109b4427, + 0x00233797, + 0x825200f6, + 0x43432003, + 0xf62208e7, + 0x1f441c00, + 0xf6ff2d05, + 0xf6fff600, + 0x00000e01, + 0x1e002c02, + 0x26291382, + 0x09001d01, + 0xe6ff5601, + 0x06974902, + 0x82f20121, + 0x004c24c7, + 0x820f021e, + 0x001b2407, + 0x498c022d, + 0x01210573, + 0x20078207, + 0x20038243, + 0x473b8203, + 0x1528075b, + 0x98023100, + 0x85023400, + 0x36201782, + 0x1a380382, + 0x18022c00, + 0xdc011c00, + 0xcf02ffff, + 0x01023000, + 0xbb020f00, + 0xa6023f00, + 0x362c4782, + 0x4f020600, + 0xcc02edff, + 0x4701edff, + 0x07240382, + 0xc702ecff, + 0x58200f82, + 0x2f830b82, + 0xe9ffd32c, + 0x2e003002, + 0x4f003502, + 0x2b82e401, + 0x34001328, + 0x2e00c001, + 0x4782a801, + 0x4b001d2e, + 0x3b000a02, + 0x52000601, + 0x4900ee01, + 0x10220382, + 0x0b823202, + 0x0600da28, + 0x1c00af01, + 0x37821702, + 0x16004a28, + 0x4e002502, + 0x33822202, + 0x1a00cc28, + 0x3c00fe01, + 0x0b82a802, + 0x0900e12c, + 0x3d00b102, + 0x3300bd02, + 0x2782b001, + 0x23823020, + 0x42000a22, + 0x02201b83, + 0x63836f82, + 0x5f820220, + 0x06225b84, + 0x4b83eaff, + 0x3f843b83, + 0x06223383, + 0x0b84e1ff, + 0xfaff442a, + 0xf3ff3d02, + 0x03003602, + 0x06260382, + 0xf4ffca02, + 0x0f82c602, + 0x0782c520, + 0x0782c120, + 0xe8ff6523, + 0x20038302, + 0x831f8220, + 0x82852003, + 0x82852017, + 0x824f2017, + 0x824f2053, + 0x82fc20e7, + 0x82f9200f, + 0x82f8200f, + 0xfff42607, + 0xff0203f3, + 0x220382f4, + 0x82cc02f3, + 0xffcc241f, + 0x827903ed, + 0x8275200f, + 0x82752017, + 0x82712007, + 0xff482307, + 0x038203e8, + 0xff7d0123, + 0x240382f4, + 0xff4701f3, + 0x220382ea, + 0x82f401ed, + 0xfff1240f, + 0x82f001f3, + 0x82ec2007, + 0xffc32307, + 0x038301e8, + 0xf2ff0728, + 0xfeff0701, + 0x5f82f902, + 0x6782eb20, + 0x5782cd20, + 0x5782c720, + 0x4f827420, + 0x4f827620, + 0x07827020, + 0x17826c20, + 0x0382ac20, + 0x58209783, + 0x58201f82, + 0x01201f82, + 0xfd200f82, + 0xce200382, + 0xd3474782, + 0x05032106, + 0xf7204382, + 0xd6281382, + 0xd302ebff, + 0x8403e9ff, + 0x80203b82, + 0x7f204382, + 0x7b200782, + 0x31200782, + 0x03839b82, + 0x03002228, + 0xfaff4703, + 0x13824003, + 0x1b82cc20, + 0x0782c820, + 0x0782c820, + 0x0782c420, + 0x23826820, + 0x8e260383, + 0x04045a00, + 0x0382f4ff, + 0x7c04f322, + 0x78240782, + 0x7704f3ff, + 0x74200782, + 0x4a230782, + 0x8204e8ff, + 0xa7032503, + 0x07042d00, + 0xfa203782, + 0x86201382, + 0x83201b82, + 0x82200782, + 0x7e200782, + 0x36200782, + 0x03822382, + 0x00300223, + 0x2303af2e, + 0x2e00c001, + 0x0223039b, + 0xa74b001d, + 0x06012303, + 0x03823800, + 0x06012c24, + 0x0782edff, + 0x07824420, + 0x0382e020, + 0x0786da20, + 0x0782e420, + 0x0386ef20, + 0xf7201783, + 0xcf200b82, + 0xe1200382, + 0xe3220386, + 0xbf821702, + 0x2523039b, + 0x82024e00, + 0x077b4203, + 0x022307b7, + 0xa83300bd, + 0x2f534103, + 0x202a2f41, + 0xab2b8302, + 0x292b828b, + 0x4900ee01, + 0x2e001702, + 0x0382d201, + 0x52009d2a, + 0x1100f201, + 0x2f00f900, + 0x41200382, + 0x52200386, + 0x40280782, + 0xee001e02, + 0xedff4000, + 0x7a200782, + 0xf4240382, + 0x52000601, + 0xcb200782, + 0xbf200386, + 0xb4200782, + 0xee200382, + 0x73200382, + 0x6d200382, + 0x77200786, + 0x82200782, + 0x62200386, + 0x74200782, + 0x76280386, + 0xf4ff7700, + 0xf3ff7500, + 0xea205382, + 0xed220382, + 0x0f82ed00, + 0x0f82ea20, + 0xe6200783, + 0xbc230782, + 0x8200e8ff, + 0x20022b03, + 0x44020300, + 0x4c025a00, + 0x9b825a00, + 0x7e025a32, + 0x0f021a00, + 0x25035a00, + 0x2a020600, + 0x90022a00, + 0x03831b82, + 0x76202383, + 0x20062745, + 0x053f458c, + 0x34082345, + 0x0234003b, + 0x021c0018, + 0x02050002, + 0x022f00dc, + 0x020f0001, + 0x24238282, + 0x03430056, + 0x204b8261, + 0x240b826a, + 0x031c00d0, + 0x8307821e, + 0x003b2347, + 0x43830320, + 0x16004622, + 0x2208974d, + 0x841c00af, + 0x244b837f, + 0x012a0016, + 0x228f8207, + 0x82ecff07, + 0x01122a07, + 0x031f00e0, + 0x03060087, + 0x203f82a1, + 0x836782b8, + 0x83938343, + 0x8285206f, + 0x82662013, + 0x82982013, + 0x00112283, + 0x24438400, + 0x03210009, + 0x20bf864f, + 0x201f8274, + 0x201f82cc, + 0x059f4f95, + 0x2107df4b, + 0xa3822702, + 0x43005f24, + 0x67835602, + 0x2026ef86, + 0x36030300, + 0x93840800, + 0x3a009222, + 0x4b4dfb84, + 0x826b8307, + 0xf8012103, + 0x20246782, + 0xfc013500, + 0x33051748, + 0x13001402, + 0x2e00f001, + 0x0d00a902, + 0x2500c801, + 0x52003502, + 0x87820383, + 0x13025226, + 0x79020a00, + 0x32200f82, + 0x1e200382, + 0x29202382, + 0x2b200782, + 0xc8203782, + 0x2c06cf45, + 0x020c00d3, + 0x012f00de, + 0x020e00be, + 0x241b822a, + 0x023b0000, + 0x200782ed, + 0x240382f5, + 0x021a0054, + 0x202b82a2, + 0x222f84eb, + 0x82e20218, + 0x00022213, + 0x07874b20, + 0x00240225, + 0x849b0108, + 0x012e361b, + 0x001c00a3, + 0x004500f6, + 0x01eafff6, + 0x00110001, + 0x02d8fff7, + 0x205b82df, + 0x203382f6, + 0x20278220, + 0x839386f2, + 0x822e206f, + 0x8240200b, + 0x258f825b, + 0x0c00dd01, + 0x4382a001, + 0x1c00ae24, + 0xbf86ce02, + 0x1f821820, + 0x1f826620, + 0x53003a23, + 0x49a78301, + 0xe22007cb, + 0x0820a382, + 0x20209f82, + 0xeb821f82, + 0x82ff0021, + 0x00f82637, + 0x00110334, + 0x8593863a, + 0x063b4bfb, + 0x2507ff49, + 0x2f000e02, + 0x37827d03, + 0xbb826120, + 0x2c00f126, + 0x4f00f101, + 0x24200382, + 0x1a200382, + 0x11200382, + 0x19200382, + 0x30200382, + 0x1b830382, + 0x07822920, + 0x0b862820, + 0x1a022c2c, + 0x71013700, + 0xf5013200, + 0x13822500, + 0x07021a24, + 0x07822200, + 0x0d021928, + 0xeb013d00, + 0x07822c00, + 0x03823720, + 0x27833420, + 0x5f992b84, + 0x5f8a3120, + 0x06021e24, + 0x57843400, + 0x8300f121, + 0x821a206f, + 0x2083830f, + 0x22078219, + 0x82e90139, + 0x00072257, + 0x200b8231, + 0x93338626, + 0x204f8baf, + 0x06c74328, + 0x2807d343, + 0x00b4032f, + 0x0021015e, + 0x26038455, + 0x012600a9, + 0x823000a9, + 0x01502423, + 0x825000aa, + 0x82392007, + 0x823f2003, + 0x8239200b, + 0x863f2003, + 0x013f240b, + 0x822d000f, + 0x01362203, + 0x240782ad, + 0x013600ad, + 0x2c9b8237, + 0x032900e0, + 0x05290020, + 0x082900dc, + 0x84ab8498, + 0x2833820f, + 0x00300141, + 0x00f40128, + 0x2703830c, + 0x00003302, + 0x52002f01, + 0x26200382, + 0x5e200382, + 0x1f200382, + 0x22200382, + 0x5e2a0784, + 0xf1000a00, + 0x5e015c00, + 0x07840e00, + 0x3a00a224, + 0x5f82c601, + 0xf1240383, + 0x30022d00, + 0x872e5782, + 0x25025c00, + 0x2f035500, + 0xa7022600, + 0x03825500, + 0xb0012624, + 0x4b8a1b00, + 0x7a205385, + 0x7a21d782, + 0x855b8300, + 0x822f200f, + 0x002f320f, + 0x00e8021f, + 0x00e70231, + 0x00a70131, + 0x007d0217, + 0x20038203, + 0x3603821b, + 0x008d021c, + 0x004f031c, + 0x000e0333, + 0x00f10133, + 0x00f60023, + 0x82d60145, + 0x000e281f, + 0x00f7015a, + 0x822b0234, + 0x82db2007, + 0x00bb2203, + 0x227f825a, + 0x43520234, + 0x0121058b, + 0x205382b6, + 0x200b8202, + 0x201782b5, + 0x20038287, + 0x20038249, + 0x202f824d, + 0x22078406, + 0x820b0233, + 0x00da3e1b, + 0x00d3012a, + 0x0047021c, + 0x00bf0157, + 0x00ac0200, + 0x00c50117, + 0xff9f010f, + 0x00db01ff, + 0xdb67832d, + 0xc8022303, + 0x03880800, + 0x21002123, + 0x83d38202, + 0x8fd78303, + 0x8ce78303, + 0x003e2203, + 0x20a38221, + 0x2003a65a, + 0x20278657, + 0x412f9c35, + 0x25230743, + 0x9b023400, + 0x00522303, + 0x038b025a, + 0x20007626, + 0xfcff0701, + 0x2105a352, + 0x0b82efff, + 0x0382d220, + 0x0382eb20, + 0x1382fd20, + 0x07824a20, + 0x00211382, + 0x200b823f, + 0x0ac3524c, + 0xa341f120, + 0x02022107, + 0xab414f82, + 0x01532205, + 0x05b341b5, + 0x0320078a, + 0xff220b85, + 0xab5202fa, + 0x4149200b, + 0x079706d3, + 0xc3824d20, + 0x2f2203b9, + 0x3faadf02, + 0x8b820620, + 0x03990b20, + 0x00da0123, + 0x2b03972a, + 0x2a00aa03, + 0x5b005202, + 0x1c00d301, + 0x0223039b, + 0xbc570047, + 0x82552003, + 0x8703933f, + 0x00ac2357, + 0x038a0217, + 0xff9f0123, + 0x23039cff, + 0x012d00db, + 0x022d038e, + 0x0221003e, + 0x025a000d, + 0x023a0046, + 0x20078238, + 0x05a3410e, + 0x2008af43, + 0x220f82c0, + 0x421e0002, + 0x2d200683, + 0x5a26f782, + 0x34004d02, + 0x17840701, + 0xbd015a26, + 0x87020000, + 0xd7223386, + 0x1b833100, + 0x824c0221, + 0x00062a0f, + 0x00d7015a, + 0x00d3012c, + 0x2d93831c, + 0x30008f02, + 0x0f00c501, + 0x3f007102, + 0x17825002, + 0xebff0722, + 0xdd281784, + 0x59030300, + 0x57035a00, + 0xd6241382, + 0x07020300, + 0x01208385, + 0x32227783, + 0x77831a00, + 0x00b90228, + 0x00e60106, + 0x3742022b, + 0x20238307, + 0x2077862e, + 0x822f8252, + 0x2073888f, + 0x839b82f7, + 0x00bd2673, + 0x00800205, + 0x2073842f, + 0x24238243, + 0x0343001d, + 0x20678204, + 0x240b820b, + 0x021c006e, + 0x200782d0, + 0x24a38208, + 0x032000f6, + 0x220b8221, + 0x8616000a, + 0x025a22e3, + 0x82b38255, + 0xf501217f, + 0xda204b82, + 0x2e089348, + 0x000701eb, + 0x00b60112, + 0x00fd021f, + 0x82280300, + 0x82632033, + 0x828b8347, + 0xbd012197, + 0x45206f82, + 0x1e201382, + 0x8f821382, + 0x00c80124, + 0x43830100, + 0x2100d624, + 0xbf86e702, + 0x1f823720, + 0x1f827d20, + 0x0121ef82, + 0x415b82f7, + 0xeb2807af, + 0x23020f00, + 0x1d024300, + 0x4f838f82, + 0x2f82b920, + 0x0300d626, + 0x0800c802, + 0x4622ff84, + 0xfb843a00, + 0x83061b43, + 0x2a6f846b, + 0x01200016, + 0x013700f9, + 0x82320066, + 0x01223ce7, + 0x011700cb, + 0x012400e1, + 0x011f00d1, + 0x013e00e8, + 0x012100af, + 0x013600e9, + 0x463100e3, + 0x30240a97, + 0x3a00a901, + 0x30109746, + 0x0139008c, + 0x013f008c, + 0x01290037, + 0x0229009e, + 0x460782af, + 0x6f26175b, + 0x6f012300, + 0x03825700, + 0x03822820, + 0x2a200b83, + 0x2d200786, + 0x32200782, + 0x07830382, + 0x07822720, + 0x03871e20, + 0x00ed0023, + 0x24038241, + 0x00b10027, + 0x2003822b, + 0xe42f8621, + 0x907bb743, + 0x00593837, + 0x00760125, + 0x006d0121, + 0xff6b011e, + 0x008801ff, + 0x007b0139, + 0x829b0120, + 0x825f2007, + 0x824a2003, + 0x829b2003, + 0x00b2240f, + 0x82b00039, + 0x0041240b, + 0x82830112, + 0x82452007, + 0x82e62003, + 0x82af2003, + 0x82bb2003, + 0x8481201f, + 0x011f2207, + 0x3f078285, + 0x011a0064, + 0x01110064, + 0x013800af, + 0x02feff5a, + 0x010d000e, + 0x0108005a, + 0x01fdff40, + 0x011b0066, + 0x34227385, + 0x73823201, + 0x50287b83, + 0xc9001c00, + 0x57011300, + 0x6e2c0f82, + 0xa6003400, + 0xa9002a00, + 0x5101e6ff, + 0xae280b82, + 0x2f023400, + 0x71013400, + 0xa3830382, + 0x07827620, + 0x00213382, + 0x2c0782f0, + 0x0013001b, + 0x011000e8, + 0x01320072, + 0x205f8241, + 0x200b82e7, + 0x20078233, + 0x2a03823f, + 0x01150022, + 0x0016002e, + 0x841900c7, + 0xffac2403, + 0x823e019c, + 0x206b8217, + 0x21038501, + 0x47820119, + 0x00790123, + 0x2e6f8222, + 0x00b10034, + 0x00ec002b, + 0x005c0129, + 0x82320229, + 0x824b2007, + 0x82f12003, + 0x82f120c7, + 0x00f12667, + 0x00f10135, + 0x20038a17, + 0x200b823d, + 0x83038212, + 0x201b8307, + 0x240b820b, + 0xfff1010a, + 0x200782f1, + 0x210b8544, + 0x2f862f00, + 0x48202383, + 0x0f200b82, + 0x21200382, + 0x0a240386, + 0x59ff5600, + 0x032d0387, + 0x04230038, + 0x032300aa, + 0x033f000d, + 0x24038228, + 0x0322001c, + 0x22078224, + 0x88290035, + 0x82352007, + 0x004e221f, + 0x200f862a, + 0x85078423, + 0x03232123, + 0x21221b83, + 0x13831e00, + 0x84440421, + 0x82232037, + 0x86222067, + 0x84322003, + 0x00f62207, + 0x87138abc, + 0x2007871b, + 0x201b863c, + 0x83078224, + 0x22240803, + 0x28000e03, + 0x28001002, + 0x34004c01, + 0x29002d02, + 0x1600f801, + 0x5900a102, + 0x15009901, + 0x2e002003, + 0x1a006b02, + 0x2a200382, + 0x27200382, + 0x2a240382, + 0x2d007f03, + 0x19200382, + 0x21200382, + 0x33200b86, + 0x03830782, + 0x03831783, + 0x23830f87, + 0x1f031924, + 0x03834a00, + 0x00640233, + 0x00f70100, + 0x0005021d, + 0x00f90038, + 0x00aa0152, + 0x20078252, + 0x24038240, + 0x00ad0052, + 0x2403821e, + 0x001e0210, + 0x20038280, + 0x060f4ed7, + 0x72007430, + 0x15011600, + 0xe1000600, + 0xe1003700, + 0x0f83e0ff, + 0x62201b82, + 0x7d200382, + 0x8a200382, + 0x73200382, + 0xa1200382, + 0xaf200382, + 0xd8200382, + 0xb6200382, + 0xbf280382, + 0x2e004902, + 0x71ff0000, + 0x79200382, + 0xa5200382, + 0xc8200382, + 0xca200382, + 0xdf200382, + 0x65200382, + 0x6c200382, + 0x53200382, + 0x4f200382, + 0x7b200382, + 0x7a200382, + 0xa982078a, + 0x8263ff21, + 0x826e200f, + 0x82692003, + 0x82c92003, + 0x86c72003, + 0x8268200f, + 0x86bc2007, + 0x82922003, + 0x829f2007, + 0x82a02003, + 0x8a9a2003, + 0x82392057, + 0x8232200b, + 0x83478303, + 0x82cb2043, + 0x82b0200b, + 0x86d12003, + 0x82b42037, + 0x82ab2007, + 0x20078303, + 0x200782f7, + 0x834386b7, + 0x20038747, + 0x206f86c9, + 0x20078292, + 0x83038aa1, + 0x82ad2047, + 0x82dd200f, + 0x86872003, + 0x83678373, + 0x83cf8303, + 0x864320cb, + 0x831f83b3, + 0x82582003, + 0x8aac200f, + 0x208783ef, + 0x050b4165, + 0x003afe24, + 0x0382fe00, + 0x4172ff21, + 0x07870613, + 0x67201f83, + 0x178f1382, + 0x13827a20, + 0x03827f20, + 0x03820920, + 0x37412d20, + 0x200f8306, + 0x200b8277, + 0x87f38a6f, + 0x200787fb, + 0x871f8670, + 0x8268202b, + 0x825e200f, + 0x86732003, + 0x82278333, + 0x0000250b, + 0x3200e803, + 0x26200382, + 0x14240382, + 0x15002003, + 0x5e260382, + 0x0000f101, + 0x03826400, + 0x03821420, + 0x86200283, + 0x78200482, + 0x02820382, + 0x001a0227, + 0x0023021e, + 0x200a821e, + 0x24038205, + 0x02000003, + 0x26078224, + 0x10000004, + 0x82010036, + 0x00002409, + 0x8303002c, + 0x22178209, + 0x840a0003, + 0x01062217, + 0x221982f8, + 0x86f70009, + 0x88002021, + 0x9a168207, + 0x01420802, + 0x8c048704, + 0xc606cb04, + 0x4b04df06, + 0xa3048b04, + 0xad04a404, + 0x8304f406, + 0x82049704, + 0x4c04a904, + 0x4e044d04, + 0x50044f04, + 0x52045104, + 0x54045304, + 0x84045504, + 0xfa068504, + 0xfb06f906, + 0xc9048904, + 0x8b820200, + 0x0500042a, + 0x07000600, + 0x09000800, + 0x30088f82, + 0x000c000b, + 0x000e000d, + 0x0010000f, + 0x00120011, + 0x00140013, + 0x00160015, + 0x00180017, + 0x001a0019, + 0x04a5041b, + 0x06a604ab, + 0x07a004ff, + 0x001c0027, + 0x38eb821d, + 0x0020001f, + 0x00220021, + 0x00240023, + 0x00260025, + 0x00280027, + 0x002a0029, + 0x38eb822b, + 0x002e002d, + 0x0030002f, + 0x00320031, + 0x00340033, + 0x04a70435, + 0x07a804aa, + 0x08d78201, + 0x3d003ade, + 0x5f005400, + 0xa900a000, + 0x0701dc00, + 0x08010601, + 0x09010a01, + 0x24010d01, + 0x2e012f01, + 0x32013001, + 0x50015101, + 0x54015201, + 0x77017001, + 0x78017601, + 0x79017a01, + 0xa901aa01, + 0xad01ab01, + 0xc406ae04, + 0xc706cb06, + 0x9f04b004, + 0xa001b104, + 0xc204c404, + 0x2807c504, + 0x00073107, + 0xb6004e00, + 0xfe060407, + 0xfd06fc06, + 0x9402c806, + 0x08070507, + 0x98020907, + 0x7e060607, + 0x7f028006, + 0x87011e01, + 0x88048a04, + 0x07070307, + 0x0207cc06, + 0x95046b02, + 0x86049604, + 0x36000100, + 0xa8003900, + 0x8801b700, + 0x99049804, + 0x90048f04, + 0x8e048d04, + 0x2007f706, + 0xf700c901, + 0xca06dc06, + 0x94049304, + 0xb507b407, + 0x9e04af04, + 0x92049104, + 0x3800e006, + 0x37006000, + 0x5e006200, + 0x83008200, + 0x81008500, + 0xa700a600, + 0x2c08e182, + 0x00d900a5, + 0x01d800da, + 0x0729075c, + 0x07320730, + 0x07360733, + 0x07370734, + 0x07380735, + 0x0e04002a, + 0x01000012, + 0x000001ba, + 0x00ba0007, + 0x2277822f, + 0x825a0040, + 0x7afa0949, + 0x7e017e00, + 0x8f018001, + 0xa1019301, + 0xc301b001, + 0xe301dc01, + 0xeb01e701, + 0xf901f501, + 0x1b02fd01, + 0x43023702, + 0x63025c02, + 0x7b027402, + 0x84027e02, + 0x92028802, + 0x99029502, + 0x9f029d02, + 0xa402a202, + 0xb002a702, + 0xb902b302, + 0xbf02bc02, + 0xcc02c102, + 0xde02d102, + 0x0c03e302, + 0x13030f03, + 0x27032003, + 0x2c032a03, + 0x34033103, + 0x45033d03, + 0x61034f03, + 0x7a037503, + 0x8a037e03, + 0x90038c03, + 0xa903a103, + 0xc103b003, + 0xd103ce03, + 0xd703d503, + 0xdb03d903, + 0xe103dd03, + 0x0f040704, + 0x57042f04, + 0x63045f04, + 0x93047504, + 0xa3049b04, + 0xb304ab04, + 0xbb04b704, + 0xd104c204, + 0xe304d904, + 0xef04e904, + 0x251df304, + 0x491d431d, + 0x501d4d1d, + 0x581d521d, + 0x9c1d5b1d, + 0xbb1da01d, + 0x071e031e, + 0x171e0f1e, + 0x251e211e, + 0x3b1e2b1e, + 0x531e491e, + 0x6f1e631e, + 0x8f1e851e, + 0x9e1e971e, + 0x151ff91e, + 0x451f1d1f, + 0x511f4d1f, + 0x591f571f, + 0x5d1f5b1f, + 0xb41f7d1f, + 0xd31fc41f, + 0xef1fdb1f, + 0xfe1ff41f, + 0x0b200720, + 0x1a201620, + 0x22201e20, + 0x30202620, + 0x35203320, + 0x3f203a20, + 0x49204420, + 0x7e207120, + 0x8e207f20, + 0xa1209420, + 0xa720a420, + 0xac20a920, + 0xb220ae20, + 0xba20b520, + 0x1321bd20, + 0x20211721, + 0x26212221, + 0x5e212e21, + 0x93218921, + 0x0222e721, + 0x0f220622, + 0x15221222, + 0x1e221a22, + 0x48222b22, + 0x65226022, + 0x18230323, + 0x25231f23, + 0xa0252b23, + 0xb725b325, + 0xc125bd25, + 0xca25c625, + 0x1126cc25, + 0x13276a26, + 0xe7275227, + 0x3b2e252e, + 0x53abb5a7, + 0xfffe04fb, + 0x0000ffff, + 0x30002000, + 0x41003a00, + 0x61005b00, + 0xa0007b00, + 0x8f018001, + 0xa0019201, + 0xc201af01, + 0xe201cd01, + 0xea01e601, + 0xf801f401, + 0x1802fc01, + 0x43023702, + 0x5e025002, + 0x75026402, + 0x80027d02, + 0x89028802, + 0x98029402, + 0x9f029c02, + 0xbb41a102, + 0xb2420806, + 0xbb02b702, + 0xc102be02, + 0xd002c602, + 0xe002d802, + 0x0f030003, + 0x18031103, + 0x28032303, + 0x2e032c03, + 0x39033403, + 0x4f034203, + 0x74036103, + 0x7e037a03, + 0x8c038403, + 0x91038e03, + 0xaa03a303, + 0xc203b103, + 0xbb41d003, + 0x0036080c, + 0x10040804, + 0x58043004, + 0x72046204, + 0x96049004, + 0xaa04a004, + 0xb604ae04, + 0xc004ba04, + 0xd404cf04, + 0xe604e204, + 0xf204ee04, + 0x431d251d, + 0x4d1d471d, + 0x521d4f1d, + 0xbb41561d, + 0x022c0808, + 0x0a1e061e, + 0x1e1e161e, + 0x2a1e241e, + 0x3e1e321e, + 0x561e521e, + 0x801e6a1e, + 0x921e8e1e, + 0xa01e9e1e, + 0x181f001f, + 0x481f201f, + 0x521f501f, + 0x0806bb41, + 0x801f5f32, + 0xc61fb61f, + 0xdd1fd61f, + 0xf61ff21f, + 0x09200720, + 0x18201020, + 0x20201c20, + 0x2f202620, + 0x35203220, + 0x3c203920, + 0x47204420, + 0x74207020, + 0x80207f20, + 0x3206bb41, + 0x20a920a6, + 0x20ae20ab, + 0x20b420b1, + 0x21bd20b8, + 0x41162113, + 0x502408bb, + 0x90218921, + 0x2408bb41, + 0x22152211, + 0x08bb4119, + 0x03236426, + 0x1c231823, + 0x2e06bb41, + 0x25b625b2, + 0x25c025bc, + 0x25c925c6, + 0x411026cc, + 0xe62a06bb, + 0x3a2e222e, + 0x53abb5a7, + 0xbb4100fb, + 0x1c042505, + 0xc1ff0000, + 0xbb210382, + 0x23008200, + 0x74ffa1ff, + 0x02830682, + 0x04836020, + 0xff27038b, + 0x000efe9f, + 0x828aff00, + 0xff8e2803, + 0xff8cff8d, + 0x838aff89, + 0x280f820d, + 0xff7fff5b, + 0x036bff3f, + 0x292f83f2, + 0x6704d201, + 0x6304f403, + 0x0d83e603, + 0x04000023, + 0x22038249, + 0x82460448, + 0x04472605, + 0x04440446, + 0x2c098240, + 0x00220458, + 0x001c001d, + 0xfe000010, + 0x220382f9, + 0x82d6fed7, + 0x82d82005, + 0xfed23003, + 0xffb2ffc8, + 0xffb0ffb1, + 0xffacffaf, + 0x82d2ffd1, + 0xffcd2293, + 0x994b85ce, + 0xf8e42705, + 0x000058e9, + 0x038254e9, + 0x03825720, + 0x01e95525, + 0x82e800e9, + 0x23319959, + 0x31e20000, + 0xe3281d89, + 0xe3fce3fa, + 0xe38be38a, + 0x1589df82, + 0xe7230983, + 0x83a5e7a6, + 0x29038307, + 0x000060e4, + 0xeee6efe6, + 0x07825ae4, + 0x11839820, + 0xe6d0e52f, + 0xe6d1e529, + 0xe62ce628, + 0xe629e62a, + 0x24178228, + 0xe622e62b, + 0x3e078221, + 0x00f7e51e, + 0xe3a6e300, + 0xe559e1a3, + 0xe50000dd, + 0xe57ce56a, + 0xe003e5c4, + 0x00fae465, + 0x82c8e400, + 0xe6330803, + 0xbae4dbe4, + 0x98e4a0e4, + 0x90e4a9e4, + 0x84e49ce1, + 0x70e17fe4, + 0x60e162e1, + 0x5ae15ce1, + 0x00004be1, + 0x0ce16de1, + 0x0be0b5e0, + 0xd6dcc1df, + 0x60d69cd6, + 0x8256265a, + 0xb408299f, + 0xba010100, + 0xd6010000, + 0xe0200382, + 0xe8220382, + 0x8b83ee01, + 0x03a60337, + 0x00aa03a8, + 0x03aa0300, + 0x03ca03c8, + 0x03ce03cc, + 0x03d203d0, + 0x241b84d4, + 0x030000d6, + 0x870983ec, + 0x00042403, + 0x88000204, + 0xfa032300, + 0x0c88fc03, + 0xf603002a, + 0x08040204, + 0x1e040000, + 0x05851383, + 0x1a200984, + 0x03850583, + 0x00160425, + 0x83200400, + 0x2105830b, + 0x09832a04, + 0x043f0393, + 0x042c042a, + 0x04380432, + 0x04480442, + 0x0454044a, + 0x04580456, + 0x0460045c, + 0x046c046a, + 0x84740472, + 0x00722341, + 0x09820400, + 0x11840d85, + 0x1b837020, + 0x7e042308, + 0x86048004, + 0x8a048804, + 0xb2049c04, + 0xce04b404, + 0xe204d804, + 0x0000e404, + 0x9e05ec04, + 0xd205c805, + 0x2d831c06, + 0x062f0385, + 0x0658061c, + 0x06dc06c0, + 0x070007f6, + 0x83280724, + 0x34072b15, + 0x44074007, + 0x00004807, + 0x0f834a07, + 0x46200782, + 0x4a220382, + 0x0d854e07, + 0x07210589, + 0x210b8540, + 0x07833c07, + 0x09840585, + 0x05833620, + 0x07200387, + 0x03823d83, + 0x07950f87, + 0x1b8f7b85, + 0x84160721, + 0x1fb74811, + 0x480ca348, + 0x3b480b6f, + 0x01580808, + 0xcb068804, + 0xc506c706, + 0xac04c806, + 0x3107b004, + 0x7e06c204, + 0x03079504, + 0xc4049704, + 0xc4063207, + 0x4206fe06, + 0x28074306, + 0xb1049402, + 0x37079e04, + 0x80064106, + 0xe1069604, + 0xe306e206, + 0x36008a04, + 0x38003700, + 0x3a003900, + 0x4e003d00, + 0x5e005400, + 0x60005f00, + 0x81006200, + 0x0905bf47, + 0x000101f8, + 0x00a500a0, + 0x00a700a6, + 0x06a900a8, + 0x00b600f6, + 0x00d900d8, + 0x00dc00da, + 0x010201f5, + 0x010601a0, + 0x01080107, + 0x010a0109, + 0x011e010d, + 0x012e0124, + 0x0130012f, + 0x01500132, + 0x01520151, + 0x01d30154, + 0x01760170, + 0x01780177, + 0x067a0179, + 0x018701f7, + 0x01aa01a9, + 0x01ad01ab, + 0x01d401c7, + 0x013b00c9, + 0x013c000b, + 0x014b000c, + 0x0155001b, + 0x01560025, + 0x01580026, + 0x01570028, + 0x01590027, + 0x015d0029, + 0x0163002d, + 0x01640033, + 0x01650034, + 0x016e0035, + 0x0161003e, + 0x01740031, + 0x01750044, + 0x01760045, + 0x01770046, + 0x017c0047, + 0x0180004b, + 0x0184004f, + 0x01860053, + 0x018d0055, + 0x018b005b, + 0x01870059, + 0x0105015c, + 0x018e00d7, + 0x018f005d, + 0x0061015e, + 0x00620192, + 0x00650194, + 0x00630193, + 0x00640195, + 0x00690199, + 0x006d019d, + 0x007101a1, + 0x016f019f, + 0x01040175, + 0x01aa00d5, + 0x01b4007b, + 0x01ab0085, + 0x01b7007c, + 0x01c10088, + 0x01c40092, + 0x01c20093, + 0x01c80094, + 0x01c90099, + 0x01cb009a, + 0x01ca009c, + 0x01d2009b, + 0x01d000a3, + 0x01d700a1, + 0x01db00a8, + 0x01dd00ac, + 0x01de00ae, + 0x01df00af, + 0x01e000b0, + 0x01ee00b1, + 0x01f200bf, + 0x01f600c4, + 0x00f700c8, + 0x00ce01fc, + 0x00d001fe, + 0x06cf01fd, + 0x007b00cc, + 0x008901b8, + 0x00b901e8, + 0x000e013e, + 0x00560188, + 0x007d01ac, + 0x00b201e1, + 0x00b301e2, + 0x00b401e3, + 0x00b501e4, + 0x00b601e5, + 0x00200150, + 0x00480178, + 0x008f01be, + 0x00430173, + 0x006e019e, + 0x001f014f, + 0x009d01cc, + 0x01a401d3, + 0x01e101d8, + 0x02da01d9, + 0x01dc0101, + 0x01df01de, + 0x01e401e0, + 0x01e601e5, + 0x010202e7, + 0x01ef01ee, + 0x01f201f0, + 0x01f301f4, + 0x01f701f6, + 0x01f901f8, + 0x01fc01fb, + 0x01fe01fd, + 0x020002ff, + 0x01e20124, + 0x06f501f1, + 0x06ac06a4, + 0x07b306b1, + 0x9f490724, + 0x38020c05, + 0x35073007, + 0xb906b806, + 0xad06a606, + 0x3a07b206, + 0x40073d07, + 0x44074207, + 0x48074607, + 0x4e074c07, + 0x52075007, + 0x56075407, + 0x5c075a07, + 0x6f075e07, + 0x72077107, + 0x80077e07, + 0x82078107, + 0x95039303, + 0x8f038002, + 0x82028102, + 0x86028302, + 0xae028802, + 0x87028402, + 0xa602a502, + 0xa802a702, + 0xa102af02, + 0x9b029a02, + 0x9d029c02, + 0x9f029e02, + 0xa902a002, + 0xaa02ac02, + 0xad02ab02, + 0x2e04e203, + 0x2f04e303, + 0x3004e403, + 0x3104e503, + 0x3204e603, + 0x3304e703, + 0x3404e803, + 0x3504e903, + 0x3604ea03, + 0x3704eb03, + 0x3804ec03, + 0x3904ed03, + 0x3a04ee03, + 0x3b04ef03, + 0x3c04f003, + 0x3d04f103, + 0xf303f203, + 0x3f043e04, + 0x4004f403, + 0x4104f503, + 0x4204f603, + 0x4304f703, + 0x4404f803, + 0x4504f903, + 0x4604fa03, + 0x4704fb03, + 0x4804fc03, + 0x9e069c06, + 0xa5069f06, + 0xaa06a706, + 0xaf06ae06, + 0x22015200, + 0x23015300, + 0x2a015a00, + 0x2b015b00, + 0x2c015c00, + 0x41017100, + 0x42017200, + 0x49017900, + 0x4c017d00, + 0x4e017e00, + 0x5f019000, + 0x60019100, + 0x66019600, + 0x67019700, + 0x68019800, + 0x6a019a00, + 0x6b019b00, + 0x6c019c00, + 0x7201a200, + 0x7301a300, + 0x7401a400, + 0x8601b500, + 0x9101c000, + 0x9501c300, + 0x9601c500, + 0x9701c600, + 0x9801c700, + 0x9e01cd00, + 0x9f01ce00, + 0xa201d100, + 0xa501d400, + 0xa601d500, + 0xc201f000, + 0xc301f100, + 0xc501f300, + 0xca01f800, + 0xd101ff00, + 0xd2010001, + 0xa7014d01, + 0x0f013f00, + 0x10014000, + 0x11014100, + 0x12014200, + 0x13014300, + 0x14014400, + 0x15014500, + 0x16014600, + 0x17014700, + 0x18014800, + 0x19014900, + 0x1a014a00, + 0x36016600, + 0x37016700, + 0x38016800, + 0x39016900, + 0x3a016a00, + 0x3b016b00, + 0x3c016c00, + 0x3d016d00, + 0x57018900, + 0x58018a00, + 0x7e01ad00, + 0x7f01ae00, + 0x8001af00, + 0x8101b000, + 0x8201b100, + 0x8301b200, + 0x8401b300, + 0x8a01b900, + 0x8b01ba00, + 0x8c01bb00, + 0x8d01bc00, + 0x8e01bd00, + 0xb701e600, + 0xb801e700, + 0xba01e900, + 0xbb01ea00, + 0xbc01eb00, + 0xbd01ec00, + 0xbe01ed00, + 0xc601f400, + 0xcb01f900, + 0xcc01fa00, + 0xcd01fb00, + 0x11031003, + 0x15031403, + 0x17031603, + 0x19031803, + 0xb102b002, + 0xb502b402, + 0xb702b602, + 0xb902b802, + 0x1e031d03, + 0x22032103, + 0x24032303, + 0xbd02bc02, + 0xc102c002, + 0xc302c202, + 0x26032503, + 0x2a032903, + 0x2c032b03, + 0x2e032d03, + 0xc502c402, + 0xc902c802, + 0xcb02ca02, + 0xcd02cc02, + 0x31033003, + 0x35033403, + 0x37033603, + 0x39033803, + 0xcf02ce02, + 0xd302d202, + 0xd502d402, + 0xd702d602, + 0x41034003, + 0x45034403, + 0x47034603, + 0xdb02da02, + 0xdf02de02, + 0xe102e002, + 0x5a03e802, + 0x5e035b03, + 0x60035f03, + 0x62036103, + 0xeb026303, + 0xef02ec02, + 0xf102f002, + 0xf302f202, + 0x1203f402, + 0x1f031303, + 0x27032003, + 0x32032803, + 0x42033303, + 0x4c034303, + 0x5c034d03, + 0x66035d03, + 0x6a036703, + 0x6c036b03, + 0x6e036d03, + 0xf6026f03, + 0xf802f702, + 0xfa02f902, + 0xfc02fb02, + 0x7203fd02, + 0x76037303, + 0x78037703, + 0x7a037903, + 0xff027b03, + 0x01030003, + 0x03030203, + 0x05030403, + 0x7e030603, + 0x82037f03, + 0x84038303, + 0x86038503, + 0x08038703, + 0x0a030903, + 0x0c030b03, + 0x0e030d03, + 0x1a030f03, + 0x68031b03, + 0x69036503, + 0x70031c03, + 0xbb02ba02, + 0xb302b202, + 0x9803f502, + 0x99039703, + 0xa603a303, + 0x71037403, + 0x2f037503, + 0xbe027c03, + 0xc602bf02, + 0xfe02c702, + 0x9f039d03, + 0x3a03a103, + 0x3d033b03, + 0x3c033e03, + 0xd8023f03, + 0xd002d902, + 0x9e03d102, + 0xa203a003, + 0x56035503, + 0x58035703, + 0x49034803, + 0x59035403, + 0xea02e902, + 0xe502e402, + 0xa403e202, + 0x9b03a503, + 0x7d038003, + 0x64038103, + 0xdc028803, + 0xed02dd02, + 0x0703ee02, + 0x9a039c03, + 0x01829704, + 0x049c7508, + 0x04990498, + 0x04b2049d, + 0x048e048d, + 0x048f0491, + 0x04920490, + 0x04af04ae, + 0x06b2079f, + 0x04b304e0, + 0x04a104b7, + 0x04b404a2, + 0x06b504b6, + 0x06a30640, + 0x06ca06d2, + 0x06d706da, + 0x044a04d8, + 0x06ec06c3, + 0x06f206f1, + 0x06e506e4, + 0x06e706e6, + 0x06e906e8, + 0x06eb06ea, + 0x06ee06ed, + 0x07f006ef, + 0x06f50608, + 0x070707f8, + 0x02200712, + 0x07b40725, + 0x022602b5, + 0x000c0027, + 0x26210082, + 0x8204828c, + 0x35032102, + 0x20200482, + 0x01200386, + 0x21200782, + 0x04210385, + 0x20078287, + 0x20038522, + 0x202b8304, + 0x820b8223, + 0xcb042103, + 0x24200782, + 0x06210385, + 0x200782c6, + 0x21038525, + 0x0782df06, + 0x03852620, + 0x824b0421, + 0x85272007, + 0x8b042103, + 0x28200782, + 0x29240382, + 0xa3040000, + 0x2a200782, + 0x04210385, + 0x200782ad, + 0x2103852b, + 0x0782f406, + 0x03852c20, + 0x82830421, + 0x852d2007, + 0x97042103, + 0x2e200782, + 0x04210385, + 0x20078282, + 0x2103852f, + 0x0782a904, + 0x03823020, + 0x53823920, + 0x07824c20, + 0x03823a20, + 0x0b823b20, + 0x07828420, + 0x03853c20, + 0x82fa0621, + 0x853d2007, + 0xf9062103, + 0x3e200782, + 0x06210385, + 0x200782fb, + 0x2103853f, + 0x07828904, + 0x03854020, + 0x82c90421, + 0x82412007, + 0x825a2003, + 0x00022403, + 0x855b0000, + 0xa5042103, + 0x5c200782, + 0x04210385, + 0x200782ab, + 0x2103855d, + 0x0782a604, + 0x03855e20, + 0x82ff0621, + 0x855f2007, + 0xa0042103, + 0x60200782, + 0x07210385, + 0x20078227, + 0x20038261, + 0x2003827a, + 0x2003821c, + 0x2103857b, + 0x0782a704, + 0x03857c20, + 0x82aa0421, + 0x857d2007, + 0xa8042103, + 0x7e200782, + 0x07210385, + 0x83078201, + 0x8303834b, + 0x82a1200b, + 0x2103820f, + 0x07828804, + 0x0385a220, + 0x82cb0621, + 0x85a32007, + 0xc7062103, + 0xa4200782, + 0x06210385, + 0x200782c5, + 0x210385a5, + 0x0782c806, + 0x0385a620, + 0x82ac0421, + 0x85a72007, + 0xb0042103, + 0x6f830782, + 0x07210382, + 0x200b8231, + 0x210385a9, + 0x0782c204, + 0x0385aa20, + 0x8b830620, + 0x0b82ab20, + 0x04210382, + 0x83078295, + 0x2103823f, + 0x0b820307, + 0x0385ad20, + 0x82970421, + 0x85ae2007, + 0xc4042103, + 0xaf200782, + 0x07210385, + 0x83078232, + 0x20038263, + 0x20178306, + 0x820f82b1, + 0xfe062103, + 0xb2200782, + 0xb3240382, + 0x42060000, + 0xb4200782, + 0x07210385, + 0x20078228, + 0x210385b5, + 0x07829402, + 0x0385b620, + 0x82b10421, + 0x85b72007, + 0x9e042103, + 0xb8200782, + 0x07210385, + 0x20078237, + 0x210385b9, + 0x07824106, + 0x0385ba20, + 0x82800621, + 0x85bb2007, + 0x96042103, + 0xbc200782, + 0xbe200382, + 0xe1206b82, + 0xbf200782, + 0x04210385, + 0x2007828a, + 0x830382c0, + 0x82362097, + 0x86c52007, + 0x823d2003, + 0x86c62007, + 0x824e2003, + 0x86c72007, + 0x82542003, + 0x82c82007, + 0x41ca2003, + 0x002105ef, + 0x830782cb, + 0x82622003, + 0x82cc2007, + 0x82ce2003, + 0x82812003, + 0x86cf2003, + 0x82852003, + 0x85d02007, + 0x01012103, + 0xd1200782, + 0xa0200386, + 0xd2200782, + 0xd6200382, + 0x21059b41, + 0x0782d700, + 0x06210382, + 0x200782f6, + 0x830386d8, + 0x82d920f7, + 0x86db200b, + 0x82dc200f, + 0x20038707, + 0x830b82dd, + 0x82f52003, + 0x85de2007, + 0x02012503, + 0xdf000000, + 0x01200385, + 0xe0205f83, + 0xe4240b82, + 0x06010000, + 0xe5200782, + 0x01210385, + 0x2007820d, + 0x210385e6, + 0x07821e01, + 0x0385e720, + 0x82240121, + 0x82e82007, + 0x00ea2403, + 0x822e0100, + 0x85eb2007, + 0x32012103, + 0xec200782, + 0xee200382, + 0x50201782, + 0xef200782, + 0x01210385, + 0x20078254, + 0x210385f0, + 0x0782d301, + 0x0385f120, + 0x82700121, + 0x82f22007, + 0x21c78203, + 0x07827601, + 0x0385f720, + 0x07830620, + 0x0b82f820, + 0x01210382, + 0x20078287, + 0x200382f9, + 0x205382fb, + 0x200782a9, + 0x210385fc, + 0x0782ad01, + 0x0385fd20, + 0x82c70121, + 0x85fe2007, + 0xd4012103, + 0xff200782, + 0x01210385, + 0x823382c9, + 0x8201200a, + 0x3b002103, + 0x08820b82, + 0x03830120, + 0x0b820b20, + 0x03850220, + 0x823c0021, + 0x86032007, + 0x820c2003, + 0x85042007, + 0x4b002103, + 0x05200782, + 0x1b200386, + 0x06200782, + 0x00210385, + 0x20078255, + 0x20038607, + 0x20078225, + 0x21038508, + 0x07825600, + 0x03860920, + 0x07822620, + 0x03850a20, + 0x82580021, + 0x860b2007, + 0x82282003, + 0x82638307, + 0x57002103, + 0x0d200b82, + 0x27200386, + 0x0e200782, + 0x00210385, + 0x20078259, + 0x2003860f, + 0x20078229, + 0x21038510, + 0x07825d00, + 0x03861120, + 0x07822d20, + 0x03851220, + 0x82630021, + 0x86132007, + 0x82332003, + 0x85142007, + 0x64002103, + 0x15200782, + 0x34200386, + 0x16200782, + 0x00210385, + 0x20078265, + 0x20038617, + 0x20078235, + 0x21038518, + 0x07826e00, + 0x03861920, + 0x07823e20, + 0x03851a20, + 0x82610021, + 0x861b2007, + 0x82312003, + 0x851c2007, + 0x74002103, + 0x1d200782, + 0x44200386, + 0x1e200782, + 0x00210385, + 0x20078275, + 0x2003861f, + 0x20078245, + 0x21038520, + 0x07827600, + 0x03862120, + 0x07824620, + 0x03852220, + 0x82770021, + 0x86232007, + 0x82472003, + 0x85242007, + 0x7c002103, + 0x25200782, + 0x4b200386, + 0x26200782, + 0x00210385, + 0x20078280, + 0x20038627, + 0x2007824f, + 0x21038528, + 0x07828400, + 0x03862920, + 0x07825320, + 0x03852a20, + 0x82860021, + 0x862b2007, + 0x82552003, + 0x852c2007, + 0x8d002103, + 0x2d200782, + 0x5b200386, + 0x2e200782, + 0x00210385, + 0x2007828b, + 0x2003862f, + 0x20078259, + 0x21038530, + 0x07828700, + 0x0383ff83, + 0x0b825c20, + 0x03863220, + 0x07820520, + 0x03863320, + 0x0782d720, + 0x03853420, + 0x828e0021, + 0x86352007, + 0x825d2003, + 0x85362007, + 0x8f002103, + 0x37200782, + 0x5e200386, + 0x38200782, + 0x61200386, + 0x39200782, + 0x00210385, + 0x20078292, + 0x2003863a, + 0x20078262, + 0x2103853b, + 0x07829400, + 0x03863c20, + 0x07826520, + 0x03853d20, + 0x82930021, + 0x863e2007, + 0x82632003, + 0x853f2007, + 0x95002103, + 0x40200782, + 0x64200386, + 0x41200782, + 0x00210385, + 0x20078299, + 0x20038642, + 0x20078269, + 0x21038543, + 0x07829d00, + 0x03864420, + 0x07826d20, + 0x03854520, + 0x82a10021, + 0x86462007, + 0x82712003, + 0x85472007, + 0x9f002103, + 0x48200782, + 0x6f200386, + 0x49200782, + 0x75200386, + 0x4a200782, + 0x04240386, + 0x4b010000, + 0xd5200386, + 0x4c200782, + 0x00210385, + 0x200782aa, + 0x2003864d, + 0x2007827b, + 0x2103854e, + 0x0782b400, + 0x03864f20, + 0x07828520, + 0x03855020, + 0x82ab0021, + 0x86512007, + 0x827c2003, + 0x85522007, + 0xb7002103, + 0x53200782, + 0x88200386, + 0x54200782, + 0x00210385, + 0x200782c1, + 0x20038655, + 0x20078292, + 0x21038556, + 0x0782c400, + 0x03865720, + 0x07829320, + 0x03855820, + 0x82c20021, + 0x86592007, + 0x82942003, + 0x855a2007, + 0xc8002103, + 0x5b200782, + 0x99200386, + 0x5c200782, + 0x00210385, + 0x200782c9, + 0x2003865d, + 0x2007829a, + 0x2103855e, + 0x0782cb00, + 0x03865f20, + 0x07829c20, + 0x03856020, + 0x82ca0021, + 0x86612007, + 0x829b2003, + 0x85622007, + 0xd2002103, + 0x63200782, + 0xa3200386, + 0x64200782, + 0x00210385, + 0x200782d0, + 0x20038665, + 0x200782a1, + 0x21038566, + 0x0782d700, + 0x03866720, + 0x0782a820, + 0x03856820, + 0x82db0021, + 0x86692007, + 0x82ac2003, + 0x856a2007, + 0xdd002103, + 0x6b200782, + 0xae200386, + 0x6c200782, + 0x00210385, + 0x200782de, + 0x2003866d, + 0x200782af, + 0x2103856e, + 0x0782df00, + 0x03866f20, + 0x0782b020, + 0x03857020, + 0x82e00021, + 0x86712007, + 0x82b12003, + 0x85722007, + 0xee002103, + 0x73200782, + 0xbf200386, + 0x74200782, + 0x00210385, + 0x200782f2, + 0x20038675, + 0x200782c4, + 0x21038576, + 0x0782f600, + 0x03867720, + 0x0782c820, + 0x03857820, + 0x82f70021, + 0x85792007, + 0xfc002103, + 0x7a200782, + 0xce200386, + 0x7b200782, + 0x00210385, + 0x200782fe, + 0x2003867c, + 0x200782d0, + 0x2103857d, + 0x0782fd00, + 0x03867e20, + 0x0782cf20, + 0x03868020, + 0x07822120, + 0x03868f20, + 0x07820320, + 0x03859220, + 0x82cc0621, + 0x85932007, + 0x83002003, + 0x82a0205b, + 0x2103820b, + 0x0782b800, + 0x0386a120, + 0x07828920, + 0x0385af20, + 0x82e80021, + 0x86b02007, + 0x82b92003, + 0x82c22007, + 0x00c32403, + 0x82220200, + 0x85cd2007, + 0x3e002103, + 0xce200782, + 0x0e200386, + 0xcf200782, + 0x00210385, + 0x83078288, + 0x200383ab, + 0x200b8256, + 0x210385d1, + 0x0782ac00, + 0x0386d220, + 0xd320c783, + 0x03820b82, + 0x82e10021, + 0x86d42007, + 0x82b22003, + 0x85d52007, + 0xe2002103, + 0xd6200782, + 0xb3200386, + 0xd7200782, + 0x00210385, + 0x200782e3, + 0x200386d8, + 0x200782b4, + 0x210385d9, + 0x0782e400, + 0x0386da20, + 0x0782b520, + 0x0385db20, + 0x82e50021, + 0x86dc2007, + 0x82b62003, + 0x82578307, + 0x50002103, + 0x4b830b82, + 0x20200383, + 0xe6200b82, + 0x00210385, + 0x20078278, + 0x200386e7, + 0x20078248, + 0x210385ea, + 0x0782be00, + 0x0386eb20, + 0x07828f20, + 0x0385f420, + 0x82730021, + 0x86f52007, + 0x82432003, + 0x85f82007, + 0x9e002103, + 0xf9200782, + 0x6e200386, + 0xfc200782, + 0x00210385, + 0x2007824f, + 0x240386fd, + 0x0200001f, + 0x21038518, + 0x0782cc00, + 0x03851920, + 0x829d0121, + 0x851a2007, + 0xd3002103, + 0x1b200782, + 0x01210385, + 0x200782a4, + 0x21038537, + 0x0782d601, + 0x02206f82, + 0x00210382, + 0x820b8251, + 0x820220cf, + 0xd8012103, + 0x0f830b82, + 0x01210382, + 0x200b82e1, + 0x20038252, + 0x05234153, + 0x82540221, + 0x2003830b, + 0x20078201, + 0x21038555, + 0x0782dc01, + 0x03825620, + 0x23825820, + 0x0782de20, + 0x03825920, + 0x0b825c20, + 0x0782e420, + 0x03825e20, + 0x0b826320, + 0x0782e820, + 0x03866420, + 0x07820220, + 0x03826520, + 0x17826720, + 0x0782ee20, + 0x03856820, + 0x82f20121, + 0x85692007, + 0xf4012103, + 0x6a200782, + 0x01210385, + 0x200782f3, + 0x2003826b, + 0x202f826e, + 0x200782f6, + 0x2003826f, + 0x200b8274, + 0x200782fb, + 0x20038275, + 0x2003827b, + 0x20038203, + 0x2003827d, + 0x2403827e, + 0x0200000a, + 0x20038280, + 0x20038284, + 0x2003820c, + 0x20038688, + 0x20078211, + 0x20038289, + 0x20038292, + 0x20038213, + 0x20038294, + 0x20038295, + 0x2003821e, + 0x20038698, + 0x20078224, + 0x21038599, + 0x0782e201, + 0x03859c20, + 0x82f10121, + 0x859d2007, + 0xf5012103, + 0x9f200782, + 0x01210385, + 0x200782fa, + 0x200382a1, + 0x200382a2, + 0x20038220, + 0x210385a4, + 0x0782e301, + 0x0386a720, + 0x07821220, + 0x0385b020, + 0x27830620, + 0x0b82b220, + 0x06200382, + 0xb3202b83, + 0x03820b82, + 0x82ac0621, + 0x85b72007, + 0xb1062103, + 0xb8200782, + 0x06210385, + 0x200782b3, + 0x200385b9, + 0x209b8307, + 0x240b82bb, + 0x040000bc, + 0x2007828d, + 0x240382be, + 0x070000bf, + 0x20078225, + 0x210385c1, + 0x0782b506, + 0x0382c620, + 0x1782cc20, + 0x07822920, + 0x0382d020, + 0x0000d124, + 0x0782b606, + 0x0385d820, + 0x82330721, + 0x85d92007, + 0x36072103, + 0xda200782, + 0x07210385, + 0x20078234, + 0x210385db, + 0x07823807, + 0x0385dc20, + 0x82300721, + 0x85dd2007, + 0x35072103, + 0xde200782, + 0x06200385, + 0xe020a383, + 0x03820b82, + 0x82b90621, + 0x85e12007, + 0xa6062103, + 0xe2200782, + 0x06210385, + 0x200782ad, + 0x200385e3, + 0x24f38206, + 0x00000003, + 0x21038203, + 0x07823a07, + 0x03850120, + 0x823d0721, + 0x85022007, + 0x40072103, + 0x03200782, + 0x07210385, + 0x20078242, + 0x21038504, + 0x07824407, + 0x03850520, + 0x82460721, + 0x85062007, + 0x48072103, + 0x07200782, + 0x07210385, + 0x2007824c, + 0x21038508, + 0x07824e07, + 0x03850920, + 0x82500721, + 0x850a2007, + 0x52072103, + 0x0b200782, + 0x07210385, + 0x20078254, + 0x2103850c, + 0x07825607, + 0x03850f20, + 0x82580721, + 0x85112007, + 0x5a072103, + 0x12200782, + 0x07210385, + 0x2007825c, + 0x21038513, + 0x07825e07, + 0x03821820, + 0x00002024, + 0x07826007, + 0x03822320, + 0x0b822720, + 0x07826920, + 0x03852820, + 0x826f0721, + 0x82292007, + 0x822a2003, + 0x82712017, + 0x852c2007, + 0x73072103, + 0x2e200782, + 0x31200382, + 0x74201782, + 0x34200782, + 0x07210385, + 0x20078278, + 0x20038239, + 0x2017823d, + 0x83078279, + 0x210382ff, + 0x0b827e07, + 0x03824320, + 0x17824520, + 0x07828020, + 0x03854f20, + 0x82a70721, + 0x85612007, + 0x83072103, + 0x4b830782, + 0x07827520, + 0x03829120, + 0x03867a20, + 0x07829620, + 0x03833f83, + 0x0b828e20, + 0x03868420, + 0x07829320, + 0x03868520, + 0x07829520, + 0x03858620, + 0x5f830220, + 0x0b828720, + 0x8f200383, + 0x88200782, + 0x8a240382, + 0x81020000, + 0x8c200782, + 0x02210385, + 0x20078285, + 0x2003858e, + 0x83378302, + 0x21038227, + 0x13828802, + 0x03859020, + 0x86ae0221, + 0x43a12087, + 0x032105db, + 0x200f82a3, + 0x830b82a9, + 0x82aa20d7, + 0x2103820b, + 0x07828402, + 0x0385ab20, + 0x82870221, + 0x82ac2007, + 0x82af2003, + 0x82a52023, + 0x85b02007, + 0x82022003, + 0xb103210f, + 0xc1200b82, + 0x89201782, + 0xc2200782, + 0x02210385, + 0x200782a1, + 0x200382c3, + 0x201782c9, + 0x2007829a, + 0x210385ca, + 0x0782a902, + 0x0385cb20, + 0x4f830220, + 0x0b82cc20, + 0x2382cd20, + 0x03216f82, + 0x820b82ce, + 0xad022103, + 0xd0200782, + 0xd1200382, + 0x2105b743, + 0x0b82d503, + 0x02210382, + 0x2007829d, + 0x830386d7, + 0x82d9206b, + 0x2003830b, + 0x2007828a, + 0x200386db, + 0x2007828b, + 0x200386dd, + 0x2007828c, + 0x240386e1, + 0x0400008d, + 0x20038200, + 0x21578507, + 0x0b820804, + 0x0b820f20, + 0x0782da20, + 0x00001024, + 0x0b822f04, + 0x0421c782, + 0x200b8230, + 0x200b8257, + 0x200782fd, + 0x20038258, + 0x2003825f, + 0x20038226, + 0x21038562, + 0x0782e203, + 0x03866320, + 0x07822e20, + 0x03857220, + 0x82e30321, + 0x86732007, + 0x214b8203, + 0x0b827404, + 0x03210382, + 0x200782e4, + 0x83038675, + 0x8290205b, + 0x2103820b, + 0x0782e503, + 0x03869120, + 0x07823120, + 0x03859220, + 0x82e60321, + 0x86932007, + 0x82322003, + 0x85962007, + 0xe7032103, + 0x97200782, + 0x33200386, + 0x98200782, + 0x03210385, + 0x200782e8, + 0x20038699, + 0x20078234, + 0x2103859a, + 0x0782e903, + 0x03869b20, + 0x07823520, + 0x0385a020, + 0x82ea0321, + 0x86a12007, + 0x82362003, + 0x85a22007, + 0xeb032103, + 0xa3200782, + 0x37200386, + 0xaa200782, + 0x03210385, + 0x200782ec, + 0x200386ab, + 0x20078238, + 0x210385ae, + 0x0782ed03, + 0x0386af20, + 0x07823920, + 0x0385b020, + 0x82ee0321, + 0x86b12007, + 0x823a2003, + 0x85b22007, + 0xef032103, + 0xb3200782, + 0x3b200386, + 0xb6200782, + 0x03210385, + 0x200782f0, + 0x200386b7, + 0x2007823c, + 0x210385ba, + 0x0782f103, + 0x0386bb20, + 0x07823d20, + 0x0382c020, + 0x0000c124, + 0x0782f203, + 0x0386c220, + 0x07823e20, + 0x0386cf20, + 0x07823f20, + 0x0385d020, + 0x82f40321, + 0x86d12007, + 0x82402003, + 0x85d42007, + 0xf5032103, + 0xd5200782, + 0x41200386, + 0xd6200782, + 0x03210385, + 0x200782f6, + 0x200386d7, + 0x20078242, + 0x210385d8, + 0x0782f703, + 0x0386d920, + 0x07824320, + 0x0385e220, + 0x82f80321, + 0x86e32007, + 0x82442003, + 0x85e62007, + 0xf9032103, + 0xe7200782, + 0x45200386, + 0xe8200782, + 0x03210385, + 0x200782fa, + 0x200386e9, + 0x20078246, + 0x210385ee, + 0x0782fb03, + 0x0386ef20, + 0x07824720, + 0x0382db83, + 0x82fc0321, + 0x86f3200b, + 0x00482403, + 0x85251d00, + 0x1d022103, + 0x87820782, + 0x03821d20, + 0x829b0621, + 0x2033820b, + 0x2103821d, + 0x0b829c06, + 0x49242783, + 0x9e060000, + 0x4d200b82, + 0x06210385, + 0x200782a1, + 0x2103854f, + 0x0782a506, + 0x03855020, + 0x82a70621, + 0x85522007, + 0xa9062103, + 0x56200782, + 0x06210385, + 0x200782aa, + 0x20038257, + 0x20478258, + 0x200782ae, + 0x2103855b, + 0x0782b006, + 0x03859c20, + 0x829d0621, + 0x85a02007, + 0x83062003, + 0x82bb2007, + 0x2503820b, + 0x0000b406, + 0x0385021e, + 0x5b820020, + 0x82031e21, + 0x2103820b, + 0x07822201, + 0x03850620, + 0x82530021, + 0x85072007, + 0x23012103, + 0x0a200782, + 0x00210385, + 0x2007825a, + 0x2103850b, + 0x07822a01, + 0x03850c20, + 0x7f820020, + 0x820d1e21, + 0x2103820b, + 0x07822b01, + 0x03850e20, + 0x825c0021, + 0x850f2007, + 0x2c012103, + 0x16200782, + 0x00210385, + 0x20078271, + 0x21038517, + 0x07824101, + 0x03851e20, + 0x82720021, + 0x851f2007, + 0x42012103, + 0x20200782, + 0x00210385, + 0x20078279, + 0x21038521, + 0x07824901, + 0x03852420, + 0x827d0021, + 0x85252007, + 0x4c012103, + 0x93830782, + 0x00210382, + 0x830b827e, + 0x21038287, + 0x0b824e01, + 0x03853220, + 0x82900021, + 0x85332007, + 0x5f012103, + 0x34200782, + 0x00210385, + 0x20078291, + 0x21038535, + 0x07826001, + 0x03853620, + 0x82960021, + 0x85372007, + 0x66012103, + 0x38200782, + 0x00210385, + 0x20078297, + 0x21038539, + 0x07826701, + 0x03853a20, + 0x82980021, + 0x853b2007, + 0x68012103, + 0x3e200782, + 0x00210385, + 0x2007829a, + 0x2103853f, + 0x07826a01, + 0x03854020, + 0x829b0021, + 0x82ff8307, + 0x6b012103, + 0x42200b82, + 0x00210385, + 0x2007829c, + 0x21038543, + 0x07826c01, + 0x03854420, + 0x82a20021, + 0x85452007, + 0x72012103, + 0x46200782, + 0x00210385, + 0x200782a3, + 0x21038547, + 0x07827301, + 0x03854820, + 0x82a40021, + 0x85492007, + 0x74012103, + 0x52200782, + 0x00210385, + 0x200782b5, + 0x21038553, + 0x07828601, + 0x03855620, + 0x82c00021, + 0x85572007, + 0x91012103, + 0x58200782, + 0x00210385, + 0x200782c3, + 0x21038559, + 0x07829501, + 0x03855a20, + 0x82c50021, + 0x855b2007, + 0x96012103, + 0x5c200782, + 0x00210385, + 0x200782c6, + 0x2103855d, + 0x07829701, + 0x03855e20, + 0x82c70021, + 0x855f2007, + 0x98012103, + 0x60200782, + 0x00210385, + 0x200782cd, + 0x21038561, + 0x07829e01, + 0x03856220, + 0x82ce0021, + 0x85632007, + 0x9f012103, + 0x6a200782, + 0x00210385, + 0x200782d1, + 0x2103856b, + 0x0782a201, + 0x03856c20, + 0x82d40021, + 0x856d2007, + 0xa5012103, + 0x6e200782, + 0x00210385, + 0x200782d5, + 0x2103856f, + 0x0782a601, + 0x03858020, + 0x82f00021, + 0x85812007, + 0xc2012103, + 0x82200782, + 0x00210385, + 0x200782f1, + 0x20038583, + 0x20fb8301, + 0x820b8284, + 0xf3002103, + 0x85200782, + 0x01210385, + 0x200782c5, + 0x2103858e, + 0x0782f800, + 0x03858f20, + 0x82ca0121, + 0x85922007, + 0xff002103, + 0x93200782, + 0x01200385, + 0x9420b383, + 0x03820b82, + 0x82000121, + 0x85952007, + 0xd2012103, + 0x96200782, + 0x01210385, + 0x2007824d, + 0x21038597, + 0x0782a701, + 0x03859e20, + 0x82cf0021, + 0x85a02007, + 0x3f002103, + 0xa1200782, + 0x01210385, + 0x2007820f, + 0x210385a2, + 0x07824000, + 0x0385a320, + 0x82100121, + 0x85a42007, + 0x41002103, + 0xa5200782, + 0x01210385, + 0x20078211, + 0x210385a6, + 0x07824200, + 0x0385a720, + 0x82120121, + 0x85a82007, + 0x43002103, + 0xa9200782, + 0x01210385, + 0x20078213, + 0x210385aa, + 0x07824400, + 0x0385ab20, + 0x82140121, + 0x85ac2007, + 0x45002103, + 0xad200782, + 0x01210385, + 0x20078215, + 0x210385ae, + 0x07824600, + 0x0385af20, + 0x82160121, + 0x85b02007, + 0x47002103, + 0xb1200782, + 0x01210385, + 0x20078217, + 0x210385b2, + 0x07824800, + 0x0385b320, + 0x82180121, + 0x85b42007, + 0x49002103, + 0xb5200782, + 0x01210385, + 0x20078219, + 0x210385b6, + 0x07824a00, + 0x0385b720, + 0x821a0121, + 0x85b82007, + 0x66002103, + 0xb9200782, + 0x01210385, + 0x20078236, + 0x210385ba, + 0x07826700, + 0x0385bb20, + 0x82370121, + 0x85bc2007, + 0x68002103, + 0xbd200782, + 0x01210385, + 0x20078238, + 0x210385be, + 0x07826900, + 0x0385bf20, + 0x82390121, + 0x85c02007, + 0x6a002103, + 0xc1200782, + 0x01210385, + 0x2007823a, + 0x210385c2, + 0x07826b00, + 0x0385c320, + 0x823b0121, + 0x85c42007, + 0x6c002103, + 0xc5200782, + 0x01210385, + 0x2007823c, + 0x210385c6, + 0x07826d00, + 0x0385c720, + 0x823d0121, + 0x85c82007, + 0x89002103, + 0xc9200782, + 0x01210385, + 0x20078257, + 0x210385ca, + 0x07828a00, + 0x0385cb20, + 0x82580121, + 0x85cc2007, + 0xad002103, + 0xcd200782, + 0x01210385, + 0x2007827e, + 0x210385ce, + 0x0782ae00, + 0x0385cf20, + 0x827f0121, + 0x85d02007, + 0xaf002103, + 0xd1200782, + 0x01210385, + 0x20078280, + 0x210385d2, + 0x0782b000, + 0x0385d320, + 0x82810121, + 0x85d42007, + 0xb1002103, + 0xd5200782, + 0x01210385, + 0x20078282, + 0x210385d6, + 0x0782b200, + 0x0385d720, + 0x82830121, + 0x85d82007, + 0xb3002103, + 0xd9200782, + 0x01210385, + 0x20078284, + 0x210385da, + 0x0782b900, + 0x0385db20, + 0xcb830120, + 0x0b82dc20, + 0x00210382, + 0x200782ba, + 0x210385dd, + 0x07828b01, + 0x0385de20, + 0x82bb0021, + 0x85df2007, + 0x8c012103, + 0xe0200782, + 0x00210385, + 0x200782bc, + 0x210385e1, + 0x07828d01, + 0x0385e220, + 0x82bd0021, + 0x85e32007, + 0x8e012103, + 0xe4200782, + 0x00210385, + 0x200782e6, + 0x210385e5, + 0x0782b701, + 0x03820f83, + 0x82e70021, + 0x2103860b, + 0x0b82b801, + 0x0385e820, + 0x82e90021, + 0x21038607, + 0x0b82ba01, + 0x0385ea20, + 0x07830020, + 0x0b82eb20, + 0x01200382, + 0xec209b83, + 0x03820b82, + 0x0f820020, + 0x82ed1e21, + 0x2003820b, + 0x209b8301, + 0x820b82ee, + 0xec002103, + 0xef200782, + 0x01200385, + 0xf0209b83, + 0x03820b82, + 0x82ed0021, + 0x85f12007, + 0xbe012103, + 0xf2200782, + 0x00210385, + 0x200782f4, + 0x210385f3, + 0x0782c601, + 0x03820f83, + 0x82f90021, + 0x85f5200b, + 0xcb012103, + 0xf6200782, + 0x00210385, + 0x200782fa, + 0x210385f7, + 0x0782cc01, + 0x0385f820, + 0x82fb0021, + 0x85f92007, + 0xcd012503, + 0x001f0000, + 0x01240382, + 0x10030000, + 0x02200782, + 0x07200382, + 0x14200b82, + 0x08200782, + 0x09240382, + 0xb0020000, + 0x0a200782, + 0x0f240382, + 0xb4020000, + 0x27830782, + 0x23821120, + 0x0b821d20, + 0x03821220, + 0x0b821520, + 0x07822120, + 0x03821820, + 0x23821920, + 0x0782bc20, + 0x03821a20, + 0x02211f82, + 0x200782c0, + 0x82038220, + 0x2503211f, + 0x22200782, + 0x27200382, + 0x29202f82, + 0x28200782, + 0x07820382, + 0x82c40221, + 0x822a2007, + 0x822f2003, + 0x82c8203b, + 0x82302007, + 0x82312003, + 0x20078323, + 0x200b8232, + 0x200b8237, + 0x20078234, + 0x20038238, + 0x20238239, + 0x200782ce, + 0x2003823a, + 0x200b823f, + 0x200782d2, + 0x20038240, + 0x83238241, + 0x82422007, + 0x8245200b, + 0x8244200b, + 0x82482007, + 0x4f492003, + 0x1f21056f, + 0x200b824a, + 0x054b4f4d, + 0x82501f21, + 0x8251200b, + 0x20138323, + 0x200b8252, + 0x200b8257, + 0x2007824e, + 0x21038559, + 0x0782e302, + 0x03855b20, + 0x82e60221, + 0x855d2007, + 0xe7022103, + 0x5f200782, + 0x02210385, + 0x200782e8, + 0x20038260, + 0x203b8261, + 0x2007825a, + 0x20038262, + 0x200b8267, + 0x2007825e, + 0x20038268, + 0x206b8269, + 0x200782eb, + 0x2003826a, + 0x200b826f, + 0x200782ef, + 0x20038270, + 0x20238271, + 0x20078212, + 0x20038272, + 0x200b8273, + 0x2007821f, + 0x20038274, + 0x05d34e75, + 0x82761f21, + 0x8277200b, + 0x20f7830b, + 0x4e0b8278, + 0x1f21069b, + 0x200b827a, + 0x2017827b, + 0x2407824c, + 0x1f00007c, + 0x200b827d, + 0x2007825c, + 0x20038280, + 0x200b8281, + 0x20078266, + 0x20038282, + 0x830b8287, + 0x82882073, + 0x828f200b, + 0x82f62077, + 0x82902007, + 0x82912003, + 0x20738317, + 0x200b8292, + 0x830b8297, + 0x82982067, + 0x829f200b, + 0x82ff2023, + 0x82a02007, + 0x82a12003, + 0x007e2417, + 0x82a21f00, + 0x82a72003, + 0x204f830b, + 0x200b82a8, + 0x200b82af, + 0x20078208, + 0x200382b0, + 0x200b82b1, + 0x2007821a, + 0x210385b2, + 0x07826803, + 0x0385b320, + 0x82650321, + 0x85b42007, + 0x82032003, + 0xb61f21ff, + 0x03820b82, + 0x821c0321, + 0x85b72007, + 0x70032103, + 0xb8200782, + 0xb9240382, + 0xba020000, + 0x03830782, + 0x0b82bb20, + 0xbc204f83, + 0x03820f82, + 0x82f50221, + 0x85bd2007, + 0x83032003, + 0x82be20a3, + 0x2003820b, + 0x21b78203, + 0x0b82bf1f, + 0x03210382, + 0x20078299, + 0x210385c0, + 0x0782a303, + 0x0385c120, + 0x82a60321, + 0x85c22007, + 0x74032103, + 0xc3200782, + 0x03210385, + 0x20078271, + 0x210385c4, + 0x07827503, + 0x0385c620, + 0x822f0321, + 0x85c72007, + 0x7c032503, + 0xc81f0000, + 0xc9200382, + 0x2105ef51, + 0x0b82ca1f, + 0x0b82cb20, + 0xcc202b83, + 0x03820b82, + 0x82fe0221, + 0x85cd2007, + 0x9d032103, + 0xce200782, + 0x03210385, + 0x2007829f, + 0x210385cf, + 0x0782a103, + 0x0382d020, + 0x0000d124, + 0x07823a03, + 0x0382d220, + 0x0b82d320, + 0x07823d20, + 0x0385d620, + 0x823c0321, + 0x85d72007, + 0x3f032103, + 0xd8200782, + 0xd9200382, + 0x07836b82, + 0x0b82da20, + 0x4f52db20, + 0xdd1f2105, + 0x03820b82, + 0x829e0321, + 0x85de2007, + 0xa0032103, + 0xdf200782, + 0x03210385, + 0x200782a2, + 0x200382e0, + 0x205f82e3, + 0x20078255, + 0x200382e4, + 0x200b82e5, + 0x20078248, + 0x210385e6, + 0x07825403, + 0x0385e720, + 0x82590321, + 0x82e82007, + 0x82e92003, + 0x2103825f, + 0x0b82ea1f, + 0x0b82eb20, + 0x0782e420, + 0x0385ec20, + 0x82e20221, + 0x82ed2007, + 0x82ee2003, + 0x82a42047, + 0x85ef2007, + 0x9b032103, + 0xf2200782, + 0x03210385, + 0x20078280, + 0x210385f3, + 0x07827d03, + 0x0385f420, + 0x82810321, + 0x85f62007, + 0x64032103, + 0xf7200782, + 0x03210385, + 0x20078288, + 0x200382f8, + 0x206b82f9, + 0x200782dc, + 0x200382fa, + 0x200b82fb, + 0x200782ed, + 0x210385fc, + 0x07820703, + 0x0385fd20, + 0x829c0321, + 0x85fe2007, + 0x9a032403, + 0x82200000, + 0x2103831b, + 0x0b82ad07, + 0x03820920, + 0x00000b24, + 0x0782ae07, + 0x03851020, + 0x82970421, + 0x85112007, + 0x200b8403, + 0x820b8212, + 0x82042003, + 0x13202147, + 0x14240b82, + 0x98040000, + 0x15200782, + 0x04210385, + 0x2007829d, + 0x21038516, + 0x0782b204, + 0x03821820, + 0x23821920, + 0x07828d20, + 0x03851a20, + 0x82910421, + 0x821c2007, + 0x821d2003, + 0x008f2417, + 0x851e2000, + 0x92042103, + 0x20200782, + 0x21200382, + 0x83831782, + 0x0b822220, + 0x04210382, + 0x2007829f, + 0x21038526, + 0x07828604, + 0x03852f20, + 0x5f830720, + 0x0b823020, + 0x06210382, + 0x200782e0, + 0x23038232, + 0x07000033, + 0x20213f82, + 0x820b8235, + 0x23072103, + 0x39200782, + 0x3a200382, + 0x21052f50, + 0x0b823c20, + 0x04210382, + 0x200782b3, + 0x2103853d, + 0x0782b704, + 0x03823e20, + 0x23823f20, + 0x0782a120, + 0x03854420, + 0x82dc0621, + 0x85472007, + 0xb4042103, + 0x48200782, + 0x04210385, + 0x200782b6, + 0x21038549, + 0x0782b504, + 0x03857020, + 0x82400621, + 0x85712007, + 0xa3062103, + 0x74200782, + 0x7e230382, + 0x83060000, + 0x827f204f, + 0x2103820b, + 0x0782a806, + 0x00008024, + 0x17828e20, + 0x07825120, + 0x03859420, + 0x82bc0621, + 0x85a12007, + 0xcd062103, + 0xa4200782, + 0x06210385, + 0x200782ce, + 0x200382a6, + 0x202f82a7, + 0x200782cf, + 0x210385a9, + 0x0782d106, + 0x0385ab20, + 0x82d20621, + 0x85ac2007, + 0xca062103, + 0xae200782, + 0x06210385, + 0x200782d9, + 0x200382b1, + 0x203b82b2, + 0x200782d3, + 0x820382b4, + 0xd50621af, + 0xb8200782, + 0x06210385, + 0x200782da, + 0x200382b9, + 0x202382ba, + 0x200782d7, + 0x250385bd, + 0x0000db06, + 0x03851321, + 0x820a0721, + 0x85162007, + 0x4a042103, + 0x17200782, + 0x04210385, + 0x200782c3, + 0x21038520, + 0x0782c604, + 0x03852220, + 0x82c50421, + 0x85262007, + 0x82022003, + 0x2e2121f3, + 0x03820b82, + 0x820b0721, + 0x85502007, + 0xec062103, + 0xff820782, + 0x82522121, + 0x82f12077, + 0x8253200b, + 0x825a2003, + 0x82e4200b, + 0x825b2007, + 0x825e2003, + 0x82ed200b, + 0x85892007, + 0xf3062103, + 0x90200782, + 0x93240382, + 0x0c070000, + 0xe7200782, + 0x07250385, + 0x220000ab, + 0x21038502, + 0x07820507, + 0x03850620, + 0x826b0221, + 0x850f2007, + 0x09072103, + 0x11200782, + 0x07210385, + 0x20078208, + 0x21038512, + 0x0782f506, + 0x03851520, + 0x82dd0621, + 0x85192007, + 0xf8062103, + 0x1a200782, + 0x07210385, + 0x20078207, + 0x2103851e, + 0x07820407, + 0x03852b20, + 0x82060721, + 0x85482007, + 0x83072003, + 0x8260207f, + 0x8203820b, + 0x2200222e, + 0x280b8264, + 0x06000065, + 0x230000fc, + 0x21038503, + 0x0782ac07, + 0x03851820, + 0x82a80721, + 0x821c2007, + 0x001f2403, + 0x82b80400, + 0x85252007, + 0xa9072103, + 0x5f820782, + 0x03822320, + 0x00aa0725, + 0x85a02500, + 0x10072103, + 0xb2200782, + 0xb3240382, + 0x14070000, + 0xb6200782, + 0xb7200382, + 0x16200b82, + 0xbc200782, + 0xbd200382, + 0x5b820b82, + 0x82c02521, + 0x82c1200b, + 0x821a200b, + 0x85c62007, + 0x82072003, + 0xc92521f7, + 0x03820b82, + 0x82120721, + 0x85ca2007, + 0x20072103, + 0xcc200782, + 0x07250385, + 0x26000039, + 0x82038210, + 0x1c07212b, + 0x6a200782, + 0x07200385, + 0x27249f82, + 0x27000013, + 0x07210382, + 0x2007821e, + 0x20038552, + 0x210f8207, + 0x0b82e627, + 0x0000e723, + 0x247f8204, + 0x0000222e, + 0x21c3822e, + 0x0782be04, + 0x03823a20, + 0x17823b20, + 0x00009a24, + 0x0385b5a7, + 0x00db0125, + 0x8553ab00, + 0xdd012503, + 0x00fb0000, + 0x02200385, + 0xfb213382, + 0x240b8201, + 0x07000002, + 0x200782b4, + 0x28038203, + 0x02000004, + 0xfe000026, + 0x250385ff, + 0x0100b307, + 0x03826af1, + 0x53826b20, + 0x8300c721, + 0x4c0f0700, + 0x002c002c, + 0x0084004f, + 0x00d000b3, + 0x01f800e5, + 0x0141012a, + 0x0169014d, + 0x01920183, + 0x02e501c3, + 0x02350214, + 0x029d0276, + 0x03f202e1, + 0x03320316, + 0x0399036c, + 0x04cc03b6, + 0x04370404, + 0x04970465, + 0x05eb04ca, + 0x05780556, + 0x058e0583, + 0x05c305a7, + 0x061706f5, + 0x06760643, + 0x07c806a9, + 0x072c0707, + 0x076a074e, + 0x07cf07a4, + 0x081408ff, + 0x082c0820, + 0x08440838, + 0x085c0850, + 0x08740868, + 0x088c0880, + 0x08a40898, + 0x08bc08b0, + 0x08d808c8, + 0x08f008e4, + 0x090809fc, + 0x09520918, + 0x099a098e, + 0x09cd09c1, + 0x0a170ad9, + 0x0a2f0a23, + 0x0a470a3b, + 0x0a5f0a53, + 0x0a770a6b, + 0x0a8f0a83, + 0x0aa30a9b, + 0x0abb0aaf, + 0x0ad30ac7, + 0x0aeb0adf, + 0x0b030bf7, + 0x0b1b0b0f, + 0x0b330b27, + 0x0b4b0b3f, + 0x0b670b57, + 0x0bc60b97, + 0x0cf50bd2, + 0x0c0d0c01, + 0x0c250c19, + 0x0c3d0c31, + 0x0c550c49, + 0x0caa0c61, + 0x0cc20cb6, + 0x0cda0cce, + 0x0d0b0dff, + 0x0d230d17, + 0x0d3b0d2f, + 0x0d530d47, + 0x0d6b0d5f, + 0x0d9b0d77, + 0x0db30da7, + 0x0dcb0dbf, + 0x0de30dd7, + 0x0e060eef, + 0x0e1e0e12, + 0x0e3a0e2a, + 0x0e600e46, + 0x0e780e6c, + 0x0e900e84, + 0x0ea80e9c, + 0x0ec00eb4, + 0x0ed80ecc, + 0x0ef00ee4, + 0x0f080ffc, + 0x0f200f14, + 0x0f380f2c, + 0x0f500f44, + 0x0f680f5c, + 0x0f800f74, + 0x0f9c0f8c, + 0x10e40fa8, + 0x1052102a, + 0x109e1092, + 0x10b610aa, + 0x11ce10c2, + 0x11211115, + 0x1139112d, + 0x11511145, + 0x1169115d, + 0x11851179, + 0x119d1191, + 0x11b511a9, + 0x11cd11c1, + 0x121412d9, + 0x122c1220, + 0x12441238, + 0x125c1250, + 0x12821268, + 0x129a128e, + 0x12b212a6, + 0x12ca12be, + 0x12e212d6, + 0x13fa12ee, + 0x13121306, + 0x132a131e, + 0x13421336, + 0x13821376, + 0x139a138e, + 0x13b213a6, + 0x14f813ec, + 0x14101404, + 0x1428141c, + 0x14401434, + 0x1458144c, + 0x14701464, + 0x1488147c, + 0x14a01494, + 0x14b814ac, + 0x15ea14c4, + 0x1540150c, + 0x15971575, + 0x15af15a3, + 0x15c715bb, + 0x15df15d3, + 0x16f715eb, + 0x160f1603, + 0x1627161b, + 0x163f1633, + 0x165b164b, + 0x16731667, + 0x168b167f, + 0x17ec169b, + 0x174d1741, + 0x17b617aa, + 0x18fc17c2, + 0x18141808, + 0x182c1820, + 0x18441838, + 0x188b1850, + 0x18a31897, + 0x18ea18af, + 0x190219f6, + 0x191a190e, + 0x19321926, + 0x194a193e, + 0x19621956, + 0x197a196e, + 0x19921986, + 0x19ae199e, + 0x1a461afa, + 0x1a921a52, + 0x1aaa1a9e, + 0x1ac21ab6, + 0x1b4e1bce, + 0x1b661b5a, + 0x1b7e1b72, + 0x1b961b8a, + 0x1bcc1ba2, + 0x1be21bd7, + 0x1cf81bed, + 0x1c0e1c03, + 0x1c241c19, + 0x1c641c2f, + 0x1c7a1c6f, + 0x1c911c86, + 0x1ca91c9d, + 0x1cce1cb5, + 0x1dfe1cd9, + 0x1d161d0a, + 0x1d311d22, + 0x1d651d3d, + 0x1d7d1d71, + 0x1d951d89, + 0x1dad1da1, + 0x1dc51db9, + 0x1ddd1dd1, + 0x1ef51de9, + 0x1e0d1e01, + 0x1e251e19, + 0x1e3d1e31, + 0x1e551e49, + 0x1e6d1e61, + 0x1e851e79, + 0x1e9d1e91, + 0x1eb91ead, + 0x1f331ff2, + 0x1fc21f83, + 0x1fda1fce, + 0x1ff21fe6, + 0x204320fe, + 0x205b204f, + 0x20722067, + 0x208a207e, + 0x20a42095, + 0x20bb20af, + 0x20d320c7, + 0x20eb20df, + 0x210321f7, + 0x21762148, + 0x218e2182, + 0x21a6219a, + 0x21be21b2, + 0x22f721eb, + 0x220f2203, + 0x2227221b, + 0x223f2233, + 0x2257224b, + 0x226f2263, + 0x2287227b, + 0x229f2293, + 0x22e022ab, + 0x23f822ec, + 0x23102304, + 0x2356231c, + 0x23a12395, + 0x23b923ad, + 0x23d123c5, + 0x23e923dd, + 0x240124f5, + 0x2419240d, + 0x24312425, + 0x2449243d, + 0x24612455, + 0x24b8246d, + 0x251d25eb, + 0x25452539, + 0x25bd257e, + 0x264026fc, + 0x26b8268a, + 0x273b27fa, + 0x27ad276e, + 0x281128b5, + 0x28952844, + 0x291329d4, + 0x29782952, + 0x2a0b2ac9, + 0x2a752a3c, + 0x2bc72a98, + 0x2b0f2b07, + 0x2b2f2b1b, + 0x2b572b4b, + 0x2b902b63, + 0x2be12bac, + 0x2c222cef, + 0x2c982c55, + 0x2dfc2cca, + 0x2d522d23, + 0x2ecd2d9a, + 0x2e462e05, + 0x2ea32e84, + 0x2ff12ec2, + 0x2f3a2f20, + 0x2f842f5f, + 0x300230d6, + 0x305d3038, + 0x31d830a9, + 0x3139310e, + 0x318e3155, + 0x32da31bd, + 0x32433202, + 0x32ac3275, + 0x33f932d3, + 0x33573328, + 0x33953375, + 0x340534ce, + 0x341d3411, + 0x34a73457, + 0x34c734bb, + 0x34df34d3, + 0x35f734eb, + 0x350f3503, + 0x3527351b, + 0x353f3533, + 0x3578356c, + 0x35de35ac, + 0x36f635ea, + 0x360e3602, + 0x3626361a, + 0x363e3632, + 0x3656364a, + 0x366e3662, + 0x3686367a, + 0x36a23692, + 0x36ba36ae, + 0x36d236c6, + 0x372d37e2, + 0x3786377a, + 0x379a378e, + 0x37b237a6, + 0x381538be, + 0x382d3821, + 0x38453839, + 0x38653850, + 0x387c3871, + 0x38953887, + 0x38b838a0, + 0x38e938c4, + 0x393439fd, + 0x3944393c, + 0x396d3953, + 0x397d3975, + 0x39ba3985, + 0x39ca39c2, + 0x39ee39e6, + 0x3a103af6, + 0x3a2a3a18, + 0x3a4a3a32, + 0x3a5a3a52, + 0x3a9d3a95, + 0x3bfa3ac2, + 0x3b103b05, + 0x3b263b1b, + 0x3b393b2e, + 0x3b4c3b44, + 0x3cd33b8c, + 0x3c473c1d, + 0x3dcf3c8e, + 0x3d353d0b, + 0x3d803d64, + 0x3edc3db7, + 0x3e343e15, + 0x3eb33e87, + 0x3f173fe6, + 0x3f6f3f4b, + 0x3fdc3f9e, + 0x403140fa, + 0x40ab4074, + 0x413e41fb, + 0x418a417e, + 0x41a24196, + 0x41b841ad, + 0x41d041c4, + 0x41e841dc, + 0x42ff41f3, + 0x4215420a, + 0x42284220, + 0x42404234, + 0x4258424c, + 0x426e4263, + 0x427e4276, + 0x42944289, + 0x42a7429f, + 0x42bf42b3, + 0x42d742cb, + 0x42ed42e2, + 0x430043f8, + 0x4318430c, + 0x43304324, + 0x4348433c, + 0x435e4353, + 0x43714369, + 0x4389437d, + 0x43a14395, + 0x43b943ad, + 0x43c943c1, + 0x43df43d4, + 0x43f243ea, + 0x440a44fe, + 0x44224416, + 0x4439442d, + 0x444c4444, + 0x44644458, + 0x447c4470, + 0x45d64488, + 0x45644524, + 0x46bf456c, + 0x46654612, + 0x472347b8, + 0x479a478e, + 0x47b247a6, + 0x47ca47be, + 0x47e247d6, + 0x48fa47ee, + 0x48124806, + 0x482a481e, + 0x48424836, + 0x485a484e, + 0x48b54866, + 0x48cd48c1, + 0x48e548d9, + 0x49fd48f1, + 0x49154909, + 0x492d4921, + 0x49454939, + 0x495d4951, + 0x49754969, + 0x498d4981, + 0x49a54999, + 0x49bd49b1, + 0x49d549c9, + 0x49ed49e1, + 0x4a054af9, + 0x4a1d4a11, + 0x4a354a29, + 0x4a4d4a41, + 0x4a654a59, + 0x4a7d4a71, + 0x4a954a89, + 0x4aab4aa0, + 0x4ac14ab6, + 0x4ad74acc, + 0x4aed4ae2, + 0x4b034bf8, + 0x4b194b0e, + 0x4b2f4b24, + 0x4b454b3a, + 0x4b5d4b51, + 0x4b754b69, + 0x4b8d4b81, + 0x4ba54b99, + 0x4bbd4bb1, + 0x4bd54bc9, + 0x4bed4be1, + 0x4c054cf9, + 0x4c1d4c11, + 0x4c354c29, + 0x4c4d4c41, + 0x4c654c59, + 0x4c7d4c71, + 0x4c954c89, + 0x4cad4ca1, + 0x4cc54cb9, + 0x4cdd4cd1, + 0x4df54ce9, + 0x4d0d4d01, + 0x4d254d19, + 0x4d3d4d31, + 0x4d554d49, + 0x4d6d4d61, + 0x4d854d79, + 0x4d9c4d91, + 0x4db44da8, + 0x4dcc4dc0, + 0x4de44dd8, + 0x4efc4df0, + 0x4e144e08, + 0x4e2c4e20, + 0x4e444e38, + 0x4e5c4e50, + 0x4e744e68, + 0x4e8c4e80, + 0x4ea44e98, + 0x4ff04eb0, + 0x4f534f23, + 0x4f9c4f69, + 0x4fad4fa4, + 0x4fc54fb6, + 0x4fdc4fd3, + 0x4ff34fea, + 0x501950fc, + 0x502b5022, + 0x503d5034, + 0x504f5046, + 0x50615058, + 0x5073506a, + 0x5085507c, + 0x5097508e, + 0x50bc50a0, + 0x50e650d8, + 0x510e51ee, + 0x514e512e, + 0x51a7516e, + 0x52e851e0, + 0x5214520c, + 0x524e521c, + 0x529e5256, + 0x53ff52dd, + 0x5335530b, + 0x5367535f, + 0x5377536f, + 0x5387537f, + 0x5397538f, + 0x53f653c0, + 0x541754fe, + 0x544f5439, + 0x548f546b, + 0x55d954b8, + 0x5541550a, + 0x55715569, + 0x55b05579, + 0x55ed55bc, + 0x56fd55f5, + 0x56315605, + 0x56785639, + 0x56c756a5, + 0x56df56d3, + 0x570257eb, + 0x575e572b, + 0x579b5789, + 0x580158b3, + 0x58745844, + 0x58be58a1, + 0x59f958f1, + 0x5951591e, + 0x59995978, + 0x59ad59a1, + 0x59c159b9, + 0x59d559cd, + 0x59ed59e1, + 0x5a015af5, + 0x5a155a0d, + 0x5a8a5a58, + 0x5ac25a99, + 0x5b065bca, + 0x5b6c5b45, + 0x5b9e5b78, + 0x5cfc5bc5, + 0x5c185c10, + 0x5c325c2a, + 0x5c4b5c3a, + 0x5cad5c53, + 0x5ccd5cb5, + 0x5d025dec, + 0x5d3e5d1e, + 0x5d815d63, + 0x5ee45db1, + 0x5e135e0b, + 0x5e585e1b, + 0x5e945e64, + 0x5ea45e9c, + 0x5ed85eac, + 0x5f1b5fe0, + 0x5f495f41, + 0x5f615f55, + 0x5f845f6d, + 0x5fb25faa, + 0x60ee5fdd, + 0x60466004, + 0x60b36088, + 0x61f560db, + 0x61436124, + 0x619a6169, + 0x61c761bf, + 0x61db61d3, + 0x61ef61e7, + 0x620362fb, + 0x621b620f, + 0x622f6223, + 0x6289623b, + 0x635763f3, + 0x6393637c, + 0x64fb63bd, + 0x6452641f, + 0x64aa6491, + 0x653e65ff, + 0x65a86573, + 0x66e165ce, + 0x6613660b, + 0x6623661b, + 0x6644662b, + 0x6654664c, + 0x66bb6689, + 0x67f766e0, + 0x675f6721, + 0x67b46781, + 0x67d667bc, + 0x681a68de, + 0x68356822, + 0x6867685f, + 0x6877686f, + 0x6899687f, + 0x68a968a1, + 0x69e568ce, + 0x694b690d, + 0x69a2696f, + 0x6afa69e1, + 0x6a8c6a4d, + 0x6ac16aa2, + 0x6ad96acd, + 0x6b096be9, + 0x6b626b2a, + 0x6baa6b9a, + 0x6bd56bb6, + 0x6cff6bf3, + 0x6c146c0b, + 0x6c316c20, + 0x6c4e6c42, + 0x6c666c5a, + 0x6c7e6c72, + 0x6c976c8a, + 0x6cab6ca3, + 0x6cca6cb4, + 0x6cdf6cd6, + 0x6d146dfa, + 0x6d3f6d2e, + 0x6d8c6d50, + 0x6dd76dc8, + 0x6ef36de4, + 0x6e256e07, + 0x6e646e3e, + 0x6ee26ec5, + 0x6ffa6eee, + 0x6f126f06, + 0x6f586f1e, + 0x6f746f66, + 0x6f926f83, + 0x6fc06fa9, + 0x6fde6fcf, + 0x70fc6fed, + 0x70a67057, + 0x711f71f3, + 0x71ba7174, + 0x725f72f1, + 0x73fa72cb, + 0x73257302, + 0x73857359, + 0x73b673a2, + 0x74f673c8, + 0x7416740a, + 0x744a7432, + 0x74827458, + 0x74cf74a3, + 0x752a75f0, + 0x758b754e, + 0x75c0759c, + 0x761676dc, + 0x765f7642, + 0x76817675, + 0x7699768d, + 0x76b176a5, + 0x76c976bd, + 0x76e176d5, + 0x77f976ed, + 0x77117705, + 0x7729771d, + 0x77457739, + 0x775d7751, + 0x77797769, + 0x77ee77b3, + 0x782078fa, + 0x7838782c, + 0x787f7873, + 0x7897788b, + 0x78af78a3, + 0x78c778bb, + 0x78df78d3, + 0x78f778eb, + 0x790b79ff, + 0x79237917, + 0x793b792f, + 0x79537947, + 0x796b795f, + 0x79837977, + 0x799b798f, + 0x79b379a7, + 0x79f179c3, + 0x7a097afd, + 0x7a377a2b, + 0x7a4f7a43, + 0x7a677a5b, + 0x7a7f7a73, + 0x7a977a8b, + 0x7ae57ad9, + 0x7bfd7af1, + 0x7b2b7b09, + 0x7b437b37, + 0x7b5b7b4f, + 0x7b737b67, + 0x7b8b7b7f, + 0x7ba37b97, + 0x7bd37baf, + 0x7beb7bdf, + 0x7c037cf7, + 0x7c1b7c0f, + 0x7c3e7c32, + 0x7c567c4a, + 0x7c727c66, + 0x7c977c8b, + 0x7caf7ca3, + 0x7cc77cbb, + 0x7cdf7cd3, + 0x7df77ceb, + 0x7d0f7d03, + 0x7d277d1b, + 0x7d3f7d33, + 0x7d577d4b, + 0x7d6f7d63, + 0x7d877d7b, + 0x7d9f7d93, + 0x7db77dab, + 0x7e077ec7, + 0x7e3a7e2e, + 0x7e527e46, + 0x7e6a7e5e, + 0x7eba7e76, + 0x7fd27ec6, + 0x7f177f0b, + 0x7f2f7f23, + 0x7f477f3b, + 0x7f637f53, + 0x7f7b7f6f, + 0x7f937f87, + 0x7fab7f9f, + 0x7fc37fb7, + 0x800a80cf, + 0x80228016, + 0x803a802e, + 0x80528046, + 0x8077805e, + 0x808f8083, + 0x80a7809b, + 0x80bf80b3, + 0x80d780cb, + 0x80ef80e3, + 0x810781fb, + 0x811f8113, + 0x8137812b, + 0x8177816b, + 0x818f8183, + 0x81a7819b, + 0x81ed81e1, + 0x820582f9, + 0x821d8211, + 0x82358229, + 0x824d8241, + 0x82658259, + 0x827d8271, + 0x82958289, + 0x82ad82a1, + 0x83de82b9, + 0x83378302, + 0x838a8368, + 0x83c583bd, + 0x83dc83cd, + 0x84fd83f5, + 0x840d8405, + 0x8446843e, + 0x846a844e, + 0x847a8472, + 0x849a8492, + 0x84b484ac, + 0x84d384cb, + 0x851085db, + 0x853d8518, + 0x857d8575, + 0x85ae8585, + 0x860786c9, + 0x8631860f, + 0x86418639, + 0x86798671, + 0x87f486b8, + 0x87218715, + 0x87738748, + 0x8783877b, + 0x8793878b, + 0x87a3879b, + 0x88ce87ab, + 0x880b8803, + 0x88428823, + 0x88748858, + 0x88bc8896, + 0x890b89db, + 0x8961893c, + 0x89718969, + 0x89b289a6, + 0x89ea89e2, + 0x8afa89f2, + 0x8a2e8a26, + 0x8a958a6d, + 0x8ac48ab8, + 0x8adc8ad0, + 0x8b1a8bf3, + 0x8b798b4d, + 0x8ba08b8a, + 0x8c228ce4, + 0x8c788c4e, + 0x8cc08c92, + 0x8ded8cc8, + 0x8d438d1e, + 0x8d6a8d62, + 0x8d828d76, + 0x8d968d8a, + 0x8daa8d9e, + 0x8dbe8db6, + 0x8ed68dca, + 0x8e5b8e36, + 0x8e978e6e, + 0x8ff58ed2, + 0x8f668f27, + 0x90d08f7f, + 0x902c900d, + 0x9081904b, + 0x90c090b8, + 0x90d090c8, + 0x90e090d8, + 0x90f090e8, + 0x910891fc, + 0x913c9122, + 0x915e914d, + 0x91d49199, + 0x91e691dd, + 0x92f891ef, + 0x920a9201, + 0x921c9213, + 0x922e9225, + 0x92409237, + 0x92529249, + 0x9264925b, + 0x9276926d, + 0x9288927f, + 0x929a9291, + 0x92ac92a3, + 0x92be92b5, + 0x92db92c7, + 0x92f292e7, + 0x930493fb, + 0x9316930d, + 0x934e933b, + 0x93ac9373, + 0x94f793c8, + 0x9447942f, + 0x94c8948f, + 0x95fc94e2, + 0x95309512, + 0x95429539, + 0x9554954b, + 0x9566955d, + 0x9578956f, + 0x958a9581, + 0x959c9593, + 0x95ae95a5, + 0x95be95b6, + 0x96e995c6, + 0x9648961c, + 0x967a9665, + 0x96bd968d, + 0x96df96d2, + 0x971397fa, + 0x974b9722, + 0x9799976d, + 0x98f297b7, + 0x98519815, + 0x98819863, + 0x99d5989d, + 0x991f9901, + 0x996a9934, + 0x99c6999b, + 0x9a2c9af9, + 0x9ab39a50, + 0x9bf09ad3, + 0x9b359b1c, + 0x9b7f9b50, + 0x9bcb9b9f, + 0x9c2c9cfc, + 0x9c859c4a, + 0x9cc89ca7, + 0x9d049dde, + 0x9d4f9d24, + 0x9d869d62, + 0x9da69d99, + 0x9e019ec7, + 0x9e779e3c, + 0x9fda9ea9, + 0x9f269f19, + 0x9f3f9f33, + 0x9f599f4c, + 0xa0c39f82, + 0xa041a004, + 0xa090a06c, + 0xa111a1d7, + 0xa1a5a149, + 0xa234a2f0, + 0xa2a8a263, + 0xa32fa3e7, + 0xa3b6a364, + 0xa41ba4ef, + 0xa472a44e, + 0xa4baa48b, + 0xa4d1a4c9, + 0xa4eaa4d9, + 0xa507a5f6, + 0xa529a518, + 0xa54ba53a, + 0xa56da55c, + 0xa58fa57e, + 0xa5b1a5a0, + 0xa5d3a5c2, + 0xa6f5a5e4, + 0xa617a606, + 0xa63da62c, + 0xa65ea651, + 0xa6a3a677, + 0xa6b7a6ac, + 0xa6e2a6cd, + 0xa71ba7ff, + 0xa74ba735, + 0xa793a76b, + 0xa7aea79e, + 0xa83da8ff, + 0xa893a872, + 0xa9c1a8ae, + 0xa949a900, + 0xa979a961, + 0xa9a8a990, + 0xaac5a9b5, + 0xaa2caa14, + 0xaa55aa3d, + 0xaa7faa66, + 0xaaaaaa91, + 0xaad6aabc, + 0xab25abee, + 0xab78ab44, + 0xaba8ab99, + 0xabc3abb4, + 0xabd4abcb, + 0xabe6abdd, + 0xacf8abef, + 0xac0eac01, + 0xac1fac17, + 0xac2fac27, + 0xac41ac38, + 0xac53ac4a, + 0xac65ac5c, + 0xac77ac6e, + 0xad3ead80, + 0xad5aad4c, + 0xad76ad68, + 0xad92ad84, + 0xadb8ada5, + 0xae05aedf, + 0xae1fae12, + 0xae2fae27, + 0xae6bae4f, + 0xaea2ae86, + 0xaeceaeb8, + 0xaf18aff3, + 0xaf4aaf31, + 0xaf94af6f, + 0xafbeafa9, + 0xafe4afd1, + 0xb00eb0f9, + 0xb049b02e, + 0xb080b067, + 0xb0a4b09c, + 0xb0c4b0b4, + 0xb1ebb0d2, + 0xb115b105, + 0xb139b125, + 0xb14eb145, + 0xb160b157, + 0xb197b17a, + 0xb1d2b1b4, + 0xb2ffb1f2, + 0xb218b20f, + 0xb22ab221, + 0xb23cb233, + 0xb27cb263, + 0xb29db28c, + 0xb2e2b2c8, + 0xb2f2b2ea, + 0xb327b3fa, + 0xb35fb344, + 0xb395b368, + 0xb4efb3c2, + 0xb449b41c, + 0xb4b9b48d, + 0xb517b5e5, + 0xb563b549, + 0xb597b57d, + 0xb5d8b5b1, + 0xb62eb6fd, + 0xb686b65f, + 0xb6cfb6a8, + 0xb725b7f1, + 0xb790b754, + 0xb8f0b7c9, + 0xb838b817, + 0xb892b859, + 0xb9d6b8b4, + 0x2801820f, + 0xb9aeb992, + 0xba04badd, + 0x08018e17, + 0x2fba235e, + 0x05000000, + 0x00005900, + 0x94023502, + 0x09000300, + 0x12000f00, + 0x00001500, + 0x11211133, + 0x27272125, + 0x33370723, + 0x17233737, + 0x01273703, + 0x01590711, + 0x0190fedc, + 0x04344901, + 0x31043636, + 0x7942eb42, + 0x58017f7f, + 0xfd94027e, + 0x67843a6c, + 0x775ec567, + 0xe68dfe77, + 0x0132fee8, + 0x0200e8ce, + 0x00244f82, + 0x90021d02, + 0x11315582, + 0x07130000, + 0x26262733, + 0x06062327, + 0x13331303, + 0x08598223, + 0xc51fcb23, + 0x1020121f, + 0xda200f04, + 0x59de5ede, + 0x013fef3e, + 0x3764646f, + 0x6d39396d, + 0x90025afe, + 0xc8c870fd, + 0x20438200, + 0x209d825a, + 0x24458224, + 0x001a0011, + 0x28998323, + 0x16163233, + 0x07061415, + 0x2b068415, + 0x33032306, + 0x34353632, + 0x11232326, + 0x49080887, + 0x6543c35a, + 0x3b2f3139, + 0x4a703f4b, + 0x4a54617e, + 0x72654d4d, + 0x565d5e55, + 0x20900272, + 0x4f313a46, + 0x4e0b040f, + 0x2a564044, + 0x323a7901, + 0xf4fd3039, + 0x393d423f, + 0x34000100, + 0x1b02f4ff, + 0x1d009c02, + 0x22050000, + 0x34352626, + 0x6b823636, + 0x2607172b, + 0x06222326, + 0x16141506, + 0x08608216, + 0x06173738, + 0x52520106, + 0x844c4b81, + 0x1c5c3c53, + 0x2a421a2d, + 0x32335d3e, + 0x4a2f3e5b, + 0x62272e1f, + 0x6b98510c, + 0x3152986a, + 0x221c3620, + 0x52527641, + 0x22284279, + 0x00322d34, + 0xc7830002, + 0xc7823420, + 0x11000822, + 0xc482c586, + 0x88272321, + 0x98a427b3, + 0x55959d9e, + 0x0082734b, + 0x90024b2b, + 0xae9d9ca9, + 0x7c7c8b44, + 0x82978285, + 0xde012139, + 0x0b203982, + 0x21263783, + 0x33152115, + 0x05822315, + 0x7a015a2f, + 0xf9f9d9fe, + 0x90023101, + 0xee47ce46, + 0x20298647, + 0x202982d4, + 0x20298a09, + 0x21278411, + 0x2582fafa, + 0xfe46de23, + 0x20e786da, + 0x20e78226, + 0x82e79720, + 0x35372593, + 0x11333523, + 0x5c39ea82, + 0x4e4c8656, + 0x5d445788, + 0x42192e1c, + 0x35624232, + 0x40236971, + 0x1fd78b13, + 0x24ea8669, + 0x1a361e33, + 0x2aea8224, + 0x1215917c, + 0xecfe45ab, + 0x85002b21, + 0x32022189, + 0x3326b387, + 0x33112111, + 0x05822311, + 0x01535a33, + 0xfe545431, + 0xfe9002cf, + 0xfd1301ed, + 0xfe350170, + 0x212d85cb, + 0x2d82ad00, + 0xb7830320, + 0x5a113327, + 0xfd900253, + 0x24178270, + 0x01f4ff1f, + 0x28178289, + 0x1700000f, + 0x16372722, + 0x20998216, + 0x3c4a8235, + 0xd4060614, + 0x163c3a7b, + 0x34352338, + 0x0c502554, + 0x23272a69, + 0xc7014b41, + 0x5e3831fe, + 0x214f8537, + 0x37823f02, + 0x4f850c20, + 0x33013333, + 0x03231307, + 0x535a1507, + 0x5e110103, + 0xc45dedcd, + 0x29818271, + 0xfa4901b7, + 0x55016afe, + 0xb186d085, + 0x82cc0121, + 0x85052033, + 0x82212033, + 0x1f01212c, + 0xb7218782, + 0x211d8647, + 0x1d827d02, + 0x1d841d20, + 0x16161328, + 0x36363317, + 0xd5831337, + 0x36342508, + 0x03072337, + 0x23270323, + 0x11151616, + 0x0c7e645a, + 0x0c040c17, + 0x657c0c15, + 0x0403084e, + 0x7c377c34, + 0x07030434, + 0xa2236f82, + 0x82224522, + 0x5e012102, + 0x692ef782, + 0x952b6b2c, + 0x5401acfe, + 0x2c6b2b95, + 0xb38697fe, + 0x61822d20, + 0x61851320, + 0x26331723, + 0x88ea8326, + 0xed562257, + 0x25468247, + 0x47ee564f, + 0x4d830404, + 0x32886426, + 0x5301346b, + 0x9d324b82, + 0x34683187, + 0x0200a9fe, + 0xf4ff3400, + 0x9c026502, + 0xc3420f00, + 0x1642080e, + 0x06061415, + 0x36363227, + 0x23263435, + 0x14150622, + 0x4c011616, + 0x47477f52, + 0x7e53527f, + 0x537e4848, + 0x6a30573b, + 0x306a5858, + 0x9a540c58, + 0x51976969, + 0x69699751, + 0x4349549a, + 0x8e7a5279, + 0x79527a8e, + 0xc1420043, + 0x820b2006, + 0x000b22a1, + 0x0a874314, + 0x11232322, + 0x3b097843, + 0x3e6e4abb, + 0x626c6c86, + 0x56575356, + 0x2490025e, + 0x64674855, + 0x4801fcfe, + 0x37474641, + 0x5b229f84, + 0x9f827302, + 0x2a000d25, + 0x8c250000, + 0x2205258f, + 0x022e2726, + 0x84067343, + 0x160721af, + 0x20086f43, + 0x279f884c, + 0x7a5b0301, + 0x3c6c471d, + 0x3a2fb985, + 0x55174668, + 0x0d221635, + 0x39320f10, + 0x83547b43, + 0x7b5429ac, + 0x4359de43, + 0x6092580a, + 0x5e2ac785, + 0x2b0c5990, + 0x4004052c, + 0xc3860906, + 0xc3822020, + 0x17000e22, + 0x0723c38a, + 0x8b032313, + 0xcd2c08c6, + 0x503b6843, + 0x9e5ea744, + 0x524d6e77, + 0x026e4d52, + 0x44512390, + 0xfe115d4c, + 0xfe1501e2, + 0x3f5901eb, + 0x00344140, + 0x2a000100, + 0xef01f4ff, + 0x2d23cf82, + 0x82050000, + 0x06a042bf, + 0x26263423, + 0x44cb8927, + 0x5908063f, + 0x16161415, + 0x021e1717, + 0x06061415, + 0x76451001, + 0x5f23322b, + 0x1d484133, + 0x1f5e1f31, + 0x5e35293d, + 0x23643b3b, + 0x2e491e2d, + 0x32214337, + 0x3d265d1a, + 0x0c643624, + 0x253a2c35, + 0x22303b2d, + 0x290e1c28, + 0x30422a0d, + 0x2d2d4f32, + 0x211d3624, + 0x291f2c34, + 0x10280b1a, + 0x3431412d, + 0x87823255, + 0x8c821c20, + 0xd582fc20, + 0xd3830720, + 0x21352330, + 0xe2112315, + 0xc6e001c6, + 0x46464a02, + 0x1c82b6fd, + 0xff570025, + 0x822e02f4, + 0x84152021, + 0x352624a9, + 0x44113311, + 0x362005cf, + 0x93820a84, + 0x43432208, + 0x29533e6b, + 0x462c2b45, + 0x6a3e5029, + 0x697c360c, + 0x7dfe8101, + 0x26265b4f, + 0x83014f5b, + 0x7c697ffe, + 0x24698236, + 0x02000000, + 0x20478203, + 0x2169820d, + 0x07433303, + 0xd2033509, + 0x126959d2, + 0x1204131b, + 0x5569111c, + 0xfe9002d0, + 0x3a653a9e, + 0x01230282, + 0x8270fd62, + 0x82172037, + 0x82fa2037, + 0x8e212037, + 0x21418a37, + 0x1f460323, + 0x07230805, + 0x568ba203, + 0x09140945, + 0x0b180b04, + 0x0c5b4c5b, + 0x09040c18, + 0x50450a12, + 0x09636488, + 0x0704080f, + 0x82610812, + 0x359b2c5f, + 0x6b35356a, + 0xfe650134, + 0x856b349b, + 0x70fd2609, + 0x49268b01, + 0x21028226, + 0x738275fe, + 0xf8820f20, + 0x7382f220, + 0x73821920, + 0x33031323, + 0x06b44317, + 0x03333724, + 0x8b462313, + 0x07370806, + 0xb2bf0f07, + 0x170d595c, + 0x150e040f, + 0xb358570c, + 0x0d605cbf, + 0x0e04101b, + 0x015f0c1a, + 0xa83d0153, + 0x1d1d2c16, + 0xfea8162c, + 0xb1b1febf, + 0x1e1e3318, + 0x00b11833, + 0x82ffff01, + 0x44dd2059, + 0x33210597, + 0x3c598c35, + 0x59c5c415, + 0x101f1055, + 0x0f221104, + 0xfec55754, + 0x24b99201, + 0x46252546, + 0x6efeb924, + 0x209382fe, + 0x2039822d, + 0x06a145f1, + 0x01358c08, + 0x15213521, + 0x2d152101, + 0xc6fe5901, + 0xa6fea201, + 0x02325d01, + 0xfd314618, + 0x000047e8, + 0xff340002, + 0x01b101f4, + 0x001a00f2, + 0x17000024, + 0x34352622, + 0x26343736, + 0x06222326, + 0x36362707, + 0x15163233, + 0x23272311, + 0x32270606, + 0x06353736, + 0x16141506, + 0x8f513dc2, + 0x282b119b, + 0x201d4a2a, + 0x593a6322, + 0x03074450, + 0x23165122, + 0x6179233e, + 0x41490c32, + 0x1f115550, + 0x14202338, + 0x6d291639, + 0x3ad6fe5b, + 0x22422a1c, + 0x3c0f871f, + 0x8225292f, + 0x8252206f, + 0x02fb256f, + 0x001300c8, + 0x27051946, + 0x23072327, + 0x07153311, + 0x41446b85, + 0x05404405, + 0x15073708, + 0x29011616, + 0x03204922, + 0x02524207, + 0x5f284f21, + 0x465f3b62, + 0x453b4f3c, + 0x2023401f, + 0x1d210c3f, + 0xc2c80232, + 0x86271d58, + 0x3e765371, + 0x505a6745, + 0xff202263, + 0xfc82171c, + 0x822e0021, + 0x82af2065, + 0x461c20d5, + 0x33081b7d, + 0x01060617, + 0x3c684012, + 0x303e6b41, + 0x152a1945, + 0x452c1d2f, + 0x22435327, + 0x2124163a, + 0x723c0c50, + 0x3c725250, + 0x13361722, + 0x38552f18, + 0x141d6753, + 0x00211d37, + 0x2f20c182, + 0xd9205b82, + 0x3141c187, + 0x33362705, + 0x27171632, + 0x2a413335, + 0x35372107, + 0x0808ce47, + 0x6e5bf832, + 0x2a37613b, + 0x5304203e, + 0x1c030744, + 0x3c40194c, + 0x271e391f, + 0x0c46263f, + 0x734f7985, + 0x531a1e3e, + 0x3938fdbb, + 0x4345291c, + 0x2f171cfe, + 0x63573853, + 0xbf836382, + 0xbf82ca20, + 0x1f001822, + 0x1524c18c, + 0x21070614, + 0x0808b244, + 0x34210346, + 0x06222326, + 0x6a411701, + 0x37643f3e, + 0x0201655d, + 0x5705b8fe, + 0x1b3b2346, + 0xcb4f1f1d, + 0x393f0401, + 0x3d0c5133, + 0x72504f72, + 0x0d687c3e, + 0x5c4d0919, + 0x14361115, + 0x4a26011e, + 0x01004f4d, + 0x00001e00, + 0xd4023f01, + 0x24058b49, + 0x35373523, + 0x20c88434, + 0x08548207, + 0x3315152b, + 0x60112315, + 0x49454242, + 0x12102a17, + 0x67441c1b, + 0x3ea30167, + 0x574a4d05, + 0x0c3f0709, + 0xfe434d5e, + 0x0003005d, + 0x0120ff2d, + 0x24a782ec, + 0x003d0031, + 0x083f424d, + 0x4a82fd82, + 0x06853720, + 0x4c825284, + 0x2a064849, + 0x06062722, + 0x33161415, + 0x82163233, + 0x030621cc, + 0x20055649, + 0x20138322, + 0x220b8513, + 0x85262223, + 0xf67f0823, + 0x21267059, + 0x13221912, + 0x54322718, + 0x0d241431, + 0x171164a9, + 0x27325030, + 0x25120d22, + 0x55555e31, + 0x2a4c6e3c, + 0x2b2b3c3d, + 0x46363d3c, + 0x542f3354, + 0x1a10210e, + 0x44e04b18, + 0x16391f3f, + 0x1c280b04, + 0x040d2e1f, + 0x352b4414, + 0x05072a4e, + 0x1f35103f, + 0x11294c34, + 0x17141b0b, + 0x2d3d371e, + 0xb1012f4c, + 0x3c35353f, + 0x3f35353c, + 0x263d88fe, + 0x04041a22, + 0x27152a13, + 0x0001002e, + 0x01000052, + 0x46c802d7, + 0x9b420681, + 0x11380807, + 0x26341123, + 0x07062223, + 0x03525211, + 0x4d324d23, + 0x302c5247, + 0x02253b25, + 0x2164c2c8, + 0xfe5d612f, + 0x442901cc, + 0xfe25263e, + 0xffff00a0, + 0x00004500, + 0xb602b300, + 0x5c012602, + 0x06230982, + 0x827c4c07, + 0xd8ff2515, + 0xb20027ff, + 0xd6201584, + 0x7b201585, + 0x6f846a82, + 0x6f82e620, + 0x3d074948, + 0x13073313, + 0x15072723, + 0xcf035152, + 0x5ab9a35b, + 0xc8025b8e, + 0x00011efe, + 0xeaddfec3, + 0x3184806a, + 0x00f4ff23, + 0x203182d8, + 0x0573410f, + 0x11331123, + 0x07c74614, + 0x292ea939, + 0x04090e52, + 0x080b0707, + 0x35390c16, + 0x94fd6602, + 0x01011113, + 0x8504043e, + 0xf10232d9, + 0x2100f201, + 0x11330000, + 0x36331733, + 0x16323336, + 0x20058417, + 0x20df8615, + 0x08078807, + 0x07445221, + 0x2b4c2003, + 0x260f3f38, + 0x494b2c4e, + 0x362e2c52, + 0x2f2c5244, + 0xe6014436, + 0x312f2346, + 0x8734292c, + 0xfe4b22f4, + 0x82fb83a0, + 0x21638506, + 0x6382d701, + 0x8605bf47, + 0x225d8763, + 0x83110706, + 0x4e232156, + 0x84083e41, + 0x0c3d414c, + 0x2006ff42, + 0x224382f0, + 0x421b000f, + 0x16200cff, + 0x44066348, + 0x15370521, + 0x0f011614, + 0x3f3f673b, + 0x663c3b67, + 0x3c663f3f, + 0x3f4d4d3f, + 0x434e4e3e, + 0x3c2f06bb, + 0x72505272, + 0x5367443c, + 0x54686854, + 0x82006753, + 0xff522457, + 0x82fb0133, + 0x00132557, + 0x17000020, + 0x83080141, + 0x22232555, + 0x15172726, + 0x25068342, + 0x15070622, + 0xa9831616, + 0x4f212608, + 0x3b625e2b, + 0x4322385f, + 0x3c770222, + 0x1f453b4f, + 0x3e21243f, + 0x38b302cd, + 0x7187281c, + 0x1e3e7652, + 0x01a4551a, + 0x0a7d4406, + 0x2f000222, + 0xd9206582, + 0x05246587, + 0x06063735, + 0x75485c82, + 0x33172606, + 0x03113337, + 0x0a214432, + 0x04860125, + 0x442a4b1d, + 0x40250526, + 0x42080221, + 0x082244cf, + 0x58adcd30, + 0x7985281c, + 0x1d3e734f, + 0x4dfd2e1d, + 0x23440601, + 0x05a54209, + 0x65825e20, + 0xcb411120, + 0x0607480a, + 0x08056441, + 0x29481921, + 0x0c10171d, + 0x431f0f14, + 0x58e60119, + 0x480a362e, + 0x3e320404, + 0x0000c8fe, + 0xff1c0001, + 0x828301f4, + 0x002a233d, + 0x55481700, + 0x022e210d, + 0x49080744, + 0x524807c7, + 0xd1460806, + 0x29235e34, + 0x302b4420, + 0x1b332130, + 0x592a4222, + 0x1c4e2d4f, + 0x20361928, + 0x301e2b2e, + 0x2d44231b, + 0x270c4f29, + 0x2119371c, + 0x22191f2d, + 0x210d0a17, + 0x4f3b2935, + 0x13341720, + 0x171c2a18, + 0x0d0b151d, + 0x272e3721, + 0x7d822842, + 0x7d821820, + 0x6e024524, + 0x7d841700, + 0x2311352a, + 0x33373735, + 0x23153315, + 0x0809c742, + 0x3d4eeb23, + 0x450a4c48, + 0x2a218383, + 0x100c1e0d, + 0x5a0c2f14, + 0x3e0d0148, + 0x43888805, + 0x312df2fe, + 0x073e0409, + 0x2049820b, + 0x2449824b, + 0x00e601ce, + 0x0e094314, + 0x8c451120, + 0xe0200806, + 0x2b53484d, + 0x223b2630, + 0x03074452, + 0x610c4c22, + 0xfe34015d, + 0x273e44d7, + 0xfe59012b, + 0x30284c1a, + 0x0c244382, + 0xc7010000, + 0x6f484382, + 0xafbb3b10, + 0x170b5c55, + 0x170b040b, + 0xac515c0a, + 0xecfee601, + 0x23234824, + 0x14012448, + 0x37821afe, + 0x00001824, + 0x3782b602, + 0x3c246f48, + 0x4854879f, + 0x04070e08, + 0x4b091008, + 0x11094c50, + 0x0f080408, + 0x824e4707, + 0x0f094664, + 0x21158209, + 0x5f82440a, + 0x4322e723, + 0x22028222, + 0x89fe1901, + 0x011a2a09, + 0x25442305, + 0xfe234525, + 0x207382fc, + 0x20ab820e, + 0x257382b0, + 0x33000019, + 0x6f482737, + 0x1707220a, + 0x086f4823, + 0x9f0e2d08, + 0x0b415993, + 0x0b040d18, + 0x563b0b16, + 0x47599e93, + 0x040e1a0d, + 0x420c180d, + 0x136be8fe, + 0x2a14142a, + 0xf5f16b13, + 0x152c1671, + 0x71172b15, + 0x0c245582, + 0xc7012fff, + 0x1b205582, + 0x210b0d42, + 0x7c493737, + 0x0e37080c, + 0x1d105a02, + 0x1408100c, + 0x0f362909, + 0x6355c30b, + 0x040b190b, + 0x570a140b, + 0x2f11b750, + 0x0406d145, + 0x3b050241, + 0xe701242d, + 0x481ff3fe, + 0x20482122, + 0xf2fd0d01, + 0x822d4c30, + 0x1f0021b0, + 0x8f200482, + 0x09205f82, + 0x3522b582, + 0x91482301, + 0x011f3305, + 0x4c01e400, + 0x080100ff, + 0x4377012c, + 0x4389fe2c, + 0xcf4fffff, + 0x63032f05, + 0x02002602, + 0x07000000, + 0x0f013b07, + 0x17920000, + 0x178c3e20, + 0x2f884620, + 0x178c4120, + 0x17884920, + 0x178c4320, + 0x17882d20, + 0x178c4f20, + 0x17881820, + 0x178c4520, + 0x17884a20, + 0x178c4a20, + 0x17887020, + 0x178c5320, + 0x17884d20, + 0x17875720, + 0x0232ff25, + 0x8890021d, + 0x8c692017, + 0x8868202f, + 0x8c512017, + 0x88782017, + 0x96902017, + 0x8c922017, + 0x888a2017, + 0x8c94202f, + 0x88ab2017, + 0x8b962017, + 0x4103208f, + 0x27220737, + 0x17834107, + 0x07070022, + 0xb420978d, + 0x98203788, + 0x17894f8c, + 0x178c9a20, + 0x2f88b820, + 0x178c9c20, + 0x1788af20, + 0x7f8c9e20, + 0x22075741, + 0x8b4a0727, + 0x02002d7f, + 0x2cff0300, + 0x90023c02, + 0x23000900, + 0x2e0bd751, + 0x35262201, + 0x23373634, + 0x23072327, + 0x48133313, + 0x3224054b, + 0x06061737, + 0x3609e951, + 0x38280f01, + 0x3e131932, + 0xde553fef, + 0x2d23de5e, + 0x1317121c, + 0x512d0f17, + 0xfd3708f8, + 0x292b2c86, + 0xc8c81143, + 0x70fd9002, + 0x17203d0e, + 0x0b2d0e17, + 0x84030011, + 0x821d2073, + 0x00112273, + 0x2075831b, + 0x256b8505, + 0x14150617, + 0x63843316, + 0x5f520320, + 0x1c012b10, + 0x24333828, + 0x111e3721, + 0x63821316, + 0x6e526520, + 0x2cd42810, + 0x1a472c2b, + 0x8533291f, + 0x43022165, + 0x210f7d52, + 0x7785ffff, + 0x0263032d, + 0x004c0026, + 0x07070000, + 0x820f013e, + 0x00022607, + 0x03000008, + 0x2c8f8205, + 0x00150005, + 0x33070100, + 0x01062311, + 0x099b5101, + 0x35212008, + 0x22010723, + 0x3504ac3d, + 0x5801b0fe, + 0xeafe9b01, + 0x2001e8e8, + 0x63ce8cfe, + 0x01767801, + 0x82fe6b4c, + 0xce4627cb, + 0xbf47ee47, + 0x658200bf, + 0x03214d84, + 0x2065826b, + 0x825d824e, + 0x35022365, + 0x17880800, + 0x17882020, + 0x17834520, + 0x00030027, + 0x0200001e, + 0x207d8235, + 0x28098215, + 0x3300002b, + 0x37352335, + 0x21175311, + 0x33154008, + 0x4d6b2315, + 0x6543c34d, + 0x483a3839, + 0x49703f50, + 0x4c53627f, + 0x73654d4f, + 0x565d5f54, + 0xab989873, + 0xaa010437, + 0x30384620, + 0x0b040f4b, + 0x57424550, + 0x397c012b, + 0xfd303637, + 0x414643ed, + 0x833b5f3c, + 0x825a20ab, + 0x0324227b, + 0x20938235, + 0x23ab8403, + 0x001f014d, + 0xff251784, + 0x02240256, + 0x22178890, + 0x842e0177, + 0xff342617, + 0x021b021e, + 0x2017829c, + 0x222f8404, + 0x8657016e, + 0x02f42417, + 0x8863031b, + 0x013e2217, + 0x20178a49, + 0x20178846, + 0x20178c41, + 0x2017884d, + 0x83178c57, + 0x205f858f, + 0x8317864d, + 0x033421a7, + 0x05202f83, + 0x57227784, + 0x5f843401, + 0x2f831785, + 0x4d201785, + 0xff231787, + 0x84340232, + 0x221785bf, + 0x88310169, + 0x20178bd7, + 0x24178677, + 0x02000021, + 0x222f824a, + 0x85010106, + 0x00002327, + 0xcf84de01, + 0x6f840620, + 0x22013b22, + 0x3e201794, + 0xe783178c, + 0x41202f85, + 0xb783178c, + 0x57201785, + 0x2d20178c, + 0x1785ff82, + 0x178c4f20, + 0x17881820, + 0x178c4520, + 0x17884a20, + 0x178c4a20, + 0x4785ff83, + 0x17874d20, + 0x0132ff23, + 0x85ff84de, + 0x01692217, + 0x20bf8a2a, + 0x20478868, + 0x20478c51, + 0x20178849, + 0x23178943, + 0x78030102, + 0x90201788, + 0x4f241786, + 0xde010000, + 0x9220178a, + 0x01232f89, + 0x888a03f1, + 0x8c94202f, + 0x88ab205f, + 0x8b962017, + 0x410320a7, + 0x27220737, + 0x17834107, + 0x07070022, + 0x0029af84, + 0xff5a0001, + 0x02ee012c, + 0x069d4d90, + 0x36343525, + 0x43112137, + 0x23220998, + 0x3244020e, + 0x9e012708, + 0x1c2f3828, + 0x4755d1fe, + 0x17033007, + 0x121e1b2a, + 0x0e171315, + 0x2b2cd42e, + 0x55124229, + 0x03230658, + 0x441a2f1f, + 0xc2820522, + 0xde205f84, + 0x23205f8c, + 0x29565f8b, + 0x05934405, + 0x27310126, + 0xc01a2e38, + 0x6f245f87, + 0x1d1a2a18, + 0x21225f92, + 0x5e851832, + 0x85ffff21, + 0x6303215d, + 0x6f26f582, + 0x07000000, + 0xdd843e07, + 0x5a000322, + 0xde287a82, + 0x0b00c803, + 0x13000f00, + 0x2a0add55, + 0x01152115, + 0x27152135, + 0x56173727, + 0xfe27080f, + 0x980c01be, + 0x8627791f, + 0xdf0227be, + 0x265c3939, + 0x5d833067, + 0xd4224582, + 0x5d823503, + 0x5d840720, + 0x1e014d22, + 0x20087343, + 0x20758426, + 0x22178408, + 0x8a5f013e, + 0x82462017, + 0x2017852f, + 0x20178c41, + 0x2017884a, + 0x83178c4a, + 0x202f855f, + 0x2417884d, + 0x0226021e, + 0x202f889c, + 0x202f8c6c, + 0x2017884d, + 0x20178c57, + 0x20178818, + 0x20178c45, + 0x20178849, + 0x20178343, + 0x05b95700, + 0x24036524, + 0x914c3200, + 0x2617210c, + 0x4b0f2d4b, + 0x35460683, + 0x56362005, + 0x1a300fe3, + 0x3e06132e, + 0x0c1e1433, + 0x0b0f0810, + 0x10101c19, + 0x3216f156, + 0x14140607, + 0x05083d30, + 0x1f06033f, + 0x17221617, + 0x561b1337, + 0x69410dff, + 0x32022305, + 0xa9824603, + 0x00000929, + 0x41070700, + 0x45004501, + 0x32240525, + 0x90023202, + 0x69201788, + 0x19201788, + 0x7420178c, + 0x56201788, + 0x7720178c, + 0x002b1783, + 0x00200002, + 0x028e0200, + 0x54130090, + 0x232605c7, + 0x33353735, + 0x03822115, + 0x23153339, + 0x21112311, + 0x35211111, + 0x4e4e6e21, + 0x54310153, + 0xfe544848, + 0x823101cf, + 0x37e62303, + 0x00826f04, + 0x1afe3b2d, + 0xcbfe3501, + 0xff697d01, + 0x82fdffff, + 0x03ba229f, + 0x20918263, + 0x2409820a, + 0x003b0707, + 0x24a98484, + 0x0100004e, + 0x20178a0b, + 0x2117853e, + 0x1782f0ff, + 0xd9841820, + 0x41202f85, + 0xd3201786, + 0x35221782, + 0x47884903, + 0x17864320, + 0x1782ec20, + 0x2d031c22, + 0x4f201788, + 0xfe201786, + 0x0a221782, + 0x17881803, + 0x17854520, + 0x824b0021, + 0x03bd2285, + 0x20178835, + 0x20778c4d, + 0x2017884d, + 0x21178557, + 0x2f824000, + 0x6803d322, + 0x51201788, + 0x4d261786, + 0xbb0032ff, + 0x17889002, + 0x17836920, + 0x0001002b, + 0x002cff2b, + 0x009002db, + 0x08135115, + 0x33112323, + 0x0aad4811, + 0x38288b28, + 0x5315192b, + 0x3848221f, + 0x2cd42c06, + 0x163e292b, + 0x70fd9002, + 0x431f3418, + 0x002205a8, + 0x4783ffff, + 0x20061f41, + 0x2181828b, + 0x1f410707, + 0x82f22007, + 0x031622d7, + 0x2077884a, + 0x268f864a, + 0x01f4ff1f, + 0x824603f0, + 0x840b2017, + 0x0141232f, + 0x1142005c, + 0x021e2205, + 0x20a7843f, + 0x2217840c, + 0x4248016c, + 0x178b0829, + 0x17886920, + 0x2f8c5620, + 0x17867720, + 0x77824f20, + 0x6303cc22, + 0x0d205f82, + 0x3e224784, + 0x07828500, + 0x5a000222, + 0x02281783, + 0x000500d6, + 0x3300000a, + 0x212fea82, + 0x33270315, + 0x535a0707, + 0x047e1f01, + 0x820e013b, + 0x47b72ed9, + 0x39d40202, + 0x00ffff9b, + 0x011eff5a, + 0x858d84cc, + 0x016c2245, + 0x08054621, + 0x0425178a, + 0x01fc0082, + 0x202f8413, + 0x202f8c32, + 0x222f8569, + 0x82ffffff, + 0x18032117, + 0x27228d86, + 0x8d844507, + 0x86070721, + 0x2067821f, + 0x20378c56, + 0x23378377, + 0xfaff0100, + 0xd120ad82, + 0x23065f56, + 0x37270735, + 0x373daf82, + 0x21150717, + 0x1e475f15, + 0x1eb05365, + 0xf01f01ce, + 0x01373528, + 0x5fc9fe5c, + 0x47ce6e35, + 0x066b4300, + 0xf9847d20, + 0xf9850e20, + 0x476b0121, + 0x7d2208e9, + 0x83823503, + 0x4d201785, + 0xff231787, + 0x847d0232, + 0x221785e3, + 0x886d0169, + 0x842d202f, + 0x860f2047, + 0x944e2047, + 0x013b2117, + 0x4d20178b, + 0x2f855f82, + 0x178c5720, + 0x17884920, + 0x17874320, + 0x021eff23, + 0x8577842d, + 0x016c222f, + 0x835f8a4b, + 0x201785a7, + 0x202f884d, + 0x202f8c32, + 0x212f8769, + 0x178c56ff, + 0x17867720, + 0xf4ff3424, + 0xbf846502, + 0xbf841020, + 0x4c013b22, + 0x8b08c545, + 0x8c3e2017, + 0x82462017, + 0x202f85a7, + 0x83178c41, + 0x201785bf, + 0x20178c43, + 0x202f882d, + 0x20178c4f, + 0x20178818, + 0x20178c45, + 0x2017886c, + 0x20178c55, + 0x2017884d, + 0x24178857, + 0x02650232, + 0x2017889c, + 0x202f8c69, + 0x20178868, + 0x20178c51, + 0x20178878, + 0x20179690, + 0x20178c92, + 0x202f888a, + 0x20178c94, + 0x201788ab, + 0x82178896, + 0x4103208f, + 0x2722071f, + 0x17834107, + 0x07070022, + 0x4a20978d, + 0x4a203788, + 0x04211f84, + 0x05874100, + 0x0f00c828, + 0x21001d00, + 0x93462500, + 0x0725530c, + 0x200a895b, + 0x06bf4703, + 0x2016915b, + 0x05cc474c, + 0x2117985b, + 0xdd47a202, + 0x03003505, + 0xe2ff3200, + 0xae026b02, + 0x20001700, + 0x00002a00, + 0x26372717, + 0x2306c45e, + 0x07173717, + 0x2908e455, + 0x17161403, + 0x22232601, + 0x805b1306, + 0x27630805, + 0x2e601601, + 0x47221f46, + 0x4868527f, + 0x20452e3e, + 0x537e4822, + 0x11134768, + 0x33200110, + 0xc26a584c, + 0x1130573b, + 0x32e1fe10, + 0x2c5b241e, + 0x97694876, + 0x23513f51, + 0x47752b59, + 0x41549a69, + 0x53301601, + 0x36750120, + 0x4378fe8e, + 0x51305279, + 0x388afe1f, + 0x00020000, + 0x03000034, + 0x0090021e, + 0x00190010, + 0x83222100, + 0x49332087, + 0x25220985, + 0x865c1133, + 0x71012705, + 0x98a9a895, + 0x1f4d9f01, + 0x305d3506, + 0x7b7b7630, + 0xa99c9dae, + 0xee47ce46, + 0x08024447, + 0x8a7d7d84, + 0x37284f83, + 0x6c02f4ff, + 0x1c002503, + 0x9d5fd983, + 0x36172609, + 0x27263435, + 0x86db8437, + 0x0ee65ce1, + 0xe65c4f20, + 0x3b472b05, + 0x41060851, + 0x32390d0a, + 0xef5c3730, + 0x101f2f12, + 0x0c1f0f42, + 0x1729101c, + 0x2b0d3b32, + 0xfc5c5b8a, + 0xffff220d, + 0x2e7f8500, + 0x00260263, + 0x000000b8, + 0x013e0707, + 0x9200004f, + 0x8c3b2017, + 0x88682017, + 0x8c51202f, + 0x88492017, + 0x01432217, + 0x20478647, + 0x88df8332, + 0x01692217, + 0x2e67824b, + 0xff340002, + 0x0265022c, + 0x0021009c, + 0x4e00002f, + 0x265d06f5, + 0x0aba460e, + 0x525d0320, + 0x5901330c, + 0x1f213828, + 0x4742754e, + 0x7e53527f, + 0x385b3648, + 0xdf4a2b37, + 0x5d212006, + 0xd4290850, + 0x3e1d2b2c, + 0x96550517, + 0x052e5d66, + 0x54875f26, + 0x193f1212, + 0x2205e746, + 0x5e431101, + 0xff210901, + 0x218d85ff, + 0xa5826303, + 0x9d82be20, + 0x44070721, + 0x5a260749, + 0x0b020000, + 0x17823503, + 0x17841120, + 0x82014d21, + 0x069945ad, + 0x2f842020, + 0x17841320, + 0x27013e22, + 0x2208f144, + 0x824d0320, + 0x2017852f, + 0x83178c57, + 0x20178547, + 0x2517874d, + 0x20021eff, + 0x2f889002, + 0x36016c22, + 0x8b082347, + 0x8b692017, + 0x18032117, + 0x27222f86, + 0x47834507, + 0x07070022, + 0x56201f89, + 0x77204f8c, + 0x2a243786, + 0xef01f4ff, + 0x1420af84, + 0x1620af86, + 0x17856784, + 0x4f824620, + 0x41211785, + 0x83178b01, + 0x201785c7, + 0x24178857, + 0x02ef011e, + 0x222f889c, + 0x8611016e, + 0x20178d47, + 0x8317886c, + 0x85f78377, + 0x884d2047, + 0x8c322047, + 0x83692047, + 0x01002b2f, + 0xf4ff5b00, + 0x9c027002, + 0x775e2600, + 0x26372911, + 0x06222326, + 0x11231115, + 0x0806315a, + 0x1516164f, + 0x01060614, + 0x1f5c3ab2, + 0x253c1d30, + 0x53213a35, + 0x1089054d, + 0x5a4f3342, + 0x53798754, + 0x688a1b6b, + 0x0c552f5e, + 0x1f36222a, + 0x1f31401d, + 0x360d2936, + 0x60302299, + 0x016efe65, + 0x548675a1, + 0x63159846, + 0x30533447, + 0x1c00ffff, + 0xfc010000, + 0x28ed8303, + 0x00000015, + 0x01570707, + 0x85d5840b, + 0x85bd8317, + 0x874d2017, + 0x1eff2817, + 0x9002fc01, + 0x85002602, + 0x016e2217, + 0x8e2f8506, + 0x886c2017, + 0x8c32202f, + 0x8869202f, + 0x8c562017, + 0x8c772017, + 0x882d2077, + 0x834f205f, + 0x01002117, + 0x2d08a785, + 0x10009002, + 0x11330000, + 0x33373523, + 0x21352335, + 0x33152315, + 0xe2112315, + 0xc623587b, + 0x7bc6e001, + 0x3831017b, + 0x4646de03, + 0xcffe3bde, + 0x1f5fffff, + 0x63032105, + 0x16204b82, + 0x3b22db84, + 0xab844201, + 0xf4ff5724, + 0x178a2e02, + 0x178c3e20, + 0x2f884620, + 0x178c4120, + 0x17884920, + 0x178c4320, + 0x5f85ab83, + 0x178c4f20, + 0x2f881820, + 0x178c4520, + 0x17884a20, + 0x178c4a20, + 0x17887020, + 0x178c5320, + 0x17886c20, + 0x178c5520, + 0x17884d20, + 0x178c5720, + 0x17888b20, + 0x178c8c20, + 0x1788c820, + 0x178c8620, + 0x1788c220, + 0x178c8e20, + 0x88202f89, + 0x32241788, + 0x90022e02, + 0x69202f88, + 0x68202f8c, + 0x51201788, + 0x00341783, + 0xff570001, + 0x03a202f4, + 0x00210039, + 0x14110100, + 0x22230606, + 0x6005fe62, + 0x362309a4, + 0x45343536, + 0x022406e9, + 0x436a3e2e, + 0x2e09ae60, + 0x0f312921, + 0x430c0b41, + 0xa3fe6c02, + 0x60367c69, + 0x052a0eb9, + 0x1b1f2a24, + 0x1729101c, + 0xe741383a, + 0x03a22206, + 0x287f8263, + 0x000000e8, + 0x013e0707, + 0x08e74143, + 0x3b20178b, + 0xaf83178c, + 0x51202f85, + 0x4920178c, + 0x43204788, + 0x32201788, + 0x1788c783, + 0xdf84f784, + 0x2e022c24, + 0xb1439002, + 0x34352506, + 0x022e3736, + 0x20108461, + 0x0aca4507, + 0x284f0128, + 0x3c172138, + 0x9361365e, + 0x575d2307, + 0x9d502822, + 0x3c212609, + 0x783b0515, + 0x0da26162, + 0x15828125, + 0x501c3e08, + 0x5721084b, + 0x847382ff, + 0x86ee20eb, + 0x05d342eb, + 0x00001724, + 0x1784fa02, + 0x17841820, + 0x89013b27, + 0xffff0000, + 0x20178f00, + 0x23178c3e, + 0x00260246, + 0x41202f85, + 0x2d20178c, + 0x4f201788, + 0x1d611785, + 0x205f8405, + 0x205f851a, + 0x207f8200, + 0x230082ff, + 0xdd010000, + 0x3e20178a, + 0x5f83178c, + 0x41202f85, + 0x5f83178c, + 0x4f201785, + 0x3520178c, + 0x17857782, + 0x17874d20, + 0x0132ff25, + 0x889002dd, + 0x00692217, + 0x86d783f0, + 0x8868208f, + 0x8c512017, + 0x88492047, + 0x85432017, + 0x2d002117, + 0xf120a782, + 0x1b20a784, + 0x3e22bf84, + 0x47831801, + 0x4d201786, + 0x17852f82, + 0x178c5720, + 0x17858f83, + 0x17874d20, + 0xf1208f82, + 0x17858f84, + 0x1a016922, + 0xff224785, + 0x178b0156, + 0x17837720, + 0x0002002d, + 0x02000021, + 0x0090024a, + 0x4419000c, + 0x112306b9, + 0x68163233, + 0x15260c25, + 0x70231533, + 0x2b684f4f, + 0x9595270b, + 0x042b4101, + 0x31682001, + 0x2fdc2108, + 0x5a204b82, + 0x15204b82, + 0x0d224b82, + 0x4b831600, + 0x56153321, + 0x2323061d, + 0x68351523, + 0x533b0872, + 0x3d6c4976, + 0x6c766c86, + 0x55545356, + 0x6e90026c, + 0x68485425, + 0x41da9663, + 0x82364746, + 0xff3a2843, + 0x025e02f4, + 0x6018009c, + 0x37220ae9, + 0x80622621, + 0x0514620b, + 0x21373f08, + 0x48011616, + 0x01407955, + 0x04d00101, + 0x52315e65, + 0x6923291d, + 0x45938043, + 0x6853567c, + 0x0585fe08, + 0x97530c64, + 0x070d0567, + 0x1d248079, + 0xae2b2239, + 0x50996da4, + 0x6d707545, + 0x01000078, + 0x67825a00, + 0x67824720, + 0xcd462220, + 0x3536210b, + 0x2805ea62, + 0x23110706, + 0x36153311, + 0x08c08636, + 0x96010639, + 0x140e2d13, + 0x1b10170b, + 0x48291b2d, + 0x383c1a31, + 0x23515314, + 0x67413462, + 0x0c4f2c3b, + 0x054b0708, + 0x68752f06, + 0x19307163, + 0x0ffe1d2c, + 0x28519002, + 0x7b924035, + 0x8245987e, + 0xff5a28d1, + 0x02b4015b, + 0x53030090, + 0x33210543, + 0x0a5f5d11, + 0x1133113e, + 0x535a0614, + 0x0d251681, + 0x0d170a10, + 0x3e531825, + 0x70fd9002, + 0x420408a5, + 0x2c340603, + 0x6d360b82, + 0xffff584a, + 0xf4ff3400, + 0x0d03b101, + 0x1c002602, + 0x07000000, + 0x8d463a07, + 0x20178f06, + 0x21178b3d, + 0x2f88e402, + 0x178a4020, + 0xd102b822, + 0x42201788, + 0xaf202f8c, + 0x4e201788, + 0x9220178c, + 0x44201788, + 0xda20178c, + 0x48201788, + 0xef20178c, + 0x52201788, + 0xea20178c, + 0x56201788, + 0x32241788, + 0xf201b101, + 0x69241788, + 0x0000f900, + 0x0221ef87, + 0x201788f8, + 0x242f8850, + 0x03f601f4, + 0x20178811, + 0x2417868f, + 0x01f4ff14, + 0x20178ab1, + 0x222f8a91, + 0x881703dc, + 0x4193202f, + 0x23200c37, + 0x95201788, + 0x8f821788, + 0x22083741, + 0x83400727, + 0x07002217, + 0x21978c07, + 0x37884003, + 0x4f8c9720, + 0x99201789, + 0x5020178c, + 0x9b202f88, + 0x2220178c, + 0x9d201788, + 0x57417f8c, + 0x07272207, + 0x2d7f8b48, + 0x34000200, + 0xc60132ff, + 0x2c00f201, + 0x994b3600, + 0x23272308, + 0x4f600606, + 0x0fa86505, + 0x2506d945, + 0x06173736, + 0xaf650306, + 0x78012a08, + 0x1c343526, + 0x51220307, + 0x0fb9652e, + 0x1c2d2a2a, + 0x09140c12, + 0xb12d0e15, + 0x2805be65, + 0x292a2bce, + 0x1c361341, + 0x10c6652a, + 0x1d3c102b, + 0x06071717, + 0x01100b29, + 0x08ce6504, + 0xb120a186, + 0x3022a182, + 0xeb523a00, + 0x22062108, + 0x23209f95, + 0x7f46ba83, + 0x28a58e07, + 0x213526f8, + 0x03070414, + 0x115c663f, + 0x132a1328, + 0x121d2019, + 0xa882130b, + 0x88312c21, + 0x392223a8, + 0xa6900113, + 0x1e0e3a26, + 0x1c3d100e, + 0xff25aa90, + 0xff3400ff, + 0x05534332, + 0x53430120, + 0x013d2c05, + 0x0000000b, + 0xff3a0003, + 0x82eb02f4, + 0x002b24c1, + 0x673f0038, + 0x17271503, + 0x32333636, + 0x65141516, + 0xe1820a7b, + 0x27062728, + 0x26373632, + 0x17672726, + 0x373e0805, + 0x23263433, + 0x3dc90622, + 0x10978f52, + 0x4828282b, + 0x6022211d, + 0x0f463636, + 0x5931521d, + 0xc5fe0360, + 0x233e5603, + 0x1f1e1b38, + 0x523d324d, + 0x2249661c, + 0x0a082150, + 0x31627301, + 0x383bf6f1, + 0x39674a32, + 0x3821080d, + 0x7d382f2f, + 0x4c121c68, + 0x3911175c, + 0x24371e14, + 0x2427425b, + 0x191c3513, + 0x292f3c0f, + 0x504be025, + 0x84d18254, + 0x0d0325b9, + 0x1e012602, + 0x0726c982, + 0x9d013d07, + 0x17870000, + 0x88920221, + 0x83442017, + 0x02002317, + 0x7b670800, + 0x001b2c06, + 0x05000027, + 0x23272622, + 0x55112307, + 0x332205d5, + 0x83672315, + 0x0b826712, + 0x524a4a24, + 0x8667b6b6, + 0x463c210c, + 0x37068567, + 0x5d053630, + 0x57523b5d, + 0x667d271d, + 0x453a6e4c, + 0x5a454f5f, + 0x171cd743, + 0xef678b83, + 0x26022306, + 0xa3841d00, + 0x46014c22, + 0x5226a384, + 0xfb0156ff, + 0x1788c802, + 0x28017722, + 0x2e261784, + 0xaf011eff, + 0x1782f201, + 0x6d22d385, + 0x17860a01, + 0xaf01f422, + 0x0020eb83, + 0x3d221785, + 0x17891201, + 0x88e40221, + 0x8c40202f, + 0x88ea2017, + 0x8c562017, + 0x88b62017, + 0x834c2017, + 0x03002f17, + 0xf4ff2f00, + 0xf8024902, + 0x20001300, + 0x05422500, + 0x67362007, + 0x012419d7, + 0x07073327, + 0x2519dc67, + 0x3b044801, + 0xe2670e01, + 0xeb012118, + 0x68050955, + 0x8d82064b, + 0x1d411f20, + 0xe8002105, + 0x2f26d584, + 0xd90132ff, + 0x1788c802, + 0x15016922, + 0x56201786, + 0x7720178c, + 0x00211783, + 0x26bd8402, + 0x00c80221, + 0x8e28001b, + 0x352328bb, + 0x15333533, + 0x68071533, + 0xa12a1c9b, + 0x484853a1, + 0x1c030646, + 0x7c641a4a, + 0x0c280808, + 0x6a486f7c, + 0x541a1f3a, + 0x5d5d3055, + 0xc5fd052b, + 0x45271c37, + 0x171cd743, + 0x4c304b2b, + 0xffff005b, + 0xf4ff2e00, + 0x0d03ca01, + 0x2020a582, + 0x3a22bd84, + 0x93410801, + 0x20178b08, + 0x21178b3d, + 0x2f88e402, + 0x178c4020, + 0x1788ea20, + 0x178c5620, + 0x1788af20, + 0x178c4e20, + 0x17889220, + 0x178c4420, + 0x1788da20, + 0x178c4820, + 0x1788b620, + 0x17884c20, + 0xca013224, + 0x1788f201, + 0x2f8c6920, + 0x1788f820, + 0x178c5020, + 0x1788d120, + 0x178a4220, + 0x1103f322, + 0x8f201788, + 0x11241786, + 0xca01f4ff, + 0x9120178a, + 0xd9222f8a, + 0x2f881703, + 0x37419320, + 0x8823200c, + 0x88952017, + 0x41a78217, + 0x27220837, + 0x17834007, + 0x07070022, + 0x0024af84, + 0xff2e0002, + 0x0021c784, + 0x069b5a2b, + 0x36343524, + 0xdd4c0637, + 0x44342005, + 0x366a06b9, + 0x6815200b, + 0x406a082b, + 0x26662807, + 0x0d132934, + 0x6a410c18, + 0x412a1147, + 0x0c131c2e, + 0x0e150913, + 0x4f6afb2d, + 0x2bce2705, + 0x113d262a, + 0x566a0304, + 0x412e220f, + 0x07754520, + 0x4d4ae824, + 0x9796004f, + 0x6a085752, + 0x15460dca, + 0x06d76a0d, + 0x35251027, + 0x5a381c22, + 0x0fdb6a34, + 0x1d321b2d, + 0x121c2c2e, + 0x1609130b, + 0x88a52c0f, + 0x3b202696, + 0x6b410814, + 0x0cec6a48, + 0x05161125, + 0x8b213909, + 0xffff2198, + 0x2d052f41, + 0x26020d03, + 0x00003f01, + 0x3d070700, + 0x07820801, + 0xcf420420, + 0x004b2606, + 0x001f0018, + 0x06234523, + 0xb7672620, + 0x41ae8d06, + 0x27210638, + 0x05155d35, + 0x261d816b, + 0xa70a0103, + 0x6b268720, + 0xf7261788, + 0x27683939, + 0x97823163, + 0x00001e2a, + 0x65033f01, + 0x21002602, + 0x07268f82, + 0xda004d07, + 0x17823000, + 0x20ff2d24, + 0xaf83ec01, + 0x84220021, + 0x013d2417, + 0x87000002, + 0xe4022117, + 0x17852f82, + 0x178c4020, + 0x1788da20, + 0x178c4820, + 0x1788b620, + 0x17834c20, + 0x6b040021, + 0x022205c5, + 0xc56b00e8, + 0x475b2005, + 0xc76b0803, + 0x26132d46, + 0x36343526, + 0x06061737, + 0x17161415, + 0x2936d56b, + 0x56344169, + 0x2e3f084f, + 0xdf6b2225, + 0xe6022e3e, + 0x2c222308, + 0x0429042c, + 0x14131517, + 0x09474103, + 0x1741ea20, + 0x41562008, + 0x92200c2f, + 0x44201788, + 0xd120178c, + 0x42201788, + 0x52261786, + 0xd7010000, + 0x17827603, + 0x00002334, + 0x41070700, + 0x30002701, + 0x5200ffff, + 0xd70132ff, + 0x1788c802, + 0xcd626920, + 0xff522206, + 0x20178c56, + 0x20178877, + 0x20178c19, + 0x23178374, + 0x08000100, + 0x02235f83, + 0x4d1c00c8, + 0x352206b9, + 0xb7471533, + 0x0a9f6c0a, + 0x524a4a24, + 0xa36cb6b6, + 0x06a2470c, + 0x30216432, + 0xf3fe5d61, + 0x3d440201, + 0xc7fe2525, + 0xedffffff, + 0xb422a982, + 0xa76c0d03, + 0x7c3a2208, + 0x20b18200, + 0x20698244, + 0x20158a0b, + 0x2115833d, + 0x1582e1ff, + 0xe4021722, + 0x40202b88, + 0xcf201584, + 0x29221582, + 0x1588d102, + 0x15844220, + 0x1582ea20, + 0xaf020e22, + 0x4e201588, + 0xf7201584, + 0x01221582, + 0x15889202, + 0x578a4420, + 0x1588ea20, + 0x83845620, + 0x99823820, + 0xf802cc22, + 0x50201588, + 0x44221584, + 0x576d32ff, + 0x24002105, + 0x06281f82, + 0x007b6907, + 0x26000200, + 0xcf261582, + 0x1600b402, + 0x715d2200, + 0x37362513, + 0x03060617, + 0x08052058, + 0x15163229, + 0x26810614, + 0x14152b35, + 0x1c231e52, + 0x0a130b13, + 0x192d0e15, + 0x18212118, + 0xce212117, + 0x3b292a2b, + 0xfee60115, + 0x4a36161a, + 0x032b07f0, + 0x18171e18, + 0x17181d1d, + 0x83ffff1e, + 0x0b012769, + 0x26020d03, + 0x7f846502, + 0x20051941, + 0x22d782e0, + 0x88da0218, + 0x7c4821ab, + 0x00211082, + 0x23218252, + 0x00e601a4, + 0x21067176, + 0x57835252, + 0xffffff29, + 0x0127ffd8, + 0x82e40218, + 0x84d6202d, + 0x7d402143, + 0x28052949, + 0x02e6011e, + 0x002602c8, + 0x25158226, + 0x016c0707, + 0x17850013, + 0x178c3220, + 0x17886920, + 0x178c5620, + 0x17837720, + 0x6e010021, + 0x7582054d, + 0x28104d6e, + 0x5bce0352, + 0x8e5ab7a1, + 0x2786825a, + 0xc30201fe, + 0x6ae7ddfe, + 0x472a7984, + 0x0401f4ff, + 0x26029303, + 0x8f842700, + 0x307d3e26, + 0x52000200, + 0x14241582, + 0x0f00f802, + 0x27105b6b, + 0x13060617, + 0x07073327, + 0x240b6a6e, + 0x013b0423, + 0x0d6f6e0e, + 0xd4300224, + 0xc1859b39, + 0x6b01f425, + 0x8500c802, + 0x04072e5f, + 0x01b30082, + 0x00ffff13, + 0x001eff32, + 0x83f184df, + 0x21f18277, + 0xf1879100, + 0x8ad80021, + 0x85692017, + 0xf7ff2717, + 0x030132ff, + 0xa7864803, + 0x45072622, + 0x0721a782, + 0x271d8607, + 0x56ff0c00, + 0xc8021601, + 0x07221d86, + 0x35837707, + 0x82010021, + 0x01f42235, + 0x207d8218, + 0x05194217, + 0xf05d3520, + 0x096b6c08, + 0x292eb529, + 0x52671e49, + 0x6f681d4b, + 0xeb2c0a39, + 0x013f352f, + 0x2ff3fe36, + 0xe5fe3e35, + 0x2907426f, + 0x5200ffff, + 0xf1020000, + 0x67820d03, + 0x00002828, + 0x3d070700, + 0xb585a901, + 0x02211783, + 0x201788b6, + 0x2517874c, + 0xf10232ff, + 0x1788f201, + 0xa5016922, + 0x01212f87, + 0x204784d7, + 0x58478629, + 0x454405b7, + 0x855f8305, + 0x013a2117, + 0x0221178a, + 0x854782ea, + 0x8c562017, + 0x88d12017, + 0x87422017, + 0x1eff2317, + 0x7784d701, + 0x6c202f85, + 0x8406434a, + 0x85a7845f, + 0x884c2017, + 0x8c32202f, + 0x07734a2f, + 0x56ff5222, + 0x7720178c, + 0x3f204786, + 0xb526ef82, + 0x2600bb02, + 0xbf838e04, + 0x00290023, + 0x08fd49de, + 0xd784f020, + 0xd7842a20, + 0xf1693a20, + 0xff2e2306, + 0x178b01f4, + 0x178b3d20, + 0x82e40221, + 0x202f85bf, + 0x83178c40, + 0x201785d7, + 0x20178c42, + 0x202f88af, + 0x20178c4e, + 0x20178892, + 0x20178c44, + 0x201788f9, + 0x20178c54, + 0x201788ea, + 0x24178856, + 0x01f00132, + 0x201788f2, + 0x202f8c69, + 0x201788f8, + 0x22178a50, + 0x881103fa, + 0x868f2017, + 0x84182017, + 0x201789ef, + 0x0c074191, + 0x2f881720, + 0x178c9320, + 0x17882320, + 0x17889520, + 0x1f418f82, + 0x07272208, + 0x0ea96b40, + 0x67832e20, + 0x88da0221, + 0x84482037, + 0x05cd481f, + 0x4b03f02a, + 0x1b000f00, + 0x23001f00, + 0x7114215e, + 0x1f5e0847, + 0x134f7108, + 0xc0484720, + 0x05127506, + 0x210e5671, + 0xbf482102, + 0x03003b05, + 0xe9ff2e00, + 0xfd01f001, + 0x20000800, + 0x00002800, + 0x13171437, + 0x06222326, + 0x245e0306, + 0x32373b16, + 0x27343536, + 0x177f1603, + 0x293825d6, + 0x252c2542, + 0x3f1d1936, + 0x3b503b67, + 0x09832432, + 0x4f3c663d, + 0x513f8b3c, + 0xf627d518, + 0x03012e43, + 0xfe542f28, + 0x20411dbc, + 0x72523556, + 0x823d323c, + 0x36572d09, + 0x313c7250, + 0x44526711, + 0x27fcfe2e, + 0xf4248184, + 0xf2012103, + 0x2f20ed82, + 0x7d063151, + 0xc24f0861, + 0x021e2808, + 0x37363233, + 0x4f060617, + 0x044107c2, + 0x4f252008, + 0x260805c1, + 0x643a0801, + 0x3b643d3c, + 0x1c1a5e38, + 0x625a355a, + 0x02c1fe03, + 0x2329442a, + 0x1f1e1b3a, + 0x5e39324f, + 0x3c78391c, + 0x823c4c4c, + 0x11012603, + 0x32383efa, + 0x066f724b, + 0x393b3f32, + 0x1c687d41, + 0x2a4c3212, + 0x14391117, + 0x7938411e, + 0x31087c72, + 0x54504bde, + 0x2e000200, + 0x0c02f4ff, + 0x1d009102, + 0x8f412900, + 0x5817200b, + 0x06200a77, + 0x8809625e, + 0x07e57298, + 0x292d322c, + 0x0a400f2d, + 0x1c32200d, + 0xef722c26, + 0x08153010, + 0x1b1c292e, + 0x1629101e, + 0x08213627, + 0x72446620, + 0xff210cfd, + 0x2d7d85ff, + 0x26020d03, + 0x00008901, + 0x3d070700, + 0xb1431101, + 0x0c022107, + 0x3a20178a, + 0x0221178b, + 0x202f88f8, + 0x20178c50, + 0x211788d1, + 0x4e820142, + 0x32205f84, + 0x1788dd83, + 0x2f836920, + 0x3228f584, + 0xf201f001, + 0x2e002200, + 0x5e08c552, + 0x3621155f, + 0x05ba5237, + 0x1a27f989, + 0x1c1f3526, + 0x73385d37, + 0x2b2d05e3, + 0x27312a47, + 0x120c111d, + 0x2c0e1609, + 0x06ee731e, + 0x2a2bce35, + 0x05163c1c, + 0x524b6e3f, + 0x723c3c72, + 0x40624252, + 0x52371310, + 0x062008ae, + 0x85070074, + 0x058344a1, + 0x828f0121, + 0x070721b2, + 0x2a078344, + 0x0133ff52, + 0x02b602fb, + 0x842b0026, + 0x08134517, + 0x01000025, + 0x820d036d, + 0x842d2017, + 0x443d2017, + 0x1a2606e3, + 0x5e011eff, + 0x1786f201, + 0x6c070624, + 0x5d820079, + 0x2d824320, + 0xea027922, + 0x56202d88, + 0x52202d86, + 0x5e201782, + 0x45855d84, + 0x17864c20, + 0x32ff4222, + 0x6920458c, + 0x15834584, + 0x92026322, + 0x27224586, + 0x2d834407, + 0x07060022, + 0xff231d84, + 0x8c56fff4, + 0x84772033, + 0xff1c2433, + 0x848301f4, + 0x862e20a7, + 0x00d721a7, + 0x17849183, + 0x82e40221, + 0x2117854b, + 0x178b0040, + 0x1785a983, + 0x17885620, + 0x83011e22, + 0x1785d784, + 0xd6006d22, + 0x8b084d5d, + 0x886c2017, + 0x84778217, + 0x202f85d9, + 0x2047884c, + 0x20478c32, + 0x2d2f8369, + 0x52000100, + 0x2302f4ff, + 0x3100d202, + 0xcb7c0000, + 0x32332a05, + 0x2e343536, + 0x3e343503, + 0x06f34102, + 0x545e1120, + 0x16690806, + 0x020e1415, + 0x031e1415, + 0x01061415, + 0x1f452983, + 0x29363421, + 0x3b3a282b, + 0x1b221b28, + 0x3c35292a, + 0x355e6652, + 0x251b2648, + 0x3a3b281b, + 0x1b0c5628, + 0x312b3a16, + 0x1e2a231f, + 0x222a3221, + 0x1f2f2b31, + 0x4d4e3126, + 0x03020cfe, + 0x4228715e, + 0x2b362528, + 0x231d1a2a, + 0x313a251d, + 0x0000563f, + 0xff180002, + 0x024501f4, + 0x001700f8, + 0x1983741c, + 0x33270324, + 0x88740707, + 0x04022410, + 0x740e013b, + 0xef48128d, + 0x315b8408, + 0x26023b03, + 0x00002f00, + 0x4c070700, + 0x85009400, + 0x7382ffff, + 0x73821e20, + 0x17886e20, + 0x2d416d20, + 0xff182106, + 0x6c20178d, + 0x32201788, + 0x69202f8c, + 0x56231788, + 0x89025c01, + 0x86772047, + 0x83022017, + 0x340321d3, + 0x4e205f88, + 0x6d757783, + 0x851f200a, + 0x233523e9, + 0x03833735, + 0x23057175, + 0x23153315, + 0x83091150, + 0x754820ec, + 0x79750577, + 0x36472b0c, + 0x053e8b05, + 0x8b438888, + 0x7c75483b, + 0x20d18207, + 0x2271824b, + 0x820d03ce, + 0x47302071, + 0x178f0ceb, + 0x84076743, + 0xe4022117, + 0x40202f88, + 0x8506e346, + 0x88d12017, + 0x8c422017, + 0x88af2017, + 0x07eb4717, + 0x92202f85, + 0xeb471788, + 0x20178507, + 0x201788da, + 0x20478c48, + 0x201788ef, + 0x22178a52, + 0x88f902d6, + 0x071b4817, + 0xea204785, + 0x56201788, + 0xce222f8a, + 0x17881d03, + 0x178c8b20, + 0x17884c20, + 0x178c8520, + 0x17884820, + 0x178c8d20, + 0x87202f89, + 0x32241788, + 0xe601ce01, + 0x69202f88, + 0x8506b554, + 0x88f8208f, + 0x83502017, + 0x05fd762f, + 0x022e0223, + 0x07f54c9b, + 0x2208077a, + 0x64363311, + 0x06200ab4, + 0x7706fc53, + 0x152a080b, + 0x06083123, + 0x1d0d0a40, + 0x1577172c, + 0x2a053211, + 0x0c1d0e31, + 0x1629101e, + 0x081f3628, + 0x284c39fe, + 0x05e94130, + 0x032e0231, + 0x0126020d, + 0x000000b9, + 0x013d0707, + 0x9200000e, + 0x8b3a2017, + 0x82022017, + 0x202f86b1, + 0x20178c50, + 0x224788d1, + 0x860a0142, + 0x83322047, + 0x221788c9, + 0x821b0169, + 0x00012867, + 0x0132ff4b, + 0x5ee601e3, + 0xff580ad3, + 0x6bec8a07, + 0x363c0759, + 0x06061737, + 0x35269501, + 0x03082031, + 0x4d324c22, + 0x312a5348, + 0x52223b26, + 0x111d2b2c, + 0x2805e858, + 0x292a2bce, + 0x2848173d, + 0x0d087830, + 0x2009ed4d, + 0x20738500, + 0x207382ce, + 0x08ad462a, + 0x23222224, + 0x4a5f2622, + 0x32332305, + 0x7a823736, + 0x2811cb58, + 0x34261301, + 0x0604141f, + 0x0b717802, + 0x102c1724, + 0xbb581d1b, + 0x227b8207, + 0x8d133921, + 0x184b2678, + 0x37150e27, + 0x06a1521b, + 0x28055141, + 0x03ce0132, + 0x0126020d, + 0x0ca346c0, + 0x00001824, + 0x1783b602, + 0x84320021, + 0x013a2317, + 0x2f830068, + 0x3d20178f, + 0x0223178b, + 0x862602e4, + 0x8c40202f, + 0x88af2017, + 0x864e2017, + 0xff0c2417, + 0x84c7012f, + 0x8534205f, + 0xf300215f, + 0x178f5f84, + 0x178b3d20, + 0x2f855f84, + 0x178c4020, + 0x17855f83, + 0x178c4e20, + 0x7782b620, + 0x4c201785, + 0x0121178b, + 0x271788e6, + 0x00880169, + 0x00ffff04, + 0x02217784, + 0x201788f8, + 0x20478c50, + 0x201788d1, + 0x24178642, + 0x0100001f, + 0x20bf848f, + 0x22bf8435, + 0x84e7003d, + 0x211784bf, + 0x2f82ea02, + 0x56201785, + 0x8f83178c, + 0x4c201785, + 0xff231787, + 0x848f0132, + 0x2217858f, + 0x85e10069, + 0x56ff2147, + 0x7720178c, + 0x00301783, + 0xff350002, + 0x02e501f4, + 0x000f00da, + 0x37000030, + 0x2b054b62, + 0x27263435, + 0x22232626, + 0x26221306, + 0x2b08814a, + 0x07272626, + 0x27263727, + 0x17161637, + 0x08082b69, + 0x40268354, + 0x01434426, + 0x22422101, + 0x388a4943, + 0x5d373d63, + 0x1947263a, + 0x8d26380d, + 0x3c347f18, + 0x20462426, + 0x3c81188e, + 0xde61364c, + 0x6e294b32, + 0x0d1c0e58, + 0xfe5c1e2c, + 0x486939d1, + 0x20386544, + 0x255d3e22, + 0x28412949, + 0x2d133420, + 0x4229491b, + 0x5077a83d, + 0x95824479, + 0x2205d148, + 0x7c1300c8, + 0xdd5906e9, + 0x13e97c0a, + 0x2001522e, + 0x6460284c, + 0x23385f3b, + 0x77012142, + 0x2d09e87c, + 0x54c19503, + 0x7187251a, + 0x1d3e7652, + 0xe97c5319, + 0x0001280d, + 0x0127ff52, + 0x18f201d7, + 0x8207cb41, + 0x323323d9, + 0x277f3536, + 0x7d232007, + 0x11320960, + 0x52010614, + 0x100c2516, + 0x240d1809, + 0x25302c18, + 0x077e253b, + 0xd93c2a08, + 0x033e0508, + 0x012c3305, + 0x053f7f60, + 0x2e07127e, + 0x00584a95, + 0xffd8ff01, + 0x01a50027, + 0x7c0f00e6, + 0x11210ca9, + 0x24528233, + 0x0d251620, + 0x20518411, + 0x29448852, + 0xe3fd1d02, + 0xffff584a, + 0x9b824500, + 0xb602a82e, + 0x24002600, + 0x07000000, + 0xf6002500, + 0x02260782, + 0xf4ff4b00, + 0xb382c801, + 0x17831a20, + 0x26220523, + 0x22a58935, + 0x4c070614, + 0x2722081d, + 0x91483636, + 0x07460805, + 0x5c670e01, + 0x23020744, + 0x4a393159, + 0x15019b90, + 0x45293036, + 0x5e20201c, + 0x2d607aa8, + 0x26452220, + 0x015e720c, + 0x2c244422, + 0x5e523e41, + 0x24391d11, + 0x16391321, + 0x3f10f429, + 0x24222631, + 0x02000028, + 0xf4ff2700, + 0x71820002, + 0x576a1d20, + 0x23272a05, + 0x34112307, + 0x22222326, + 0x22648207, + 0x7f163233, + 0x42180723, + 0x2e3710fd, + 0x06034744, + 0x03090c43, + 0x080b0607, + 0x27210e15, + 0x52210206, + 0x18625e2b, + 0x36070743, + 0x3e21243f, + 0x012f3b0c, + 0x0210148a, + 0x2005033e, + 0x872a1d27, + 0x18765271, + 0x510b0c43, + 0xfb2205c7, + 0x734cd402, + 0x207e8508, + 0x20778336, + 0x21848207, + 0x43180706, + 0xf75b117b, + 0x55542a0b, + 0x13102c16, + 0x2d301c1b, + 0x11fd5b02, + 0x301c203d, + 0x68531902, + 0x0c3f0709, + 0x1d713940, + 0x526f8527, + 0x65453d74, + 0x43614f58, + 0x83171cf7, + 0xff5224fb, + 0x820c0233, + 0x0019257d, + 0x1700002f, + 0x27052f68, + 0x06141516, + 0x021e1507, + 0x06200682, + 0x200c8c42, + 0x07366223, + 0x06226d08, + 0x16161115, + 0x31636652, + 0x32383655, + 0x322d4929, + 0x5b2d3756, + 0x37960324, + 0x16525949, + 0x3b424307, + 0x22413a2b, + 0xb802cd4f, + 0x4c268168, + 0x14593a3a, + 0x4f2b0604, + 0x335c3e3c, + 0xa4622520, + 0x414c0601, + 0x4d3a4e46, + 0x5839393e, + 0x2ba1fe59, + 0x0002001d, + 0x01bbff2e, + 0x00f201bc, + 0x00310009, + 0x07222500, + 0x36323316, + 0x07263435, + 0x37363627, + 0x13864b18, + 0x2f4e1720, + 0x82062006, + 0x276308a1, + 0x4e010606, + 0x32264043, + 0xed173820, + 0x0d190b33, + 0x6b412621, + 0x1945303e, + 0x1d311528, + 0x1428472d, + 0x2e5b2811, + 0x47293532, + 0x0c38482d, + 0x1a489814, + 0x15111b21, + 0x331d14dd, + 0x3d5f2116, + 0x223c7252, + 0x18133317, + 0x25395630, + 0x302d1740, + 0x3a252936, + 0x2d142121, + 0x09000100, + 0xc90133ff, + 0x1900e601, + 0x18170000, + 0x08183b46, + 0xa3af0933, + 0x1e094959, + 0x1c0a0409, + 0xa2564909, + 0x095759b2, + 0x09040a1e, + 0xcd570a1b, + 0x3d017601, + 0x163d159a, + 0x9a173b16, + 0x8cfec1fe, + 0x194417c6, + 0xc6184319, + 0x2aef8200, + 0x0227ff2f, + 0x00d4023f, + 0x462b001e, + 0x401805c5, + 0x27210d85, + 0x32421835, + 0x1801200a, + 0x280b8e40, + 0x3b3e0202, + 0x2b491e01, + 0xb744185b, + 0x1c162908, + 0x1007130a, + 0xf5fe200a, + 0x39081b5c, + 0x884049d9, + 0x7985281c, + 0x1e3e734f, + 0xfcc7531a, + 0x052f29ee, + 0x08053e03, + 0x40181201, + 0x022809a1, + 0xf4ff2f00, + 0xd6024302, + 0x45188385, + 0x26200b29, + 0x6a067d42, + 0x27240645, + 0x27060623, + 0x575d838b, + 0x01012d08, + 0x1c114340, + 0x0f07100b, + 0x441a2109, + 0x153f4518, + 0x5146852b, + 0x023f0505, + 0xfd2a3204, + 0x474518c9, + 0xff25290f, + 0x01c201f4, + 0x001800f2, + 0x2005fb4a, + 0x05a14427, + 0x26213725, + 0x83343526, + 0x15162584, + 0x03060614, + 0x39080e82, + 0xdd062223, + 0x1d205331, + 0x47233f1b, + 0xb9fe0452, + 0x5d6f0301, + 0x3b385e3b, + 0x0301b168, + 0x39374407, + 0x141e0c48, + 0x5c151136, + 0x0d19094d, + 0x723e7c68, + 0x3d724f50, + 0x4f482601, + 0xe785004d, + 0xdf430920, + 0x24e78a07, + 0x11333733, + 0x0a6c5014, + 0x3835e694, + 0x02214029, + 0x03154307, + 0x090b0706, + 0x27200f14, + 0x4c1c0306, + 0x0869411b, + 0x2d06425e, + 0x76fe2f1d, + 0x3e010124, + 0x28200503, + 0x46182c1c, + 0x8f54092b, + 0xd5012805, + 0x0602e601, + 0x4100ff03, + 0x032706f9, + 0x00c8023b, + 0x5e400032, + 0x33250e0b, + 0x07152115, + 0x05ab6b36, + 0x41182320, + 0xfc820bf4, + 0x13270723, + 0x07225e23, + 0x42183620, + 0x34080a9d, + 0x386857ee, + 0x3827355c, + 0x0153041f, + 0x5241a561, + 0x335a3827, + 0x291c5440, + 0x322d3d16, + 0x16373a46, + 0xab201119, + 0x030744fc, + 0x1f17441c, + 0x331d1d36, + 0x233b241c, + 0x08b48541, + 0x53191f26, + 0xf72ce2bb, + 0x36583401, + 0x32336246, + 0x2816341c, + 0x463e4352, + 0x012d0808, + 0x395dfe02, + 0x23452a1b, + 0x181bfe20, + 0x07f34618, + 0x220fab41, + 0x66363435, + 0x16210d08, + 0x05204515, + 0x21373c08, + 0x5cee1614, + 0x0101036d, + 0x424b0447, + 0x1d1c3d25, + 0x3d335322, + 0x60393861, + 0x0746383d, + 0x0c44fdfe, + 0x190e6d7d, + 0x175a4909, + 0x1b173913, + 0x4f50723c, + 0x52423e73, + 0x004e4f4b, + 0x82000200, + 0xac023065, + 0x2b00f201, + 0x00003600, + 0x26262217, + 0x66262527, + 0x17230a6c, + 0x4d060637, + 0x2324090d, + 0x35352622, + 0x33078f51, + 0x32331616, + 0x34353636, + 0x42f22734, + 0x01052f57, + 0x31481043, + 0x25087c85, + 0x1869492f, + 0x1b01018b, + 0x07130d19, + 0x19210d16, + 0x024c3625, + 0xc15d3302, + 0x2836410a, + 0x0c011f3a, + 0x7e395f39, + 0x8d843539, + 0x474b2708, + 0x0e1c1436, + 0x05092938, + 0x330f082c, + 0x0d1e123f, + 0x73450f1c, + 0x3c35b244, + 0x09315230, + 0x01000712, + 0xf4ff3200, + 0xa184a301, + 0x35229f84, + 0x47183634, + 0x07200b49, + 0xa283ad84, + 0x23153323, + 0x08ab8a22, + 0x5a37f943, + 0x282a4236, + 0x2f51312a, + 0x211f482c, + 0x2820351b, + 0x373a3739, + 0x47413b46, + 0x203d2137, + 0x0c4e2a23, + 0x352d4124, + 0x0e040b3a, + 0x3a2d223b, + 0x3717191c, + 0x26261511, + 0x2a3b2a21, + 0x152f2828, + 0x191e3717, + 0x207d8200, + 0x207d8225, + 0x437d8896, + 0x3523062f, + 0x45232634, + 0xb6460a9b, + 0x20511806, + 0x31d23b0b, + 0x21232b51, + 0x4638213c, + 0x36453c40, + 0x2934363b, + 0x211b3920, + 0x2e2d4d21, + 0x94822e4d, + 0x5835422b, + 0x371e190c, + 0x282f1517, + 0x39708228, + 0x15262621, + 0x19173711, + 0x222d3a1c, + 0x0b040e3b, + 0x412d353a, + 0x02000024, + 0x7d822e00, + 0x7d82f120, + 0xb5441620, + 0x073b4906, + 0x27226a8b, + 0x8f8e3632, + 0x1614152d, + 0x73462a01, + 0x44724343, + 0x84304f31, + 0x395a356e, + 0x393f4135, + 0x35381b2a, + 0x59492937, + 0x6f380c5a, + 0x3b755651, + 0x42206f8c, + 0x68238b88, + 0x825f575d, + 0xebff29fb, + 0x100127ff, + 0x1800e601, + 0x230d6948, + 0x33373523, + 0x23056a5b, + 0x33061411, + 0x25087248, + 0x52015c5d, + 0x77485858, + 0x16012a08, + 0xcccc0536, + 0x4aeafe3b, + 0x05854358, + 0x43022426, + 0x28009c02, + 0x41058754, + 0x37200648, + 0x200e8545, + 0x0c084534, + 0xb5651420, + 0x26262505, + 0x06062223, + 0x5808d483, + 0x1f515e01, + 0x43234a23, + 0x1c020141, + 0x6e5b2b49, + 0x2937613c, + 0x40011f3e, + 0x0b1d1043, + 0x0c120710, + 0x5e71171e, + 0x1f1f3b22, + 0x40271e39, + 0x35dc4625, + 0x4816173a, + 0x261b5c3c, + 0x6f4c7382, + 0x501a1e3d, + 0x05065141, + 0x3204033f, + 0x5dedfd29, + 0x2125016a, + 0x171cee22, + 0x5234502e, + 0x25a18660, + 0xf201d901, + 0x6b411d00, + 0x22a19505, + 0x82333733, + 0x320321f4, + 0x200b1244, + 0x24969301, + 0x07021f40, + 0x248d9a45, + 0xfe2d1c1d, + 0x26848e05, + 0xff2e0001, + 0x4ac001f4, + 0x5318083f, + 0x5218120d, + 0x44080725, + 0x01060615, + 0x3e6b4118, + 0x38426d40, + 0x1528194a, + 0x482d2733, + 0x1b47572b, + 0xb56c0f2e, + 0x3b0c571b, + 0x724f5372, + 0x3317253d, + 0x552c1c12, + 0x1165593c, + 0xd53b770d, + 0x02002419, + 0x20ff0c00, + 0xe601c701, + 0x23001800, + 0xdf4c1800, + 0xd6441807, + 0x1616350c, + 0x27061415, + 0x34353632, + 0x15062327, + 0x37ec1614, + 0xaa1d203c, + 0x0af74518, + 0x201da637, + 0x1516363c, + 0x1629042a, + 0x233240e0, + 0xae01374c, + 0x3822fdfe, + 0x39028222, + 0x52fe0301, + 0x32234c37, + 0x161f3940, + 0x35494836, + 0x01001f16, + 0x33ff4b00, + 0x7182d101, + 0x00001424, + 0xef413505, + 0x0bab4e06, + 0x057e0125, + 0x4e324e23, + 0x3c260524, + 0xaecd5323, + 0x8c4e276a, + 0x4dfd220c, + 0x06c55b00, + 0xd402d727, + 0x00001e00, + 0x05354933, + 0xad491720, + 0x0aed5d0c, + 0x5d0aa149, + 0x98490cf3, + 0x217e2108, + 0xfe296082, + 0x442201d3, + 0xfe25253d, + 0x225d83a7, + 0x830127ff, + 0x05e14e5d, + 0x4b06fa41, + 0x97420ab7, + 0x22232107, + 0x4b081e4a, + 0x799013c1, + 0x20090d43, + 0x4a6b8559, + 0x8485091d, + 0x584a9c23, + 0x06b34600, + 0xe601e025, + 0x4f040602, + 0x092005fd, + 0x102ef282, + 0x2602b602, + 0x00006602, + 0x4c070700, + 0x07828f00, + 0x2e000122, + 0x20081782, + 0x00e60127, + 0x3300000b, + 0x23113335, + 0x23153335, + 0x2e153311, + 0x53f95454, + 0x60014353, + 0xa0fe4343, + 0x22cf8443, + 0x4cd800f4, + 0xa84f0823, + 0x06172209, + 0x0f4b1806, + 0x8401320e, + 0x111376fe, + 0x043e0101, + 0xffffff04, + 0x01f9fee6, + 0x2077845c, + 0x836f8267, + 0x00da2177, + 0xff2c9f82, + 0x01f4fff3, + 0x00c8026d, + 0x33270026, + 0x78288f83, + 0x8100b000, + 0xfdff0200, + 0x49208f82, + 0x0a261782, + 0x00001d00, + 0xa6563313, + 0x11132108, + 0x2305f168, + 0x17163233, + 0xa583a782, + 0x15752b08, + 0x11121a17, + 0x430c351f, + 0x14252e3e, + 0x6d520a1c, + 0x0675016d, + 0x0f14281b, + 0x8bfe1610, + 0x28383a01, + 0x0b0d3023, + 0x3badfef3, + 0xc184c6fe, + 0x0b012722, + 0x15d14b18, + 0x3843cd32, + 0x0b1c1652, + 0x0a110712, + 0x4952d920, + 0xfafc0603, + 0x85066e49, + 0x27022137, + 0x22243782, + 0x11330000, + 0x081ee047, + 0x52112126, + 0xb06e0152, + 0x3a295745, + 0x5743355c, + 0x4017281c, + 0x414a3530, + 0x1119153e, + 0xf7feb821, + 0x2ce2c802, + 0x593402f7, + 0x2106ad47, + 0xad472717, + 0x0691420a, + 0xe6018124, + 0x69840500, + 0x52276b82, + 0xe601dd52, + 0x82435dfe, + 0xff4d241b, + 0x82ec02f4, + 0x1821201b, + 0x200c8549, + 0x06f64237, + 0x3e082f51, + 0x27262223, + 0x4be10606, + 0x2e2d5249, + 0x2c534237, + 0x5243372e, + 0x20020744, + 0x40372c4c, + 0x184f250f, + 0x26089c49, + 0xfe60014b, + 0x833e44d7, + 0x461a2806, + 0x2b323022, + 0x84003429, + 0x87332065, + 0x07594365, + 0x99514e82, + 0x25708b0a, + 0x22049a02, + 0x5784294c, + 0x708c2c20, + 0x67adcd24, + 0x52832d26, + 0x89078851, + 0x4dfd216d, + 0x23065141, + 0x00f201f1, + 0x0d6f5318, + 0x26341124, + 0x4d182223, + 0xda4e091b, + 0x06284c09, + 0x0614112d, + 0x23157002, + 0x1708100c, + 0x1815230c, + 0x18082a4d, + 0x200e434d, + 0x0bea4e3a, + 0x09354d18, + 0x0b504d18, + 0x584a9522, + 0xff21eb82, + 0x09594fec, + 0x4e0c3f6e, + 0xff43072b, + 0x06142e09, + 0x0a201329, + 0x0a120810, + 0x0546151d, + 0x5a4d1803, + 0x8537200a, + 0x292f256d, + 0x23462402, + 0x0ba14e18, + 0x52496222, + 0x00256382, + 0x0227ff52, + 0x087d453d, + 0x2115b64f, + 0x2c5b3316, + 0x00022305, + 0xb64f3843, + 0x1c162c0d, + 0x1007120b, + 0x52d9200a, + 0x4f670149, + 0x8e200db8, + 0x820a9f42, + 0x01cd2468, + 0x181700e6, + 0x3c09d356, + 0x35352626, + 0x03231133, + 0x23272626, + 0x15151616, + 0x0ea94e52, + 0x03040d1f, + 0xab4d4e05, + 0x3108840d, + 0xedfee601, + 0x2f173b16, + 0xfeca265c, + 0x1613011a, + 0x0a83163c, + 0x00010027, + 0x01f4ff19, + 0x20b1829a, + 0x0ba1471d, + 0x4807c56f, + 0x36080a96, + 0x512cb606, + 0x3a172320, + 0x27442c21, + 0x23294026, + 0x1b2a1631, + 0x643a374b, + 0x0c673d3d, + 0x14371d21, + 0x37542f1d, + 0x172f5439, + 0x22173614, + 0x5053723b, + 0x00003c72, + 0x82100002, + 0x82ef205d, + 0x7923205d, + 0x26220a07, + 0xa64f2326, + 0x47362008, + 0x232206ad, + 0x144a0622, + 0x32272105, + 0x27207b83, + 0x0805ac47, + 0x5955004e, + 0x391c3643, + 0x1a121d1d, + 0x2716290e, + 0x52292a52, + 0x0e291528, + 0x1e1d121a, + 0x44351d37, + 0x2f2f5459, + 0x36282737, + 0x495a0c2e, + 0x1f316e35, + 0x0a3c0e24, + 0x29292e0c, + 0x3c0a0c2e, + 0x311f240e, + 0x5a49356e, + 0x2c2a3a42, + 0x59252559, + 0x003a2a2c, + 0x2105cd5c, + 0x8f82f001, + 0x16000f22, + 0x136b5718, + 0x86820320, + 0x26213f08, + 0x36320326, + 0x16162137, + 0x673c0f01, + 0x3c673e3e, + 0x3e3e663d, + 0x4e3a3d66, + 0x09230109, + 0x513e3b4e, + 0x05dbfe04, + 0x72390c50, + 0x3a715553, + 0x5355713a, + 0xbe013972, + 0x50484850, + 0x515983fe, + 0x73495a50, + 0xa7022105, + 0x18206582, + 0x210e457c, + 0xce762117, + 0x33152505, + 0x06062115, + 0x3723ea82, + 0x4a262611, + 0x01240572, + 0x426d421f, + 0x31080282, + 0x011e2f19, + 0xc0c0e518, + 0x1ddefeef, + 0x230f1430, + 0x0f231010, + 0x0c5d5d43, + 0x5453723a, + 0x08043a71, + 0xa03b8d3f, + 0x4305073f, + 0x5f010408, + 0x5f5c0705, + 0x6f825c60, + 0xf4ff3324, + 0x6f828d02, + 0x2d001523, + 0x05914700, + 0x33023e2b, + 0x15161632, + 0x22230614, + 0x050b4e26, + 0x35353624, + 0x4a531533, + 0x070f4908, + 0x49dd4308, + 0x714d2761, + 0x43856449, + 0x48294c5b, + 0x45130412, + 0x4d332324, + 0x2c152719, + 0x49633337, + 0x38316349, + 0x36786d0c, + 0x502f5064, + 0x7373497f, + 0x2a2e2e2a, + 0x68453742, + 0x16372f68, + 0x613c564f, + 0x3a633e39, + 0x57415050, + 0x02332e05, + 0x00c8027a, + 0x001e0015, + 0x05000026, + 0x058c5c35, + 0x33353722, + 0x22069450, + 0x82031507, + 0x1117367c, + 0x3405020e, + 0x3e112726, + 0x422e0102, + 0x75494975, + 0x74444c42, + 0x08068248, + 0x4e2ef743, + 0x2e4e2f2f, + 0x4c5fa201, + 0xcd2e4d30, + 0x703c02c4, + 0x3b6f4f4f, + 0x02d9d902, + 0x4f4f6f3b, + 0xc4023c70, + 0x543ac101, + 0x7a01022e, + 0x3a522e02, + 0xfe036356, + 0x542e0286, + 0xff010000, + 0x01f4fffd, + 0x00e60109, + 0x6d5a1811, + 0x081f450a, + 0x171d313d, + 0x0e140d10, + 0x5219431f, + 0x19020744, + 0x480a0c49, + 0x3d330404, + 0x1afe3801, + 0x87372e59, + 0xabb9823d, + 0x1a02233d, + 0x3d8738fd, + 0x70012722, + 0x1d207b82, + 0x25051150, + 0x06062335, + 0xfc472223, + 0x073a4506, + 0x22054257, + 0x82353f32, + 0x8929207e, + 0x4616208e, + 0x2126057f, + 0xa1444dd9, + 0x9687372e, + 0x43dcfd21, + 0x374507e8, + 0x5e012105, + 0x20089b43, + 0x07555335, + 0x08925018, + 0x2508756a, + 0x443843cd, + 0x50180307, + 0xdd460b9d, + 0x2402210a, + 0x09a85018, + 0x5d8a8a20, + 0x00005124, + 0x5d824f01, + 0x49000e21, + 0x5786060f, + 0x5111153c, + 0x21354f59, + 0x141a100f, + 0x3a013a25, + 0x450e6256, + 0x41400407, + 0x0200d7fe, + 0x33825200, + 0xef82cf20, + 0x59180e20, + 0x17220d87, + 0xa0742723, + 0x5221080a, + 0x305335ac, + 0x5b832d3d, + 0x364d5b75, + 0x4d363d3d, + 0x3f1be601, + 0x0e443a36, + 0xfbc0c0ca, + 0x272b2b2e, + 0x26499000, + 0x15331123, + 0x5f333733, + 0x23240da8, + 0x52acfe15, + 0x83254482, + 0x53303d2d, + 0x36498642, + 0x0ec8bebe, + 0x40353b44, + 0x2b29401c, + 0x00ad2f2a, + 0xff1c0001, + 0x82830127, + 0x423920c7, + 0x352005fb, + 0x24059050, + 0x26263435, + 0x78511827, + 0x22232319, + 0x954e2726, + 0x449a2709, + 0x5633043a, + 0x51183229, + 0x3a321985, + 0x1a1e3719, + 0x0a180d22, + 0xd9220d10, + 0x02994a58, + 0x5118141c, + 0x082a1d92, + 0x32313b0a, + 0x053d0306, + 0x71550008, + 0x1f012505, + 0x1b00d602, + 0x4c0d074d, + 0x7d550fac, + 0x4e412a09, + 0x100b1e14, + 0x2a0b1207, + 0x08014a1c, + 0x4a6b022c, + 0x3f050858, + 0x2c340603, + 0xd34696fd, + 0x82eb2005, + 0x823220fb, + 0x8d242057, + 0x35232257, + 0x09e24a37, + 0x22232628, + 0x33111506, + 0x6b4d2315, + 0x4d638a0f, + 0x01210e75, + 0x2169881a, + 0x804de7fe, + 0x00012205, + 0x186b8218, + 0x342f6152, + 0x014959d9, + 0x88053eda, + 0x25fe4388, + 0x0508312d, + 0x000b073e, + 0x21498302, + 0xb5825002, + 0x34002b22, + 0x200b3b76, + 0x053e4335, + 0x5d272621, + 0x4818074a, + 0x354d0d07, + 0x23112906, + 0x01161415, + 0x0d241651, + 0x2b05f956, + 0x2d491c03, + 0x48014549, + 0xd1450a4c, + 0x1f21d182, + 0x0635410a, + 0x39249225, + 0x4728d11f, + 0x332705af, + 0x23216f2c, + 0x83f15d61, + 0x414e2089, + 0x01290c44, + 0x01271f14, + 0x3e44e622, + 0x2a978200, + 0x02f4ff09, + 0x00e60140, + 0x5d200017, + 0x33210ad7, + 0x07ab4e15, + 0x23272325, + 0x43270606, + 0x353e0575, + 0x484dfa23, + 0xde535c5c, + 0x44585852, + 0x4c220307, + 0x26302b74, + 0x0cde223b, + 0x364f5d61, + 0x0082ab04, + 0xfffe3a34, + 0xc930284c, + 0x2b273e44, + 0x01000074, + 0xf4ff2800, + 0x5d82fa01, + 0xa7622520, + 0x82372008, + 0x153323e8, + 0x97450606, + 0x35362206, + 0x08fb8234, + 0x2315332f, + 0x15161615, + 0x01060614, + 0x34644611, + 0xb9611f37, + 0x3e203328, + 0x1f3d2e2d, + 0x61b92832, + 0x6334371f, + 0x38663f0c, + 0x021e684a, + 0x64223543, + 0x05384548, + 0x2264482b, + 0x1e024335, + 0x66384a68, + 0x206b823f, + 0x246b824b, + 0x00f201e0, + 0x4b6b841b, + 0x618308bd, + 0x07222326, + 0x32333627, + 0x29086185, + 0x536a5106, + 0x3a2a2d3e, + 0x0d29261e, + 0x23170d0f, + 0x61314f44, + 0x016f670c, + 0x52ebfe1c, + 0x3e633947, + 0x4006514d, + 0x556d6708, + 0xc1834e87, + 0x53180c20, + 0x13220ad5, + 0x6f481333, + 0x06062d05, + 0xac0c0307, + 0x5c55af60, + 0x040b180a, + 0x5b2e0382, + 0x1afee601, + 0x49241401, + 0x24492323, + 0x5318ecfe, + 0x20230ad5, + 0x82330000, + 0x16162637, + 0x36363317, + 0x21418937, + 0x4a890307, + 0x65821839, + 0x09100846, + 0x0a0f0804, + 0x54876044, + 0x080e0748, + 0x4b120f04, + 0x82094c50, + 0x0f072314, + 0x5d824708, + 0x4522fb28, + 0x22462525, + 0x67820401, + 0x42231928, + 0xfe444322, + 0x088301e7, + 0x23422224, + 0xa988e7fe, + 0x83d40221, + 0x133323ff, + 0x6218023e, + 0x0721090f, + 0x08b68b07, + 0x2f11c237, + 0x1c113145, + 0x1507100c, + 0x0f362909, + 0x6454c316, + 0x040c180b, + 0x560a150a, + 0x4d302b02, + 0x4105052c, + 0x2d3b0502, + 0x0119fe41, + 0x2247200d, + 0xfe204821, + 0xff0100f3, + 0x206282ff, + 0x051b4da0, + 0x0f475c18, + 0xa8a72308, + 0x1b0d4258, + 0x190e040e, + 0xa757420d, + 0x8a4201a4, + 0x1d1d371c, + 0xfe8a1c37, + 0x0100a4be, + 0x27ff1f00, + 0x3982ec01, + 0x97411720, + 0x21352905, + 0x35230135, + 0x33011521, + 0x2f098b44, + 0x3640b001, + 0x0001e5fe, + 0xff4c01e4, + 0x1d16fe00, + 0x2b052956, + 0x464251d9, + 0x4377012c, + 0x8189fe2c, + 0x2008c345, + 0x224f8202, + 0x82d501af, + 0x000b2a4f, + 0x2500002a, + 0x32070622, + 0x0c855732, + 0x5f852720, + 0x33160323, + 0x06f34136, + 0x22222338, + 0x01060623, + 0x142e1674, + 0x280b170b, + 0x3495122a, + 0x2e040804, + 0x7183265d, + 0x32ff473e, + 0x31481b31, + 0x534e312a, + 0x050c180a, + 0x3330a208, + 0x16121625, + 0x21120af3, + 0x01020110, + 0x03298086, + 0x29314d47, + 0x27114a34, + 0x20d18200, + 0x20d18203, + 0x56818296, + 0x36200c0d, + 0x2205c64d, + 0x83132707, + 0x072055dd, + 0x49c82308, + 0x1a29205c, + 0x3b243546, + 0x15414523, + 0xc0211119, + 0xbc5501f1, + 0x3a335d41, + 0x1e30d95e, + 0x25261834, + 0xcc542d43, + 0x2c432906, + 0x5a2d07fd, + 0x3362463b, + 0x454a6383, + 0x4b002009, + 0xe38205b9, + 0x26263722, + 0x27051e44, + 0x07061415, + 0x32331616, + 0x08087f66, + 0x165d0621, + 0x121a0e29, + 0x1c391d1d, + 0x55594336, + 0x35445954, + 0x1d1e371d, + 0x290e1a12, + 0x29522815, + 0x4a0c522a, + 0x6f27061f, + 0x59594a34, + 0x4a6f344a, + 0x6d820a39, + 0x82feff21, + 0x028d2204, + 0x05e146d4, + 0xca883620, + 0xdc563620, + 0x07280808, + 0x52569211, + 0x46333c42, + 0x5f1f2c19, + 0x365c3946, + 0x01314c2c, + 0x3e5b3148, + 0x1d2c443a, + 0x2b362136, + 0x54384055, + 0xdbfe1f44, + 0x00214882, + 0x20048214, + 0x654d87a3, + 0x6a4708a2, + 0x16143e07, + 0x31bd1117, + 0x5f382c4c, + 0x1e5c443a, + 0x3143182c, + 0x5652463e, + 0x441f2501, + 0x55403854, + 0x284c822b, + 0x3a442c1d, + 0xfe315b3e, + 0x06ad6eb8, + 0x4b829720, + 0x00002029, + 0x35233533, + 0x94353337, + 0x3315289e, + 0x9c152315, + 0x90205777, + 0x737325a5, + 0x85053688, + 0x6222a990, + 0x5d82883b, + 0x5d89a987, + 0x5c84ae93, + 0x5c82bd20, + 0x5c84b590, + 0xb9906220, + 0x5c828520, + 0x1d285d82, + 0x64010000, + 0x1500c802, + 0x0454bb88, + 0x23538409, + 0x324e809d, + 0x52210282, + 0x33008275, + 0x670536f5, + 0xf6f60536, + 0xf53b673b, + 0x40000200, + 0xb800f4ff, + 0x052b3b82, + 0x00001100, + 0x33270337, + 0x6e070307, + 0x602a0a7a, + 0x0254020c, + 0x23191c0c, + 0x03821923, + 0x7a01c63d, + 0x86fe8888, + 0x1d1b23d2, + 0x1b1d2323, + 0x00030023, + 0x01f4ff3b, + 0x00d402d2, + 0x4b19000b, + 0x3a420691, + 0x76461808, + 0x8a13200d, + 0x01300855, + 0x6e6e5e07, + 0x6e6e5d5e, + 0x2139235d, + 0x49353548, + 0x14233a21, + 0x14141c1c, + 0xb20c1b1b, + 0xbabab3c1, + 0x44b2c1b3, + 0x996f853b, + 0x6f999090, + 0x00013b85, + 0x14221a84, + 0xe8821c14, + 0x001e0025, + 0x825c0200, + 0x00272571, + 0x23112100, + 0x35210183, + 0x52738437, + 0x15220572, + 0xdb463315, + 0x22232108, + 0x15320d82, + 0x7d011123, + 0x424252cb, + 0x27324c4b, + 0x24231e11, + 0x5e18cb28, + 0xfe2e0c26, + 0x3ea3015d, + 0x584c4005, + 0x330d3e12, + 0x5e183e30, + 0xff210b33, + 0x206d84ff, + 0x2d6d82f4, + 0x00250226, + 0x00070000, + 0x00410224, + 0x1782ff00, + 0x03f4ff23, + 0x20178a19, + 0x27178327, + 0x1e000100, + 0x4502f4ff, + 0x29251782, + 0x11330000, + 0xa55e1823, + 0x365a180f, + 0x2223230f, + 0xc1823526, + 0x0bb95e18, + 0x440ab230, + 0x2a228484, + 0x100c1e0d, + 0x4e172f14, + 0x5e18ae3d, + 0x5a180cc8, + 0x5a250b4f, + 0xfe0d0148, + 0x2173855d, + 0x73826203, + 0x11413b20, + 0x41859626, + 0x92921825, + 0x94173441, + 0x002e269f, + 0x02280100, + 0x12175390, + 0x5353fa2e, + 0x46030247, + 0x47fdfd46, + 0x2500ffff, + 0x03322783, + 0x02260263, + 0x0000002a, + 0x003b0707, + 0xff0000ac, + 0x3f8300ff, + 0x178a3320, + 0x17863e20, + 0x2f821820, + 0x46034022, + 0x41202f88, + 0xff211785, + 0x221782fb, + 0x8849035d, + 0x85432017, + 0x14002117, + 0x44221782, + 0x17882d03, + 0x17864f20, + 0x17822620, + 0x18033222, + 0x45201788, + 0x2822778a, + 0x17883503, + 0x778c4d20, + 0x17884d20, + 0x2f8c5720, + 0x17886820, + 0x17875120, + 0x8332ff21, + 0x221788ff, + 0x84ad0069, + 0x821a20d7, + 0x033e2277, + 0x2017884a, + 0x252f834a, + 0x2e000100, + 0x2f832cff, + 0x491e0021, + 0x34230529, + 0x54233736, + 0x23200a4e, + 0x0a124318, + 0x3827b12d, + 0x5468182c, + 0x5353fa54, + 0x18221d57, + 0x22090b43, + 0x41134129, + 0x172b0757, + 0x17171d37, + 0x110b2d0e, + 0x84ffff00, + 0x05494159, + 0x00003626, + 0x3e070700, + 0x5a267186, + 0x2d025bff, + 0x19619002, + 0x2342080e, + 0x16232703, + 0x23111516, + 0x17133311, + 0x35262633, + 0x14113311, + 0x16a90106, + 0x0a100d24, + 0x17250d17, + 0x0447ee05, + 0x564f0704, + 0x030447ed, + 0xa53d4f07, + 0x03420408, + 0x012b3506, + 0x6831879d, + 0x02a9fe34, + 0x6718fe90, + 0x6d220792, + 0x6218574b, + 0x0121088d, + 0x06e761f2, + 0x42572220, + 0x37332108, + 0x188d6218, + 0x5d06715c, + 0x1d23154e, + 0x5d1afe2f, + 0xe3820c45, + 0xf4ff2f2a, + 0x0d03d901, + 0x39022602, + 0x3a23e384, + 0x83001501, + 0x20178ffb, + 0x21178b3d, + 0x2f88e402, + 0x178c4020, + 0x1788d120, + 0x178c4220, + 0x1788af20, + 0x178c4e20, + 0x17889220, + 0x178c4420, + 0x1788da20, + 0x178c4820, + 0x1788ef20, + 0x178c5220, + 0x1788ea20, + 0x17885620, + 0xd9013224, + 0x1788f201, + 0x2f8c6920, + 0x1788f820, + 0x17895020, + 0x03000223, + 0x20178811, + 0x2417868f, + 0x01f4ff1e, + 0x20178ad9, + 0x232f8991, + 0x1703e601, + 0x93202f88, + 0x200c3741, + 0x20178823, + 0x82178895, + 0x0837418f, + 0x40072722, + 0x00221783, + 0x978c0707, + 0x88400321, + 0x8c972037, + 0x2017894f, + 0x20178c99, + 0x202f8850, + 0x20178c9b, + 0x20178822, + 0x417f8c9d, + 0x27220757, + 0x7f8b4807, + 0x0002002b, + 0x0132ff2f, + 0x00f201ee, + 0x0a677a25, + 0x098d4018, + 0x32333627, + 0x37331716, + 0x0c8c6733, + 0x0de96018, + 0x3526a028, + 0x03071f31, + 0xcb5a4c1c, + 0x21402606, + 0x2c430702, + 0x8440182b, + 0x5ea92007, + 0xa56708f5, + 0x1c352205, + 0x05626029, + 0x752f1d21, + 0x01210b8f, + 0x09646007, + 0xd9209586, + 0x27209582, + 0x23069f4d, + 0x37363435, + 0x0e6f6118, + 0x8d11ac67, + 0x26202a97, + 0x03181e35, + 0x613c6e5b, + 0x058d5f37, + 0x03074427, + 0x18182a13, + 0x07b9671c, + 0x998b2920, + 0x19342022, + 0x39269689, + 0x100f1e12, + 0xbf671a39, + 0x259a8a06, + 0x2f00ffff, + 0x374332ff, + 0x00502806, + 0x07070000, + 0x431b013d, + 0x24210637, + 0x23b18201, + 0xeb010602, + 0x03230f89, + 0x8326020d, + 0x2027840f, + 0x21178919, + 0x1788e402, + 0x1a014022, + 0xda20178a, + 0x48201788, + 0xb620178c, + 0x4c201788, + 0x00211783, + 0x82878203, + 0xe8022a6f, + 0x2b001d00, + 0x00003900, + 0x08f35105, + 0x5b0d8d5c, + 0xbb7913eb, + 0x25f95b0d, + 0xaa797720, + 0x0e915c08, + 0x2112035c, + 0x8d79f601, + 0xff2f2110, + 0xea20ad83, + 0x5620c588, + 0x9220dd8c, + 0x44201788, + 0xd120178c, + 0x42201788, + 0x0128f584, + 0x00005200, + 0xc802a400, + 0x23097d77, + 0x38fdc802, + 0x2606a56f, + 0x02970300, + 0x825b0226, + 0x07062421, + 0x5134793e, + 0x142206e1, + 0x2d82f802, + 0x00000832, + 0x11331133, + 0x07332713, + 0x39525207, + 0x0e013b04, + 0x02213983, + 0x07cd7624, + 0x01000023, + 0x8557826b, + 0x09cd763f, + 0x1eff1c26, + 0xc802c900, + 0x6c225788, + 0x6d82007b, + 0x32ff4424, + 0x158ab200, + 0x15836920, + 0xfff6ff27, + 0x03020132, + 0x292b8648, + 0x7c450726, + 0x07060030, + 0x31827c69, + 0x56231b82, + 0x89020001, + 0x7b772147, + 0xa9827082, + 0x0d010022, + 0x0b207582, + 0xc2769d83, + 0x415e3509, + 0x3f525e1d, + 0x4d015d1e, + 0x01383529, + 0x27f3fe37, + 0x8afe3735, + 0x27056549, + 0xd402da01, + 0x21002600, + 0x07243b82, + 0x36015b02, + 0x01220782, + 0x8f822600, + 0xe601cf24, + 0x09471600, + 0x99561809, + 0x37362309, + 0x1b790617, + 0x13137911, + 0x00010027, + 0x01000009, + 0x20498210, + 0x06234b0b, + 0x15333536, + 0x15231533, + 0x525c5c65, + 0x36df5959, + 0x3bcccc05, + 0x020000df, + 0x8205635b, + 0x000a2227, + 0x50738222, + 0x2625058f, + 0x05062223, + 0x06bc5926, + 0x33363425, + 0x82171632, + 0x143f0885, + 0x16160706, + 0x191f2817, + 0x28072320, + 0x011a1c24, + 0x14252304, + 0x42392e41, + 0x2b17373e, + 0x04045314, + 0x6b173019, + 0x19211a13, + 0x40ae181d, + 0x41231f30, + 0x0b382d2d, + 0xfe02020b, + 0x10221303, + 0x182d4b1c, + 0x25082762, + 0x06029002, + 0x50180200, + 0x24200805, + 0x03210f84, + 0x21b08200, + 0x04825a00, + 0x9002d422, + 0x2d05c55a, + 0x11211521, + 0xfe7a015a, + 0x469002d9, + 0x3182b6fd, + 0xb0821e20, + 0x1d842e20, + 0x2008d584, + 0x15133313, + 0x27032125, + 0xd81e0723, + 0x4afed860, + 0x45665a01, + 0x02324504, + 0x32a2fd5e, + 0xd22c0147, + 0x837183d2, + 0x84de2051, + 0x18062061, + 0x8409c149, + 0x05ed430f, + 0x02211f82, + 0x200f8432, + 0x35818209, + 0xff340003, + 0x026502f4, + 0x0003009c, + 0x00210013, + 0x33351300, + 0x256a0315, + 0xbb531809, + 0xe0dc2212, + 0x466f1870, + 0x35012514, + 0xbffe4848, + 0x174b6f18, + 0x83ffff21, + 0xad0021eb, + 0x0a207984, + 0x20080b41, + 0x200f843f, + 0x2089820c, + 0x22038201, + 0x82030200, + 0x000d23ed, + 0x21513100, + 0x60d1350c, + 0x116a58d2, + 0x1204131c, + 0x0269111c, + 0x0170fd90, + 0x3a653a63, + 0xfe210282, + 0x21f1869d, + 0x47847d02, + 0x57880e20, + 0x0f842d20, + 0x53820f20, + 0x31000326, + 0xe4010000, + 0x03225782, + 0xa14a0700, + 0x15212305, + 0x03853501, + 0xb301312e, + 0x1d0198fe, + 0x9f01a2fe, + 0x35014747, + 0x15220382, + 0x53834646, + 0x23061541, + 0x10000602, + 0x5a249b84, + 0x2b020000, + 0x07274382, + 0x11330000, + 0x82231121, + 0x015a2503, + 0xd5fe53d1, + 0x02238e83, + 0x85b6fd4a, + 0x0b0221df, + 0x11207784, + 0x2c203384, + 0xf5207782, + 0x2107154b, + 0x72820313, + 0x0317213a, + 0xe22c1521, + 0xfea701de, + 0x01ccc9c2, + 0x1b01325f, + 0x46311201, + 0x47f8fefb, + 0x076b5018, + 0x15203f84, + 0x09c34b18, + 0x1a200f84, + 0x302cc784, + 0x9f02eaff, + 0x1500a602, + 0x23001c00, + 0x08152758, + 0x1614014f, + 0x06061117, + 0x27263405, + 0x01363611, + 0x447c5242, + 0x4b527c44, + 0x44447b53, + 0xf4fe537b, + 0x69585869, + 0x5968cd01, + 0x5d166859, + 0x4e724004, + 0x043e6f4e, + 0x3e045c5c, + 0x724e4e6f, + 0x015d0440, + 0x056a5461, + 0x66058101, + 0x05665353, + 0x6a057ffe, + 0x20958200, + 0x20c5820f, + 0x208584f2, + 0x24d58419, + 0x0200003f, + 0x26d5827c, + 0x21000017, + 0x59262635, + 0x17220519, + 0x6f823311, + 0x25080b84, + 0x01150706, + 0x52837436, + 0x524f5253, + 0x74835352, + 0x7e7705f5, + 0x595e9da1, + 0xfe580104, + 0x5e5805a8, + 0x777ea19d, + 0x5482f505, + 0x822d0021, + 0x02792949, + 0x0027009c, + 0x33353300, + 0x5906f558, + 0x4582067a, + 0x23153322, + 0x5905a24f, + 0x3c08076f, + 0x832d1517, + 0x4523361c, + 0x7e55557e, + 0x1d362346, + 0x4e38e983, + 0x3d3d572f, + 0x384d2e57, + 0x501c0444, + 0x8f5c4269, + 0x5c8f5252, + 0x1c506942, + 0x2c3d4404, + 0x7147678a, + 0x47714141, + 0x3d2c8a67, + 0x20c98200, + 0x2d6f8206, + 0x009e0233, + 0x16680226, + 0x03060000, + 0x15821994, + 0x82edff21, + 0x841e2015, + 0x406c2115, + 0x00201584, + 0x72201587, + 0x6e201584, + 0x0021158d, + 0x201584ed, + 0x2a158a70, + 0x010000ec, + 0x022d031c, + 0x85850006, + 0xf4ff233b, + 0x25849402, + 0x8d2f7621, + 0x84592051, + 0x7c7b2115, + 0xff201589, + 0xdd203b82, + 0xf7263b84, + 0x02000000, + 0x0482e9ff, + 0x2582a820, + 0x2b002722, + 0x24281541, + 0x17372701, + 0x1819415c, + 0x37dbfe24, + 0x1e414c1d, + 0xd001241f, + 0x820bc30b, + 0x2e00217a, + 0x2226bb82, + 0x2000f201, + 0xad673000, + 0x3733240c, + 0x53020e33, + 0x232d0967, + 0x23352622, + 0x36322706, + 0x2e373736, + 0x061f6402, + 0x53e94d08, + 0x38613c68, + 0x0215542d, + 0x1c0d5115, + 0x08131d14, + 0x0a0c0713, + 0x352b161f, + 0x204f3703, + 0x0803273a, + 0x172e280d, + 0x3f273f23, + 0x54777f0c, + 0x453a3e76, + 0x808e4073, + 0x051a192d, + 0x09043f03, + 0x45633330, + 0x5b294529, + 0x2c153835, + 0x5d554056, + 0x4f2a8d83, + 0x09024dff, + 0x1a00d402, + 0x8d823200, + 0x52341121, + 0x77180846, + 0x22270808, + 0x16162726, + 0x52323717, + 0x07210569, + 0x07b77527, + 0x06076208, + 0x4f161615, + 0x3044592b, + 0x2e323453, + 0x57365447, + 0x265a2e31, + 0x96010202, + 0x44444a35, + 0x340d181a, + 0x293c1c3e, + 0x03014038, + 0x02b35223, + 0x3d69439e, + 0x363b4c26, + 0x0a041d53, + 0x5c414d65, + 0x3d292130, + 0x4aec3e76, + 0x064e3a43, + 0x3f300b3f, + 0x5b383820, + 0x2dacaf56, + 0x0001001f, + 0x014dff06, + 0x00f201d0, + 0x20918219, + 0x08768236, + 0x27022e48, + 0x17021e37, + 0x37363633, + 0x07020e33, + 0xc4151616, + 0x38210203, + 0x1e532545, + 0x040e353f, + 0x5308492f, + 0x3c4c2c0d, + 0x21b30406, + 0x913c2830, + 0x15308595, + 0x4c99822a, + 0x5265c45c, + 0x2b629b92, + 0x02002a63, + 0xf4ff3400, + 0xe782e401, + 0xe95d2220, + 0x35262106, + 0x3722ea82, + 0x0682022e, + 0x52323321, + 0x162709ee, + 0x15021e17, + 0x5c270614, + 0x52080889, + 0x01060627, + 0x3e64370d, + 0x23345532, + 0x524d263d, + 0x3e147859, + 0x262a235d, + 0x2a274328, + 0xef712b46, + 0x42243f27, + 0x4c2c3f43, + 0x63350c58, + 0x3e5a3b45, + 0x3e361910, + 0x27412c26, + 0x1e121742, + 0x302f1a14, + 0x55431e1d, + 0xdf80673b, + 0x5926462f, + 0x22523d49, + 0x82006011, + 0x822e20e1, + 0x60ac208d, + 0x3d6a0571, + 0x15f06705, + 0x37363227, + 0x23222615, + 0x09154222, + 0x5afb2b08, + 0x262a3b73, + 0x32553327, + 0x21224f2c, + 0x2d223c1c, + 0x0e3a353d, + 0x2416131c, + 0x3e467812, + 0x23224023, + 0x4e0c522c, + 0x0b393544, + 0x1c820e04, + 0x1c3a2808, + 0x1537191c, + 0x21262616, + 0x4001022a, + 0x2f285202, + 0x22371b16, + 0x0001001a, + 0x0148ff30, + 0x00c802a0, + 0x05000027, + 0x5a363627, + 0x3e2c088e, + 0x06223702, + 0x21350706, + 0x030e2315, + 0x4b087782, + 0x16161716, + 0x01061415, + 0x161a4268, + 0x312e2f12, + 0x4f313353, + 0x581b2e5e, + 0x4a01205a, + 0x50602e05, + 0x2d412431, + 0xb81a4247, + 0x1424201b, + 0x0911140f, + 0x4f5e2f0a, + 0x63757938, + 0x02020123, + 0x63214343, + 0x39337775, + 0x0d082344, + 0x4716322d, + 0x4b24f983, + 0xd1014dff, + 0x1a20f982, + 0x49427782, + 0x23112308, + 0xd4823411, + 0x0808e960, + 0x027e012b, + 0x2b240103, + 0x52294028, + 0x074b0502, + 0x36512603, + 0x50b33d47, + 0x4446a0a6, + 0xfe3e2f3e, + 0x1d6101c2, + 0x38652642, + 0xfe5d6139, + 0x063f5319, + 0xd402cf26, + 0x12000b00, + 0x21075158, + 0x42583634, + 0x22033405, + 0x26330706, + 0x36320326, + 0x1e233736, + 0x5e050102, + 0x835e6c6c, + 0x44312e03, + 0x4304f204, + 0x20352232, + 0x2002f202, + 0x08325336, + 0x7c9c022d, + 0xfd7c8e8e, + 0x667934a8, + 0x83347966, + 0xff5224b1, + 0x64ea00f4, + 0x22080b69, + 0x14150606, + 0x17373233, + 0x33af0606, + 0x0501532a, + 0x0b120c22, + 0x3b0c1c0b, + 0x62810136, + 0x062758cd, + 0x8307053e, + 0xff492437, + 0x82f101f8, + 0x002223e9, + 0xde843300, + 0x15161626, + 0x023e3315, + 0x072a3883, + 0x0717021e, + 0x0627022e, + 0x02820706, + 0x0352153e, + 0x04055106, + 0x685e2704, + 0x54280834, + 0x4b42192d, + 0x391a5b24, + 0x170b1837, + 0x0111160b, + 0x483ded82, + 0x203e1320, + 0x51744398, + 0x3d0d4e0d, + 0x666b3031, + 0x521d0828, + 0x1e0d2c5b, + 0x304d1d10, + 0x206d8319, + 0x296d8210, + 0x00d402e7, + 0x17000014, + 0x8a721327, + 0x073a0805, + 0x33363627, + 0x13171632, + 0x67230323, + 0x1406d357, + 0x1d142936, + 0x2a11140e, + 0x20544821, + 0x048657b8, + 0xf1010808, + 0x0a454315, + 0x0a084406, + 0xfefd686a, + 0x01009301, + 0x4dff5200, + 0xef821702, + 0x49822520, + 0x11331122, + 0x2105be49, + 0x31513311, + 0x2223220a, + 0x06044e26, + 0xc7822720, + 0x2a52523a, + 0x223e212f, + 0x14050153, + 0x0b100d10, + 0x29141c0a, + 0x1a02052a, + 0x301d2845, + 0x033fbb82, + 0x9902b302, + 0x4240d7fe, + 0x4c013c23, + 0x1458cd62, + 0x053e0613, + 0x2e312d07, + 0x301c132e, + 0x83273d44, + 0x00062dbb, + 0x01c60100, + 0x001000f2, + 0x26263300, + 0x0809eb43, + 0x07060621, + 0x3e621bc1, + 0x303d2253, + 0x442c040e, + 0x57135309, + 0x5dfa864a, + 0x988f3415, + 0x62d25d42, + 0x8281e67f, + 0x1c002938, + 0xa80148ff, + 0x3900c802, + 0x5d08c942, + 0x36200557, + 0x42065343, + 0x222008cf, + 0x2207c85a, + 0x18261537, + 0x42087b7b, + 0x560806de, + 0x161a426f, + 0x5633432c, + 0x28442934, + 0x2226392c, + 0x1f2b291a, + 0x30728401, + 0x1d3a254a, + 0x13131a14, + 0x4c29141f, + 0x2d472830, + 0xb81b3e48, + 0x1424201b, + 0x0a0d1917, + 0x30404d2a, + 0x040c374f, + 0x29344a12, + 0x02011141, + 0x3e434302, + 0x2037233a, + 0x05460402, + 0x2f432301, + 0x421c3630, + 0x022607f7, + 0xf4ff2e00, + 0xe382e901, + 0xa1420f20, + 0x0be76a06, + 0x45270621, + 0xa083065c, + 0x3c0b0124, + 0x02823c65, + 0x05833d20, + 0x48413d3d, + 0x48404148, + 0x723b0c48, + 0x3c725251, + 0x5152723c, + 0x66443b72, + 0x67675554, + 0x83665455, + 0xff1628fd, + 0x013102f4, + 0x822200e6, + 0x822220fd, + 0x023e2d54, + 0x06142335, + 0x36362707, + 0x37352335, + 0x4206c543, + 0x012305ad, + 0x82303ae5, + 0xac3808a5, + 0x11530b12, + 0x01467112, + 0x030261d5, + 0x0c2e0102, + 0x210d0b1b, + 0x133b3f0c, + 0x285b5846, + 0x0566db66, + 0x3f62d967, + 0x5f294405, + 0x3012465a, + 0x07043f06, + 0x4e000200, + 0xf6014dff, + 0x1222bd82, + 0x25461f00, + 0x07cc7109, + 0x080a1d46, + 0x15150636, + 0x3a4e1616, + 0x6c663b61, + 0x27335b3a, + 0x0302224a, + 0x4c367e01, + 0x4f35443c, + 0x01b34122, + 0x376e55ab, + 0x76527484, + 0x41271e3e, + 0x67ec416a, + 0x5a63505a, + 0x19297c5c, + 0x2e206182, + 0x1620c782, + 0x1422c782, + 0x7f5c2100, + 0x33362608, + 0x26261521, + 0x066e5c27, + 0x20052441, + 0x068f6226, + 0x3b083c08, + 0x663f3c63, + 0x290a0139, + 0x332d2948, + 0x393b6038, + 0x2a3a1e4a, + 0x0c4c4d3a, + 0x5550703a, + 0x0346356e, + 0x19040104, + 0x6b4b4464, + 0x52604439, + 0x59345331, + 0x0062545b, + 0xff1a0001, + 0x82b201f4, + 0x84152067, + 0x11352165, + 0x43052441, + 0x280805d2, + 0x06173736, + 0x37200106, + 0x0146a32c, + 0x0202a452, + 0x0c180b29, + 0x0c290e0c, + 0x35013b3f, + 0x5243053e, + 0x05304a9f, + 0x09043f03, + 0x20478200, + 0x3547823c, + 0x00f201c7, + 0x1700001f, + 0x34352622, + 0x26343536, + 0x16163327, + 0xa16d1415, + 0x200f8306, + 0x080f8437, + 0x6257f939, + 0x50050304, + 0x41060305, + 0x1145352b, + 0x16155017, + 0x60600c72, + 0x1d2b562c, + 0x38192642, + 0x2d6f2920, + 0x5e5a3741, + 0x13437438, + 0x7c417f3f, + 0x00030083, + 0x024dff2e, + 0x626e027a, + 0xb32147af, + 0x07af62aa, + 0x627f7f21, + 0xaa2207af, + 0xaf62a701, + 0x09002514, + 0xe80141ff, + 0x0d20d982, + 0x3008d982, + 0x37031327, + 0x33373313, + 0x03071303, + 0xc1535c23, + 0x049352be, + 0xccad577d, + 0xbf04a350, + 0x0156010c, + 0xfcfe153a, + 0xfebffef8, + 0x1f0115b1, + 0x00010000, + 0x20b7823d, + 0x27b78279, + 0x05000024, + 0x35262635, + 0x24091441, + 0x16141506, + 0x05c24a33, + 0x5f183420, + 0x153d085a, + 0x717b3001, + 0x04500502, + 0x4f010102, + 0x58504d50, + 0x17501711, + 0xb3778515, + 0x678202a7, + 0x051d4182, + 0x343c1b37, + 0x025a4910, + 0x03c9fd37, + 0x61376766, + 0x6c3d1340, + 0x0391823f, + 0x246d82a7, + 0x02f4ff33, + 0x20a9828a, + 0x08d94e2e, + 0xa5441720, + 0x058d4106, + 0x72870c8a, + 0x3a06ba44, + 0x346049dc, + 0x2d294b26, + 0x35232836, + 0x045a0404, + 0x29223504, + 0x1c221034, + 0x6430284a, + 0x26080668, + 0x79780c44, + 0x2139874d, + 0x4c4d723c, + 0x1e433752, + 0x3d27273d, + 0x5434461e, + 0x484d3257, + 0x7b3a1f29, + 0x2a7a7a55, + 0x822a2e2e, + 0xff2e2485, + 0x8293014c, + 0x44232085, + 0x03200a7f, + 0x0de57f18, + 0x080a4747, + 0x1a423c40, + 0x222b1c1b, + 0x3c203642, + 0x42313a63, + 0x2b152a19, + 0x264c3d1d, + 0x303c253f, + 0x211ab41e, + 0x2018162c, + 0x36210c0d, + 0x6d4e3c51, + 0x36172239, + 0x50601813, + 0x0d244339, + 0x19323113, + 0x0300004d, + 0xf3824e00, + 0xd2020428, + 0x2a001800, + 0x71823700, + 0x022e2223, + 0x12b54935, + 0x2a092c43, + 0x15141407, + 0x03021e14, + 0x47150614, + 0x5f08076f, + 0x50273101, + 0x572b2943, + 0x35532e42, + 0x5b513838, + 0x393d6038, + 0x323e1d4a, + 0x1e3b3e10, + 0x017c322e, + 0x39296052, + 0x0c3f3828, + 0x425c3719, + 0x68430901, + 0x3b4b253c, + 0x041b5536, + 0x3f4f6a07, + 0x4948305a, + 0x2740263d, + 0x2210110b, + 0x27453613, + 0x20a40110, + 0x33101836, + 0x35392843, + 0x00020058, + 0x01f4ff42, + 0x23058b47, + 0x1300002c, + 0x37287882, + 0x2207022e, + 0x26221306, + 0x26080b42, + 0x36323316, + 0x82063736, + 0xab4e18b8, + 0x064c0808, + 0x5d341591, + 0x3d240347, + 0x72372929, + 0x06025a51, + 0x3901064e, + 0x20352228, + 0x477b5c01, + 0x2f4f2e1e, + 0x5b33726f, + 0x3c1f1d02, + 0x600a132d, + 0x3f013372, + 0x5b5aa3fd, + 0x101a342c, + 0x35462838, + 0x0c727c2f, + 0x2651401e, + 0xb72e5236, + 0x47a48bb3, + 0x2e318582, + 0x7a024dff, + 0x0b00f601, + 0x00002900, + 0x17161401, + 0x05bd4a36, + 0x4d030621, + 0x4c180503, + 0x675b079a, + 0x06610808, + 0x17161607, + 0x01017801, + 0x2c3a614a, + 0x4349291e, + 0x2e3d4876, + 0x622f2b43, + 0x5340544b, + 0x44744864, + 0x01010201, + 0x3e7a3d2b, + 0x535a6604, + 0xdffd3f60, + 0x6e3902aa, + 0x36824b53, + 0x44643430, + 0xf2045c54, + 0x71836268, + 0x023f7452, + 0xff2a552b, + 0xff2e00ff, + 0x032202f4, + 0x02260202, + 0x00000089, + 0x013f0707, + 0x2947181c, + 0x84ac2008, + 0x858d2017, + 0xf7002117, + 0x4b241784, + 0xd1014dff, + 0x8f201784, + 0x01211785, + 0x24178423, + 0x00f4ff52, + 0x201784ea, + 0x2e178291, + 0x7c3f0706, + 0xffffff00, + 0x01f4ffea, + 0x82af020e, + 0x2015855d, + 0x8315834e, + 0xe9012173, + 0x97202b84, + 0x0d204386, + 0x3c204384, + 0xc7202d82, + 0x9c201784, + 0x00211785, + 0x841789f4, + 0x20178545, + 0x2017864e, + 0x20bb8233, + 0x202f848a, + 0x212f85a0, + 0x2f835e01, + 0x82e1ff21, + 0x03172247, + 0x20758806, + 0x85758481, + 0x8515835d, + 0x85812045, + 0xfaff3245, + 0x42020000, + 0x26009902, + 0x00256802, + 0xa7030600, + 0x20b98306, + 0x201582f3, + 0x2015853a, + 0x2015831d, + 0xe97318a8, + 0x0b354e08, + 0x4e19a921, + 0x02230a4b, + 0x84800206, + 0x29b5827f, + 0x9e02c702, + 0x68022700, + 0x9982aa00, + 0xab030622, + 0x53831784, + 0x1786c320, + 0x1784a620, + 0x2f88ac20, + 0xad20178d, + 0xbf202f88, + 0xa2202f86, + 0xae202f84, + 0xe8201784, + 0x62229b82, + 0xb183a002, + 0x9b834520, + 0x1594af20, + 0xb188b020, + 0x4a031d26, + 0x3c000602, + 0x18200f8a, + 0x3b200f82, + 0x54207b88, + 0x6c21e784, + 0x204b8376, + 0x8b7988a7, + 0x21fd8415, + 0x1d4feaff, + 0x84a9200e, + 0x06334f2b, + 0x8120fd82, + 0xcb205188, + 0x6c21b584, + 0x201b8200, + 0x20fd8b00, + 0x821786c8, + 0x89178249, + 0x052d41fd, + 0xe9006c22, + 0xfd89e584, + 0x22051541, + 0x8ae5006c, + 0x82f420fd, + 0x84a82085, + 0x8e6e20b1, + 0x89158bb1, + 0x4f7220b1, + 0xb1890ab9, + 0xb1821582, + 0xb1878220, + 0x841f0321, + 0x8f6e2099, + 0x1c0321b1, + 0xb18e1786, + 0x861b0321, + 0x21b18e17, + 0x17861703, + 0xe820b18b, + 0xee28b182, + 0x2700a002, + 0xbc006e02, + 0xb141c984, + 0x20178d09, + 0x218f87b0, + 0xe1842301, + 0xe18d7020, + 0xe188158c, + 0x880c8550, + 0x821583e1, + 0x888320e1, + 0x849a2051, + 0x8f702099, + 0x970121e1, + 0xe18e1786, + 0x86960121, + 0x21e18e17, + 0x17869201, + 0x0121e18e, + 0x20e18469, + 0x8ee18f70, + 0x2ae18517, + 0x010000f2, + 0x024a0316, + 0x848d0006, + 0x82fe209f, + 0x030a220f, + 0x200f8218, + 0x2b0f8486, + 0x02f4fff4, + 0x009c02c6, + 0x61760226, + 0x820a9542, + 0x85b82015, + 0x43532015, + 0xff210893, + 0x831582ea, + 0x202b82db, + 0x41158335, + 0x15820601, + 0x9e029426, + 0x85020602, + 0x03215187, + 0x22b98447, + 0x43e20076, + 0xff230b93, + 0x864303f4, + 0x43de2017, + 0x17820b93, + 0x17863d20, + 0x9542d820, + 0x2017820b, + 0x20178639, + 0x0a9542d4, + 0x0000f326, + 0x99028102, + 0x7821b182, + 0x839b8976, + 0x82862015, + 0x02272315, + 0x9782007b, + 0x03060022, + 0x2008b541, + 0x0bff5102, + 0x8308b541, + 0x41b38215, + 0x3d820505, + 0x84030321, + 0x017b226b, + 0x829b8a26, + 0xfe022117, + 0x21201786, + 0x230e1744, + 0x00a002cf, + 0xf2206d83, + 0x6d411784, + 0x05575205, + 0x26024a22, + 0x00248582, + 0x4a070700, + 0x0cff5f18, + 0x17881820, + 0x17834520, + 0xff020023, + 0x26cb82f4, + 0x009c02da, + 0x52360027, + 0x43182a77, + 0x8e200cd5, + 0x2a198252, + 0x211709a1, + 0x41092a29, + 0x52331f49, + 0xcd2e2089, + 0x1b1e0926, + 0x2f011d17, + 0x232c2e01, + 0x9b821a2d, + 0xcc20fb83, + 0x2e219baf, + 0xe4531802, + 0x9980200a, + 0x1df92a9a, + 0x41491f33, + 0x21292a09, + 0x259aa117, + 0x232d1a07, + 0x9a822e2c, + 0x1b171d25, + 0x8200091e, + 0x82eb209b, + 0x53ab2004, + 0x5f2032af, + 0xd5239199, + 0xa01d4c32, + 0xc3d0268a, + 0xff00c30b, + 0x072f54ff, + 0x02060229, + 0x00000088, + 0x82f4ff03, + 0x84592004, + 0x0034258f, + 0x21000038, + 0x22255755, + 0x18362701, + 0x25096964, + 0x17372717, + 0x9f990d01, + 0x120c2229, + 0x35094319, + 0xa48f3941, + 0x0b262ca8, + 0x0435151e, + 0x2e30012f, + 0x830c352c, + 0x20a582b5, + 0x20a582f3, + 0x21a5b155, + 0xd3412626, + 0x14152305, + 0xa5841716, + 0xa5990920, + 0x39225c2a, + 0x43093640, + 0x336c1219, + 0x2c234e41, + 0x2e2c350c, + 0x042f0130, + 0x0b1e1535, + 0x20a58626, + 0x20a582f4, + 0x41a5b154, + 0x37240c4b, + 0x08010717, + 0x2720a599, + 0x23074b41, + 0x324c1d5d, + 0x4121f441, + 0x01200b4b, + 0x200a4b41, + 0x41a5b151, + 0xa5830c4b, + 0xa5990520, + 0x4b416020, + 0xa4392007, + 0x0b4b41a5, + 0xa5861b20, + 0x0000e82c, + 0xa0020603, + 0x3d002700, + 0x61444b00, + 0x26222129, + 0x210a0c7d, + 0xfb733316, + 0x27072105, + 0x200b7744, + 0x2bb799ba, + 0x191e18ec, + 0x02100c10, + 0x2120042a, + 0x11210a84, + 0x290a8201, + 0x1812086d, + 0x3b072520, + 0x7041393e, + 0x50022a1f, + 0x130c1112, + 0x11232306, + 0x30068412, + 0x0e052199, + 0x02100e0a, + 0x1f1d0227, + 0x0300211f, + 0x18d5ccff, + 0xb00c9658, + 0x243729d5, + 0x073a403a, + 0x13172025, + 0x0724d5b0, + 0x1d1f1f21, + 0x1020d482, + 0x0522dc82, + 0xd782ffff, + 0x0903f43c, + 0x26009002, + 0x00006802, + 0x97030700, + 0x00001e02, + 0xfaffffff, + 0x2e03f4ff, + 0x17829902, + 0x1786b020, + 0x17844320, + 0x1782f320, + 0x17842720, + 0x1786b120, + 0x7f473c20, + 0x02b32208, + 0x202f829e, + 0x201786b4, + 0x202f88c8, + 0x201784af, + 0x201786b5, + 0x852f88c4, + 0x8cb62017, + 0x205f8317, + 0x202f84ab, + 0x201786b7, + 0x202f84c0, + 0x227782e8, + 0x82a0024f, + 0x86b8205f, + 0x8e642017, + 0x8bb92017, + 0x5a002117, + 0x75202f82, + 0x6e20d784, + 0x8a201786, + 0xeb207788, + 0x8782bf84, + 0xef820020, + 0x1e820320, + 0xffffff22, + 0x17857783, + 0x1082c520, + 0xf4241789, + 0x6304f4ff, + 0xcf828f84, + 0x78202f84, + 0x2f824784, + 0x845f0421, + 0x86c92017, + 0x8474202f, + 0x202f8317, + 0x2017845e, + 0x201786ca, + 0x202f8873, + 0x2017845a, + 0x201786cb, + 0x8217846f, + 0x310421d7, + 0xcc20d784, + 0x46201786, + 0xcd20178e, + 0x00231789, + 0x822d0002, + 0x028f26d7, + 0x0027009c, + 0x28594338, + 0x26220523, + 0x0c365535, + 0x26195a5b, + 0x2c323e02, + 0x55040253, + 0x5d42063f, + 0x3b0c301f, + 0x50310136, + 0x1314489f, + 0x07053e06, + 0x82ffffff, + 0xee0321fd, + 0x26229d82, + 0xb586eb02, + 0x05420320, + 0x84e12008, + 0x85ec2017, + 0xf6022117, + 0x26082d41, + 0x009e026d, + 0x85ef0226, + 0x4b032017, + 0xf32405b1, + 0x6904f4ff, + 0xf0201784, + 0x7e201786, + 0x17852f88, + 0x178cf120, + 0x65202f83, + 0xf2202f84, + 0x7a201786, + 0x22084541, + 0x82a0021d, + 0x86f3205f, + 0x8e322017, + 0x8bf42017, + 0x102d4f17, + 0x1c015f24, + 0x454f0a00, + 0xf5022107, + 0x2008454f, + 0x09454f5d, + 0x03220223, + 0x2017880d, + 0x2017963a, + 0x4f178c3d, + 0xa520098d, + 0xa2201796, + 0xa4201796, + 0xa1201796, + 0x2720178c, + 0xa6208f88, + 0xa3201796, + 0x0221178b, + 0x202f88da, + 0x20178c48, + 0x20178892, + 0x20178c44, + 0x201788d1, + 0x23178942, + 0xf802ac01, + 0x4d501782, + 0x505f2005, + 0x2e22064d, + 0x1782f4ff, + 0x1788f520, + 0x178b5d20, + 0x880d0321, + 0x963a2017, + 0x8c3d2017, + 0x88022017, + 0x96a5202f, + 0x96a22017, + 0x96a42017, + 0x50a12017, + 0xbf840bf5, + 0x00008f26, + 0x5f070700, + 0x2506f550, + 0x014dff4b, + 0xbf8302d1, + 0x5d201785, + 0xbf84178b, + 0x3a201785, + 0x3d201796, + 0xbf83178c, + 0xa5202f85, + 0xa2201796, + 0xa4201796, + 0xa1201796, + 0x2723178c, + 0x85022602, + 0x96a6205f, + 0x8ca32017, + 0x88d120d7, + 0x8642202f, + 0x51382017, + 0x5f260ee5, + 0xffff0a7c, + 0x15832c00, + 0x51f50221, + 0x5d26086f, + 0xffff007c, + 0x2b84edff, + 0x15880d20, + 0x15833a20, + 0xff440026, + 0x030b01f4, + 0x3d201589, + 0xe0242b84, + 0xef00f4ff, + 0x200a3d52, + 0x201584a5, + 0x206d8eda, + 0x202b88a2, + 0x202b8afc, + 0x201584a4, + 0x202b82e4, + 0x20158af6, + 0x201584a1, + 0x216d82ef, + 0xf7830309, + 0x20057f52, + 0x201594a6, + 0x821584a3, + 0x18012383, + 0xaf88da02, + 0x15844820, + 0x4182f720, + 0x92020122, + 0x44201588, + 0xcf201584, + 0x29221582, + 0x1588d102, + 0x15844220, + 0x200f7752, + 0x20159489, + 0x20158481, + 0x224182e3, + 0x88260315, + 0x538a2041, + 0x5f221419, + 0x5f440d01, + 0xe9012307, + 0x2d82f502, + 0x20053153, + 0x6b17825d, + 0xf42405e1, + 0x0d03e901, + 0x3a201788, + 0x3d201796, + 0x0220178c, + 0xa5202f88, + 0xa2201796, + 0xa4201796, + 0xa1201796, + 0x4e231786, + 0x41014dff, + 0x99200585, + 0x20062743, + 0x84bf8425, + 0x85bf8417, + 0x015d2217, + 0x14f15325, + 0xf4005f22, + 0x3c242f84, + 0xc701f4ff, + 0xab532f84, + 0x545d2005, + 0xef840b09, + 0x3a201785, + 0x3d201796, + 0xef83178c, + 0xa5202f85, + 0xa2201796, + 0xa4201796, + 0xa1201796, + 0x2723178c, + 0x85022602, + 0x96a6205f, + 0x8ba32017, + 0xd1022117, + 0x42202f88, + 0xda20178c, + 0x48201788, + 0x9220178c, + 0x44201788, + 0xcb545f8c, + 0x96892009, + 0x8c812017, + 0x88262017, + 0x558a2047, + 0x5f2e1641, + 0x0a005e01, + 0x3300ffff, + 0x8a02f4ff, + 0x2f82f502, + 0x0000a026, + 0x5d070700, + 0x85055955, + 0x0d032117, + 0x3a201788, + 0x3d201796, + 0x0220178c, + 0xa5202f88, + 0xa2201796, + 0xa4201796, + 0xa1201796, + 0x2720178c, + 0xa6205f88, + 0xa3201796, + 0x0221178b, + 0x202f88d1, + 0x26178642, + 0x0237ff2e, + 0x46f20122, + 0x822308b7, + 0x43001f01, + 0x1782055f, + 0xbf820320, + 0x00650326, + 0x07070000, + 0x8209ef47, + 0xf5022317, + 0x17862602, + 0x8209ef47, + 0x0d032117, + 0xef471788, + 0x47178d09, + 0x5f8d09ef, + 0x8d09ef47, + 0x09ef4717, + 0xef47178d, + 0x47178d09, + 0x178309ef, + 0x8f882720, + 0x8d09ef47, + 0x09ef4717, + 0x02211782, + 0x472f88d1, + 0x4b2607bf, + 0xd10137ff, + 0x0f46f201, + 0x07062706, + 0xff007682, + 0x158400ff, + 0x82020321, + 0x4771202d, + 0x0a200815, + 0x02211787, + 0x471788f5, + 0x45820915, + 0x880d0321, + 0x09154717, + 0x1547178d, + 0x89178309, + 0x0915475f, + 0x1547178d, + 0x47178d09, + 0x178d0915, + 0x83091547, + 0x88272017, + 0x0915478f, + 0x1547178d, + 0x21178209, + 0x2f88d102, + 0x26071547, + 0x0237ff33, + 0x42f2018a, + 0x82270855, + 0x00005801, + 0x8400ffff, + 0x83032017, + 0x417d20bf, + 0x5d43061f, + 0x212f8207, + 0x4782f502, + 0x5d431785, + 0x21178209, + 0x17880d03, + 0x8d095d43, + 0x095d4317, + 0x5f891783, + 0x8d095d43, + 0x095d4317, + 0x5d43178d, + 0x43178d09, + 0x1783095d, + 0x8f882720, + 0x8d095d43, + 0x095d4317, + 0x02211782, + 0x222f88d1, + 0x825e0142, + 0x00012af7, + 0x0145ff49, + 0x00f201f1, + 0x165f6228, + 0x07060626, + 0x37363627, + 0x2a1c6562, + 0x601d4921, + 0x1a1c4827, + 0x62173739, + 0x34291a6b, + 0x29082364, + 0x511d2b59, + 0x0971625a, + 0x2e000226, + 0xe9014dff, + 0x0b257f82, + 0x00002100, + 0x0ac16025, + 0x67681720, + 0x021e240f, + 0x600b0115, + 0x1b2306c9, + 0x60315334, + 0x2f2a05dd, + 0x01013352, + 0x55673602, + 0x03836755, + 0x09aae925, + 0x60486b3f, + 0x472905e4, + 0x1f0a3f6a, + 0x00233633, + 0x26658201, + 0x01b80148, + 0x611f00e6, + 0x33240fdd, + 0x22261533, + 0x61050c60, + 0x310806c3, + 0x161b425f, + 0x5b353a1f, + 0x446f4037, + 0x294b1d97, + 0x4456594b, + 0xb81d3546, + 0x1225201b, + 0x0d0e2014, + 0x554c6138, + 0x0246356e, + 0x4e4f5b59, + 0x2e331111, + 0xed624a16, + 0x83012105, + 0x3d05d36c, + 0x15211117, + 0x15331723, + 0x17161423, + 0xe4310152, + 0x03cece02, + 0x9902b301, + 0x513bd943, + 0x2b825899, + 0xf1821120, + 0xb202da24, + 0x8b891d00, + 0x07060626, + 0x27262527, + 0x26220685, + 0xea823727, + 0x06145408, + 0x0a50c801, + 0x3f050508, + 0x0122447a, + 0x451b0f10, + 0x01224b84, + 0x4a752a16, + 0x54a17433, + 0x300ab308, + 0x3f202e5c, + 0x233a1c1f, + 0x383f7a45, + 0x45263e1f, + 0x2b78477d, + 0xffd2463d, + 0xff60328b, + 0xff2f00ff, + 0x01c60056, + 0x040602db, + 0xff000085, + 0x014100ff, + 0x82b8005d, + 0x0407260f, + 0x01000082, + 0x26118369, + 0xb8001e02, + 0x84029c02, + 0x2a022111, + 0x52249982, + 0xb900c101, + 0x04329982, + 0x37130000, + 0x52070733, + 0x220f5116, + 0x5cf1c101, + 0x1d820095, + 0x0000402c, + 0xf200a700, + 0x00000400, + 0x1e823733, + 0x220f4027, + 0x965c1636, + 0x2c5d83f2, + 0x012e02ee, + 0x0002036e, + 0x013f0707, + 0x2a27820f, + 0x01edff01, + 0x025600d0, + 0x8203009e, + 0x37272b4b, + 0x1d372417, + 0x0bd0014c, + 0x2d830bc3, + 0x33027a26, + 0x0603b001, + 0x81222d82, + 0x9d841501, + 0x37fff426, + 0xc2ff6f01, + 0x82201182, + 0x6d821183, + 0xf4ff5228, + 0x9601eb00, + 0x955f1000, + 0x0c024f05, + 0xe74eb020, + 0x0fc74e0b, + 0x02cb0027, + 0x025f013c, + 0x204b82f8, + 0x218b835f, + 0x1192ffff, + 0x3e02bf26, + 0xf5025301, + 0x5d202382, + 0xb4202386, + 0x3020c182, + 0x3c20c184, + 0xd38e1186, + 0x73244782, + 0x82012f02, + 0xa5202384, + 0x6d202386, + 0x7b201182, + 0xa2201184, + 0x23831186, + 0x11848f20, + 0x1186a420, + 0x23827720, + 0x11848920, + 0x1186a120, + 0x32028226, + 0x27039c01, + 0xa6207d82, + 0xa3201190, + 0x62261186, + 0xbc014102, + 0x2382d102, + 0x11864220, + 0x33027426, + 0x0603aa01, + 0x89201182, + 0x81201190, + 0x76261186, + 0xa8014c02, + 0x23822603, + 0x87418a20, + 0x01f42b06, + 0x028700cd, + 0x000e0099, + 0x8e531300, + 0x1806210c, + 0x2009eb57, + 0x0fcb5701, + 0xf3ff0122, + 0x86203782, + 0xa2573786, + 0x5762200c, + 0x01210987, + 0x0f6757cd, + 0xeaff0126, + 0x5300d001, + 0x2409f741, + 0x1d4c321c, + 0x07035701, + 0x2d061342, + 0x94030602, + 0x02000000, + 0xd001f4ff, + 0x2b820001, + 0x10000c23, + 0x209d8600, + 0x05ec6227, + 0x37271724, + 0x72551817, + 0x848f2007, + 0x0b525543, + 0x0bc30c23, + 0x203f82c3, + 0x206b82f3, + 0x553f88fc, + 0x3f820c28, + 0x58564e20, + 0xd001210b, + 0x200bec54, + 0x9a3f8526, + 0x1737227f, + 0x257f8807, + 0x324c1d5d, + 0xd255d001, + 0xff022110, + 0x3f827f9a, + 0x39207f88, + 0x6c553f84, + 0xff022c10, + 0x00b701e8, + 0x00a002d4, + 0x82230015, + 0x224255ff, + 0x27558f20, + 0x1e07551e, + 0xde5471a5, + 0x5471950c, + 0x719009c3, + 0x2410a354, + 0x1d020000, + 0x06577102, + 0x00020023, + 0x2d0f825a, + 0x0090021b, + 0x0016000d, + 0x21113300, + 0x79182115, + 0x272008fd, + 0x08fb7918, + 0xfe95013f, + 0x6c467ebe, + 0x826c803e, + 0x56545474, + 0x90027254, + 0x4f24ce46, + 0x42606742, + 0x383f4340, + 0x06c36f00, + 0x85089f71, + 0xd401210f, + 0x02226783, + 0x6282006a, + 0xff1a0025, + 0x82640244, + 0x00093667, + 0x1300001e, + 0x21070606, + 0x020e2311, + 0x27231503, + 0x023e3335, + 0x08028237, + 0x3311213d, + 0x35230715, + 0x162310df, + 0x0ab73101, + 0x497d0f0e, + 0x1d0e1e09, + 0x120c1020, + 0x4c010b13, + 0x01490949, + 0x1f6c5325, + 0x5b380302, + 0xbca3fe5a, + 0x2c0632d1, + 0x69415763, + 0xb7fd466d, + 0x71bcd132, + 0x002b10c1, + 0x00060001, + 0x021e0300, + 0x822f009c, + 0x271331d9, + 0x2223022e, + 0x36270706, + 0x16163233, + 0x11331717, + 0x76820182, + 0x2708266c, + 0x13070706, + 0x11230323, + 0x50080182, + 0x46c90603, + 0x0f1a1d10, + 0x0e060e04, + 0x321e150f, + 0x5a4c172d, + 0x174d594f, + 0x151e322d, + 0x0c070e0f, + 0x1c1b0e05, + 0x5bc84611, + 0x5f4f5faa, + 0x9d5c01aa, + 0x020b2325, + 0x14064e02, + 0x01a73234, + 0xa7ebfe15, + 0x06143432, + 0x0b02024e, + 0xfe9d2523, + 0xfe3701a4, + 0x820383c9, + 0xff2a248f, + 0x820202f4, + 0x182b208f, + 0x180fbb7a, + 0x23129453, + 0x07061415, + 0x08062267, + 0x47160143, + 0x2c2f3273, + 0x462b3957, + 0x4a545d2a, + 0x494d5636, + 0x1e4e2e37, + 0x3c6a232d, + 0x2f33745c, + 0x6b3f4b39, + 0x39332d0c, + 0x3a1e252b, + 0x403c3f29, + 0x3534373a, + 0x23381c21, + 0x344f592b, + 0x0b04114f, + 0x583f4453, + 0x267d822f, + 0x0200005a, + 0x18900236, + 0x8207cd7a, + 0x3733235f, + 0xef823313, + 0x3736342d, + 0x5a030723, + 0x04030752, + 0x8558f147, + 0x90023306, + 0x6b34adfe, + 0x9e018632, + 0x570170fd, + 0x86316834, + 0xd54162fe, + 0x36023105, + 0x26024903, + 0x0000b903, + 0x4b070700, + 0x04004c01, + 0x42205b86, + 0x1922d982, + 0x58410000, + 0x535a2718, + 0x2d1c5c71, + 0x42411d2e, + 0x1b182706, + 0x5be25714, + 0x698270ca, + 0x32a7eb2e, + 0x4d061335, + 0x240b0102, + 0xa3fe9c24, + 0x24062d41, + 0x02f4ff00, + 0x21af821c, + 0x41180018, + 0x3625097f, + 0x37363637, + 0x08b38221, + 0x06062332, + 0x38020e07, + 0x110e1a10, + 0x1e120d0f, + 0x24140f1d, + 0x53480113, + 0x111d10b4, + 0x0c392c12, + 0x064d0504, + 0x674d4c17, + 0x70fd6cc9, + 0xae5a4a02, + 0x286b6457, + 0x7317f172, + 0xdf8208d3, + 0x860cbd72, + 0x022b26ef, + 0x02060290, + 0x08217377, + 0x0f830b20, + 0x84110021, + 0x262f830f, + 0x029c021b, + 0x84040006, + 0x001c240f, + 0x84fc0100, + 0x0015211f, + 0x00210a82, + 0x22c38205, + 0x75900202, + 0x440806a5, + 0x16163727, + 0x37363233, + 0x13330337, + 0x13373317, + 0x06060333, + 0x0e1d1688, + 0x0e140811, + 0x0e0d2820, + 0x327a59e0, + 0x55712e04, + 0x0c4c19d7, + 0x034b0505, + 0x231c1904, + 0xdcfef601, + 0x24018181, + 0x463de7fd, + 0x00030000, + 0x2251822f, + 0x829c02ad, + 0x0018237f, + 0x8f67001f, + 0x36342405, + 0x42333537, + 0x0721052c, + 0x0ec97215, + 0x95854925, + 0x834a8595, + 0xfe2d0804, + 0x616169ec, + 0x68de0169, + 0x0c686262, + 0x7381055e, + 0x5d047d73, + 0x737d045d, + 0x5e058173, + 0x61555701, + 0x036d0103, + 0x5c55555c, + 0x0393fe03, + 0x13c17261, + 0x44ff5a24, + 0xcd826802, + 0x77830c20, + 0x33112123, + 0x38038311, + 0x02071533, + 0x5344fe16, + 0x49531f01, + 0x02bcbc09, + 0x02b7fd90, + 0x32b7fd49, + 0x20ff83d1, + 0x20048243, + 0x283182fc, + 0x21000014, + 0x23060611, + 0x07f77222, + 0x36323323, + 0x3f408237, + 0x3918a901, + 0x396b4a27, + 0x254f5552, + 0x01531437, + 0x29060426, + 0x9e9e4f5e, + 0x04063f52, + 0x70fd2501, + 0x00253e82, + 0x0300005a, + 0x20438207, + 0x065b420b, + 0x33203682, + 0x5a250382, + 0xdc51dc52, + 0x826e8752, + 0x00702372, + 0xa1820001, + 0x82500321, + 0x8d10202b, + 0x21a3822b, + 0x30853523, + 0x49094922, + 0xa682338a, + 0x0000bc25, + 0x821c0002, + 0x45a42004, + 0x23210905, + 0x25d98235, + 0x15161632, + 0xa7180614, + 0xee3f0974, + 0x6c2601d2, + 0x83416f46, + 0x5368726d, + 0x61565955, + 0xfe464a02, + 0x415127f3, + 0x3e446169, + 0x823c3c46, + 0x21ab83a6, + 0xab84c402, + 0x18001422, + 0x478f8386, + 0xbc830120, + 0x48665337, + 0x6e833d6d, + 0x56535d67, + 0x015a5656, + 0x900253c4, + 0x5126f3fe, + 0x234b8442, + 0xc0fe3a3e, + 0x7020a482, + 0x51849482, + 0x51861820, + 0x8f055b43, + 0x535a224f, + 0x264b8479, + 0x57536f7a, + 0x8d6d5656, + 0x01002948, + 0xf4ff2000, + 0x9c020702, + 0x1806337f, + 0x2108395b, + 0x225c2135, + 0x08ea820c, + 0x43f30634, + 0x212e2967, + 0x6856334f, + 0x01edfe04, + 0x56630912, + 0x2e1d4b2b, + 0x533d6720, + 0x7d47457c, + 0x342d320c, + 0x7c7c2822, + 0x216f6847, + 0x3120361d, + 0x6f6f974e, + 0xa3844d98, + 0x03f4ff23, + 0x23618258, + 0x0023000d, + 0x0ea9a518, + 0x26221727, + 0x11232726, + 0x23f38223, + 0x33363633, + 0x063dbb85, + 0x52394a02, + 0x5556622d, + 0x38532c62, + 0x0444764d, + 0x94535392, + 0x516f8e0c, + 0x79444479, + 0x4588183d, + 0x4e492509, + 0xcbfe6390, + 0xed28d082, + 0x97519887, + 0x549a6969, + 0x16366d83, + 0xec010000, + 0x0e009002, + 0x00001700, + 0x03231121, + 0x26261323, + 0x5d823435, + 0x11333108, + 0x23353303, + 0x14150622, + 0x79990116, + 0x40b760aa, + 0x43683b54, + 0x6e6ec1cd, + 0x0153534c, + 0x01ebfe15, + 0x4f5a111e, + 0xfd235144, + 0xf4590170, + 0x3f404134, + 0x26083546, + 0x06026303, + 0x89005e00, + 0x822d200f, + 0x0062210f, + 0x00256a82, + 0x02f4ff1c, + 0x206f827e, + 0x10b54524, + 0x07062222, + 0x2325d982, + 0x23152135, + 0x08dc8915, + 0x11ca0139, + 0x070f0b24, + 0x32180a16, + 0x1d4d5421, + 0xb2541536, + 0x18e5eb01, + 0x69432239, + 0x0c52343d, + 0x03430406, + 0x323b1905, + 0x0505434a, + 0x4a02befe, + 0x05c34646, + 0x4a5c2b05, + 0x8727594c, + 0x82d4207d, + 0x0326228d, + 0xd39318b4, + 0x0001210a, + 0x21066944, + 0x476d1e00, + 0x1632210a, + 0x2206e272, + 0x18152107, + 0x08094da2, + 0x5452013e, + 0x834a4981, + 0x1c5e3b55, + 0x29441a2d, + 0x010b6d57, + 0x05ecfe13, + 0x4a2f5d6c, + 0x62272e1f, + 0x6f984d0c, + 0x314e976f, + 0x221c3620, + 0x7c47686f, + 0x3422287c, + 0xffff322d, + 0xf4ff2a00, + 0x9c02ef01, + 0x1420f782, + 0x78070741, + 0xff200b75, + 0x230cad75, + 0x12000300, + 0xf52c9f82, + 0x0b002d03, + 0x1b001700, + 0x22130000, + 0x091a4718, + 0x0b8a3320, + 0x3311032c, + 0x1a133f11, + 0x1914131a, + 0x07867519, + 0x0253822b, + 0x16151ccb, + 0x15161b1b, + 0x2907871c, + 0x900235fd, + 0xffff70fd, + 0x87821f00, + 0x90028922, + 0x0b208782, + 0x022c6182, + 0xf4ff0600, + 0x90025b03, + 0x29002000, + 0x42110946, + 0x23220651, + 0x11461123, + 0x33252105, + 0x0805b24e, + 0x103e2326, + 0x0e110e1a, + 0x1d1d120e, + 0x13241410, + 0x485b3401, + 0x6e833d6d, + 0x1d10a0af, + 0x392c1310, + 0x5351a801, + 0x4f565657, + 0x430a2846, + 0x0234067e, + 0x57af5a4a, + 0x50276b64, + 0x3a3e463e, + 0x5a000200, + 0x75030000, + 0x13227d82, + 0xcf431c00, + 0x82212005, + 0x217589cf, + 0x71881121, + 0x01535a24, + 0x66855427, + 0xd9feb024, + 0x61857b01, + 0xfe900225, + 0x861301ed, + 0x3501245c, + 0x8444cbfe, + 0x01002158, + 0x02204f83, + 0x16205983, + 0x0887a718, + 0x38054442, + 0x35231515, + 0x22232634, + 0xb2ce1107, + 0x18e5eb01, + 0x796b1c3b, + 0x384d4d52, + 0x062b422f, + 0xc36e602a, + 0x0a3f4ac3, + 0xffffbefe, + 0x02279d83, + 0x02670342, + 0x42bb0326, + 0x4322062d, + 0xa7470400, + 0x47178308, + 0x3b2205a7, + 0x17844c01, + 0xf4ff0526, + 0x45030202, + 0xc4202f82, + 0x4b222f84, + 0x07820101, + 0x5a000126, + 0x2b0244ff, + 0x0b25e582, + 0x35050000, + 0x06d94523, + 0x0107232a, + 0x0153c51f, + 0x08bb532b, + 0x2108d745, + 0x2d45bc70, + 0x023a2306, + 0x134100bc, + 0x9a7c1806, + 0x4a232007, + 0x25081139, + 0x548a8aa6, + 0x484eeaea, + 0x6e7e3d6d, + 0x51534a54, + 0x01435853, + 0x7d7d44fb, + 0x4c228844, + 0x425d693f, + 0x353e453b, + 0x4b7b0000, + 0x21531809, + 0x7b4c2025, + 0x28080b46, + 0x010a6852, + 0x52680a88, + 0xfe056b56, + 0x0c6b0574, + 0x6d6d9a50, + 0x964e4e96, + 0x509a6d6d, + 0x69726202, + 0xe4fd7269, + 0x837a7a83, + 0x36e98300, + 0x02310200, + 0x0018009c, + 0x33033300, + 0x17161613, + 0x37363633, + 0x4a363637, + 0x073b0804, + 0x59d2d203, + 0x131c1169, + 0x10191004, + 0x343a1440, + 0x0511151b, + 0x1a16080d, + 0x1802930b, + 0x2b08a5a8, + 0x094249e3, + 0x2504024d, + 0x00fefd25, + 0x2505fb48, + 0x3c03dd01, + 0x55820700, + 0x37211134, + 0x11210733, + 0x0f2d015a, + 0xd9fe0947, + 0xf2ac9002, + 0x2382b6fd, + 0x28822120, + 0x9002ea24, + 0xeb410d00, + 0x4b372005, + 0x15360567, + 0x4f701123, + 0xfe7a014f, + 0x019595d9, + 0x0104372b, + 0x3be4462a, + 0x2f82d5fe, + 0x44ff0624, + 0xa9823503, + 0xb94a3420, + 0x15332427, + 0x4a352307, + 0x9f242cbe, + 0x20490940, + 0x2323c14a, + 0xbcd132eb, + 0x8208c44a, + 0xff2a249b, + 0x82020244, + 0x002e269b, + 0x26351700, + 0x06504626, + 0x0fcb5d18, + 0x36270722, + 0x4a06ac75, + 0x072507c6, + 0x623af107, + 0x1bc74a2b, + 0x37573228, + 0x05b2bc08, + 0xcb4a2c2d, + 0x5238241a, + 0x47b30732, + 0x022105e9, + 0x05d5465a, + 0x4114714a, + 0x764a0810, + 0x46b42412, + 0x4a214909, + 0xea201279, + 0x0020e986, + 0x20069d43, + 0x205f82ca, + 0x05b1411b, + 0x33112122, + 0x28132c4c, + 0x1a01c6e2, + 0x2c1c5c71, + 0x08d54a2f, + 0x57141c24, + 0x5b825ae2, + 0xfe464a22, + 0x8613d64a, + 0x487b20b9, + 0x598209a3, + 0x2c05f84c, + 0x11211123, + 0x3101535a, + 0x49094954, + 0xf5ae184b, + 0x83b72008, + 0xfe352293, + 0x249383cb, + 0x0244ff34, + 0x2193821b, + 0x54180020, + 0x4e1808eb, + 0x06750963, + 0x06172a08, + 0x01070706, + 0x406f482b, + 0x75b0184c, + 0x4e202912, + 0xb2bc0831, + 0x6390550a, + 0x1079b018, + 0x082f2524, + 0x0082ffb3, + 0xdd206a82, + 0x22083d7d, + 0x85ffff01, + 0x1600290f, + 0x35330000, + 0x33373523, + 0x0cc3aa18, + 0x23153328, + 0x588bc415, + 0xaa18af1d, + 0xaf280ac9, + 0x37f08b75, + 0xb9660103, + 0x07cdaa18, + 0xf03a9a22, + 0x00214482, + 0x20bf820f, + 0x20f9820e, + 0x63ab181e, + 0x05ae4111, + 0x08f8a218, + 0x0e68ab18, + 0x09449724, + 0xab182748, + 0xf824176b, + 0xb1bcd132, + 0x076eab18, + 0x00010023, + 0x20658243, + 0x20658245, + 0x16734a19, + 0x784a6a84, + 0x0949220e, + 0x0f7b4a47, + 0x5682b720, + 0x2105dd43, + 0x4d821302, + 0xb3821420, + 0x11331123, + 0x05c34836, + 0x0806a245, + 0x11070621, + 0x3918535a, + 0x396b4b26, + 0x24505552, + 0x90021437, + 0x0604fefe, + 0xc24f5e29, + 0x063e53c2, + 0x7fb7fe04, + 0x062a12bd, + 0x1e030000, + 0x26024503, + 0x8345b703, + 0x6e922006, + 0x17830a6d, + 0x1786b120, + 0x17841020, + 0x2f820820, + 0x90020526, + 0x4e000602, + 0x830a9f48, + 0x86b62027, + 0x841c2027, + 0xff3a2a17, + 0x025e02f4, + 0x0106029c, + 0x260f8403, + 0x0200005a, + 0x4d1c0336, + 0x452008ab, + 0x20060346, + 0x22278234, + 0x822d0365, + 0x84bf2017, + 0x824f203f, + 0x0cb97f17, + 0x84e30321, + 0x052b463f, + 0x2b461820, + 0x00452208, + 0x20178afc, + 0x2017886c, + 0x82178655, + 0xb1012357, + 0xa782f201, + 0x00328f82, + 0xff350002, + 0x02f001f4, + 0x000e00da, + 0x1300002c, + 0x99471614, + 0x06222506, + 0x13141407, + 0x2905d476, + 0x37363637, + 0x07060617, + 0x6818030e, + 0x5f0809bb, + 0x384a4c84, + 0x233f4449, + 0x6d96254c, + 0x71502b78, + 0x16262945, + 0x1f321310, + 0x2039563a, + 0x2e572006, + 0x613a6d56, + 0x756a1701, + 0x594b5267, + 0x13093226, + 0x93a0d3fe, + 0x2853987b, + 0x0a0b060a, + 0x050d0d4b, + 0x572d1509, + 0x7829284b, + 0x3e724d6b, + 0x52000300, + 0xd5010000, + 0x0f00e601, + 0x21001800, + 0x11330000, + 0x4405417a, + 0x23210694, + 0x0fb41803, + 0x522f0810, + 0x2b6350bb, + 0x6c3d2926, + 0x3d5c7254, + 0x62383334, + 0x3e3b3c69, + 0xe601643e, + 0x35284239, + 0x360a030b, + 0x01434835, + 0x2222271a, + 0x2d90fe26, + 0x182a2528, + 0x350f515d, + 0x11231521, + 0xdd2f0152, + 0xfe43e601, + 0x0200005d, + 0x54ff1300, + 0x8182fe01, + 0x81820620, + 0x82370021, + 0x113322ed, + 0x08f75023, + 0xf5503720, + 0xb7280806, + 0xe2111b08, + 0x0947679b, + 0x16170e18, + 0x2e011a09, + 0xff470847, + 0x011a5a48, + 0xac5dfe60, + 0x230834bb, + 0xfed74e53, + 0xacbb345d, + 0x2905695b, + 0x01ca01f4, + 0x000602f2, + 0xde820020, + 0x820d0021, + 0x019c2466, + 0x822900f2, + 0x273725df, + 0x22232626, + 0x2605e650, + 0x35331717, + 0x46331533, + 0x4a0807e0, + 0x07062223, + 0x27231707, + 0x35231523, + 0x990d0723, + 0x14221027, + 0x0d0f060a, + 0x193f2810, + 0x4d494d2c, + 0x283e1a2c, + 0x060e0c10, + 0x1123130a, + 0x7a599926, + 0x7a504950, + 0x182a61ff, + 0x2a054d02, + 0xc8c86c3e, + 0x052a3e6c, + 0x2a18024d, + 0x82dbff61, + 0x01002700, + 0xf4ff2500, + 0x7782a101, + 0x56182b20, + 0x64180c07, + 0x42082063, + 0x2b5b32dd, + 0x25472223, + 0x3b414732, + 0x3a3b3743, + 0x3d2a2c39, + 0x5423231d, + 0x31503034, + 0x3b2a262a, + 0x1b0c5937, + 0x151c3523, + 0x2929282f, + 0x2524293b, + 0x36151625, + 0x3a1c1d19, + 0x0f3a232d, + 0x35390b04, + 0x8324412d, + 0x825220f5, + 0x01e32404, + 0x821700e6, + 0x112008f5, + 0x06141533, + 0x36363307, + 0x11331337, + 0x36343523, + 0x06062337, + 0x50520307, + 0x0e040305, + 0x4db80d25, + 0x0d3c0883, + 0x01b90d26, + 0x5d27cae6, + 0x163b172f, + 0x1afe1501, + 0x2f5e27ca, + 0xfe163c16, + 0x00ffffea, + 0x022d4d84, + 0x042602d6, + 0x00000005, + 0x01490707, + 0x20e1821d, + 0x20178401, + 0x86e382e5, + 0x08054665, + 0x06222331, + 0x23130707, + 0x52152327, + 0x14305e52, + 0x411a2c26, + 0x2037053a, + 0x5aa52914, + 0xe6016087, + 0x2d2c6cc8, + 0x024d050f, + 0xff602c16, + 0x82dbdb00, + 0x0a0025ac, + 0xc101f4ff, + 0x08b34518, + 0x50063847, + 0x29080bd1, + 0x140d3606, + 0x0a05100b, + 0x07201a07, + 0x0109120a, + 0x0797532b, + 0x0c150811, + 0x014c0404, + 0x4f363103, + 0x1afe4f9d, + 0x8743a301, + 0x7542a243, + 0x27022105, + 0x23204d82, + 0xb018ff84, + 0xff8409b0, + 0x31050041, + 0x26272307, + 0x1e232726, + 0x52151502, + 0x170b5f5f, + 0x0382040a, + 0x4b5e5d2c, + 0x04020503, + 0x5c0b180a, + 0x05825e37, + 0x02042108, + 0xe6010304, + 0x1d3b1ee4, + 0xe41e3b1d, + 0x16da1afe, + 0x1c193e3b, + 0xe1e11b3c, + 0x191c3c1b, + 0xda163b3e, + 0x5220bb83, + 0xe0200482, + 0x854f6d82, + 0x33152305, + 0x67823335, + 0xea2ffc83, + 0x01ea5252, + 0xfec5c5e6, + 0xffd8d81a, + 0x822e00ff, + 0x01f027e3, + 0x000602f2, + 0x6218002a, + 0x378208ff, + 0x21051d49, + 0x01822311, + 0x85015226, + 0xe601e152, + 0xfe22ca83, + 0x3382005d, + 0x33ff5224, + 0x3384fb01, + 0x42002b21, + 0xaf2007df, + 0x1e200f84, + 0x1a204384, + 0xb2204882, + 0x232e4387, + 0x23152135, + 0x01a3bd11, + 0xa301a398, + 0x41854343, + 0x2fff0c26, + 0xe601c701, + 0x34207582, + 0x032f3182, + 0x33ff2f00, + 0xc802af02, + 0x30002300, + 0x18003d00, + 0x2909bf63, + 0x33363634, + 0x27171632, + 0x6f183335, + 0x032d1047, + 0x11373632, + 0x22232626, + 0x16141506, + 0x05454c21, + 0x06226808, + 0x16161107, + 0x14024701, + 0x65531d31, + 0x1d315433, + 0x5002162f, + 0x1b371702, + 0x55335b56, + 0x18311732, + 0x26169e02, + 0x152b1414, + 0x013e4130, + 0x35403325, + 0x172a143b, + 0x9ccd2c16, + 0x85150f49, + 0x3e734f79, + 0xb1480f14, + 0x14114ab1, + 0x76527187, + 0x4810133e, + 0x1006019c, + 0x12300113, + 0x5753670f, + 0x505a6763, + 0xfe140e63, + 0x830e13cf, + 0x820e20f5, + 0x84b020e5, + 0x843320c3, + 0xff5224f5, + 0x82170254, + 0x086d51f5, + 0x82113321, + 0x07153a01, + 0x8afec801, + 0x4752da52, + 0x01acac08, + 0x015dfee6, + 0x345dfea3, + 0x000100bb, + 0x203f823b, + 0x2a2f82ae, + 0x21000013, + 0x23060635, + 0x82352622, + 0x161422e6, + 0x3ed88233, + 0x01113335, + 0x2026195c, + 0x3d52665c, + 0x15241643, + 0x0505c252, + 0x85855b4e, + 0x04053036, + 0x421afee2, + 0x9b20064d, + 0x5108df41, + 0x33270663, + 0xab525211, + 0x8751ac4f, + 0x846b8267, + 0x2099822b, + 0x512b82e2, + 0x30851365, + 0x47084722, + 0x9f82338a, + 0x0000ac25, + 0x821a0002, + 0x842a2004, + 0x001425d1, + 0x23113300, + 0x8d459e82, + 0x23230805, + 0x35323327, + 0x23232634, + 0x51feacc6, + 0x576a6a57, + 0x3c794951, + 0xa301493d, + 0x5048b343, + 0x59424a51, + 0x45002a2e, + 0x022105cb, + 0x233f8250, + 0x0012000a, + 0x09a99018, + 0x06141522, + 0x05203f88, + 0x5231b882, + 0x6b564552, + 0x3c45566b, + 0x3c3e3b79, + 0x01525a01, + 0x204488e6, + 0x839482f3, + 0x52002584, + 0xc1010000, + 0x89824986, + 0x8e153321, + 0x52522287, + 0x2143835c, + 0x4382535c, + 0x408a5320, + 0x00273682, + 0x01f4ff18, + 0x51f2019a, + 0xcc820e4f, + 0x08104f51, + 0x522eb73a, + 0x3b17221f, + 0x04544324, + 0x4f09d5d7, + 0x1535243a, + 0x364b1927, + 0x3b3d643d, + 0x1d210c67, + 0x541a1432, + 0x4b4c3b55, + 0x17321219, + 0x57723723, + 0x00387155, + 0x52000200, + 0xb402f4ff, + 0x2714815d, + 0x27262622, + 0x11231523, + 0x6e50ae82, + 0x3cde390a, + 0x3b3c4545, + 0x393f4949, + 0x69063a5c, + 0x0c6a5252, + 0x5f3a5276, + 0x385f3939, + 0x07307b18, + 0x6535442f, + 0xe601d547, + 0x3c6f65c8, + 0x72505272, + 0x2065833c, + 0x056d4220, + 0x000f002c, + 0x21000018, + 0x07232335, + 0x46513723, + 0x33272108, + 0x08074651, + 0x015a5e22, + 0x2e945d86, + 0x36573241, + 0x4c4c9eac, + 0xc0414139, + 0x430ecbc0, + 0x1b3f363a, + 0xaafc1afe, + 0x2d2b2b27, + 0x25089146, + 0x06020d03, + 0xc1432e01, + 0x02ca2208, + 0x210f82af, + 0x68820032, + 0xff080029, + 0x02f30127, + 0x512a00c8, + 0x26210f43, + 0x07445123, + 0x85183720, + 0x44080d05, + 0x01020e14, + 0x0b1f1327, + 0x0b150810, + 0x1b213823, + 0x3b222836, + 0x4a4a5224, + 0x04b6b652, + 0x57314c22, + 0x4c351c5d, + 0x3e0508d9, + 0x87350503, + 0x2962567c, + 0xc5fe2523, + 0x052b3b02, + 0x5d305d5d, + 0x8b2d2161, + 0x58967195, + 0x06d74525, + 0x0e038525, + 0x82042602, + 0x07002788, + 0xf6003d07, + 0x01820100, + 0xf4ff2e24, + 0xc541af01, + 0x18052005, + 0x5109b549, + 0x3322074f, + 0xaa552315, + 0x17350805, + 0x12010606, + 0x403b6841, + 0x46303f6a, + 0x32162719, + 0x0a523c20, + 0x5305e4e2, + 0x163c2344, + 0x0c502121, + 0x56557138, + 0x17223872, + 0x4d191334, + 0x55543b4a, + 0x1d34131d, + 0x20778221, + 0x255f821c, + 0x02f20183, + 0x11410006, + 0x82452005, + 0x02b3227e, + 0x300f82b6, + 0xff000024, + 0x00eaffff, + 0x020e0100, + 0x010602af, + 0x22198254, + 0x82110003, + 0x02f02205, + 0x254d51ae, + 0x131b1b27, + 0x6f1a1a14, + 0x27078513, + 0x4c02527f, + 0x1c15151c, + 0xfd21038b, + 0xa38418b4, + 0xb2002109, + 0x25207784, + 0x022c6182, + 0xf4ff0c00, + 0xe601b502, + 0x26001e00, + 0x0c23ae18, + 0x37363623, + 0x07054321, + 0x22054c51, + 0x43250606, + 0x22080695, + 0x0a150d38, + 0x070a050f, + 0x0b092517, + 0x2401040b, + 0x6b6b5640, + 0x04899356, + 0x460d0c0b, + 0x7a374a01, + 0x46373e3c, + 0x303905a2, + 0x529e4b37, + 0x515048b3, + 0x43a3014a, + 0x4a4c478f, + 0x2a2e594e, + 0x00020000, + 0x20048252, + 0x237582cd, + 0x001a0012, + 0x43056f43, + 0x232309fb, + 0x87152335, + 0x52523569, + 0x574052d5, + 0x92576b6b, + 0x382701d5, + 0x383e3b79, + 0xc5c5e601, + 0xd8225184, + 0x4c8242d8, + 0x00ffff2d, + 0x01000008, + 0x02c802d7, + 0x184f0106, + 0x26087f83, + 0x020e03e5, + 0x82070426, + 0x070726e1, + 0x0014013d, + 0x06f94101, + 0x1784e320, + 0x2205d147, + 0x841d013a, + 0xff0c2617, + 0x02c7012f, + 0x202f82d5, + 0x222f8410, + 0x82f30049, + 0x00012607, + 0x0154ff52, + 0x050145dc, + 0x23271722, + 0x29060145, + 0x03f30723, + 0x52e6529e, + 0x6d45099a, + 0x441a2008, + 0x162308cb, + 0x86006e02, + 0x0c0351d1, + 0x250b9144, + 0x529898b2, + 0xd444bcbc, + 0x7a482b05, + 0x01483e3c, + 0x747443b7, + 0xd7448443, + 0x0b334708, + 0x84030221, + 0x820c2089, + 0x01f222e1, + 0x13a750f2, + 0x17162108, + 0x22232607, + 0xbb030706, + 0x0b5c55af, + 0x09040b18, + 0x14300a13, + 0x150f3237, + 0x0f0a100c, + 0x6d0c1a16, + 0x09ddb018, + 0x4448942a, + 0x064a0504, + 0xa4fe2524, + 0x00215082, + 0x22048252, + 0x5092028f, + 0x333505a7, + 0x23073337, + 0x10ea5211, + 0x01e20943, + 0xfeeface6, + 0x0001005d, + 0x2521821c, + 0x00e60194, + 0xe94d000d, + 0x21352505, + 0x33152315, + 0x652f0382, + 0x2f014949, + 0xcf8686dd, + 0x43dc0536, + 0x82cf3b99, + 0xff0d242b, + 0x82bb0254, + 0x4a2e20a3, + 0x33242373, + 0x35230715, + 0x2426784a, + 0x47084771, + 0x197b4a29, + 0xbb34bc24, + 0x0082dbac, + 0x0025aa82, + 0x0154ff25, + 0x248382a1, + 0x1700002d, + 0x08895027, + 0x0e546e18, + 0x20068850, + 0x09505b16, + 0xba070726, + 0x23482604, + 0x271b824a, + 0xac094159, + 0x1c1c04a2, + 0x2b1a854a, + 0xa30a4b3a, + 0x52000100, + 0x050254ff, + 0x1c208382, + 0x5006d742, + 0x23250725, + 0x07070622, + 0x4af88817, + 0x7a241024, + 0x2b46094b, + 0x200e274a, + 0x83db84bd, + 0x001a24d9, + 0x82590200, + 0x47192055, + 0x578c0827, + 0x2723133d, + 0xacc61523, + 0x14315dfe, + 0x101a2b26, + 0x0a060f0d, + 0x29132013, + 0x5f875ba5, + 0x4a43a301, + 0x53201279, + 0x2720a582, + 0x2408b147, + 0x33353315, + 0x2a9a8511, + 0x53152335, + 0x4652ea52, + 0x49484709, + 0x5d2005c5, + 0xd8218382, + 0x248383d8, + 0x0154ff2e, + 0x208382af, + 0x055d411d, + 0x0dfb4018, + 0x09b07018, + 0xea070725, + 0x18685004, + 0x2b127bb9, + 0xac094335, + 0x6a820ea4, + 0x223c7252, + 0x0b7db918, + 0xa30c2f2a, + 0x0c000100, + 0xc70133ff, + 0x0f209182, + 0x35205d82, + 0x08098c53, + 0x03331322, + 0x55b7c315, + 0x0b180b5b, + 0x0a180b04, + 0xcdb2515b, + 0xfee601cd, + 0x224724f7, + 0x01244722, + 0xcd1afe09, + 0x3d879b83, + 0x3d831620, + 0x37352322, + 0x820ace53, + 0x15332841, + 0x94c31523, + 0x8aa1304e, + 0x789c2847, + 0x36cdcd8e, + 0x8aab0105, + 0x3b55224b, + 0x208982cd, + 0x20e7820e, + 0x248982ce, + 0x3300001e, + 0x89b31837, + 0x0e95500d, + 0x939f0e22, + 0x0b8eb318, + 0x08497330, + 0x0d472946, + 0x0d040e1a, + 0xfe420c18, + 0xb3186be8, + 0xb2230791, + 0x18acbb34, + 0x820894b3, + 0x823b2061, + 0x82f52061, + 0x49182061, + 0x65841599, + 0x220d9e49, + 0x49460947, + 0x5d200ca1, + 0x2006f94d, + 0x2afc8252, + 0x02c802d7, + 0x00230006, + 0x4dffff00, + 0x022505f9, + 0x042602d5, + 0x05cb4403, + 0x84550121, + 0xff522417, + 0x84d800f4, + 0x84272027, + 0xff34240f, + 0x83b101f4, + 0xfd032127, + 0x06202786, + 0x3a291784, + 0xeb02f4ff, + 0x0602f201, + 0x44fd8201, + 0xca200689, + 0x02204f84, + 0x08202786, + 0x25202784, + 0xc2203f82, + 0xe4202784, + 0x22087345, + 0x4d9302e3, + 0x4420082d, + 0x20065b45, + 0x2227822e, + 0x82af02f0, + 0x840b2017, + 0xe77f183f, + 0x08154c07, + 0x9b500220, + 0x05834505, + 0x83459220, + 0x00442208, + 0x855784f3, + 0x88f92017, + 0x83542017, + 0x02002317, + 0x57822f00, + 0xda02e226, + 0x33002600, + 0x2908ff58, + 0x35022e37, + 0x37363634, + 0x4350023e, + 0x15022605, + 0x17161614, + 0x2006821e, + 0xe94b1806, + 0x026c080e, + 0x6a3b6137, + 0x283f2257, + 0x28486939, + 0x110f1c2d, + 0x461f3615, + 0x40282555, + 0x28452d25, + 0x26c96336, + 0x4a42233e, + 0x5a4e2e3d, + 0x4261340c, + 0x181b6e5c, + 0x321c312d, + 0x0409142f, + 0x4b070906, + 0x08040d0b, + 0x11171309, + 0x1f1a231d, + 0x443b5442, + 0x2dda3b6a, + 0x495d2643, + 0x13224e3c, + 0x04000062, + 0xf4ff3b00, + 0x8a026f03, + 0x3a002a00, + 0x4a004600, + 0x25055547, + 0x35363227, + 0x8f823311, + 0x82331721, + 0x34352ea6, + 0x17163233, + 0x15062217, + 0x26262311, + 0x05914d27, + 0x01061422, + 0x22097848, + 0x82141516, + 0x07754cb5, + 0x073fc982, + 0x5b153335, + 0x07080809, + 0x2e5c1111, + 0x04392b58, + 0x4e020505, + 0x07070a08, + 0x2d5c1211, + 0x82382c58, + 0x2401260f, + 0x462a5202, + 0x2702842a, + 0x2a462929, + 0x272f2f27, + 0x53080382, + 0x020cfd58, + 0x18124101, + 0xcc671c02, + 0x613f8168, + 0x639e2f58, + 0x11410202, + 0x67e4fd18, + 0x3f8068cd, + 0x9f305761, + 0x20013131, + 0x34334826, + 0x47262647, + 0x26483334, + 0x32313937, + 0x31323939, + 0x3232b539, + 0x00030000, + 0x02f4ff20, + 0x009c0252, + 0x0035000b, + 0x13000041, + 0x0a6b4318, + 0x07097d18, + 0x20072d4a, + 0x29ba8432, + 0x17161607, + 0x33373636, + 0x09830606, + 0xe4820720, + 0x7b4cce82, + 0x080b8405, + 0x0e11bd7d, + 0x211d432d, + 0x3b2b2c25, + 0x3a25325b, + 0x26171422, + 0x443d2d45, + 0x2025432c, + 0x2f1e2e58, + 0x39134d0f, + 0x1b3e2227, + 0x284d2216, + 0x4bb25e25, + 0x1c3f2236, + 0x22235930, + 0x1b020230, + 0x411e1e3a, + 0x362b1d2b, + 0x522fc9fd, + 0x36442c35, + 0x244d2917, + 0x4829462c, + 0x38442b3a, + 0x275f321b, + 0x40386129, + 0x20173477, + 0x250a4408, + 0xbb29221c, + 0x191c4237, + 0x1c35642a, + 0x0002003d, + 0x01f4ff2c, + 0x828a02c5, + 0x001723c7, + 0x955a1700, + 0x4127200a, + 0x35080a6a, + 0x6d6d60f9, + 0x6d6d5f60, + 0x4444385f, + 0x45453838, + 0xa1a0ad0c, + 0xa0a1a8a8, + 0x8c7f42ad, + 0x8c7b7b8c, + 0x01007f8c, + 0x00004f00, + 0x7e02b701, + 0x00000c00, + 0x11333533, + 0xed833523, + 0x15331134, + 0x2c74924f, + 0x843f1a41, + 0x35d60144, + 0xfd101708, + 0x288244c6, + 0x82240021, + 0x82c42004, + 0x831b2077, + 0x104d182d, + 0x08125708, + 0x07063108, + 0x33333636, + 0x86602815, + 0x283d3c46, + 0x282f1c44, + 0x66593e5b, + 0x1a4c7543, + 0x31b91938, + 0x33759160, + 0x202d4637, + 0x67352c2f, + 0x877b3c55, + 0x4704024f, + 0x1a208182, + 0xbe20cb82, + 0x2a205382, + 0x230e6d51, + 0x32352326, + 0x0e916118, + 0x0809eb46, + 0x4cec0647, + 0x1d2a2066, + 0x4a3a384e, + 0x444c5927, + 0x333b224f, + 0x2c1d4328, + 0x53385a25, + 0x3a34406c, + 0x0c5f3850, + 0x1e362337, + 0x2635402e, + 0x203f2039, + 0x362f2136, + 0x23341d24, + 0x3a4d552d, + 0x0d04144a, + 0x52384253, + 0x0002002c, + 0x20cf8211, + 0x26fd82d5, + 0x00140009, + 0x51333700, + 0x2c080760, + 0x35213513, + 0x33113301, + 0x68152315, + 0x040104c8, + 0x330e1a0c, + 0x1101e1fe, + 0xf257575c, + 0x19481ab9, + 0xfe172c17, + 0x0136b034, + 0x4274fe98, + 0x214282b0, + 0xc3821900, + 0x4782c120, + 0xc38e2020, + 0x06222328, + 0x21132707, + 0x07542315, + 0x82162005, + 0x063708c0, + 0x21644cea, + 0x384c1d28, + 0x3e4a513b, + 0x2c1d2f21, + 0xf73f0115, + 0x1d2e1711, + 0x3d365937, + 0x21360c62, + 0x4f2d1c36, + 0x144a4243, + 0x33011c13, + 0x0e0cbd47, + 0x4545582b, + 0x82003261, + 0x823020ad, + 0x02c92665, + 0x000b008a, + 0x82748228, + 0x1616275a, + 0x35363233, + 0x55182634, + 0x17230a9f, + 0x82262607, + 0x54062075, + 0x48080978, + 0x481f0501, + 0x3d47081e, + 0x343b402f, + 0x453a643e, + 0x4b343f6f, + 0x38132e1b, + 0x2f4a2d1e, + 0x27501e02, + 0x55346353, + 0x2c284801, + 0x3f4d625d, + 0xacfe493e, + 0x80668944, + 0x1d27479c, + 0x331b1733, + 0x2b256577, + 0x5c3d6263, + 0x00010034, + 0x2073822c, + 0x08e382c7, + 0x00000d2a, + 0x37023e33, + 0x15213521, + 0xb107030e, + 0x3f4d2706, + 0x9b01c2fe, + 0x14284839, + 0xa9bf7804, + 0x48334757, + 0x5d9a8785, + 0x29000300, + 0xc820af82, + 0x1f20af82, + 0x39213b82, + 0x2d781800, + 0x37362207, + 0x06904d35, + 0x20066243, + 0x05db4415, + 0xc5180320, + 0x03200b99, + 0x6908d784, + 0x06062726, + 0xfa161415, + 0x23375e3c, + 0x36231e37, + 0x53335230, + 0x14281c61, + 0x3320321d, + 0x2320115d, + 0x3b2c353a, + 0x38054429, + 0x2e4f3045, + 0x0c4f3326, + 0x2a32502d, + 0x04103141, + 0x31324819, + 0x4a60294a, + 0x0f2f3b21, + 0x3d2c1004, + 0x2d4e2f2b, + 0x401d6801, + 0x38422f23, + 0x2332262f, + 0x313fc6fe, + 0x12263429, + 0x352c4619, + 0x02000045, + 0xa9822800, + 0x5941c020, + 0x43132007, + 0x232407df, + 0x22130622, + 0x1808085a, + 0x080c8c5a, + 0x1415164b, + 0x3b750606, + 0x1f47203b, + 0x2e3d4808, + 0x4d335841, + 0x37142e1a, + 0x2f4c2d1e, + 0x28501e01, + 0x55346352, + 0x39643f33, + 0xbd016e45, + 0x2d28493e, + 0xfd4d615d, + 0x341c27f8, + 0x78341c17, + 0x632c2666, + 0x345c3d62, + 0x80678844, + 0x0000479c, + 0x0ccd4303, + 0xcf432320, + 0x43372019, + 0xdb430ae7, + 0x48482d09, + 0x48483938, + 0x24241939, + 0x23231919, + 0x2f09e343, + 0x7d8a8982, + 0x82898a7d, + 0x201f23cd, + 0x1f202222, + 0x698b5882, + 0x18001521, + 0x21080b4c, + 0xcd833233, + 0x06220333, + 0x36361307, + 0x03263435, + 0x03373632, + 0x14150606, + 0x2e658816, + 0xdb11351f, + 0x38480505, + 0xdb113320, + 0x88480604, + 0x57023065, + 0xc8fe2926, + 0x8c253e1a, + 0x28e8fd7e, + 0x8238012b, + 0x838b2b0a, + 0x00020000, + 0x01f4ff37, + 0xa14402e3, + 0x44052006, + 0x012516a1, + 0x7272640d, + 0x23038364, + 0x3b48483b, + 0x20080382, + 0x9e9db00c, + 0x9d9eabab, + 0x8a7f44b0, + 0x8a7a7a8a, + 0x00007f8a, + 0x00320001, + 0x02f90000, + 0x0008007e, + 0x08a14400, + 0x2c75a72d, + 0x023f1a42, + 0x1708351a, + 0x8382fd10, + 0x82252025, + 0x44c02004, + 0x2b35209b, + 0x39458460, + 0x1b45283e, + 0x3d5b2a30, + 0x74426459, + 0x19381a4a, + 0x099b44b1, + 0x44332e21, + 0xff22089b, + 0x9b4400ff, + 0x06022906, + 0x00004f04, + 0x2200ffff, + 0xe6206382, + 0x06238982, + 0x83115004, + 0x06f7430f, + 0x51201f82, + 0x3d201f84, + 0xd620f582, + 0x06238382, + 0x820d5204, + 0x2c00212a, + 0xb9200482, + 0x2c103343, + 0x4c2506a7, + 0x01d0fe3e, + 0x2846388d, + 0x0b334313, + 0x00ffff23, + 0x21418837, + 0x61830e54, + 0x0f823420, + 0x5184cc20, + 0x000c5524, + 0x57410300, + 0x0023220c, + 0x17594100, + 0x410b2b42, + 0x3e2b0965, + 0x3d3e4949, + 0x193d4a4a, + 0x82192424, + 0x096d4103, + 0x88878228, + 0x87887c7c, + 0x2c42cb82, + 0x22698b08, + 0x8d1d0014, + 0x052b4269, + 0x22082a42, + 0x89161415, + 0x37222963, + 0x4d0cea13, + 0x1237233d, + 0x61880682, + 0x27570233, + 0x36c6fe29, + 0xfd7e8c4a, + 0x012a29e8, + 0x8b4a363b, + 0x08c74683, + 0xc7464a20, + 0x5e20081e, + 0x5d5e6f6f, + 0x3b5d6f6f, + 0x3b3b4141, + 0x970c4242, + 0x96969594, + 0x42979495, + 0x7a6e6d7c, + 0x7c6d6e7a, + 0x2008c746, + 0x1ac7463e, + 0x08359626, + 0x06fe1017, + 0x210ac746, + 0xc7460048, + 0x5f26081e, + 0x3b3b4685, + 0x2f1c4528, + 0x573e5b28, + 0x48714066, + 0xb019381a, + 0x647a4f31, + 0x2c44352e, + 0x352c2e20, + 0x66365366, + 0xc746436f, + 0x01aa2507, + 0x004a02be, + 0x084ec746, + 0x2337562f, + 0x422d1e36, + 0x21392636, + 0x21372140, + 0x1d24382f, + 0x572d2334, + 0x134d3a4d, + 0x43550d04, + 0x002d5438, + 0xff110002, + 0x02d501b6, + 0x0008003e, + 0x09c74613, + 0xc6460720, + 0x1b19210f, + 0x3807c546, + 0x451acba0, + 0xfe303219, + 0x0137a835, + 0x4262fea9, + 0x000100a8, + 0x01aaff19, + 0x464382c1, + 0x290840c3, + 0x34223756, + 0x43512c1c, + 0x14134b43, + 0x4738011c, + 0x2b0f0cc2, + 0x6346455a, + 0xffff0033, + 0xf4ff3100, + 0x8a02ca01, + 0x52040602, + 0x75820001, + 0xb9822c20, + 0x7582c720, + 0x00000d23, + 0x17554617, + 0xc3794a2b, + 0x334758ad, + 0x9c8b8749, + 0x4643835e, + 0x43820657, + 0x00005426, + 0x1e000200, + 0xc228b982, + 0x0b004a02, + 0x00002600, + 0x2311bd45, + 0x36363233, + 0x080cbc45, + 0x06141543, + 0x3f3a6c06, + 0x061f4b23, + 0x4431414a, + 0x20463060, + 0x2f3e3123, + 0x1f032f4a, + 0x61582a53, + 0x69355935, + 0x016f3e78, + 0x284f4375, + 0x5269672e, + 0x1b1ef3fd, + 0x73312e3a, + 0x6c2b2562, + 0x36603f64, + 0xa07a92a6, + 0x079b434e, + 0x7782cd20, + 0x64040623, + 0x09a74408, + 0xa7443e20, + 0xda012712, + 0x10170835, + 0x2583c2fd, + 0x04822920, + 0x4202bc21, + 0x30351f7b, + 0x3740805f, + 0x1c40283c, + 0x3d57282f, + 0x6d3c6258, + 0x19381a48, + 0x147b42a3, + 0x00ffff2e, + 0x01aaff1a, + 0x024a02be, + 0x00670406, + 0x29059744, + 0x02dd01b6, + 0x0406003e, + 0x0f850868, + 0xc101aa28, + 0x06023e02, + 0x1f846904, + 0xf4ff392b, + 0x8a02d201, + 0x52040600, + 0x07854109, + 0x8541b920, + 0x06a52310, + 0xa7444d26, + 0x29472605, + 0x7a4a0413, + 0x058541c2, + 0x5f9c8a22, + 0x2007c941, + 0x204384d0, + 0x20638454, + 0x22838226, + 0x824a02ca, + 0x086d2253, + 0x08db4300, + 0xdb439c20, + 0x07a34a26, + 0xaaacab30, + 0xacaaa7a7, + 0x918442ab, + 0x8f80808f, + 0xdb438491, + 0x43902008, + 0xe9261adb, + 0x10170834, + 0xdb43b4fd, + 0x009c250a, + 0x33000019, + 0x0fd26b18, + 0x06141523, + 0x05a24a07, + 0x4a929a21, + 0x8d390aa1, + 0x19381a73, + 0xcc8631b5, + 0x2c493954, + 0x352c2e20, + 0xcb61586a, + 0x4704026d, + 0x089f4a00, + 0xd7439c20, + 0x353f2149, + 0x39099f4a, + 0x3b273942, + 0x39213f20, + 0x24392f23, + 0x2c23341c, + 0x4e3c4f56, + 0x550e0413, + 0xd7433a44, + 0x23808205, + 0x009002d5, + 0x31299f4a, + 0x4619c8f6, + 0x18311819, + 0x36b52bfe, + 0x66fea501, + 0x4282b541, + 0x21069f4a, + 0xdb430090, + 0x059f4a40, + 0x47475435, + 0x1b13134e, + 0xbe463301, + 0x5d2c0e0d, + 0x35654848, + 0x43020000, + 0x9c2006db, + 0x2b2f9f4a, + 0x1e481f06, + 0x2f3d4807, + 0x3f333b40, + 0x220a9f4a, + 0x4a4b2d1d, + 0x2208069f, + 0x5a015633, + 0x6b652d28, + 0x4e434351, + 0x91489afe, + 0x469c816c, + 0x17331d26, + 0x6577341b, + 0x68672b25, + 0x4a36603f, + 0x9021089f, + 0x0f9f4a00, + 0x404e2536, + 0x9b01c2fe, + 0x1328483a, + 0xafc57d04, + 0x4a324659, + 0x609f8d88, + 0x26089f4a, + 0x001f009a, + 0x4a38002b, + 0x3521229f, + 0x06465b34, + 0x9e4a1620, + 0x35243013, + 0x53335230, + 0x14291b61, + 0x331f331d, + 0x4a43115d, + 0x3908099d, + 0x32272f4e, + 0x502d0c4f, + 0x33452c32, + 0x4a1a0410, + 0x2a4b3234, + 0x3d224c61, + 0x11040f30, + 0x2f2d412e, + 0x70012d4e, + 0x4430483d, + 0x3427303a, + 0x3fbdfe24, + 0x28372c31, + 0x2f4b1912, + 0x9b4a4535, + 0x06554108, + 0x2011dd44, + 0x10de4416, + 0x39069b4a, + 0x1f47223a, + 0x2e3f4906, + 0x4e355d41, + 0x3a152e1c, + 0x2f482a1f, + 0x29511d03, + 0x9b4a6252, + 0x6d432c05, + 0x4f42c701, + 0x6a652e29, + 0x4aeafd52, + 0x773b059b, + 0x682b2566, + 0x35604066, + 0x85698a45, + 0x000049a2, + 0xff410001, + 0x00b800f4, + 0x4a0b0072, + 0x7d280d97, + 0x19232319, + 0x0c232318, + 0x08186e18, + 0x2f242b82, + 0xc60056ff, + 0x12202b82, + 0x27262b82, + 0x06273636, + 0xf8492322, + 0x14433e0a, + 0x0201302b, + 0x23180206, + 0x25201924, + 0x1330aa46, + 0x1d01283f, + 0x341f1b1c, + 0xff61402d, + 0x256985ff, + 0x2702db01, + 0x78828204, + 0x06006922, + 0x61760783, + 0x2a17890a, + 0xff000083, + 0xff5e00ff, + 0x827303f4, + 0x0426326d, + 0x00001d82, + 0x01820427, + 0x0000006c, + 0x02820407, + 0x220782bb, + 0x82550002, + 0x02cc24b9, + 0x1805009e, + 0x2615e76e, + 0x53020b74, + 0x861c0b02, + 0x01c625c7, + 0xfe5e5e7a, + 0x0ae76e18, + 0x48243f83, + 0xf201cc00, + 0x17263f85, + 0x13331337, + 0xce8a0317, + 0x0b026726, + 0x29020b39, + 0x25083f86, + 0x7a015eb8, + 0x025e86fe, + 0x1b1c242c, + 0x1c1b2323, + 0x02000024, + 0xf4ff2600, + 0xaa027901, + 0x25001900, + 0x26370000, + 0x4042033e, + 0x08426605, + 0x17030e23, + 0x08518a07, + 0x1807a034, + 0x31202d2b, + 0x173b2130, + 0x3755202f, + 0x2f205b4c, + 0x22051b2c, + 0x19222219, + 0xc6232319, + 0x363c482f, + 0x39282036, + 0x242b1b1f, + 0x274a562f, + 0x423a383f, + 0x7f41d22a, + 0x00022609, + 0x013cff30, + 0x84b18283, + 0x8317206f, + 0x033e2659, + 0x0e163327, + 0x915d1803, + 0x20c18b09, + 0x226184d7, + 0x8449051a, + 0x31302877, + 0x30173a21, + 0x862b5520, + 0x87c420d1, + 0x27778662, + 0x2b1b1e38, + 0x38023023, + 0x2008e088, + 0x01500001, + 0x02a800af, + 0x000500b2, + 0x27271300, + 0x63070733, + 0x03580310, + 0xa7af0110, + 0xffa75c5c, + 0x211f83ff, + 0x1f825901, + 0x8b042626, + 0x07000000, + 0xb1200582, + 0x012a0782, + 0xac013900, + 0xb802bb00, + 0x37821100, + 0x3725ff84, + 0x15060617, + 0x05874c36, + 0x1e782108, + 0x18343621, + 0x06032626, + 0x011e2114, + 0x3c2b2fac, + 0x19271e58, + 0x1a012a39, + 0x001e1919, + 0x3f000100, + 0xc1227582, + 0x3d84bb02, + 0x36362724, + 0x64420635, + 0x17563b0b, + 0x05032526, + 0x171e2015, + 0x0137221d, + 0x391926af, + 0x181a012b, + 0x2c2f1e1a, + 0x9182573c, + 0x01217982, + 0x2279826c, + 0x828d0426, + 0x82072089, + 0x82918205, + 0x21538217, + 0x53827201, + 0x8e042622, + 0x8e211784, + 0x27178600, + 0xc1006fff, + 0x07027b00, + 0xfd211783, + 0x292983c0, + 0x72016fff, + 0x26007b00, + 0x29849104, + 0x29839120, + 0x2d3e9582, + 0xd9004200, + 0x0600b601, + 0x27370000, + 0x07173735, + 0x8888b517, + 0x42767624, + 0x1e9b3e9b, + 0x21829e9c, + 0x21823620, + 0x2187e220, + 0x37273731, + 0x23591517, + 0x89237676, + 0x9c9e1c42, + 0x823e9b1e, + 0x2143825b, + 0x21827701, + 0x93042622, + 0x93275b84, + 0x00009e00, + 0x8200ffff, + 0x80012139, + 0x94201784, + 0x94201784, + 0x51821783, + 0xdb002928, + 0x1a010f01, + 0x73820300, + 0x15333527, + 0x3fdbe629, + 0x0561483f, + 0xb701df24, + 0x17851801, + 0x29152127, + 0x39df8e01, + 0x222f8439, + 0x8af702df, + 0xce022117, + 0x05211788, + 0x21178ab3, + 0x17888a05, + 0x856f0821, + 0x15012917, + 0x6f083521, + 0x1801baf7, + 0x01214987, + 0x21318ac9, + 0x3182a001, + 0x2921a982, + 0x23618400, + 0x99040602, + 0x412ab984, + 0xb8000301, + 0x07028101, + 0x98828204, + 0x83820f20, + 0x8f002828, + 0x80010801, + 0xb3820b00, + 0x240afb42, + 0x43432d98, + 0x2803822d, + 0x3636428f, + 0x36364343, + 0x272e8242, + 0x82ff0c00, + 0xb9ffe801, + 0x1733c783, + 0x0c152135, + 0x377edc01, + 0x00ffff37, + 0x0138020c, + 0x826f02e8, + 0x00a02455, + 0x82b60200, + 0xff002b55, + 0xff330217, + 0x000d00bf, + 0xb14f0500, + 0x17373c08, + 0x1a010606, + 0x232b8e61, + 0x4d4d8129, + 0x2b232881, + 0x374ae98d, + 0x3d3c3227, + 0x7b372731, + 0x5024054d, + 0xdc020901, + 0x17223583, + 0x50182626, + 0xd6370a1e, + 0x3e46463e, + 0x39393a33, + 0xdd65b03a, + 0x64de8484, + 0x72dd5f18, + 0x825fdd72, + 0xff262469, + 0x86dd0050, + 0x0ce77833, + 0x2f845920, + 0x39823320, + 0x2d86b020, + 0xde641825, + 0x82dd8484, + 0xff5e2f33, + 0x02110168, + 0x000700c4, + 0x33111700, + 0x03822315, + 0x75b35e2a, + 0x5c039875, + 0x2f02fd2f, + 0x1f24e983, + 0xd10068ff, + 0x35232186, + 0x82231133, + 0x741f2a03, + 0x2f98b274, + 0xfc2ffe02, + 0x202183a4, + 0x20438622, + 0xc15b182b, + 0x05de480b, + 0x3320b882, + 0x22235582, + 0x5a141506, + 0x0c820a0d, + 0xe4321582, + 0x23093a3b, + 0x09233333, + 0x1b2d3b3a, + 0x1c061c28, + 0x04822020, + 0x1b282508, + 0x374d3898, + 0x301d3258, + 0x30013401, + 0x3758331c, + 0x2a2f384d, + 0x33542e31, + 0x04093331, + 0x33303409, + 0x2a312e54, + 0x01219987, + 0x8399820d, + 0x33352677, + 0x34353632, + 0xf1891826, + 0x07925a09, + 0x6f827683, + 0x06151722, + 0x23288386, + 0x1b291a1f, + 0x20201b05, + 0x292d0482, + 0x393c2c1a, + 0x32322409, + 0x3c390924, + 0x21668598, + 0x66823430, + 0x66846c82, + 0x33218a83, + 0x218a841c, + 0x8a83321d, + 0x0a28ef83, + 0x510160ff, + 0x0300c602, + 0x012def82, + 0x010a0133, + 0xf5fe3c0b, + 0xfc6603a0, + 0x261d839a, + 0x0006ff5c, + 0x84ee0296, + 0x3311291d, + 0xfa3a5c11, + 0x18fce803, + 0x0e201983, + 0x54203782, + 0x05203785, + 0x01263782, + 0x3bf5fe19, + 0x38850b01, + 0x89000221, + 0x00072337, + 0x39821300, + 0x3d840320, + 0x013a3a39, + 0xfecb0123, + 0x01e3fd35, + 0x0030fed0, + 0x013a0001, + 0x026801a4, + 0x820e00c8, + 0x272b0825, + 0x17372737, + 0x37173337, + 0x07170717, + 0x39288a27, + 0x09660f61, + 0x0f670931, + 0x47273861, + 0x5e1da401, + 0x6c192e28, + 0x282e186b, + 0x83561d5e, + 0xff362481, + 0x829001b0, + 0x820b203b, + 0x071330b9, + 0x33271735, + 0x27153707, + 0x8f05c013, + 0x8346058f, + 0x02502704, + 0x0547053b, + 0x0482a0a0, + 0x8bc5fd21, + 0x82152031, + 0x83372031, + 0x84048431, + 0x83172036, + 0x8417203b, + 0x843f883b, + 0x233d8243, + 0x07b1b107, + 0x09864785, + 0x0200002e, + 0xc0ff2d00, + 0xac02c401, + 0x44003400, + 0x270d8b54, + 0x3435042e, + 0x26263736, + 0x5c6b0582, + 0x14152909, + 0x1415041e, + 0x16160706, + 0x63080582, + 0x1e140306, + 0x36361702, + 0x022e3435, + 0xec060627, + 0x321f5935, + 0x28283a19, + 0x463f282d, + 0x2531283f, + 0x4b4d110f, + 0x281c4f2f, + 0x2a213618, + 0x473f2825, + 0x262f283f, + 0x4929100e, + 0x473e27a6, + 0x271f1d1f, + 0x1c1f463e, + 0x21264021, + 0x291c182d, + 0x1d251d1c, + 0x2e3e291e, + 0x1015402c, + 0x4e341a28, + 0x14351722, + 0x1b1a251a, + 0x2a251582, + 0x3c2f2e3e, + 0x2e158216, + 0x01243e27, + 0x202b219c, + 0x260e121d, + 0x822c2221, + 0x28102107, + 0x2930c182, + 0xd001b0ff, + 0x03009002, + 0x00000e00, + 0x11331105, + 0x0808dd54, + 0x0111332e, + 0x48ab547c, + 0x6d3f4272, + 0x02502c45, + 0x0120fde0, + 0x4b602e32, + 0xfe295d4f, + 0xffff0052, + 0x06ff5c00, + 0xee022b01, + 0xaa042600, + 0x07000000, + 0x95210582, + 0x22178300, + 0x82f4ff55, + 0x829e2051, + 0x84872017, + 0x01872217, + 0x26178404, + 0x02f4ff26, + 0x82aa02ff, + 0x84892017, + 0x01892217, + 0x82178486, + 0x7702212f, + 0x2f851784, + 0xfe008922, + 0x52202f88, + 0x87202f8a, + 0xb1822f83, + 0x5f821b20, + 0x17828120, + 0x27001b2a, + 0x27370000, + 0x07153327, + 0x47061b57, + 0x15200aea, + 0x360bea47, + 0x46050aab, + 0x1d291206, + 0x344a3537, + 0x365a232f, + 0x30206251, + 0x471b2030, + 0xfb3507ea, + 0x238b4153, + 0x2c253937, + 0x292b403d, + 0x2d44592d, + 0x41353642, + 0x0aeb472c, + 0x5e00013e, + 0x11010000, + 0x0500b102, + 0x11330000, + 0x11231533, + 0x0275b35e, + 0x7efd2fb1, + 0x1f000100, + 0xd120cd82, + 0x232b1b87, + 0x93113335, + 0x8202b274, + 0x824ffd2f, + 0xff5e221b, + 0x203782cc, + 0x2137837e, + 0x39831117, + 0x753e5e27, + 0xfdb20234, + 0x06ed437d, + 0xd100cc23, + 0x821d8502, + 0x11332b37, + 0x343e741f, + 0xfd83022f, + 0xe782004e, + 0x68ff5e2a, + 0xc4025b01, + 0x0b000700, + 0x2a09c944, + 0x23113327, + 0x6e6efd5e, + 0x442d2dca, + 0x2f2206d0, + 0x2d83fe02, + 0x2d821f20, + 0x2d881c20, + 0x8306d544, + 0x6e1f262d, + 0x2c60fd6e, + 0x06dc442c, + 0xcf822d84, + 0x82160121, + 0x83c42097, + 0x87132097, + 0x231282cf, + 0x81fe2fae, + 0x1f22b582, + 0x97821601, + 0xd1861d86, + 0x7f231d82, + 0x8452fe2f, + 0x016822d3, + 0x20218211, + 0x82958405, + 0x24d3823d, + 0xfeae0198, + 0x095b4581, + 0xd3871d86, + 0x012f9823, + 0x083a827f, + 0x00030024, + 0x02f5ff31, + 0x008d02b7, + 0x00230013, + 0x0500003f, + 0x35022e22, + 0x33023e34, + 0x15021e32, + 0x27020e14, + 0xb5183632, + 0x15240884, + 0x37161614, + 0x5709da5a, + 0x5b490669, + 0x74012909, + 0x335a7541, + 0x41755a33, + 0x57080787, + 0x4b4b7d4c, + 0x7e4b4c7d, + 0x537e4b4b, + 0x34315332, + 0x3b2a3055, + 0x29142318, + 0x4143371a, + 0x16302036, + 0x0b3e1c1e, + 0x4c7c572f, + 0x2e567a4c, + 0x4c7a562e, + 0x2f577c4c, + 0x5784492a, + 0x48488257, + 0x84575782, + 0x592f5e49, + 0x2e553a3e, + 0x14271821, + 0x423b4b15, + 0x2a13194d, + 0x04002118, + 0x2e20b58c, + 0x08595f18, + 0x272ab79a, + 0x16323311, + 0x23061415, + 0xc5451523, + 0x23232106, + 0x2c2baf9c, + 0x56563e8a, + 0x2d3e493e, + 0x9e2c3231, + 0x016a2da4, + 0x423d386b, + 0x26a57341, + 0x00202429, + 0x17319d82, + 0x90013f01, + 0x0f00c902, + 0x2d001f00, + 0x00003500, + 0x11105c13, + 0x200c5541, + 0x83938227, + 0x05c56b9d, + 0x35280c82, + 0x23232634, + 0x335633d3, + 0x34200282, + 0x30080583, + 0x28432a34, + 0x2a2a4328, + 0x43272743, + 0x2e204c1e, + 0x2e2e1114, + 0x2b1a2923, + 0x011c1712, + 0x3a59323f, + 0x3232583b, + 0x593a3b58, + 0x49282532, + 0x29492f2f, + 0x3c058329, + 0x1dcb3d28, + 0x061f1224, + 0x66464653, + 0x00120f22, + 0x01030002, + 0x0260026e, + 0x000700a4, + 0x2f95821b, + 0x21352311, + 0x33112315, + 0x17173311, + 0x33373733, + 0x33080f82, + 0x23072337, + 0x15172327, + 0x03016366, + 0x2f499464, + 0x2e1c041c, + 0x04073748, + 0x04492f49, + 0x016e0107, + 0xff363600, + 0x74360100, + 0xfe744e4e, + 0xc26989ca, + 0x008969c2, + 0x1b225782, + 0x57826201, + 0x2600ab24, + 0x57823a00, + 0x82078148, + 0x272721c5, + 0x23107145, + 0x16171716, + 0x3720ec83, + 0x8c3f7692, + 0x21173921, + 0x31192912, + 0x162f1615, + 0x1c2e3b26, + 0x101d1132, + 0x18171124, + 0x1d2e1317, + 0x8f783b22, + 0x62200890, + 0x1125161a, + 0x10142715, + 0x280b170a, + 0x16312723, + 0x120c2710, + 0x130f0f17, + 0x270d1709, + 0x0c382323, + 0x0222aa8e, + 0xa9821c00, + 0xab027e26, + 0x2e001300, + 0x8292a982, + 0x20055156, + 0x0b234636, + 0x32331628, + 0x06173736, + 0x7e8f1c06, + 0x543dc438, + 0x1e294328, + 0x0d200e30, + 0x3623131a, + 0x1e152434, + 0x3313210e, + 0x768d6e01, + 0x4d570c36, + 0x17284a33, + 0x0e0d2510, + 0x3c39383a, + 0x16221010, + 0x03000019, + 0x6e248b82, + 0xa4028602, + 0x1c228b82, + 0x8d952400, + 0xb9182120, + 0x23210dfd, + 0x2b839023, + 0x4e4a5c3e, + 0x1f22484e, + 0x1e5d2e2e, + 0x0139788f, + 0x4a494f36, + 0x343b2f54, + 0x00020069, + 0x0365ff33, + 0x0086021c, + 0x004e0040, + 0x051b6700, + 0x82023e21, + 0x151625e6, + 0x23060614, + 0x08246818, + 0x2605fd43, + 0x37331716, + 0x82060733, + 0x06a842f8, + 0x15020e24, + 0x08411614, + 0x32032407, + 0x18373736, + 0x08089567, + 0x6293017f, + 0x75425ea0, + 0x93655496, + 0x2e5c3e50, + 0x02053a28, + 0x33214019, + 0x47321b45, + 0x0d291a2c, + 0x27370b02, + 0x3d20541e, + 0x5b7b3f29, + 0x3a647d43, + 0x2e55874e, + 0x2b162252, + 0x2e15465f, + 0x1e0e1d19, + 0x1f392714, + 0xa0529b28, + 0x74a36574, + 0x6395533f, + 0x273c7757, + 0x49271d25, + 0x44522844, + 0x2819172a, + 0x5d3175c8, + 0x487e5141, + 0x588e6536, + 0x1a488961, + 0x191a3113, + 0x1f1c0c01, + 0x3613179f, + 0x2a30264e, + 0x24db8400, + 0x02dc02e8, + 0x20db82b0, + 0x83dba84d, + 0x21dc83cc, + 0xdb8c2223, + 0x8b322721, + 0x6f5908da, + 0x3d569056, + 0x594e8a6b, + 0x54354a86, + 0x0530262e, + 0x233f1602, + 0x2f19402c, + 0x27182a44, + 0x380c020d, + 0x23140d28, + 0x7d24361a, + 0x5a723d7a, + 0x49774734, + 0x171c4423, + 0x28394f25, + 0x1b0d1b31, + 0x1c352314, + 0x8b461823, + 0x69935a69, + 0x58824938, + 0x29397050, + 0x47281d24, + 0x404e263a, + 0x3dd98227, + 0x2b363cb2, + 0x866c3d55, + 0x4e7e5a30, + 0x1139755a, + 0x13162e11, + 0x17893aec, + 0x23483112, + 0xd7832828, + 0x00002330, + 0x8a02d301, + 0x1f001b00, + 0x37330000, + 0x03853523, + 0x33073323, + 0x23038237, + 0x33072315, + 0x23240382, + 0x13072337, + 0x5a2e1882, + 0x12575019, + 0x35175c55, + 0x35188517, + 0x0b835118, + 0x1835192d, + 0x84201984, + 0x39cc8412, + 0x82b73a94, + 0x943a2800, + 0xcccccc39, + 0x18940501, + 0x230b03db, + 0x00240006, + 0x03206d83, + 0xd4266d82, + 0x09000602, + 0xd3181100, + 0xe5180bd3, + 0x270807ab, + 0x189c18b4, + 0x040e180e, + 0xb9bf190d, + 0x3058ba5e, + 0x1a0130c5, + 0x532b4a4a, + 0xfe532b2b, + 0xfd0602bb, + 0x009292fa, + 0x5a000300, + 0xe5204582, + 0x10244582, + 0x22001900, + 0x1120b582, + 0x71066342, + 0x3108199a, + 0x5839aa5a, + 0x372d2d32, + 0x645d7741, + 0x3e3b444e, + 0x415a513e, + 0x5a45494d, + 0x38190602, + 0x0c3e252f, + 0x353d0a04, + 0x2b014a4d, + 0x2328282a, + 0x332b76fe, + 0x62822b2c, + 0xff340027, + 0x02d701f4, + 0xa1691812, + 0x1195460e, + 0x462a2c08, + 0x72434070, + 0x1a4f3248, + 0x2233162f, + 0x4c595d4c, + 0x2e193b27, + 0x3f0c5522, + 0x79555679, + 0x331a2842, + 0x5d6b1916, + 0x1a1d6c5e, + 0x7a262532, + 0x01210519, + 0x20bf82f7, + 0xa3e51808, + 0x808f3616, + 0x407d8d8e, + 0x5a5a5c3e, + 0x06023e5c, + 0x85808081, + 0x5b606441, + 0x05537464, + 0x82aa0121, + 0x830b2039, + 0x9d8b18f5, + 0x015a2d09, + 0xcecef346, + 0x420602fd, + 0x42ad3f96, + 0xa1202786, + 0x09202782, + 0x5a2b278b, + 0xcff44701, + 0x440602cf, + 0x82df40a3, + 0x20dd8323, + 0x7cdd82e3, + 0x15241417, + 0x32331614, + 0x07ef8518, + 0x4a330138, + 0x76444273, + 0x194f394b, + 0x2835152e, + 0x565b6051, + 0xbc70213c, + 0xe0845c1c, + 0x29417a30, + 0x1a143318, + 0x6c5d5f6b, + 0xe23d7f1c, + 0x7f862219, + 0xa787f820, + 0xf36f3320, + 0x535a2408, + 0x825353f8, + 0xd3d32517, + 0xebebfafd, + 0x00212785, + 0x202782ad, + 0x27a78303, + 0x535a1133, + 0xfafd0602, + 0x1f241782, + 0x5f01f4ff, + 0x0f201782, + 0x080ab77b, + 0x33113520, + 0x06061411, + 0x1a4e37be, + 0x2a39243a, + 0x4722542b, + 0x292b2d0c, + 0x01392f3a, + 0x2e97fe63, + 0x4f852e4d, + 0x82fe0121, + 0x840c2037, + 0x3315224f, + 0x91e51837, + 0x5cda3109, + 0x9e59c5ad, + 0xf606025a, + 0xc2fec8f6, + 0xa55f0401, + 0x9a202f86, + 0xe3492f82, + 0x33112a05, + 0xed535a15, + 0x3ffe0602, + 0x211b8545, + 0x1b822d02, + 0x4b841920, + 0x18171321, + 0x3c0bf342, + 0x27272307, + 0x15161623, + 0x665d5a11, + 0x64260425, + 0x03064b5d, + 0x28632d04, + 0x03042d63, + 0x34408207, + 0x016767f8, + 0x01fafd08, + 0x245d2300, + 0x75fdfd75, + 0xff235e23, + 0x21538500, + 0x5382ef01, + 0x53871320, + 0x35262627, + 0x23113335, + 0x2a4d8403, + 0xbf545a15, + 0x0803043c, + 0x83c0534d, + 0x25478206, + 0x5d276fce, + 0x4882f32a, + 0x286f3230, + 0x00f52a5a, + 0xff340002, + 0x021a02f4, + 0x6c180012, + 0x27262137, + 0x3e3e6e47, + 0x0586476e, + 0x4756563c, + 0x0c565647, + 0x55547a42, + 0x79404079, + 0x427a5455, + 0x5e5d6d46, + 0x5d5e6a6a, + 0x5782006d, + 0x9e825a20, + 0x9982dc20, + 0x14000b22, + 0x230a5143, + 0x11152323, + 0x3c05924e, + 0xb15a2323, + 0x75355e3e, + 0x45585e5c, + 0x56454341, + 0x441e0602, + 0xc450553b, + 0x33320001, + 0x06214535, + 0x23026722, + 0x0b239982, + 0x18002500, + 0x210dff4b, + 0xa3472622, + 0x43362005, + 0xe64507a7, + 0x26012107, + 0x47299382, + 0xf1555548, + 0x5a196a51, + 0x39ad856e, + 0x4613596f, + 0x0c1d122e, + 0x6f361e10, + 0x6a6a5d60, + 0xcf6f605d, + 0x8f0e3f51, + 0xb8835471, + 0x8f715429, + 0x0523290e, + 0x870f3e04, + 0x82e720b5, + 0x6f0e20b5, + 0x322106d5, + 0x09e44816, + 0x3522b882, + 0xb7822634, + 0x593ab32d, + 0x8a364134, + 0x57608159, + 0x823e4481, + 0x421c2db9, + 0x0f4c3a39, + 0x01d0d0da, + 0x28325e0c, + 0x0025f882, + 0x01f4ff2a, + 0x82bb82b4, + 0x5017200c, + 0x5c4808dd, + 0x1e470818, + 0x06141502, + 0x25663ef3, + 0x2e51212c, + 0x24313733, + 0x654d3541, + 0x1c57394f, + 0x26421a2b, + 0x282d342c, + 0x213b2642, + 0x212a0c68, + 0x2c241e39, + 0x0f222623, + 0x3841141a, + 0x19264e41, + 0x261c1736, + 0x10221f23, + 0x35220e1a, + 0x8357402c, + 0x821c2079, + 0x82b72004, + 0x7d0720c1, + 0x112b08cb, + 0x9b01a4c0, + 0x45c101a4, + 0x823ffe45, + 0x5700211c, + 0xf0209b82, + 0x15202182, + 0x1853e518, + 0x3a242508, + 0x2053365d, + 0x38242338, + 0x5c354f20, + 0x55642b0c, + 0xd1fe2e01, + 0x1d1d453b, + 0x2f013b45, + 0x6455d2fe, + 0x0001002b, + 0x01210082, + 0x204782bf, + 0x2069820d, + 0x08c37c03, + 0x03331337, + 0x5557b0b0, + 0x040e180e, + 0x530e170f, + 0x0602af54, + 0x502df4fe, + 0x2302822d, + 0xfafd0c01, + 0x17243782, + 0x94020000, + 0x21203782, + 0x1320378e, + 0x8206057d, + 0x18232041, + 0x080853e5, + 0x52748b21, + 0x08100837, + 0x0a150903, + 0x0a48484a, + 0x08040a15, + 0x4d37080e, + 0x07506171, + 0x0704060d, + 0x824e080c, + 0x2af22a5f, + 0x54292954, + 0xfe0e012a, + 0x820682f2, + 0x0e01350c, + 0x2201fafd, + 0x1d1d3b1f, + 0xdefe1f3b, + 0x0f000100, + 0xb6010000, + 0x19207382, + 0x13207382, + 0x180c5969, + 0x320b53e5, + 0x465b96a1, + 0x040d130a, + 0x4309130b, + 0x5ca19658, + 0x82170a4c, + 0x0b15390c, + 0xfb0b014a, + 0x1725117a, + 0x7a112517, + 0x80f9feff, + 0x18182914, + 0x00801429, + 0x2005917a, + 0x055744a0, + 0x0f098918, + 0x58a7a63b, + 0x0e1b0d42, + 0x0d1a0e04, + 0xc4a75642, + 0x1c894201, + 0x381d1d38, + 0xbefe891c, + 0x209182c4, + 0x2091822d, + 0x065145b1, + 0x2101353f, + 0x01152135, + 0x012d1521, + 0x01fefe1b, + 0x01e5fe67, + 0x9101311f, + 0x70fe3144, + 0xffff0045, + 0x05e54600, + 0x2602ef2e, + 0x0000cd04, + 0x3b070700, + 0x8cffeb00, + 0x3e201792, + 0xd220178c, + 0x41202f88, + 0xd520178c, + 0x43201788, + 0xb920178c, + 0x4f201788, + 0xa420178c, + 0x45201788, + 0xd620178c, + 0x4a201788, + 0xfc20178c, + 0x53201788, + 0xd920178c, + 0x57201788, + 0xff251787, + 0x02d40132, + 0x23178806, + 0x00eb0069, + 0xf420ef89, + 0x51201788, + 0x0321478b, + 0x20178804, + 0x20179690, + 0x20178c92, + 0x202f8816, + 0x20178c94, + 0x20178837, + 0x418f8c96, + 0x27220737, + 0x17834107, + 0x07070022, + 0x0321978c, + 0x20378840, + 0x894f8c98, + 0x8c9a2017, + 0x88442017, + 0x8c9c202f, + 0x883b2017, + 0x8c9e2017, + 0x0757417f, + 0x4a072722, + 0x002d7f8b, + 0xff030002, + 0x02f2012c, + 0x00090006, + 0x0bed4823, + 0x2622132a, + 0x37363435, + 0x07232723, + 0x0ec1dc18, + 0x3509ff48, + 0x323828e1, + 0xc5301219, + 0x5eb95430, + 0x1c2d23ba, + 0x16131712, + 0x0d492d0e, + 0xe7fd3808, + 0x43292b2c, + 0x02929211, + 0x0efafd06, + 0x1717203d, + 0x110b2d0e, + 0x84030000, + 0x82d42073, + 0x00112273, + 0x2075831b, + 0x186b8517, + 0x2e1cc1dc, + 0x333828f9, + 0x1e372124, + 0x17131611, + 0x49592d0f, + 0xd4201083, + 0x0dc0dc18, + 0x49ee0121, + 0xff210e92, + 0x237586ff, + 0x042602ef, + 0x2c05256c, + 0xffeb003e, + 0x0002008c, + 0x02000008, + 0x2d8d8297, + 0x00160006, + 0x33071300, + 0x06062335, + 0xb8480101, + 0x35213f09, + 0x30fc0723, + 0x2b16038a, + 0x1e01f6fe, + 0xbee36701, + 0xbffeedbe, + 0x24014cac, + 0x5428fc59, + 0xd148b5fe, + 0x8d8d2106, + 0x8205bd71, + 0x2a63834b, + 0x000000ff, + 0x013e0707, + 0x888cffd2, + 0x82a42017, + 0x2017857b, + 0x27178345, + 0x21000300, + 0xf9010000, + 0x132b7b82, + 0x29001c00, + 0x35330000, + 0x7b373523, + 0x152c20c3, + 0x6d231533, + 0x56aa4c4c, + 0x382e2d6e, + 0x08092d4a, + 0x51445726, + 0x8057494c, + 0x03377f80, + 0x45384d01, + 0x040c3c23, + 0x4d38410a, + 0x2c31014a, + 0xfe252928, + 0x33393160, + 0x003a4730, + 0x2305b37d, + 0xc102e501, + 0xce208d82, + 0x4d22a584, + 0xa5841401, + 0x56ff5a22, + 0x06201782, + 0x77231788, + 0x83001e01, + 0xff34262f, + 0x02d7011e, + 0x20178212, + 0x222f84cf, + 0x6d26016e, + 0xd7210877, + 0x85ed8302, + 0x013e2217, + 0x4a478427, + 0xd2200593, + 0x41202f88, + 0xd920178c, + 0x57201788, + 0x8f83178c, + 0x4d204785, + 0x5a251786, + 0xf7010000, + 0x202f8302, + 0x227784d0, + 0x841b0157, + 0x8317855f, + 0x2017852f, + 0x2117874d, + 0x2f8232ff, + 0x1785bf83, + 0x19016922, + 0xd783a784, + 0x8902f721, + 0x86772017, + 0x00212417, + 0x820b0200, + 0x05062217, + 0x822785b3, + 0x84aa206f, + 0x84d120cf, + 0x013b226f, + 0x8b6f8808, + 0x8c3e2017, + 0x85e78317, + 0x8c41202f, + 0x85b78317, + 0x8c572017, + 0x82b92017, + 0x201785ff, + 0x20178c4f, + 0x201788a4, + 0x20178c45, + 0x201788d6, + 0x83178c4a, + 0x204785ff, + 0x8217874d, + 0x84aa20ff, + 0x221785e7, + 0x8a120169, + 0x88f420d7, + 0x86512047, + 0x8257202f, + 0x02b922ef, + 0x201788d5, + 0x225f8a43, + 0x880403e7, + 0x86902017, + 0x82352017, + 0x8aaa202f, + 0x8a922017, + 0x03d7222f, + 0x202f8816, + 0x22178a94, + 0x883703aa, + 0x8c962017, + 0x073741a7, + 0x41072722, + 0x00221783, + 0xaf840707, + 0x0001002c, + 0x012cff5a, + 0x000602ba, + 0xd966001f, + 0x23372206, + 0x098f4311, + 0x0cb7dc18, + 0x37286a25, + 0x4cfb1c2e, + 0x0320055a, + 0x10b4dc18, + 0x23056b4c, + 0x1b2e1f03, + 0x21057c44, + 0x5b84ffff, + 0x220b2341, + 0x410b0170, + 0x73820523, + 0xef02aa2c, + 0x20052602, + 0x07000000, + 0x93843e07, + 0x2805c74d, + 0x005403aa, + 0x000f000b, + 0x0dd14c13, + 0x21350127, + 0x37272715, + 0x06d94c17, + 0x01d8fe27, + 0x791f980c, + 0x060f4427, + 0x396b0222, + 0x0b6bdc18, + 0xc102a126, + 0xd2042602, + 0x4d225b84, + 0x27430a01, + 0x83e32008, + 0xd3042173, + 0x3e221784, + 0x178a3401, + 0x2f82d220, + 0x41201785, + 0xd620178c, + 0x4a201788, + 0x5f83178c, + 0x4d202f85, + 0x1e241788, + 0x1202e301, + 0x6c222f88, + 0xb7433101, + 0x02e32208, + 0x201788d9, + 0x20478c57, + 0x201788a4, + 0x22178a45, + 0x88d502e5, + 0x83432017, + 0x059d4d17, + 0x02180225, + 0x182e0081, + 0x580c25b6, + 0x8b4e0f5b, + 0x0fad4d0b, + 0x041e262e, + 0x1b132e37, + 0x0c07100c, + 0x1a171509, + 0x3014b94d, + 0x280f0c09, + 0x3b050635, + 0x12170402, + 0x1033201f, + 0x09c54d16, + 0x3006cb44, + 0x02d202f8, + 0x00d40426, + 0x07070000, + 0xff290141, + 0x2517838c, + 0xf80132ff, + 0x17880602, + 0x29016922, + 0x5a22fb84, + 0x178c19ff, + 0x17887420, + 0x178c5620, + 0x17837720, + 0x0002002a, + 0x02000020, + 0x00060256, + 0x0c5ddc18, + 0xcd793320, + 0x23113905, + 0x11152335, + 0x6e233533, + 0xf8534e4e, + 0x534a4a53, + 0x01f8f8f8, + 0x5205357a, + 0x3a2b0082, + 0xebeb86fe, + 0xff4e2c01, + 0x82fcffff, + 0x02b92299, + 0x208b82ef, + 0x240982d5, + 0x003b0707, + 0x24a38483, + 0x0100004d, + 0x20178a0a, + 0x2117853e, + 0x1782efff, + 0xd3841720, + 0x41202f85, + 0xd2201786, + 0x34221782, + 0x4788d502, + 0x17864320, + 0x1782eb20, + 0xb9021b22, + 0x4f201788, + 0xfd201786, + 0x09221782, + 0x1788a402, + 0x17854520, + 0x824a0021, + 0x02bc2285, + 0x201788c1, + 0x20778c4d, + 0x201788d9, + 0x21178557, + 0x2f823f00, + 0xf402d222, + 0x51201788, + 0x4c261786, + 0xba0032ff, + 0x17880602, + 0x61006921, + 0x2b220593, + 0xd7852cff, + 0x843d0521, + 0x22d784ef, + 0x82000100, + 0xdb002117, + 0x4705254c, + 0x232206f3, + 0x89183311, + 0x37290788, + 0x8b060617, + 0x182b3828, + 0x6fdc1814, + 0x3c2b270c, + 0xfd060216, + 0xdc1818fa, + 0xff210a6f, + 0x22d782f1, + 0x88d60215, + 0x864a2077, + 0xff1f268f, + 0x02c301f4, + 0x201782d2, + 0x237784d6, + 0xff2f0141, + 0x22050b42, + 0x84fe011e, + 0x84d720a7, + 0x016c2217, + 0x060b422b, + 0x178c3220, + 0x17886920, + 0x178c5620, + 0x17867720, + 0x77825320, + 0xef029a22, + 0xd8205f82, + 0x3e284784, + 0x8cff8900, + 0x5a000200, + 0x66271784, + 0x0a000500, + 0x82330000, + 0x332108d2, + 0x33270315, + 0x535a0707, + 0x3b0462ed, + 0x06020e01, + 0x01453ffe, + 0x9b39d492, + 0x00ffff00, + 0x011eff5a, + 0x858d849a, + 0x016c2245, + 0x08a54504, + 0x0425178a, + 0x00df0082, + 0x202f84ed, + 0x202f8c32, + 0x212f8669, + 0x1783ff03, + 0x8d86a420, + 0x45072722, + 0x07218d84, + 0x221f8707, + 0x8c56ff5a, + 0x83772037, + 0x01002737, + 0x0000faff, + 0x634d9f01, + 0x35210806, + 0x11372707, + 0x17371533, + 0x15331507, + 0x651e475f, + 0xb01e9253, + 0x3027aeed, + 0xf2170138, + 0x8e5e314e, + 0x23b18445, + 0x2d020000, + 0xd920f784, + 0x0121f785, + 0x05574143, + 0xc1201784, + 0x17858182, + 0x17874d20, + 0x0232ff23, + 0x85e1842d, + 0x01692217, + 0x20e18843, + 0x204784ef, + 0x204786da, + 0x085f472d, + 0x3b21178b, + 0x20178b01, + 0x855f82d9, + 0x8c57202f, + 0x88d52017, + 0x87432017, + 0x1eff2317, + 0x7784ef01, + 0xe7412f85, + 0x21f18208, + 0xa78302ef, + 0x4d201785, + 0x32202f88, + 0xff412f8c, + 0x41478b0b, + 0x342407ff, + 0x1a02f4ff, + 0xdb20bf84, + 0x3b22bf84, + 0xbf842601, + 0x3e20178f, + 0xd220178c, + 0x2f85a782, + 0x178c4120, + 0x1785bf83, + 0x178c4320, + 0x2f88b920, + 0x178c4f20, + 0x1788a420, + 0x178c4520, + 0x1788f820, + 0x178c5520, + 0x1788d920, + 0x17885720, + 0xbf823220, + 0x17881220, + 0xc7496920, + 0x20178209, + 0x201788f4, + 0x242f8851, + 0x031a02f4, + 0x20178804, + 0x20179690, + 0x20178c92, + 0x202f8816, + 0x20178c94, + 0x20178837, + 0x418f8c96, + 0x2722071f, + 0x17834107, + 0x07070022, + 0x00399784, + 0xff2f0003, + 0x021f02e9, + 0x0007001e, + 0x0027001f, + 0x17141300, + 0x22232613, + 0xa8bd1806, + 0x1a86321f, + 0x494229f2, + 0x3c243358, + 0x6e3e1d1a, + 0x38405b47, + 0x08098525, + 0x9c3f5d37, + 0xf2195749, + 0x4804012a, + 0x2b1a0132, + 0x1d86fe6c, + 0x385d2346, + 0x35417855, + 0x22461d41, + 0x7b53395c, + 0x6f0c3742, + 0xfe32475e, + 0x02002ce6, + 0x00003400, + 0x0602ae02, + 0xb9db1800, + 0x1523230d, + 0x03831533, + 0x11332522, + 0x25088c82, + 0x01161415, + 0x90918348, + 0xe5600180, + 0xfeefc0c0, + 0x60262698, + 0x80825c5c, + 0x96428480, + 0x4242ad3f, + 0x5f648301, + 0x454b655b, + 0x02f42405, + 0x41a3022d, + 0x63290805, + 0x20009901, + 0x3400ffff, + 0x291783ff, + 0x052602ef, + 0x00000067, + 0x3d420707, + 0x022d210b, + 0x6d421789, + 0x022d220b, + 0x412f88f4, + 0x2d220bad, + 0x1788d502, + 0x1c014322, + 0x20069d42, + 0x86778532, + 0x0169225f, + 0x82678227, + 0x2cff29dd, + 0x12021a02, + 0x2d002100, + 0x78086749, + 0x02530574, + 0x07062206, + 0x05087b06, + 0x10eebc18, + 0x38283432, + 0x65421f21, + 0x486d3e39, + 0x2c3e6e47, + 0x29382e4a, + 0x3106994d, + 0x56564721, + 0x54544947, + 0x1c2b2cd4, + 0x4404173f, + 0xca535077, + 0x6a482605, + 0x40131043, + 0x05864917, + 0x530e0121, + 0xff8408d5, + 0xe7838783, + 0xff906d20, + 0xd6021a22, + 0x35082f41, + 0xff26014a, + 0x0004008c, + 0x02f4ff34, + 0x0054031a, + 0x001b000f, + 0xfd70001f, + 0x7b262005, + 0x162006bf, + 0x200f6878, + 0x06a34903, + 0x69540120, + 0x49402013, + 0x705405b0, + 0x31022115, + 0x220cbf49, + 0x82c102dc, + 0x84dc2089, + 0x014d22a1, + 0x08b7441e, + 0x8202e721, + 0xde0421b9, + 0x3e221784, + 0x178a1a01, + 0x17852f83, + 0x178c4d20, + 0x4782d920, + 0x57201785, + 0xff251787, + 0x02e7011e, + 0x22178806, + 0x461d016c, + 0x178b089f, + 0x178c6920, + 0x2f86a420, + 0x45072722, + 0x00224783, + 0x1f890707, + 0x4f8c5620, + 0x37867720, + 0x83054154, + 0x85df20af, + 0xfe0021af, + 0x1785af84, + 0x4f82d220, + 0x41201785, + 0xaf83178c, + 0x57201785, + 0x1e241788, + 0x1202b401, + 0x6e222f88, + 0xaf84f400, + 0xc7822a20, + 0x6c22178b, + 0x17860301, + 0x2f82f420, + 0x2f88c120, + 0x47884d20, + 0x478c3220, + 0x2f896920, + 0x02840326, + 0x04260012, + 0x04237784, + 0x82d001df, + 0x000126af, + 0x02f4ff5b, + 0x65178327, + 0x35250bdf, + 0x27262634, + 0x05875b27, + 0x23111524, + 0xb45c3411, + 0x16540805, + 0x06141516, + 0x31840106, + 0x182b1a4f, + 0x2c291c34, + 0x063d421b, + 0x2a360e71, + 0x7454473f, + 0x165e496a, + 0x274f5371, + 0x19240c49, + 0x2e151732, + 0x1e281924, + 0x1a722e08, + 0xfe4b4b25, + 0x5c4701c7, + 0x713b4a6f, + 0x283a4a10, + 0xffff2844, + 0x00001c00, + 0xd902b701, + 0xe0042602, + 0x07268582, + 0xea005707, + 0x17888cff, + 0x1785d583, + 0x17874d20, + 0x821eff21, + 0x8806202f, + 0x006e252f, + 0xff0000e5, + 0x178e4782, + 0xea006c22, + 0x32201786, + 0x69202f8c, + 0x56201788, + 0x7720178c, + 0x8f841787, + 0x5f88b920, + 0x77834f20, + 0x86010021, + 0x000623a7, + 0x47500010, + 0x35332205, + 0xe2401823, + 0x7cc03408, + 0x01a42359, + 0x7c7ca49b, + 0xa20436e5, + 0x3aa24545, + 0x55ffffe5, + 0xef2006b5, + 0xe1204982, + 0x3b22d984, + 0xd9842401, + 0x8905cd55, + 0x8c3e2017, + 0x88d22017, + 0x8c41202f, + 0x88d52017, + 0x8c432017, + 0x85a98317, + 0x8c4f205f, + 0x88a42017, + 0x8c45202f, + 0x88d62017, + 0x8c4a2017, + 0x88fc2017, + 0x8a532017, + 0x02f22217, + 0x201788f8, + 0x202f8c55, + 0x201788d9, + 0x21178b57, + 0x17881703, + 0x178c8c20, + 0x17885420, + 0x178c8620, + 0x17884e20, + 0x178c8e20, + 0x88202f89, + 0x32241788, + 0x0602f001, + 0x69242f88, + 0x00002401, + 0x20086741, + 0x201788f4, + 0x2e2f8351, + 0x57000100, + 0x6302f4ff, + 0x2100ad02, + 0x18010000, + 0x2420e9db, + 0x5c35f001, + 0x0944573b, + 0x33271f2e, + 0x0d0a400e, + 0xfee20145, + 0x2b6455f6, + 0x2a0e4f57, + 0x1d282803, + 0x28101e19, + 0x85383917, + 0x2967827f, + 0x052602ef, + 0x0000009a, + 0xcf410707, + 0x41178c0a, + 0x17820aff, + 0x2f86af82, + 0x4788af84, + 0x4788d520, + 0x2009e741, + 0x202f8232, + 0x841788ad, + 0x24df84f7, + 0x02f0012c, + 0xe9db1806, + 0x2830272a, + 0x34172137, + 0x29582e50, + 0x46513407, + 0x121e2820, + 0x0e171315, + 0x2b2cd42e, + 0x05153a23, + 0x584e612f, + 0x68250d38, + 0x3d070f6a, + 0x08df4f1e, + 0x83ff5721, + 0x20eb8373, + 0x25eb8ca0, + 0x02000017, + 0x17820294, + 0x84e30421, + 0x013b2417, + 0x828cff56, + 0x20178fd3, + 0x22178c3e, + 0x862602d2, + 0x8c41202f, + 0x88b92017, + 0x854f2017, + 0x22498217, + 0x84a00100, + 0x85e5205f, + 0xd000215f, + 0x17905f83, + 0x178c3e20, + 0x2f855f83, + 0x178c4120, + 0x17855f83, + 0x178c4f20, + 0x7782c120, + 0x4d201785, + 0xff211787, + 0x20778232, + 0x25178806, + 0x00ce0069, + 0x0082ff00, + 0x8f830020, + 0x1788f420, + 0x478c5120, + 0x1788d520, + 0x17854320, + 0x3b580020, + 0x82ef2005, + 0x84e62017, + 0x003e22bf, + 0x86bf83fa, + 0x88d92017, + 0x8c572017, + 0x858f8317, + 0x874d202f, + 0x218f8217, + 0x8f8302b1, + 0x69221785, + 0x8f83fd00, + 0xff2d0024, + 0x178b0156, + 0x17837720, + 0x00020022, + 0x21068353, + 0xa9730c00, + 0x35232205, + 0x06056437, + 0x099a5c18, + 0x15331526, + 0x4d4d6e23, + 0x250b715e, + 0x2bf87e7e, + 0x755edf04, + 0x2f9d2108, + 0x200a1d5c, + 0x334f180e, + 0x08d56107, + 0x260aed64, + 0x3d5e535a, + 0x8236365e, + 0x45553504, + 0x55444342, + 0x1d560602, + 0x49383b44, + 0x31af7023, + 0x00283534, + 0x3a264782, + 0x1202f4ff, + 0x8f821202, + 0xd7502020, + 0xe2b51808, + 0x163e0817, + 0x46220116, + 0x01013a68, + 0x53048201, + 0x1942274a, + 0x3a5b1e28, + 0x3e3b6a47, + 0x543e466c, + 0x05d0fe09, + 0x79430c51, + 0x070c0650, + 0x151f5f56, + 0x41261b37, + 0x7b535479, + 0x4f574442, + 0x0100584e, + 0x69825a00, + 0x69820720, + 0x2505e752, + 0x16163727, + 0xeb7e3233, + 0x23112208, + 0xebdb1811, + 0x0132080a, + 0x0d271169, + 0x0d130914, + 0x46162416, + 0x184c1f3b, + 0x501f5153, + 0x3357372c, + 0x07060c55, + 0x24040441, + 0x576e5059, + 0x82fe232b, + 0x203f0602, + 0x6175352b, + 0xcb838291, + 0x68ff5a30, + 0x0602b401, + 0x13000300, + 0x11330000, + 0x395c1133, + 0x180d820a, + 0x2f10e5db, + 0x98fafd06, + 0x03410508, + 0x012c3305, + 0x4a04fef9, + 0x6822a585, + 0x4382ef01, + 0x86050d41, + 0x5e3520a5, + 0xa582070e, + 0x33171322, + 0x3305225e, + 0x78010614, + 0x0f0b2014, + 0x1d0a1408, + 0x3cc00314, + 0x4d080304, + 0x29062d5e, + 0x04079837, + 0x2e05023e, + 0x255e0128, + 0x09375e05, + 0x5243f722, + 0x24099f59, + 0x04060206, + 0x082b4ecd, + 0x8302e521, + 0x00ce220f, + 0x06955e00, + 0x8582a220, + 0x83530520, + 0x5a112906, + 0x02f54801, + 0x40fe4606, + 0x1e20e783, + 0x2d822282, + 0x00050023, + 0x081f820b, + 0x33133520, + 0x21251513, + 0x07232727, + 0xb45fb41e, + 0x150191fe, + 0x38033851, + 0xfed50131, + 0xd845312b, + 0x3752a5a5, + 0x84aa2006, + 0x84d1205f, + 0x05ff426f, + 0xe6206f83, + 0xf8207f88, + 0xd4201f84, + 0x03207f82, + 0x410cd35e, + 0x734a05af, + 0x35272318, + 0x6f4a1533, + 0x4921080d, + 0x49495656, + 0xb6125757, + 0x557a420c, + 0x40407855, + 0x7a555578, + 0x606e4342, + 0x606a6a60, + 0x3fb86e60, + 0x4955183f, + 0x20818308, + 0x208188d5, + 0x208184fe, + 0x208182d7, + 0x25038201, + 0x02be0100, + 0x95180006, + 0xae351007, + 0x5557af61, + 0x040e180d, + 0x550e160f, + 0xfafd0602, + 0x522c0c01, + 0x2102822c, + 0xbd4ff4fe, + 0x20578309, + 0x205788d9, + 0x205784ef, + 0x079518da, + 0x82a72008, + 0x18032057, + 0x20090795, + 0x36c18225, + 0x15213525, + 0xfe760131, + 0xd0fef9c9, + 0x42426601, + 0xd53f3fef, + 0x4cff4242, + 0x1a2605af, + 0x06021202, + 0x9941db04, + 0x5ef22008, + 0x2122071d, + 0x01822311, + 0x98015a23, + 0x82128253, + 0xfec02289, + 0x21838640, + 0x7384dc01, + 0x3384dc20, + 0x00002c24, + 0x3382b101, + 0x00000b26, + 0x27373533, + 0x21376a82, + 0x15210717, + 0x01b8bb2c, + 0xa4fafe6d, + 0x312001a9, + 0x412dd1d7, + 0x8342c7bc, + 0x0581493d, + 0xe020c183, + 0x830adb44, + 0x84e5200f, + 0xff302bc1, + 0x025f02ee, + 0x00110018, + 0x62180018, + 0x03201435, + 0x0dff9418, + 0x836f2225, + 0x834b6f83, + 0x58ed2604, + 0x01584a4a, + 0x0805838f, + 0x05471221, + 0x6a5f5e6c, + 0x04474704, + 0x6c5e5f6a, + 0x16014705, + 0x01044a41, + 0x4148041c, + 0xfe044841, + 0x824a04e4, + 0x06f35dfb, + 0xe420fb82, + 0x3f24c784, + 0x32020000, + 0x172ac782, + 0x35210000, + 0x35352626, + 0x6a831533, + 0x0cf59418, + 0x64122608, + 0x4043506f, + 0x5042414d, + 0x05bb646f, + 0x7c81665f, + 0x01044348, + 0x04f5fe0b, + 0x817c4843, + 0xbb055f66, + 0x00010000, + 0x2349822c, + 0x00120225, + 0x29f59418, + 0x6b2c3d08, + 0x3c1d2c17, + 0x6d49486d, + 0x172c1d3c, + 0x3e2fcc6b, + 0x31324626, + 0x2e3e2646, + 0x3c150342, + 0x7149314f, + 0x49714242, + 0x153c4f31, + 0x233b4203, + 0x56364b67, + 0x36563131, + 0x3b23674b, + 0xffffff00, + 0x22073354, + 0x41360506, + 0xb9240a53, + 0xa9050602, + 0x0322d982, + 0x8f820300, + 0xd9828320, + 0x11000924, + 0x195c1500, + 0x0707650b, + 0x33112123, + 0x120b6511, + 0x6553d921, + 0x0123100e, + 0x4562fe9e, + 0x0221059f, + 0x225182ff, + 0x180f000b, + 0x2408254d, + 0x23352311, + 0x2a498315, + 0x53f8535a, + 0xff01f853, + 0x63060253, + 0x34840578, + 0x2c203582, + 0xfd268782, + 0x27001202, + 0x35822b00, + 0x25b78018, + 0x1d415083, + 0xb3012219, + 0x1f204153, + 0x0b5f7c83, + 0x06934408, + 0x0121c185, + 0x22c182df, + 0x1815000d, + 0x08124d68, + 0x26343522, + 0x015a2323, + 0x63f3fe60, + 0x71365e3b, + 0x865b665b, + 0x02584445, + 0x1a964506, + 0x4a52363f, + 0x272e603e, + 0x2005e543, + 0x08d74401, + 0xa2210f86, + 0x22638202, + 0x8200bb05, + 0x1a0025ea, + 0x1e0254ff, + 0x082d6382, + 0x00001d00, + 0x33070637, + 0x020e2311, + 0x47681803, + 0x21340810, + 0xf32317cb, + 0x0c0c0792, + 0x1b08476a, + 0x0d19190c, + 0x090f0f0b, + 0x08462601, + 0xf09afe47, + 0x7c013575, + 0xfe414128, + 0x0636bc3c, + 0x31414c24, + 0xfe355350, + 0xacbc3640, + 0x44078943, + 0x002308f7, + 0x82060001, + 0x02b32474, + 0x822b0012, + 0x271325d1, + 0x22232626, + 0x155e5718, + 0x23224e08, + 0x07070622, + 0x23272313, + 0x23352315, + 0x39a90607, + 0x05141f13, + 0x0d0e050b, + 0x1c3e2815, + 0x464e473e, + 0x273e1d3e, + 0x060d0d15, + 0x2014050a, + 0x59a93913, + 0x4c4e4b8b, + 0x7513018b, + 0x4b021626, + 0x82392705, + 0x3982d6d6, + 0x024b0527, + 0xfe752616, + 0x820083ed, + 0xff2b247d, + 0x82bf01f4, + 0x7029207d, + 0xbb180da5, + 0x3c6f0bc7, + 0x67062008, + 0x3f08063a, + 0x623bf306, + 0x4b242a2b, + 0x4948332f, + 0x44314143, + 0x492c3b3c, + 0x5b202b36, + 0x2a635331, + 0x363f2f28, + 0x27240c5d, + 0x31202038, + 0x382e2f2e, + 0x2b252a2a, + 0x231c3733, + 0x3d283e4c, + 0x4109040e, + 0x26483233, + 0x2311e364, + 0x07061415, + 0x2e053965, + 0x37363435, + 0x5a030723, + 0x0403084d, + 0x8455be3c, + 0x02c03206, + 0x5d2af306, + 0x32016f27, + 0x2af5fafd, + 0xfe6f285a, + 0x06b741ce, + 0xbb02ef25, + 0x4f052602, + 0x4b2405cb, + 0x76ff2a01, + 0x2105a746, + 0xd1820202, + 0xe3421820, + 0x36372106, + 0x20058f4e, + 0x0a404126, + 0x535a2608, + 0x38224d58, + 0x07130927, + 0x060a050f, + 0x47181c12, + 0x58a459bd, + 0x83d50602, + 0x02042539, + 0x2715024a, + 0xededfe75, + 0x284d82ed, + 0x01f4ff00, + 0x000602d4, + 0x0b1f4119, + 0x0e266818, + 0x0d322e08, + 0x06110b1a, + 0x190f060a, + 0x1f110d18, + 0x53200110, + 0x0e170d8e, + 0x0c332711, + 0x014b0403, + 0x3b3a1203, + 0xfd529c4f, + 0x41c201fa, + 0x59513f81, + 0x22bb8523, + 0x46022d02, + 0xeb460d11, + 0x0fe14508, + 0x01212f85, + 0x212f83f2, + 0x4146c805, + 0x08cd4508, + 0x01272f85, + 0x021202d7, + 0x84cf0406, + 0x0caf451f, + 0x0520c582, + 0xbc20c582, + 0x1320c582, + 0x2727c583, + 0x32331637, + 0x6d033737, + 0x3008066d, + 0x78060603, + 0x11111624, + 0x0c142e14, + 0x2c5f57bd, + 0x52582704, + 0x0c4316b3, + 0x26064708, + 0xd08a0119, + 0xfed06c6c, + 0x003b345d, + 0xff2f0003, + 0x025302f4, + 0x28e54512, + 0x7e701d3e, + 0x7047707e, + 0xe7707f7f, + 0x544c4c54, + 0x4d538701, + 0x4f0c534d, + 0x5c5c6304, + 0x49490463, + 0x4f310785, + 0x443f1201, + 0x02090102, + 0x433f3f43, + 0x02f7fe02, + 0x12e54544, + 0x54ff5a24, + 0xbf822902, + 0x10ab5618, + 0x80feda33, + 0x4654e253, + 0x02acac08, + 0x0140fe06, + 0x3640fec0, + 0x24ef82bc, + 0x01000043, + 0x20ef85c3, + 0xab561821, + 0x136f3a13, + 0x6d5e202e, + 0x1d404352, + 0xe154102a, + 0x614e0404, + 0x303d7e7e, + 0xfde30404, + 0x064142fa, + 0x3d82ab20, + 0x0f116818, + 0x50b05024, + 0x678750b1, + 0x85c00121, + 0x2099822b, + 0x202b82f1, + 0x11681810, + 0x22308413, + 0x89470846, + 0x05054433, + 0x00020027, + 0x0200001c, + 0x20d18444, + 0x21398315, + 0x53183523, + 0x6d18081d, + 0x21080816, + 0x0101aeca, + 0x74745d56, + 0x424e565d, + 0x4c454546, + 0xcc46c001, + 0x4c575146, + 0x30322e43, + 0x0300002b, + 0x43825a00, + 0x43827620, + 0x1b5b0a20, + 0x67561807, + 0x35362c0b, + 0x23232634, + 0x11331105, + 0x834c535a, + 0x444c2145, + 0x42254583, + 0x02537601, + 0x22478906, + 0x820602fe, + 0x054159c7, + 0x4b86de20, + 0x11330022, + 0x5a224991, + 0x45836053, + 0x83586021, + 0x8b562045, + 0x01002942, + 0xf4ff2000, + 0x1202c201, + 0x22b35618, + 0x38cd3108, + 0x192e1d58, + 0x5646283f, + 0x09dedf04, + 0x3b264151, + 0x52232c1a, + 0x3e6b4435, + 0x2d0c6e41, + 0x1e19341c, + 0x4b3f5e57, + 0x34171b53, + 0x773f2321, + 0x3c7a5d55, + 0x0025e482, + 0x02f4ff5a, + 0x225f82fd, + 0x6820000b, + 0x23201135, + 0x0fb25618, + 0x460d0225, + 0x82465454, + 0x472f0803, + 0x73088165, + 0x0c745353, + 0x6c466180, + 0x3a6c3d3d, + 0x685f5e6d, + 0x6d5e5f68, + 0xeb738446, + 0x6ad30602, + 0x55784075, + 0x00427b54, + 0x00160002, + 0x82b00100, + 0x830e20ff, + 0x35212209, + 0xae561823, + 0x0329080b, + 0x22233533, + 0x01141506, + 0x5e895f5c, + 0x33423698, + 0xabb4395a, + 0x413f5657, + 0x0edad1d1, + 0x42393c4b, + 0x01fafd1c, + 0x3227b80c, + 0x09df455f, + 0x0602ef25, + 0x89000f05, + 0x82b9200f, + 0x0013210f, + 0x00256482, + 0x02f6ff1c, + 0x20698226, + 0x61a31823, + 0x3536230a, + 0x62822634, + 0xc9820720, + 0x10ee6718, + 0x1f8b3508, + 0x12060d17, + 0x1a261307, + 0x261c3d41, + 0x01935411, + 0x2c13bda4, + 0x365a381c, + 0x070a462c, + 0x12040241, + 0x3135222a, + 0x01f40404, + 0x924545c1, + 0x48210404, + 0x1f45393b, + 0xa2267987, + 0x2602d902, + 0x514ed905, + 0x0e012305, + 0x355e76ff, + 0xd7012105, + 0x2017d36b, + 0x9b561807, + 0x462a350c, + 0x72424070, + 0x1a503248, + 0x2435162f, + 0xde0a5843, + 0x495805df, + 0x3606b86c, + 0x5858793e, + 0x1a283f78, + 0x51191633, + 0x5d583f4d, + 0x25321a1d, + 0x69ffff26, + 0x02230727, + 0x41df0406, + 0x00220701, + 0x574b02ad, + 0x0df94808, + 0x07e96718, + 0x00ba0226, + 0x0017000b, + 0x31e96718, + 0x161b5824, + 0x038b1b16, + 0x02a8fd28, + 0xfffafd06, + 0x1f6c00ff, + 0x20878206, + 0x20ff82d6, + 0x278b8202, + 0x02d402f4, + 0x00200006, + 0x450ced46, + 0x561805cd, + 0x0e2a0d9c, + 0x32332502, + 0x26343536, + 0xdd452323, + 0x430c270f, + 0x5c75755c, + 0xe2457a96, + 0x6a012705, + 0x4547423a, + 0xea453945, + 0x46cc240b, + 0x454c5751, + 0x4f2007ed, + 0x2605ad43, + 0x005a0002, + 0x82ff0200, + 0x8312207d, + 0x113324e3, + 0x18331533, + 0x8510a356, + 0x535a2370, + 0x638354ea, + 0xea965d24, + 0x5d823e01, + 0x39444626, + 0xd3d30602, + 0xeb215584, + 0x06fd43eb, + 0x1c000122, + 0x20204f82, + 0x17204f82, + 0x2508136a, + 0x33363615, + 0x67181632, + 0x062307df, + 0x42af1507, + 0x5c27062b, + 0x3b3d5266, + 0x4211261c, + 0x4b280621, + 0x3e8f8f5d, + 0xf404042f, + 0x27055946, + 0xd9020202, + 0xe0052602, + 0x22062342, + 0x4776ff23, + 0x1783085d, + 0x22055d47, + 0x842a013b, + 0x05494617, + 0x2f82bb20, + 0x2f84e920, + 0xe3004b2c, + 0x010076ff, + 0x54ff5a00, + 0x3345ee01, + 0x27052105, + 0x09dd5618, + 0x04000128, + 0x54ed53a2, + 0xa0450a9f, + 0xfafd2207, + 0x05fd44ac, + 0x02f40124, + 0x0b41002e, + 0xdd561806, + 0x050b4113, + 0x718d2208, + 0xc2c25471, + 0x75755c42, + 0x4239415d, + 0x38444546, + 0x623b9101, + 0x445e3b62, + 0x3f4a5550, + 0x292f322d, + 0x0b194e00, + 0x1d001622, + 0x0cbf6a18, + 0x14151632, + 0x22030606, + 0x26210706, + 0x36320326, + 0x16162137, + 0x080d174e, + 0x09554127, + 0x55093e01, + 0x05574441, + 0x5605c0fe, + 0x567b400c, + 0x3e3e7857, + 0x7b565778, + 0x53db0140, + 0xfe534e4e, + 0x58586068, + 0x82e18260, + 0xe50125ee, + 0x19001202, + 0x480ce16a, + 0x2621085d, + 0x08668223, + 0xafaf0330, + 0x180e5557, + 0x150d050e, + 0x3212300d, + 0x0a140f30, + 0x07090611, + 0x78081513, + 0xf3fe0602, + 0x322d522b, + 0x42a02c4c, + 0x4b040337, + 0x1b1f0103, + 0xad6f76fe, + 0x18af2008, + 0x2b0b3757, + 0x440ffd5a, + 0x0602f508, + 0x40feefa9, + 0x21282182, + 0xb8010000, + 0x0d000602, + 0x0f375718, + 0x4f4f702f, + 0x95f54801, + 0x0436e095, + 0x3aa646ec, + 0x242b82e0, + 0x0254ff06, + 0x20a582cd, + 0x244d4a30, + 0x18331721, + 0x4a0b3957, + 0x7e242052, + 0x24470845, + 0x231a554a, + 0xacbc36cd, + 0x2208574a, + 0x82bf0154, + 0x002a2587, + 0x26271700, + 0x1807b350, + 0x4a0cbb61, + 0x07251057, + 0x5a03d007, + 0x19584a48, + 0x09455b26, + 0x4009a2ac, + 0x24185a4a, + 0xa30a5142, + 0x058b4200, + 0x821d0221, + 0x4a1d207b, + 0xf4891501, + 0x2411064a, + 0x47084b8d, + 0x0e094a25, + 0x5782d585, + 0x00001c24, + 0x57827202, + 0xb1471a20, + 0x135b4a08, + 0x01aeca23, + 0x0a5d4a01, + 0x4a130521, + 0x0122065d, + 0x5e4a46c0, + 0x20ab860f, + 0x083f483f, + 0x35331522, + 0x0a395718, + 0xf8535a33, + 0x47084753, + 0x0602f84b, + 0x40fed3d3, + 0xebacbc36, + 0x24df83eb, + 0x0154ff34, + 0x828782d7, + 0x6f17208f, + 0x71720933, + 0x0707250f, + 0x6b5404f7, + 0x27117172, + 0xac09573b, + 0x708811a5, + 0x220e7372, + 0x54a10941, + 0xd94f09b5, + 0x090b6d07, + 0x199d6718, + 0x5971a624, + 0x156d9607, + 0x6096270a, + 0x0437aa71, + 0x196d2101, + 0x3bdf2208, + 0x20b583aa, + 0x20b5820f, + 0x20e982d1, + 0x10ad6d1e, + 0x28079041, + 0x23272626, + 0x07070606, + 0x0db26d0f, + 0x08467624, + 0xb56d2847, + 0x36c12314, + 0xb76dacbc, + 0x43002509, + 0x0a0254ff, + 0x57186182, + 0xfa491c07, + 0x0947220c, + 0x0bfd4947, + 0x8240fe21, + 0x20ab8350, + 0x2004825a, + 0x053f4ada, + 0x54113321, + 0x57450604, + 0x535a3a0a, + 0x5f1f2e14, + 0x4142526d, + 0x02112a1d, + 0x0404c806, + 0x9797624d, + 0x04042f3e, + 0x067747fc, + 0x4d0bef46, + 0xbe2406e1, + 0xdc052602, + 0x23053345, + 0x79ff5a01, + 0x8308dd4e, + 0x85d62017, + 0xea002117, + 0x082a1784, + 0x97020000, + 0x06020602, + 0x4148ff04, + 0x82d1200a, + 0x85db203f, + 0x09012627, + 0xffff8cff, + 0x06275500, + 0x05060223, + 0x222788b5, + 0x4d8e02ef, + 0x45200811, + 0x2606b345, + 0x02f4ff34, + 0x82a6021a, + 0x84e42017, + 0x014f223f, + 0x85678427, + 0x02122417, + 0x84080606, + 0x05db453f, + 0xdb453f83, + 0x00452205, + 0x0af345e3, + 0xf345e220, + 0x83552008, + 0x03002317, + 0x3d552000, + 0x000b2506, + 0x003e0032, + 0x13c55518, + 0x12c45518, + 0x09c35518, + 0x55182720, + 0x72080dc2, + 0x260c0eaa, + 0x1e1b1735, + 0x4d342225, + 0x112b422b, + 0x283c2114, + 0x39253c35, + 0x26481c1f, + 0x104b1833, + 0x351c2130, + 0x453e1516, + 0x3d92521f, + 0x17331a2c, + 0x1c1d4828, + 0x14910124, + 0x3016172b, + 0x29211621, + 0x432744fe, + 0x1a443529, + 0x231c3c1f, + 0x303f233b, + 0x142c3421, + 0x401d4525, + 0x295b3353, + 0x42061710, + 0x211b2d0f, + 0x15312898, + 0x284a2010, + 0x00002e14, + 0x4a370002, + 0x0b2006b5, + 0x075f0e19, + 0x7b363421, + 0x5518059d, + 0x23080bbd, + 0x6a6b5afc, + 0x6b6b5b5b, + 0x4040335b, + 0x41413233, + 0x7f7f920c, + 0x7f7f8e8e, + 0x6a654292, + 0x6b60606b, + 0x0100656a, + 0x0026ff82, + 0x0602ee00, + 0x19440800, + 0x36363305, + 0x9c113337, + 0x193b296a, + 0x35a9013f, + 0xfd0d1407, + 0x258200fa, + 0x04822220, + 0x3f449820, + 0x114b1806, + 0x062f0812, + 0x33363607, + 0x7f281533, + 0x2534338a, + 0x252e183d, + 0x5e503457, + 0x1640653c, + 0x30931b35, + 0x2c3d966e, + 0x2d182333, + 0x45552a26, + 0x3b696231, + 0x82460302, + 0x82172051, + 0x729720c1, + 0x23211291, + 0x05bc4835, + 0x45062221, + 0x43081064, + 0x5f42d506, + 0x481a281d, + 0x4e3f3034, + 0x33475966, + 0x1a3f222c, + 0x3352222a, + 0x2e39634d, + 0x58344734, + 0x341e2c0c, + 0x28302418, + 0x343c342c, + 0x1c2a2426, + 0x251d3319, + 0x3c2d4147, + 0x430b0311, + 0x24432f35, + 0x24000200, + 0xbf20c782, + 0x4b18ed82, + 0x2708120d, + 0x33113313, + 0x78152315, + 0x030102ad, + 0x2f0e140d, + 0x5df1fffe, + 0x85c94d4d, + 0x14163b16, + 0x92fe151e, + 0x4601368a, + 0x8a3fc3fe, + 0x1f20bb82, + 0x9e20bb82, + 0x4b184582, + 0x3721140b, + 0xab551821, + 0xda34080c, + 0x261e5944, + 0x3232441a, + 0x1f334045, + 0x122a192b, + 0x0cdf2401, + 0x31192913, + 0x5a373150, + 0x351c2c0c, + 0x333b2516, + 0x10113932, + 0x8f44ff19, + 0x48230d09, + 0x2a4f3938, + 0x3e20a982, + 0xba226382, + 0x4b181202, + 0x43082f09, + 0x1a411b03, + 0x29354108, + 0x3a2e3539, + 0x673f365c, + 0x1947303b, + 0x1d33122d, + 0x02294327, + 0x4a254b1b, + 0x0150305a, + 0x49221e03, + 0x2f2e3a47, + 0x37f1fe39, + 0x7f675670, + 0x3218213b, + 0x5b271612, + 0x51231d4e, + 0x2a4c3351, + 0x2006b747, + 0x06b7478c, + 0x55183e20, + 0x8e3c08a9, + 0x37442105, + 0x6b01f2fe, + 0x11243f33, + 0x87965f04, + 0x3a314446, + 0x4c7b6b69, + 0x36000300, + 0xb520af82, + 0x1d25af82, + 0x37002a00, + 0xa9551800, + 0x07855116, + 0x55180320, + 0x15200ba8, + 0x0ba85518, + 0x37f75b08, + 0x32203258, + 0x2c31211b, + 0x5a4e2f4c, + 0x3d281c34, + 0x1d13562f, + 0x282f341f, + 0x323b2433, + 0x2a45283e, + 0x0c453121, + 0x23284025, + 0x040d2735, + 0x2a283c14, + 0x3c4e223d, + 0x0312412a, + 0x28353c15, + 0x2a012541, + 0x251a3316, + 0x1c242a31, + 0x2efb1b28, + 0x1e281f27, + 0x2435120e, + 0x02003528, + 0xa1823100, + 0xa182aa20, + 0x27000a23, + 0xe34f1800, + 0xa0551808, + 0x7e41081f, + 0x3f1a3334, + 0x276d0f1c, + 0x48314e39, + 0x34122c18, + 0x2941271c, + 0x25481a02, + 0x4f2f5b49, + 0x365c3a2f, + 0x6a01653f, + 0x221e3731, + 0x5afe3991, + 0x11321721, + 0x4d5b2716, + 0x5151221d, + 0x372a4c33, + 0x80675670, + 0x3479823a, + 0x00f4ff55, + 0x000602cc, + 0x00110005, + 0x27273700, + 0x22020f33, + 0x8a9d1826, + 0x464a1808, + 0x50f0230e, + 0x4918f050, + 0x55240c93, + 0xcc000000, + 0x3d84b782, + 0x37373325, + 0x18171733, + 0x200b8349, + 0x454a1867, + 0xf050260c, + 0x940150f0, + 0x424a1824, + 0x00022207, + 0x26f58230, + 0x0026026f, + 0x82240018, + 0x3e26277b, + 0x26343503, + 0x5b432223, + 0x404a1808, + 0x1606330f, + 0x2b1d2a28, + 0x28323e2c, + 0x47344f1f, + 0x2a2b1e56, + 0x4a180418, + 0x2033083f, + 0x2823232e, + 0x312a1d1c, + 0x44251d30, + 0x2532253a, + 0x891d2821, + 0x000226aa, + 0x01e0ff3a, + 0x84a98279, + 0x3d4a186b, + 0x18372010, + 0x200ea1e8, + 0x215e85d7, + 0x73844905, + 0x842b2c21, + 0x19282873, + 0x18192323, + 0x87202323, + 0x2373895f, + 0xb401261c, + 0xff2fd888, + 0x015000ff, + 0x02a8005a, + 0x0406025d, + 0x85ab008b, + 0x5901210f, + 0x8c200f84, + 0x39260f84, + 0xbb005701, + 0x1f826302, + 0x0f848d20, + 0x2f823f20, + 0x6602c122, + 0x8e200f82, + 0x1f820f84, + 0x026c0127, + 0x04060063, + 0x820f848f, + 0x7201231f, + 0x0f826602, + 0x0f849020, + 0x00292408, + 0x010f01ef, + 0x0406022e, + 0x00140097, + 0x00290001, + 0x017301f3, + 0x0003002c, + 0x21353700, + 0x4a012915, + 0x853939f3, + 0x86022117, + 0x0221178a, + 0x2617855d, + 0x0182ff52, + 0x18760209, + 0x2d1b1b48, + 0x6dba537e, + 0x1854b96d, + 0x5d5db64f, + 0x4b824eb7, + 0x82ff2624, + 0x3386dd00, + 0x161b4818, + 0x4e187e2d, + 0xb65d5db7, + 0xb954184f, + 0x82ba6d6d, + 0xff5e2733, + 0x0211019a, + 0x4818005d, + 0x66270e1b, + 0xfd2fc302, + 0x82002f9b, + 0xff1f2421, + 0x86d1009a, + 0x18352021, + 0x26091b48, + 0x65022f66, + 0x833dfd2f, + 0x86222021, + 0x1b481843, + 0x3632240d, + 0x18263435, + 0x08331b48, + 0x44316623, + 0x1c243e26, + 0x2e34012e, + 0x273d251b, + 0x222f3144, + 0x223a2128, + 0x0408322f, + 0x222e3209, + 0x2328203b, + 0x2197852f, + 0x97820d01, + 0x23194818, + 0x48183320, + 0x31082119, + 0x28232f66, + 0x2e223b20, + 0x08040932, + 0x3a222f32, + 0x2f222821, + 0x3d274431, + 0x342e1b25, + 0x241c2e01, + 0x3144263e, + 0x2300ffff, + 0x4d017f01, + 0x07021d03, + 0xfa826206, + 0x11828b20, + 0x8b015726, + 0x1103ec00, + 0x63201182, + 0x28241186, + 0x40018b01, + 0x64202384, + 0x35831186, + 0x11843f20, + 0x11866520, + 0x23822a20, + 0x35845020, + 0x238a6620, + 0x11844320, + 0x11866720, + 0x6b822d20, + 0x35844620, + 0x11866820, + 0x35823220, + 0x69202385, + 0x6b85238a, + 0x11866a20, + 0x35822720, + 0x6b201185, + 0x1e261186, + 0x5101ae01, + 0xa182f402, + 0x00005b24, + 0xb3824302, + 0x37021e22, + 0x6c201182, + 0x5c201182, + 0x01211187, + 0x201182e3, + 0x201182c0, + 0x2611865d, + 0x003c0141, + 0x825e03c6, + 0x886c2011, + 0x003c2259, + 0x201184ac, + 0x2611866d, + 0x0083012b, + 0x82e20186, + 0x866e2023, + 0x01212411, + 0x84900017, + 0x866f2011, + 0xff232611, + 0x004d0143, + 0x053141e1, + 0x824fff21, + 0xff57267d, + 0x00ec004f, + 0x053141d5, + 0x28241184, + 0x40014fff, + 0x64222384, + 0x11840000, + 0x3f203583, + 0x65201184, + 0x2a201186, + 0x50202382, + 0x66203584, + 0x4320238a, + 0x67201184, + 0x2d201186, + 0x46206b82, + 0x68203584, + 0x32201186, + 0x23853582, + 0x238a6920, + 0x6a206b85, + 0x27201186, + 0x11853582, + 0x11836b20, + 0x0001002f, + 0x016bff1e, + 0x00b10051, + 0x1700000b, + 0x09a54f35, + 0x7d7d9b2c, + 0x957e7e38, + 0x88883589, + 0xde828935, + 0xf4202782, + 0x29222782, + 0x27830300, + 0x1e152127, + 0x350c3301, + 0x22e18235, + 0x82a0ff1e, + 0x027d2817, + 0x005c0626, + 0x82060054, + 0x82ac2005, + 0xff412615, + 0x01c60000, + 0x05514122, + 0x2720e584, + 0xac201182, + 0x6d201184, + 0x23827983, + 0x47ff2b26, + 0xa6ff8600, + 0x84055141, + 0xfe212423, + 0x849000db, + 0x846f2011, + 0x0002289d, + 0x01f4ff23, + 0x1892014d, + 0x241dd954, + 0x525243b8, + 0x38038343, + 0x26303026, + 0x0c303027, + 0x6c62646c, + 0x6c64626c, + 0x4e4e4f33, + 0x4e4e4d4d, + 0x26e7824f, + 0x00000057, + 0x498601ec, + 0xac2d0cbf, + 0x142c2155, + 0x2a340134, + 0xfe0f1306, + 0x20e5837a, + 0x20048228, + 0x216f8240, + 0x54180017, + 0x270814d1, + 0x15330706, + 0x285e5b34, + 0x112a1923, + 0x28431726, + 0x4126473b, + 0x5225a52a, + 0x2c262c67, + 0x22231821, + 0x253e402a, + 0x372b4845, + 0xb9836f82, + 0x49823f20, + 0x0c236918, + 0x26343522, + 0x0814b749, + 0x15161645, + 0x2fb40614, + 0x122b174b, + 0x2e201f32, + 0x38323940, + 0x28162027, + 0x3e1a2711, + 0x264a3228, + 0x5233211e, + 0x21212b0c, + 0x22241f1b, + 0x28292322, + 0x1b221c1e, + 0x231d2214, + 0x30223237, + 0x2731080e, + 0x00003f36, + 0x822a0002, + 0x825020bb, + 0x052b08e1, + 0x00001000, + 0x37353337, + 0x35170723, + 0x33373523, + 0x23153315, + 0x046f6d15, + 0xb2323204, + 0x3a3a48a4, + 0x516d4696, + 0xfd2168f8, + 0x82682ef0, + 0x83002032, + 0x824320a9, + 0x5a1e2037, + 0x22230f1f, + 0x82270706, + 0x1823203d, + 0x3908e05e, + 0x174934b7, + 0x2230132b, + 0x242e2d23, + 0x1f102317, + 0x0ba0d512, + 0x3511200e, + 0x9d85514b, + 0x2825312f, + 0x170e122e, + 0x065f38bc, + 0x3c3f4409, + 0x2a95834b, + 0x01f4ff2d, + 0x00920146, + 0x8224000b, + 0x21528295, + 0x76531616, + 0xa4491805, + 0x06d54e08, + 0x4b360721, + 0x3a080599, + 0x2816bf06, + 0x24300517, + 0x20262720, + 0x48625245, + 0x1a102d22, + 0x2b14210e, + 0x372b053f, + 0x3b223f3b, + 0x3a1813c6, + 0x23232d3a, + 0x5c69d22c, + 0x0c126b6e, + 0x480e0a2d, + 0x3845284a, + 0x83233c25, + 0x823220cd, + 0x08cd8304, + 0x00000c27, + 0x37023e33, + 0x15213523, + 0x8307020e, + 0x28321a04, + 0x2f1101c9, + 0x44041634, + 0x3736676e, + 0x736f3c24, + 0x03000044, + 0x209f8300, + 0x289f8240, + 0x00250019, + 0x17000031, + 0x744d1822, + 0x4990850a, + 0x6646068c, + 0x22232d05, + 0x16141506, + 0x35363217, + 0x27262634, + 0x52080b83, + 0x2e4c3db6, + 0x4721191c, + 0x28483532, + 0x4f272214, + 0x26141624, + 0x3225191b, + 0x1c2e200c, + 0x2b361b2e, + 0x252c410c, + 0x11041038, + 0x382f1f29, + 0x2e222f38, + 0x3111040e, + 0xeb412f23, + 0x1a132611, + 0x1e181f1e, + 0x1c27c722, + 0x0b131c18, + 0x2a1a3120, + 0x27000200, + 0x8301f4ff, + 0x000b228f, + 0x097d4924, + 0x7e492620, + 0x0637220c, + 0x41a58423, + 0x2a080630, + 0x17242762, + 0x31041629, + 0x34281f25, + 0x1b112d22, + 0x2c14210e, + 0x372b043f, + 0x3b22403a, + 0x62524624, + 0x2d220f01, + 0x3a3a1813, + 0x41c2fe2d, + 0x4b35052d, + 0x26374629, + 0x5c69233b, + 0x00006b6e, + 0xff410001, + 0x01c600b1, + 0x117f47d3, + 0x2d2b9937, + 0x262d2b2d, + 0x4f262121, + 0x5455803d, + 0x3a163d7f, + 0x7d43427e, + 0x2033823c, + 0x20338227, + 0x473386ac, + 0x56210c7f, + 0x312f832f, + 0x2d2d292f, + 0x7d3c164f, + 0x3a7e4243, + 0x547f3d16, + 0x33828055, + 0xf8ff2b27, + 0x57008600, + 0xdf541800, + 0x1459300e, + 0x14141a1a, + 0x1a081919, + 0x1a1a1615, + 0x831a1516, + 0xff212493, + 0x8290008c, + 0x0011232b, + 0x52181700, + 0x25081079, + 0x221e1031, + 0x1c110503, + 0x1c19131c, + 0x0b257433, + 0x15011c28, + 0x25191515, + 0x00452c24, + 0x2300ffff, + 0x4d01fe00, + 0x85459c02, + 0x0a012105, + 0x57261182, + 0xec000a01, + 0x85459002, + 0x24118405, + 0x010a0128, + 0x20238440, + 0x836e8264, + 0x20358323, + 0x2011843f, + 0x20118665, + 0x2023822a, + 0x20358450, + 0x20238a66, + 0x20118443, + 0x20118667, + 0x206b822d, + 0x20358446, + 0x20118668, + 0x85358232, + 0x8a692023, + 0x206b8523, + 0x2011866a, + 0x85358227, + 0x866b2011, + 0x00412611, + 0x02c600bb, + 0x052f45dd, + 0x2720a184, + 0xac201182, + 0x6d201184, + 0x2b262386, + 0x86000201, + 0x2f456101, + 0x24238405, + 0x00960021, + 0x20118490, + 0x3023866f, + 0x01830125, + 0x02d4022a, + 0x009b0606, + 0x00ffff00, + 0x200f8221, + 0x200f8442, + 0x200f84bd, + 0x200f821e, + 0x2c0f844e, + 0x000000a9, + 0x01ffff02, + 0x036d018b, + 0x8745183b, + 0x89270817, + 0x0b137e13, + 0x0a020b15, + 0x48939516, + 0x9d274393, + 0x3e790227, + 0x2348243e, + 0xeefe4625, + 0x50feb001, + 0x00007f7f, + 0x82390003, + 0x826f2045, + 0x000f2745, + 0x00210018, + 0x5d7b1300, + 0x1827200e, + 0x36102177, + 0x55438639, + 0x34302626, + 0x3e51495d, + 0x31312f35, + 0x3b364940, + 0x8249373a, + 0x30b03646, + 0x0b341f3a, + 0x2c330802, + 0x24f93f40, + 0xfe1e2222, + 0x262b27b1, + 0x21de8224, + 0xbb822000, + 0x43036822, + 0x64063f58, + 0x3d440719, + 0x14152206, + 0x08658216, + 0x06173733, + 0x5737e106, + 0x375a3433, + 0x23133e29, + 0x3c1a2912, + 0x1e3c474a, + 0x19231330, + 0x34830143, + 0x65464664, + 0x27162037, + 0x4d5c1511, + 0x16185b4f, + 0x00201e26, + 0x20bd8402, + 0x22bd827a, + 0x89100008, + 0x852320bb, + 0x232339b4, + 0x6c657039, + 0x3034636b, + 0x2e934948, + 0xb0018b01, + 0x7169686e, + 0xa3525632, + 0xf7839183, + 0x39823f20, + 0x37830b20, + 0x70152121, + 0x392607b4, + 0xa4c10001, + 0x2d83c7a4, + 0x347f3526, + 0x01003494, + 0x3a206384, + 0x09202982, + 0x3925298b, + 0xa5c20101, + 0x222684a5, + 0x82bd348a, + 0x20e18325, + 0x20e18272, + 0xc74b181f, + 0x08e18d0c, + 0x35233522, + 0x06061533, + 0x345b39e8, + 0x2c3b5d35, + 0x1024143f, + 0x4c40202b, + 0x28174449, + 0x1692590c, + 0x35830148, + 0x6426e682, + 0x28142137, + 0xe6821611, + 0x0b0c5c27, + 0x15b9336b, + 0x83af871d, + 0x2faf84e9, + 0x35331533, + 0x35231133, + 0x3f391523, + 0xc33f3fc3, + 0xb2258783, + 0xc850feb2, + 0x21af85c8, + 0xaf827800, + 0x89820320, + 0x11331124, + 0x1d833f39, + 0x8250fe21, + 0x01122419, + 0x820a0183, + 0x840e2019, + 0x372726a3, + 0x36323316, + 0x3a228235, + 0x2b8c0614, + 0x1b2c143b, + 0x3f22222e, + 0x2483013b, + 0x292f1f22, + 0xfe290130, + 0x855139d2, + 0x8301214f, + 0x0c203582, + 0x15284f84, + 0x07333733, + 0x07272313, + 0x02277a82, + 0x9d8846ae, + 0x83487e45, + 0xd2d22760, + 0xdbf5fea5, + 0xab878754, + 0x31823420, + 0x31840520, + 0x82331121, + 0x84bc202a, + 0x41842084, + 0xae20074f, + 0x19201d82, + 0x0dcb4a18, + 0x36342108, + 0x07072337, + 0x23272723, + 0x15151616, + 0x1f534939, + 0x49501e03, + 0x0302063b, + 0x52215123, + 0x06020224, + 0xe1314283, + 0xfee15656, + 0x481de150, + 0xd9d9601c, + 0x1d481c60, + 0x20a186e1, + 0x20518276, + 0x67518413, + 0x2321086e, + 0x2c4b8603, + 0x032e9742, + 0x413a0502, + 0x02022f97, + 0x3a888404, + 0x4a205af9, + 0x50fed423, + 0x21590701, + 0x00d72246, + 0x01200002, + 0x039b0183, + 0x420f0043, + 0x31710ea3, + 0x37dd2710, + 0x56303056, + 0x05833837, + 0x4439383f, + 0x44383944, + 0x37830144, + 0x64454665, + 0x45633635, + 0x36376546, + 0x5b4d4f5d, + 0x5d4f4d5b, + 0x06a14200, + 0x9b826720, + 0x12000a22, + 0x210aa142, + 0x4d181523, + 0x393807be, + 0x5c5a498b, + 0x6c454c47, + 0x01453636, + 0x3ab0018b, + 0xa7424647, + 0x222c56d9, + 0x1f243b82, + 0xa5011e01, + 0x0b229382, + 0x3b822600, + 0x18363221, + 0x2108595b, + 0x45182217, + 0x0621178d, + 0x259286dc, + 0x13543ec0, + 0xa8855947, + 0x0f45542d, + 0x160f2338, + 0x220a0c09, + 0x855fb701, + 0x995f269c, + 0x770b2d3a, + 0x29b4855e, + 0x1c0e755c, + 0x30030419, + 0xb1860604, + 0xb1827020, + 0x15000d22, + 0x0723b189, + 0x8a272317, + 0x438d2db4, + 0x6e2b3458, + 0x464c6547, + 0x46323365, + 0x3734b783, + 0x0c3e3144, + 0xe4b2b2ba, + 0x00212850, + 0x1a000100, + 0x4c018301, + 0x2720bb82, + 0x21076b42, + 0xc0843316, + 0x12572720, + 0x384d1805, + 0x1748080c, + 0x15161617, + 0x2eb50614, + 0x18251e4f, + 0x2c292140, + 0x203f1f28, + 0x263d5139, + 0x15211845, + 0x29231f30, + 0x293f192d, + 0x83015030, + 0x192a1e22, + 0x201d251b, + 0x0e1c0d1b, + 0x42322f33, + 0x1227181e, + 0x1d1c2016, + 0x111c0b1c, + 0x49372d31, + 0x11207782, + 0x54208c82, + 0x0720bd82, + 0x09b94e18, + 0x01839424, + 0x16828243, + 0x35357b24, + 0x9b8385fe, + 0x9b823820, + 0x23827820, + 0x9b841220, + 0x33353522, + 0x84058144, + 0x06063b08, + 0x3e5948d9, + 0x392a2b38, + 0x0148293c, + 0xfa695583, + 0x39394cfd, + 0x46fafd4c, + 0x3b822553, + 0x82feff21, + 0x825c2048, + 0x820d203b, + 0x3303213b, + 0x09777918, + 0x8c8a032e, + 0x120b4542, + 0x110c030c, + 0x8a40430b, + 0xb0322582, + 0x264325e4, + 0xe4254326, + 0x010050fe, + 0x8b010d00, + 0x37820102, + 0x378e2120, + 0x2321418a, + 0x07625727, + 0x5b682108, + 0x0c072b41, + 0x0e070306, + 0x3b383b08, + 0x02080f08, + 0x2c070b06, + 0x3f4b5a3c, + 0x02050a06, + 0x3d050b05, + 0xe5235f83, + 0x82234523, + 0xe5e52e02, + 0x23234622, + 0xfee52246, + 0x3019f950, + 0x20028219, + 0x206f82f9, + 0x20218208, + 0x06654352, + 0x8a273721, + 0x170721a8, + 0x33086789, + 0x45767f08, + 0x0a0f0838, + 0x070f0903, + 0x7f774336, + 0x12083c45, + 0x1209030b, + 0x8b013c08, + 0x0f6ad1df, + 0x1d14141d, + 0xdcd46a0f, + 0x13211170, + 0x70112113, + 0xfdff0100, + 0x43205782, + 0x0f205782, + 0x2a19c782, + 0x813d0ecf, + 0x0b374284, + 0x0b030b14, + 0x41350a15, + 0xa58b0183, + 0x18760b01, + 0x2e19192e, + 0xf5fe7618, + 0x209382a5, + 0x203b821b, + 0x0649454c, + 0x2313353d, + 0x03152135, + 0xe21b1533, + 0xe11b01ce, + 0x258b01e3, + 0x26355601, + 0x0034aafe, + 0x47000200, + 0x0023060b, + 0x41220019, + 0x342105a3, + 0x05c17236, + 0x0807d451, + 0x27231546, + 0x27060623, + 0x06353732, + 0x16141506, + 0x60372c88, + 0x231a0167, + 0x1714371a, + 0x3c274519, + 0x04073237, + 0x270d3214, + 0x1f3d4d2b, + 0x2b338301, + 0x200a3835, + 0x2b0d1529, + 0x3f461b0f, + 0x1b1225c4, + 0x08552831, + 0x19191c27, + 0x342a6b83, + 0x55018301, + 0x13005f03, + 0x6b841f00, + 0x19232721, + 0x0816cb2a, + 0x16150735, + 0x3116c916, + 0x30060414, + 0x3117033e, + 0x27433f1c, + 0x31242e40, + 0x2b272a27, + 0x83012914, + 0x01201315, + 0x133a7ed4, + 0x374a591a, + 0x4033294e, + 0x2b3c343b, + 0x820f10a1, + 0x821e20f7, + 0x02222461, + 0x841a00d4, + 0x4a71185f, + 0x057a420d, + 0x17372f08, + 0x43b80606, + 0x29482b57, + 0x1e0f3123, + 0x29161c0f, + 0x1a2b3638, + 0x111a0e22, + 0x58830133, + 0x284b3650, + 0x0c280d16, + 0x3435410c, + 0x280b1041, + 0xb783170f, + 0x55822120, + 0xb7844220, + 0x578c2020, + 0x33352723, + 0x061d4111, + 0x35373624, + 0xf64a2626, + 0xaa330805, + 0x40284940, + 0x142c1a24, + 0x07323e03, + 0x0e2d1303, + 0x14142414, + 0x33231227, + 0x5b83012b, + 0x27493353, + 0x77381113, + 0x12232cfe, + 0x14153319, + 0x3d0f11a2, + 0x83403b33, + 0x821c2065, + 0x82362065, + 0x001821bb, + 0x1625658c, + 0x07061415, + 0xea4f1823, + 0x33272208, + 0x08688434, + 0x5c42ba40, + 0x32284529, + 0x0202183a, + 0x2d3803d9, + 0x18112a17, + 0xa7833917, + 0x241d220e, + 0x57830130, + 0x294c3451, + 0x0a20452f, + 0x38310b0e, + 0x0f280c0e, + 0x2b16c314, + 0x0100311c, + 0x8b011300, + 0x6a03dc00, + 0xb5431600, + 0x18372005, + 0x080cc1bb, + 0x1533152f, + 0x2d401123, + 0x2034302d, + 0x12070d18, + 0x4416160c, + 0x018b0144, + 0x2a022f10, + 0x2e0a4232, + 0x1d210402, + 0xf0fe312e, + 0x00030000, + 0x01f8001e, + 0x2ead824c, + 0x0039002d, + 0x37000048, + 0x34352622, + 0x4c263537, + 0x17200c17, + 0x16204e82, + 0x2329bf83, + 0x06272622, + 0x16141506, + 0x052c4c33, + 0x61450320, + 0x840b850b, + 0x08218222, + 0x4a3ca46e, + 0x17100d2e, + 0x4b1b100d, + 0x6e161d33, + 0x480d0a3e, + 0x0c190b32, + 0x1f190b08, + 0x5a383b3e, + 0x27271b4c, + 0x26261d1b, + 0x21362c25, + 0x1708351e, + 0xf8301f0b, + 0x1c2a2a2c, + 0x131a0804, + 0x04091e13, + 0x361c2d0d, + 0x0a30093d, + 0x3c341220, + 0x11060604, + 0x2510100b, + 0x01432d2a, + 0x21212721, + 0x21222425, + 0x1725f627, + 0x03011014, + 0x1b191a16, + 0x34000100, + 0x4123dd82, + 0x46005f03, + 0x152005cf, + 0x3506c34d, + 0x34352315, + 0x07222326, + 0x033e3415, + 0x38203814, + 0x26173e2e, + 0x2a822f25, + 0x7dd42108, + 0x46201543, + 0x26c2cb38, + 0x00e52f2c, + 0x2a000200, + 0x7e008b01, + 0x03005903, + 0x00000f00, + 0x11331113, + 0x260b4b55, + 0x121e3e34, + 0x82121818, + 0x343a8203, + 0x01bffe41, + 0x1110177f, + 0x10111717, + 0xff020017, + 0x00fa00e6, + 0x25398280, + 0x001b000f, + 0x4b183700, + 0x43820945, + 0x13061422, + 0x2c0ad055, + 0x0b161017, + 0x0a0c060d, + 0x2b3e1017, + 0x2f4f860d, + 0x310404fa, + 0x1d1f0303, + 0xa1fe6301, + 0x10023d36, + 0xd1855788, + 0xd1824c20, + 0x27054348, + 0x33373311, + 0x27231707, + 0x0427ca83, + 0x7e704583, + 0x82385d45, + 0xfed4318c, + 0xbe83a0cd, + 0x00514394, + 0x34000100, + 0x99008301, + 0xab483182, + 0x18352005, + 0x3a08b4ba, + 0x24750617, + 0x07093e1d, + 0x09040703, + 0x2b83010d, + 0xfe8b0126, + 0x010b0e70, + 0x84062f01, + 0x018b2635, + 0x00d402ff, + 0x26f78420, + 0x36363317, + 0x83173233, + 0x08776104, + 0x46410720, + 0x05323109, + 0x21301404, + 0x35171644, + 0x3e2f3620, + 0x2c222318, + 0x21210482, + 0x2689822c, + 0x1f162d41, + 0x4124183c, + 0x58410753, + 0x20c58505, + 0x415d8241, + 0x5d850597, + 0x342d588a, + 0x15040631, + 0x2e382037, + 0x2625173e, + 0x4146862f, + 0xc14b0b97, + 0x21634806, + 0x4629b623, + 0x08028329, + 0x2a2a4522, + 0x2f292945, + 0x3029292f, + 0x28830130, + 0x4c36354b, + 0x364c2727, + 0x33284b35, + 0x41353441, + 0x41343541, + 0x2205c144, + 0x84550101, + 0x8a1f2097, + 0x15162bf7, + 0x23060614, + 0x17272622, + 0xcd423715, + 0x07223505, + 0x34161615, + 0x14030731, + 0x433f1d33, + 0x16254027, + 0x4e041431, + 0x2f08c144, + 0x25cb0101, + 0x4a591b12, + 0x13294e37, + 0xb5683f12, + 0x2608c144, + 0x01210002, + 0x82420101, + 0x00122761, + 0x0100001e, + 0x58843735, + 0x2605c844, + 0x33373317, + 0x44322711, + 0x30080969, + 0x12030401, + 0x4a401a30, + 0x34244128, + 0x30060426, + 0x1326268a, + 0x34221228, + 0x7001012b, + 0x5916123a, + 0x284c354f, + 0x35fe2028, + 0x11a525b5, + 0x37373e10, + 0x05b7413f, + 0x82f10021, + 0x8710205f, + 0x938918bf, + 0x34153c09, + 0x26030732, + 0x0c0c1a35, + 0x15081206, + 0x8b01112c, + 0x40384101, + 0x03023806, + 0x82cb261f, + 0x1300258c, + 0x07018301, + 0x69483b82, + 0x022e2110, + 0x6848a182, + 0x1e46080d, + 0x06141502, + 0x18412490, + 0x1b2f161e, + 0x1c2d1e1c, + 0x3b1d2c16, + 0x14342334, + 0x1721121f, + 0x1c2c1b1b, + 0x401d2d17, + 0x13198301, + 0x1a151029, + 0x0a181713, + 0x1b241709, + 0x0e163626, + 0x190e0e28, + 0x0b16160f, + 0x1e231608, + 0xb182382b, + 0x83011028, + 0x2703e100, + 0xb1821500, + 0x35262222, + 0x0a89f518, + 0x33142508, + 0x06173732, + 0x2b35a006, + 0x34083230, + 0x15315858, + 0x230d0d10, + 0x323e8301, + 0x5b0230a7, + 0x3ea7325b, + 0x08042e08, + 0x3220b983, + 0x3f24b982, + 0x1400cc02, + 0x200d8748, + 0x07c04537, + 0x38992608, + 0x25183e2f, + 0x3e172914, + 0x14030731, + 0x46830137, + 0x26c3cc37, + 0xe519162b, + 0x162dbffe, + 0x0001001f, + 0x018b0108, + 0x20418239, + 0x05554809, + 0x3733172f, + 0x7c033337, + 0x1f3a3e74, + 0x3d3a1f04, + 0x261d8274, + 0x6060b041, + 0x84bffeb0, + 0x018b22b1, + 0x832b82d7, + 0x330322b1, + 0x852b8417, + 0x23033c05, + 0x07232727, + 0x40596907, + 0x1604132c, + 0x1632382f, + 0x3b2b1504, + 0x152b4b57, + 0x832b1502, + 0x5bb32343, + 0x0383b35b, + 0xa3bffe25, + 0x86a35c5c, + 0x822a2077, + 0x8211204b, + 0x27372177, + 0x07214c86, + 0x3f478517, + 0x44636c08, + 0x1b041f29, + 0x69624225, + 0x04232b44, + 0x8b012921, + 0x334299a8, + 0xa1a04233, + 0x45373745, + 0x05223f84, + 0x3f823701, + 0x3f821820, + 0x884c2220, + 0x37372105, + 0x080c4e49, + 0x41060630, + 0x0e0d1217, + 0x09241a0a, + 0x3f3f8307, + 0x04071008, + 0x34070f07, + 0x3a12773d, + 0x32060501, + 0x151c2506, + 0x16a93f01, + 0x2e18192e, + 0xacfea917, + 0x55824132, + 0xab821520, + 0x0d411020, + 0x37353606, + 0x15333523, + 0x15153307, + 0xa7e294a8, + 0x218b01ac, + 0xed2232ee, + 0x20258232, + 0x24258216, + 0x00680324, + 0x467b8215, + 0x2342051a, + 0x154a080d, + 0x543f3186, + 0x133e2d3c, + 0x1f2b0f20, + 0x3a352e29, + 0x21bb8b01, + 0x41403848, + 0x13281624, + 0x28242b1c, + 0x00d5223c, + 0x19000200, + 0xae000000, + 0x0300e601, + 0x00000700, + 0x17333733, + 0x07332703, + 0x450b4519, + 0x45954550, + 0x5a018e8e, + 0x6d828c8c, + 0x5a011922, + 0x00212586, + 0x201f8213, + 0x851b825e, + 0x9cff2e19, + 0xbc00c200, + 0x13009601, + 0x35030000, + 0x05884637, + 0x37363223, + 0x055b4317, + 0xb1643537, + 0x191b0101, + 0x1706140c, + 0x2518220d, + 0x3d130136, + 0x0e1c1446, + 0x73ea1838, + 0x24818208, + 0x01f80008, + 0x20ef8236, + 0x059f5318, + 0x34352623, + 0x0d444136, + 0x1516162b, + 0x32270614, + 0x27343536, + 0x08608423, + 0x2b26a028, + 0x3f701316, + 0x070f073b, + 0x07100703, + 0x146d3c3a, + 0x0f272b15, + 0x0c031b0e, + 0x2cf80e0f, + 0x23301823, + 0x16a61a01, + 0x02821625, + 0xe5fea630, + 0x23173023, + 0x0f13292c, + 0x29172e22, + 0xa8830f10, + 0x011c0027, + 0x03360182, + 0x20f58293, + 0x2375831c, + 0x17372713, + 0x18055d46, + 0x48081852, + 0x70231215, + 0x4823662d, + 0x02261a19, + 0x77286efd, + 0x1e4866fe, + 0x216b8317, + 0x75b08301, + 0x6723ab24, + 0x759c612c, + 0x28771f24, + 0x759818fe, + 0x19000222, + 0x33247582, + 0x1800d402, + 0x2806194a, + 0x36343526, + 0x26263337, + 0x0bb85f23, + 0x27062b08, + 0x23373632, + 0x33a01614, + 0x0202193b, + 0x2d2f02d9, + 0x17122718, + 0x45203517, + 0x2a432752, + 0xa6032f25, + 0x30830124, + 0x0d0b2245, + 0xf4482d0c, + 0x50592d05, + 0x31294b34, + 0x39283130, + 0x21000200, + 0x4a05e551, + 0x5445087d, + 0x17162205, + 0xf9d11833, + 0x14153610, + 0x4940aa16, + 0x1a244128, + 0x0604142c, + 0x04053330, + 0x240e2d13, + 0x07c44928, + 0x34525a2e, + 0x13142849, + 0x23bffe1f, + 0x28341912, + 0x2005c249, + 0x2461823f, + 0x01f90022, + 0x2ec58243, + 0x002a001d, + 0x27223700, + 0x33161637, + 0x45353632, + 0x142011c4, + 0x314aca84, + 0x3ead2b08, + 0x31171737, + 0x022d2b17, + 0xce452c16, + 0x32300805, + 0x31060328, + 0x24143b4f, + 0x12291315, + 0xf92b3323, + 0x0e0e2b24, + 0x2c0d2631, + 0x47581812, + 0x26284932, + 0x3fb4fe1e, + 0x1415cd48, + 0x3b0f1191, + 0x003c3132, + 0x2306d945, + 0x005f0372, + 0x35068d50, + 0x8b013e34, + 0x2cfed401, + 0x2b00ffff, + 0x86008301, + 0x2702c302, + 0x28826e06, + 0x07008b22, + 0x02210783, + 0x2633826c, + 0x00250229, + 0x845202c5, + 0x33352833, + 0x029c2915, + 0x842d2d25, + 0x01272417, + 0x85500233, + 0x15212817, + 0x020a0129, + 0x82292927, + 0x2900253c, + 0x0a022702, + 0xe120198b, + 0x022d1985, + 0xad012900, + 0xad022301, + 0x19000d00, + 0x615d1800, + 0x05ee4907, + 0x0ca1c118, + 0x3921a62e, + 0x32324b23, + 0x2238234b, + 0x212a2a21, + 0x2b080382, + 0x3a1fad01, + 0x46463b26, + 0x1f3a263b, + 0x25232e2e, + 0x23252e2e, + 0x0200002e, + 0x67001a00, + 0x2d02d701, + 0x2a001e00, + 0x27370000, + 0x34352637, + 0x17350582, + 0x17323336, + 0x16071737, + 0x06141516, + 0x27071707, + 0x22230606, + 0x07784727, + 0x15064608, + 0x2c461614, + 0x40242440, + 0x3f30442c, + 0x2c44303e, + 0x14141141, + 0x442c4111, + 0x401d3a17, + 0x46306f2f, + 0x46313046, + 0x412d6746, + 0x31444331, + 0x25462d42, + 0x422d4625, + 0x22233b17, + 0x2d41173b, + 0x26131345, + 0x3c3c4a17, + 0x2c03834a, + 0x34000100, + 0xb50192ff, + 0x2d00ec02, + 0x838f1800, + 0x34352c0b, + 0x3435042e, + 0x33353736, + 0x52161615, + 0x1e210878, + 0x3b8f8304, + 0x5a30de15, + 0x4d202620, + 0x2837382e, + 0x28404740, + 0x303c4150, + 0x1c2c1b43, + 0x362e2935, + 0x2b081084, + 0x636e4754, + 0x391d2b05, + 0x2e39271c, + 0x23263429, + 0x4331402b, + 0x63650a59, + 0x311d2a05, + 0x2c341e1b, + 0x22222f24, + 0x4736462d, + 0x00650a5d, + 0x35208182, + 0xc5240482, + 0x2a008a02, + 0x24086b59, + 0x37352327, + 0xc55d1833, + 0x076c4b12, + 0x15074308, + 0x33361521, + 0x64030437, + 0x110a1243, + 0x4c355367, + 0x3013301a, + 0x0f393622, + 0x02929f09, + 0x011e2003, + 0x601c3219, + 0x0d1c0e38, + 0x3e200434, + 0x2b63551f, + 0x1e172f20, + 0x3c1f3441, + 0x1c0d3820, + 0x1f47340f, + 0x74824704, + 0x82170021, + 0x02da2404, + 0x831d007e, + 0x35232379, + 0x03823533, + 0x820c3846, + 0x83152070, + 0xcf290803, + 0x8da2a2a2, + 0x0f4e56a3, + 0x1104101d, + 0x544e0f1d, + 0xa3a38ea4, + 0x41309ea3, + 0xab40012f, + 0x23234321, + 0xfeab2143, + 0x30412fc0, + 0x87cf829e, + 0x82152055, + 0x92112055, + 0xcf112451, + 0x8aaa94a2, + 0x95ab274b, + 0x300101a3, + 0x48884d01, + 0xfe30b323, + 0x364783ff, + 0xeb01f4ff, + 0x31008a02, + 0x22050000, + 0x35232726, + 0x35342637, + 0x82373434, + 0x36362108, + 0x28096646, + 0x21153307, + 0x14151406, + 0x058b4c14, + 0x32336208, + 0x06173736, + 0x5a3f0106, + 0x3b40117d, + 0x403b0101, + 0x2d628311, + 0x15311a4e, + 0x50422032, + 0xfefefe0d, + 0xd5da0101, + 0x253d4e0d, + 0x21311938, + 0x75820c54, + 0x1209042b, + 0x07110809, + 0x8576052c, + 0x1a2f212d, + 0x31566321, + 0x0a080e07, + 0x55300913, + 0x2c222560, + 0x0000322b, + 0xff3d0002, + 0x02c601df, + 0x001b008d, + 0x258f8222, + 0x35262635, + 0x1f423634, + 0x1127210a, + 0x77820d82, + 0x77150721, + 0x4c0806ff, + 0x70590601, + 0x34385c35, + 0x2817402c, + 0x201a2d14, + 0x1d241434, + 0x3fab2748, + 0x21403738, + 0x6a7a0b68, + 0x083c6445, + 0x2202676a, + 0x17123416, + 0x02a8fe01, + 0x1a34121b, + 0x01670322, + 0x0d584357, + 0x580d4f01, + 0x00010000, + 0x019fff12, + 0x009c02ce, + 0x08cb7224, + 0x83373621, + 0x373321fe, + 0x080b0041, + 0x07070648, + 0x07231533, + 0x2e5b020e, + 0x1b170f1b, + 0x1808292f, + 0x06194557, + 0x16504d0b, + 0x0a120e2a, + 0x261e131b, + 0x7e070414, + 0x23071a85, + 0x3e0f6143, + 0xdb4c500a, + 0x6438043b, + 0x3f070b68, + 0x3b250905, + 0xed3f3f22, + 0x00345c3d, + 0xe3820300, + 0xde01922a, + 0x0900ec02, + 0x37003100, + 0x222a8082, + 0x16030706, + 0x26261317, + 0xef843703, + 0x33373729, + 0x33323607, + 0x82171632, + 0x16162608, + 0x27260717, + 0x08f68603, + 0x37230736, + 0x03072726, + 0x06131714, + 0x073e0106, + 0x193c070e, + 0x0f073e1f, + 0x433a109c, + 0x260c5b6c, + 0x050c050c, + 0x0c091209, + 0x29180e26, + 0x15133110, + 0x1733203c, + 0x33501f30, + 0x3f081982, + 0x3e0d1d1c, + 0x36333633, + 0x01014802, + 0x041208fe, + 0x02020c02, + 0x26834afd, + 0xa9866b98, + 0x01636916, + 0x72660202, + 0x2e14230b, + 0x06fe0f18, + 0x2c1f2304, + 0x62033228, + 0x710b0363, + 0x4987af01, + 0x8119c801, + 0x820a4143, + 0x353327b3, + 0x34353636, + 0x41433534, + 0x1c484305, + 0x15331728, + 0x15141423, + 0x4e430614, + 0x456b2a06, + 0x05080420, + 0x05093d54, + 0x0a524307, + 0xad040628, + 0x020705a0, + 0x55438d92, + 0x02022c07, + 0x0f052c01, + 0x052c0f1d, + 0x43132413, + 0x132a085a, + 0x0e311223, + 0x01310f1e, + 0x5e430203, + 0x00053905, + 0x0100000b, + 0x007e02e3, + 0x001f0003, + 0x00290023, + 0x1300002f, + 0x03273317, + 0x03849b83, + 0x33173323, + 0x05945c35, + 0x15308982, + 0x15232723, + 0x23273337, + 0x27331527, + 0x17172335, + 0x87250583, + 0x35372f0c, + 0x2400824b, + 0x41575954, + 0x3c008248, + 0xcf5c5454, + 0x9c2c0b04, + 0x8c39154d, + 0x48023604, + 0xb2b23302, + 0x26f0cdfd, + 0x05253c05, + 0x300082fd, + 0xf02b3c2a, + 0xa64af0f0, + 0x013b2651, + 0x1a220e2e, + 0x207d8200, + 0x2087820a, + 0x248782e4, + 0x00180012, + 0x0593431e, + 0x33353726, + 0x17161632, + 0x41087682, + 0x23230606, + 0x33151115, + 0x03232626, + 0x37363233, + 0x49495323, + 0x3c5d3b79, + 0x093e3e06, + 0xb52a577a, + 0x20414d07, + 0x074d4120, + 0x33a101b5, + 0x4920a505, + 0x5558383c, + 0x6c4502f4, + 0xe8fe313b, + 0x0400393b, + 0x5d82f1ff, + 0x5d82fd20, + 0x1d000522, + 0x0030e584, + 0x27330713, + 0x03032327, + 0x03373523, + 0x37331333, + 0x1322e582, + 0x6a820333, + 0x82230321, + 0x33272301, + 0xdc833737, + 0x48080583, + 0x042b03e6, + 0x2897040f, + 0x4d274147, + 0x48233f1d, + 0x471d4123, + 0x26413b25, + 0x28372959, + 0x0f0d0427, + 0x04e30a35, + 0x0f370a0b, + 0x1b1a7401, + 0x01e9fda2, + 0x0104262f, + 0xfcdcfe25, + 0xfe2401fc, + 0xd1fe2bdc, + 0xd1fe2f01, + 0x6969883e, + 0x82038288, + 0x844420e7, + 0x009922e7, + 0x05bf791b, + 0x1b5c3720, + 0x27172108, + 0x2008d05f, + 0x07cd5107, + 0x0809624d, + 0x21350746, + 0x5548e115, + 0x252a4b2e, + 0x9204192f, + 0x4e4e4692, + 0x1603063a, + 0x2e331539, + 0x2a1c2819, + 0x0172343c, + 0x5b626e67, + 0x182c5037, + 0x31225316, + 0x052c4343, + 0x162b53fe, + 0x9b353b1f, + 0x32441316, + 0x31a9463d, + 0x00040031, + 0x20076541, + 0x227d821e, + 0x4132002d, + 0x23260767, + 0x33353735, + 0x9b441632, + 0x14152305, + 0x73410714, + 0x34132907, + 0x15232726, + 0x27363633, + 0x23077c41, + 0x49532337, + 0x55080082, + 0x15704c79, + 0x01013f47, + 0x13463e01, + 0xb72a4d72, + 0xb5b50101, + 0xa9b70101, + 0x20334610, + 0xab206b20, + 0x05247901, + 0x7804253b, + 0x07294137, + 0x0d070911, + 0x42432906, + 0x09bc01f4, + 0x063b0711, + 0x223f900d, + 0x4ce8fe1d, + 0x2f000100, + 0xcc0192ff, + 0x2300ec02, + 0x35050000, + 0xcc46022e, + 0x16450811, + 0x37363233, + 0x33352335, + 0x15070611, + 0x5f3f0301, + 0x3c617336, + 0x3119472a, + 0x52223416, + 0x1d4c5657, + 0xb0650d32, + 0x646e523b, + 0x608d5308, + 0x6510ad8c, + 0x1f2c0463, + 0x8e211b2e, + 0x168e7b79, + 0xfe45a90f, + 0x64093ef2, + 0x06a74500, + 0x8a02d924, + 0x69823900, + 0x83262221, + 0x82f48268, + 0x853720d8, + 0x34352106, + 0x410de349, + 0x05820501, + 0xa64b2120, + 0x015d080b, + 0x0a67550f, + 0x2a444e08, + 0xb8132710, + 0x2018b345, + 0x33252930, + 0x4b1d2b1a, + 0x115d4b37, + 0x148c600e, + 0xfee1152c, + 0x38130fec, + 0x1d462934, + 0x0c5e2125, + 0x2a194c55, + 0x14052b13, + 0x052c0f20, + 0x241f3115, + 0x2e1a1f30, + 0x46532d20, + 0x3114311d, + 0x30112012, + 0x271c2c13, + 0x361b2733, + 0x00002d21, + 0x06d94402, + 0xbd45e920, + 0x0e0f4107, + 0x0811bc45, + 0x62411752, + 0x34647637, + 0x3119472a, + 0x1d1c2b12, + 0x1d301630, + 0x45b92e48, + 0x6e454040, + 0x8f520763, + 0x0fae8c61, + 0x2c035f62, + 0x1f182f1f, + 0x05f1fd03, + 0x252c1c24, + 0x01640630, + 0x0d8c6faf, + 0x88100a02, + 0x48000100, + 0xc3010000, + 0x1c007e02, + 0x35370000, + 0x37363233, + 0x26059144, + 0x21352323, + 0x43162315, + 0x2f08057a, + 0x27231307, + 0x54484748, + 0xa045e704, + 0x4742520a, + 0x3c8e7b01, + 0x0442440e, + 0x5ebc4153, + 0x3a43fcb2, + 0x2e052c3c, + 0x20314426, + 0x574b3147, + 0xfcfcfe0f, + 0x00255282, + 0x01f2ff0f, + 0x285782d1, + 0x17000020, + 0x37270711, + 0x24038335, + 0x17371533, + 0x2f038407, + 0x3435023e, + 0x16372726, + 0x06061415, + 0x64135173, + 0x54230282, + 0x82b0139d, + 0x2c290802, + 0x04013c5a, + 0x9e5c0746, + 0x2a0b010c, + 0x2a48332b, + 0xa5ce332c, + 0x485d2b53, + 0xe65c2c54, + 0x34482602, + 0x120e1508, + 0x6f541920, + 0x06cf6935, + 0x6582cd20, + 0x00001726, + 0x35073533, + 0x03826582, + 0x1522ba84, + 0x69821537, + 0xcf210382, + 0x24008282, + 0xacac01ae, + 0x24008281, + 0x443544c1, + 0x30038248, + 0xa44040cb, + 0x48453545, + 0xe9443545, + 0x00020000, + 0x83b28221, + 0x00082247, + 0x0611430c, + 0x1139fd82, + 0x15213501, + 0x0146aecf, + 0x00ffac66, + 0xda01ac01, + 0xfe30042c, + 0x314d0226, + 0x20318231, + 0x2031820a, + 0x207982a7, + 0x223b8318, + 0x84233533, + 0x11372177, + 0x0a5f4318, + 0x18153321, + 0x210a845f, + 0x00824953, + 0x3f784608, + 0x643a3964, + 0xcaca293e, + 0x4f4f4820, + 0x2ba62048, + 0x042c3d05, + 0x4f243b01, + 0x2752403f, + 0x01a6303d, + 0x45414443, + 0xff010038, + 0x00f4ff59, + 0x009c02fb, + 0x07000003, + 0xa7013301, + 0xfe386a01, + 0xa8020c96, + 0xff0058fd, + 0x241d87ff, + 0xdc060602, + 0x250f9200, + 0xf4ff2300, + 0x3d821603, + 0x62062722, + 0x0a27a582, + 0xdc062700, + 0x82007201, + 0x6206234a, + 0x3183c901, + 0x04212183, + 0x22218288, + 0x85df0626, + 0x3b032117, + 0x3f241784, + 0xed02f4ff, + 0x63233984, + 0x8501e8ff, + 0x845b2039, + 0x01662221, + 0x2021889d, + 0x20218ef9, + 0x22218447, + 0x84b90164, + 0x82222021, + 0x84fc2043, + 0xff652221, + 0x204386ff, + 0x22218481, + 0x88ac0166, + 0x8ef42043, + 0x84412043, + 0x01652221, + 0x202184b5, + 0x20c18229, + 0x22218404, + 0x86010064, + 0x86732043, + 0x88c52021, + 0x94f82043, + 0x8a672043, + 0x94082043, + 0x01672143, + 0x23204385, + 0x21856582, + 0x27416520, + 0x846f2008, + 0x20218765, + 0x2021822a, + 0x20438421, + 0x20218866, + 0x20218688, + 0x208788de, + 0x20878ef1, + 0x2221844b, + 0x84ab0168, + 0x20658321, + 0x20218401, + 0x22658e67, + 0x9ebb0168, + 0x866920cb, + 0xff3f24cb, + 0x94f502f4, + 0x866a2065, + 0x20658321, + 0x8f218405, + 0x8a6a20cb, + 0x8f2185ed, + 0x20218787, + 0x8565821e, + 0xff6922cb, + 0x067541ec, + 0xcb843d20, + 0xb1016a22, + 0xfb20a988, + 0x6b208794, + 0x0420cb89, + 0x22053141, + 0x824b01dc, + 0x0627213b, + 0x22074942, + 0x84a60163, + 0x0262224b, + 0x081741d4, + 0x4205e341, + 0x7d4109a5, + 0x83652005, + 0x01002eb1, + 0x68002200, + 0x2c02cf01, + 0x00000b00, + 0x081a4737, + 0xd815232b, + 0xb641b6b6, + 0x3ec368b6, + 0x200282c3, + 0x25278300, + 0xcf012b01, + 0x234e6901, + 0x01222607, + 0x3e2b01ad, + 0x2619833e, + 0x017e0032, + 0x841502bf, + 0x37273141, + 0x37173727, + 0x07170717, + 0x9b2c5e27, + 0x9a9b2c9b, + 0x9a2c0583, + 0x9e9f2d7e, + 0x2d9f9f2d, + 0xa02d9f9e, + 0x22224182, + 0x73826000, + 0x09823320, + 0x1b000f28, + 0x35130000, + 0xf9641521, + 0x14152208, + 0x0b555706, + 0xd6286782, + 0x17202017, + 0x171f1f17, + 0x77830786, + 0x181ecb2a, + 0x171e1e17, + 0x68011e18, + 0xff310987, + 0x01bc00ff, + 0x01330107, + 0x04070085, + 0x017b0082, + 0x22118213, + 0x82c00022, + 0x02d428b5, + 0x00f50626, + 0x8206006b, + 0x84952005, + 0x828320f3, + 0x1522087f, + 0x00000900, + 0x25352525, + 0x15070715, + 0xcf011717, + 0xad0153fe, + 0xd38686d3, + 0xa842a883, + 0x04324e47, + 0x2b8d4e32, + 0x3735372a, + 0x27273537, + 0x22150535, + 0x01222683, + 0x258583ad, + 0x42a84729, + 0x00020000, + 0x86000022, + 0x8b0d2055, + 0x82052057, + 0x235b85dd, + 0xd28787d2, + 0x992c6383, + 0x47994a99, + 0x2c042c49, + 0x3e3ee049, + 0x65893990, + 0x39820120, + 0x34832220, + 0x84ad0121, + 0x24338536, + 0xfe4a9947, + 0x24378bce, + 0x000b002c, + 0x0dbd410f, + 0x39820720, + 0x2a05c141, + 0x7fad01f7, + 0xbebe3eb1, + 0x417fb13e, + 0x3c2605ad, + 0xb5011c01, + 0xfb839e02, + 0x33131333, + 0x27272313, + 0x3c070723, + 0x48984998, + 0x32043141, + 0x261d8241, + 0xb07efe82, + 0x84b08585, + 0x824120fb, + 0x005322d1, + 0x235d8213, + 0x33352337, + 0x21200382, + 0x08f96818, + 0x3d07212b, + 0x5b8b674c, + 0x4c0a01e6, + 0x2808843c, + 0x414cf6fe, + 0x3e983e7f, + 0x2004847f, + 0x283f8200, + 0x01010124, + 0x009301cd, + 0x220c8217, + 0x51022e22, + 0x1e2108de, + 0x07994d02, + 0x2f1e502c, + 0x16152728, + 0x1b2e1126, + 0x0b8a2042, + 0x19010129, + 0x201d1922, + 0x842a3021, + 0x2f222907, + 0xffff002a, + 0x96002400, + 0xfe284f82, + 0x01072602, + 0x06006b00, + 0xcd410582, + 0x682a0805, + 0x6901cf01, + 0x00000500, + 0x35213525, + 0x8d011121, + 0xad0195fe, + 0xfe3ec368, + 0x030000ff, + 0x93002800, + 0xff01e602, + 0x2a001e00, + 0x23823600, + 0x27262224, + 0x8c820e23, + 0x56262621, + 0x162005c6, + 0x26067058, + 0x06141516, + 0x5d322506, + 0x15230610, + 0x57051614, + 0x710806dd, + 0x16160706, + 0x5d403a02, + 0x3111042d, + 0x45292a41, + 0x29465d29, + 0x0412303f, + 0x32405f23, + 0x4d2d2c4d, + 0x44295bfe, + 0x26431f19, + 0x01373528, + 0x3c38329c, + 0x254c2b36, + 0x42934c2a, + 0x23301438, + 0x502b482b, + 0x1831205b, + 0x4f2d4a2f, + 0x2f553933, + 0x2b263652, + 0x2a2a2f34, + 0x2b410438, + 0x34374032, + 0x02003c37, + 0xf4ff2800, + 0x9c02e701, + 0x29000b00, + 0x14370000, + 0x84873316, + 0x0ab96e18, + 0x34361722, + 0x080d7d6f, + 0x7606064f, + 0x59412d43, + 0x2145210f, + 0x3068484a, + 0x62343353, + 0x1d4f2943, + 0x40414b01, + 0x50202630, + 0x4373612e, + 0x463bb977, + 0x222a626d, + 0x2ef9fe58, + 0x65423b57, + 0x08212639, + 0x6c7d0911, + 0x23203332, + 0xab729992, + 0x00010060, + 0x0162ff34, + 0x00150333, + 0x09574e23, + 0x2e343523, + 0x0f4c5d02, + 0x021e3f08, + 0x06061415, + 0x0a102064, + 0x182b170b, + 0x160d100d, + 0x1a0f393c, + 0x11070a06, + 0x0c18290b, + 0x3c150c11, + 0x043e079e, + 0x7e374e52, + 0x41377f83, + 0x02043c67, + 0x5502023e, + 0x827e364d, + 0x6841387e, + 0x6982003c, + 0xff293608, + 0x033102a1, + 0x000f0034, + 0x07030500, + 0x16133727, + 0x36331716, + 0x33133736, + 0x96190103, + 0x74851347, + 0x04040805, + 0xb2030603, + 0x015fd93c, + 0x3b2d20ac, + 0x2010a6fe, + 0x23028210, + 0x6dfcf902, + 0x16284183, + 0xf50188ff, + 0x0d007e02, + 0x3529ab82, + 0x21350313, + 0x13152115, + 0x39048203, + 0x01e3ee16, + 0xd4affeb8, + 0x787701de, + 0x01460135, + 0x04473546, + 0xcffed1fe, + 0x77824704, + 0x88ff5924, + 0x35824902, + 0x35820720, + 0x11211123, + 0x08038223, + 0xf0015931, + 0x78b8fe55, + 0x0afdf602, + 0x53fdad02, + 0x00020000, + 0x01f4ff15, + 0x00d40292, + 0x00280009, + 0x36151300, + 0x26343536, + 0x13062223, + 0x06272622, + 0x82270706, + 0x751120a7, + 0x07210727, + 0x05a24115, + 0x06174708, + 0x423bbc06, + 0x281b1921, + 0x055c3e4e, + 0x210e1a0d, + 0x54142b17, + 0x684a393e, + 0x1f25345c, + 0x1921122b, + 0xd50a0243, + 0x3246833b, + 0xa1fd422a, + 0x12095556, + 0x1e0f3409, + 0x740f0110, + 0x5f4a4f65, + 0x46234fb0, + 0x33111b3a, + 0x7d822817, + 0xf4ff2e2b, + 0x9402f202, + 0x32002000, + 0x05721800, + 0x2115230d, + 0x6f821522, + 0x16161732, + 0x37363233, + 0x01060633, + 0x35353221, + 0x26262734, + 0x07229d82, + 0x1c820606, + 0x90013208, + 0x37618149, + 0x49816137, + 0x3761804a, + 0x0504c2fd, + 0x40712903, + 0x342a7644, + 0xcefe9331, + 0x0a06b801, + 0x403e6e2a, + 0x05032a70, + 0x7a5c340c, + 0x5c7a4646, + 0x08078334, + 0xb8040826, + 0x2e050906, + 0x3c333d36, + 0x065a0148, + 0x2c0a0cb8, + 0x042d3532, + 0x06b4060c, + 0x1a000100, + 0x4302f1ff, + 0x09000702, + 0x20088f82, + 0x17013501, + 0x21152107, + 0xfe2b0117, + 0x2a1101ef, + 0xfeb701c9, + 0x010fc949, + 0x09010409, + 0xbb44bb2e, + 0x262f8200, + 0x02e7ff2a, + 0x840f0241, + 0x07112c2f, + 0x01330127, + 0x01112707, + 0x832ebb13, + 0x2f0a2f25, + 0xb70119bb, + 0x10012ac9, + 0xc92af0fe, + 0x2f8249fe, + 0x5f822720, + 0x5f864f20, + 0x21372735, + 0x37272135, + 0x3f011501, + 0x4afec92b, + 0x2bc9b601, + 0x830f1001, + 0xfe2e2359, + 0x5d8f04f7, + 0x1737012c, + 0x37113311, + 0x33010117, + 0x2483f7fe, + 0xf6fe2f23, + 0x26958419, + 0xc94afeb6, + 0x82effe2a, + 0xff2d285d, + 0x025203c4, + 0x410300e9, + 0x2d2705f3, + 0x033c2503, + 0x82dbfc25, + 0xff192619, + 0x026603b0, + 0x2b1983fd, + 0x01020905, + 0x0159fec0, + 0x50a601a7, + 0xfe210483, + 0x2c15825a, + 0x03b5ff21, + 0x00f8025e, + 0x00270013, + 0x0e8b4137, + 0x020e1432, + 0x023e3227, + 0x022e3435, + 0x020e2223, + 0x021e1415, + 0x0a917318, + 0x15162b08, + 0x01060614, + 0x739654c0, + 0x96734242, + 0x72965454, + 0x96724242, + 0x637f4554, + 0x7f633939, + 0x647e4545, + 0x7e643939, + 0x48754545, + 0x05827548, + 0x47473408, + 0x6d394b75, + 0x9960619b, + 0x6e3a3a6e, + 0x9b616099, + 0x3038396d, + 0x5656875d, + 0x31315d86, + 0x5656865d, + 0x61305d87, + 0x4f507841, + 0x77424277, + 0x4177514f, + 0x87000200, + 0x000522d7, + 0x3dd98309, + 0x07112137, + 0x21112125, + 0xe302422d, + 0x0240fd38, + 0x3c56fdaa, + 0xfd38ed02, + 0x022c421d, + 0xed8200ab, + 0xc4ff3324, + 0xed824c03, + 0x2d820520, + 0x33013532, + 0x01331501, + 0x8a01048b, + 0x3703023c, + 0x0002c9fc, + 0x21895182, + 0x23870820, + 0x82212521, + 0x25268329, + 0x570248fd, + 0x2c86d5fe, + 0x7f023a22, + 0x2d275183, + 0x6603caff, + 0x8300e302, + 0x82112051, + 0x2d012150, + 0x36274b84, + 0x76fe1903, + 0x8475fe04, + 0x832187a3, + 0x21238451, + 0x26860137, + 0x80023924, + 0x2b8780fd, + 0x2c016124, + 0xa5852b01, + 0xa582b020, + 0x5383e920, + 0x01150127, + 0x03350123, + 0x264c844c, + 0xfc02e902, + 0x863703c9, + 0x822387a7, + 0x22258555, + 0x87012105, + 0xfdb82428, + 0x872c01a9, + 0xfd3a222e, + 0x20558381, + 0x20a98219, + 0x21a98552, + 0x54821101, + 0x52030122, + 0xe3234e85, + 0x8301e7fc, + 0x89ab82de, + 0x84558323, + 0x01072125, + 0x39252887, + 0x800280fd, + 0x252d8702, + 0xfed5fe61, + 0x338200d4, + 0xf6ff4a26, + 0x9f02d502, + 0x8341ad82, + 0x3d4a340c, + 0xfd354e02, + 0xfd1502d5, + 0x76020aeb, + 0x3d94fd33, + 0x8634022b, + 0x2503272f, + 0x0b001b03, + 0xb3411e00, + 0x36363205, + 0x07061737, + 0x21250711, + 0x07060611, + 0x27262607, + 0x060a4537, + 0x3d4a212a, + 0x371afc01, + 0x2729351c, + 0x43304a84, + 0x1b562470, + 0x25382b46, + 0x2004143d, + 0x27fe416a, + 0x23275983, + 0x26321c3d, + 0x829dfd2d, + 0x5e152e5f, + 0x4d0a81e5, + 0x3a264088, + 0xda6e3f7e, + 0x28f58361, + 0x02ecff00, + 0x00ac0268, + 0x866b8210, + 0x3e330858, + 0x0e173702, + 0x3b970702, + 0x4429385c, + 0x71240417, + 0x4f364e8f, + 0x14267591, + 0x3e2685a2, + 0xea774388, + 0x49324dce, + 0x0087eec6, + 0xff1d0001, + 0x02e101e8, + 0x822100b6, + 0x0933513d, + 0x1e331124, + 0x80571702, + 0x06d86c05, + 0x14114a08, + 0x28820606, + 0x2e48283d, + 0x32072114, + 0x191b0d05, + 0x0b152e44, + 0x41050823, + 0x184e303c, + 0x351f2527, + 0x02050721, + 0x16130d19, + 0x395b3012, + 0x0d174527, + 0x2f1b2918, + 0x69fe1354, + 0x00264a37, + 0xff380002, + 0x02cd01f6, + 0x0005009e, + 0x0869820f, + 0x3313032f, + 0x33270313, + 0x27273737, + 0x17070723, + 0x4ba5a5dd, + 0x0427a5a5, + 0x3e41413e, + 0x41413f04, + 0x0154010a, + 0xfeacfe54, + 0x8a8545ac, + 0x89868689, + 0x3de7838a, + 0x00c10152, + 0x00b202b9, + 0x13000004, + 0x07071737, + 0x0f511652, + 0xf0c20122, + 0xff955b01, + 0x1d8200ff, + 0x826a0121, + 0x0726211d, + 0x0021c982, + 0x26058207, + 0x000000b1, + 0x82400001, + 0x86a72035, + 0x27272e35, + 0x22711737, + 0x0116510f, + 0x015b95c1, + 0x833585f0, + 0x06022153, + 0x00202f82, + 0x1e260f82, + 0x9e002202, + 0x3f82e902, + 0x55007924, + 0x11822303, + 0x11821020, + 0x11849020, + 0x59006422, + 0x80261184, + 0x47013d02, + 0x23820d03, + 0x82013a21, + 0x202382cb, + 0x201182d7, + 0x2011849e, + 0x2611863d, + 0x01380274, + 0x82e402aa, + 0x88402023, + 0x823e2011, + 0x82ea2011, + 0x83562011, + 0x28998211, + 0x00150216, + 0x00dc025c, + 0x2acf8203, + 0x1c073327, + 0x02064606, + 0x82c7c715, + 0x0206264f, + 0x02100159, + 0x232b8292, + 0x008b0044, + 0x37249783, + 0xfe003d02, + 0x06236182, + 0x826f3d07, + 0xe0ff210f, + 0xa7200f82, + 0x3a200f84, + 0x002c0f83, + 0x00f2fe16, + 0x00b9ff5c, + 0x39710706, + 0x00211f82, + 0x65b71862, + 0x027d2610, + 0x02a1014b, + 0x205382af, + 0x2091864e, + 0x2065828a, + 0x86658594, + 0x02732611, + 0x02ab013b, + 0x202382da, + 0x26118648, + 0x012a02a1, + 0x82ef027d, + 0x86522011, + 0x82af2011, + 0x02d622d9, + 0x201182f9, + 0x26118654, + 0x014a02d8, + 0x82b60246, + 0x864c2011, + 0xffb62611, + 0x0063011e, + 0x22118203, + 0x8415016d, + 0xffbf24bf, + 0x84670132, + 0x846f2011, + 0x000c3efd, + 0x02f4ff2e, + 0x00f2011c, + 0x0017000b, + 0x002e0022, + 0x0046003a, + 0x005d0052, + 0x00740069, + 0x21f58380, + 0xad492237, + 0x14152306, + 0x0b8a2706, + 0x4663178a, + 0x0b424c0b, + 0x2e9617a2, + 0x0b8a688b, + 0x150d6c28, + 0x14100d15, + 0x07842d13, + 0x0b141522, + 0x14290784, + 0x14140e2a, + 0x14150f0e, + 0x20078610, + 0x2107835a, + 0x0f851410, + 0x5a200782, + 0x0f222683, + 0x06852415, + 0x0e3e1330, + 0x0f0e1515, + 0x140f0814, + 0x160e0f14, + 0x0e852b14, + 0x1014612c, + 0x12141412, + 0x146d1410, + 0x00821211, + 0x6e141123, + 0x26068214, + 0xfe261212, + 0x821313d3, + 0x13113012, + 0x147f0113, + 0x12121310, + 0xfe141013, + 0x82121366, + 0x12112510, + 0x14b40113, + 0x14220985, + 0x278567fe, + 0x7e01262c, + 0x13121015, + 0x15101213, + 0x5585d4fe, + 0x54892420, + 0x252b3785, + 0xff010000, + 0x003d0271, + 0x420d0338, + 0x372a0579, + 0x3a9d0e17, + 0x993d028d, + 0x1b83a737, + 0xb9027926, + 0x63033600, + 0x11281b87, + 0x028e2f98, + 0x803773b9, + 0xa5261b83, + 0x21002e02, + 0x1b830203, + 0x3727032c, + 0x55431817, + 0xc52e0227, + 0x1b83c90f, + 0x5382c820, + 0x53858f20, + 0x0e281b83, + 0x023a8d2a, + 0x37a7293d, + 0xca201b83, + 0x87205382, + 0x1b835385, + 0x8e251127, + 0x2ab9022f, + 0x201b8480, + 0x205382df, + 0x2053855f, + 0x27538313, + 0x02552b39, + 0x0fc90b2e, + 0x21083783, + 0x00380265, + 0x00e4029b, + 0x03000007, + 0x07173337, + 0x9b072327, + 0x23725272, + 0x02760476, + 0x208c8c58, + 0x25837171, + 0xbb026c26, + 0x46039400, + 0x27202584, + 0x702e2685, + 0x69566924, + 0x02046e24, + 0x71711abb, + 0x25835d1a, + 0x4102532b, + 0xd102ad00, + 0x00001700, + 0x14994c13, + 0x261b4833, + 0x16111e1f, + 0x02370217, + 0x261b342f, + 0x16121d20, + 0x290b8316, + 0x22194102, + 0x03232c19, + 0x07824d3b, + 0x04222d30, + 0x01004d3a, + 0xc5024fff, + 0x4903b100, + 0x4d921600, + 0x06173730, + 0x291c4b06, + 0x13121e1f, + 0x0338031a, + 0x0b842d36, + 0x82082821, + 0xc502290a, + 0x22151d15, + 0x42390420, + 0x42230782, + 0x83413a04, + 0x027b2899, + 0x02850059, + 0x82030092, + 0x213529e5, + 0x0a018515, + 0x39395902, + 0x7a261983, + 0x8600df02, + 0x19871803, + 0x0c018624, + 0x1982df02, + 0xffffff22, + 0x02283386, + 0x00440706, + 0xffffff00, + 0x0f822986, + 0x83004521, + 0x643b0839, + 0x9c003b02, + 0x1100da02, + 0x22110000, + 0x37272626, + 0x3233021e, + 0x17373636, + 0x4335020e, + 0x04330321, + 0x21202c19, + 0x3304192b, + 0x02432102, + 0x25452d3b, + 0x1f301908, + 0x0819301f, + 0x832d4525, + 0x0263283f, + 0x029d003c, + 0x860f00d5, + 0x4a33203f, + 0x2808068c, + 0x4338020e, + 0x02440220, + 0x26323126, + 0x20024401, + 0x2c3c0243, + 0x3e2b2746, + 0x46272b3e, + 0xff01002c, + 0x00c1026e, + 0x004a0392, + 0x2137840d, + 0xd6683727, + 0x46462808, + 0x2f063206, + 0x822f2b2b, + 0x02462c06, + 0x08344dc1, + 0x23313123, + 0x834d3408, + 0x8269206d, + 0x03972235, + 0x3a6d9245, + 0x021d4137, + 0x2a230248, + 0x4801242a, + 0x02401d02, + 0x213d26c1, + 0x23333323, + 0x82263d21, + 0x02c9286d, + 0x0237004a, + 0x840b00b6, + 0x08227d6d, + 0x1f1f1823, + 0x29038218, + 0x191d4a02, + 0x181e1e18, + 0x63831d19, + 0xca02c726, + 0x35033900, + 0x21272b90, + 0x21181821, + 0x50ca0221, + 0x00220754, + 0xc5820200, + 0x92004b24, + 0x2b82af02, + 0x00001722, + 0x200b2944, + 0x0a874433, + 0x1c166028, + 0x1c15161c, + 0x0382ab1c, + 0x0b821520, + 0x1d4b0225, + 0x8b1d1515, + 0x26498203, + 0x00cb0268, + 0x9d2d0398, + 0x84672049, + 0x1b1b2541, + 0x1b1b16b8, + 0x02235183, + 0x86151ccb, + 0x8207860a, + 0xbc2e08eb, + 0x50003c02, + 0x0c00f802, + 0x27030000, + 0x34353636, + 0x16163727, + 0x20061415, + 0x53201809, + 0x444b4405, + 0x06283c02, + 0x042b1316, + 0x2c310136, + 0x31842b2b, + 0x4f00ba24, + 0x31956803, + 0x49410931, + 0x26ba0243, + 0x27131407, + 0x29023003, + 0x822a2b26, + 0x029226ad, + 0x026e002a, + 0x20ad85ef, + 0x43931811, + 0x3c322316, + 0x0383323c, + 0x39411820, + 0x382a3106, + 0x38382a2b, + 0x25382b2a, + 0x211c1c22, + 0x221c1c21, + 0x9f264982, + 0x6100bb02, + 0x499d7003, + 0x37372a3d, + 0x3838292a, + 0x1f1f1429, + 0x1e1e1614, + 0x2832bb02, + 0x29323229, + 0x1c243228, + 0x831c1a1a, + 0x28498203, + 0x003802a0, + 0x00f902c7, + 0x06df4303, + 0x27171732, + 0x2d331737, + 0x2e333b56, + 0x38023a57, + 0xa51cac15, + 0x00200382, + 0x9a262982, + 0xce00bf02, + 0x298d6c03, + 0x5c2b3b24, + 0x03823738, + 0x15bf0225, + 0x828d2098, + 0x05574403, + 0x9b003e24, + 0x5187ea02, + 0x1737333d, + 0x23722907, + 0x23760476, + 0x8c3e0272, + 0x20717120, + 0xff01008c, + 0x00c2026c, + 0x8b4d0394, + 0x692b2f25, + 0x6e046e24, + 0xc2026924, + 0x5c5c1a71, + 0x7582711a, + 0x9f823920, + 0x9f8f6020, + 0x3a63642d, + 0x3b646957, + 0xa5380256, + 0x8215ac1c, + 0x209f8303, + 0x209f8232, + 0x249f8f66, + 0x5c386965, + 0x25038275, + 0x208dbf02, + 0x03821598, + 0x0805bd43, + 0x9c003839, + 0x1100d702, + 0x27030000, + 0x3233023e, + 0x07171616, + 0x2223022e, + 0x33690606, + 0x35432103, + 0x02214336, + 0x2b190433, + 0x192c2021, + 0x25083802, + 0x452d2d45, + 0x2f1a0825, + 0x832f1f1f, + 0x026e283f, + 0x039200c0, + 0x830d0049, + 0x0b2c5e3f, + 0x06326023, + 0x43008246, + 0x022a068a, + 0x4c3508c0, + 0x2308354c, + 0x35833131, + 0x3402cb28, + 0xee022e00, + 0x35821000, + 0x34352227, + 0x06173736, + 0x078e7806, + 0x2633023b, + 0x1b1c122b, + 0x0f050302, + 0x3402171a, + 0x133f2345, + 0x17230d20, + 0x16141401, + 0x2d3b8316, + 0x003e02b0, + 0x00f50244, + 0x1300000c, + 0x3c852626, + 0x16141533, + 0x452b2017, + 0x5305444b, + 0x3e021820, + 0x2b2b2908, + 0x2fb5822e, + 0x0616132b, + 0xd1ff0100, + 0x33003202, + 0x0f00ed02, + 0xcc77a384, + 0x32333a07, + 0x1e061415, + 0x03033611, + 0x191a0f06, + 0x02263210, + 0x2c1c2032, + 0x17131401, + 0x23738216, + 0xffffff00, + 0x24060743, + 0x50070602, + 0x29798300, + 0x0007ffb4, + 0x00c6ff55, + 0xb97b0007, + 0x6f232808, + 0x48f9326f, + 0x83bf482f, + 0x82ab201f, + 0x854c201f, + 0x3507211f, + 0x25056f5d, + 0x6f6f3255, + 0x2082bff9, + 0x02273f84, + 0x0255003d, + 0x820500ca, + 0x233521b9, + 0x23312182, + 0x3d02a16f, + 0x008d2f5e, + 0x01f7ff01, + 0x029400b2, + 0x06414383, + 0x20055a59, + 0x36a08216, + 0x08540801, + 0x0d0a4006, + 0x29b20156, + 0x1a10440e, + 0x26121e0e, + 0x823e3b18, + 0xfeb72431, + 0x823700ff, + 0x820d206d, + 0x0623088d, + 0x36343526, + 0x06261517, + 0x37161415, + 0x41413f37, + 0x2121283f, + 0x3602ff28, + 0x02362d2e, + 0x1b230124, + 0x8301231c, + 0xffa02481, + 0x8860002d, + 0x28a384a1, + 0x47324760, + 0x6a6a2fd3, + 0x201f852f, + 0x201f8207, + 0x20e183a0, + 0x29a18507, + 0xc0471915, + 0x2f6af947, + 0x1f896a2f, + 0x0b00c624, + 0x1f840000, + 0x23204184, + 0x44822382, + 0x82f94721, + 0x22e986e6, + 0x824fffa0, + 0x007e2247, + 0x2d278303, + 0xc0601533, + 0x002f2fb1, + 0xc9ffffff, + 0xb38232ff, + 0x07029e28, + 0x00004c07, + 0x1182e8fc, + 0x36ff6e26, + 0x9aff9200, + 0x4e201182, + 0xeb201182, + 0x92261182, + 0x6e0000ff, + 0x1182c5ff, + 0x11825220, + 0xe982d620, + 0x1effa124, + 0xe9854e00, + 0xfb780720, + 0x0857370c, + 0x23242e3f, + 0x55344112, + 0x170528e2, + 0x03131414, + 0x22240726, + 0x33872c2b, + 0x0f207f82, + 0x33878182, + 0x16073326, + 0x06141516, + 0x24823583, + 0x231d3523, + 0x28378426, + 0x06161416, + 0x2008435b, + 0xbc38821f, + 0x82b02039, + 0x825820dd, + 0x7a112073, + 0x260808d5, + 0x14150633, + 0x37323316, + 0x0b060617, + 0x1b2a3526, + 0x121c4038, + 0x0e161215, + 0x2a2bce2d, + 0x2f144226, + 0x0d17173d, + 0x82100b29, + 0xffad2475, + 0x825d002c, + 0x8a12203b, + 0x3c3c893b, + 0x2c38280d, + 0x24203d1c, + 0x1316111e, + 0xd42d0f17, + 0x44272b2c, + 0x1d391815, + 0x2d0e1717, + 0x286e820b, + 0xfeddff01, + 0xff2300f2, + 0x2c4182b9, + 0x33370300, + 0x3a062317, + 0xc7f2fe06, + 0x265982c7, + 0x001eff87, + 0x41aeff79, + 0x210805d3, + 0x35231533, + 0xf2791523, + 0x90e2962e, + 0x00616190, + 0x65ffffff, + 0x9b0020ff, + 0x0702ccff, + 0x00005607, + 0x1182e2fc, + 0x19ff6426, + 0xb8ff9c00, + 0x48201182, + 0xde201182, + 0x13201184, + 0xb2201182, + 0x5a201182, + 0xdb201182, + 0x53261182, + 0xad0021ff, + 0x1182b1ff, + 0x11824220, + 0x1182e020, + 0x56ff7b26, + 0x8fff8500, + 0x44201182, + 0xfd201182, + 0x432b7982, + 0xbd00b800, + 0x17004801, + 0x49370000, + 0x5e2c1407, + 0x26283121, + 0x02161616, + 0x312b0337, + 0xb8280b8a, + 0x2a192219, + 0x4a360923, + 0x2c250782, + 0x4b350921, + 0x244d8200, + 0x00fffec9, + 0x06054249, + 0x16352208, + 0x26343536, + 0x16363507, + 0x37061415, + 0x28212128, + 0xff41413f, + 0x1c230124, + 0x2401231b, + 0x2e2d3602, + 0x20f98436, + 0x33f98b1f, + 0x15333533, + 0x2e962e79, + 0x60608fe1, + 0x0200008f, + 0x10ff87ff, + 0xb3201f82, + 0x2005c545, + 0x2d1d8207, + 0x23353327, + 0x96c4f279, + 0xa3a3f096, + 0x41825428, + 0x16ff5830, + 0xb0ffa800, + 0x00001d00, + 0x33363407, + 0xcd551632, + 0x07152606, + 0x22232634, + 0xbe4a1806, + 0x152a0808, + 0x1a2e30a8, + 0x08020728, + 0x302e1928, + 0x17171b30, + 0x18173017, + 0x4ee41b16, + 0x20201a46, + 0x064e461a, + 0x262a283c, + 0x2a261313, + 0x55823c28, + 0x2b02ac2c, + 0xd4025400, + 0x00000b00, + 0xd3582703, + 0x21332209, + 0x21028833, + 0x0c822b02, + 0x33332222, + 0x21250282, + 0xffff0033, + 0x06534aff, + 0x07060224, + 0x0f830042, + 0x8206154a, + 0x8443200f, + 0x06e3440f, + 0x5e210f82, + 0x27568200, + 0x330265ff, + 0x06039b00, + 0x0f226382, + 0x59481b00, + 0x2717230d, + 0x9f181737, + 0x712c0b57, + 0x12181812, + 0x63181811, + 0x2a422d2b, + 0x11200782, + 0x02250f82, + 0x13131753, + 0x24038317, + 0x0ec90a20, + 0x200c87a5, + 0x2ebd8200, + 0x0037ffdf, + 0x00c2ff5a, + 0x17000010, + 0x18353522, + 0x3e078eea, + 0x06173736, + 0x404d2c06, + 0x0c120101, + 0x090a0804, + 0x5dc9130a, + 0x0b1d0d2e, + 0x02010f10, + 0x82050431, + 0x3afe2939, + 0xc6012602, + 0x0d00cf02, + 0x27200c82, + 0x3b0b2b46, + 0x651852fe, + 0xe37f7fe2, + 0xe25f1864, + 0x02e26d6d, + 0x413e2a26, + 0x3a2a3e41, + 0xffff3535, + 0xb9283582, + 0x6203c601, + 0x83070702, + 0x932ad982, + 0x72ff0300, + 0x8e004c02, + 0xdb934c03, + 0xdb8e3720, + 0x1b136035, + 0x1914131b, + 0x52234519, + 0x1a130731, + 0x1a14131a, + 0x844c021a, + 0x13142706, + 0x7318751a, + 0x0c87de22, + 0x59820020, + 0xcb026c26, + 0xc8039400, + 0x475a5997, + 0x8667200b, + 0x2552244d, + 0x8607355f, + 0xcb022365, + 0x6c82141a, + 0x1a141427, + 0x24771a6c, + 0x830c87d9, + 0x24b3b259, + 0x52316053, + 0x23b39136, + 0x8d732269, + 0xe941b3aa, + 0x24b3870b, + 0x5f356f54, + 0x23b39141, + 0x8677246d, + 0x4342b38b, + 0x0a1d4f1e, + 0x43420620, + 0x405d2407, + 0x42492942, + 0xc5231143, + 0x4216c90e, + 0x03320943, + 0x4c0267ff, + 0x26039900, + 0x21001500, + 0x00002d00, + 0x70562213, + 0x05144205, + 0x32331627, + 0x06173736, + 0x0b6d4106, + 0x2b0b0d4b, + 0x242b2347, + 0x03181118, + 0x262a022a, + 0xcd200a89, + 0xac20cf86, + 0x29073141, + 0x171819c3, + 0x35270417, + 0x06841918, + 0x33417720, + 0x0b3b4107, + 0x20059541, + 0x13ef411d, + 0x375c2720, + 0x0749420e, + 0x0b013a23, + 0x10944125, + 0x2f2fa223, + 0x119341a2, + 0x57a38b20, + 0x23079341, + 0x1f0c0133, + 0x23109241, + 0x922e2e92, + 0x30114542, + 0x00070048, + 0x001f0013, + 0x37270300, + 0x17373317, + 0x17294107, + 0x1e5e2228, + 0x1e600460, + 0x1b41825e, + 0x5cd0270f, + 0x1c49491c, + 0x1341845c, + 0x05034313, + 0x63a7c220, + 0x21632428, + 0x21640464, + 0x14418b63, + 0x86ba2006, + 0x4703286b, + 0x4b4b1b60, + 0x877c601b, + 0x28c789bf, + 0x027aff02, + 0x03eb003a, + 0x45638211, + 0x33250503, + 0x23270717, + 0x08cd8217, + 0x641d6921, + 0x671d6444, + 0x57238804, + 0x223a0231, + 0x48225c5c, + 0x22781c05, + 0xff020000, + 0x00bb027f, + 0x917803df, + 0x225f3633, + 0x225d485d, + 0x1e7b045d, + 0xbb022361, + 0x1a5a5a1a, + 0x5d200545, + 0x20338327, + 0x20678209, + 0x20678f86, + 0x23678a07, + 0x64307184, + 0x70226787, + 0x33837524, + 0x67822d20, + 0x678f8120, + 0x67873383, + 0x235a7723, + 0x22678755, + 0x835f2558, + 0x22cf8333, + 0x821703d1, + 0x0015239b, + 0x19500300, + 0x48172006, + 0xd9870cab, + 0x13097629, + 0x07252017, + 0x863a3f3b, + 0x23072d77, + 0x14101205, + 0x01290114, + 0x23282325, + 0xe9834d83, + 0x8a03cf22, + 0x14204d82, + 0x15224d93, + 0x8a870614, + 0x130b7528, + 0x0926211a, + 0x8f863878, + 0x05230e30, + 0x1114100f, + 0x44052a02, + 0x02002326, + 0xff8277ff, + 0x23038922, + 0x1d204982, + 0x37204989, + 0x87146d43, + 0x1d432e9f, + 0x0f13242a, + 0x042b040e, + 0x2a1e2321, + 0x820a8623, + 0x58582bab, + 0x15474522, + 0x04161415, + 0x06843227, + 0x82332621, + 0x026f2661, + 0x039100bb, + 0x8761a3ab, + 0x20442fb4, + 0x1215212a, + 0x022d0311, + 0x2a202825, + 0x0a841422, + 0xc1822420, + 0x1a57572c, + 0x19194a42, + 0x26051618, + 0x06831835, + 0x82352721, + 0x02642a61, + 0x039c003b, + 0x00110040, + 0x11615015, + 0x37272738, + 0x21433517, + 0x19043003, + 0x2d22212e, + 0x0230031a, + 0x273b4321, + 0x69503458, + 0x321a2e05, + 0x1a322020, + 0x2d452508, + 0x287c1d6c, + 0x504d8200, + 0xb4220535, + 0xaf500d00, + 0x0a375006, + 0x46284b83, + 0x062f0646, + 0x312c2c31, + 0x46340682, + 0x355f2943, + 0x344dc102, + 0x33332508, + 0x4d340825, + 0x24741d62, + 0x91b14383, + 0x34653123, + 0x22919058, + 0xaf7c2871, + 0x6b492391, + 0x918c5f35, + 0x74246d22, + 0x50209189, + 0x1f20d382, + 0x21132341, + 0x504c3636, + 0x102d4109, + 0x15085129, + 0x0729231b, + 0x8f3e443d, + 0x246f21a1, + 0x25059942, + 0x28290132, + 0xab892628, + 0x0d00b824, + 0x75511b00, + 0x4227200f, + 0x47410ced, + 0x0a5d290c, + 0x25211a12, + 0x393e3b08, + 0x5f20bb8b, + 0x2407ab42, + 0x26232402, + 0x2a5d8323, + 0x003b0270, + 0x00220390, + 0x8425000f, + 0x4126205d, + 0x0e21089c, + 0x15b44202, + 0x1f3d312f, + 0x2f042f03, + 0x042e2f2e, + 0x3d1f032f, + 0x06bb4210, + 0x23042f23, + 0x06bb4225, + 0x02280a82, + 0x1932203b, + 0x2b2b1908, + 0x32290482, + 0x15158b20, + 0x26051615, + 0x23068232, + 0x32260415, + 0x6f267783, + 0x9100c402, + 0xd582af03, + 0x11208682, + 0x24083f79, + 0x06061737, + 0x142b4327, + 0x05444625, + 0x822e052e, + 0x21068200, + 0xce420444, + 0x40c43215, + 0x2a1b082a, + 0x2a081b2a, + 0x19198740, + 0x27051718, + 0x06da4235, + 0xff020029, + 0x003a027f, + 0x44240381, + 0xe2820d2f, + 0x2908f088, + 0x1f620606, + 0x1f5f445f, + 0x3e020460, + 0x0626053b, + 0x282a2a28, + 0x3b052606, + 0x53183a02, + 0x493e1853, + 0x160a2138, + 0x0a162020, + 0x4d823821, + 0xbb027724, + 0xbf828900, + 0x44000721, + 0x4d8d0a7d, + 0x5c215f2a, + 0x5d215c48, + 0x42420204, + 0x2b27b382, + 0x052a2c2b, + 0x4343042e, + 0x452b0573, + 0x08253949, + 0x16222216, + 0x82392508, + 0x0268264d, + 0x037a002f, + 0x05214302, + 0x022e0322, + 0x0809614f, + 0x17371724, + 0x2c183707, + 0x043a471d, + 0x33141a49, + 0x02434a2b, + 0x26150641, + 0x022a291d, + 0x13270433, + 0xc92e0517, + 0x4182c50e, + 0x41825e20, + 0x41956c20, + 0x17372723, + 0x23418841, + 0x264b4073, + 0x3823418e, + 0x82c90ec5, + 0x02732641, + 0x038d0032, + 0x05914127, + 0x2408e54f, + 0x16141506, + 0x15084217, + 0x3a241b2a, + 0x25073a40, + 0x1e121820, + 0x2e150342, + 0x1f220732, + 0x27011e1e, + 0x0a0e1001, + 0x4178050f, + 0x068606fd, + 0x64207182, + 0x8020b382, + 0xf552b388, + 0x1706210b, + 0x2008b482, + 0x1b140a78, + 0x463b0449, + 0x329e2d1c, + 0x41024a2a, + 0x13170526, + 0x02330427, + 0x261d292a, + 0xc90a1815, + 0x0585430e, + 0x73002f22, + 0xa12343a3, + 0x8f274a3f, + 0x8af88343, + 0xcfce18f9, + 0x94412028, + 0x088123ef, + 0x65461812, + 0x8dcb2006, + 0x992508eb, + 0x0a0f0521, + 0x2701100e, + 0x1f1e1e01, + 0x00060022, + 0x034eff32, + 0x00ba02b6, + 0x003e0033, + 0x00540049, + 0x0063005f, + 0x06354a00, + 0x2335332e, + 0x34352622, + 0x16323336, + 0x33151516, + 0x2406b761, + 0x23061415, + 0xdb5d1823, + 0x26222507, + 0x23353526, + 0x06231282, + 0x82363227, + 0x06222509, + 0x13161415, + 0x26212a82, + 0x200a8423, + 0x60288225, + 0x112306ee, + 0x82331614, + 0x26342423, + 0x82252323, + 0x4ad03159, + 0x32667654, + 0x54766632, + 0x2754444a, + 0x435527ca, + 0x5430108e, + 0x493b3544, + 0x572c493a, + 0x30353b49, + 0xeb01492c, + 0x30240c83, + 0x363a3a36, + 0x3a3a0d82, + 0xcae7fe49, + 0x435ab2ca, + 0x59d45956, + 0x3b594258, + 0x26264267, + 0x593b6742, + 0x10825842, + 0x5a435627, + 0x263e683e, + 0x31048226, + 0x374c483f, + 0x3c24303b, + 0x48372302, + 0x30243c4c, + 0x0e84373b, + 0xf2fd4c24, + 0x0e83484c, + 0xd4423508, + 0x00020000, + 0x03f4ff26, + 0x009602c2, + 0x000b0007, + 0x21010500, + 0x21012135, + 0x21350115, + 0xfe8a0215, + 0x01f7fea5, + 0x015b0138, + 0x01b1fe09, + 0x5c020c4f, + 0x46a4fd46, + 0x46320582, + 0x00030000, + 0x03fcff14, + 0x008e0293, + 0x000a0005, + 0x39820016, + 0x21013529, + 0x11212511, + 0x4d050321, + 0x01360ada, + 0x01effe25, + 0xfd6e0211, + 0xfef701bf, + 0x3f01e309, + 0x2c90902c, + 0x02848f8f, + 0x4b010438, + 0xfd430104, + 0x16023e6e, + 0x2cc0f9fe, + 0x952d9394, + 0x94932d95, + 0x9582942c, + 0xff154108, + 0x020b03cb, + 0x000900c4, + 0x17000013, + 0x01272311, + 0x23070133, + 0x11332511, + 0x23013733, + 0xe3331701, + 0x790110be, + 0x10790104, + 0xe2e2febe, + 0xf2fe029d, + 0x02f2fe04, + 0x6901359d, + 0xfe690127, + 0x97fe2797, + 0x042f0a82, + 0xfafe0601, + 0x00010004, + 0x0287015e, + 0x82d302c2, + 0x003108ab, + 0x01012713, + 0x308e2507, + 0x32013201, + 0x01fefe30, + 0x1a013287, + 0xf332e6fe, + 0x1e00ffff, + 0xd7010000, + 0x2600d402, + 0x00002100, + 0x24000700, + 0x00002401, + 0x231782ff, + 0xfc01f4ff, + 0x2720178a, + 0x21821783, + 0x1400002a, + 0x0300f600, + 0x09040100, + 0xc6200d82, + 0x0b850382, + 0x49820120, + 0x1786c620, + 0x0e000224, + 0x0b86e400, + 0x4c000324, + 0x0b86f200, + 0x238a0420, + 0x64000524, + 0x17863e01, + 0x2a000624, + 0x0b86a201, + 0xc0000724, + 0x0b86cc01, + 0x34000824, + 0x0b868c02, + 0x18000924, + 0x0b86c002, + 0x32000b24, + 0x0b86d802, + 0x20030d24, + 0x0b860a03, + 0x34000e24, + 0x0b852a06, + 0x00000125, + 0x865e0638, + 0x0001240b, + 0x86960618, + 0x0002240b, + 0x86ae0614, + 0x0003240b, + 0x86c20616, + 0x8204200b, + 0x2553860b, + 0x12000501, + 0x1786ee06, + 0x1e00062e, + 0xa9000007, + 0x32002000, + 0x31003000, + 0x20220382, + 0x0d882d00, + 0x09823820, + 0x64004128, + 0x62006f00, + 0x0b826500, + 0x79005326, + 0x74007300, + 0x6d200b82, + 0x20260782, + 0x6e004900, + 0x1d826300, + 0x70007222, + 0x61200584, + 0x64201b84, + 0x28222982, + 0x0b826800, + 0x17827420, + 0x2f003a22, + 0x77210182, + 0x22018300, + 0x8861002e, + 0x842e204d, + 0x826d2039, + 0x0029221b, + 0x2231822c, + 0x82690077, + 0x82682031, + 0x82522009, + 0x8273205f, + 0x00722203, + 0x83058276, + 0x8246204d, + 0x826e205d, + 0x0020221d, + 0x2041824e, + 0x2415826d, + 0x00182020, + 0x22158253, + 0x82720075, + 0x20652447, + 0x8b2e0019, + 0x20ab840f, + 0x209d8261, + 0x20098273, + 0x21238250, + 0x5583006f, + 0x75006724, + 0x41826c00, + 0xed827220, + 0x30002e30, + 0x35003400, + 0x41003b00, + 0x42004400, + 0x09824f00, + 0x0021518a, + 0x20278253, + 0x85e5826e, + 0x8e2d203d, + 0x2035853f, + 0x2237824f, + 0x84560045, + 0x827320ab, + 0x826f20bf, + 0x8c202071, + 0x8268205b, + 0x847420a3, + 0x826e20e9, + 0x002022cd, + 0x20a78231, + 0x20038230, + 0x207d8231, + 0x20718239, + 0x2065826d, + 0x203f826b, + 0x20dd826f, + 0x20078266, + 0x85038278, + 0x82352041, + 0x82362025, + 0x0035249f, + 0x8c360039, + 0x8b999ddb, + 0x822020c3, + 0x00732293, + 0x20638220, + 0x205f8220, + 0x20078272, + 0x835f8264, + 0x00722273, + 0x2217826b, + 0x4166006f, + 0x692038e1, + 0x7422eb84, + 0xb1846800, + 0x0d825520, + 0xfd416920, + 0x82532008, + 0x050b4209, + 0x6e287d85, + 0x2f006400, + 0x72006f00, + 0x33857384, + 0x63200b83, + 0x75201382, + 0x74203982, + 0x69201982, + 0x73204782, + 0x6f42f382, + 0x82502033, + 0x007522d9, + 0x205d826c, + 0x23418244, + 0x00480020, + 0x83425585, + 0x00742429, + 0x82700079, + 0x82542081, + 0x006921cf, + 0x7342b583, + 0x82532009, + 0x826620a5, + 0x827720d1, + 0x84722065, + 0x242185ed, + 0x0069006c, + 0x200f8263, + 0x202f826e, + 0x20e18265, + 0x20758420, + 0x83118264, + 0x26e585db, + 0x00530020, + 0x824c0049, + 0x844f2099, + 0x826e205f, + 0x20598909, + 0x20418c4c, + 0x421b822c, + 0x31200f4b, + 0x0383cf82, + 0x89002021, + 0x41778d99, + 0x762009e3, + 0x69229f82, + 0x05826c00, + 0x05826220, + 0x53436520, + 0x8461200c, + 0x00412277, + 0x20078251, + 0x20cb8261, + 0x4107823a, + 0x73200d1d, + 0x7224cb82, + 0x70006900, + 0x73201d82, + 0x73207582, + 0x6c200b82, + 0x6f2a0782, + 0x67007200, + 0x4f002f00, + 0xc7824600, + 0x37822e20, + 0x202b2341, + 0x20458264, + 0x83518273, + 0x00622259, + 0x08214275, + 0x2a052943, + 0x006e0061, + 0x00182020, + 0x82530041, + 0x00492457, + 0x82192053, + 0x84422007, + 0x210d820f, + 0x0d822c00, + 0x49005722, + 0x4820fb82, + 0x55207f82, + 0x20220782, + 0x1d825700, + 0x52005222, + 0x4e200582, + 0x49220f82, + 0x3b844500, + 0x11824f20, + 0x43002022, + 0x4e222582, + 0x31844400, + 0x0b844920, + 0xb9835783, + 0x2f842020, + 0x4f825920, + 0x1d824b20, + 0x5b832383, + 0x9d826520, + 0x22098d42, + 0x82780065, + 0x007224fd, + 0x82730065, + 0x42202001, + 0x692206af, + 0x15826d00, + 0x29826c20, + 0x64006524, + 0x41822e00, + 0x21825320, + 0x07826520, + 0x2231e141, + 0x86660020, + 0x203b8755, + 0x225b8273, + 0x82630065, + 0x8266205d, + 0x82632003, + 0x006c2855, + 0x006e0061, + 0x82750067, + 0x82672007, + 0x822c2069, + 0x82702013, + 0x82722007, + 0x84692087, + 0x82692099, + 0x846e2043, + 0x202983a1, + 0x83338464, + 0x436920a5, + 0x1f890675, + 0x29826720, + 0x3b847620, + 0x5d826e20, + 0x55826e20, + 0x79002022, + 0x75221382, + 0x35827200, + 0x43827520, + 0x0544c783, + 0x42918305, + 0x2e201ff9, + 0x420ed545, + 0x50202533, + 0x65206d82, + 0x6520f982, + 0x72200782, + 0xb1838d82, + 0xab824120, + 0xe1826820, + 0x03826220, + 0x6b007322, + 0x2020f384, + 0xb1839982, + 0x23826e20, + 0x9b826b20, + 0x6c005322, + 0x68201d84, + 0x7a203386, + 0x72200782, + 0x53202382, + 0x72203b82, + 0x69201982, + 0x6820cf82, + 0x20200b82, + 0x41202782, + 0x74200382, + 0x6e201f84, + 0x09831982, + 0x07822020, + 0x67221593, + 0x27845300, + 0x91846920, + 0x49248b83, + 0x69005400, + 0x6c204782, + 0x20082341, + 0x22098266, + 0x84750067, + 0x007323b7, + 0x00840002, + 0x00ceff23, + 0x8e088432, + 0xb6072104, + 0x033c1082, + 0x25002400, + 0x27002600, + 0x29002800, + 0x2b002a00, + 0x2d002c00, + 0x2f002e00, + 0x31003000, + 0x32083782, + 0x00340033, + 0x00360035, + 0x00380037, + 0x003a0039, + 0x003c003b, + 0x0044003d, + 0x00460045, + 0x00480047, + 0x004a0049, + 0x004c004b, + 0x004e004d, + 0x0050004f, + 0x82520051, + 0x290f07a7, + 0x00550054, + 0x00570056, + 0x00590058, + 0x005b005a, + 0x005d005c, + 0x00c900ad, + 0x00ae00c7, + 0x01020162, + 0x01630003, + 0x01050104, + 0x01070106, + 0x01090108, + 0x010b010a, + 0x010d010c, + 0x010f010e, + 0x01110110, + 0x00130112, + 0x01140190, + 0x01160115, + 0x00180117, + 0x01fd0064, + 0x01ff0019, + 0x011b011a, + 0x011d011c, + 0x001f011e, + 0x006500cb, + 0x002001c8, + 0x012101ca, + 0x01230122, + 0x01250124, + 0x01270126, + 0x01290128, + 0x012b012a, + 0x012d012c, + 0x012f012e, + 0x01310130, + 0x01f80032, + 0x01340133, + 0x01360135, + 0x01380137, + 0x013a0139, + 0x013c013b, + 0x00cf003d, + 0x01cd00cc, + 0x01ce003e, + 0x01fa003f, + 0x01410140, + 0x01430142, + 0x01450144, + 0x01470146, + 0x01490148, + 0x014b014a, + 0x014d014c, + 0x014f014e, + 0x01e20050, + 0x01520151, + 0x01540153, + 0x00560155, + 0x01570166, + 0x01590158, + 0x00d3005a, + 0x00d100d0, + 0x016700af, + 0x015c015b, + 0x015e015d, + 0x0160015f, + 0x01620161, + 0x01640163, + 0x00660165, + 0x01b00091, + 0x01680167, + 0x016a0169, + 0x016c016b, + 0x016e016d, + 0x0170016f, + 0x01720171, + 0x01740173, + 0x01760175, + 0x00780177, + 0x017901e4, + 0x017b017a, + 0x017d017c, + 0x017f017e, + 0x01810180, + 0x01830182, + 0x00850184, + 0x00d400d6, + 0x008601d5, + 0x01870168, + 0x01890188, + 0x018b018a, + 0x018d018c, + 0x018f018e, + 0x01910190, + 0x01930192, + 0x01950194, + 0x01970196, + 0x01990198, + 0x019b019a, + 0x019d019c, + 0x01eb009e, + 0x01bb009f, + 0x01a101a0, + 0x01a301a2, + 0x01e600a4, + 0x01a601a5, + 0x00e900a7, + 0x01a801ed, + 0x00aa01a9, + 0x0069006a, + 0x006d006b, + 0x01ab016c, + 0x016e00ac, + 0x01ae01ad, + 0x01b001af, + 0x01b201b1, + 0x01b401b3, + 0x01b601b5, + 0x01b801b7, + 0x01ba01b9, + 0x00bc01bb, + 0x01bd01a0, + 0x01bf01be, + 0x00c101c0, + 0x01fe006f, + 0x010001c2, + 0x01c401c3, + 0x01c601c5, + 0x000101c7, + 0x00700071, + 0x00c80172, + 0x01c90173, + 0x01cb01ca, + 0x01cd01cc, + 0x01cf01ce, + 0x01d101d0, + 0x01d301d2, + 0x01d501d4, + 0x01d701d6, + 0x01d901d8, + 0x01f900da, + 0x01dc01db, + 0x01de01dd, + 0x01e001df, + 0x01e201e1, + 0x00e401e3, + 0x00740075, + 0x00e50176, + 0x01e60177, + 0x01e801e7, + 0x01ea01e9, + 0x00ec01eb, + 0x01ed01d7, + 0x01ef01ee, + 0x01f101f0, + 0x01f301f2, + 0x01f501f4, + 0x01f701f6, + 0x01e300f8, + 0x01fa01f9, + 0x01fc01fb, + 0x00fe01fd, + 0x02ff0178, + 0x02010200, + 0x00030202, + 0x0079007a, + 0x007d007b, + 0x0204027c, + 0x02060205, + 0x02080207, + 0x020a0209, + 0x020c020b, + 0x020e020d, + 0x00a1000f, + 0x021002b1, + 0x02120211, + 0x02140213, + 0x02160215, + 0x02180217, + 0x021a0219, + 0x021c021b, + 0x021e021d, + 0x0220021f, + 0x02e50021, + 0x02230222, + 0x00250224, + 0x02260289, + 0x02280227, + 0x022a0229, + 0x022c022b, + 0x007f002d, + 0x0280007e, + 0x0281002e, + 0x0230022f, + 0x02320231, + 0x02340233, + 0x02360235, + 0x02380237, + 0x023a0239, + 0x023c023b, + 0x023e023d, + 0x0240023f, + 0x02420241, + 0x02440243, + 0x02460245, + 0x02ec0047, + 0x02ba0048, + 0x024a0249, + 0x024c024b, + 0x02e7004d, + 0x024f024e, + 0x00ea0050, + 0x025102ee, + 0x02530252, + 0x02550254, + 0x02570256, + 0x02590258, + 0x025b025a, + 0x025d025c, + 0x025f025e, + 0x02610260, + 0x02630262, + 0x02650264, + 0x02670266, + 0x02690268, + 0x026b026a, + 0x026d026c, + 0x026f026e, + 0x02710270, + 0x02730272, + 0x02750274, + 0x02770276, + 0x02790278, + 0x027b027a, + 0x027d027c, + 0x027f027e, + 0x02810280, + 0x02830282, + 0x02850284, + 0x02870286, + 0x02890288, + 0x028b028a, + 0x028d028c, + 0x028f028e, + 0x02910290, + 0x02930292, + 0x02950294, + 0x02970296, + 0x02990298, + 0x029b029a, + 0x029d029c, + 0x029f029e, + 0x02a102a0, + 0x02a302a2, + 0x02a502a4, + 0x02a702a6, + 0x02a902a8, + 0x02ab02aa, + 0x02ad02ac, + 0x02af02ae, + 0x02b102b0, + 0x02b302b2, + 0x02b502b4, + 0x02b702b6, + 0x02b902b8, + 0x02bb02ba, + 0x02bd02bc, + 0x02bf02be, + 0x02c102c0, + 0x02c302c2, + 0x02c502c4, + 0x02c702c6, + 0x02c902c8, + 0x02cb02ca, + 0x02cd02cc, + 0x02cf02ce, + 0x02d102d0, + 0x02d302d2, + 0x02d502d4, + 0x02d702d6, + 0x02d902d8, + 0x02db02da, + 0x02dd02dc, + 0x02df02de, + 0x02e102e0, + 0x02e302e2, + 0x02e502e4, + 0x02a800e6, + 0x02e802e7, + 0x02ea02e9, + 0x02ec02eb, + 0x02ee02ed, + 0x02f002ef, + 0x02f202f1, + 0x02f402f3, + 0x02f602f5, + 0x02f802f7, + 0x029f00f9, + 0x02fb02fa, + 0x02fd02fc, + 0x03ff02fe, + 0x03010300, + 0x03030302, + 0x03050304, + 0x03070306, + 0x03090308, + 0x030b030a, + 0x000d030c, + 0x030e0397, + 0x0010030f, + 0x0311039b, + 0x03130312, + 0x03150314, + 0x03170316, + 0x03190318, + 0x031b031a, + 0x031d031c, + 0x031f031e, + 0x03210320, + 0x03230322, + 0x03250324, + 0x03270326, + 0x03290328, + 0x032b032a, + 0x032d032c, + 0x032f032e, + 0x03310330, + 0x03330332, + 0x03350334, + 0x03370336, + 0x03390338, + 0x033b033a, + 0x033d033c, + 0x033f033e, + 0x03410340, + 0x03430342, + 0x03450344, + 0x03470346, + 0x03490348, + 0x034b034a, + 0x034d034c, + 0x034f034e, + 0x03510350, + 0x03530352, + 0x03550354, + 0x03570356, + 0x03590358, + 0x035b035a, + 0x035d035c, + 0x035f035e, + 0x03610360, + 0x03630362, + 0x03650364, + 0x03670366, + 0x03690368, + 0x036b036a, + 0x036d036c, + 0x036f036e, + 0x03710370, + 0x03730372, + 0x03750374, + 0x03770376, + 0x03790378, + 0x037b037a, + 0x037d037c, + 0x037f037e, + 0x03810380, + 0x03830382, + 0x03850384, + 0x03870386, + 0x03890388, + 0x038b038a, + 0x038d038c, + 0x038f038e, + 0x03910390, + 0x03930392, + 0x03950394, + 0x03970396, + 0x03990398, + 0x039b039a, + 0x039d039c, + 0x039f039e, + 0x03a103a0, + 0x03a303a2, + 0x03a503a4, + 0x03a703a6, + 0x03a903a8, + 0x03ab03aa, + 0x03ad03ac, + 0x03af03ae, + 0x03b103b0, + 0x03b303b2, + 0x03b503b4, + 0x03b703b6, + 0x03b903b8, + 0x03bb03ba, + 0x03bd03bc, + 0x03bf03be, + 0x03c103c0, + 0x03c303c2, + 0x03c503c4, + 0x03c703c6, + 0x03c903c8, + 0x03cb03ca, + 0x03cd03cc, + 0x03cf03ce, + 0x03d103d0, + 0x03d303d2, + 0x03d503d4, + 0x03d703d6, + 0x03d903d8, + 0x03db03da, + 0x03dd03dc, + 0x03df03de, + 0x03e103e0, + 0x03e303e2, + 0x03e503e4, + 0x03e703e6, + 0x03e903e8, + 0x03eb03ea, + 0x03ed03ec, + 0x03ef03ee, + 0x03f103f0, + 0x03f303f2, + 0x03f503f4, + 0x03f703f6, + 0x03f903f8, + 0x03fb03fa, + 0x03fd03fc, + 0x04ff03fe, + 0x04010400, + 0x04030402, + 0x04050404, + 0x04070406, + 0x04090408, + 0x040b040a, + 0x040d040c, + 0x040f040e, + 0x04110410, + 0x04130412, + 0x04150414, + 0x04170416, + 0x04190418, + 0x041b041a, + 0x041d041c, + 0x041f041e, + 0x04210420, + 0x04230422, + 0x04250424, + 0x04270426, + 0x04290428, + 0x042b042a, + 0x042d042c, + 0x042f042e, + 0x04310430, + 0x04330432, + 0x04350434, + 0x04370436, + 0x04390438, + 0x043b043a, + 0x043d043c, + 0x043f043e, + 0x04410440, + 0x04430442, + 0x04450444, + 0x04470446, + 0x04490448, + 0x044b044a, + 0x044d044c, + 0x044f044e, + 0x04510450, + 0x04530452, + 0x04550454, + 0x04570456, + 0x04590458, + 0x045b045a, + 0x045d045c, + 0x045f045e, + 0x04610460, + 0x04630462, + 0x04650464, + 0x04670466, + 0x04690468, + 0x046b046a, + 0x046d046c, + 0x046f046e, + 0x04710470, + 0x04730472, + 0x04750474, + 0x04770476, + 0x04790478, + 0x047b047a, + 0x047d047c, + 0x047f047e, + 0x04810480, + 0x04830482, + 0x04850484, + 0x04870486, + 0x04890488, + 0x048b048a, + 0x048d048c, + 0x048f048e, + 0x04910490, + 0x04930492, + 0x04950494, + 0x04970496, + 0x04990498, + 0x049b049a, + 0x049d049c, + 0x049f049e, + 0x04a104a0, + 0x04a304a2, + 0x04a504a4, + 0x04a704a6, + 0x04a904a8, + 0x04ab04aa, + 0x04ad04ac, + 0x04af04ae, + 0x04b104b0, + 0x04b304b2, + 0x04b504b4, + 0x04b704b6, + 0x04b904b8, + 0x04bb04ba, + 0x04bd04bc, + 0x04bf04be, + 0x04c104c0, + 0x000900c2, + 0x00140013, + 0x00160015, + 0x00180017, + 0x001a0019, + 0x041c001b, + 0x04c404c3, + 0x04c604c5, + 0x04c804c7, + 0x04ca04c9, + 0x04cc04cb, + 0x04ce04cd, + 0x04d004cf, + 0x04d204d1, + 0x04d404d3, + 0x04d604d5, + 0x04d804d7, + 0x04da04d9, + 0x04dc04db, + 0x04de04dd, + 0x04e004df, + 0x04e204e1, + 0x04e404e3, + 0x04e604e5, + 0x04e804e7, + 0x04ea04e9, + 0x04ec04eb, + 0x00ee04ed, + 0x000f0011, + 0x001e001d, + 0x000400ab, + 0x002200a3, + 0x000a00a2, + 0x00b60005, + 0x00b400b7, + 0x00c400b5, + 0x00be00c5, + 0x00a900bf, + 0x001000aa, + 0x04b300b2, + 0x04f004ef, + 0x00f204f1, + 0x008700c3, + 0x04f30442, + 0x000b00f4, + 0x003e000c, + 0x005e0040, + 0x00120060, + 0x003f005f, + 0x000d00e8, + 0x00c20082, + 0x04880086, + 0x04f604f5, + 0x04f804f7, + 0x04fa04f9, + 0x04fc04fb, + 0x04fe04fd, + 0x050005ff, + 0x05020501, + 0x00040503, + 0x0005058b, + 0x058c008a, + 0x05070506, + 0x05230008, + 0x05060009, + 0x050b050a, + 0x050d050c, + 0x050f050e, + 0x05110510, + 0x05130512, + 0x05150514, + 0x05170516, + 0x05190518, + 0x051b051a, + 0x051d051c, + 0x051f051e, + 0x05210520, + 0x05230522, + 0x05250524, + 0x05270526, + 0x05290528, + 0x052b052a, + 0x052d052c, + 0x052f052e, + 0x05310530, + 0x05330532, + 0x05350534, + 0x05370536, + 0x05390538, + 0x053b053a, + 0x053d053c, + 0x053f053e, + 0x05410540, + 0x05430542, + 0x05450544, + 0x05470546, + 0x05490548, + 0x054b054a, + 0x054d054c, + 0x054f054e, + 0x05510550, + 0x05530552, + 0x05550554, + 0x05570556, + 0x05590558, + 0x055b055a, + 0x055d055c, + 0x055f055e, + 0x05610560, + 0x05630562, + 0x05650564, + 0x05670566, + 0x05690568, + 0x056b056a, + 0x056d056c, + 0x056f056e, + 0x05710570, + 0x05730572, + 0x05750574, + 0x05770576, + 0x05790578, + 0x057b057a, + 0x057d057c, + 0x057f057e, + 0x05810580, + 0x05830582, + 0x05850584, + 0x05870586, + 0x05890588, + 0x058b058a, + 0x058d058c, + 0x058f058e, + 0x05910590, + 0x05930592, + 0x05950594, + 0x05970596, + 0x05990598, + 0x059b059a, + 0x059d059c, + 0x059f059e, + 0x05a105a0, + 0x05a305a2, + 0x05a505a4, + 0x05a705a6, + 0x05a905a8, + 0x05ab05aa, + 0x05ad05ac, + 0x05af05ae, + 0x05b105b0, + 0x05b305b2, + 0x05b505b4, + 0x05b705b6, + 0x05b905b8, + 0x05bb05ba, + 0x05bd05bc, + 0x05bf05be, + 0x05c105c0, + 0x05c305c2, + 0x05c505c4, + 0x05c705c6, + 0x05c905c8, + 0x05cb05ca, + 0x05cd05cc, + 0x05cf05ce, + 0x05d105d0, + 0x05d305d2, + 0x05d505d4, + 0x05d705d6, + 0x05d905d8, + 0x05db05da, + 0x05dd05dc, + 0x05df05de, + 0x05e105e0, + 0x05e305e2, + 0x05e505e4, + 0x05e705e6, + 0x05e905e8, + 0x05eb05ea, + 0x05ed05ec, + 0x05ef05ee, + 0x05f105f0, + 0x05f305f2, + 0x05f505f4, + 0x05f705f6, + 0x05f905f8, + 0x05fb05fa, + 0x05fd05fc, + 0x06ff05fe, + 0x06010600, + 0x06030602, + 0x06050604, + 0x06070606, + 0x06090608, + 0x060b060a, + 0x060d060c, + 0x060f060e, + 0x06110610, + 0x06130612, + 0x06150614, + 0x06170616, + 0x06190618, + 0x061b061a, + 0x061d061c, + 0x061f061e, + 0x06210620, + 0x06230622, + 0x06250624, + 0x06270626, + 0x06290628, + 0x062b062a, + 0x062d062c, + 0x062f062e, + 0x06310630, + 0x06330632, + 0x06350634, + 0x06370636, + 0x06390638, + 0x063b063a, + 0x063d063c, + 0x063f063e, + 0x06410640, + 0x06430642, + 0x06450644, + 0x06470646, + 0x06490648, + 0x064b064a, + 0x064d064c, + 0x064f064e, + 0x06510650, + 0x06530652, + 0x06550654, + 0x06570656, + 0x06590658, + 0x065b065a, + 0x065d065c, + 0x065f065e, + 0x06610660, + 0x06630662, + 0x06650664, + 0x06670666, + 0x06690668, + 0x066b066a, + 0x066d066c, + 0x066f066e, + 0x06710670, + 0x06730672, + 0x06750674, + 0x06770676, + 0x06790678, + 0x067b067a, + 0x067d067c, + 0x067f067e, + 0x06810680, + 0x06830682, + 0x06850684, + 0x06870686, + 0x06890688, + 0x068b068a, + 0x068d068c, + 0x068f068e, + 0x06910690, + 0x06930692, + 0x06950694, + 0x06970696, + 0x06990698, + 0x069b069a, + 0x069d069c, + 0x069f069e, + 0x06a106a0, + 0x06a306a2, + 0x06a506a4, + 0x06a706a6, + 0x06a906a8, + 0x06ab06aa, + 0x06ad06ac, + 0x06af06ae, + 0x06b106b0, + 0x06b306b2, + 0x06b506b4, + 0x06b706b6, + 0x06b906b8, + 0x00bb06ba, + 0x00bc069d, + 0x06bd069e, + 0x06bf06be, + 0x06c106c0, + 0x06c306c2, + 0x06c506c4, + 0x06c706c6, + 0x06c906c8, + 0x06cb06ca, + 0x06cd06cc, + 0x06cf06ce, + 0x06d106d0, + 0x06d306d2, + 0x06d506d4, + 0x06d706d6, + 0x06d906d8, + 0x06db06da, + 0x06dd06dc, + 0x06df06de, + 0x06e106e0, + 0x06e306e2, + 0x06e506e4, + 0x06e706e6, + 0x06e906e8, + 0x06eb06ea, + 0x06ed06ec, + 0x06ef06ee, + 0x06f106f0, + 0x06f306f2, + 0x06f506f4, + 0x06f706f6, + 0x06f906f8, + 0x06fb06fa, + 0x06fd06fc, + 0x00ff06fe, + 0x00bd0083, + 0x00850007, + 0x07000796, + 0x07840001, + 0x07030702, + 0x07050704, + 0x07070706, + 0x07090708, + 0x070b070a, + 0x070d070c, + 0x070f070e, + 0x00110710, + 0x071207bc, + 0x00080013, + 0x00f500c6, + 0x07f600f4, + 0x07150714, + 0x07170716, + 0x07190718, + 0x071b071a, + 0x071d071c, + 0x071f071e, + 0x07210720, + 0x00230722, + 0x00ef000e, + 0x07b800f0, + 0x00200024, + 0x0021001f, + 0x00950094, + 0x00410093, + 0x0061008f, + 0x00a400a7, + 0x00980092, + 0x00a5009c, + 0x079a0099, + 0x07260725, + 0x07280727, + 0x072a0729, + 0x072c072b, + 0x072e072d, + 0x0730072f, + 0x07320731, + 0x07340733, + 0x07360735, + 0x07380737, + 0x003a0739, + 0x073b07b9, + 0x073d073c, + 0x073f073e, + 0x00430040, + 0x00d8008d, + 0x074107e1, + 0x07430742, + 0x00450744, + 0x008e00d9, + 0x00db00da, + 0x00df00dd, + 0x00de00dc, + 0x074607e0, + 0x07480747, + 0x074a0749, + 0x074c074b, + 0x074e074d, + 0x0750074f, + 0x07520751, + 0x07540753, + 0x07560755, + 0x07580757, + 0x075a0759, + 0x075c075b, + 0x075e075d, + 0x0760075f, + 0x07620761, + 0x07640763, + 0x07660765, + 0x07680767, + 0x076a0769, + 0x076c076b, + 0x076e076d, + 0x0770076f, + 0x07720771, + 0x07740773, + 0x07760775, + 0x07780777, + 0x077a0779, + 0x077c077b, + 0x077e077d, + 0x0780077f, + 0x07820781, + 0x07840783, + 0x07860785, + 0x07880787, + 0x078a0789, + 0x078c078b, + 0x078e078d, + 0x0790078f, + 0x07920791, + 0x07940793, + 0x07960795, + 0x07980797, + 0x079a0799, + 0x079c079b, + 0x079e079d, + 0x07a0079f, + 0x07a207a1, + 0x07a407a3, + 0x07a607a5, + 0x07a807a7, + 0x07aa07a9, + 0x07ac07ab, + 0x07ae07ad, + 0x07b007af, + 0x07b207b1, + 0x07b407b3, + 0x07b607b5, + 0x07b807b7, + 0x07ba07b9, + 0x07bc07bb, + 0x07be07bd, + 0x00c007bf, + 0x07c100c0, + 0x63616d41, + 0x066e6f72, + 0x65726241, + 0x75076576, + 0x3130696e, + 0x07834443, + 0x41453123, + 0x20078630, + 0x20078632, + 0x20078634, + 0x20078636, + 0x20078638, + 0x20078641, + 0x20078643, + 0x21078545, + 0x07863042, + 0x42203f86, + 0x422a3f86, + 0x6f410736, + 0x656e6f67, + 0x0786096b, + 0x0b642e22, + 0x30257984, + 0x30333034, + 0x20858531, + 0x224d8446, + 0x84453130, + 0x3230233d, + 0x4d853334, + 0x0f843020, + 0x3045313e, + 0x63430b36, + 0x75637269, + 0x656c666d, + 0x64430a78, + 0x6361746f, + 0x746e6563, + 0x61634406, + 0x2d86d282, + 0x30209b86, + 0x35824d84, + 0x1e824520, + 0x616f7225, + 0x85450674, + 0x41452025, + 0x45270600, + 0x76657262, + 0x88450a65, + 0x203f8546, + 0x20e38642, + 0x20478642, + 0x20478642, + 0x21e38642, + 0x27853043, + 0x95864320, + 0xe3864320, + 0x07364323, + 0x86e38645, + 0x21e38707, + 0xe3873831, + 0x31453122, + 0x20064941, + 0x254d8431, + 0x34463130, + 0xd38a470b, + 0x8c8c4720, + 0x32313025, + 0x8a470632, + 0x303229db, + 0x696e750b, + 0x37343030, + 0x33205182, + 0x23053541, + 0x480b3339, + 0x9b854189, + 0x93863220, + 0x09413222, + 0x31332f82, + 0x2e363945, + 0x62480463, + 0x49067261, + 0x646c6974, + 0x41490765, + 0x41850503, + 0x85464321, + 0x86432035, + 0x414323f9, + 0xc9854907, + 0x31226d84, + 0xa3414532, + 0x43322309, + 0x6d8d4a0b, + 0x33313022, + 0x3320d386, + 0x2a061141, + 0x4c063433, + 0x74756361, + 0x884c0665, + 0x222582bb, + 0x824c0442, + 0x886a85dd, + 0x20728632, + 0x066c4133, + 0x85453321, + 0x3034211f, + 0x32220786, + 0x4a844e06, + 0x4623a985, + 0x8a4e0638, + 0x35342152, + 0xee862586, + 0x88863420, + 0x07383423, + 0x2de0854f, + 0x75684f0d, + 0x7261676e, + 0x616c6d75, + 0x44857475, + 0x85314421, + 0x41432035, + 0x432006d8, + 0x44207386, + 0x44207386, + 0x4420c686, + 0x44205586, + 0x44205586, + 0x3022ab84, + 0x2f863431, + 0x05323527, + 0x726f684f, + 0x204d856e, + 0x20c18644, + 0x20558644, + 0x21258644, + 0x1f853045, + 0x2206d442, + 0x41414531, + 0x45210554, + 0x09144241, + 0x06363523, + 0x21e58452, + 0xdd885206, + 0x35453122, + 0x35206f86, + 0x35217f86, + 0x20498541, + 0x23618635, + 0x53064535, + 0x0b213584, + 0x0f914153, + 0x7c843520, + 0x31323022, + 0x31224284, + 0x84863645, + 0xda863620, + 0x06453923, + 0x20698a54, + 0x21598436, + 0x1e853130, + 0x0f843682, + 0x69863682, + 0x42453621, + 0x37220646, + 0x4341632e, + 0x36362305, + 0x49425506, + 0x41552005, + 0x062e0568, + 0x65726255, + 0x55056576, + 0x676e6972, + 0x7541550d, + 0x06ae4212, + 0x85354421, + 0x37442141, + 0x39200786, + 0x42200786, + 0x4520dd85, + 0x23067541, + 0x55053645, + 0x20095d41, + 0x20c88645, + 0x20998645, + 0x20998645, + 0x25e88445, + 0x30464531, + 0xb2425507, + 0x32372e0b, + 0x31303330, + 0x72675706, + 0x06657661, + 0x05264157, + 0x26415720, + 0x57092b09, + 0x72656964, + 0x73697365, + 0x23845906, + 0x41590b21, + 0x31220d43, + 0x5a873845, + 0x46209086, + 0x23068641, + 0x5a063846, + 0x0a214f84, + 0x0cac435a, + 0x39453122, + 0x84075d41, + 0x31302331, + 0xda854638, + 0xb4843420, + 0x33313025, + 0x41610732, + 0x6120062d, + 0x860b7c45, + 0x31412168, + 0x21050141, + 0x07863341, + 0x07863520, + 0x07863720, + 0x07863920, + 0x20062941, + 0x07b44541, + 0x31236684, + 0x85314245, + 0x8642201f, + 0x8642203f, + 0x3742233f, + 0x1b416107, + 0x86092005, + 0x07984407, + 0x43353021, + 0x462009d8, + 0x30224d84, + 0x3d844531, + 0x3020bc82, + 0x30204d85, + 0x31250f84, + 0x0b373045, + 0x09224163, + 0x88630a21, + 0x640621fb, + 0x200a4942, + 0x209b8630, + 0x824d8430, + 0x06462235, + 0x201e8565, + 0x20f98665, + 0x21f98465, + 0x3b41650a, + 0x8642200e, + 0x864220dc, + 0x86422040, + 0x86422040, + 0x314321dc, + 0x43208e85, + 0x43208e86, + 0x4323dc86, + 0x86650737, + 0x450786dc, + 0x39200875, + 0x20096043, + 0x06424131, + 0x4d843120, + 0x46313025, + 0x8a670b35, + 0x8c6720cc, + 0x3130258c, + 0x67063332, + 0x3229d48a, + 0x6e750b31, + 0x36303069, + 0x22518237, + 0x42680b33, + 0x32200f29, + 0x39208b86, + 0x28062142, + 0x68044232, + 0x06726162, + 0x05214369, + 0x6b456920, + 0x0764440b, + 0xef864320, + 0x07424323, + 0x0c6b4569, + 0x92414620, + 0x44322309, + 0x6b8d6a0b, + 0x33313022, + 0x3320c986, + 0x37060741, + 0x6b0c3533, + 0x65657267, + 0x6e616c6e, + 0x06636964, + 0x7563616c, + 0x6c066574, + 0x0421be84, + 0x0670456c, + 0x43203782, + 0x88053f41, + 0x207f863f, + 0x066f4133, + 0x85463321, + 0x3134211f, + 0x33220786, + 0x78456e06, + 0x0639220b, + 0x0811416e, + 0x45313021, + 0xf9860868, + 0x95863420, + 0x0b39342f, + 0x6f70616e, + 0x6f727473, + 0x07656870, + 0x21f9856f, + 0x0e446f0d, + 0x062b4312, + 0x46077948, + 0x9c450783, + 0x86442007, + 0x052e44df, + 0x44453121, + 0x0782052e, + 0x8182b784, + 0x3523af86, + 0x446f0533, + 0x44200926, + 0x4420cd86, + 0x20063d42, + 0x21258644, + 0xd5853145, + 0x2907dc42, + 0x750b4245, + 0x3130696e, + 0x23424245, + 0x37352309, + 0xf18a7206, + 0xf1880e83, + 0x35453122, + 0x07827784, + 0x35206186, + 0x35236186, + 0x84730646, + 0x730b2135, + 0x200faa41, + 0x227c8435, + 0x86313230, + 0x8636203a, + 0x33362384, + 0x598a7406, + 0x51843620, + 0x36313022, + 0x2e82f184, + 0x31220f84, + 0x61863645, + 0x46843620, + 0x39453123, + 0x054d4437, + 0x06373623, + 0x05584275, + 0x5e417520, + 0x75062e05, + 0x76657262, + 0x72750565, + 0x0d676e69, + 0x126b4175, + 0x46068f44, + 0x302105c8, + 0x07c84631, + 0x8205b246, + 0x061b420f, + 0xcd414520, + 0x37452306, + 0x53417505, + 0x86452009, + 0x864520be, + 0x86452097, + 0x86452097, + 0x31462397, + 0xc1427507, + 0x86092005, + 0x07814307, + 0x3033372e, + 0x06313033, + 0x61726777, + 0x77066576, + 0x20052641, + 0x09264177, + 0x45770921, + 0x79200884, + 0x0b212384, + 0x0d434179, + 0x45453121, + 0x31220542, + 0x9a864645, + 0x41374621, + 0x462305c8, + 0x457a0639, + 0x7a200584, + 0x230cbb43, + 0x33394531, + 0x39202185, + 0x30223184, + 0xb6843431, + 0x42323021, + 0x302105f8, + 0x05384331, + 0x35323023, + 0x82278330, + 0x86322007, + 0x21378407, + 0x35453741, + 0x84178205, + 0x4241223f, + 0x82178435, + 0x8636200f, + 0x82818427, + 0x8638200f, + 0x8531200f, + 0x39392107, + 0x41200785, + 0x20056c41, + 0x05304232, + 0xfc452782, + 0x35322105, + 0xbd478786, + 0x20178205, + 0x422f8545, + 0xa2470725, + 0x32302105, + 0x82052542, + 0x42978607, + 0x36200716, + 0x17828f84, + 0x36208786, + 0x39218786, + 0x20478543, + 0x478f8636, + 0x322106cb, + 0x218f8636, + 0x1f864439, + 0x36207f86, + 0x17872f87, + 0x39218786, + 0x86278646, + 0x30372107, + 0x37200f85, + 0x3720df86, + 0x37208f86, + 0x20060f41, + 0x86e78737, + 0x86362007, + 0x86372007, + 0x863720a7, + 0x863720a7, + 0x863720a7, + 0x8637209f, + 0x41372097, + 0x37200617, + 0x37209786, + 0x37208f86, + 0x38218f86, + 0x217f8530, + 0x07863138, + 0x38207f86, + 0x38207f86, + 0x38206f86, + 0x41205786, + 0x38206786, + 0x38205f86, + 0x38205f86, + 0x38205f86, + 0x3820f786, + 0xde476786, + 0x32302105, + 0x23056142, + 0x30393230, + 0x39216785, + 0x84078631, + 0x4431216f, + 0x8205dc45, + 0x426f861f, + 0x32200657, + 0x2205ad47, + 0x84413230, + 0x31302127, + 0x82050e4c, + 0x269f8607, + 0x66033839, + 0x8205665f, + 0x695f2103, + 0x6c200584, + 0x74200f82, + 0x742b0984, + 0x612e4903, + 0x72674908, + 0x83657661, + 0x63612308, + 0x08827475, + 0x42490d21, + 0x168309fd, + 0x6c697423, + 0x21168264, + 0x2543490b, + 0x612e2207, + 0x06b74b09, + 0x0c612e23, + 0x08f74249, + 0x75221682, + 0x7982696e, + 0x09854620, + 0x43453123, + 0x20098838, + 0x23098541, + 0x43323130, + 0xd64b0982, + 0x612e2206, + 0x4b31840d, + 0x218705d8, + 0x2e413425, + 0x82610361, + 0x87612079, + 0x87612099, + 0x8c612099, + 0x87612099, + 0x8a612099, + 0x06d94899, + 0x62233e83, + 0x82766572, + 0x610725b8, + 0x676e6972, + 0x45209d88, + 0x31230985, + 0x88314145, + 0x88332009, + 0x88352009, + 0x88372009, + 0x88392009, + 0x88422009, + 0x88442009, + 0x20ed8809, + 0x204f8842, + 0x204f8842, + 0x214f8842, + 0x31823742, + 0x2007f748, + 0x08014961, + 0x01416220, + 0x05014905, + 0xa788f782, + 0x2e354624, + 0x1c480d61, + 0x20d0820a, + 0x20d08667, + 0x0927480c, + 0x82085541, + 0x48082071, + 0x1285052b, + 0x32453123, + 0x065e4131, + 0x82062f48, + 0x826c205c, + 0x05984744, + 0x632b0883, + 0x6e6f7261, + 0x6c06612e, + 0x85746f64, + 0x31302334, + 0x09854333, + 0x33453122, + 0x3320ff88, + 0x3320ff88, + 0x082bff82, + 0x616c736c, + 0x612e6873, + 0x826c6604, + 0x0634482b, + 0x09782e29, + 0x30696e75, + 0x87383632, + 0x44393e09, + 0x4105782e, + 0x6168706c, + 0x74654204, + 0x61470561, + 0x07616d6d, + 0x69737045, + 0x046e6f6c, + 0x2112825a, + 0x16824503, + 0x82685421, + 0x49042209, + 0x390a826f, + 0x7070614b, + 0x614c0661, + 0x6164626d, + 0x02754d02, + 0x5802754e, + 0x6d4f0769, + 0xa7826369, + 0x69500232, + 0x6f685203, + 0x67695305, + 0x5403616d, + 0x55077561, + 0x03254a85, + 0x03696850, + 0x23038243, + 0x0a697350, + 0x74256f84, + 0x736f6e6f, + 0x8469860c, + 0x8208200c, + 0x20088469, + 0x84688309, + 0x830c2009, + 0x07364209, + 0x64860c20, + 0x58861985, + 0x0f200c84, + 0x29870c86, + 0x6d4f0a25, + 0x84616765, + 0x6105211a, + 0x6220dc84, + 0x0521bf82, + 0x27dc8367, + 0x6c656405, + 0x65076174, + 0x04219785, + 0x2018827a, + 0x21038203, + 0xe2847405, + 0xe2836920, + 0xe2846b20, + 0xe2856c20, + 0x02756e26, + 0x6f076978, + 0x0321df85, + 0x20dc8272, + 0x20dc8473, + 0x20dc8274, + 0x21448575, + 0xd8827003, + 0x03826320, + 0x05210e82, + 0x257a836f, + 0x696e7507, + 0xe4433330, + 0x49332006, + 0x302405c5, + 0x05314433, + 0x2e222982, + 0x93840a61, + 0x86050041, + 0x05004187, + 0x00418782, + 0x41868305, + 0x09830500, + 0x86080041, + 0x86198585, + 0x200c847c, + 0x410c860f, + 0x85840800, + 0x11201a84, + 0x1184418b, + 0x2c8e1420, + 0xb1831484, + 0x30463123, + 0x20078638, + 0x50078539, + 0x462006d5, + 0x2206674b, + 0x85413046, + 0x42302117, + 0x43200786, + 0x44200786, + 0x45200786, + 0x46200786, + 0x1d510785, + 0x4b462006, + 0x462006af, + 0x2106614e, + 0x5f863146, + 0x20064350, + 0x06df4a46, + 0x86314621, + 0x8631205f, + 0x8631205f, + 0x8631205f, + 0x8632205f, + 0x8732209f, + 0x202f863f, + 0x202f8643, + 0x200f8632, + 0x860f8732, + 0x8732203f, + 0x209f863f, + 0x209f8632, + 0x204f8633, + 0x484f8633, + 0x312105e3, + 0x06194a46, + 0x86334621, + 0x06f74a4f, + 0x86334621, + 0x8633204f, + 0x0680504f, + 0x86334621, + 0x052b494f, + 0x4f863f82, + 0x5f863420, + 0x0f863420, + 0x0f864620, + 0x0f864620, + 0x2105eb4d, + 0x76484631, + 0x86078205, + 0x8634205f, + 0x06b84e5f, + 0x1e484620, + 0x46312105, + 0x2006d04e, + 0x065d4946, + 0x26484620, + 0x46312105, + 0x20065f4a, + 0x051e4846, + 0x67862782, + 0x20068d49, + 0x05ee4746, + 0x47463121, + 0x312205e6, + 0xd7864646, + 0x27414620, + 0x05064806, + 0x0f871f82, + 0x554a8786, + 0x36462106, + 0x4a063741, + 0x4620065d, + 0x2006e552, + 0x054e4746, + 0x47463121, + 0x07820546, + 0x46475786, + 0x860f8205, + 0x05464747, + 0x47860f82, + 0x21054647, + 0x54514631, + 0x39462106, + 0x1649af86, + 0x46312205, + 0x20478639, + 0x488f8639, + 0x178205b6, + 0x20061741, + 0x48478639, + 0xcf820586, + 0x41206786, + 0x41204786, + 0x20065f41, + 0x20478641, + 0x20478641, + 0x86278741, + 0x86412047, + 0x41412047, + 0x302106bf, + 0x05b74230, + 0x21056354, + 0xd6484631, + 0x20078205, + 0x20178631, + 0x20078632, + 0x20078633, + 0x20078634, + 0x20078635, + 0x20078636, + 0x20078537, + 0x204f8642, + 0x203f8642, + 0x201f8642, + 0x20178631, + 0x49178631, + 0x6782052e, + 0x31205786, + 0x31206786, + 0x67860f87, + 0x67863120, + 0x3f863220, + 0x3f873220, + 0x4e491f86, + 0x46312205, + 0x203f8632, + 0x533f8632, + 0x462006e1, + 0x82059e48, + 0x2087861f, + 0x20a78632, + 0x200f8643, + 0x20578633, + 0x86578733, + 0x05964917, + 0x53463121, + 0x462006b3, + 0x8205164b, + 0x2077860f, + 0x53978633, + 0x462006a8, + 0x21053e4b, + 0xf9444631, + 0x86078205, + 0x05534c4f, + 0x9f860f82, + 0x2006b74d, + 0x06af4d46, + 0xc8534620, + 0x4e462006, + 0x46200657, + 0x2105064a, + 0x064a4631, + 0x46312205, + 0x55378634, + 0x462106eb, + 0x537f8634, + 0x462006da, + 0x20060e52, + 0x069b4c46, + 0xb64b4620, + 0x46312205, + 0x4a7f8635, + 0x4f820546, + 0x20060f42, + 0x4b4f8635, + 0x278205b6, + 0x35204f86, + 0x4c53cf86, + 0x35462106, + 0x20062741, + 0x060f4145, + 0x2006a653, + 0x06294e46, + 0xae534620, + 0x46312105, + 0x8205314e, + 0x4b2f8607, + 0x312105a6, + 0x05a64b46, + 0x7f427782, + 0x05be4a06, + 0x7f861782, + 0x8205b64b, + 0x4b7f860f, + 0x0f8205be, + 0xbe4b6f86, + 0x46312105, + 0x21065552, + 0xd7414246, + 0x05f64a06, + 0x4a463121, + 0x312205f6, + 0x4f864246, + 0x21064957, + 0x0f863846, + 0x8205064b, + 0x205f8627, + 0x20df8638, + 0x205f8638, + 0x20af8638, + 0x51078642, + 0x46200637, + 0x2105e64a, + 0xe64a4631, + 0x46312105, + 0x8205d146, + 0x52478607, + 0x462006c3, + 0x2106464d, + 0x17873946, + 0xe3505f86, + 0x4e462006, + 0x3782058d, + 0x46205f86, + 0x4158bf86, + 0x4b462006, + 0xdf82051e, + 0x4620af86, + 0x2e4b4786, + 0x46312105, + 0x2006e452, + 0x052e4d46, + 0x5f860f82, + 0xbf864120, + 0x8205ce4b, + 0x215f843f, + 0x4f423330, + 0x54078205, + 0x3320052e, + 0x8205cf45, + 0x4744200f, + 0xb7410599, + 0x33302e05, + 0x61094537, + 0x65746f6e, + 0x6169656c, + 0x2309880d, + 0x7061632e, + 0xb64c2785, + 0x37332906, + 0x6f740535, + 0x09736f6e, + 0x1f830584, + 0x6a470d20, + 0x083d4707, + 0x6d444d82, + 0x06fb5706, + 0x95524620, + 0x52462006, + 0x46210695, + 0x066d4446, + 0x20060b4f, + 0x05445346, + 0x50463121, + 0x462006d5, + 0x20068750, + 0x06625646, + 0x14564620, + 0x50462006, + 0x462006ed, + 0x20069f50, + 0x06535846, + 0x5b4f4620, + 0x54462006, + 0x462706d6, + 0x750b3143, + 0x8231696e, + 0x85a18377, + 0x4546210b, + 0x45210b89, + 0x210b8946, + 0x0b894446, + 0x0b8a4320, + 0x0b8a4420, + 0x3b8a4320, + 0x0b8a4420, + 0x478a4320, + 0x0b844420, + 0x77820720, + 0x31343023, + 0x20078630, + 0x20078631, + 0x20078632, + 0x20078633, + 0x20078634, + 0x20078635, + 0x41078636, + 0x342205b5, + 0x0f863831, + 0x2205b541, + 0x86413134, + 0x8642200f, + 0x86432007, + 0x05c54107, + 0x45313422, + 0x46200f86, + 0x15450785, + 0x34302105, + 0x82051545, + 0x457f8607, + 0x0f820505, + 0x05457f86, + 0x860f8205, + 0x0505457f, + 0x7f860f82, + 0x82055d48, + 0x487f860f, + 0x0f82054d, + 0x4d487f86, + 0x860f8205, + 0x054d487f, + 0x30343023, + 0x21878530, + 0x07863130, + 0x30207f86, + 0x3020ff86, + 0x30207f86, + 0x3020ff86, + 0x30257f86, + 0x6e750937, + 0x223f8269, + 0x86612e37, + 0x20898639, + 0x06094130, + 0x82057749, + 0x06094121, + 0x89863020, + 0x09413020, + 0x86302006, + 0x41302089, + 0x9a570609, + 0x46342006, + 0x30210557, + 0x06c74234, + 0xcf433420, + 0x34302105, + 0x8205b743, + 0x47818607, + 0x0f82057f, + 0x9743f186, + 0x34302105, + 0x82057f43, + 0x86178707, + 0x05d74667, + 0x44343021, + 0x0782056f, + 0x2f4a4786, + 0x34302105, + 0x8205a142, + 0x85312007, + 0x050746cf, + 0x59343021, + 0x07820524, + 0x2f492f86, + 0x34302105, + 0x82053f45, + 0x57178607, + 0x0f8205c0, + 0x46206f86, + 0x46064941, + 0x3021059f, + 0x059f4634, + 0x17870782, + 0x20066141, + 0x06614133, + 0x82058f46, + 0x464f861f, + 0x0f82058f, + 0x49065741, + 0x0f8205ef, + 0xdf49d786, + 0x410f8205, + 0xdf490657, + 0x860f8205, + 0x05df497f, + 0x46343021, + 0x0782059f, + 0x8f46d786, + 0x860f8205, + 0x058f467f, + 0xe1410f82, + 0x05f95406, + 0xe1420f82, + 0x050f4a06, + 0xd7410f82, + 0x05ff4906, + 0xd7410f82, + 0x86342006, + 0x05ff497f, + 0x7f861782, + 0xd7413420, + 0x05cf4606, + 0x46343021, + 0x078205cf, + 0xbf46ff86, + 0x860f8205, + 0x05bf46ff, + 0xff860f82, + 0x61423520, + 0x42352006, + 0x2e5a0861, + 0x4a342006, + 0x29820559, + 0x4a060941, + 0x0f820551, + 0x594a8986, + 0x860f8205, + 0x05614a89, + 0x46343021, + 0x302105b1, + 0x06e05134, + 0x79483420, + 0x34302105, + 0x82052946, + 0x06114107, + 0x8205f945, + 0x49f1860f, + 0x302105d1, + 0x05f14534, + 0x27860782, + 0x8205a149, + 0x21e9860f, + 0x39423142, + 0x05e94605, + 0x46343021, + 0x07820599, + 0x46062941, + 0x30210589, + 0x051b4534, + 0x56343021, + 0x07820509, + 0x46067941, + 0x34210601, + 0x47778644, + 0x30220599, + 0x89414534, + 0x05194b06, + 0x6f860f82, + 0x0b33462d, + 0x30696e75, + 0x2e313334, + 0x83627273, + 0x31322b7b, + 0x7a063631, + 0x2e6f7265, + 0x06850730, + 0x84097321, + 0x6e702807, + 0x6f086d75, + 0x842e656e, + 0x77742208, + 0x2408846f, + 0x7268740a, + 0x24138565, + 0x756f6609, + 0x23148472, + 0x76696609, + 0x08231385, + 0x84786973, + 0x730a2512, + 0x6e657665, + 0x65240a85, + 0x74686769, + 0x09220a84, + 0x5086696e, + 0x70216b86, + 0x216b8408, + 0x74867030, + 0x74877420, + 0x74830884, + 0x74860883, + 0x74850a83, + 0x74830985, + 0x74832784, + 0x74852784, + 0x74850a84, + 0x74842884, + 0x6c840984, + 0x63876f20, + 0x63830884, + 0x63860883, + 0x63850a83, + 0x63830985, + 0x63832784, + 0x63852784, + 0x63850a84, + 0x63842884, + 0x4b410983, + 0x05632205, + 0x21e8826f, + 0x5d830563, + 0x41076321, + 0x63260533, + 0x756f6606, + 0x06822e72, + 0x63215483, + 0x21518305, + 0x4e850763, + 0x85076321, + 0x0663214b, + 0x63264884, + 0x696e7507, + 0x974d4532, + 0x2b078205, + 0x69660a42, + 0x65727567, + 0x68736164, + 0x30201a84, + 0x2105224b, + 0x9a4d3032, + 0x20078205, + 0x20178646, + 0x4d078536, + 0x322105c2, + 0x05845830, + 0x39200782, + 0x9a431785, + 0x202f8205, + 0x220f8444, + 0x86433133, + 0x200f8707, + 0x850f8645, + 0x4a37204f, + 0x3221050a, + 0x05504237, + 0x4b453221, + 0x07820572, + 0x27843320, + 0x724b4520, + 0x200f8205, + 0x220f8435, + 0x85373131, + 0x30322807, + 0x46317506, + 0x85413631, + 0x07423206, + 0x632e7461, + 0x03657361, + 0x03742e69, + 0x03732e41, + 0x20038242, + 0x20038243, + 0x20038244, + 0x20038245, + 0x20038246, + 0x20038247, + 0x20038248, + 0x20038249, + 0x2003824a, + 0x2003824b, + 0x2003824c, + 0x2003824d, + 0x2003824e, + 0x2003824f, + 0x20038250, + 0x20038251, + 0x20038252, + 0x20038253, + 0x20038254, + 0x20038255, + 0x20038256, + 0x20038257, + 0x20038258, + 0x24038259, + 0x08732e5a, + 0x05b35341, + 0xb3530882, + 0x0d732205, + 0x0ab35341, + 0xb3531682, + 0x0b732205, + 0x08b35341, + 0x62097321, + 0x3e83060a, + 0x3005e252, + 0x72410773, + 0x2e676e69, + 0x6e750973, + 0x43313069, + 0x23098544, + 0x30414531, + 0x32200988, + 0x34200988, + 0x36200988, + 0x38200988, + 0x41200988, + 0x43200988, + 0x45200988, + 0x42200987, + 0x42204f88, + 0x42204f88, + 0x42214f88, + 0x20278236, + 0x05545841, + 0x0a732e22, + 0xb6540988, + 0x34302906, + 0x31303330, + 0x4104732e, + 0x30224f86, + 0x63864631, + 0x45313022, + 0x30234f86, + 0x87333432, + 0x8830206d, + 0x82302063, + 0x430a2859, + 0x69646563, + 0x82616c6c, + 0x414320f7, + 0x4320072d, + 0x200c2d41, + 0x05a35343, + 0x620c7321, + 0x2c820963, + 0x15864420, + 0x20050c5f, + 0x20e08830, + 0x20e08830, + 0x26908230, + 0x72634408, + 0x8274616f, + 0x4145202f, + 0x45200793, + 0x45206587, + 0x4520658c, + 0x0b214f86, + 0x0a934145, + 0x83069d62, + 0x0693413e, + 0xa1620c20, + 0x083e4109, + 0x20086641, + 0x20858842, + 0x20858842, + 0x08664142, + 0x66414320, + 0x41432008, + 0x43200802, + 0x21086641, + 0x4f823643, + 0x2107ab62, + 0x09880a73, + 0x62066641, + 0x728705b6, + 0xe3413120, + 0x41312008, + 0x34230975, + 0x620d732e, + 0xb4820abe, + 0xb4874720, + 0x9f564720, + 0x064d4209, + 0x82823220, + 0xcd620820, + 0x21548705, + 0x40823032, + 0x850ad162, + 0x31302317, + 0x17823339, + 0x880ad562, + 0x20bb882f, + 0x28f78832, + 0x732e3639, + 0x61624806, + 0x577d8272, + 0x73220653, + 0x71414908, + 0x0b535707, + 0x05431682, + 0x09535707, + 0x53577320, + 0x57732008, + 0xb3860b53, + 0x87464321, + 0x4143207a, + 0x43200872, + 0x3f577a82, + 0x4242820c, + 0x374307ab, + 0x43322105, + 0x2663be82, + 0x2243850a, + 0x41333130, + 0x33200843, + 0x21088e41, + 0xb7823433, + 0x83052e63, + 0x0a624208, + 0x42202f82, + 0x4c23da82, + 0x85746f64, + 0x45312140, + 0x8e88408a, + 0x83413321, + 0x051c5637, + 0x2682b584, + 0x20080042, + 0x08004234, + 0x82323421, + 0x054b6326, + 0x30224d85, + 0x43824631, + 0x4f630820, + 0x411b8305, + 0xc285061b, + 0x85353421, + 0x45312225, + 0x08734134, + 0xbe883420, + 0x39833420, + 0xde424f20, + 0x414f2007, + 0x4f20076c, + 0x200cde42, + 0x2150864f, + 0xde424f0b, + 0x0697630a, + 0x0f732e22, + 0x850c9963, + 0x3130236c, + 0x6f413144, + 0x08ce4208, + 0xcd884320, + 0xcd884420, + 0x3f414420, + 0x88442008, + 0x8844209e, + 0x8444209e, + 0x0612419e, + 0x824f0421, + 0x4f07253f, + 0x6e726f68, + 0x44205b87, + 0x20083c42, + 0x20658844, + 0x20658844, + 0x44658845, + 0x3121084b, + 0x08f34145, + 0x44414521, + 0x2641057c, + 0x20358806, + 0x20918835, + 0x20878235, + 0x05cf6308, + 0x35207087, + 0xdb639083, + 0x21128505, + 0x25833130, + 0x20054844, + 0x208d8835, + 0x208d8835, + 0x20578235, + 0x05dd6308, + 0x0d732e22, + 0x230adf63, + 0x5308732e, + 0x830c2342, + 0x218b8429, + 0x12423132, + 0x88362008, + 0x32362ec1, + 0x670c732e, + 0x616d7265, + 0x6c62646e, + 0x227c8573, + 0x83394531, + 0x0501645e, + 0x36201287, + 0x30218586, + 0x86338331, + 0x20998851, + 0x20998836, + 0x21f18836, + 0x3b853739, + 0xf1833182, + 0x0e425520, + 0x42552007, + 0x5520070e, + 0x640c0e42, + 0x2e23052f, + 0x42550b73, + 0x3d640a0e, + 0x64d58206, + 0x2e23053f, + 0x46550773, + 0x0f200581, + 0x420c4364, + 0xd345081f, + 0x31302206, + 0x06a04244, + 0x87880982, + 0x88394421, + 0x85422027, + 0x45312209, + 0x081f4245, + 0x83364521, + 0x0b07425d, + 0x31414520, + 0x88452008, + 0x884520e9, + 0x884520e9, + 0x304621e9, + 0x5f644d82, + 0x06b04406, + 0x61643120, + 0x64b88205, + 0x08830563, + 0x6764f787, + 0x64ee820a, + 0x22820869, + 0x83056b64, + 0x642b8708, + 0x2b820a76, + 0x1a415920, + 0x6e75250a, + 0x38453169, + 0xc7888389, + 0xe7424620, + 0x82462008, + 0x640820bf, + 0x5382058c, + 0x17425a20, + 0x640c2006, + 0xef410997, + 0x089c4208, + 0x2e34392b, + 0x74450573, + 0x07732e68, + 0x090a4154, + 0x38313022, + 0x2206e844, + 0x42343130, + 0x33200808, + 0x0a203582, + 0x13858682, + 0x4107612c, + 0x6168706c, + 0x4206732e, + 0x06827465, + 0x61470724, + 0x07826d6d, + 0x21830920, + 0x57833320, + 0xfb590920, + 0x20228206, + 0x8222845a, + 0x82208268, + 0x220d8468, + 0x846f4906, + 0x614b2337, + 0x16827070, + 0x715a0820, + 0x732e2405, + 0x82754d04, + 0x834e2004, + 0x69582104, + 0x145ab182, + 0x20138206, + 0x230e8250, + 0x6f685205, + 0x5322ac82, + 0x6c836769, + 0x61540522, + 0x09212782, + 0x05a65955, + 0x5021ca82, + 0x20238368, + 0x21058443, + 0x0b827350, + 0x41248e85, + 0x0e732e39, + 0x220b6a5a, + 0x5a11732e, + 0x20820e52, + 0x6920d084, + 0x73289582, + 0x732e6275, + 0x6174450c, + 0x0e240c88, + 0x67656d4f, + 0x55840e89, + 0x30313422, + 0x23055041, + 0x31313430, + 0x5a410988, + 0x42138206, + 0x3421079b, + 0x06ab4131, + 0xa5421382, + 0x47342007, + 0x1382073f, + 0x2007af42, + 0x07b14334, + 0xaf821382, + 0x7e416386, + 0x31342107, + 0x8206c342, + 0x0693421d, + 0x91490982, + 0x42098206, + 0x09820619, + 0x2107ba41, + 0x9f883234, + 0x9f883220, + 0x9f883220, + 0x9f883220, + 0x9f883220, + 0x9f883220, + 0x55423220, + 0x34302206, + 0x219f8832, + 0xe5873832, + 0x9f883220, + 0x82077847, + 0x209f8827, + 0x209f8832, + 0x209f8832, + 0x209f8832, + 0x209f8832, + 0x209f8830, + 0x499f8830, + 0x3022079b, + 0x9f883034, + 0x9f883020, + 0x9f883020, + 0x9f883020, + 0x2e373025, + 0x51750a73, + 0x7321065e, + 0x05364161, + 0xaa883020, + 0xaa883020, + 0x8207a149, + 0x49aa885a, + 0x138207ab, + 0x3020aa88, + 0x3020aa88, + 0x0445aa88, + 0x37342108, + 0x20084041, + 0x20968837, + 0x20c88839, + 0x201d8839, + 0x20a08839, + 0x208b8839, + 0x08cc4139, + 0x2207404b, + 0x88413430, + 0x89412031, + 0x4b81881d, + 0x30210718, + 0x07184b34, + 0x59880982, + 0x2107ed49, + 0xd9493430, + 0x41098207, + 0x1e47084a, + 0x34302107, + 0x82071447, + 0x203b8809, + 0x46958844, + 0x342108d6, + 0x451d8845, + 0x3021070a, + 0x07f64434, + 0x46343022, + 0x0b2ba982, + 0x65706d61, + 0x6e617372, + 0x4d732e64, + 0x732c05ef, + 0x656e6f05, + 0x7405732e, + 0x732e6f77, + 0x2006ef4d, + 0x05ef4d73, + 0x69210682, + 0x221b8376, + 0x82786973, + 0x05ef4d1b, + 0xef4d7320, + 0x4d732006, + 0x732a05ef, + 0x63786508, + 0x2e6d616c, + 0x08850c73, + 0x776f642d, + 0x0a732e6e, + 0x73657571, + 0x826f6974, + 0x870e200a, + 0x2a19850a, + 0x6f75710d, + 0x69736574, + 0x826c676e, + 0x8227825a, + 0x6264250d, + 0x0b732e6c, + 0x6c231884, + 0x82746665, + 0x230b844b, + 0x68676972, + 0x40820c82, + 0x1b852385, + 0x1b840f20, + 0x1e863282, + 0x79680827, + 0x6e656870, + 0x2489822e, + 0x7361646e, + 0x20088368, + 0x2508856d, + 0x7261700b, + 0x36856e65, + 0x0b840c20, + 0x0d273386, + 0x63617262, + 0x8574656b, + 0x860e201a, + 0x201c860d, + 0x200e830b, + 0x201a8565, + 0x860b840c, + 0x055d5018, + 0x70757326, + 0x6e6f0873, + 0x0883bc82, + 0x6f777423, + 0x4f11832e, + 0x0a830684, + 0x8505844f, + 0x76692109, + 0x73222786, + 0x27857869, + 0x82064541, + 0x4f0a203b, + 0x28840538, + 0x86696e21, + 0x70092450, + 0x8573756c, + 0x696d2229, + 0x240a876e, + 0x61757165, + 0x2015846c, + 0x82d28a0e, + 0x8b0f2043, + 0x260f82d5, + 0x7265700b, + 0x84646f69, + 0x630a252a, + 0x616d6d6f, + 0xb9870a84, + 0xb9876220, + 0xb9850882, + 0x88736221, + 0x736221b9, + 0x0983b987, + 0x2782b985, + 0x2782b985, + 0x0a82b987, + 0x2882b987, + 0x0982b986, + 0x1e82b986, + 0x0a82b987, + 0x6221b987, + 0x21b98c73, + 0xb98d7362, + 0x89736221, + 0x873582b9, + 0x275582b9, + 0x6f72657a, + 0x6f6e642e, + 0x8405d151, + 0x83b98308, + 0x83b98608, + 0x85b9850a, + 0x84b98309, + 0x84b98327, + 0x84b98527, + 0x84b9850a, + 0x83b98428, + 0x83998a09, + 0x83998b0e, + 0x8499870f, + 0x8499853f, + 0x2899843f, + 0x726d756e, + 0x656e6f08, + 0x8308842e, + 0x86088399, + 0x850a8399, + 0x83098599, + 0x83278499, + 0x85278499, + 0x850a8499, + 0x84288499, + 0x8a098399, + 0x8b0e8399, + 0x870f8399, + 0x853f8499, + 0x270a8399, + 0x64726f0d, + 0x696d6566, + 0x61294684, + 0x732e4106, + 0x06737075, + 0x20068542, + 0x20068543, + 0x20068544, + 0x20068545, + 0x20068546, + 0x20068547, + 0x20068548, + 0x20068549, + 0x2006854a, + 0x2006854b, + 0x2006854c, + 0x2006854d, + 0x2006854e, + 0x2006854f, + 0x20068550, + 0x20068551, + 0x20068552, + 0x20068553, + 0x20068554, + 0x20068555, + 0x20068556, + 0x20068557, + 0x20068558, + 0x20068559, + 0x4206855a, + 0x062105b8, + 0x200d8562, + 0x42068563, + 0x062005d8, + 0x21055343, + 0x14856606, + 0x06856720, + 0x06856820, + 0x06856920, + 0x06856a20, + 0x06856b20, + 0x21053b43, + 0x0d856d06, + 0x06856e20, + 0x06856f20, + 0x06857020, + 0x06857120, + 0x06857220, + 0x21058243, + 0x0d857406, + 0x06857520, + 0x06857620, + 0x06857720, + 0x06857820, + 0x06857920, + 0x06847a20, + 0x6e750725, + 0x6c323069, + 0x302105dc, + 0x06545732, + 0xfa543220, + 0x5a322006, + 0x3025052e, + 0x0b304532, + 0x065d4b65, + 0x73707524, + 0x3c4a650b, + 0x200b8206, + 0x213f840c, + 0xf4853935, + 0x06836120, + 0x84066121, + 0x066121df, + 0x6125c384, + 0x6c6f630a, + 0x20c0856f, + 0x07f8440b, + 0xfb444484, + 0x440b8406, + 0x0b8206fe, + 0x6579062b, + 0x4e432e6e, + 0x72754504, + 0x239c846f, + 0x0d323931, + 0x6d2c4284, + 0x74656e6f, + 0x04797261, + 0x6172696c, + 0x32271a83, + 0x06364130, + 0x82736570, + 0x250e8615, + 0x6f640439, + 0x0c85676e, + 0x2105ee55, + 0x50583032, + 0x20078205, + 0x53178634, + 0x3020053d, + 0x82054062, + 0x85412017, + 0x05b85f17, + 0x38200f82, + 0x6a5b0f85, + 0x32322405, + 0x4d0a3531, + 0x662405c8, + 0x08636172, + 0x68288383, + 0x09647269, + 0x746f7774, + 0x73200883, + 0x31202d84, + 0x82051e57, + 0x0513542c, + 0xde5d3120, + 0x850f8205, + 0x5731204d, + 0x0f820514, + 0x31236d85, + 0x82093035, + 0x69652b4a, + 0x68746867, + 0x7268740c, + 0x0b856565, + 0x660b7324, + 0x0b877669, + 0x65730c25, + 0x866e6576, + 0x20678618, + 0x20078631, + 0x61078532, + 0xa5820526, + 0x2c057354, + 0x09333131, + 0x69747365, + 0x6574616d, + 0x29218564, + 0x61073039, + 0x776f7272, + 0x0f867075, + 0x84093221, + 0x6f64230f, + 0x11846e77, + 0x9a593520, + 0x35322205, + 0x20bb8543, + 0x053a6335, + 0x35373229, + 0x72740732, + 0x86676169, + 0x57352039, + 0x32210538, + 0x05726035, + 0x37200782, + 0x64201f85, + 0x31414786, + 0x59352006, + 0x4f8205aa, + 0x5f843120, + 0x30313622, + 0x0f850786, + 0x33313722, + 0x22620f85, + 0x30322105, + 0x82050260, + 0x22178507, + 0x83353330, + 0x3230211f, + 0x8205a141, + 0x86452007, + 0x8546200f, + 0x05e26307, + 0x85323021, + 0x200782a7, + 0x57178641, + 0x322005c8, + 0x82050262, + 0x8443207f, + 0x30332717, + 0x6e750930, + 0x07823069, + 0x88632e21, + 0x86672009, + 0x8631201b, + 0x88312011, + 0x2e31211b, + 0x32201b87, + 0x32221b86, + 0x2d86632e, + 0x11863320, + 0x11883320, + 0x11863420, + 0x11883420, + 0x11863520, + 0x11883520, + 0x11863620, + 0x6b2e3622, + 0x89870988, + 0x4b2e3622, + 0x50595b86, + 0x30332205, + 0x20378837, + 0x202d8638, + 0x20118838, + 0x20118639, + 0x20118839, + 0x20118641, + 0x20118841, + 0x20118642, + 0x20118842, + 0x20118643, + 0x20118843, + 0x20118646, + 0x21118746, + 0x11853131, + 0x88313121, + 0x21fd8611, + 0x0f413231, + 0x86312007, + 0x333121fd, + 0x38201188, + 0x3121bb85, + 0x41078639, + 0x33210589, + 0x05894131, + 0x2306f156, + 0x44313330, + 0xc9411f86, + 0x31332105, + 0x2005c941, + 0x065e5d33, + 0x33323322, + 0xe1561f85, + 0x33302105, + 0x22064e5d, + 0x86363233, + 0x061b4117, + 0x1b413220, + 0x41322008, + 0x3220061b, + 0x5d081b41, + 0x33200662, + 0x8205b065, + 0x86432043, + 0x5d73863b, + 0x33200652, + 0x2006f05b, + 0x06f05b33, + 0xe05b3320, + 0x5b332006, + 0x332006c0, + 0x22050858, + 0x86333330, + 0x05dd57c3, + 0xc3860f82, + 0x17413420, + 0x42342006, + 0x34200815, + 0xaa5bbd86, + 0x62332006, + 0x3022053a, + 0x53413633, + 0x31362406, + 0x420b612e, + 0x38250581, + 0x31303330, + 0x210b8a0d, + 0x198a632e, + 0x198a3020, + 0x632e3022, + 0x67200d8c, + 0x585a278a, + 0x30332105, + 0x34204d83, + 0x3420258a, + 0x43204d8c, + 0x4320198a, + 0x32201988, + 0x0b84818a, + 0x8187198c, + 0x81821983, + 0x0d837386, + 0x4d863920, + 0x338c0b84, + 0x198a3320, + 0x19883320, + 0x678a3620, + 0x198c0b84, + 0x19836787, + 0x0d836789, + 0x0b846787, + 0x6787338c, + 0x67891983, + 0x36208f83, + 0x3620818a, + 0x31203387, + 0xc185dd84, + 0x30200b84, + 0x41410b8a, + 0x33312106, + 0x1786a583, + 0x23870b83, + 0xd5410b83, + 0x07462607, + 0x32696e75, + 0x054a6033, + 0x9b423220, + 0x20078206, + 0x20178442, + 0x06ad5931, + 0x0f843182, + 0x59303021, + 0x30220595, + 0x0f863930, + 0x07864120, + 0x730a422b, + 0x65636170, + 0x6172662e, + 0x42128563, + 0x462a0592, + 0x00464645, + 0x00000100, + 0x03820800, + 0x00042808, + 0x6902000e, + 0x726f6564, + 0x006e6d6f, + 0x4c464404, + 0x631a0054, + 0x006c7279, + 0x6572671a, + 0x6c1a006b, + 0x006e7461, + 0x8206001a, + 0x8200202b, + 0x82022035, + 0x000c2435, + 0x8456ff01, + 0x22118341, + 0x830c0000, + 0x7603251b, + 0x91000200, + 0x35200382, + 0x4b221982, + 0x05824c00, + 0x4d004d22, + 0x4e220f82, + 0x0b824e00, + 0x6f006e22, + 0x70220582, + 0x11827000, + 0x7a007a22, + 0x7b220582, + 0x11827b00, + 0x8b008b22, + 0x8c220582, + 0x11828c00, + 0xb800b622, + 0xbe220b82, + 0x0582be00, + 0xbf00bf22, + 0xd7221182, + 0x0b82d700, + 0xe800e822, + 0xee220582, + 0x0582ee00, + 0xef00ef2e, + 0x03010200, + 0x01000401, + 0x1c011b01, + 0x1d220582, + 0x11821d01, + 0x1e011e22, + 0x29220b82, + 0x0b822901, + 0x3f013e22, + 0x40220b82, + 0x0b824001, + 0x47014722, + 0x4a220582, + 0x05824a01, + 0x5a015922, + 0x5c220582, + 0x1d825c01, + 0x63016322, + 0x69220b82, + 0x0b826901, + 0x89018722, + 0x8f220582, + 0x05828f01, + 0x90019022, + 0xa1221782, + 0x0582a101, + 0xa801a822, + 0xb9221182, + 0x0582b901, + 0xc001bf22, + 0xc1220582, + 0x1782c101, + 0xd601d322, + 0xd82d0b82, + 0x01002402, + 0x25022502, + 0x28020200, + 0x23778202, + 0x2a022a02, + 0x36221182, + 0x05823602, + 0x39023822, + 0x4f220582, + 0x05825002, + 0x52025222, + 0x57220582, + 0x29825702, + 0x5b025b22, + 0x65220b82, + 0x05826702, + 0x68026828, + 0x6c020400, + 0x05826c02, + 0x6e026e22, + 0x70220582, + 0x05827002, + 0x76027622, + 0x78220582, + 0x05827802, + 0x7b027b22, + 0x7f220582, + 0x05827f02, + 0x84028422, + 0x87224182, + 0x05828702, + 0x89028922, + 0x8d224182, + 0x05828d02, + 0x8f028f22, + 0x91220582, + 0x05829102, + 0x97029722, + 0x99220582, + 0x05829902, + 0x9c029c22, + 0xa0220582, + 0x0582a002, + 0xa902a922, + 0xac223582, + 0x0582ac02, + 0x8803b02e, + 0x8a030200, + 0x01008a03, + 0x8c038c03, + 0x97280582, + 0x04009703, + 0x99039903, + 0x9f220582, + 0x05829f03, + 0xa203a222, + 0xb1220582, + 0x1d82b103, + 0xb403b422, + 0xb6220582, + 0x0582b703, + 0xb903b922, + 0xbb220582, + 0x0582bb03, + 0xbf03bf22, + 0xc4220582, + 0x0582c403, + 0xc803c722, + 0xcc220582, + 0x0582cc03, + 0xd003ce22, + 0xd5220582, + 0x0582d503, + 0xd703d722, + 0xe2220582, + 0x0582e403, + 0xee03ed22, + 0xf5220582, + 0x0582f503, + 0xf703f722, + 0xfa220582, + 0x0582fa03, + 0xfd03fd28, + 0x00040100, + 0x05820004, + 0x03040222, + 0x05220582, + 0x05820504, + 0x07040722, + 0x0b220582, + 0x05820b04, + 0x10041022, + 0x13220582, + 0x05821404, + 0x18041822, + 0x1a220582, + 0x05821c04, + 0x21042122, + 0x2f220582, + 0x05822f04, + 0x3a043922, + 0x46220582, + 0x05824604, + 0xe604cd22, + 0xfc210582, + 0x28598304, + 0x00ff04ff, + 0x051f0501, + 0x22058220, + 0x823d053d, + 0x05672205, + 0x22058267, + 0x826d056d, + 0x05892205, + 0x22058289, + 0x829a059a, + 0x05a02205, + 0x220582a0, + 0x82b605b5, + 0x05b92205, + 0x210582ba, + 0xe38205bd, + 0x05c10523, + 0x220b82c2, + 0x82c505c4, + 0x05c72205, + 0x220582c7, + 0x82c905c9, + 0x05cc2105, + 0x0523ef82, + 0x82d605d6, + 0x05d9220b, + 0x220582d9, + 0x82dc05db, + 0x05de2205, + 0x220582de, + 0x82e005e0, + 0x05e42205, + 0x220582e4, + 0x82e905e9, + 0x05f12205, + 0x270582f1, + 0x00f505f3, + 0x06070601, + 0x0623dd82, + 0x82090609, + 0x0612220b, + 0x22058213, + 0x821a061a, + 0x061c2105, + 0x0623d782, + 0x82b106b1, + 0x06b8380b, + 0x070400b8, + 0x00390739, + 0x073a0701, + 0x07030082, + 0x00a60785, + 0x82020003, + 0x073a2209, + 0x2215825f, + 0x8281077d, + 0x2a158305, + 0x00010001, + 0x010a0000, + 0x43c6030c, + 0x2c2e0cc7, + 0x6b657267, + 0x616c5200, + 0x64006e74, + 0x23820400, + 0xffff0022, + 0x0c2c0784, + 0x24001800, + 0x01000a00, + 0x20425253, + 0x17850b82, + 0x0d000127, + 0x25001900, + 0x260d8500, + 0x000e0002, + 0x8a26001a, + 0x03340837, + 0x1b000f00, + 0x2e002700, + 0x54410700, + 0x3c002048, + 0x20455a41, + 0x52434a00, + 0x58002054, + 0x2056414e, + 0x534e6600, + 0x7400204d, + 0x20534b53, + 0x52548200, + 0x9000204b, + 0x04264d86, + 0x1c001000, + 0x0d862800, + 0x11000526, + 0x29001d00, + 0x06260d86, + 0x1e001200, + 0x0d862a00, + 0x13000726, + 0x2b001f00, + 0x08260d86, + 0x20001400, + 0x0d862c00, + 0x15000926, + 0x2d002100, + 0x0a240d86, + 0x22001600, + 0xaf858d82, + 0x17000b2e, + 0x2f002300, + 0x656b3000, + 0x22016e72, + 0x28200584, + 0x2e200584, + 0x34200584, + 0x3a200584, + 0x40200584, + 0x46200584, + 0x4c200584, + 0x52200584, + 0x58200584, + 0x5e200584, + 0x64260584, + 0x6b72616d, + 0x05846a01, + 0x05847c20, + 0x05848e20, + 0x0584a020, + 0x0584b220, + 0x0584c420, + 0x0584d620, + 0x0584e820, + 0x0583fa20, + 0x840c0221, + 0x841e2005, + 0x6d302605, + 0x026b6d6b, + 0x20058442, + 0x20058448, + 0x2005844e, + 0x20058454, + 0x2005845a, + 0x20058460, + 0x20058466, + 0x2005846c, + 0x20058472, + 0x20058478, + 0x2605847e, + 0x7a697384, + 0x848a0265, + 0x848e2005, + 0x84922005, + 0x84962005, + 0x849a2005, + 0x849e2005, + 0x84a22005, + 0x84a62005, + 0x84aa2005, + 0x84ae2005, + 0x84b22005, + 0x00b62605, + 0x00010000, + 0x2005c408, + 0x28458407, + 0x00030002, + 0x00050004, + 0x400d8206, + 0x0121c511, + 0xbdc78500, + 0x00982405, + 0x82940000, + 0x82902003, + 0x828c2003, + 0x82882003, + 0x82842003, + 0x82802003, + 0x827c2003, + 0x82782003, + 0x82742003, + 0x82702003, + 0x826c2003, + 0x00093403, + 0x001c0014, + 0x002c0024, + 0x003c0034, + 0x004c0044, + 0x82040054, + 0x00012217, + 0x2107855e, + 0x07862208, + 0x07863c20, + 0x0785ca20, + 0x86c00d21, + 0x85da2007, + 0x240e2b07, + 0x00010600, + 0x000f0100, + 0x3f820900, + 0x76100730, + 0x86107e10, + 0x96108e10, + 0xa6109e10, + 0x13826400, + 0x01220285, + 0x0f829010, + 0x0c000129, + 0x4d004201, + 0x82030000, + 0x8e0321a1, + 0x0b970786, + 0x078f1f87, + 0x178f2f87, + 0x4f830fb7, + 0x9b8b038f, + 0x179f9f8b, + 0x378f83b7, + 0x22088f8f, + 0x02280188, + 0x0264025e, + 0x0270026a, + 0x027c0276, + 0x02880282, + 0x0294028e, + 0x02a0029a, + 0x02ac02a6, + 0x82b802b2, + 0x02be2a03, + 0x02ca02c4, + 0x02d602d0, + 0x340382dc, + 0x02e802e2, + 0x02f402ee, + 0x030003fa, + 0x030c0306, + 0x03f40212, + 0x28018218, + 0x0324031e, + 0x0330032a, + 0x26038236, + 0x0342033c, + 0x824e0348, + 0x0354280b, + 0x0360035a, + 0x826c0366, + 0x035e2267, + 0x28658272, + 0x03780376, + 0x0384037e, + 0x2a03828a, + 0x03ca0290, + 0x03d00296, + 0x82a2039c, + 0x03ee2253, + 0x245182a8, + 0x03ae0306, + 0x223982b4, + 0x82c003ba, + 0x034e2405, + 0x82cc03c6, + 0x03d22201, + 0x245782d8, + 0x03e403de, + 0x206f82ea, + 0x200782f0, + 0x207f82f6, + 0x32598200, + 0x04fc03e4, + 0x03080402, + 0x04080454, + 0x0414040e, + 0x8220041a, + 0x04e4241d, + 0x82360326, + 0x04f434a5, + 0x0332042c, + 0x043804de, + 0x0424033e, + 0x044a0444, + 0x84500450, + 0x033038a7, + 0x045604e4, + 0x0436035c, + 0x04680462, + 0x0474046e, + 0x0374047a, + 0x82800442, + 0x0386314f, + 0x048c0448, + 0x04980492, + 0x02a4049e, + 0x03aa04fa, + 0x0431c782, + 0x03b604b0, + 0x0426046c, + 0x045c04bc, + 0x04c804c2, + 0x2a0382ce, + 0x04da04d4, + 0x04e604e0, + 0x82ac02e6, + 0x04ec224f, + 0x220582ec, + 0x82ae03da, + 0x04803785, + 0x040804ec, + 0x02ae03f2, + 0x04f804ee, + 0x020405fe, + 0x050a05ee, + 0xff820210, + 0x0516052f, + 0x0222051c, + 0x052805b2, + 0x0534052e, + 0x2807823a, + 0x05be0240, + 0x058e0246, + 0x2a15824c, + 0x02e20252, + 0x057203e2, + 0x82b20258, + 0x03202e3b, + 0x055e0506, + 0x036a0564, + 0x05660336, + 0x24498270, + 0x057c0576, + 0x20158282, + 0x20118288, + 0x08998254, + 0x8e053620, + 0x9a059405, + 0xa605a005, + 0xb205ac05, + 0xbe05b805, + 0xca05c405, + 0xd605d005, + 0xe205dc05, + 0x0382e805, + 0xf405ee32, + 0x0006fa05, + 0x0c060606, + 0x18061206, + 0x24061e06, + 0x2a200182, + 0xa6203182, + 0xe2202d82, + 0x1d833d82, + 0x3006002c, + 0xfa053606, + 0x3c069405, + 0x47841e06, + 0x4384ca20, + 0xe8059a22, + 0x423a3382, + 0xa6054806, + 0x54064e06, + 0xe2055a06, + 0x66066006, + 0x72066c06, + 0x7e067806, + 0x1d828406, + 0x2a06182c, + 0xf804dc05, + 0x00000100, + 0x0583fd01, + 0x00a60225, + 0x840f0101, + 0x841f2005, + 0x84492005, + 0x84342005, + 0x84222005, + 0x841e2005, + 0x845f2005, + 0x83452005, + 0x84002105, + 0x5c200b84, + 0x37200584, + 0x85201184, + 0x6b200b84, + 0x4e200584, + 0x4c200584, + 0x2f200584, + 0x27200584, + 0x16200584, + 0x0b200584, + 0x42200584, + 0x01200584, + 0x89200584, + 0xee204184, + 0x18200b84, + 0x0b200584, + 0x01239b83, + 0x82d60227, + 0x8412209b, + 0x840b200b, + 0x8408200b, + 0x84da20b3, + 0x8402200b, + 0x027b220b, + 0x202382b2, + 0x21118320, + 0x17847d00, + 0x2f84a920, + 0x05842720, + 0x05840f20, + 0x29841620, + 0x0584de20, + 0x0584d720, + 0x83029422, + 0xeb20fb82, + 0x68201d84, + 0xdf201184, + 0xf3200584, + 0xe7200584, + 0x02230583, + 0x82ae0235, + 0x841d2059, + 0x8483209b, + 0x834f2095, + 0x14022105, + 0x4b200b84, + 0x43200584, + 0x56200584, + 0x59200584, + 0x9d200584, + 0x7c204184, + 0x88200584, + 0xbb208f84, + 0x11206584, + 0x0e200584, + 0x0b220584, + 0x5984f601, + 0x0021dd82, + 0x84b985e8, + 0x84152017, + 0x84302005, + 0x84232005, + 0x84ed2017, + 0x8401200b, + 0x849e2005, + 0x84f72011, + 0x84dd2059, + 0x84292011, + 0x848f200b, + 0x84f62005, + 0x84e82005, + 0x84172017, + 0x84ac200b, + 0x84ad2005, + 0x84b22035, + 0x84f52005, + 0x84832005, + 0x84a32023, + 0x84cf201d, + 0x8400200b, + 0x849e2005, + 0x845c2005, + 0x84562005, + 0x84db2029, + 0x84db2023, + 0x84da200b, + 0x84052017, + 0x84bc2011, + 0x84cb2011, + 0x02912205, + 0x20cb8283, + 0x20e98432, + 0x20238428, + 0x2023840d, + 0x201d84f9, + 0x260b84d0, + 0x00ff01d9, + 0x84c90001, + 0x84cd2011, + 0x84d32005, + 0x84c42005, + 0x847c2005, + 0x8407203b, + 0x02ab220b, + 0x204d82a6, + 0x2047841a, + 0x20058422, + 0x20418425, + 0x200b84f4, + 0x200b845b, + 0x200b84f9, + 0x2029840e, + 0x2205848f, + 0x82aa024c, + 0x84422035, + 0x84052005, + 0x84402011, + 0x84252005, + 0x849a2005, + 0x84bd2005, + 0x83472005, + 0xd9002305, + 0x2f82ce02, + 0x11840a20, + 0x05845a20, + 0x53845520, + 0x05841d20, + 0x05841320, + 0x05841820, + 0x71845d20, + 0x0b84cc20, + 0x05848a20, + 0x11841020, + 0x3302eb22, + 0x14204182, + 0x27200584, + 0x1b200584, + 0x08200584, + 0x0a200584, + 0x34200584, + 0x29200584, + 0x00210583, + 0x200b8483, + 0x2005842f, + 0x20118420, + 0x200b8489, + 0x20058443, + 0x2005842d, + 0x20058426, + 0x2005841e, + 0x2023841a, + 0x200584fe, + 0x201184ea, + 0x200b8424, + 0x200b84e2, + 0x200b8456, + 0x200584e5, + 0x200584d0, + 0x200584fa, + 0x201d84e9, + 0x200584d2, + 0x20058433, + 0x20058437, + 0x201d8409, + 0x220b84ec, + 0x821c020e, + 0x845a20b9, + 0x842a200b, + 0x8320200b, + 0xe6002105, + 0x6a200b84, + 0xf4202984, + 0xa1201d84, + 0x10200584, + 0xeb261184, + 0x01004102, + 0x0b83e800, + 0x0b2e0b23, + 0x220b8234, + 0x8212000c, + 0x00002205, + 0x8305820a, + 0x05434203, + 0xfd01d928, + 0x180b0100, + 0x2184200b, + 0x02001626, + 0x2a000000, + 0x0f3e0384, + 0x2c002600, + 0x38003200, + 0x44003e00, + 0x50004a00, + 0x5c005600, + 0x68006200, + 0x74006e00, + 0x4b847a00, + 0x99820020, + 0x2d825720, + 0x11010122, + 0x0b200584, + 0x0a200584, + 0x08200584, + 0x00210583, + 0x200584d6, + 0x821184d7, + 0x01002304, + 0x0682f700, + 0xcc000122, + 0x19201184, + 0x26200584, + 0xf4201184, + 0xe3200584, + 0x25201184, + 0x0a230583, + 0x84ce0aac, + 0x006a2695, + 0x01000017, + 0x0803d8f2, + 0x9a01c966, + 0xa601a001, + 0xb201ac01, + 0xbe01b801, + 0xca01c401, + 0xd601d001, + 0xe201dc01, + 0xee01e801, + 0xfa01f401, + 0x06020002, + 0x12020c02, + 0x1e021802, + 0x2a022402, + 0x36023002, + 0x42023c02, + 0xf4014802, + 0x54024e02, + 0x60025a02, + 0x6c026602, + 0x42027202, + 0x78029a01, + 0x84027e02, + 0x90028a02, + 0x9c029602, + 0xa802a202, + 0xb402ae02, + 0xe8205982, + 0xba244584, + 0xc602c002, + 0xcc203182, + 0xd2202982, + 0x90285982, + 0xde02d802, + 0xea02e402, + 0x962a4382, + 0x3602f002, + 0xfc02f602, + 0x0f820203, + 0x0803422e, + 0x96020e03, + 0x1a031403, + 0x20034802, + 0x42264782, + 0x2c032603, + 0x13822c03, + 0x03322008, + 0x02540238, + 0x033e03ea, + 0x024a0344, + 0x0350036c, + 0x035c0356, + 0x02680362, + 0x036e0324, + 0x827a0374, + 0x02ea303f, + 0x03800366, + 0x039a0186, + 0x0392038c, + 0x829e0398, + 0x03a42201, + 0x2e9b82aa, + 0x03b00342, + 0x036002b6, + 0x03c203bc, + 0x82b20138, + 0x83c8204f, + 0xce0331a9, + 0xda03d403, + 0xe603e003, + 0xec038603, + 0xf203b402, + 0xf82a0382, + 0x0404fe03, + 0x10040a04, + 0x7b824202, + 0x4403fe28, + 0x1c041604, + 0x15822204, + 0x33822820, + 0x2e04f022, + 0x012fa383, + 0x04ac01b8, + 0x043a0434, + 0x04460440, + 0x8252044c, + 0x012e3605, + 0x045804f4, + 0x041a035e, + 0x04b40264, + 0x0470046a, + 0x04d00176, + 0x230f837c, + 0xb2017c04, + 0xf022d382, + 0x11820602, + 0x46203583, + 0x7c203184, + 0x822e3182, + 0x8e048804, + 0x00000100, + 0x0100eaff, + 0x05840f01, + 0x05842e20, + 0x05845720, + 0x05843120, + 0x05832a20, + 0x84870021, + 0x845f200b, + 0x84452005, + 0x84842011, + 0x84fd2005, + 0x84482011, + 0x84212005, + 0x846d2005, + 0x844b2005, + 0x844c2005, + 0x84892023, + 0x8436200b, + 0x84112005, + 0x840b2005, + 0x84422005, + 0x84022005, + 0x848c2005, + 0x84fc2029, + 0x84f02005, + 0x841a2011, + 0x84f9200b, + 0x8428200b, + 0x840a2005, + 0x84152005, + 0x84082005, + 0xfffa221d, + 0x20b98226, + 0x200b841f, + 0x2205847b, + 0x822dff41, + 0x84132011, + 0x8491200b, + 0x84a52029, + 0xff7f220b, + 0x20178235, + 0x210583a9, + 0x11847900, + 0x0584d620, + 0x2384d720, + 0x0b841220, + 0x0b84eb20, + 0x0b846820, + 0x0584df20, + 0x5f83c820, + 0x84e10021, + 0x84592017, + 0x843d2005, + 0x84a32005, + 0x849c201d, + 0x84bb200b, + 0x841b2005, + 0x840e2005, + 0x84832017, + 0x84152083, + 0x841e2005, + 0x84612017, + 0x84222005, + 0x84ed201d, + 0x84f42083, + 0x84192011, + 0x83a12005, + 0xea002129, + 0xf7201d84, + 0x66200584, + 0x19203b84, + 0xe8201784, + 0x0520e384, + 0x17201184, + 0x8f201d84, + 0xac200584, + 0x6c200584, + 0xad264d84, + 0x0100ecff, + 0x1184be00, + 0xe984aa20, + 0x2f845b20, + 0x5f84a920, + 0x05849a20, + 0x4d84a520, + 0x0b84cc20, + 0x2005f141, + 0x200b84b2, + 0x2005845c, + 0x201d8456, + 0x20418481, + 0x200b8498, + 0x200584b4, + 0x221184f1, + 0x8231ffe6, + 0x844f205f, + 0x84d72011, + 0x84182059, + 0x84e82017, + 0x84d02005, + 0xffd52205, + 0x2223826b, + 0x8291ffe5, + 0x84c92005, + 0x84b52029, + 0x84bf2017, + 0x84c42005, + 0x847c2005, + 0x8407206b, + 0x84ad200b, + 0x844b200b, + 0x847420bf, + 0x842320b3, + 0x84fa2017, + 0x845b2017, + 0x84262005, + 0x84292005, + 0x84832017, + 0x84d12005, + 0x842b2011, + 0x84042005, + 0x84432005, + 0x841d2005, + 0x84032005, + 0x84242005, + 0x84562005, + 0x84ed202f, + 0x84ce2005, + 0x84272011, + 0x84cf200b, + 0x84f52005, + 0x83252011, + 0xbe062305, + 0xb5457e05, + 0xf4002513, + 0x25010100, + 0x06230583, + 0x8aa806a2, + 0x00163021, + 0x00160007, + 0x0022001c, + 0x002e0028, + 0x823a0034, + 0x0100221b, + 0x282d82e6, + 0x008602d5, + 0x020d0201, + 0x200b829a, + 0x2211846c, + 0x82f0019b, + 0x01a7220b, + 0x220582f3, + 0x821102cf, + 0x83992005, + 0x68062317, + 0x07467006, + 0x0042260a, + 0x00420000, + 0x14ff451b, + 0x7a006832, + 0x86008000, + 0x92008c00, + 0x98006e00, + 0xa4009e00, + 0xaa2a0b82, + 0xb600b000, + 0xc200bc00, + 0x4782c800, + 0x59823e82, + 0x2005d145, + 0x200c8295, + 0x20318201, + 0x20118200, + 0x200b834c, + 0x225d8301, + 0x846c0101, + 0x845b200b, + 0x8473201d, + 0x840f200b, + 0x84882005, + 0x84122005, + 0x84f32017, + 0x84ea2005, + 0x848f2005, + 0x84ac2005, + 0x84a3201d, + 0x84a8200b, + 0x8489200b, + 0x84992005, + 0x84592005, + 0x467d2017, + 0x0121095b, + 0x09554624, + 0x05b60124, + 0xd94e00c6, + 0x48012108, + 0x4e209082, + 0x07830382, + 0x1f870b97, + 0x2f87078f, + 0x0fb7178f, + 0x078b8387, + 0x9f8b9b8b, + 0x83b7179f, + 0x9391378f, + 0x1e000826, + 0x2a002400, + 0x30240384, + 0x36003000, + 0x230d994c, + 0xdc020000, + 0x02211183, + 0x21058398, + 0x0b842003, + 0x0584b720, + 0x0582ef20, + 0x00000224, + 0x07855c04, + 0x856c2121, + 0x00562107, + 0x8e210785, + 0x21078568, + 0x0785c6c8, + 0x849afe21, + 0x35012207, + 0x08dd5408, + 0x7d070030, + 0x26008107, + 0xa6078507, + 0x01002b00, + 0x19832801, + 0x63520020, + 0x00073605, + 0x00090008, + 0x000b000a, + 0x000d000c, + 0x000f000e, + 0x00110010, + 0xc15a1812, + 0x1d002113, + 0x1f28c382, + 0x21002000, + 0x23002200, + 0x24776318, + 0x004b3c08, + 0x004e004c, + 0x006f006e, + 0x008b007b, + 0x00b700b6, + 0x00be00b8, + 0x00e800d7, + 0x010301ee, + 0x011b0104, + 0x011e011c, + 0x013f013e, + 0x0169015c, + 0x01880187, + 0x018f0189, + 0x01b901a8, + 0x18c001bf, + 0x24086361, + 0x01d901d8, + 0x5f6118da, + 0xe5012213, + 0x57611801, + 0x5561180c, + 0x01f3280a, + 0x01f601f4, + 0x18f801f7, + 0x180b4f61, + 0x18094d61, + 0x22174361, + 0x18021002, + 0x08203f61, + 0x02220287, + 0x02240223, + 0x0236022a, + 0x02390238, + 0x0250024f, + 0x025b0252, + 0x02660265, + 0x02890267, + 0x028f028d, + 0x02970291, + 0x029c0299, + 0x038a03a0, + 0x03b1038c, + 0x03b603b4, + 0x03b903b7, + 0x03bf03bb, + 0x03c703c4, + 0x03cc03c8, + 0x03cf03ce, + 0x03d503d0, + 0x03e203d7, + 0x03e403e3, + 0x03ee03ed, + 0x03f703f5, + 0x04fd03fa, + 0x04020400, + 0x04050403, + 0x040b0407, + 0x04130410, + 0x04180414, + 0x041b041a, + 0x0421041c, + 0x0439042f, + 0x0446043a, + 0x3b5c18cd, + 0xfc5c0832, + 0xff04fd04, + 0x20051f05, + 0x67053d05, + 0x89056d05, + 0xa0059a05, + 0xb605b505, + 0xba05b905, + 0xbe05bd05, + 0xc105bf05, + 0xc405c205, + 0xc705c505, + 0xcc05c905, + 0xd905d605, + 0xdc05db05, + 0xe005de05, + 0xe905e405, + 0xf305f105, + 0xf505f405, + 0x09060706, + 0x13061206, + 0x1c061a06, + 0x01003907, + 0x62070100, + 0x0b830584, + 0x6d070224, + 0x0d826e07, + 0x04000f3c, + 0x15001400, + 0x20001e00, + 0x2f002e00, + 0xe6013000, + 0x13020102, + 0xdf04cf04, + 0x3582e004, + 0x00022408, + 0x07600705, + 0x07000061, + 0x006c0764, + 0x07710702, + 0x070b0077, + 0x007c0779, + 0x07820712, + 0x00160082, + 0x82270002, + 0x00112a03, + 0x00130000, + 0x00100035, + 0x2201827b, + 0x82b80033, + 0x00342201, + 0x220182d7, + 0x82e80035, + 0x36cc0801, + 0x04010301, + 0x1e013700, + 0x39001e01, + 0x5c015c01, + 0x69013a00, + 0x3b006901, + 0x89018701, + 0xa8013c00, + 0x3f00a801, + 0xb901b901, + 0xd3014000, + 0x4100d601, + 0x2402d801, + 0x2a024500, + 0x92002a02, + 0x39023802, + 0x52029300, + 0x95005202, + 0x5b025b02, + 0x66029600, + 0x97006702, + 0x89028902, + 0x8d029900, + 0x9a008d02, + 0x8f028f02, + 0xa0029b00, + 0x9c00a002, + 0xdc04cd04, + 0xde049d00, + 0xad00e604, + 0x67056705, + 0x8905b600, + 0xb7008905, + 0x9a059a05, + 0xb505b800, + 0xb900b605, + 0xba05b905, + 0xbd05bb00, + 0xbd00bf05, + 0xc205c105, + 0xc405c000, + 0xc200c505, + 0xc705c705, + 0xc905c400, + 0xc500c905, + 0xcc05cc05, + 0xb106c600, + 0xc700b106, + 0x39073907, + 0x0100c800, + 0x78070100, + 0x63200584, + 0x07200582, + 0x1628ef82, + 0x30002a00, + 0xe104db04, + 0x01261f82, + 0x6f070200, + 0x19827007, + 0x02001b26, + 0x0a000600, + 0x1c241f84, + 0x24002000, + 0x012f2583, + 0x01d8015c, + 0x01e401e0, + 0x02f301f2, + 0x82130203, + 0x023922dd, + 0x22ad8266, + 0x88d504d1, + 0x08210841, + 0x44074007, + 0x46074507, + 0x4c074707, + 0x50074e07, + 0x661b0100, + 0x00000400, + 0xb801d700, + 0xf401ca01, + 0x09ab4b02, + 0x46023422, + 0x201e8b53, + 0x0a8953be, + 0x53108753, + 0x5c090c83, + 0x0342033c, + 0x06020448, + 0x08ea06cc, + 0x0afe08e0, + 0x0aa60a54, + 0x0ab20aac, + 0x0abe0ab8, + 0x0d520cc4, + 0x0eea0de4, + 0x0e260e08, + 0x0e4a0e38, + 0x0e720e5c, + 0x0e960e78, + 0x0ea20e9c, + 0x0fc60ea8, + 0x0f2a0f1c, + 0x0f520f3c, + 0x0f720f60, + 0x0fc60fa0, + 0x10f20fdc, + 0x10261000, + 0x106e104c, + 0x10821078, + 0x10961088, + 0x10b210a4, + 0x10ce10c0, + 0x10ea10dc, + 0x110611f8, + 0x113a1114, + 0x11861160, + 0x11d211ac, + 0x121e12f8, + 0x12521244, + 0x126e1260, + 0x128a127c, + 0x12a61298, + 0x12c212b4, + 0x12d612d0, + 0x12e612e0, + 0x12f212ec, + 0x130213f8, + 0x130e1308, + 0x13221318, + 0x132e1328, + 0x133a1334, + 0x134a1340, + 0x13561350, + 0x1362135c, + 0x138a1384, + 0x13961390, + 0x13aa13a0, + 0x13be13b8, + 0x14d613d0, + 0x141e1400, + 0x14561438, + 0x14a21474, + 0x14ca14b8, + 0x15ee14e0, + 0x15321514, + 0x15721550, + 0x15ba158c, + 0x16ea15d4, + 0x16861638, + 0x1692168c, + 0x16be1698, + 0x16e616e0, + 0x18f216ec, + 0x187a1868, + 0x1892188c, + 0x18ba18a8, + 0x18e218cc, + 0x19fe18f8, + 0x191e1918, + 0x19361924, + 0x1952194c, + 0x197e1968, + 0x19ae1988, + 0x19de19cc, + 0x1afa19e4, + 0x1a361a0c, + 0x1a661a4c, + 0x1a7a1a70, + 0x1ab61a84, + 0x1b161bf8, + 0x01040054, + 0x011d0052, + 0x01240053, + 0x2c038254, + 0x001d0055, + 0x0050010a, + 0x00510114, + 0x2019820d, + 0x20198235, + 0x2a198240, + 0x00550140, + 0x00560135, + 0x8257012a, + 0x005b2817, + 0x00650235, + 0x8207000d, + 0x823c2029, + 0x823c2025, + 0x82502025, + 0x823c2025, + 0x823c2025, + 0x013c2a25, + 0x003c005b, + 0x00a40601, + 0x2c058e1b, + 0x001400b3, + 0x00830402, + 0x00850407, + 0xb17b9207, + 0x25638a51, + 0x28001e02, + 0x05a30100, + 0xab919992, + 0x042511a2, + 0x00f9ffbb, + 0x20059d01, + 0x20f38306, + 0x8305a401, + 0x002e2e71, + 0x00e8ff15, + 0x00f0ff17, + 0x00fcff18, + 0x240b821a, + 0x00edff35, + 0x200782d0, + 0x200382d1, + 0x200382d2, + 0x200382d3, + 0x200382d4, + 0x200382d5, + 0x200382d6, + 0x200382d7, + 0x202b82f0, + 0x200382f1, + 0x200382f2, + 0x200382f3, + 0x201382f4, + 0x200382f5, + 0x200382f6, + 0x200382f7, + 0x200382f8, + 0x200382f9, + 0x280382fa, + 0x01e8fffb, + 0x01edffce, + 0x200382cf, + 0x200382d0, + 0x240382d1, + 0x02edffd2, + 0x2003821a, + 0x2c03821b, + 0x04edff1c, + 0x04e5ff89, + 0x04f0ff8e, + 0x24038290, + 0x04f6ff97, + 0x20038298, + 0x20038299, + 0x2003829c, + 0x2403829d, + 0x04caffad, + 0x202382b4, + 0x240382b6, + 0x07e5ffb7, + 0x20af8225, + 0x20b982b2, + 0x20b982ec, + 0x28b584f2, + 0x00f6ff1c, + 0x0001001e, + 0x2003821f, + 0x20038220, + 0x200f8222, + 0x2007822a, + 0x2403822c, + 0x00060031, + 0x24038232, + 0x00ecffd0, + 0x200382d1, + 0x200382d2, + 0x200382d3, + 0x200382d4, + 0x200382d5, + 0x200382d6, + 0x9f0382d7, + 0xff0624c5, + 0x820701f6, + 0x82082003, + 0x82092003, + 0x820a2003, + 0x820b2003, + 0x820c2003, + 0x820d2003, + 0x820e2003, + 0x820f2003, + 0x82102003, + 0x82112003, + 0x82122003, + 0x82132003, + 0x82142003, + 0x82152003, + 0x82162003, + 0x82172003, + 0x82182003, + 0x82192003, + 0x821a2003, + 0x821b2003, + 0x821c2003, + 0x821d2003, + 0x821e2003, + 0x821f2003, + 0x82202003, + 0x00242403, + 0x82250101, + 0x82262003, + 0x82272003, + 0x82282003, + 0x82292003, + 0x822a2003, + 0x822b2003, + 0x21d78203, + 0x07822d01, + 0x03822e20, + 0x03822f20, + 0x03823020, + 0x03823120, + 0x03823220, + 0x03823320, + 0x03823420, + 0x03823520, + 0x03823620, + 0x03823720, + 0x03823820, + 0x03823920, + 0x03823a20, + 0x03823b20, + 0x03823c20, + 0x03823d20, + 0x03823e20, + 0x03823f20, + 0x03824020, + 0x03824120, + 0x7b824320, + 0x03824420, + 0x03824520, + 0x03824620, + 0x03824720, + 0x03824820, + 0x03824920, + 0x03824a20, + 0x23827620, + 0x03827720, + 0x03827820, + 0x03827920, + 0x03827a20, + 0x03827b20, + 0x03827c20, + 0x03827d20, + 0x03827e20, + 0x03827f20, + 0x03828020, + 0x03828120, + 0x03828220, + 0x03828320, + 0x03828420, + 0x03828520, + 0x03828620, + 0x03828720, + 0x03828820, + 0x03828920, + 0x03828a20, + 0x03828b20, + 0x03828c20, + 0x03828d20, + 0x03828e20, + 0x03828f20, + 0x03829020, + 0x0600c224, + 0x0382c301, + 0x0382c420, + 0x0382c520, + 0x1382dc20, + 0x0382de20, + 0x0382df20, + 0x0382e120, + 0x0382e320, + 0x0382ea20, + 0x0382eb20, + 0x0100ec24, + 0x03820302, + 0x03820420, + 0x03820520, + 0x03820620, + 0x06001924, + 0x07823902, + 0x0221f382, + 0x2007823b, + 0x2003823c, + 0x2003823d, + 0x2003823e, + 0x8203823f, + 0x820220f3, + 0x420221f3, + 0x43200b82, + 0x44200382, + 0x45200382, + 0x46200382, + 0x47200382, + 0x48200382, + 0x49200382, + 0x4a200382, + 0x4b200382, + 0x4c200382, + 0x4d200382, + 0x4e200382, + 0x4f200382, + 0x50200382, + 0x51200382, + 0x52200382, + 0x53200382, + 0x54200382, + 0x55200382, + 0x56200382, + 0x57200382, + 0x58200382, + 0x59200382, + 0x5a280382, + 0x97040100, + 0x9804ecff, + 0x99200382, + 0x9c200382, + 0x9d200382, + 0x9e2e0382, + 0xc404f2ff, + 0x07001400, + 0x3e005001, + 0x03825201, + 0x5700532c, + 0x45005401, + 0x37005501, + 0x0b825601, + 0x50005b2a, + 0x0b007d00, + 0x1400ecff, + 0xa9430382, + 0x00f63209, + 0x00e6ff1a, + 0x00f2ff1c, + 0x00feff21, + 0x00f6ff22, + 0x240b822f, + 0x00050031, + 0x28038232, + 0x00f5ff33, + 0x00040035, + 0x2033828e, + 0x200382c8, + 0x200382c9, + 0x200382ca, + 0x200382cb, + 0x200382cc, + 0x200382cd, + 0x430382ce, + 0xf62221e5, + 0x5b82f100, + 0x0382f220, + 0x0382f320, + 0x7382f420, + 0x0382f520, + 0x0382f620, + 0x0382f720, + 0x0382f820, + 0x0382f920, + 0x0382fa20, + 0xe6fffb28, + 0xf2ff0601, + 0x03820701, + 0x03820820, + 0x03820920, + 0x03820a20, + 0x03820b20, + 0x03820c20, + 0x03820d20, + 0x03820e20, + 0x03820f20, + 0x03821020, + 0x03821120, + 0x03821220, + 0x03821320, + 0x03821420, + 0x03821520, + 0x03821620, + 0x03821720, + 0x03821820, + 0x03821920, + 0x03821a20, + 0x03821b20, + 0x03821c20, + 0x03821d20, + 0x03821e20, + 0x03821f20, + 0x03822020, + 0xfeff4223, + 0x1fab4201, + 0x2782a120, + 0x0382a220, + 0x0382a320, + 0x0382a420, + 0x0382a520, + 0x0382a620, + 0x0382a720, + 0x0382a820, + 0x0500c224, + 0x0382c301, + 0x0382c420, + 0x0382c520, + 0x0400ce24, + 0x0382cf01, + 0x0382d020, + 0x0382d120, + 0x0400d223, + 0x29a78202, + 0xf2ff1202, + 0x05001902, + 0x0f821a02, + 0x03821b20, + 0x03821c20, + 0xfeff2524, + 0x03822602, + 0x03822720, + 0x03822820, + 0x03822920, + 0xfeff6428, + 0xf6ff8e04, + 0x03829004, + 0xffff9324, + 0x03829504, + 0x06009724, + 0x03829804, + 0x03829920, + 0x03829c20, + 0x03829d20, + 0xff9e2208, + 0xffab04fc, + 0xffad04ec, + 0xffc504de, + 0xffb606ef, + 0xffb706f5, + 0xff2507f5, + 0xffb407f6, + 0xffb507fe, + 0x1e1342fe, + 0x0b005524, + 0xff44d8ff, + 0x00fc2d06, + 0x00f9ff1a, + 0x00fcff1b, + 0x00ecff1c, + 0x00254382, + 0x00e8ff35, + 0x441f828e, + 0xf92221ef, + 0x3b82f500, + 0x0382f620, + 0x0382f720, + 0x0382f820, + 0x0382f920, + 0x0382fa20, + 0x0382fb20, + 0x5382fc20, + 0x0382fd20, + 0x0382fe20, + 0xfcffff24, + 0x03820001, + 0xecff0624, + 0x03820701, + 0x03820820, + 0x03820920, + 0x03820a20, + 0x03820b20, + 0x03820c20, + 0x03820d20, + 0x03820e20, + 0x03820f20, + 0x03821020, + 0x03821120, + 0x03821220, + 0x03821320, + 0x03821420, + 0x03821520, + 0x03821620, + 0x03821720, + 0x03821820, + 0x03821920, + 0x03821a20, + 0x03821b20, + 0x03821c20, + 0x03821d20, + 0x03821e20, + 0x03821f20, + 0x03822020, + 0xf6ff5d28, + 0xe8ffce01, + 0x0382cf01, + 0x0382d020, + 0x0382d120, + 0x0382d220, + 0x1782d620, + 0x0382e920, + 0xf6fffe24, + 0x03820f02, + 0x03821020, + 0xe8ff1a24, + 0x03821b02, + 0xe8ff1c28, + 0xddff8204, + 0x03828304, + 0x03828620, + 0x03829120, + 0x03829220, + 0xf9ff9724, + 0x03829804, + 0x03829920, + 0x03829c20, + 0x03829d20, + 0xecffa930, + 0xf8ffad04, + 0x2d00c404, + 0x0d00c504, + 0x51461400, + 0x00e2210a, + 0x26213d41, + 0xfff500e2, + 0x82f600e2, + 0x82f72003, + 0x82f82003, + 0x82f92003, + 0x82fa2003, + 0xfffb2203, + 0x205982e2, + 0x0e8d48e8, + 0xecff3722, + 0x632e118c, + 0xc9ff0b00, + 0xf6ff1b00, + 0xe7ff1c00, + 0x07822200, + 0xfaff2524, + 0x07822e00, + 0x13003124, + 0x91823200, + 0x0b823520, + 0x23828e20, + 0x0782fc20, + 0x0382fd20, + 0x0021f182, + 0x20f982ff, + 0x24038200, + 0x01e7ff06, + 0x20038207, + 0x20038208, + 0x20038209, + 0x2003820a, + 0x2003820b, + 0x2003820c, + 0x2003820d, + 0x2003820e, + 0x2003820f, + 0x20038210, + 0x20038211, + 0x20038212, + 0x20038213, + 0x20038214, + 0x20038215, + 0x20038216, + 0x20038217, + 0x20038218, + 0x20038219, + 0x2003821a, + 0x2003821b, + 0x2003821c, + 0x2003821d, + 0x2003821e, + 0x2003821f, + 0x43038220, + 0x5d241f69, + 0x9901faff, + 0x9a209382, + 0x9b200382, + 0x9c200382, + 0x9d200382, + 0x9e200382, + 0x9f200382, + 0xc2240382, + 0xc3010d00, + 0xc4200382, + 0xc5200382, + 0xce200382, + 0xcf201382, + 0xd0200382, + 0xd1200382, + 0xd2200382, + 0xd6200382, + 0xe9204382, + 0xfe280382, + 0x0e02faff, + 0x0f02f6ff, + 0x10200782, + 0x19240382, + 0x1a021300, + 0x1b200f82, + 0x1c280382, + 0x8204f6ff, + 0x8304c7ff, + 0x86200382, + 0x8d280382, + 0x8e042200, + 0x8f04f9ff, + 0x90200782, + 0x91200782, + 0x92201382, + 0x93240382, + 0x9504ecff, + 0x97240382, + 0x9804e8ff, + 0x99200382, + 0x9c200382, + 0x9d200382, + 0x9e380382, + 0xa904f0ff, + 0xab04deff, + 0xc4040d00, + 0x25073e00, + 0x2607f9ff, + 0x64002200, + 0x018d0110, + 0xb3062383, + 0x91411400, + 0x05c54a08, + 0x9d1d1d47, + 0x0404211d, + 0x2905e343, + 0xffc404a3, + 0xffc504fb, + 0x118300d6, + 0xad04f324, + 0x1182b7ff, + 0x1182dd20, + 0x1188dd20, + 0x0744c120, + 0x00262806, + 0xff820405, + 0x828304ba, + 0x82862003, + 0x82912003, + 0xff923003, + 0x000100ba, + 0x0021002b, + 0x00520107, + 0x82530128, + 0x82542003, + 0x82552003, + 0x82562003, + 0x005b2303, + 0x1d830728, + 0x05900120, + 0x2e1d614c, + 0xff910215, + 0xffa802b2, + 0xff1503ec, + 0x821703a3, + 0xff212403, + 0x822203c4, + 0x82232003, + 0x82242003, + 0xff302403, + 0x823103f9, + 0x00322c03, + 0xff330314, + 0x003803e5, + 0x82390312, + 0x003a2403, + 0x82450335, + 0x8247202f, + 0x826b2003, + 0x826d2003, + 0xff972e03, + 0xffbb04b2, + 0x030300ea, + 0x03000032, + 0x24038238, + 0x00000039, + 0x260d8204, + 0xff380307, + 0x823903fc, + 0x003a2403, + 0x82050014, + 0x820d2011, + 0x030d251f, + 0x030d0039, + 0x03211182, + 0x8315823b, + 0x83158835, + 0x892d8235, + 0x00092635, + 0xff21030b, + 0x229b82cb, + 0x822303cb, + 0x82242007, + 0x20978903, + 0x204d82de, + 0x204d8205, + 0x204d8205, + 0x224d8221, + 0x82090028, + 0x82de202d, + 0x82de202d, + 0x03de242d, + 0x82deff24, + 0x82282073, + 0x82192025, + 0x82192025, + 0x823c2025, + 0x843c2025, + 0x8a142089, + 0x84282089, + 0x209f833b, + 0x20158210, + 0x202b8209, + 0x20518609, + 0xa5d58e21, + 0x2225a55f, + 0x82300308, + 0x8431205d, + 0x20a38361, + 0x20778222, + 0x2a778222, + 0x00820435, + 0x00850400, + 0x83020013, + 0xb9042305, + 0x4d4e1f00, + 0x0401320a, + 0x00feffb9, + 0xff8e0403, + 0xff9004f3, + 0xff2507f3, + 0x410d8ff3, + 0x95410c87, + 0xa50dd30d, + 0x250010ed, + 0x032d0901, + 0xecff8e04, + 0xecff9004, + 0xecff2507, + 0x420dc900, + 0x2b42180f, + 0x0201341a, + 0x0012009e, + 0xffbb0402, + 0xff1906d1, + 0x040100bd, + 0x82f1ffb9, + 0xffbb2205, + 0x830b88eb, + 0x85218b11, + 0x0024221b, + 0x91378a5b, + 0x85478b41, + 0xffb92231, + 0x10c742fe, + 0x2405cd42, + 0x00250401, + 0x2a6f820e, + 0x000900a4, + 0x008b0408, + 0x828c0419, + 0x008d2403, + 0x828e042d, + 0x828f2007, + 0x00902407, + 0x82250719, + 0x00262203, + 0x2227822d, + 0x88280001, + 0x26558505, + 0x04f5ff32, + 0x82fcff43, + 0x2109875f, + 0x25820403, + 0x85088351, + 0x04043067, + 0x04f6ff59, + 0x04f2ff5a, + 0x04f0ff5b, + 0x82e8ff5f, + 0xff592645, + 0x040a00f9, + 0x22178258, + 0x82e6ff59, + 0x82f0201b, + 0x04f6261b, + 0x04d8ff5c, + 0x2013825d, + 0x2a27845e, + 0xff6104de, + 0xffcb06ec, + 0x860700de, + 0x82f62041, + 0x84f22025, + 0x825f2021, + 0xff61224d, + 0x221d82f6, + 0x820600f2, + 0x82ec201d, + 0x201d8343, + 0x201d82f6, + 0x206382f5, + 0x203b82ec, + 0x203784f2, + 0x871986e5, + 0x83e82037, + 0x20378219, + 0x201d84f9, + 0x879786ef, + 0x82e6201d, + 0x84f0201d, + 0x820b2055, + 0x82e8209d, + 0x82f02059, + 0x82ec2021, + 0x82ec2077, + 0x82a2209d, + 0x04e6245d, + 0x82e2ff5e, + 0x04f02261, + 0x85078260, + 0x00d122a1, + 0x20298205, + 0x82c384e8, + 0x204382df, + 0x204384e8, + 0x20998a04, + 0x26f984f2, + 0xff6f0405, + 0x827004f3, + 0x827120e3, + 0xff7328c1, + 0xff7504fc, + 0x820300e6, + 0x04f92215, + 0x240d8471, + 0x040900ec, + 0x201f826e, + 0x855d826f, + 0x04ee2827, + 0x04f5ff72, + 0x82eeff73, + 0x04cd222b, + 0x20f58477, + 0x22bd82eb, + 0x8af0ff6f, + 0x82f22049, + 0x82e6201d, + 0x84f1201d, + 0x82072079, + 0x86e82051, + 0x86ee201d, + 0x82e2203b, + 0x82ee201d, + 0x00ee221d, + 0x20618208, + 0x202182fc, + 0x203f8ee2, + 0x202182de, + 0x222182f2, + 0x8a0600f0, + 0x82f2203f, + 0x835d833f, + 0x00f6221d, + 0x203b820b, + 0x201d82e8, + 0x203b82ec, + 0x20b382f0, + 0x209d82f0, + 0x222182c6, + 0x827404e8, + 0xff7526b5, + 0xff7604ec, + 0x20a586f4, + 0x20478ce6, + 0x202582f6, + 0x20a582f6, + 0x221d82e8, + 0x860500f2, + 0x82f62043, + 0x30198743, + 0x021300e2, + 0x020f0080, + 0x022d0081, + 0x02210082, + 0x20078283, + 0x24078285, + 0x02140086, + 0x20078288, + 0x241b82b3, + 0x021200be, + 0x201782bf, + 0x200782c6, + 0x200782c7, + 0x200782d0, + 0x240782d1, + 0x020500dc, + 0x202382dd, + 0x202b82e5, + 0x220b82ed, + 0xce2100ee, + 0x0501254d, + 0x00f9ffe1, + 0x092a058b, + 0x28005001, + 0x41005201, + 0x03825301, + 0x03825420, + 0x03825520, + 0x03825620, + 0x03825b20, + 0x03825d20, + 0x2200a736, + 0xb5030800, + 0xbc03d8ff, + 0xdb03ecff, + 0x0104ecff, + 0x0804e5ff, + 0x27240382, + 0xda05e5ff, + 0x538f0382, + 0x8304012a, + 0x5d00fbff, + 0xa9ff8204, + 0xa9220982, + 0x07828604, + 0x03829120, + 0x03829220, + 0xdcffcd28, + 0xe6ffcf04, + 0x0382d304, + 0x8fffd624, + 0x0782db04, + 0x0382dd20, + 0xdfffdf28, + 0xe3ffe604, + 0x1f82e704, + 0x0382e820, + 0x0382e920, + 0x0382ea20, + 0x0382eb20, + 0x0382ec20, + 0x0382ed20, + 0x0382ee20, + 0x0382ef20, + 0x0382f020, + 0x0382f120, + 0x0382f220, + 0x0382f320, + 0x0382f420, + 0x0382f520, + 0x0382f620, + 0x0382f720, + 0x0382f820, + 0x0382f920, + 0x0382fa20, + 0x0382fb20, + 0x0382fc20, + 0x0382fd20, + 0xdcfffe28, + 0xe6ff0505, + 0x03820605, + 0x03820720, + 0x03820820, + 0x03820920, + 0x03822420, + 0x03822520, + 0x03822620, + 0x03822720, + 0x03822820, + 0x03822920, + 0x03822a20, + 0x03822b20, + 0x03822c20, + 0x8fff3f24, + 0x07825605, + 0x03825720, + 0x03825820, + 0x03825920, + 0x03825a20, + 0x03825b20, + 0x03825c20, + 0x03825d20, + 0x03825e20, + 0x03825f20, + 0x03826020, + 0x03826120, + 0x03826220, + 0x03826320, + 0x03826420, + 0x03826520, + 0x03826620, + 0x03826720, + 0x03826820, + 0x03826920, + 0x03826a20, + 0x03826b20, + 0x03826c20, + 0x03826d20, + 0x03826e20, + 0x03826f20, + 0x03827020, + 0xdfff7924, + 0x03827a05, + 0x03827b20, + 0x03827c20, + 0x03827d20, + 0x03827e20, + 0x03827f20, + 0x03828020, + 0xe3ffae24, + 0x0382af05, + 0x0382b020, + 0x0382b120, + 0xe3ffb232, + 0xd2ff3706, + 0xf0050400, + 0xf805deff, + 0x0206deff, + 0x0f220382, + 0x1192deff, + 0xbb04012a, + 0x0500d8ff, + 0xf9ffb904, + 0xf0202d82, + 0xf6202d82, + 0xf6242d82, + 0xf0ff0f06, + 0x51832d92, + 0x2382f220, + 0x2382f220, + 0x2382f220, + 0x3996f220, + 0x6b854f95, + 0xa4040626, + 0xa6040900, + 0xa8200382, + 0xb9200382, + 0xbb200382, + 0xbd230382, + 0x85000900, + 0x9105851f, + 0x255396bb, + 0xfcff1206, + 0xbb820500, + 0x0623978c, + 0x96f5ff33, + 0x06022c9b, + 0x06faff24, + 0x00f3ff2a, + 0x82230609, + 0xff242809, + 0xff2506f9, + 0x822606f6, + 0xff272607, + 0xff2906eb, + 0x2a1d82ef, + 0xff2b06f5, + 0xff2c06f7, + 0x820700ef, + 0x82ef202f, + 0x06f6261d, + 0x06e3ff27, + 0x22298228, + 0x82f2ff29, + 0x82f02021, + 0x00f02221, + 0x201d8204, + 0x201d82f7, + 0x203782f2, + 0x211583f6, + 0x11820100, + 0x05829182, + 0x2506f524, + 0x3186fcff, + 0x1b84fc20, + 0x29832d83, + 0x0d82f820, + 0x5d82f220, + 0x0a00f622, + 0xf2208382, + 0xf6202b82, + 0xf2202b82, + 0x27224784, + 0x3382d5ff, + 0x4f82e920, + 0x6183f020, + 0x06212583, + 0x20878237, + 0x20258205, + 0x20a986ee, + 0x203f82f6, + 0x203f84f3, + 0x859d8406, + 0x82f620bf, + 0x20678333, + 0x221982e9, + 0x840200fc, + 0x822a2051, + 0x09455839, + 0x0c230989, + 0x46ff5904, + 0xf92c074b, + 0xf9ff5d04, + 0xdfff5f04, + 0xebff6104, + 0x22062945, + 0x827104ef, + 0x8273200b, + 0xff752903, + 0xff7704c6, + 0x041000f5, + 0x2605df46, + 0xff5a04f0, + 0x825b04f5, + 0xff5c2203, + 0x243982b3, + 0xff5e04f5, + 0x243d82e9, + 0xff6004ec, + 0x244182f0, + 0xff6e04f6, + 0x2a4582ee, + 0xff7404e2, + 0xff7504e8, + 0x827604e4, + 0xff77240f, + 0x460700f6, + 0x612208d5, + 0xcd45fcff, + 0x82f6200a, + 0x00ee2c25, + 0x0059040f, + 0x005a040c, + 0x825b041e, + 0xff5c2403, + 0x825d04ec, + 0x825e2007, + 0x826e2029, + 0xff6f3003, + 0x007004f6, + 0x0071041a, + 0x0072040e, + 0x82730414, + 0x82742007, + 0x00762217, + 0x2c9d820a, + 0x020400f6, + 0x0221001e, + 0x0235001f, + 0x3a078220, + 0x002e0021, + 0x00d70001, + 0x00170007, + 0x00230021, + 0x00290028, + 0x0033002d, + 0x18420172, + 0x180a9981, + 0x220a9581, + 0x18015b01, + 0x20176181, + 0x31811889, + 0x1892200a, + 0x2a0c2b81, + 0x01d801d5, + 0x01df01dc, + 0x5fea01e0, + 0x48080805, + 0x01fd01fa, + 0x020702fe, + 0x020b020a, + 0x0212020f, + 0x02170216, + 0x02190218, + 0x021e021a, + 0x0220021f, + 0x02250221, + 0x026c026a, + 0x0271026d, + 0x02790275, + 0x027b027a, + 0x027e027d, + 0x02860281, + 0x028e0287, + 0x029e0296, + 0x02a902a1, + 0xe77e18ae, + 0x02e33810, + 0x02e502e4, + 0x02e702e6, + 0x02e902e8, + 0x033303ea, + 0x03350334, + 0x18370336, + 0x080a0b7e, + 0xb4038931, + 0xc403b503, + 0xca03c703, + 0xe003d403, + 0xe503e403, + 0xeb03e603, + 0xfb03f003, + 0x0104fc03, + 0x13041204, + 0x25041604, + 0x31043004, + 0x35043304, + 0x18043704, + 0x20074b7c, + 0x157c1858, + 0xfd7b1812, + 0x93360813, + 0xa3049504, + 0xa704a504, + 0xb804a904, + 0xbc04ba04, + 0x8905dd04, + 0xd805d705, + 0xda05d905, + 0xeb05dd05, + 0xef05ec05, + 0x0906f905, + 0x0b060a06, + 0x10060d06, + 0x14061206, + 0x78181506, + 0x2408146b, + 0x06b60637, + 0x06c606b7, + 0x06c806c7, + 0x002b07ca, + 0x00b82a02, + 0x2b000004, + 0x000a2c10, + 0x0082002a, + 0xffecff00, + 0x220182f6, + 0x84effff2, + 0x00fb2101, + 0x01000010, + 0xff103003, + 0xfff6ffef, + 0xffe2ffb0, + 0xffdbffc4, + 0x101300c4, + 0x03011401, + 0xfff6ff27, + 0xffb0ffb7, + 0x0b0110a3, + 0xc3240401, + 0xd8ffcbff, + 0x29fd0941, + 0x0000deff, + 0xf2ffecff, + 0x0382e8ff, + 0xc9ffd124, + 0x0d82e6ff, + 0x83ffde21, + 0xffe22209, + 0x201784d8, + 0x261b82ec, + 0xffebffd1, + 0x82e5fff6, + 0x82e82005, + 0xffec2205, + 0xcb3541db, + 0x82efff21, + 0x87f020db, + 0xe6ff21d1, + 0x11870991, + 0x1f860783, + 0xf2ff0322, + 0xf2243582, + 0x0300ecff, + 0x00101583, + 0x20000103, + 0x01011021, + 0x00210001, + 0x03011000, + 0x9f419f01, + 0xecff2506, + 0x0d00f6ff, + 0x825baf42, + 0x00cb2e61, + 0x00abff49, + 0xffabff0d, + 0xffe3ffb7, + 0x820d83ee, + 0x82cb2007, + 0xdbb72003, + 0xa75b4079, + 0xfff2ff23, + 0x450182ec, + 0xb7ed0875, + 0xedf6ff21, + 0xfd6d406f, + 0x45e0ff21, + 0xff220719, + 0x008300d3, + 0x04832120, + 0xffe0ff23, + 0x830f86f0, + 0x2303f20e, + 0xecffe3ff, + 0xff217699, + 0xd51b99b0, + 0xecff2519, + 0xf0ffedff, + 0xf1200384, + 0x558f61d5, + 0xffe2ff2f, + 0x00dcffd8, + 0xffd8ff00, + 0xffdeffe1, + 0x201f90e1, + 0xdf118fc0, + 0xd2ff230f, + 0x8d82e6ff, + 0xddffe628, + 0xdbffd1ff, + 0x6fdfc8ff, + 0xff2b5f95, + 0x00d8ffe8, + 0xfff6ff00, + 0x89e8fffa, + 0xf6ff2121, + 0xf2209982, + 0x43440f87, + 0x06614225, + 0x00001023, + 0x873988ff, + 0x8207a741, + 0x82ef208d, + 0xffd5227b, + 0x237f82ef, + 0xffe2ffe8, + 0xe2200983, + 0x27403da7, + 0x2309108e, + 0x2e429f01, + 0xb8074267, + 0xb348ff20, + 0x67984176, + 0xff2167a3, + 0x1025a3fa, + 0x28012300, + 0x23a80b43, + 0x0000f0ff, + 0x211ff746, + 0x2382f2ff, + 0xe3ffe322, + 0x210ffd41, + 0x1190efff, + 0x2982f020, + 0x0600f022, + 0xf2200582, + 0xff251b83, + 0xff0000e6, + 0x210383c0, + 0x0f83c6ff, + 0x03820983, + 0xc6201583, + 0x8313a949, + 0xf6ff2113, + 0xd8200584, + 0xff221f85, + 0x0982ffd3, + 0xe8260582, + 0xecffe8ff, + 0x0582e6ff, + 0xf0ffef22, + 0xe6240582, + 0xf2ffe5ff, + 0xd1240982, + 0xdaffdeff, + 0xe8200f82, + 0xda201b82, + 0x05ff6385, + 0x822b1748, + 0x41f220c3, + 0xcfad1f7f, + 0xa3f6ff21, + 0xc2ff274f, + 0xebff0000, + 0x5badd4ff, + 0xff252db7, + 0xff3b00c6, + 0x227182a9, + 0x84a7ffa9, + 0x230d8243, + 0xc6ffd8ff, + 0x0f850382, + 0xff211482, + 0xa00482dd, + 0xc2ff2102, + 0xff212783, + 0x212885d6, + 0x0987c2ff, + 0xdd200f88, + 0xd9821183, + 0xddffeb22, + 0xd4200582, + 0x0d26e1ac, + 0xecfff2ff, + 0x0584cbff, + 0x4756ec20, + 0xcbff210d, + 0x05ae6185, + 0x254a0d20, + 0x203b823b, + 0x200382f9, + 0x567383ec, + 0xf55018d7, + 0x29914224, + 0xffdfff27, + 0x00ecfff0, + 0x22738206, + 0x510d0013, + 0x15830e53, + 0x02ad1882, + 0x00dfff23, + 0x3b614700, + 0x03268d82, + 0xcbff1300, + 0x95820300, + 0xecff0d22, + 0x3b440983, + 0xa161830d, + 0x4183a993, + 0x0a200603, + 0x21225382, + 0x01821a00, + 0x02880882, + 0x0c881583, + 0x034108a7, + 0x00062c42, + 0x00b7ff21, + 0x000a0006, + 0x83ecff1a, + 0x5e034109, + 0xf0ffd522, + 0xed836182, + 0x0e001a22, + 0x03410182, + 0x42d52041, + 0x00204007, + 0xa320fb82, + 0x0a258882, + 0xecff0e00, + 0x410982ff, + 0x61820e03, + 0x029e1d82, + 0xeb48d782, + 0xbaff2136, + 0x1e405a9e, + 0x030110e2, + 0xcd200401, + 0x28e2e841, + 0xfff6ff00, + 0x00f6ffe1, + 0xa5ebc009, + 0x8c192041, + 0x830d8d67, + 0x5109201a, + 0xf14305b7, + 0x8d18830d, + 0x0eb54703, + 0x870e0b5e, + 0x22d9821d, + 0x82e8ffe1, + 0x072b4905, + 0xb0ff1925, + 0x82003a00, + 0x29294705, + 0x0dbe778d, + 0x8fa82f4c, + 0x15b549e7, + 0x2105814a, + 0x5b4cf9ff, + 0x05334c11, + 0x21056541, + 0x1f82f5ff, + 0x518ffc20, + 0x5f830fa9, + 0xcb412d9b, + 0x9b5d9f3d, + 0x201b8979, + 0x83df92ff, + 0x832187f7, + 0x87239365, + 0x9f079f1f, + 0x9d1f9fa5, + 0x9d3dbd5f, + 0x431d985b, + 0xff23980b, + 0x820700ea, + 0xff002403, + 0x82eaffe3, + 0x98f92001, + 0x2018d5c1, + 0x21569157, + 0x8984f1ff, + 0xa741ea20, + 0x58ff2059, + 0xfd4f06b7, + 0xf8ff2307, + 0xf343f3ff, + 0x00062106, + 0x94910183, + 0xff2511ee, + 0xfff9ffe5, + 0x220382f1, + 0x410000f2, + 0x35463707, + 0x20c09a0d, + 0x831b832f, + 0xfcff2165, + 0x8311db44, + 0x4503831b, + 0x19831513, + 0x1f5103c3, + 0x427f8306, + 0x15470881, + 0xe8ff2307, + 0xc953f9ff, + 0xf5ff2537, + 0xfaff0000, + 0x41198b44, + 0x534f0923, + 0x822b9907, + 0xc3d72049, + 0x234397eb, + 0xe8fff6ff, + 0xfc206382, + 0xb5820382, + 0x73462585, + 0x20118205, + 0x4b0382ef, + 0xf62037e1, + 0x201daf4f, + 0x10a359ff, + 0x501c0341, + 0xbd8524d1, + 0x074205b1, + 0x9bc79d1d, + 0xfaff216d, + 0x4d5f3b82, + 0x0c2b431a, + 0x2a000128, + 0xf301dd01, + 0xed6bfa01, + 0x021e2706, + 0x0398021f, + 0xa8180394, + 0x32080fcb, + 0x04f103ed, + 0x043a0439, + 0x045f0449, + 0x04880475, + 0x049e048a, + 0x06ab04a9, + 0x06160612, + 0x062a0624, + 0x0630062c, + 0x06330631, + 0x07370634, + 0x002f072b, + 0x82290002, + 0x00dd2857, + 0x01fa010b, + 0x820100fa, + 0x0016345d, + 0x02170227, + 0x02280017, + 0x00180218, + 0x021e0229, + 0x820d001e, + 0x001f286d, + 0x0298020e, + 0x82170098, + 0x00942275, + 0x08798221, + 0x1000a73e, + 0xa803a803, + 0xa9030600, + 0x2400a903, + 0xaa03aa03, + 0xab031500, + 0x1200ab03, + 0xac03ac03, + 0xad030800, + 0x1100ad03, + 0xae03ae03, + 0xed030700, + 0x0400ed03, + 0xf103f103, + 0x39040200, + 0x22003904, + 0x3a22a582, + 0xa9822300, + 0x0a004922, + 0x5f22ad82, + 0xb1821e00, + 0x1d007522, + 0x8822b582, + 0xb9820c00, + 0x18008a22, + 0x9e22bd82, + 0xc1821600, + 0x2000a928, + 0xab04ab04, + 0xc9820900, + 0x05001222, + 0x1622cd82, + 0xd1820300, + 0x14002422, + 0x2a22d582, + 0xd9821f00, + 0x13002c22, + 0x3022dd82, + 0xe1821900, + 0x1c003122, + 0x3322e582, + 0xe9821a00, + 0x1b003428, + 0x37063706, + 0xf1820f00, + 0x26002b24, + 0xf7822f07, + 0x02002524, + 0xfd826d01, + 0x6c000224, + 0x01840400, + 0x08000822, + 0x0b260782, + 0x7c000b00, + 0x01821000, + 0x12000422, + 0x04220182, + 0x01821400, + 0x15006d22, + 0x41220182, + 0x01821600, + 0x17004222, + 0x43220182, + 0x01821800, + 0x19004422, + 0x6e220182, + 0x01821a00, + 0x1b004522, + 0x6f220182, + 0x01821c00, + 0x1d004a22, + 0x7f280182, + 0x20001e00, + 0x21000300, + 0x01220182, + 0x01822200, + 0x23000222, + 0x7f220182, + 0x01822400, + 0x25007b22, + 0x402e0182, + 0x27002600, + 0x28007f00, + 0x4b002900, + 0x01822a00, + 0x2b000322, + 0x4b220182, + 0x01822c00, + 0x2d000322, + 0x4b220182, + 0x01822e00, + 0x2f004c22, + 0x05220182, + 0x01823000, + 0x31004d22, + 0x06220182, + 0x01823200, + 0x33000722, + 0x50220182, + 0x01823400, + 0x35000822, + 0x4e240182, + 0x4d003600, + 0x5128d782, + 0x3e005100, + 0x58005400, + 0x5d22d782, + 0x0b825d00, + 0x7b007322, + 0x80260b82, + 0x3f008000, + 0x01828e00, + 0xa5007c24, + 0x1182bf00, + 0x00c82308, + 0x006d00ce, + 0x00d700d0, + 0x00d80041, + 0x004200ef, + 0x00f300f0, + 0x00f40044, + 0x004500fb, + 0x000001fc, + 0x0082016f, + 0x3e003508, + 0x03010301, + 0x06017d00, + 0x4a002001, + 0x21012101, + 0x22018000, + 0x7f002301, + 0x41012401, + 0x42010300, + 0x01004201, + 0x4a014301, + 0x4b010200, + 0x7f004e01, + 0x4f014f01, + 0x50342382, + 0x7b005b01, + 0x5c015c01, + 0x5d014b00, + 0x40005d01, + 0x60015e01, + 0x61221d82, + 0x11826101, + 0x68016222, + 0x6a220b82, + 0x0b827401, + 0x90017622, + 0x91224782, + 0x0b829801, + 0x9f019928, + 0xa0014c00, + 0x1d82a001, + 0x01a12008, + 0x010500a8, + 0x00c101a9, + 0x01c2014d, + 0x010700c5, + 0x00cd01c6, + 0x01ce0108, + 0x014e00d2, + 0x82d401d4, + 0x01d52223, + 0x223582d5, + 0x82d601d6, + 0x01d7225f, + 0x227182d7, + 0x82d801d8, + 0x01d9222f, + 0x221782d9, + 0x82db01da, + 0x01dc2823, + 0x010300dc, + 0x82df01de, + 0x01e12205, + 0x220582e1, + 0x82e201e2, + 0x01e3221d, + 0x220b82e3, + 0x82e901e9, + 0x01ea223b, + 0x220b82ec, + 0x82ed01ed, + 0x01ee225f, + 0x224182ee, + 0x82f001ef, + 0x01f1223b, + 0x222982f1, + 0x82f401f4, + 0x01f82205, + 0x221182f9, + 0x82fa01fa, + 0x01fb220b, + 0x222382fc, + 0x82fd01fd, + 0x01fe220b, + 0x2e4182fe, + 0x000002ff, + 0x0203024b, + 0x02030006, + 0x820a020a, + 0x020c220b, + 0x0805820d, + 0x0e020e32, + 0x0f024c00, + 0x40001002, + 0x12021102, + 0x15020500, + 0x4d001502, + 0x19021902, + 0x1a020600, + 0x4e001c02, + 0x29022502, + 0x2a020100, + 0x36003702, + 0x5a023902, + 0x5b284182, + 0x7f006202, + 0x64026402, + 0x20081782, + 0x00650265, + 0x0268027b, + 0x02640068, + 0x006b026b, + 0x026d0266, + 0x026b006d, + 0x006f026f, + 0x02720275, + 0x28178272, + 0x00750275, + 0x0276026a, + 0x08118276, + 0x79027926, + 0x7a026900, + 0x3c007a02, + 0x7b027b02, + 0x7d023d00, + 0x65007d02, + 0x7e027e02, + 0x80026800, + 0x7a008002, + 0x87028702, + 0x20081782, + 0x00890289, + 0x028b0270, + 0x0247008b, + 0x00930293, + 0x02950267, + 0x02480095, + 0x00970297, + 0x029a0271, + 0x2805829a, + 0x009b029b, + 0x029d0249, + 0x280b829d, + 0x009e029e, + 0x02a00246, + 0x220b82a1, + 0x82a402a4, + 0x02a52205, + 0x224182a5, + 0x82aa02aa, + 0x02ad220b, + 0x220582ad, + 0x82b902b0, + 0x02ba225f, + 0x229582bb, + 0x82ea02e9, + 0x02f52265, + 0x340b82f5, + 0x00fd02f6, + 0x0310037a, + 0x0370001c, + 0x00470340, + 0x035a0371, + 0x22058264, + 0x82700365, + 0x037d2211, + 0x220b8288, + 0x828b038a, + 0xb1260805, + 0x5d00b103, + 0xb503b503, + 0xb7031e00, + 0x6200b703, + 0xb803b803, + 0xbc032e00, + 0x2300bc03, + 0xbf03bf03, + 0xc2037400, + 0x0582c203, + 0x03c32008, + 0x033a00c3, + 0x00c403c4, + 0x03c50327, + 0x032000c5, + 0x00c603c6, + 0x03c80360, + 0x031b00c8, + 0x82cb03cb, + 0x03ce221d, + 0x283b82ce, + 0x00d003d0, + 0x03d3032b, + 0x221182d3, + 0x82d503d5, + 0x03d62e3b, + 0x035e00d6, + 0x00da03da, + 0x03db0379, + 0x225982db, + 0x82dd03dd, + 0x03e0221d, + 0x284d82e0, + 0x00e203e2, + 0x03e30361, + 0x282982e3, + 0x00e403e4, + 0x03e70338, + 0x228982e7, + 0x82e803e8, + 0x03ea224d, + 0x222982ea, + 0x82ec03ec, + 0x03ef221d, + 0x227182ef, + 0x82f003f0, + 0x03f32271, + 0x222382f3, + 0x82f403f4, + 0x03f922bf, + 0x221d82fa, + 0x82fc03fb, + 0xfd23084d, + 0x7200fd03, + 0xfe03fe03, + 0xff031900, + 0x24000004, + 0x01040104, + 0x02041c00, + 0x73000204, + 0x03040304, + 0x82042f00, + 0x2c002500, + 0x07040504, + 0x08281d82, + 0x21000804, + 0x0a040904, + 0x0b220b82, + 0x23820b04, + 0x0c040c22, + 0x0e220b82, + 0x0b820e04, + 0x0f040f2e, + 0x10042600, + 0x3b001004, + 0x11041104, + 0x12281182, + 0x5f001204, + 0x13041304, + 0x14282382, + 0x1a001404, + 0x16041504, + 0x17220b82, + 0x29821704, + 0x19041822, + 0x1a280b82, + 0x1f001a04, + 0x1b041b04, + 0x1c280b82, + 0x29001c04, + 0x1e041d04, + 0x20223b82, + 0x11822004, + 0x21042122, + 0x232e0b82, + 0x78002404, + 0x26042604, + 0x27043900, + 0x83822704, + 0x28042822, + 0x2a221d82, + 0x05822b04, + 0x2c042c22, + 0x2d227182, + 0x0b822d04, + 0x2e042e28, + 0x2f042800, + 0x35822f04, + 0x30043028, + 0x31043700, + 0x17823104, + 0x33043322, + 0x3422cb82, + 0xcb823404, + 0x35043522, + 0x36221182, + 0x83823604, + 0x37043722, + 0x38220b82, + 0x2f823804, + 0x3a043922, + 0x3b222f82, + 0xb3823b04, + 0x3c043c22, + 0x3e22ad82, + 0x35823e04, + 0x41044028, + 0x42047200, + 0x23824204, + 0x44044422, + 0x45222f82, + 0x0b824604, + 0x48044722, + 0x822e7782, + 0x11008304, + 0x85048404, + 0x86045100, + 0x0b828604, + 0x8904893a, + 0x8b041200, + 0x15008c04, + 0x8d048d04, + 0x8e041300, + 0x14008e04, + 0x8f048f04, + 0x90220b82, + 0x0b829004, + 0x92049122, + 0x932e2982, + 0x7e009304, + 0x94049404, + 0x95043100, + 0x0b829504, + 0x96049622, + 0x97280b82, + 0x4f009904, + 0x9d049c04, + 0xb4220582, + 0x4d82b404, + 0xb704b622, + 0xcc340582, + 0x7b00cc04, + 0xcd04cd04, + 0xcf040900, + 0x0a00cf04, + 0xd304d304, + 0xd6280582, + 0x5a00d604, + 0xdb04db04, + 0xdd220b82, + 0x0582dd04, + 0x04df3e08, + 0x040b00df, + 0x00e004e0, + 0x04e1040c, + 0x040d00e1, + 0x00e204e2, + 0x04e3040e, + 0x040f00e3, + 0x00e404e4, + 0x04e5045b, + 0x041000e5, + 0x00e604e6, + 0x04e7045c, + 0x050900fe, + 0x00090505, + 0x0524050a, + 0x2805822c, + 0x003f053f, + 0x0556055a, + 0x080b8270, + 0x8005793e, + 0x81050b00, + 0x77008105, + 0x89058205, + 0x8a050c00, + 0x0d00a105, + 0xa505a205, + 0xa6050f00, + 0x1000ad05, + 0xb205ae05, + 0xb9055c00, + 0x6300b905, + 0xbe05be05, + 0xc0055900, + 0x7600c005, + 0xc305c305, + 0xc7221182, + 0x0b82c705, + 0xcb05cb34, + 0xcc055700, + 0x5800cc05, + 0xce05ce05, + 0xd2055600, + 0x0b82d205, + 0xd305d322, + 0xd6342382, + 0x3200d605, + 0xd905d705, + 0xda052500, + 0x1d00da05, + 0xdb05db05, + 0xdc2e0b82, + 0x3000dc05, + 0xdd05dd05, + 0xde052d00, + 0x1182e005, + 0xe105e128, + 0xe2052200, + 0x0b82e305, + 0xe405e428, + 0xe5053400, + 0x0b82e605, + 0xe705e722, + 0xe83a0b82, + 0x1700e805, + 0xe905e905, + 0xea053500, + 0x3300ea05, + 0xeb05eb05, + 0xec055300, + 0x2382ec05, + 0xed05ed28, + 0xee051600, + 0x0b82ef05, + 0xf005f022, + 0xf1222982, + 0x0b82f205, + 0xf305f322, + 0xf4225f82, + 0x0b82f405, + 0xf505f528, + 0xf6052a00, + 0x0b82f705, + 0xf805f822, + 0xf9222382, + 0x0b82f905, + 0xfa05fa22, + 0xfb285f82, + 0x5200fb05, + 0xfd05fc05, + 0xff3a1182, + 0x5500ff05, + 0x00060006, + 0x01062200, + 0x25000106, + 0x02060206, + 0x03061700, + 0x0b820406, + 0x05060525, + 0x82063500, + 0x340b8200, + 0x00070607, + 0x06080618, + 0x06340008, + 0x00090609, + 0x060a0654, + 0x2e17820a, + 0x000c060c, + 0x060d0630, + 0x062d000d, + 0x820e060e, + 0x060f2211, + 0x2241820f, + 0x82100610, + 0x0611220b, + 0x2e2f8211, + 0x00140614, + 0x06150653, + 0x06160015, + 0x82170616, + 0x06182217, + 0x28358218, + 0x00190619, + 0x061b0632, + 0x2211821b, + 0x821d061d, + 0x061e2205, + 0x222f821f, + 0x82210620, + 0x069c2877, + 0x0681009c, + 0x82a306a2, + 0x06a52205, + 0x220582a8, + 0x82ac06ac, + 0x06af2205, + 0x080582af, + 0xb706b638, + 0xbf065000, + 0x8100bf06, + 0x25072507, + 0x26071400, + 0x13002607, + 0xb507b407, + 0x02000100, + 0x0400902d, + 0x422e0000, + 0x3400d031, + 0x00007000, + 0xf2fff0ff, + 0xe5ffe8ff, + 0x0982f4ff, + 0x4000ca21, + 0xff21d400, + 0x21d683c1, + 0x0582d1ff, + 0xc8ff0a2e, + 0xfaff0700, + 0x0700fcff, + 0xf6ff0300, + 0xe2280b82, + 0x1400f0ff, + 0xf6ff1400, + 0xe525ff82, + 0xd8ffe3ff, + 0x247958ff, + 0x02404b82, + 0xf2ff2184, + 0xc9200182, + 0xe628b582, + 0xa2ffc8ff, + 0xdcff0000, + 0x1420d982, + 0x07209a82, + 0x1020d582, + 0x02870782, + 0x67ff0d21, + 0x1726092b, + 0xe5fffaff, + 0x2182b0ff, + 0x17000726, + 0xf9ff1900, + 0xff230983, + 0x830400fc, + 0xf6ff2b09, + 0xcbfff9ff, + 0xf6ff0d00, + 0x03841400, + 0xd8fff22a, + 0xf1ff0e00, + 0x1000f2ff, + 0x0f200382, + 0x04202b82, + 0xf2257382, + 0xbdff1800, + 0x227983ff, + 0x87ccffb0, + 0x2107d364, + 0xd582deff, + 0x0382d420, + 0x8d1a0d6a, + 0xf6ff2177, + 0xf7202d82, + 0xff231385, + 0x82ebfff6, + 0x2011830d, + 0x200782ef, + 0x821583fc, + 0x4d0020e5, + 0x198311fd, + 0x45820397, + 0x9712fb53, + 0x2517ad2d, + 0x0000f0ff, + 0x0382dcff, + 0x37addf20, + 0x14202d82, + 0x02850382, + 0xdb850620, + 0x4e05c14e, + 0x2e851bc7, + 0xff210585, + 0x0b6d5df0, + 0x00faff22, + 0x85340f5d, + 0x23059f4b, + 0xc9ffebff, + 0xff202383, + 0x210a6344, + 0x8182f2ff, + 0x834ec420, + 0xe5ff2505, + 0xebff0000, + 0x03c92183, + 0x8fd1ff21, + 0xefff214b, + 0x8f1f7358, + 0x2b0f9f31, + 0xd4ffdfff, + 0xcdff9cff, + 0xbdffe8ff, + 0xff212b83, + 0x850583de, + 0xfcff2103, + 0x5763df82, + 0x221b8610, + 0x86b6ffe8, + 0xfff22809, + 0x00fcfff9, + 0x82f9ff00, + 0x84f12001, + 0xfff52407, + 0x85e5ffb0, + 0x23059b1d, + 0xcbffb4ff, + 0xff211f85, + 0x206b82f5, + 0x263b82f2, + 0xfff6fffc, + 0x82e5fff2, + 0x82f52001, + 0xfff92103, + 0x850ef960, + 0x8205ab2d, + 0xffec224f, + 0x200182e8, + 0x206382f5, + 0x2039a9cf, + 0x1a7550ff, + 0x298a45a9, + 0x0b8a0620, + 0xb5420a8d, + 0xe8ff234c, + 0xbb890000, + 0x7744fd84, + 0xfcff2306, + 0x7882fcff, + 0x5d430920, + 0xc72b8227, + 0x000d2202, + 0x254ab903, + 0xecffe8ff, + 0xd582e2ff, + 0xf0fff524, + 0xdb891700, + 0x000d0023, + 0x200d8210, + 0x086f5403, + 0x83087d53, + 0x20f9826b, + 0x210783e4, + 0xef8e0000, + 0x15831d20, + 0x41e5ff21, + 0x43892ddf, + 0xff203783, + 0x4305a942, + 0x0e2007ed, + 0x7f6d5184, + 0x233d8338, + 0xecff0000, + 0xff21c783, + 0x200782fc, + 0x220984f0, + 0x82effff0, + 0xffd22215, + 0x220d86d5, + 0x560600f2, + 0x61853751, + 0x4b440591, + 0xf9ff2111, + 0x20125746, + 0x82398210, + 0x559b8203, + 0x118208e3, + 0xff2102a6, + 0x20c582fc, + 0x20d582b0, + 0x07ab45ec, + 0x8605fb62, + 0x85c42005, + 0x0de94446, + 0x69842d82, + 0xfff2ff23, + 0x833d82d9, + 0x82098241, + 0x85e1207f, + 0x0000242d, + 0x41ffd1ff, + 0xff21226f, + 0x427388f3, + 0x3e8205fb, + 0x82e8ff21, + 0x82c9203d, + 0xfff6244b, + 0x82e6ffcd, + 0x00de220b, + 0x20168206, + 0x050b4100, + 0x8309e741, + 0x2703b113, + 0x0000dcff, + 0xf7ffd3ff, + 0x69830584, + 0xd7418920, + 0x87962006, + 0x8761bf4b, + 0x21079547, + 0x1155f9ff, + 0x2124880c, + 0xe982f3ff, + 0x4938d144, + 0xff210979, + 0x204782d2, + 0x205683b2, + 0x240583ff, + 0x0088ff0e, + 0x240d8404, + 0xff000090, + 0x830983f8, + 0xd5ff2303, + 0x0784ceff, + 0xabffcf22, + 0x21056743, + 0x0982c4ff, + 0xed70f220, + 0x280d490c, + 0x2d884984, + 0x0982ff20, + 0xff6eff27, + 0xff0000f5, + 0x821983c8, + 0x84df2007, + 0x23dd8613, + 0xb5ffe8ff, + 0x05a51785, + 0x45f2ff21, + 0x339b0b23, + 0x83097142, + 0x0e3f44d3, + 0x39820d20, + 0x03820820, + 0x03820620, + 0x45000021, + 0x1e8419eb, + 0x4d8b0491, + 0x210fe543, + 0x7989ecff, + 0xeb20ed82, + 0x8339595a, + 0xe8ff2777, + 0xf8ff0000, + 0x0b82d8ff, + 0x09820920, + 0xf0fffc22, + 0x82110544, + 0x8b02981b, + 0x9a24988b, + 0x85e98b18, + 0xe5ff2126, + 0x85052343, + 0x4905850d, + 0xff212949, + 0x203f82fc, + 0x08f542ee, + 0x49440720, + 0x830f200a, + 0x835b824b, + 0x4b0a82eb, + 0xff200de5, + 0x8406d36b, + 0x83d42023, + 0x00002105, + 0x22068348, + 0x67f2ffe3, + 0x3985299f, + 0x7182058b, + 0x0f83f620, + 0xff25e987, + 0x00f2ffe6, + 0x0bfb4200, + 0x03cd1d83, + 0x8b9cff21, + 0x07c3494f, + 0x00cfff25, + 0x84f2ff00, + 0x83c4207d, + 0x88038209, + 0x24f54199, + 0x55840720, + 0x37823a20, + 0xb741d520, + 0x821b8411, + 0xd3ff2104, + 0x210c854b, + 0xeb8400d5, + 0x232f2742, + 0x0d00f9ff, + 0xa7833982, + 0xe2ffb425, + 0x82ffc5ff, + 0x09002305, + 0x13825aff, + 0x0382f320, + 0x6882a120, + 0xff2002a4, + 0xa2085f7f, + 0x097f4c2e, + 0xff462c88, + 0xecff210d, + 0xc8207b82, + 0x05820385, + 0x88131d47, + 0x21089739, + 0x3982d6ff, + 0x1d85e320, + 0xffa3ff27, + 0xff83ffd3, + 0x201182b7, + 0x21118383, + 0x05844cff, + 0x7fffec24, + 0xc3420000, + 0x82002008, + 0xffc42225, + 0x2a1182c5, + 0xff93ff97, + 0xffcbffbb, + 0x828fffb2, + 0xffe22409, + 0x82d3ffef, + 0x82dc2015, + 0xffe72243, + 0xa43983bf, + 0x21e58203, + 0x298293ff, + 0x03820720, + 0xbfff0027, + 0x3fffcfff, + 0x836d8200, + 0x2145836f, + 0x8f84a1ff, + 0x1d84d220, + 0x97ffb722, + 0x03830783, + 0x82c5ff21, + 0x20d34d01, + 0xfff1ff25, + 0x41dfffe8, + 0xff210535, + 0x933783e9, + 0x6cff2003, + 0x5984083b, + 0x2007d95c, + 0x210d830f, + 0x13830800, + 0xff210383, + 0x09ef5bf6, + 0x830f0545, + 0x2103991f, + 0x2f89efff, + 0x270ba942, + 0x0000ecff, + 0xe8fff2ff, + 0x2109054a, + 0x0b82efff, + 0x03828d83, + 0x07204f84, + 0x2127a942, + 0x2f82fcff, + 0xe5ff0322, + 0xf6203f82, + 0x0d824583, + 0x9d450282, + 0x226b8309, + 0x4a000600, + 0x6da71ee9, + 0x02945a82, + 0x83823f93, + 0x2e83d582, + 0x0883a384, + 0xff2103aa, + 0x2a3f82f0, + 0xff0000e8, + 0x00f6fff9, + 0x82d1ff10, + 0x07bf463a, + 0x14000322, + 0xf1821b82, + 0x9f421382, + 0x00f6240b, + 0x88dbff03, + 0x790d2089, + 0x3d8205d9, + 0xf0ff0026, + 0xefff0000, + 0x84275346, + 0x8c5a8371, + 0x85578503, + 0xecff211b, + 0xe5204f82, + 0x15881183, + 0x470d834a, + 0x8b822069, + 0xe8fff624, + 0x4f83e5ff, + 0x8c0bdb4e, + 0x410c8472, + 0xd988093b, + 0x04871784, + 0x7983ff20, + 0x0d840520, + 0x0a840585, + 0xc183049f, + 0x4d000021, + 0x2c86067b, + 0x200e7b45, + 0x8e16830a, + 0xae128313, + 0x42bf8503, + 0xc18905fd, + 0xf0207982, + 0xe589488b, + 0x0b89158b, + 0x890b3d43, + 0x8d09a915, + 0x470d853f, + 0x45a90711, + 0xe822b18c, + 0x59440000, + 0xff0a2208, + 0x4b0d82ec, + 0xff2108fb, + 0x0d0352f6, + 0xff213789, + 0x508989e9, + 0xff21058b, + 0x09ff46e1, + 0x8df3ff21, + 0x9f3789a7, + 0x44718209, + 0xd14706e5, + 0x20579415, + 0x0146180a, + 0x2061900b, + 0x8311821a, + 0x822d2003, + 0x20029507, + 0x0e1f4d21, + 0x2682f020, + 0xcd821420, + 0x2005d941, + 0x20098617, + 0x22478610, + 0x82170000, + 0x820d8309, + 0x22029c06, + 0x8221003c, + 0x8262201f, + 0x00f6243f, + 0x820e000d, + 0x8202830b, + 0x0c975359, + 0x0d49f620, + 0x1f3b4207, + 0x08953588, + 0x16852820, + 0x2808ff4d, + 0xff350010, + 0x002800bd, + 0x227f820f, + 0x823500c4, + 0x821d201d, + 0x2002cb03, + 0x834c901b, + 0x44148e65, + 0x2820085d, + 0x0d20df82, + 0x0ea11c8e, + 0x22823c20, + 0x1d22d983, + 0xc7822f00, + 0x8f4cf220, + 0x82df2008, + 0xff002217, + 0x200584b0, + 0x830785f0, + 0x2903830b, + 0x0000f0ff, + 0x1000f6ff, + 0x0182dfff, + 0x0b82f620, + 0xd8fffa22, + 0x17200984, + 0x0f821d83, + 0x0f00f622, + 0x2224814a, + 0x8618002f, + 0x82e82031, + 0x002d2107, + 0x2206b941, + 0x85009cff, + 0xff3524e7, + 0x823500ec, + 0x06c14559, + 0xb9461583, + 0x08554d0c, + 0x00203d82, + 0x0b844b87, + 0xff2004a6, + 0x87075b4b, + 0x4037a661, + 0x06209826, + 0xc3479984, + 0x00062605, + 0x00dcff0d, + 0x4311830d, + 0xf5431feb, + 0x8341850a, + 0x8a03aa34, + 0x4f35823f, + 0x188215c3, + 0xff2502b4, + 0xff0000ef, + 0x530382e5, + 0x4a9b0c1f, + 0x35838d83, + 0x820f0021, + 0x49fc2035, + 0x0d82099f, + 0x3783f920, + 0x7b51ff20, + 0x86278322, + 0x00162603, + 0xfff1ff00, + 0x078358f9, + 0x210b4544, + 0x1b82ecff, + 0x4f8be820, + 0x6582ad84, + 0x860b976c, + 0x6606a247, + 0xeb500587, + 0x83092008, + 0xf0ff2132, + 0x0d220582, + 0x51430900, + 0xcf2a8224, + 0x47dd8302, + 0xff223bdd, + 0xed5900e2, + 0x0b6b4d0a, + 0xff21a983, + 0x08e352e3, + 0x0f83e820, + 0xff210387, + 0x2cef82e8, + 0x000b0014, + 0xff1d000d, + 0x001400e6, + 0x2719830f, + 0x0000efff, + 0xeffff6ff, + 0xe9441b82, + 0x0ca1412c, + 0x200a8149, + 0x210b82ff, + 0x5344e5ff, + 0x4b538208, + 0x8d822db7, + 0x8d82ed20, + 0xd8ffc728, + 0xe6fff4ff, + 0xa383e7ff, + 0x1f430393, + 0x0c7f420e, + 0x82072b50, + 0x06e55347, + 0x82fcff21, + 0x16b75857, + 0xff235d8b, + 0x4ee3fff2, + 0x9342052f, + 0x84218b0b, + 0x34d1430b, + 0x048c3984, + 0x42050342, + 0x7d820985, + 0xf382f720, + 0x1783e620, + 0x84e5ff21, + 0x56ec2005, + 0x378c06e5, + 0x5b410c89, + 0x8739892f, + 0xfcff2109, + 0xae0d9759, + 0x12334251, + 0x00f6ff25, + 0x86e8ff00, + 0x4cde20db, + 0x3f4506fd, + 0xff0b2307, + 0x3d4100e8, + 0x081b5114, + 0x3d82e920, + 0x0383f920, + 0xfff0ff27, + 0x00effff2, + 0x06a74200, + 0x7142e520, + 0x00ec220c, + 0x82198210, + 0x83378502, + 0x0a514327, + 0xe6ff0622, + 0x83095f4b, + 0x053f4537, + 0x42ddff21, + 0x3e820d35, + 0xff210284, + 0x8b0684ee, + 0x45032004, + 0xff2107df, + 0x528582f6, + 0x24830a19, + 0x00b7ff27, + 0xffb4ff00, + 0x830783ec, + 0x4303a50f, + 0xec200895, + 0x20089f58, + 0x204782f2, + 0x8e3d83db, + 0x941283bf, + 0xbfff2703, + 0x0000b0ff, + 0x0382c9ff, + 0xe182f620, + 0x9438bf55, + 0x21148e5c, + 0xff5bebff, + 0x4bca2006, + 0xff21095f, + 0x200182f2, + 0x23c985ca, + 0xf0ffe5ff, + 0x8e299553, + 0x850e965c, + 0x821c8b71, + 0x0cdb4385, + 0x0b831b8b, + 0x831ca743, + 0x27039020, + 0xecffe9ff, + 0xd1ff8fff, + 0xbf20bf82, + 0xe8204184, + 0x220c1f5b, + 0x46e8ffec, + 0xff221517, + 0x2f83fff6, + 0x2d870420, + 0x82fdff21, + 0x85f62011, + 0xfcff237f, + 0x3595cbff, + 0x03896183, + 0xffbfff23, + 0x200d85ab, + 0x06a16fff, + 0x7f833982, + 0xe1fff024, + 0x7982f2ff, + 0x3b4feb82, + 0x2b1d6005, + 0x05875185, + 0x480b5d46, + 0x298715a5, + 0xff2107df, + 0x4061dffa, + 0x4145935f, + 0x45c2a52e, + 0x17220533, + 0x2e821300, + 0x82127345, + 0x20029915, + 0xf51a990f, + 0x05215319, + 0x221c9755, + 0x4307000e, + 0xd1470b01, + 0x82e32008, + 0xfff62215, + 0x200582f6, + 0x08ed4ed8, + 0x86154351, + 0x20069415, + 0x203b8226, + 0x0bf543dc, + 0xff212589, + 0x201782f2, + 0x0b1146e6, + 0x0a201182, + 0x8908114e, + 0x2109a628, + 0xed82e2ff, + 0xdfffcf28, + 0xcfffd5ff, + 0x5b82ecff, + 0xbf568f20, + 0x46a92006, + 0x0a24068b, + 0x0a000600, + 0x27414c9b, + 0x84389b1c, + 0xfcff211b, + 0xc9843f8d, + 0xdcffe324, + 0x1e84d2ff, + 0x205d4518, + 0x00212585, + 0x0b5d5600, + 0x82eeff21, + 0x85ed200f, + 0xc1ff2119, + 0xab22db82, + 0x1182c5ff, + 0xe6ffab22, + 0x88200182, + 0xec221d84, + 0x118296ff, + 0x2385c020, + 0xff000027, + 0xffd8ffb7, + 0x300782dc, + 0xffbfffa7, + 0xffd5ffc5, + 0xffa0ffc2, + 0xffd9ffbb, + 0x223d82ec, + 0x82e8ffc4, + 0xfff32105, + 0x822a8b61, + 0x88a32049, + 0x82d3205b, + 0x00822247, + 0x06b35400, + 0x0982d820, + 0xd1ffb722, + 0xd9200582, + 0xff252183, + 0xffbeffcb, + 0x230983a7, + 0xd2ff0000, + 0xd3200182, + 0x05910b85, + 0x82079945, + 0x57f22027, + 0x29910b7b, + 0x14201182, + 0x8207594f, + 0x2002830b, + 0x20318204, + 0x06f74ffc, + 0x02820682, + 0x03821120, + 0xbf640282, + 0x0cc95b2d, + 0x3e820620, + 0x03823720, + 0xf3460290, + 0x8c14200a, + 0x1c47421c, + 0x9984298c, + 0xff224785, + 0x155100f2, + 0x26058505, + 0xfffcff00, + 0x822100f6, + 0x0ea35401, + 0x02c03282, + 0x8325ad47, + 0x53298625, + 0x8b9a1901, + 0x4a05bf5d, + 0xff21072f, + 0x41df92f9, + 0x07280fbf, + 0xf9ff0000, + 0x2800efff, + 0x07262b82, + 0xf6ff0700, + 0x35852400, + 0xf6228b84, + 0x5d4a0600, + 0x58799a0a, + 0x00210955, + 0x22268204, + 0x82430007, + 0x4a029005, + 0x14200a85, + 0x04822584, + 0x14210284, + 0x84878200, + 0x8d048509, + 0xff00230d, + 0x118200f8, + 0xf224dd82, + 0xe5ffe8ff, + 0x8507d94e, + 0xd105402a, + 0x20085f67, + 0x092d57c3, + 0xfff9ff27, + 0xffc4fffc, + 0x21ed83dc, + 0x0182e5ff, + 0x42225f67, + 0x51832573, + 0x67000021, + 0x0b8505d1, + 0xff210585, + 0x0aad41f1, + 0x058c1285, + 0x38855dab, + 0xfff2ff29, + 0xffbdffdf, + 0x4af6ffd1, + 0x434b05ed, + 0x17e7500f, + 0xffefff23, + 0x8c4185be, + 0x83f5209f, + 0x1853820d, + 0x21240148, + 0x614bc4ff, + 0x213f8311, + 0xb14f0000, + 0x85098a08, + 0x0805ae19, + 0x1d000293, + 0xb103b103, + 0xb4030000, + 0x0100b703, + 0xc303b903, + 0xc5030500, + 0x1000d803, + 0xdf03da03, + 0xe1032400, + 0x2a00e103, + 0xe703e303, + 0xe9032b00, + 0x3000ec03, + 0xf003ef03, + 0xf2033400, + 0x3600fa03, + 0xfe03fd03, + 0x00043f00, + 0x41000304, + 0x0f040504, + 0x11044500, + 0x50002204, + 0x2b042704, + 0x2d046200, + 0x67003304, + 0x38043504, + 0x3b046e00, + 0x72003e04, + 0x46044004, + 0xd6057600, + 0x7d00d605, + 0xdc05d905, + 0xde057e00, + 0x8200e805, + 0xfd05ea05, + 0xff058d00, + 0xa1000406, + 0x3d008206, + 0x0806a700, + 0xa8000c06, + 0x11060e06, + 0x1406ad00, + 0xb1001506, + 0x1f061706, + 0x0200b300, + 0xb1849700, + 0xb1820220, + 0x1300b426, + 0xb503b503, + 0xb6269382, + 0x1900b603, + 0xc382b703, + 0xc3822120, + 0xb182ba20, + 0xbb03bb28, + 0xbc032100, + 0x0b82be03, + 0xbf03bf22, + 0xc022c982, + 0x0b82c003, + 0xc103c128, + 0xc2030d00, + 0xe182c203, + 0xed82c320, + 0xc5032d30, + 0x0b00c503, + 0xc603c603, + 0xc7031600, + 0x4d82c703, + 0xc903c822, + 0xca222982, + 0x0b82ca03, + 0xcb03cb28, + 0xcc032700, + 0x1182cc03, + 0xcd03cd22, + 0xce220b82, + 0x4d82cf03, + 0xd003d022, + 0xd1221182, + 0x7782d203, + 0xd303d328, + 0xd4030600, + 0x8f82d403, + 0xd503d522, + 0xd6285982, + 0x0900d603, + 0xd803d703, + 0xda282382, + 0x1e00da03, + 0xdc03db03, + 0xdd283b82, + 0x3300dd03, + 0xde03de03, + 0xdf229b82, + 0x1d82df03, + 0x20075f41, + 0x285382e3, + 0x00e403e4, + 0x03e5031c, + 0x224782e6, + 0x82e703e7, + 0x03e92223, + 0x220582ea, + 0x82eb03eb, + 0x03ec2289, + 0x225982ec, + 0x82ef03ef, + 0x03f022a7, + 0x221182f0, + 0x82f203f2, + 0x03f32241, + 0x282382f3, + 0x00f403f4, + 0x03f50302, + 0x228f82f6, + 0x82f703f7, + 0x03f8224d, + 0x221d82f8, + 0x82fa03f9, + 0xfe26080b, + 0x0300fe03, + 0x00040004, + 0x01041100, + 0x2e000104, + 0x02040204, + 0x03041700, + 0x1f000304, + 0x06040504, + 0x07042800, + 0x0b820704, + 0x0a040822, + 0x0b280b82, + 0x22000b04, + 0x0c040c04, + 0x0d220b82, + 0x0b820d04, + 0x0e040e2e, + 0x0f040e00, + 0x2b000f04, + 0x11041104, + 0x12281182, + 0x14001204, + 0x13041304, + 0x14224d82, + 0x29821504, + 0x16041622, + 0x17280b82, + 0x25001704, + 0x18041804, + 0x19221182, + 0x0b821904, + 0x1b041a22, + 0x1c222f82, + 0x11821c04, + 0x1e041d22, + 0x1f287782, + 0x04001f04, + 0x20042004, + 0x21228f82, + 0x59822104, + 0x22042228, + 0x27040700, + 0x2f822804, + 0x29042928, + 0x2a043100, + 0x8f822a04, + 0x2b042b22, + 0x2d223582, + 0x05822d04, + 0x2e042e22, + 0x2f221d82, + 0x4d822f04, + 0x30043028, + 0x31041a00, + 0x41823204, + 0x33043322, + 0x35222982, + 0x05823604, + 0x37043722, + 0x38228382, + 0x53823804, + 0x3b043b22, + 0x3c22a182, + 0x11823c04, + 0x3d043d22, + 0x3e225382, + 0x23823e04, + 0x42044122, + 0x43228382, + 0x47824304, + 0x44044422, + 0x45265982, + 0x22004604, + 0x9b18d605, + 0x123c08c5, + 0xda05da05, + 0xdb052f00, + 0x1800db05, + 0xdc05dc05, + 0xde052000, + 0x2900df05, + 0xe005e005, + 0xe1220b82, + 0x0b82e305, + 0xe405e428, + 0xe5052300, + 0x0b82e505, + 0x05e62008, + 0x050c00e6, + 0x00e705e7, + 0x05e8050f, + 0x052c00e8, + 0x00ea05ea, + 0x05eb050a, + 0x051500eb, + 0x82ec05ec, + 0x05ed224d, + 0x222982ee, + 0x82ef05ef, + 0x05f0280b, + 0x052600f0, + 0x82f105f1, + 0x05f22211, + 0x220b82f2, + 0x82f405f3, + 0x05f5224d, + 0x221182f5, + 0x82f705f6, + 0x05f82e77, + 0x050500f8, + 0x00f905f9, + 0x05fa0512, + 0x285982fa, + 0x00fb05fb, + 0x05fc0508, + 0x3d2382fd, + 0x00ff05ff, + 0x0600061d, + 0x06260001, + 0x00020602, + 0x06030632, + 0x06200003, + 0x00040604, + 0x00820629, + 0x08340582, + 0x23000806, + 0x09060906, + 0x0a061b00, + 0x12000b06, + 0x0c060c06, + 0x0e222382, + 0x05820f06, + 0x10061031, + 0x11062f00, + 0x0f001106, + 0x14061406, + 0x82061500, + 0x22118201, + 0x82170617, + 0x0618223b, + 0x2e238218, + 0x00190619, + 0x061a0601, + 0x0618001b, + 0x821c061c, + 0x061d224d, + 0x2a1d821d, + 0x001f061e, + 0x01020023, + 0x8202001a, + 0x00682201, + 0x22018204, + 0x82080030, + 0x00302201, + 0x2201820b, + 0x8210006a, + 0x00302201, + 0x22018212, + 0x82150030, + 0x00332201, + 0x22018216, + 0x82170035, + 0x00382201, + 0x22018219, + 0x821a003b, + 0x003d2201, + 0x2201821b, + 0x8221006b, + 0x002e2201, + 0x22018224, + 0x822f006f, + 0x00322201, + 0x22018231, + 0x82340036, + 0x003c3001, + 0x004d0036, + 0x00540068, + 0x00300058, + 0x827b0073, + 0x008e2805, + 0x006a008e, + 0x82bf00a5, + 0xd032080b, + 0x3300d700, + 0xef00d800, + 0xf4003500, + 0x3d00fb00, + 0x0001fc00, + 0x42016b00, + 0x2e004201, + 0x5b015001, + 0xa1016f00, + 0x3200a801, + 0xcd01c601, + 0xd7013c00, + 0x1182d701, + 0x01ed2008, + 0x023c00ed, + 0x00120211, + 0x02190232, + 0x02360019, + 0x00290225, + 0x022a022e, + 0x02690037, + 0x82640264, + 0x6520080b, + 0x6f006502, + 0x8e038e03, + 0xb1036100, + 0x1c00b103, + 0xb403b203, + 0xb5036e00, + 0x2000b503, + 0xb603b603, + 0xb72e0b82, + 0x4f00b703, + 0xb803b803, + 0xb9034e00, + 0x1182bb03, + 0xbc03bc28, + 0xbd032500, + 0x0b82be03, + 0xbf03bf28, + 0xc0032a00, + 0x0b82c103, + 0xc203c222, + 0xc33a0b82, + 0x0300c303, + 0xc403c403, + 0xc5034c00, + 0x2300c503, + 0xc603c603, + 0xc7032700, + 0x2382c703, + 0xc803c828, + 0xc9031e00, + 0x0b82ca03, + 0xcb03cb22, + 0xcc222982, + 0x0b82cd03, + 0xce03ce22, + 0xcf225f82, + 0x0b82cf03, + 0xd003d028, + 0xd1034d00, + 0x0b82d203, + 0xd303d322, + 0xd4222382, + 0x0b82d403, + 0xd503d522, + 0xd6285f82, + 0x5500d603, + 0xd803d703, + 0xda281182, + 0x4b00da03, + 0xdb03db03, + 0xdc228f82, + 0x1182dc03, + 0xdd03dd28, + 0xde030300, + 0x0b82df03, + 0xe003e022, + 0xe1228382, + 0x0b82e103, + 0xe203e228, + 0xe3032c00, + 0x4182e303, + 0xe403e428, + 0xe5030100, + 0x1782e503, + 0xe703e722, + 0xe822dd82, + 0x7d82e803, + 0xe903e922, + 0xea221182, + 0x4182ea03, + 0xeb03eb22, + 0xec220b82, + 0x2f82ec03, + 0xed03ed28, + 0xef035100, + 0xc582ef03, + 0xf003f022, + 0xf122bf82, + 0x1d82f203, + 0xf303f322, + 0xf42e3b82, + 0x1c00f403, + 0xf503f503, + 0xf6036d00, + 0x1782f603, + 0xf803f822, + 0xf9220582, + 0x3b82fa03, + 0xfc03fb22, + 0x23088382, + 0x00fd03fd, + 0x03fe031b, + 0x034a00fe, + 0x000004ff, + 0x0401045f, + 0x041f0001, + 0x00020402, + 0x04030459, + 0x04450003, + 0x00250082, + 0x0405042d, + 0x281d8207, + 0x00080408, + 0x04090424, + 0x220b820a, + 0x820b040b, + 0x040c2223, + 0x280b820c, + 0x000d040d, + 0x040e045e, + 0x2811820e, + 0x000f040f, + 0x04100402, + 0x06b34410, + 0x1204592a, + 0x26001204, + 0x13041304, + 0x14282982, + 0x1d001404, + 0x16041504, + 0x17220b82, + 0x29821704, + 0x19041822, + 0x1a280b82, + 0x22001a04, + 0x1b041b04, + 0x1c280b82, + 0x44001c04, + 0x1e041d04, + 0x1f284d82, + 0x46001f04, + 0x20042004, + 0x21221782, + 0x11822104, + 0x22042234, + 0x23042100, + 0x66002404, + 0x26042604, + 0x27044700, + 0x95822704, + 0x28042822, + 0x29222382, + 0x2f822904, + 0x2b042a22, + 0x2c220b82, + 0x83822c04, + 0x2d042d22, + 0x2e280b82, + 0x04002e04, + 0x2f042f04, + 0x30284182, + 0x28003004, + 0x31043104, + 0x32281782, + 0x5d003204, + 0x33043304, + 0x3422e982, + 0xe9823404, + 0x35043522, + 0x36221782, + 0x9b823604, + 0x37043722, + 0x38220b82, + 0x35823804, + 0x3a043922, + 0x3b223582, + 0xcb823b04, + 0x3c043c22, + 0x3e22c582, + 0x35823e04, + 0x41044028, + 0x42041b00, + 0x23824204, + 0x43044328, + 0x44045b00, + 0x35824404, + 0x46044522, + 0x47221182, + 0x83824804, + 0x8304822e, + 0x84041400, + 0x13008504, + 0x86048604, + 0x20080b82, + 0x00870487, + 0x04890462, + 0x04050089, + 0x008c048b, + 0x048d0440, + 0x043f008d, + 0x008e048e, + 0x048f0406, + 0x220b828f, + 0x82900490, + 0x0491220b, + 0x2e2f8292, + 0x00930493, + 0x04940453, + 0x04500094, + 0x82950495, + 0x0496220b, + 0x280b8296, + 0x00990497, + 0x049c0452, + 0x2e05829d, + 0x009e049e, + 0x04a40416, + 0x045700a4, + 0x82a604a6, + 0x04a82205, + 0x340582a8, + 0x00a904a9, + 0x04ab045a, + 0x044100ab, + 0x00ad04ad, + 0x04b30407, + 0x227d82b3, + 0x82b404b4, + 0x04b5227d, + 0x220b82b5, + 0x82b704b6, + 0x04b9220b, + 0x222f82b9, + 0x82bb04bb, + 0x04bd2205, + 0x080582bd, + 0xc404c420, + 0xc5044200, + 0x4300c504, + 0xcc04cc04, + 0xcd046f00, + 0x6300cd04, + 0xcf04cf04, + 0xd3042f00, + 0x0582d304, + 0xd604d628, + 0xdb046400, + 0x0b82db04, + 0xdd04dd22, + 0x38080582, + 0x00df04df, + 0x04e00431, + 0x046500e0, + 0x00e104e1, + 0x04e20434, + 0x043700e2, + 0x00e304e3, + 0x04e40439, + 0x043a00e4, + 0x00e604e6, + 0x04e7043e, + 0x056300fe, + 0x00090505, + 0x0524052f, + 0x2805822c, + 0x003f053f, + 0x05560564, + 0x080b8270, + 0x80057932, + 0x82053100, + 0x65008905, + 0xa1058a05, + 0xa2053400, + 0x3900a505, + 0xb205ae05, + 0xd6053e00, + 0x0800d605, + 0xd905d705, + 0xda056000, + 0x0a00da05, + 0xdb05db05, + 0xdc2e0b82, + 0x5600dc05, + 0xdd05dd05, + 0xde054900, + 0x1182e005, + 0xe105e128, + 0xe2050d00, + 0x0b82e305, + 0xe405e428, + 0xe5052900, + 0x0b82e605, + 0xe705e722, + 0xe83a0b82, + 0x1100e805, + 0xe905e905, + 0xea054800, + 0x0c00ea05, + 0xeb05eb05, + 0xec050e00, + 0x2382ec05, + 0xed05ed28, + 0xee050900, + 0x0b82ef05, + 0xf005f022, + 0xf1222982, + 0x0b82f205, + 0xf305f322, + 0xf4225f82, + 0x0b82f405, + 0xf505f528, + 0xf6055800, + 0x0b82f705, + 0xf805f822, + 0xf9222382, + 0x0b82f905, + 0xfa05fa22, + 0xfb285f82, + 0x0b00fb05, + 0xfd05fc05, + 0xff3a1182, + 0x1000ff05, + 0x00060006, + 0x01060d00, + 0x60000106, + 0x02060206, + 0x03061100, + 0x0b820406, + 0x05060525, + 0x82064800, + 0x340b8200, + 0x00070607, + 0x06080612, + 0x06290008, + 0x00090609, + 0x060a060f, + 0x2e17820a, + 0x000c060c, + 0x060d0656, + 0x0649000d, + 0x820e060e, + 0x060f2211, + 0x2241820f, + 0x82100610, + 0x0611220b, + 0x342f8211, + 0x00120612, + 0x06140615, + 0x060e0014, + 0x00150615, + 0x06160609, + 0x221d8217, + 0x82180618, + 0x06192e3b, + 0x06080019, + 0x001a061a, + 0x061b066c, + 0x2217821b, + 0x821d061d, + 0x061e2205, + 0x223b821f, + 0x82210620, + 0x2f500883, + 0x17002f06, + 0x31063106, + 0x33061a00, + 0x18003306, + 0x34063406, + 0x37061900, + 0x54003706, + 0x39063906, + 0x3b065c00, + 0x67003b06, + 0x25072507, + 0x26070600, + 0x3f002607, + 0xb507b407, + 0x02002e00, + 0x04001030, + 0x34310000, + 0x30007833, + 0x00008000, + 0xf9ffecff, + 0xf2220184, + 0x0182fcff, + 0xd8fff622, + 0xec240582, + 0xf2fff5ff, + 0xdd200382, + 0xf5201384, + 0xc5560582, + 0x2e634b1c, + 0x4ca82e40, + 0xff210b6d, + 0x200182f2, + 0x210382de, + 0x0583fffc, + 0xfcff9c24, + 0x0382f6ff, + 0x0300e222, + 0x4005916a, + 0xa88ea8d4, + 0xffe8ff27, + 0xffefffc4, + 0x20c582b0, + 0x271a83e5, + 0xd8ff88ff, + 0xd1ff0000, + 0xe524e582, + 0xe5ffa9ff, + 0x076f4718, + 0xe8240982, + 0xd4ffc0ff, + 0xc0201b82, + 0x8d200382, + 0xec200382, + 0xe5221382, + 0x2f84f6ff, + 0x3f82d820, + 0x0382ec20, + 0x1400c424, + 0x0782dbff, + 0xe2262b83, + 0xfcfff0ff, + 0x6182e2ff, + 0x0982f220, + 0x83ffec21, + 0x82fc2001, + 0x00e8220d, + 0x2201820d, + 0x8210000a, + 0x22d55c11, + 0x03dd9583, + 0x89076b51, + 0xfcff2165, + 0x8a273151, + 0x85f62033, + 0x09714f0b, + 0x2208155c, + 0x53fcffe8, + 0x238507d1, + 0x89a50540, + 0x55af83c9, + 0x35500989, + 0xf2ff2305, + 0x13860000, + 0x1f830920, + 0xcb5503a1, + 0x26418211, + 0xff0400fc, + 0x41f6fffa, + 0x4fa11183, + 0x818221cb, + 0xfafffc22, + 0x21059557, + 0x8f92e8ff, + 0xf0ff0a22, + 0x04206f82, + 0x02820382, + 0x9b79ff20, + 0x0b214106, + 0xe9223382, + 0x1c82fdff, + 0xcb830020, + 0xd3870983, + 0x536c4d85, + 0x83ec2006, + 0x82002021, + 0xecff2123, + 0xec21f782, + 0x08f55400, + 0x6de9ff21, + 0x27850dab, + 0x21890540, + 0xb582d4ff, + 0x2006af43, + 0x21c582ff, + 0x0f82d8ff, + 0x9f82e820, + 0x41000421, + 0x00200615, + 0x795d009e, + 0x29248305, + 0xd1ffebff, + 0x0000c9ff, + 0x0d84f0ff, + 0x5208895d, + 0x3f83318f, + 0xd98403cb, + 0xf146ab20, + 0x0b8d5c13, + 0x795d2584, + 0x0000250c, + 0xcbfff6ff, + 0x21050941, + 0x2942f2ff, + 0x22098209, + 0x82ecff00, + 0x82f6204f, + 0x200783f1, + 0x241184ef, + 0xffd3ffdd, + 0x0d6344cb, + 0x00c4ff25, + 0x83fcff00, + 0x40218305, + 0xff27f903, + 0x00f5fffc, + 0x5cf5ff06, + 0x56415489, + 0xad14202d, + 0x222dad2e, + 0x4200d1ff, + 0x658205ff, + 0x67e5ff21, + 0x0a301423, + 0xfcff0300, + 0xe2ffecff, + 0xf6ffc1ff, + 0xe3fffdff, + 0xad0b4118, + 0x25190f41, + 0xbdffe6ff, + 0x4574c8ff, + 0xa2ff210f, + 0x8207cb78, + 0x05114607, + 0x23068141, + 0x0d00c9ff, + 0x2c05cf69, + 0x0400faff, + 0xf9ff0600, + 0x1400d2ff, + 0x232382ff, + 0xd8fff8ff, + 0x99813544, + 0x641999e9, + 0x27890db9, + 0xfff2ff23, + 0x84ff82ec, + 0x9b158905, + 0x15777009, + 0x1ba5319b, + 0x9c0bdd46, + 0x26ff4731, + 0xf147438d, + 0x41042008, + 0x208d08ed, + 0x20097f5c, + 0x202184f2, + 0x401082fc, + 0xe541c802, + 0x0cb16c06, + 0x4a05ff47, + 0xf6200835, + 0x230a1b48, + 0x000600e8, + 0xed420086, + 0x05814805, + 0x15414582, + 0xfcff2106, + 0xfa200182, + 0x214db362, + 0x0967f9ff, + 0x947a8607, + 0x08c74106, + 0x149d1d94, + 0x200e0147, + 0x252d85e9, + 0xf6ffecff, + 0x6f47e6ff, + 0x0ab7750c, + 0x0c0d4018, + 0x3183de20, + 0xfff2ff25, + 0x430000e6, + 0xff23054f, + 0x82f0ffef, + 0x2141820f, + 0x0b840700, + 0x8d3c594a, + 0x936b839f, + 0x097d5a03, + 0x13971d93, + 0x62fcff21, + 0x69680b23, + 0x202c8d06, + 0x260e8303, + 0xecffebff, + 0x82ff0000, + 0x0903422d, + 0x934f1784, + 0x23db4e62, + 0x8317c744, + 0x250399a3, + 0xf9fff9ff, + 0xf5460000, + 0xf6ff210d, + 0xf6221182, + 0x7582f6ff, + 0x0382fc20, + 0x2569f020, + 0xffec2408, + 0x860500ec, + 0x830320fd, + 0xe1ff2253, + 0x41fd82ff, + 0x895c0d77, + 0x0b354805, + 0xe8206382, + 0x00212d83, + 0x0d39412f, + 0x04401384, + 0x07194498, + 0x85239167, + 0xfcff25c4, + 0x0000f6ff, + 0x8517795d, + 0x91054023, + 0x9511ad5e, + 0xefff23a3, + 0xdd82e2ff, + 0x47102d6a, + 0xa74a87f5, + 0xc8ff2335, + 0xd582c0ff, + 0x21106772, + 0xeb85c9ff, + 0x44f6ff21, + 0xc7200cff, + 0x210d1b41, + 0x3d84ebff, + 0xf342e820, + 0x411b8505, + 0x2b4513ff, + 0x85c3200a, + 0x4105af25, + 0xff257165, + 0xfff9fff5, + 0x200382fc, + 0x6daba7f1, + 0x0022092d, + 0x2b48ff00, + 0xff69180a, + 0x0db3780d, + 0xff215ba5, + 0x094141ec, + 0x23a33199, + 0x59413d91, + 0x890d8d0d, + 0x08fb452d, + 0x09861289, + 0x3c8675b5, + 0x279a0640, + 0xe8ffe1ff, + 0xe8ff0000, + 0x1b510582, + 0x11094506, + 0x200d7346, + 0x0a0947ff, + 0x82f6ff21, + 0x41f0203b, + 0xff21051b, + 0x204582f6, + 0x20ea82f0, + 0x20038214, + 0x200d8200, + 0x07cd54f6, + 0x03ff0f83, + 0x421f5b48, + 0xb7e91711, + 0x45f1ff21, + 0x7fdf1377, + 0xfff9ff23, + 0x647782d8, + 0x858b1eb9, + 0x4406ff46, + 0x4182082f, + 0x1f83fd20, + 0x83359945, + 0x21038539, + 0xa149a1ff, + 0x9014850c, + 0xc8ff2105, + 0x07b94518, + 0x10961a90, + 0xf9229f82, + 0x89771400, + 0x84229605, + 0xc4ff2116, + 0x42091154, + 0x4d55112d, + 0xa230840d, + 0x18538204, + 0x23285142, + 0xb7ff7fff, + 0x21974118, + 0x4218ff20, + 0x9e9128cb, + 0x41d8ff21, + 0xff251161, + 0xffd3ffe2, + 0x220382c1, + 0x92a3ffd6, + 0xffc42231, + 0x200182ef, + 0x251983b2, + 0x0000dcff, + 0x0382d2ff, + 0x83ffca24, + 0xed41b6ff, + 0x97ff2805, + 0xd8fff0ff, + 0x82ffabff, + 0x220b8221, + 0x82ccffdc, + 0xff432429, + 0x821b00df, + 0x822f8227, + 0xff00220d, + 0xa20583c5, + 0x0ec16803, + 0x22aa31a2, + 0x8e08c344, + 0xfcff2165, + 0xf6200184, + 0x9711f141, + 0x05ff445c, + 0x8808174e, + 0xf7ff2126, + 0x08b50a88, + 0xe6ff0d22, + 0x8d135548, + 0x18ff204c, + 0x2532e770, + 0x0000f4ff, + 0x0385e6ff, + 0x48090743, + 0xff2505cd, + 0xffebfff9, + 0x690382fc, + 0xb7450a1d, + 0x829d8517, + 0x82fc2031, + 0x83e7204b, + 0xeeff2197, + 0x2109856c, + 0x1985eeff, + 0x03831783, + 0x83052141, + 0x2003a609, + 0x25834114, + 0xa60ba949, + 0x84268659, + 0x059d465f, + 0x860a8578, + 0x2206821c, + 0x82fffcff, + 0xf2ff2117, + 0x0b4d5218, + 0x02841682, + 0x2135dd44, + 0x0541f5ff, + 0x6753182b, + 0x09a34423, + 0x04a49684, + 0xfff9ff27, + 0x00eeffee, + 0x07c76f00, + 0xff213485, + 0x241182d8, + 0xfff0ffeb, + 0x24f782e5, + 0x00dfffe5, + 0x08415914, + 0x0982ef20, + 0x2005f94d, + 0x822b83f6, + 0x00f22421, + 0x48ecff09, + 0x0d4e0b19, + 0x0eff4d05, + 0xed84f620, + 0x33831b20, + 0x072003b2, + 0xb2093b76, + 0x21329e3d, + 0x5d86a3ff, + 0x200fff43, + 0x06ff42ef, + 0x409ee120, + 0xf3851e88, + 0x83d1ff21, + 0x84ef8310, + 0x210c82f3, + 0x1954f9ff, + 0x08515205, + 0x472e4153, + 0xf12078ff, + 0x2085ff47, + 0x4400dc00, + 0x8283255b, + 0x49e6ff21, + 0x79837387, + 0x33427782, + 0x2b4f4420, + 0x05855385, + 0x431fbf44, + 0xe14b0cc9, + 0x08075509, + 0xff204583, + 0x8c1c0353, + 0x83032099, + 0x8703402f, + 0x00ecff23, + 0x41ff9f00, + 0xff210d7b, + 0x053770f9, + 0x3b4ec1c5, + 0x05514425, + 0x914171a0, + 0x842da00c, + 0xecff2120, + 0x09cb5218, + 0x04881084, + 0x41dfff21, + 0x17860cb5, + 0x096f4418, + 0xfff9ff23, + 0x451483e1, + 0xff2305f9, + 0x84dbfff2, + 0xfffc260d, + 0xffddffeb, + 0x398947de, + 0x038f4583, + 0x8150ff20, + 0xc5398f28, + 0xecff210f, + 0xeb548189, + 0xab5fb90d, + 0xa2ff2147, + 0x91119d4b, + 0x0dc35579, + 0x119b1f91, + 0x8b0bbf47, + 0x199f4227, + 0xffd2ff25, + 0x890000f2, + 0x05014437, + 0xffe6ff25, + 0x83e5ffc0, + 0xe6ff2115, + 0xec241d82, + 0xfaffe2ff, + 0x37450782, + 0x82282007, + 0x8210205b, + 0x07235803, + 0x83104b54, + 0x2003911b, + 0xe55418ff, + 0x8b1b9108, + 0xf3ff2111, + 0x0bb50d8b, + 0x2014f542, + 0x977318dc, + 0x45ff430b, + 0x5d544585, + 0x21b1970d, + 0xa34690ff, + 0x83541807, + 0x09d5611b, + 0x17994797, + 0x09635518, + 0xff232389, + 0x820600f2, + 0x4a03820d, + 0x0422081d, + 0x254ce8ff, + 0xceff2107, + 0x210c1755, + 0x094efff6, + 0xffcf2805, + 0xffd1ffc7, + 0x52efffd8, + 0xf020063b, + 0x52184182, + 0xab4212a3, + 0x832e200c, + 0x42039b23, + 0x358c1985, + 0x2033ff44, + 0x05b35af4, + 0x0026478c, + 0x0000e7ff, + 0xc382e3ff, + 0x0782ef20, + 0xa943ef20, + 0x55ff200b, + 0x29420aff, + 0xd2ff210b, + 0xe6202982, + 0xa94da785, + 0xa16d8d21, + 0xe5ff210d, + 0xa123a546, + 0x48219547, + 0xff210bff, + 0x43bd95ec, + 0x878207dd, + 0xefffec22, + 0xf0200582, + 0x3d4191bf, + 0xf6ff2105, + 0x8b7e7d84, + 0x63431828, + 0xbcd49512, + 0x5cff2015, + 0x448806cd, + 0x42000321, + 0x0624055b, + 0x0d00e8ff, + 0xef20b988, + 0x0f241f86, + 0xecff0000, + 0x2208a143, + 0x44ebffe8, + 0x5d864521, + 0x102006f9, + 0x14207ab2, + 0x8207e145, + 0x6302a107, + 0x6d432ad7, + 0xa658a10b, + 0x28774221, + 0x26404fa6, + 0x5eff20cc, + 0x0f510519, + 0x21e89714, + 0x4b5becff, + 0x994b180b, + 0x26e74708, + 0x17835597, + 0x83058144, + 0x2903f109, + 0x0000faff, + 0xe7ffdfff, + 0xf148f3ff, + 0x2187870b, + 0x0987e3ff, + 0x216207ab, + 0x06b34807, + 0x00029908, + 0x02680230, + 0x0200006c, + 0x006f026f, + 0x02710205, + 0x02060072, + 0x00760276, + 0x02780208, + 0x02090078, + 0x0081027c, + 0x0285020a, + 0x02100085, + 0x008d0288, + 0x028f0211, + 0x0217008f, + 0x00950291, + 0x02970218, + 0x021d0097, + 0x009a0299, + 0x029d021e, + 0x0220009e, + 0x00a202a0, + 0x02a40222, + 0x022500aa, + 0x00ae02ad, + 0x02b0022c, + 0x022e00c3, + 0x00e202da, + 0x03eb0242, + 0x034b0049, + 0x008a035a, + 0x038d03aa, + 0x03db008d, + 0x00970397, + 0x03b203dc, + 0x03dd00b3, + 0x00b803b8, + 0x03c403df, + 0x03e000c4, + 0x003a0182, + 0x03e203e1, + 0x03e200e2, + 0x00e803e8, + 0x03fb03e3, + 0x03e400fc, + 0x00ff03ff, + 0x008204e6, + 0xe7009908, + 0x10041004, + 0x2c04e800, + 0xe9002c04, + 0x34043404, + 0x4704ea00, + 0xeb004804, + 0xbd05b905, + 0xc005ed00, + 0xf200c005, + 0xc305c205, + 0xc705f300, + 0xf500c705, + 0xca05c905, + 0xcd05f600, + 0xf800d005, + 0xd805d705, + 0xdd05fc00, + 0xfe00dd05, + 0xe905e905, + 0x0506ff00, + 0x00010506, + 0x07060706, + 0x0d060101, + 0x02010d06, + 0x21062006, + 0x02000301, + 0x68026000, + 0x0a006802, + 0x69026902, + 0x6a020d00, + 0x1a006a02, + 0x6b026b02, + 0x6c021300, + 0x16006c02, + 0x6f026f02, + 0x71022b00, + 0x1e007102, + 0x72027202, + 0x76222982, + 0x11827602, + 0x02782008, + 0x02280078, + 0x007c027c, + 0x027d0224, + 0x0210007d, + 0x007e027e, + 0x027f0226, + 0x0222007f, + 0x82800280, + 0x02812229, + 0x22418281, + 0x82850285, + 0x0288222f, + 0x3c178288, + 0x00890289, + 0x028a0208, + 0x020b008a, + 0x008b028b, + 0x028c0218, + 0x0211008c, + 0x008d028d, + 0x087d4114, + 0x1b009132, + 0x92029202, + 0x93021c00, + 0x1f009302, + 0x94029402, + 0x952e1182, + 0x20009502, + 0x97029702, + 0x99022900, + 0x05829902, + 0x9a029a28, + 0x9d022e00, + 0x0b829d02, + 0x9e029e28, + 0xa0020e00, + 0x0b82a002, + 0xa102a128, + 0xa2022d00, + 0x6582a202, + 0xa402a422, + 0xa5221182, + 0x7782a502, + 0xa602a622, + 0xa7286582, + 0x1700a702, + 0xa902a802, + 0xaa225382, + 0x1d82aa02, + 0xad02ad22, + 0xae220582, + 0x1182ae02, + 0xbb02b022, + 0xbc22b982, + 0xb982c302, + 0xe102da22, + 0xe222b982, + 0xe982e202, + 0xf402eb22, + 0xf53abf82, + 0x1b000f03, + 0x1c031003, + 0x1d030800, + 0x14002403, + 0x2f032503, + 0x30031700, + 0x17823f03, + 0x49034028, + 0x5a032900, + 0x05826403, + 0x70036522, + 0x71222382, + 0x1d827c03, + 0x88037d22, + 0x89281182, + 0x1c008903, + 0x8a038a03, + 0x8d280b82, + 0x2c008d03, + 0x97039703, + 0xb2283582, + 0x0500b303, + 0xb803b803, + 0xc4280582, + 0x0200c403, + 0xe003e003, + 0xe2280582, + 0x0700e203, + 0xe803e803, + 0xfb221782, + 0x1182fc03, + 0xff03ff25, + 0x82040300, + 0x08058200, + 0x34043432, + 0xb9050300, + 0x0900b905, + 0xba05ba05, + 0xbb050c00, + 0x1900bb05, + 0xbc05bc05, + 0xbd051200, + 0x1500bd05, + 0xc005c005, + 0xc2052a00, + 0x1d00c205, + 0xc305c305, + 0xc7222982, + 0x1182c705, + 0x05c92c08, + 0x052700c9, + 0x00ca05ca, + 0x05cd052f, + 0x052300cd, + 0x00ce05ce, + 0x05cf050f, + 0x052500cf, + 0x00d005d0, + 0x05d70521, + 0x050400d8, + 0x82dd05dd, + 0x05e92805, + 0x060100e9, + 0x82050605, + 0x07300805, + 0x06000706, + 0x0d060d06, + 0x20060400, + 0x01002106, + 0x27010200, + 0x68026802, + 0x6b025900, + 0x65006b02, + 0x6d026d02, + 0x6f026100, + 0x5f006f02, + 0x72027202, + 0x75281782, + 0x68007502, + 0x76027602, + 0x32081182, + 0x00790279, + 0x027a0267, + 0x0254007a, + 0x007b027b, + 0x027c0260, + 0x025c007c, + 0x007d027d, + 0x027e025a, + 0x025d007e, + 0x007f027f, + 0x0280025b, + 0x027e0080, + 0x82870287, + 0x89380823, + 0x69008902, + 0x8a028a02, + 0x8b026a00, + 0x4b008b02, + 0x8c028c02, + 0x8d026b00, + 0x6c008d02, + 0x8e028e02, + 0x8f027700, + 0x6d008f02, + 0x90029002, + 0x91027000, + 0x4c009102, + 0x92029202, + 0x2c081182, + 0x00930293, + 0x02940266, + 0x027b0094, + 0x00950295, + 0x0296024d, + 0x02760096, + 0x00970297, + 0x0298026f, + 0x02630098, + 0x00990299, + 0x029a0264, + 0x2e11829a, + 0x009b029b, + 0x029c024e, + 0x0271009c, + 0x829d029d, + 0x029e2811, + 0x024a009e, + 0x829f029f, + 0x02a02211, + 0x221182a1, + 0x82a302a2, + 0x02a42265, + 0x220b82a4, + 0x82a502a5, + 0x02a6229b, + 0x228982a6, + 0x82a702a7, + 0x02a82271, + 0x287d82a8, + 0x00a902a9, + 0x02aa0273, + 0x222382aa, + 0x82ac02ab, + 0x02ad223b, + 0x220b82ad, + 0x82ae02ae, + 0x02af2217, + 0x221182af, + 0x82b902b0, + 0x02ba28e3, + 0x025900bb, + 0x82ea02e9, + 0x02f522e9, + 0x080b82f5, + 0xfd02f62c, + 0x07037e00, + 0x5b000703, + 0x1c031003, + 0x1d036900, + 0x6c002403, + 0x2f032503, + 0x30036d00, + 0x4c003103, + 0x32033203, + 0x33037300, + 0x0b823303, + 0x3f033422, + 0x40340b82, + 0x6f004703, + 0x49034803, + 0x4a036400, + 0x71005903, + 0x64035a03, + 0x65221182, + 0x41827003, + 0x7c037122, + 0x7d223b82, + 0x11828803, + 0x89038922, + 0x8a220b82, + 0x0b828b03, + 0x8c038c34, + 0x8d037b00, + 0x78008d03, + 0x8e038e03, + 0x97036e00, + 0x53829703, + 0x03b12008, + 0x032400b1, + 0x00b503b5, + 0x03b80328, + 0x033900b8, + 0x00bc03bc, + 0x03bf032d, + 0x033000bf, + 0x82c203c2, + 0xc3200805, + 0x0b00c303, + 0xc403c403, + 0xc5033500, + 0x2c00c503, + 0xc603c603, + 0xc8030600, + 0x2700c803, + 0xcb03cb03, + 0xce221d82, + 0x3b82ce03, + 0xd003d028, + 0xd3033800, + 0x1182d303, + 0xd503d522, + 0xd62e3b82, + 0x2b00d603, + 0xda03da03, + 0xdb030900, + 0x5982db03, + 0xdd03dd22, + 0xe0221d82, + 0x4d82e003, + 0xe203e228, + 0xe3034600, + 0x2982e303, + 0xe403e422, + 0x24060943, + 0x03ea0339, + 0x222382ea, + 0x82ec03ec, + 0x03ed2817, + 0x033f00ed, + 0x82ef03ef, + 0x03f02271, + 0x227182f0, + 0x82f403f4, + 0x03f922b3, + 0x221d82fa, + 0x82fc03fb, + 0x03fd3747, + 0x030100fd, + 0x00fe03fe, + 0x04ff0325, + 0x04310000, + 0x00010401, + 0x01820402, + 0x040a0028, + 0x00030403, + 0x0082040e, + 0x040d0025, + 0x82070405, + 0x0408281d, + 0x04040008, + 0x820a0409, + 0x040b220b, + 0x2223820b, + 0x820c040c, + 0x040d280b, + 0x042e000d, + 0x820e040e, + 0x040f2e11, + 0x0433000f, + 0x00100410, + 0x04110434, + 0x28118211, + 0x00120412, + 0x04130405, + 0x28298213, + 0x00140414, + 0x04150426, + 0x220b8216, + 0x82170417, + 0x04182229, + 0x280b8219, + 0x001a041a, + 0x041b0403, + 0x280b821b, + 0x001c041c, + 0x041d040c, + 0x283b821e, + 0x001f041f, + 0x04200429, + 0x22178220, + 0x82210421, + 0x04222e11, + 0x042a0022, + 0x00260426, + 0x04270408, + 0x228f8227, + 0x82280428, + 0x0429221d, + 0x22298229, + 0x822b042a, + 0x042c220b, + 0x227d822c, + 0x822d042d, + 0x042e280b, + 0x0436002e, + 0x822f042f, + 0x0430283b, + 0x042f0030, + 0x82310431, + 0x04322817, + 0x04120032, + 0x82330433, + 0x043422e3, + 0x22e38234, + 0x82350435, + 0x04362217, + 0x22958236, + 0x82370437, + 0x0438220b, + 0x22358238, + 0x823a0439, + 0x043b2235, + 0x22c5823b, + 0x823c043c, + 0x043e22bf, + 0x2835823e, + 0x00410440, + 0x04420401, + 0x28238242, + 0x00430443, + 0x04440413, + 0x22358244, + 0x82460445, + 0x04472211, + 0x2e838248, + 0x00830482, + 0x0484040f, + 0x04420085, + 0x82860486, + 0x8720080b, + 0x72008704, + 0x89048904, + 0x8b043c00, + 0x49008c04, + 0x8d048d04, + 0x8e043d00, + 0x3e008e04, + 0x8f048f04, + 0x90220b82, + 0x0b829004, + 0x92049122, + 0x932e2f82, + 0x10009304, + 0x94049404, + 0x95041100, + 0x0b829504, + 0x96049622, + 0x97280b82, + 0x22009904, + 0x9d049c04, + 0x9e2e0582, + 0x40009e04, + 0xa404a404, + 0xa6043b00, + 0x0582a604, + 0xa804a822, + 0xa9340582, + 0x1400a904, + 0xab04ab04, + 0xad046200, + 0x4700ad04, + 0xb304b304, + 0xb4227d82, + 0x7d82b404, + 0xb504b522, + 0xb6220b82, + 0x0b82b704, + 0xb904b922, + 0xbb222f82, + 0x0582bb04, + 0xbd04bd22, + 0xc42e0582, + 0x7500c404, + 0xd504d504, + 0x32053a00, + 0x05823b05, + 0x3e053d22, + 0xb9340582, + 0x4f00b905, + 0xbb05ba05, + 0xbc057400, + 0x7900bc05, + 0xbd05bd05, + 0xbe280b82, + 0x5600be05, + 0xbf05bf05, + 0xc0280b82, + 0x5e00c005, + 0xc205c105, + 0xc3220b82, + 0x2f82c305, + 0xc505c422, + 0xc6280b82, + 0x7c00c605, + 0xc705c705, + 0xc8221d82, + 0x1182c905, + 0x05ca2c08, + 0x057d00ca, + 0x00cb05cb, + 0x05cc0553, + 0x055500cc, + 0x00cd05cd, + 0x05ce0551, + 0x055000ce, + 0x00cf05cf, + 0x05d00552, + 0x057a00d0, + 0x82d105d1, + 0x05d2222f, + 0x222382d2, + 0x82d305d3, + 0x05d42253, + 0x221182d4, + 0x82d505d5, + 0x05d6341d, + 0x051500d6, + 0x00d905d7, + 0x05da0532, + 0x051700da, + 0x82db05db, + 0x05dc2e0b, + 0x052100dc, + 0x00dd05dd, + 0x05de0520, + 0x281182e0, + 0x00e105e1, + 0x05e2051a, + 0x280b82e3, + 0x00e405e4, + 0x05e5051d, + 0x220b82e6, + 0x82e705e7, + 0x05e8250b, + 0x051e00e8, + 0x2a09777a, + 0x05eb0519, + 0x051b00eb, + 0x82ec05ec, + 0xdb721823, + 0x05322409, + 0x82f005f0, + 0x05f12229, + 0x221782f2, + 0x82f305f3, + 0x05f4225f, + 0x280b82f4, + 0x00f505f5, + 0x05f6051f, + 0x220b82f7, + 0x82f805f8, + 0x05f92223, + 0x220b82f9, + 0x82fa05fa, + 0x05fb285f, + 0x051800fb, + 0x82fd05fc, + 0x05ff3a11, + 0x061c00ff, + 0x00000600, + 0x0601061a, + 0x06320001, + 0x00020602, + 0x0603061e, + 0x7a0b8204, + 0x32360977, + 0x07060706, + 0x08063700, + 0x1d000806, + 0x09060906, + 0x0a064100, + 0x23820a06, + 0x0c060c2e, + 0x0d062100, + 0x20000d06, + 0x0e060e06, + 0x0f221182, + 0x41820f06, + 0x10061022, + 0x11220b82, + 0x2f821106, + 0x1206122a, + 0x14064300, + 0x1b001406, + 0x0ae17218, + 0x18063224, + 0x3b821806, + 0x19061928, + 0x1b061500, + 0x2f821b06, + 0x1d061d22, + 0x1e220582, + 0x35821f06, + 0x0809717a, + 0x31064442, + 0x58003106, + 0x33063306, + 0x34065700, + 0x45003406, + 0x37063706, + 0x3b062300, + 0x7f003b06, + 0x25072507, + 0x26073e00, + 0x3d002607, + 0xa82a0200, + 0x00000400, + 0x362f5c2c, + 0x74002f00, + 0xf6ff0000, + 0xf0ffe5ff, + 0xe82a0582, + 0xfcff1400, + 0xbeffe8ff, + 0x0f82e2ff, + 0xecffd228, + 0xdcffc8ff, + 0x1983d8ff, + 0x82e9ff21, + 0xffec2201, + 0x241382df, + 0xfff3ffec, + 0x4dcb55c4, + 0x00e40020, + 0x82dfff21, + 0x4fe620eb, + 0x72850793, + 0x8535a761, + 0xb905403b, + 0x417b374d, + 0x17288035, + 0x0d000f00, + 0x09001c00, + 0xa6808940, + 0xf2ff2780, + 0x0000f0ff, + 0x2e83faff, + 0x41f3ff21, + 0x058605bb, + 0x1b82ec20, + 0x8b5afb20, + 0x07cd4209, + 0x220ee342, + 0x82eeffec, + 0x000e2211, + 0x20078207, + 0x672382f2, + 0x4f8306b9, + 0x4fb50340, + 0xff210b5d, + 0x22d182ec, + 0x89f6ff00, + 0xa9ff2313, + 0x1f41dcff, + 0xffe22806, + 0xffe6ffe2, + 0x180a00d2, + 0x411f0951, + 0xff236b07, + 0x82d9ffbe, + 0x82bd20a1, + 0xff2f22b7, + 0x269f82de, + 0xff0000c2, + 0x82e8ffbe, + 0x82ee20c3, + 0xffdc2209, + 0x82bd83d3, + 0x18ca20b9, + 0x23070558, + 0xd6ffc0ff, + 0xc4242782, + 0xdfffeeff, + 0xff211d83, + 0x262782af, + 0xff96ffec, + 0x82d8ffd1, + 0xffa72209, + 0x2abf8cc1, + 0xffd8ff19, + 0xffecfff0, + 0x82d2ffc7, + 0xfff22201, + 0xea1d8cd3, + 0x17415a0c, + 0xff2182a5, + 0x26e357eb, + 0x25da4ea5, + 0x0c0d6518, + 0x990ad752, + 0x0c1b63ff, + 0xda1c275f, + 0x235ae6b6, + 0xf6ffecff, + 0x0b515018, + 0xffb6ff23, + 0x069f43f2, + 0xf6241783, + 0x1a00e8ff, + 0x0a116418, + 0xff23958a, + 0x82effff9, + 0x00f62239, + 0xe0148a21, + 0xd7ff250a, + 0xe6ffdeff, + 0xe5240582, + 0xd8ff4300, + 0x0d82ab85, + 0x0000f224, + 0x0d83e4ff, + 0x2105a75a, + 0x2382fcff, + 0x8c82be20, + 0x17820920, + 0xdbffd222, + 0xe52a0582, + 0x0e000a00, + 0xf1ffe5ff, + 0x0d82cdff, + 0xa5ffe726, + 0xdbffc9ff, + 0xbd20c382, + 0x210d116d, + 0x45724c00, + 0x82eb2006, + 0x825f865d, + 0x2302f047, + 0x2300f5ff, + 0x2007b159, + 0x06d155ff, + 0x610be959, + 0x2f470e03, + 0x00212111, + 0x20050d58, + 0x09814619, + 0x2985c498, + 0x26201e89, + 0x09400a89, + 0x79711897, + 0x49002012, + 0xb7442539, + 0x28758775, + 0x1400ecff, + 0xecfffcff, + 0x08037fff, + 0x00221182, + 0x6818e6ff, + 0x00210fa3, + 0xa36a1800, + 0x9897411d, + 0x2300de22, + 0xf926dd82, + 0x3c00e1ff, + 0x7162efff, + 0x059d5b06, + 0xd382c720, + 0x9b4ce520, + 0xab5c1805, + 0x82092008, + 0x8f8a1813, + 0x07b7420d, + 0xb7421320, + 0x07af421a, + 0x5facb742, + 0xff2105ed, + 0x20d782ec, + 0x0bf760fa, + 0x41dfff21, + 0xff2005fb, + 0x2005796f, + 0x17d941e2, + 0x2d75a35c, + 0xe8ffebff, + 0xf0ffdcff, + 0x2300f0ff, + 0x0782fcff, + 0xf3ffdb22, + 0xec201382, + 0xf2200982, + 0xdc26c982, + 0xf2ffe9ff, + 0x0d82faff, + 0xaf42f020, + 0xc4ff2507, + 0xfdffe6ff, + 0x00222f82, + 0xcb85fbff, + 0xde20f986, + 0x56180d85, + 0x3b4b0eeb, + 0x211b8506, + 0x0785faff, + 0x489f0540, + 0xb985193b, + 0x85f4ff21, + 0x2905a707, + 0xf2ffc4ff, + 0xf0ffe8ff, + 0x0582fcff, + 0xf3ffca26, + 0xf9ffdcff, + 0xa70e9746, + 0x1827cc4a, + 0x8f086941, + 0x47591855, + 0x181f820f, + 0x871f7182, + 0x0e0f4bcf, + 0x00293982, + 0xff07000a, + 0xffe2fffa, + 0x220182f6, + 0x820300fa, + 0x83fd2005, + 0x2503e716, + 0xc8ffbdff, + 0x3551c9ff, + 0x3189501b, + 0x82f2ff21, + 0x00f22651, + 0xfff2ff00, + 0x48c785a2, + 0x00210599, + 0x240d8214, + 0x0010000e, + 0x2409820f, + 0x0018000d, + 0x24f98217, + 0xff1400f6, + 0x280984f6, + 0xfff9fff1, + 0x00fcfffc, + 0x26078204, + 0xffd8fff8, + 0x5fccffb0, + 0x84825447, + 0x4b47029d, + 0x87439d25, + 0x09db461d, + 0x07851187, + 0x851b7141, + 0x9805b721, + 0x900420bd, + 0x6e09208b, + 0x31901fa9, + 0x6370948e, + 0x23f36f09, + 0x0ebc3c8e, + 0x13094118, + 0x3c8250bc, + 0xe824c382, + 0xfcfffaff, + 0x89465b82, + 0xff0a2409, + 0x820400fa, + 0x0010241c, + 0x8210000a, + 0x09b76507, + 0x8208ad50, + 0x82f6202f, + 0x2037833b, + 0x242182fc, + 0x00ecff00, + 0x05234600, + 0x03bb0d83, + 0x4d08a763, + 0xeb411689, + 0x82749c18, + 0x18ec20ab, + 0x610b8d79, + 0x3291053b, + 0x2410fd41, + 0x00060006, + 0x08034108, + 0x82080f63, + 0x82eb204f, + 0x4502ba15, + 0x37521fef, + 0x266aba0f, + 0xfffcff00, + 0x4cf0fff8, + 0x09210643, + 0x08834700, + 0x7d254b41, + 0x85b10b3b, + 0x20080753, + 0xa53b95cc, + 0x233b8f83, + 0xeeffe5ff, + 0xfc20d582, + 0x200c174d, + 0x41258307, + 0x65180837, + 0xff270c0f, + 0xff0000e3, + 0x82f2fff6, + 0x82f62001, + 0x85fc2009, + 0x0a002307, + 0x0d821800, + 0x4318f620, + 0x5b8323bd, + 0x6c810340, + 0x8b4009e7, + 0x2081ca81, + 0x204b9243, + 0xaf139250, + 0x00072212, + 0xaf018243, + 0x242f8535, + 0xff00000a, + 0x1a954cf6, + 0x7d422582, + 0xa10f820c, + 0xf6ff2502, + 0xf0ffe8ff, + 0xe6200582, + 0x23053f4b, + 0xeafff9ff, + 0x15433593, + 0x00052210, + 0x206d8405, + 0x20918205, + 0x200382ec, + 0x200382ef, + 0x25757fec, + 0x138d5f93, + 0x8d1b7348, + 0x1f114163, + 0x0d93578d, + 0x75456b93, + 0x40389310, + 0xd3489413, + 0xff0a2214, + 0x498018f6, + 0x18f1831f, + 0x8b099778, + 0x3f0b41da, + 0x00f2ff23, + 0x20018222, + 0x08074528, + 0x00225c8b, + 0x0e84ceff, + 0x5f421a20, + 0x96168410, + 0x84312004, + 0x002e2617, + 0x002e0042, + 0x240b843b, + 0x00eaff00, + 0x8d09853c, + 0x41758905, + 0x0d2406e7, + 0xfcff0000, + 0x24063354, + 0x004b003e, + 0x452f854c, + 0x0c84067f, + 0x82f6ff21, + 0x840e208d, + 0x1804c80a, + 0x8a07a38a, + 0x00192450, + 0x8a19000d, + 0x820aa80f, + 0x82a720ab, + 0x820620a1, + 0x00092230, + 0x41058303, + 0x43823fa3, + 0xb14102b0, + 0xb8ff2115, + 0x21057141, + 0x50adbbff, + 0x0423c184, + 0x8a000400, + 0xd8ff2300, + 0xcf429cff, + 0x20f9820d, + 0x063774de, + 0x437af620, + 0x27058305, + 0xe8ffe6ff, + 0xe2fff0ff, + 0x14263a82, + 0x00002600, + 0x158276ff, + 0x9f8be820, + 0xff211b83, + 0x090b42f9, + 0x02a22982, + 0xffd0ff23, + 0xb76418c8, + 0x4f3e8517, + 0x25851f87, + 0x31ab058b, + 0x200c2f70, + 0x05f141f0, + 0xef823f83, + 0x8b0db352, + 0x420bb860, + 0x7f842543, + 0xb806a157, + 0xd438406a, + 0xbbb8ff21, + 0x0de742d6, + 0x3b8749bb, + 0x8813a173, + 0x00dc221b, + 0xa20b8730, + 0x830e2007, + 0x05374b23, + 0x53f2ff21, + 0x0023054d, + 0x830d0007, + 0x42038f15, + 0x47180fdf, + 0xfd4a08bb, + 0x0a554505, + 0x200a9f43, + 0x8f0b8a25, + 0x9d0fca50, + 0x1dff4265, + 0x54fdff21, + 0x0320081b, + 0xca0b9743, + 0x234aee9e, + 0xf2ffecff, + 0xff21c983, + 0x417888e4, + 0x0b24079d, + 0x0d001300, + 0x09200182, + 0x23831983, + 0x0a830f82, + 0x08220391, + 0x14910c00, + 0xb95611db, + 0x8e67db0b, + 0x0013225b, + 0x40118e06, + 0xe342960e, + 0x96b4401d, + 0x062296c3, + 0x01820d00, + 0x03821320, + 0x1c001724, + 0x52860900, + 0x860c734f, + 0xa4064013, + 0x9f0b4378, + 0x257418b0, + 0x0583780b, + 0x50180020, + 0x1b541053, + 0x97b39f6f, + 0xd64f501f, + 0x1020ee95, + 0xb7421684, + 0x00132107, + 0x84a86544, + 0x5004a4b7, + 0x56a43191, + 0x48000226, + 0x04000200, + 0x062c2b82, + 0x03000a00, + 0x0f000e00, + 0x1c000800, + 0x20080182, + 0x001e000a, + 0x000b0022, + 0x00250024, + 0x00360010, + 0x00120058, + 0x008d005e, + 0x009a0035, + 0x006500a4, + 0x220182b7, + 0x82cf0070, + 0x71720901, + 0x20010501, + 0x24017200, + 0x8e002801, + 0x2c012a01, + 0x2e019300, + 0x96004a01, + 0x5b015001, + 0x5d01b300, + 0xbf005d01, + 0x88018801, + 0xa001c000, + 0xc100a001, + 0xd801d601, + 0xdc01c200, + 0xc500dc01, + 0xdf01df01, + 0xe201c600, + 0xc700e201, + 0xe801e601, + 0xea01c800, + 0xcb00ea01, + 0xec01ec01, + 0x0402cc00, + 0xcd000402, + 0x08020802, + 0x0c02ce00, + 0xcf000d02, + 0x0f020f02, + 0x1202d100, + 0xd2001202, + 0x26022502, + 0x2a02d300, + 0xd5003802, + 0x51025002, + 0x5b02e400, + 0xe6005c02, + 0x62025f02, + 0x6402e800, + 0xec006502, + 0x6e026d02, + 0x7002ee00, + 0xf0007002, + 0x75027302, + 0x7702f100, + 0xf4007702, + 0x7b027902, + 0x8202f500, + 0xf8008402, + 0x87028602, + 0x8e02fb00, + 0xfd008e02, + 0x90029002, + 0x9602fe00, + 0xff009602, + 0x9c029b02, + 0x9f020001, + 0x02019f02, + 0xa302a302, + 0xab020301, + 0x0401ac02, + 0xaf02af02, + 0xc4020601, + 0x0701d902, + 0xea02e302, + 0x4a031d01, + 0x25015903, + 0x8b038b03, + 0xcc043501, + 0x3601cf04, + 0xd404d104, + 0xd9043a01, + 0x3e01da04, + 0x0905e704, + 0x0f054001, + 0x63013005, + 0x55054b05, + 0x66058501, + 0x90016605, + 0x81058105, + 0xb7059101, + 0x9201b805, + 0xbf05be05, + 0xc1059401, + 0x9601c105, + 0xc605c405, + 0xc8059701, + 0x9a01c805, + 0xcc05cb05, + 0xd1059b01, + 0x9d01d505, + 0xb407b407, + 0x0200a201, + 0x03827900, + 0x13000224, + 0x01820300, + 0x04001622, + 0x19220182, + 0x01820600, + 0x07001e22, + 0x21220182, + 0x01820800, + 0x09002722, + 0x2a220182, + 0x01820a00, + 0x0e002d28, + 0x2a000f00, + 0x01821c00, + 0x1e001122, + 0x17220182, + 0x01821f00, + 0x20001a22, + 0x1c220182, + 0x01822100, + 0x22001f22, + 0x25220182, + 0x01822400, + 0x25002c22, + 0x2e240182, + 0x4d003600, + 0x4e226582, + 0x31825000, + 0x5300512e, + 0x54001600, + 0x19005800, + 0x71005e00, + 0x722e1182, + 0x21007200, + 0x7b007300, + 0x7c002700, + 0x5f827f00, + 0x8000802e, + 0x81002800, + 0x2d008d00, + 0xa4009a00, + 0xb7221182, + 0x2982b700, + 0x00cf2608, + 0x012400cf, + 0x00050105, + 0x0106012d, + 0x0111001d, + 0x0020011e, + 0x0124011c, + 0x01170028, + 0x002c012a, + 0x012e011a, + 0x3a118241, + 0x00420142, + 0x0143011f, + 0x0125004a, + 0x005b0150, + 0x015d012c, + 0x012e005d, + 0x82880188, + 0x01a0281d, + 0x012200a0, + 0x82d701d6, + 0x01d82211, + 0x221182d8, + 0x82dc01dc, + 0x01df2e41, + 0x011b00df, + 0x00e201e2, + 0x01e60114, + 0x221182e6, + 0x82e801e7, + 0x01ea220b, + 0x281782ea, + 0x00ec01ec, + 0x02040217, + 0x34058204, + 0x00080208, + 0x020c021a, + 0x0214000d, + 0x000f020f, + 0x0212021b, + 0x3a058212, + 0x00250225, + 0x0226021f, + 0x022c0026, + 0x0037022a, + 0x0238022b, + 0x022a0038, + 0x82510250, + 0x025b2211, + 0x2235825c, + 0x8262025f, + 0x02642205, + 0x22058264, + 0x82650265, + 0x026d2e17, + 0x0210006d, + 0x006e026e, + 0x02700203, + 0x22058270, + 0x82740273, + 0x02752805, + 0x020d0075, + 0x82770277, + 0x027a2e0b, + 0x0206007a, + 0x007b027b, + 0x0282020a, + 0x22118284, + 0x82870286, + 0x8e20080b, + 0x0e008e02, + 0x90029002, + 0x96020700, + 0x0b009602, + 0x9b029b02, + 0x9c020400, + 0x08009c02, + 0x9f029f02, + 0xa3220582, + 0x1d82a302, + 0xac02ab22, + 0xaf220b82, + 0x0582af02, + 0xd902c422, + 0x44084182, + 0x00ea02e3, + 0x034a030a, + 0x03080059, + 0x008b038b, + 0x04cc0401, + 0x042c00cc, + 0x00cd04cd, + 0x04ce0412, + 0x041500ce, + 0x00cf04cf, + 0x04d10418, + 0x041d00d1, + 0x00d204d2, + 0x04d30420, + 0x042600d3, + 0x00d404d4, + 0x04d90429, + 0x220582da, + 0x82fe04e7, + 0x05ff342f, + 0x051d0001, + 0x00040502, + 0x05050515, + 0x05180009, + 0x8222050f, + 0x05233411, + 0x05200023, + 0x002c0524, + 0x052d0526, + 0x05290030, + 0x8255054b, + 0x05662205, + 0x281d8266, + 0x00810581, + 0x05b70523, + 0x2e1182b8, + 0x00be05be, + 0x05bf050f, + 0x050200bf, + 0x82c105c1, + 0x05c42205, + 0x280582c5, + 0x00c605c6, + 0x05c8050c, + 0x2e0b82c8, + 0x00cb05cb, + 0x05cc0505, + 0x050900cc, + 0x82d105d1, + 0x05d22211, + 0x300b82d2, + 0x00d505d3, + 0x07b40702, + 0x002c00b4, + 0x001b0102, + 0x22018202, + 0x82040056, + 0x25dd8201, + 0x59000800, + 0x01820b00, + 0x10006722, + 0x59220182, + 0x01821200, + 0x14005922, + 0x68220182, + 0x01821500, + 0x16004222, + 0x5c210182, + 0x9daa1800, + 0x0060220f, + 0x2201821a, + 0x821b0045, + 0x00622201, + 0x2801821c, + 0x001e0055, + 0x006a0020, + 0x22018221, + 0x82220057, + 0x00692201, + 0x22018224, + 0x8225006c, + 0x006f2801, + 0x00290028, + 0x822a0073, + 0x006a2201, + 0x2001822b, + 0x208f8273, + 0x222f822c, + 0x822d002d, + 0x002e2617, + 0x005a002e, + 0x2201822f, + 0x82300041, + 0x005b2201, + 0x22018231, + 0x8232005d, + 0x005e2201, + 0x22018233, + 0x8234005f, + 0x00612201, + 0x2c018235, + 0x00360070, + 0x0056004d, + 0x00580054, + 0x203d8259, + 0x2805827b, + 0x008e008e, + 0x00a50067, + 0x300b82bf, + 0x00ce00c8, + 0x00d00068, + 0x004200d7, + 0x00ef00d8, + 0x79aa185c, + 0x622e0810, + 0x20010601, + 0x24015500, + 0x6a004101, + 0x42014201, + 0x43015700, + 0x69004a01, + 0x5b015001, + 0x5c016c00, + 0x73005c01, + 0x5d015d01, + 0x61016f00, + 0x0b826101, + 0x74016a22, + 0x76220582, + 0x2f829001, + 0x98019122, + 0x26080b82, + 0x009f0199, + 0x01a1015a, + 0x014100a8, + 0x00c101a9, + 0x01c2015b, + 0x015e00c5, + 0x00cd01c6, + 0x01ce0161, + 0x017000d2, + 0x82d501d5, + 0x01d62229, + 0x224782d6, + 0x82d701d7, + 0x01d82259, + 0x282982d8, + 0x00d901d9, + 0x01dc0173, + 0x224d82dc, + 0x82df01de, + 0x01e12205, + 0x220582e1, + 0x82e201e2, + 0x01e32217, + 0x220b82e3, + 0x82e901e9, + 0x01ea2235, + 0x220b82ec, + 0x82ed01ed, + 0x01ee2253, + 0x223b82ee, + 0x82f101f1, + 0x01f42223, + 0x220582f4, + 0x82fa01fa, + 0x01fb2205, + 0x221782fc, + 0x82fd01fd, + 0x01fe220b, + 0x2e3582fe, + 0x000002ff, + 0x02030273, + 0x026a0006, + 0x820a020a, + 0x020c220b, + 0x0805820d, + 0x0e020e44, + 0x0f025a00, + 0x6f001002, + 0x12021102, + 0x15024100, + 0x5b001502, + 0x17021702, + 0x19026600, + 0x5d001902, + 0x1c021a02, + 0x1e027000, + 0x47001e02, + 0x1f021f02, + 0x25024800, + 0x57002902, + 0x37022a02, + 0x39027200, + 0x53825a02, + 0x64026422, + 0x20081182, + 0x00650265, + 0x0268026c, + 0x02320068, + 0x006b026b, + 0x026d0235, + 0x0215006d, + 0x006f026f, + 0x0272020c, + 0x22178272, + 0x82760276, + 0x7932080b, + 0x0d007902, + 0x7a027a02, + 0x7b020f00, + 0x12007b02, + 0x7c027c02, + 0x7d020900, + 0x34007d02, + 0x7e027e02, + 0x7f020a00, + 0x38007f02, + 0x80028002, + 0x87023100, + 0x23828702, + 0x02892108, + 0x02010089, + 0x008a028a, + 0x028b0233, + 0x0205008b, + 0x008c028c, + 0x028d0203, + 0x0204008d, + 0x008e028e, + 0x0805ad7a, + 0x90023640, + 0x10009002, + 0x91029102, + 0x92020700, + 0x36009202, + 0x93029302, + 0x94022100, + 0x37009402, + 0x95029502, + 0x96020800, + 0x13009602, + 0x97029702, + 0x98020b00, + 0x1b009802, + 0x99029902, + 0x9a022200, + 0x1d449a02, + 0x020e2a06, + 0x009c029c, + 0x029d0211, + 0x2811829d, + 0x009e029e, + 0x029f0202, + 0x2211829f, + 0x82a102a0, + 0x02a22211, + 0x226582a3, + 0x82a402a4, + 0x02a5220b, + 0x229b82a5, + 0x82a602a6, + 0x02a72289, + 0x227182a7, + 0x82a802a8, + 0x02a9287d, + 0x020600a9, + 0x82aa02aa, + 0x02ab2223, + 0x223b82ac, + 0x82ad02ad, + 0x02ae220b, + 0x221782ae, + 0x82af02af, + 0x02b02211, + 0x28e382b9, + 0x00bb02ba, + 0x02e90232, + 0x22e982ea, + 0x82f502f5, + 0xf62c080b, + 0x3100fd02, + 0x07030703, + 0x10033800, + 0x01001c03, + 0x24031d03, + 0x25030400, + 0x36002f03, + 0x31033003, + 0x32030700, + 0x06003203, + 0x33033303, + 0x34220b82, + 0x0b823f03, + 0x47034034, + 0x48030b00, + 0x22004903, + 0x59034a03, + 0x5a031100, + 0x11826403, + 0x70036522, + 0x71224182, + 0x3b827c03, + 0x88037d22, + 0x89221182, + 0x0b828903, + 0x8b038a22, + 0x20080b82, + 0x008c038c, + 0x038d0337, + 0x0323008d, + 0x00970397, + 0x04820407, + 0x04250083, + 0x00850484, + 0x04860424, + 0x080b8286, + 0x87048720, + 0x89047100, + 0x28008904, + 0x8c048b04, + 0x8d041900, + 0x17008d04, + 0x8e048e04, + 0x8f041800, + 0x0b828f04, + 0x90049022, + 0x91220b82, + 0x2f829204, + 0x9304932e, + 0x94042600, + 0x27009404, + 0x95049504, + 0x96220b82, + 0x0b829604, + 0x99049728, + 0x9c041600, + 0x05829d04, + 0x9e049e2e, + 0xa4041a00, + 0x3f00a404, + 0xa604a604, + 0xa8220582, + 0x0582a804, + 0xa904a934, + 0xab042900, + 0x6300ab04, + 0xad04ad04, + 0xb3044600, + 0x7d82b304, + 0xb404b422, + 0xb5227d82, + 0x0b82b504, + 0xb704b622, + 0xb9220b82, + 0x2f82b904, + 0xbb04bb22, + 0xbd220582, + 0x0582bd04, + 0x04c42008, + 0x046400c4, + 0x00c504c5, + 0x04cc0465, + 0x046c00cc, + 0x00cd04cd, + 0x04cf044b, + 0x045800cf, + 0x82d304d3, + 0x04d62805, + 0x044c00d6, + 0x82db04db, + 0x04dd220b, + 0x080582dd, + 0xdf04df3e, + 0xe0044d00, + 0x4e00e004, + 0xe104e104, + 0xe2044f00, + 0x5000e204, + 0xe304e304, + 0xe4045100, + 0x5200e404, + 0xe504e504, + 0xe6045300, + 0x5400e604, + 0xfe04e704, + 0x05054b00, + 0x58000905, + 0x2c052405, + 0x3f280582, + 0x4c003f05, + 0x70055605, + 0x38080b82, + 0x00800579, + 0x0582054d, + 0x054e0089, + 0x00a1058a, + 0x05a2054f, + 0x055100a5, + 0x00ad05a6, + 0x05ae0553, + 0x055400b2, + 0x00b905b9, + 0x05ba052a, + 0x053900bb, + 0x00bc05bc, + 0x05bd052b, + 0x280b82bd, + 0x00be05be, + 0x05bf0520, + 0x280b82bf, + 0x00c005c0, + 0x05c1051d, + 0x220b82c2, + 0x82c305c3, + 0x05c4222f, + 0x280b82c5, + 0x00c605c6, + 0x05c7053d, + 0x221d82c7, + 0x82c905c8, + 0xca2c0811, + 0x3c00ca05, + 0xcb05cb05, + 0xcc051e00, + 0x1f00cc05, + 0xcd05cd05, + 0xce053a00, + 0x1c00ce05, + 0xcf05cf05, + 0xd0053b00, + 0x2c00d005, + 0xd105d105, + 0xd2222f82, + 0x2382d205, + 0xd305d322, + 0xd4225382, + 0x1182d405, + 0x05d53808, + 0x062c00d5, + 0x002f062f, + 0x0631063e, + 0x06300031, + 0x00330633, + 0x0634062e, + 0x062f0034, + 0x00370637, + 0x0639062d, + 0x066b0039, + 0x009c069c, + 0x06a1066d, + 0x066e00a1, + 0x82a306a2, + 0x06a4220b, + 0x220b82a4, + 0x82a806a5, + 0x06aa220b, + 0x220b82aa, + 0x82ac06ac, + 0x06af220b, + 0x280582af, + 0x00b106b0, + 0x06b30640, + 0x281782b3, + 0x00b706b6, + 0x06b9065f, + 0x081182b9, + 0xbf06bf36, + 0x25076d00, + 0x18002507, + 0x26072607, + 0x2b071700, + 0x4a002b07, + 0x2f072f07, + 0xb4074900, + 0x5700b507, + 0x422b0200, + 0x00000400, + 0xd230e42c, + 0x61003900, + 0xd8ff0000, + 0x201ff35f, + 0x9e004000, + 0xffdcff2d, + 0xff0600e8, + 0x000600d8, + 0x860d0003, + 0x82062001, + 0xa6ad5107, + 0x00830020, + 0x04830d20, + 0xff210391, + 0x220184f6, + 0x82ecffee, + 0xffd83201, + 0xffddffeb, + 0xfff9fff2, + 0x00f9fff5, + 0xffd4ff0d, + 0x200982e6, + 0x200582f4, + 0x200382eb, + 0xea3d91ec, + 0x00042211, + 0x826d8314, + 0x82002097, + 0x84f620a1, + 0xfffc2207, + 0x981383fc, + 0x59318203, + 0x0983098d, + 0xffe8ff22, + 0x980d3b61, + 0x2018d23a, + 0x8253821a, + 0x09002391, + 0x09820600, + 0x05000324, + 0xc9820500, + 0x0300f222, + 0xd184d784, + 0xdf220984, + 0x1782efff, + 0xf0fff02a, + 0x0000f2ff, + 0xf6ffe2ff, + 0xff25b383, + 0xffd8ffee, + 0x833b82d2, + 0x82002022, + 0xffec2213, + 0x222582f7, + 0x82f4ffec, + 0xfff62227, + 0x631f82ec, + 0x58843e99, + 0x4f5104b6, + 0xf7ff210d, + 0xf420b782, + 0x27544a83, + 0xb0352030, + 0xd2668331, + 0x06c76803, + 0x52dc59d2, + 0x40000821, + 0x1324a300, + 0x00001000, + 0x0b4fe218, + 0xc4200d82, + 0xff21b8a5, + 0x212785a1, + 0x3382e5ff, + 0x0b85a920, + 0xff220593, + 0xbd5cffdc, + 0x82698a52, + 0x270d83c1, + 0x0000d4ff, + 0xf2ffe5ff, + 0xca200582, + 0xfc200f84, + 0x8207fb42, + 0xffec2407, + 0x82f6ff88, + 0x84b42007, + 0xffca2e19, + 0xff0000de, + 0xffb2ffe0, + 0xffa4ff68, + 0x8213839e, + 0xff032603, + 0xffeaffe6, + 0x24af82e3, + 0xffdeffb4, + 0x220782c8, + 0x18a7ffb2, + 0x2307cf52, + 0xa4fff2ff, + 0x02fa2382, + 0x7605315c, + 0xf9220c2b, + 0xc984ecff, + 0x83100f46, + 0x23aa93eb, + 0xdffff3ff, + 0x237de96d, + 0x0000fcff, + 0x210a2b46, + 0xbd410004, + 0x84ad9306, + 0x00092413, + 0x8414000b, + 0x20048309, + 0x8404831a, + 0x84138903, + 0x5c04bd0e, + 0x4db60fc5, + 0x1b001b22, + 0x142039ac, + 0x00202fae, + 0xaf4700c9, + 0x085b6b12, + 0x0f466595, + 0x566b4908, + 0x6b18b342, + 0xff290687, + 0xff0000ec, + 0xffefffcb, + 0x240782c7, + 0xffd2ffef, + 0x84a782fa, + 0x18ff208b, + 0x2316c195, + 0xedfffcff, + 0x23056f42, + 0xe3fff2ff, + 0x8205cf5e, + 0xff002833, + 0xffe7fff9, + 0x44eafff3, + 0x1b200897, + 0xfc202982, + 0x213f3159, + 0x5d4be6ff, + 0x236b8309, + 0xfafff7ff, + 0xec207782, + 0x2021d959, + 0xa3a218ff, + 0x11cb590c, + 0x0389b383, + 0x86094749, + 0x420d2013, + 0x795705bd, + 0xe8ff2141, + 0x032e5182, + 0x0f00d8ff, + 0x06000300, + 0x0b001000, + 0x07820f00, + 0x2b420d20, + 0x84298311, + 0xfb4d18db, + 0xdeff210c, + 0xe620bb82, + 0x02824382, + 0x8309cd41, + 0xfaff2109, + 0x02841282, + 0x089f5118, + 0x41124542, + 0x57830529, + 0x04b22a84, + 0xff89ff23, + 0x05b77496, + 0x6df7ff21, + 0xd58208c7, + 0x50a71385, + 0x44f3ff21, + 0x36a70ca3, + 0xff2727c4, + 0xff90ff88, + 0x846effd2, + 0x8204204c, + 0x820e2005, + 0x00002203, + 0x2291820d, + 0x82e2ffd5, + 0x84cd8205, + 0x41002011, + 0xf6200683, + 0xff21e783, + 0x091542df, + 0x21090762, + 0x2f82ceff, + 0x12594f18, + 0x08235618, + 0x49851e20, + 0x5583058b, + 0xff000025, + 0x43b2ffeb, + 0x2d8b178f, + 0x20a00b40, + 0x23a1b55f, + 0x0000c7ff, + 0x13f56c18, + 0x7ae8ff21, + 0x2b821307, + 0x1900fc22, + 0x2008c36d, + 0x200f8212, + 0x457787f0, + 0x19200835, + 0x13201182, + 0x19220382, + 0x05822100, + 0x7d6b0d20, + 0x20098205, + 0x2129833e, + 0x1968e3ff, + 0x44282008, + 0xf6260a45, + 0x0000fcff, + 0x2183aeff, + 0xff2103ad, + 0x202f82ec, + 0x22038204, + 0x46f6ff00, + 0x0b8209db, + 0x83120d42, + 0x84039525, + 0x0ce143eb, + 0x996f278f, + 0x41854411, + 0xff216385, + 0x240782fd, + 0x00eeff07, + 0x4f078206, + 0x062407ed, + 0x0a001000, + 0x42056164, + 0xff24099d, + 0xff0000f2, + 0x0384a582, + 0xe2ffe122, + 0x82094d7e, + 0x23028439, + 0x0000fcff, + 0x00211585, + 0x824d8405, + 0x69028c04, + 0x33831295, + 0x05432383, + 0x22c883c4, + 0x84daff00, + 0xba044006, + 0x21afc140, + 0x6c41d4ff, + 0x1d5d6a0f, + 0x0f9d2d8f, + 0x2105174f, + 0x2589cbff, + 0x89101948, + 0x8509c21a, + 0x9048c26f, + 0x23b78342, + 0xecffd8ff, + 0x20067b46, + 0x202084ec, + 0x2005830a, + 0x3bb718ff, + 0x1b974318, + 0x45f1ff21, + 0x45830943, + 0x6b8903bf, + 0x0bb94218, + 0xc5740020, + 0x535f9808, + 0xff2108e9, + 0x202382fc, + 0x20038203, + 0x98038209, + 0x12674902, + 0x981d5553, + 0x84188f49, + 0xff1724c1, + 0x841d00f2, + 0x00132987, + 0x00170010, + 0x0009000d, + 0x460e8549, + 0x2d4507c3, + 0x180e2006, + 0x220823b9, + 0x85f5fff0, + 0x4605850b, + 0x0e8508d5, + 0x0320058d, + 0x0d400e8d, + 0xc2ff2185, + 0x930b3b49, + 0xd8ff2393, + 0x1793c6ff, + 0xb547138b, + 0xa9148b08, + 0x9507200b, + 0xebff242a, + 0x4600f6ff, + 0x002107a1, + 0x052778ff, + 0xfcfff022, + 0x0e262d82, + 0xeeffe6ff, + 0xbb4cf2ff, + 0x22df4305, + 0x33820a20, + 0x22200283, + 0xff210483, + 0x158d47f9, + 0x081b4218, + 0x272c0d48, + 0x8fff0000, + 0xe2ffa9ff, + 0xe6200782, + 0x8206136c, + 0x20ad8264, + 0x6d4918f6, + 0x90108209, + 0xe3ff2102, + 0x07814918, + 0xff231a85, + 0x420a00d2, + 0x19850f77, + 0x9b4e059a, + 0xf56e1818, + 0x31558b21, + 0x96ff88ff, + 0x82ffc1ff, + 0xc5ffc4ff, + 0xd3ffeeff, + 0x0184e6ff, + 0x0982df20, + 0xb7ffb726, + 0xbeff0000, + 0xff212d85, + 0x260b82ee, + 0xffd9ffd2, + 0x82b5fff2, + 0xffb722e1, + 0x07fd44d1, + 0x00c0ff23, + 0x24238622, + 0xffe8ffd8, + 0x202782d9, + 0x200382df, + 0x830785de, + 0xa7ff2119, + 0xee210584, + 0x12a15000, + 0x2008934c, + 0xd96e18ca, + 0xabff210b, + 0xd2207f82, + 0x03bb3583, + 0x82f6ff21, + 0x8211203d, + 0x89028503, + 0x830f8509, + 0x00092205, + 0x90068318, + 0x820a2003, + 0x24038511, + 0x002f002c, + 0x830d8231, + 0x00152202, + 0x84068349, + 0x84322003, + 0x44049f05, + 0x269f062f, + 0x9f093d42, + 0x451f8b29, + 0xed820d1d, + 0xab822f20, + 0x0b9f208b, + 0x2fae3520, + 0x1f924f9f, + 0x8d05bb43, + 0x12834318, + 0x21820820, + 0x03822f20, + 0x35220299, + 0x1c86cfff, + 0x86124542, + 0x44068219, + 0x25822211, + 0x5d8302b7, + 0xff206185, + 0x84099b7d, + 0x15bd704c, + 0x211b1546, + 0x0741f1ff, + 0x854b8412, + 0x09215004, + 0x059f0f85, + 0x4ddcff21, + 0x6b4d058b, + 0xa1339f0b, + 0xa185af1f, + 0x2b219951, + 0xf0ffdfff, + 0xd1fffcff, + 0x06000a00, + 0xc75c0384, + 0x82132005, + 0x48fc20d1, + 0x3f870971, + 0x41f9ff21, + 0xf0221c5d, + 0x33850000, + 0x200e2543, + 0x913f87e1, + 0x8d638907, + 0x99299133, + 0xddff2111, + 0xd8207782, + 0xff211f91, + 0x201782ec, + 0x425789f6, + 0xf2220645, + 0x6418e8ff, + 0xff210b15, + 0x091149f5, + 0x18095f48, + 0x420d0b73, + 0x2d2208e1, + 0x3b82f3ff, + 0x3946ea20, + 0x82282008, + 0x8902863b, + 0xa81086c9, + 0xc1ff2306, + 0x3d83c4ff, + 0x4f0f194f, + 0x4aa30933, + 0x21204182, + 0x85183171, + 0x11c54340, + 0x8509c956, + 0x8205b621, + 0xffbf26c1, + 0xffb7fffc, + 0x264082fa, + 0x00fdff14, + 0x830a0010, + 0x00002509, + 0xebffeaff, + 0xf1200582, + 0x02860d82, + 0xffe2ff22, + 0xff210d82, + 0x241582e7, + 0xffebffed, + 0x201682ed, + 0x220b820d, + 0x823600f5, + 0x22028209, + 0x5efff2ff, + 0xf7240583, + 0xf7ff0a00, + 0x03821982, + 0x00221682, + 0x0583d1ff, + 0x35200382, + 0x028c0382, + 0x0975a018, + 0xffedff22, + 0x0c834618, + 0x41faff21, + 0x318c08b9, + 0xff220c93, + 0xc61800d7, + 0x99411455, + 0x08034b06, + 0x21057544, + 0x5155e8ff, + 0xf5ff210d, + 0x1f485382, + 0x0a714206, + 0x0c517518, + 0x22081353, + 0x42faff26, + 0xf5840c45, + 0x02bc0482, + 0xffc5ff23, + 0x205784d5, + 0x0d3f44fa, + 0x822dbb72, + 0x001a213b, + 0x46161b60, + 0x7147180b, + 0x983f8626, + 0xd2ff2906, + 0x0600deff, + 0x0400bfff, + 0x14242282, + 0x10000a00, + 0x1a240184, + 0xf0ff0400, + 0x8218c595, + 0xf0200801, + 0xb5853182, + 0x22061749, + 0x41ff0000, + 0x21820e07, + 0x254a0282, + 0x82272008, + 0x4102960c, + 0x24960d3f, + 0x5f461696, + 0xb9ab1817, + 0x21388309, + 0x4a18e8ff, + 0xff210b1d, + 0x08f14cf2, + 0xecffe922, + 0x4407d35f, + 0x4d5f09bb, + 0x843f830d, + 0x41262003, + 0x70180513, + 0x4b4b0cf7, + 0x8207201d, + 0x4f441867, + 0x87518416, + 0x82032004, + 0x18f2207b, + 0x4e0c1f51, + 0x67432001, + 0x82ff2005, + 0x24098327, + 0x0600efff, + 0x77814d00, + 0xc6821420, + 0x03821020, + 0x06000022, + 0x03208b82, + 0x06208782, + 0x05200d82, + 0xf6200d82, + 0x00200782, + 0x23072f41, + 0xecfff0ff, + 0x27057145, + 0x0000f2ff, + 0xf2ffe5ff, + 0xf9200784, + 0xd8221382, + 0x29831500, + 0x03220382, + 0x1782efff, + 0x7f7af620, + 0x21258205, + 0x1f82fff0, + 0x02841782, + 0x08211582, + 0x4e00a900, + 0x389b0ee5, + 0x822bd146, + 0x44f9209f, + 0xff620693, + 0x10c3430b, + 0x83099544, + 0x83eb8379, + 0x46002007, + 0x14820fd1, + 0x1082298d, + 0xcd9c0293, + 0xffa3ff29, + 0x00f6ffb6, + 0x7eecff00, + 0x235e0ee1, + 0x415a8d10, + 0x13870583, + 0x8b44d582, + 0x8553181f, + 0x478b4411, + 0xa5ff9c26, + 0x9cffe5ff, + 0xdd280382, + 0xecff0a00, + 0x03000900, + 0x0e209782, + 0xbd220f82, + 0xdb18c4ff, + 0xff210953, + 0x22b382e4, + 0x82deffde, + 0xffd12a11, + 0xffbeffe7, + 0xffdbffc9, + 0x242d82f9, + 0x00d2ff00, + 0x8231822e, + 0xf2ff2102, + 0xf0240182, + 0xf2fff6ff, + 0xe8202582, + 0x200a634f, + 0x831c82bd, + 0x42c59002, + 0xff2105a3, + 0x222b82f5, + 0x83d7ffe6, + 0x82038722, + 0x12e94849, + 0x07a51d87, + 0xffe9ff23, + 0x0b9359fa, + 0xffe6ff23, + 0x200f82f6, + 0x213d83e3, + 0x0583f0ff, + 0xff210385, + 0x0f0946f5, + 0x44088f56, + 0x19220f0f, + 0x5349f3ff, + 0xbf3f850b, + 0xedff2105, + 0xfd205382, + 0xec200382, + 0x20067950, + 0x20b784fa, + 0x150b46fa, + 0xff216d89, + 0x085b50df, + 0xd347df20, + 0xe22b8915, + 0x82072009, + 0x0655418f, + 0xff239783, + 0x82fbfffd, + 0xfff02295, + 0x200582f2, + 0x847f85eb, + 0x45e9200b, + 0xff21079d, + 0x09e151de, + 0x18c4ff21, + 0x2a08d5b8, + 0xffecfffa, + 0xfff6ffe2, + 0x85fafff0, + 0x853b8503, + 0xecff2105, + 0x0f852787, + 0xff200583, + 0x4108a541, + 0x19830bd5, + 0x454903af, + 0xaf502018, + 0x202fd649, + 0x24fd8214, + 0x00f9ff14, + 0x20a98250, + 0xa803830d, + 0x8f042067, + 0x09a15f29, + 0xff201985, + 0x2ca9ab18, + 0x059d3385, + 0x2214294c, + 0x82280021, + 0x00002101, + 0xff258f88, + 0x002100f6, + 0x248d820f, + 0x00450002, + 0x2a018205, + 0x000b0000, + 0x0001000d, + 0x821b0010, + 0x001d2225, + 0x0809821d, + 0x23002320, + 0x26001100, + 0x12003500, + 0x5d005900, + 0x8e002200, + 0x27009900, + 0xb600a500, + 0xb8003300, + 0x3b82ce00, + 0x01d04808, + 0x015c0004, + 0x00230121, + 0x01290191, + 0x01940029, + 0x004f014b, + 0x015c0195, + 0x019a005c, + 0x0063015e, + 0x0165019b, + 0x01a10068, + 0x0087016a, + 0x018901a5, + 0x01c3009f, + 0x00d201a1, + 0x01d401da, + 0x010c01d5, + 0x01db01d9, + 0x82de010e, + 0x01112801, + 0x01e101e0, + 0x82e40112, + 0x01142201, + 0x280182eb, + 0x01ed0115, + 0x011601f1, + 0x220182f4, + 0x82f8011b, + 0x1cf60801, + 0x0102fb01, + 0x03021d01, + 0x24010302, + 0x07020502, + 0x09022501, + 0x28010b02, + 0x0e020e02, + 0x11022b01, + 0x2c011102, + 0x15021502, + 0x19022d01, + 0x2e011a02, + 0x29022702, + 0x39023001, + 0x33014f02, + 0x5a025202, + 0x5d024a01, + 0x53015d02, + 0x85048404, + 0xa3045401, + 0x5601a304, + 0xa504a504, + 0xa7045701, + 0x5801a704, + 0xb804b804, + 0xba045901, + 0x5a01ba04, + 0xbc04bc04, + 0xd0045b01, + 0x5c01d004, + 0xd804d604, + 0xdb045d01, + 0x6001e604, + 0x0e050a05, + 0x3f056c01, + 0x71014305, + 0x4a054505, + 0x56057601, + 0x7c016505, + 0x80056705, + 0x82058c01, + 0xa601b305, + 0xb605b505, + 0x9b06d801, + 0xda019b06, + 0x9e069e06, + 0xa206db01, + 0xdc01a406, + 0xa806a606, + 0xab06df01, + 0xe201ab06, + 0xb106af06, + 0xb306e301, + 0xe601b306, + 0xb706b606, + 0xb906e701, + 0xe901b906, + 0xbf06bd06, + 0xb507ea01, + 0xed01b507, + 0xa7000200, + 0x01820500, + 0x0b001022, + 0x01220182, + 0x01820c00, + 0x0d000422, + 0x09210182, + 0x05c34a00, + 0x11001124, + 0x01841200, + 0x13001022, + 0x16220182, + 0x01821400, + 0x15001d22, + 0x21220182, + 0x01821600, + 0x17002722, + 0x2a220182, + 0x01821800, + 0x19002d22, + 0x30220182, + 0x01821a00, + 0x1b003322, + 0x36220182, + 0x01821d00, + 0x23000e22, + 0x0a220182, + 0x01822600, + 0x27000222, + 0x072e0182, + 0x29002800, + 0x2a000a00, + 0x0e002b00, + 0x01822c00, + 0x2d002522, + 0x14220182, + 0x01822e00, + 0x2f001b22, + 0x1f220182, + 0x01823000, + 0x31002522, + 0x28220182, + 0x01823200, + 0x33002b22, + 0x2e220182, + 0x01823400, + 0x35003122, + 0x34240182, + 0x5d005900, + 0x8e2cab82, + 0x01008e00, + 0x91008f00, + 0x92000400, + 0x09220182, + 0x01829300, + 0x9400062a, + 0x09009900, + 0xb600a500, + 0xb8222382, + 0xd982bd00, + 0xbf00be22, + 0xc0220b82, + 0xd582c000, + 0xc700c122, + 0xc822c182, + 0xa382ce00, + 0xd700d028, + 0xd8002100, + 0x9d82e700, + 0xed00e828, + 0xee002400, + 0x0b82ef00, + 0xf300f022, + 0xf4229782, + 0x7982fb00, + 0x0001fc25, + 0x82013600, + 0x10002b00, + 0x02010201, + 0x03011e00, + 0x0b820401, + 0x01212608, + 0x010e0023, + 0x00290129, + 0x014b0105, + 0x010a004f, + 0x005c015c, + 0x015e0125, + 0x01020061, + 0x00620162, + 0x01630107, + 0x221d8263, + 0x82680165, + 0x016a220b, + 0x22238275, + 0x82870176, + 0x01892835, + 0x010b008e, + 0x8291018f, + 0x0192340b, + 0x01140098, + 0x009f0199, + 0x01a1011b, + 0x011f00a8, + 0x82b801a9, + 0x01b92847, + 0x012200be, + 0x82c101bf, + 0x01c2340b, + 0x012b00c5, + 0x00cd01c6, + 0x01ce0131, + 0x013400d2, + 0x82d401d4, + 0x01d5223b, + 0x225382d5, + 0x82db01d9, + 0x01de280b, + 0x011300de, + 0x82e001e0, + 0x01e1220b, + 0x223582e1, + 0x82e401e4, + 0x01eb220b, + 0x220b82eb, + 0x82ed01ed, + 0x01ee223b, + 0x220b82ee, + 0x82f001ef, + 0x01f12235, + 0x220b82f1, + 0x82f401f4, + 0x01f8229b, + 0x223b82f8, + 0x82fc01fb, + 0x01fd2211, + 0x2a1d82fe, + 0x00ff01ff, + 0x02000213, + 0x82250000, + 0x000126f4, + 0x0203020e, + 0x22058203, + 0x82060205, + 0x02072205, + 0x22178207, + 0x82090209, + 0x0a2c0823, + 0x14000b02, + 0x0e020e02, + 0x11021b00, + 0x1f001102, + 0x15021502, + 0x19020e00, + 0x28001902, + 0x1a021a02, + 0x27023400, + 0x07002702, + 0x29022802, + 0x39221d82, + 0x3b824f02, + 0x5a025222, + 0x5d340582, + 0x05005d02, + 0x85048404, + 0xa3043800, + 0x3700a304, + 0xa504a504, + 0xa7220582, + 0x0582a704, + 0xb804b822, + 0xba220582, + 0x0582ba04, + 0xbc04bc22, + 0xd0340582, + 0x0f00d004, + 0xd704d704, + 0xd8040300, + 0x0800d804, + 0xdb04db04, + 0xdc281182, + 0x1100dc04, + 0xdd04dd04, + 0x4a080b82, + 0x00de04de, + 0x04df0415, + 0x041c00df, + 0x00e004e0, + 0x04e10420, + 0x042600e1, + 0x00e204e2, + 0x04e30429, + 0x042c00e3, + 0x00e404e4, + 0x04e5042f, + 0x043200e5, + 0x00e604e6, + 0x050a0535, + 0x050f000e, + 0x00420540, + 0x05430503, + 0x05080043, + 0x824a0545, + 0x05562205, + 0x28178265, + 0x006c0567, + 0x056d050c, + 0x080b8270, + 0x71057126, + 0x72051100, + 0x15007805, + 0x80057905, + 0x82051c00, + 0x20008905, + 0x99058a05, + 0x9a052600, + 0x23009f05, + 0xa105a005, + 0xa22e0b82, + 0x2c00a505, + 0xad05a605, + 0xae053200, + 0x6582b205, + 0xb305b322, + 0xb5344182, + 0x0f00b605, + 0x9b069b06, + 0x9e061900, + 0x17009e06, + 0xa206a206, + 0xa3220b82, + 0x0b82a306, + 0xa406a428, + 0xa6061800, + 0x0b82a606, + 0xa806a722, + 0xab221782, + 0x1182ab06, + 0xaf06af22, + 0xb0281182, + 0x1a00b106, + 0xb306b306, + 0xb6280582, + 0x2e00b706, + 0xb906b906, + 0xbd220b82, + 0x1d82bd06, + 0xbe06be22, + 0xbf2e2982, + 0x1700bf06, + 0xb507b507, + 0x02000700, + 0x0382f000, + 0x27000224, + 0x01820400, + 0x08002822, + 0x28220182, + 0x01820b00, + 0x10000422, + 0x28220182, + 0x01821200, + 0x14002822, + 0x29220182, + 0x01821500, + 0x83001621, + 0x002a2201, + 0x22018217, + 0x8218002c, + 0x002e2201, + 0x22018219, + 0x821a0041, + 0x00192201, + 0x2201821b, + 0x821c0045, + 0x000e2801, + 0x0020001e, + 0x82210011, + 0x00362201, + 0x22018222, + 0x8224000f, + 0x004f2201, + 0x28018225, + 0x00280010, + 0x004e0029, + 0x2201822a, + 0x822b0011, + 0x004e2201, + 0x2201822c, + 0x822d0011, + 0x004e2201, + 0x2201822e, + 0x822f0046, + 0x00152201, + 0x22018230, + 0x82310017, + 0x002b2201, + 0x22018232, + 0x8233002d, + 0x00182201, + 0x22018234, + 0x8235002f, + 0x001a2401, + 0x824d0036, + 0x004e28c5, + 0x004c0050, + 0x82580054, + 0x0073225d, + 0x2205827b, + 0x828e008e, + 0x00a522d9, + 0x220b82bf, + 0x82ce00c8, + 0x00d02273, + 0x22c382d7, + 0x82ef00d8, + 0x00f02279, + 0x086782f3, + 0xfb00f42c, + 0xfc001900, + 0x45000001, + 0x20010601, + 0x21010e00, + 0x4a002101, + 0x41012401, + 0x42011100, + 0x36004201, + 0x4a014301, + 0x4f010f00, + 0x17824f01, + 0x5b015034, + 0x5c014f00, + 0x4e005c01, + 0x5d015d01, + 0x61011000, + 0x0b826101, + 0x74016a22, + 0x76220582, + 0x35829001, + 0x98019122, + 0x2c080b82, + 0x009f0199, + 0x01a10146, + 0x011500a8, + 0x00c101a9, + 0x01c20117, + 0x012d00c5, + 0x00cd01c6, + 0x01ce012f, + 0x011a00d2, + 0x00d501d5, + 0x01d6014e, + 0x224782d6, + 0x82d701d7, + 0x01d82259, + 0x222982d8, + 0x82d901d9, + 0x01dc2217, + 0x284d82dc, + 0x00dd01dd, + 0x01de0142, + 0x220b82df, + 0x82e101e1, + 0x01e22205, + 0x221d82e2, + 0x82e301e3, + 0x01e6280b, + 0x015100e6, + 0x82e801e8, + 0x01e92205, + 0x224782e9, + 0x82ec01ea, + 0x01ed2217, + 0x226582ed, + 0x82ee01ee, + 0x01f1224d, + 0x282f82f1, + 0x00f301f3, + 0x01f40153, + 0x280b82f4, + 0x00f501f5, + 0x01fa0148, + 0x220b82fa, + 0x82fc01fb, + 0x01fd2223, + 0x220b82fd, + 0x82fe01fe, + 0x02ff3441, + 0x024e0000, + 0x00060203, + 0x02070211, + 0x02490009, + 0x820a020a, + 0x020c2211, + 0x3105820d, + 0x000e020e, + 0x020f0246, + 0x02100010, + 0x00120211, + 0x01820215, + 0x02170031, + 0x00160216, + 0x02170240, + 0x02430017, + 0x82180218, + 0x192c080b, + 0x2b001902, + 0x1c021a02, + 0x1e021a00, + 0x38001e02, + 0x1f021f02, + 0x25023900, + 0x36002902, + 0x37022a02, + 0x39024400, + 0x11005a02, + 0x64026402, + 0x65341182, + 0x4f006502, + 0x67026702, + 0x7b024800, + 0x60007b02, + 0x87028702, + 0x2c080582, + 0x00ea02e9, + 0x038e0360, + 0x0350008e, + 0x00b503b5, + 0x03b70356, + 0x035c00b7, + 0x00bc03bc, + 0x03c4035f, + 0x035a00c4, + 0x00da03da, + 0x03db0359, + 0x221182db, + 0x82e003e0, + 0x03e72211, + 0x222382e7, + 0x82f303f3, + 0xfb200805, + 0x5a00fc03, + 0x01040104, + 0x08045400, + 0x5e000804, + 0x1f041f04, + 0x26045d00, + 0x58002604, + 0x27042704, + 0x29221182, + 0x11822904, + 0x2e042e34, + 0x82045b00, + 0x02008304, + 0x85048404, + 0x86041b00, + 0x0b828604, + 0x04872008, + 0x04520087, + 0x00890489, + 0x048b041f, + 0x0431008c, + 0x008d048d, + 0x048e0430, + 0x0420008e, + 0x828f048f, + 0x0490220b, + 0x220b8290, + 0x82920491, + 0x04932e2f, + 0x041d0093, + 0x00940494, + 0x0495041e, + 0x220b8295, + 0x82960496, + 0x0497280b, + 0x041c0099, + 0x829d049c, + 0x049e2e05, + 0x0422009e, + 0x00a404a4, + 0x04a6043c, + 0x220582a6, + 0x82a804a8, + 0x04a93405, + 0x043300a9, + 0x00ab04ab, + 0x04ad0432, + 0x042100ad, + 0x82b304b3, + 0x04b4227d, + 0x227d82b4, + 0x82b504b5, + 0x04b6220b, + 0x220b82b7, + 0x82b904b9, + 0x04bb222f, + 0x220582bb, + 0x82bd04bd, + 0xc4260805, + 0x3700c404, + 0xc504c504, + 0xcc042300, + 0x4f00cc04, + 0xcd04cd04, + 0xce040300, + 0x4d00ce04, + 0xcf04cf04, + 0xd0040500, + 0x0b82d204, + 0xd304d322, + 0xd4220b82, + 0x0b82d404, + 0xd604d628, + 0xd7040100, + 0x0b82da04, + 0xdb04db22, + 0xdc221782, + 0x0b82dc04, + 0xdd04dd22, + 0xde220b82, + 0x0b82de04, + 0x04df3208, + 0x040600df, + 0x00e004e0, + 0x04e10407, + 0x040800e1, + 0x00e204e2, + 0x04e30409, + 0x040a00e3, + 0x00e404e4, + 0x04e5040b, + 0x040c00e5, + 0x00e604e6, + 0x04e7040d, + 0x347782fe, + 0x000105ff, + 0x0503054b, + 0x054d0004, + 0x00090505, + 0x050a0505, + 0x220b820d, + 0x8223050f, + 0x05242205, + 0x2211822c, + 0x8230052d, + 0x053f280b, + 0x0501003f, + 0x82490540, + 0x054b220b, + 0x22058255, + 0x82700556, + 0x0571221d, + 0x080b8278, + 0x80057926, + 0x82050600, + 0x07008905, + 0xa1058a05, + 0xa2050800, + 0x0a00a505, + 0xad05a605, + 0xae050c00, + 0x0d00b205, + 0xb405b405, + 0xb6222982, + 0x0582b805, + 0x05da4408, + 0x055500da, + 0x00ea05ea, + 0x062f0657, + 0x0635002f, + 0x00310631, + 0x0633063e, + 0x06250033, + 0x00340634, + 0x06370626, + 0x06240037, + 0x00390639, + 0x063b0634, + 0x063d003b, + 0x009b069b, + 0x069c0613, + 0x0612009c, + 0x829f069d, + 0x06a1280b, + 0x063f00a1, + 0x82a306a2, + 0x06a42211, + 0x220b82a4, + 0x82a806a5, + 0x06a9220b, + 0x221d82a9, + 0x82aa06aa, + 0x06ab2211, + 0x220b82ab, + 0x82ac06ac, + 0x06af2217, + 0x280582af, + 0x00b106b0, + 0x06b30614, + 0x281d82b3, + 0x00b706b6, + 0x06b90618, + 0x221182b9, + 0x82be06ba, + 0xbf440829, + 0x1200bf06, + 0x25072507, + 0x26072000, + 0x30002607, + 0x2b072b07, + 0x2f073b00, + 0x3a002f07, + 0x71077107, + 0xb4074700, + 0x3600b507, + 0x540a0200, + 0x00000400, + 0xf80a820a, + 0x92000900, + 0x14000000, + 0xd1ffddff, + 0x2800c9ff, + 0xff290183, + 0xfff0fff6, + 0x002100d1, + 0x30158228, + 0x00bfffc8, + 0xfff5ff1a, + 0xffd2ffe6, + 0xff9dffbb, + 0x260182ec, + 0xffe5ffb7, + 0x82f5ffcb, + 0xffd12235, + 0x221b8aa2, + 0x82a4ffba, + 0x90f62013, + 0xffdd212f, + 0xff254582, + 0xffd5ffea, + 0x823d82de, + 0xacff2725, + 0xa0ff98ff, + 0x698276ff, + 0xe2fff222, + 0xe5220182, + 0x0182dcff, + 0x821d9f53, + 0x8202ffa6, + 0x82ec20af, + 0xfff62203, + 0x228982e3, + 0x82060010, + 0xffe3260b, + 0xff0000f9, + 0x820f82ed, + 0xe6ff2502, + 0xd1ffe3ff, + 0xe5240f82, + 0xf2ffd8ff, + 0x2006f763, + 0x05975e06, + 0xbf5e1b88, + 0x202e8206, + 0x21138700, + 0x45890000, + 0x5e05ff4c, + 0x258307e5, + 0xff23038d, + 0x82e8ffef, + 0x52e5205b, + 0x0b82053d, + 0x0982eb20, + 0xf2261185, + 0xf9ffe5ff, + 0x0582fcff, + 0xec201d83, + 0xf9202982, + 0xea202986, + 0x498d8385, + 0x21c30d40, + 0xc540e0ff, + 0x8b8b18b5, + 0x08f34208, + 0x00fcff23, + 0x07355900, + 0x82f2ff21, + 0x41d82001, + 0x158205c9, + 0xe385cb20, + 0x86056750, + 0xfff2221b, + 0x09a552db, + 0x25831385, + 0xff214589, + 0x843f82ef, + 0x93178325, + 0x201f8203, + 0x976c18ec, + 0x84ec2008, + 0x2205823d, + 0x84fff9ff, + 0x201d8215, + 0x181383df, + 0x2210c9d0, + 0x82f6fff9, + 0x82f6206f, + 0x82f92027, + 0x20038307, + 0x820b82f2, + 0x0d9f5469, + 0x05bb3785, + 0x5205b342, + 0xff2309cf, + 0x52f9fff3, + 0xdf240a15, + 0xd2ffdcff, + 0xdd207982, + 0xff216383, + 0x870583c4, + 0x85ff2003, + 0xfff2221b, + 0x211187c9, + 0x13850000, + 0x45890f83, + 0xbf83c982, + 0x1f83258a, + 0xff210389, + 0x066d43e2, + 0x0000e226, + 0xe5fff2ff, + 0x1b410382, + 0x58ef2005, + 0xff210b2b, + 0x832782ee, + 0x82e82021, + 0x83ee201f, + 0x113d613d, + 0x6decff21, + 0x0b8209ff, + 0x0385dc20, + 0x03402b83, + 0x11496ca9, + 0x429fbb40, + 0xff230715, + 0x83c5ffdf, + 0xecff210b, + 0xd8200182, + 0x0d221586, + 0x93410000, + 0x21c98209, + 0xfd42ff09, + 0xffdf2205, + 0x0faf6fc4, + 0x85090021, + 0x822f8c33, + 0x20028232, + 0x2103820d, + 0x05850000, + 0x43183968, + 0xf9220665, + 0xe166b5ff, + 0xf9ff2109, + 0xfc200b82, + 0xf9220382, + 0x4384c8ff, + 0xff210482, + 0x822987b5, + 0x2102860c, + 0x0882f1ff, + 0x41004122, + 0x2011db5d, + 0x843d83ff, + 0xd5ff2703, + 0xf6ffc8ff, + 0x05822d00, + 0xa382f320, + 0x0382c420, + 0xdf22e983, + 0xef823500, + 0x1d84ab20, + 0x1382f220, + 0xadfff62c, + 0xd6ffabff, + 0xf2ffcbff, + 0x4f827bff, + 0xff23028c, + 0x82c5ffdc, + 0x820720e5, + 0xffdf2231, + 0x094f43d4, + 0x200c7167, + 0x20328414, + 0x23138307, + 0x0000dfff, + 0x1a831b8c, + 0x13920720, + 0x03a81783, + 0xfff9ff23, + 0x092341ae, + 0x15823687, + 0x0b88d120, + 0x0b831f82, + 0x83f9ff21, + 0x16db6005, + 0x27120558, + 0xc6ffbfff, + 0x3500cfff, + 0x4682b390, + 0x84abff21, + 0xfff0261d, + 0xffcfffd3, + 0x200d827c, + 0x205782d6, + 0x220382f2, + 0x54f3fff3, + 0xff200bf1, + 0x6d785782, + 0xdfff2505, + 0xa9ffd1ff, + 0x02843a82, + 0x8308375d, + 0x8306200d, + 0x00002304, + 0x0382e3ff, + 0x0382df20, + 0x11850782, + 0x2f8c0589, + 0x09a01689, + 0x08899918, + 0xcb66a120, + 0x21348709, + 0xed44f6ff, + 0xa1ff2109, + 0x1d872987, + 0xff2407a7, + 0x00ecffc9, + 0x83145771, + 0xc9ff2141, + 0xec260584, + 0x00008dff, + 0x0382c6ff, + 0x0f83e520, + 0x32080384, + 0x04070002, + 0x00830482, + 0x04860400, + 0x04020087, + 0x00890489, + 0x048b0404, + 0x04050099, + 0x009d049c, + 0x04b30414, + 0x071600b7, + 0x00260725, + 0x0002001b, + 0x88870413, + 0x82052027, + 0x008c2c27, + 0x048d0408, + 0x0406008d, + 0x828e048e, + 0x048f224b, + 0x220b828f, + 0x82900490, + 0x0493280b, + 0x04030093, + 0x82940494, + 0x04952251, + 0x220b8295, + 0x82960496, + 0x8297200b, + 0x8401205d, + 0x8201205d, + 0x82b3205d, + 0x04b42275, + 0x226f82b5, + 0x82b604b6, + 0x82b7200b, + 0x8205206f, + 0x0025246f, + 0x82260707, + 0x00062475, + 0x82490102, + 0x00022479, + 0x820b0085, + 0x00592201, + 0x22018214, + 0x8215005a, + 0x002d2201, + 0x22018216, + 0x8217002f, + 0x00322201, + 0x22018218, + 0x82190035, + 0x005d2201, + 0x2001821a, + 0x24b18238, + 0x005e001b, + 0x2801821c, + 0x001e0084, + 0x00290020, + 0x22018221, + 0x82220086, + 0x00872201, + 0x22018225, + 0x82280028, + 0x00902215, + 0x2201822a, + 0x822b0029, + 0x00902201, + 0x2201822c, + 0x822d0029, + 0x00902201, + 0x2201822e, + 0x822f0088, + 0x002b2201, + 0x22018231, + 0x82320030, + 0x00332101, + 0x5c220183, + 0x01823400, + 0x35003622, + 0x91240182, + 0x4d003600, + 0x4e26a182, + 0x83005000, + 0x01828e00, + 0xc800592a, + 0x5a00ce00, + 0xd700d000, + 0xd8224982, + 0x4382ef00, + 0xf300f022, + 0x2c082b82, + 0x00fb00f4, + 0x01fc0038, + 0x015e0000, + 0x00200106, + 0x01210184, + 0x01270021, + 0x00410124, + 0x01420129, + 0x01860042, + 0x004a0143, + 0x014f0187, + 0x2e17824f, + 0x005c015c, + 0x015d0190, + 0x0128005d, + 0x82610161, + 0x016a220b, + 0x22058274, + 0x82900176, + 0x0191222f, + 0x080b8298, + 0x9f019920, + 0xa1018800, + 0x2b00a801, + 0xc501c201, + 0xc6013300, + 0x3600cd01, + 0xd201ce01, + 0xd5019100, + 0x2382d501, + 0xd601d622, + 0xd9224182, + 0x0b82d901, + 0xdc01dc22, + 0xde223b82, + 0x0582df01, + 0xe101e122, + 0xe2220582, + 0x1782e201, + 0xe301e322, + 0xe9220b82, + 0x2982e901, + 0xec01ea22, + 0xed220b82, + 0x4782ed01, + 0xf101f122, + 0xf4221d82, + 0x0582f401, + 0xfa01fa22, + 0xfd220582, + 0x0582fd01, + 0xfe01fe22, + 0xff2e2982, + 0x90000002, + 0x06020302, + 0x0a022900, + 0x0b820a02, + 0x0d020c22, + 0x0e3a0582, + 0x88000e02, + 0x10020f02, + 0x11022800, + 0x2b001202, + 0x16021602, + 0x18025b00, + 0x05821802, + 0x02192008, + 0x02300019, + 0x001c021a, + 0x021e0291, + 0x025f001e, + 0x001f021f, + 0x02250260, + 0x02860029, + 0x825a0239, + 0x0264224d, + 0x340b8264, + 0x00680268, + 0x026b0279, + 0x0254006b, + 0x006d026d, + 0x02720258, + 0x08118272, + 0x7502754a, + 0x79025700, + 0x56007902, + 0x7a027a02, + 0x7b022300, + 0x25007b02, + 0x7c027c02, + 0x7d021d00, + 0x53007d02, + 0x7e027e02, + 0x7f021e00, + 0x55007f02, + 0x80028002, + 0x81027800, + 0x68008302, + 0x85028502, + 0x86026600, + 0x81008602, + 0x87028702, + 0x4a083582, + 0x00880288, + 0x02890265, + 0x021b0089, + 0x008a028a, + 0x028b027a, + 0x0262008b, + 0x008c028c, + 0x028d027b, + 0x027d008d, + 0x008e028e, + 0x02930282, + 0x02630093, + 0x00950295, + 0x02970264, + 0x021f0097, + 0x00980298, + 0x0299026f, + 0x02800099, + 0x829a029a, + 0x029b2811, + 0x0221009b, + 0x829d029d, + 0x029e280b, + 0x0252009e, + 0x82a102a0, + 0x02a4220b, + 0x220582a4, + 0x82a502a5, + 0x02a62265, + 0x225382a6, + 0x82aa02aa, + 0x02ad2211, + 0x220582ad, + 0x82b902b0, + 0x02ba28a1, + 0x027900bb, + 0x82bf02bc, + 0x02c422a7, + 0x220582c7, + 0x82d102ce, + 0x02da2205, + 0x22b382dd, + 0x82e202e2, + 0x02e3220b, + 0x22b982e5, + 0x82ea02e9, + 0x02eb22b9, + 0x22b982ee, + 0x82f502f5, + 0x02f62235, + 0x084182fd, + 0x0003ff2c, + 0x07036800, + 0x55000703, + 0x09030803, + 0x10036500, + 0x1b001c03, + 0x24031d03, + 0x40037d00, + 0x1f004703, + 0x49034803, + 0x5a038000, + 0x0b826403, + 0x70036522, + 0x7d221d82, + 0x0b828803, + 0x8b038a22, + 0x3e080582, + 0x00b103b1, + 0x03b50376, + 0x030700b5, + 0x00b703b7, + 0x03b80351, + 0x034e00b8, + 0x00bc03bc, + 0x03c3030c, + 0x031500c3, + 0x00c403c4, + 0x03c50317, + 0x030a00c5, + 0x00c603c6, + 0x03c80348, + 0x030400c8, + 0x82cb03cb, + 0x03ce221d, + 0x282f82ce, + 0x00d003d0, + 0x03d3034c, + 0x2e1182d3, + 0x00d603d6, + 0x03da0345, + 0x034900da, + 0x82db03db, + 0x03dd2247, + 0x221782dd, + 0x82e003e0, + 0x03e22e47, + 0x031a00e2, + 0x00e403e4, + 0x03e7030f, + 0x227182e7, + 0x82e803e8, + 0x03ea2241, + 0x2e2382ea, + 0x00ed03ed, + 0x03ef036d, + 0x034800ef, + 0x82f003f0, + 0x03f32265, + 0x222382f3, + 0x82f403f4, + 0x03f52ea7, + 0x038a00f5, + 0x00f703f7, + 0x03fb038b, + 0x3d4d82fc, + 0x00fd03fd, + 0x04ff0375, + 0x048f0000, + 0x00010401, + 0x04020405, + 0x04110002, + 0x00030403, + 0x0082044f, + 0x044d0025, + 0x82070405, + 0x0408281d, + 0x040b0008, + 0x820a0409, + 0x040b220b, + 0x2223820b, + 0x820c040c, + 0x040e220b, + 0x2e0b820e, + 0x000f040f, + 0x04100413, + 0x04160010, + 0x82110411, + 0x04122811, + 0x04470012, + 0x82130413, + 0x04142823, + 0x04020014, + 0x82160415, + 0x0417220b, + 0x22298217, + 0x82190418, + 0x041a280b, + 0x0446001a, + 0x821b041b, + 0x041c280b, + 0x044b001c, + 0x821e041d, + 0x041f283b, + 0x0408001f, + 0x82200420, + 0x04212217, + 0x2e118221, + 0x00220422, + 0x04260477, + 0x04100026, + 0x82270427, + 0x04282289, + 0x221d8228, + 0x82290429, + 0x042a2229, + 0x220b822b, + 0x822c042c, + 0x042d227d, + 0x280b822d, + 0x002e042e, + 0x042f0418, + 0x283b822f, + 0x00300430, + 0x0431040d, + 0x28178231, + 0x00320432, + 0x0433048d, + 0x22dd8233, + 0x82340434, + 0x043522dd, + 0x22178235, + 0x82360436, + 0x04372295, + 0x220b8237, + 0x82380438, + 0x04392235, + 0x2235823a, + 0x823b043b, + 0x043c22c5, + 0x22bf823c, + 0x823e043e, + 0x04402835, + 0x04750041, + 0x82420442, + 0x04442223, + 0x222f8244, + 0x82460445, + 0x0447220b, + 0x087d8248, + 0x59045926, + 0x5f044000, + 0x43005f04, + 0x6f046f04, + 0x75043f00, + 0x42007504, + 0x77047704, + 0x82043e00, + 0x89008304, + 0x86048604, + 0x20080582, + 0x00880488, + 0x048a048c, + 0x048e008a, + 0x008c048b, + 0x048d043b, + 0x0439008d, + 0x008e048e, + 0x048f043a, + 0x220b828f, + 0x82900490, + 0x0491220b, + 0x342f8292, + 0x00ad04ad, + 0x04cd043c, + 0x042600cd, + 0x00cf04cf, + 0x04d3042a, + 0x280582d3, + 0x00d604d6, + 0x04db0473, + 0x220b82db, + 0x82dd04dd, + 0xdf3e0805, + 0x6b00df04, + 0xe004e004, + 0xe1042c00, + 0x2e00e104, + 0xe204e204, + 0xe3043100, + 0x3400e304, + 0xe404e404, + 0xe5047400, + 0x3700e504, + 0xe604e604, + 0xe7046c00, + 0x2600fe04, + 0x09050505, + 0x24052a00, + 0x05822c05, + 0x3f053f28, + 0x56057300, + 0x0b827005, + 0x05793e08, + 0x056b0080, + 0x00890582, + 0x058a052c, + 0x052e00a1, + 0x00a505a2, + 0x05a60534, + 0x053700ad, + 0x00b205ae, + 0x05b9056c, + 0x051c00b9, + 0x00bc05bc, + 0x05be057c, + 0x056a00be, + 0x00c005c0, + 0x05c30520, + 0x281782c3, + 0x00c605c6, + 0x05c70569, + 0x081182c7, + 0xca05ca26, + 0xcb056700, + 0x2200cb05, + 0xcc05cc05, + 0xcd052400, + 0x7f00cd05, + 0xce05ce05, + 0xd0057200, + 0x7e00d005, + 0xd205d205, + 0xd3221782, + 0x3b82d305, + 0xd505d522, + 0xd63a1182, + 0x0100d605, + 0xda05da05, + 0xdc050600, + 0x5000dc05, + 0xe405e405, + 0xe7051200, + 0x0582e705, + 0x05e82008, + 0x051400e8, + 0x00e905e9, + 0x05ea054a, + 0x050900ea, + 0x00eb05eb, + 0x05ed0570, + 0x050300ed, + 0x82f005f0, + 0x05f8221d, + 0x220582f8, + 0x82fa05fa, + 0xfb32082f, + 0x6100fb05, + 0xff05ff05, + 0x02067100, + 0x14000206, + 0x05060506, + 0x07064a00, + 0x19000706, + 0x08060806, + 0x09061200, + 0x0e000906, + 0x0c060c06, + 0x0f065000, + 0x23820f06, + 0x11061122, + 0x12341782, + 0x6e001206, + 0x14061406, + 0x15067000, + 0x03001506, + 0x18061806, + 0x19282382, + 0x01001906, + 0x1f061e06, + 0x20222382, + 0x4d822106, + 0x06242c08, + 0x06410024, + 0x00270627, + 0x0629063d, + 0x06440029, + 0x00b706b6, + 0x0725075c, + 0x073a0025, + 0x00260726, + 0x07b40739, + 0x008600b5, + 0x82010000, + 0x030a2403, + 0x19a81402, + 0x2e0c7b5c, + 0x65726754, + 0x6cce006b, + 0x016e7461, + 0x8204000a, + 0xff002423, + 0x821800ff, + 0x820c2007, + 0x24330805, + 0x3c003000, + 0x5f004800, + 0x77006b00, + 0x8f008300, + 0xa7009b00, + 0xbf00b300, + 0xd700cb00, + 0xef00e300, + 0x0701fb00, + 0x1f011301, + 0x01000a00, + 0x20425253, + 0x83004200, + 0x08a7823f, + 0x000d002f, + 0x00250019, + 0x003d0031, + 0x00540049, + 0x006c0060, + 0x00840078, + 0x009c0090, + 0x00b400a8, + 0x00cc00c0, + 0x00e400d8, + 0x01fc00f0, + 0x01140108, + 0x08378620, + 0x0e000230, + 0x26001a00, + 0x3e003200, + 0x55004a00, + 0x6d006100, + 0x85007900, + 0x9d009100, + 0xb500a900, + 0xcd00c100, + 0xe500d900, + 0xfd00f100, + 0x15010901, + 0xb3882101, + 0x03001936, + 0x1b000f00, + 0x33002700, + 0x4b003f00, + 0x62005600, + 0x7a006e00, + 0x4608fb82, + 0x009e0092, + 0x00b600aa, + 0x00ce00c2, + 0x00e600da, + 0x01fe00f2, + 0x0116010a, + 0x002e0022, + 0x48544107, + 0x41660020, + 0x0020455a, + 0x5452439e, + 0x4ed60020, + 0x01205641, + 0x4d534e0e, + 0x53460120, + 0x0120534b, + 0x4b52547e, + 0x86b60120, + 0x043008a1, + 0x1c001000, + 0x34002800, + 0x4c004000, + 0x63005700, + 0x7b006f00, + 0x93008700, + 0xab009f00, + 0xc300b700, + 0xdb00cf00, + 0xf300e700, + 0x0b01ff00, + 0x23011701, + 0x30083786, + 0x00110005, + 0x0029001d, + 0x00410035, + 0x0058004d, + 0x00700064, + 0x0088007c, + 0x00a00094, + 0x00b800ac, + 0x00d000c4, + 0x00e800dc, + 0x010001f4, + 0x0118010c, + 0x08378624, + 0x12000630, + 0x2a001e00, + 0x42003600, + 0x59004e00, + 0x71006500, + 0x89007d00, + 0xa1009500, + 0xb900ad00, + 0xd100c500, + 0xe900dd00, + 0x0101f500, + 0x19010d01, + 0x37862501, + 0x00073008, + 0x001f0013, + 0x0037002b, + 0x004f0043, + 0x0066005a, + 0x007e0072, + 0x0096008a, + 0x00ae00a2, + 0x00c600ba, + 0x00de00d2, + 0x01f600ea, + 0x010e0102, + 0x8626011a, + 0x08300837, + 0x20001400, + 0x38002c00, + 0x50004400, + 0x67005b00, + 0x7f007300, + 0x97008b00, + 0xaf00a300, + 0xc700bb00, + 0xdf00d300, + 0xf700eb00, + 0x0f010301, + 0x27011b01, + 0x30083786, + 0x00150009, + 0x002d0021, + 0x00450039, + 0x005c0051, + 0x00740068, + 0x008c0080, + 0x00a40098, + 0x00bc00b0, + 0x00d400c8, + 0x00ec00e0, + 0x010401f8, + 0x011c0110, + 0x08378628, + 0x16000a30, + 0x2e002200, + 0x46003a00, + 0x5d005200, + 0x75006900, + 0x8d008100, + 0xa5009900, + 0xbd00b100, + 0xd500c900, + 0xed00e100, + 0x0501f900, + 0x1d011101, + 0x37862901, + 0x000b3808, + 0x00230017, + 0x003b002f, + 0x00530047, + 0x006a005e, + 0x00820076, + 0x009a008e, + 0x00b200a6, + 0x00ca00be, + 0x00e200d6, + 0x01fa00ee, + 0x01120106, + 0x012a011e, + 0x6c61612b, + 0x84040774, + 0x840c2005, + 0x84142005, + 0x841c2005, + 0x84242005, + 0x842c2005, + 0x84342005, + 0x843c2005, + 0x84442005, + 0x844c2005, + 0x84542005, + 0x635c2605, + 0x07637332, + 0x20058464, + 0x2005846e, + 0x20058478, + 0x20058482, + 0x2005848c, + 0x20058496, + 0x200584a0, + 0x200584aa, + 0x200584b4, + 0x200584be, + 0x260584c8, + 0x736163d2, + 0x84dc0765, + 0x84e82005, + 0x83f42005, + 0x00082105, + 0x0c200584, + 0x18200584, + 0x24200584, + 0x30200584, + 0x3c200584, + 0x48200584, + 0x54200584, + 0x60260584, + 0x706d6363, + 0x05846c08, + 0x05847e20, + 0x05849020, + 0x0584a220, + 0x0584b420, + 0x0584c620, + 0x0584d820, + 0x0584ea20, + 0x0583fc20, + 0x840e0921, + 0x84202005, + 0x64322605, + 0x096d6f6e, + 0x20058444, + 0x2005844a, + 0x20058450, + 0x20058456, + 0x2005845c, + 0x20058462, + 0x20058468, + 0x2005846e, + 0x20058474, + 0x2005847a, + 0x26058480, + 0x61726686, + 0x848c0963, + 0x84962005, + 0x84a02005, + 0x84aa2005, + 0x84b42005, + 0x84be2005, + 0x84c82005, + 0x84d22005, + 0x84dc2005, + 0x84e62005, + 0x84f02005, + 0x6cfa2605, + 0x0a616769, + 0x20058404, + 0x2005840a, + 0x20058410, + 0x20058416, + 0x2005841c, + 0x20058422, + 0x20058428, + 0x2005842e, + 0x20058434, + 0x2005843a, + 0x26058440, + 0x636f6c46, + 0x844c0a6c, + 0x84522005, + 0x845a2005, + 0x84602005, + 0x84662005, + 0x846e2005, + 0x84762005, + 0x847e2005, + 0x84862005, + 0x848e2005, + 0x6e962605, + 0x0a726d75, + 0x2005849e, + 0x200584a4, + 0x200584aa, + 0x200584b0, + 0x200584b6, + 0x200584bc, + 0x200584c2, + 0x200584c8, + 0x200584ce, + 0x200584d4, + 0x210584da, + 0x06826fe0, + 0x84e60a21, + 0x84ec2005, + 0x84f22005, + 0x84f82005, + 0x83fe2005, + 0x040b2105, + 0x0a200584, + 0x10200584, + 0x16200584, + 0x1c200584, + 0x22200584, + 0x28260584, + 0x6e64726f, + 0x05842e0b, + 0x05843420, + 0x05843a20, + 0x05844020, + 0x05844620, + 0x05844c20, + 0x05845220, + 0x05845820, + 0x05845e20, + 0x05846420, + 0x05846a20, + 0x82707021, + 0x760b218f, + 0x7c200584, + 0x82200584, + 0x88200584, + 0x8e200584, + 0x94200584, + 0x9a200584, + 0xa0200584, + 0xa6200584, + 0xac200584, + 0xb2200584, + 0xb8260584, + 0x746c6173, + 0x0584be0b, + 0x0584da20, + 0x0583f620, + 0x84120c21, + 0x842e2005, + 0x844a2005, + 0x84662005, + 0x84822005, + 0x849e2005, + 0x84ba2005, + 0x84d62005, + 0x73f22605, + 0x0d666e69, + 0x2005840e, + 0x20058414, + 0x2005841a, + 0x20058420, + 0x20058426, + 0x2005842c, + 0x20058432, + 0x20058438, + 0x2005843e, + 0x20058444, + 0x2605844a, + 0x636d7350, + 0x84560d70, + 0x84642005, + 0x84722005, + 0x84802005, + 0x848e2005, + 0x849c2005, + 0x84aa2005, + 0x84b82005, + 0x84c62005, + 0x84d42005, + 0x84e22005, + 0x73f02605, + 0x0d313073, + 0x210583fe, + 0x0584080e, + 0x05841220, + 0x05841c20, + 0x05842620, + 0x05843020, + 0x05843a20, + 0x05844420, + 0x05844e20, + 0x05845820, + 0x05846220, + 0x05826c20, + 0x760e3222, + 0x7e200584, + 0x86200584, + 0x8e200584, + 0x96200584, + 0x9e200584, + 0xa6200584, + 0xae200584, + 0xb6200584, + 0xbe200584, + 0xc6200584, + 0xce200584, + 0x33220582, + 0x0584d60e, + 0x0584de20, + 0x0584e620, + 0x0584ee20, + 0x0584f620, + 0x3322ad83, + 0x0b83060f, + 0x840e0f21, + 0x84162005, + 0x841e2005, + 0x22b38305, + 0x822e0f33, + 0x0f34220b, + 0x20058436, + 0x20058440, + 0x2005844a, + 0x20058454, + 0x2005845e, + 0x20058468, + 0x20058472, + 0x8305847c, + 0x0f3422b3, + 0x200b8490, + 0x2005849a, + 0x210582a4, + 0xad830f35, + 0xb40f3522, + 0xba200b84, + 0xc0200584, + 0xb3830584, + 0xcc0f3522, + 0xd2200b84, + 0xd8200584, + 0xb9830584, + 0xe40f3522, + 0xea200b84, + 0xf0250584, + 0x38317373, + 0x82bf820f, + 0x83fc2005, + 0x0210210b, + 0x08200584, + 0xc5820584, + 0x10383123, + 0x200b8414, + 0x2005841a, + 0x82058420, + 0x201782cb, + 0x200b842c, + 0x20058432, + 0x22058238, + 0x843e1039, + 0x84442005, + 0x23d78205, + 0x50103931, + 0x56200b84, + 0x5c200584, + 0x62200584, + 0xe3820584, + 0x6e201d82, + 0x74200b84, + 0x7a200584, + 0x80260584, + 0x73627573, + 0x05848610, + 0x05848c20, + 0x05849220, + 0x05849820, + 0x05849e20, + 0x0584a420, + 0x0584aa20, + 0x0584b020, + 0x0584b620, + 0x0584bc20, + 0x0584c220, + 0x7573c826, + 0xce107370, + 0xda200584, + 0xe6200584, + 0xf2200584, + 0xfe200584, + 0x11210583, + 0x2005840a, + 0x20058416, + 0x20058422, + 0x2005842e, + 0x2005843a, + 0x26058446, + 0x72657a52, + 0x845e116f, + 0x84642005, + 0x846a2005, + 0x84702005, + 0x84762005, + 0x847c2005, + 0x84822005, + 0x84882005, + 0x848e2005, + 0x84942005, + 0x849a2005, + 0x00a02405, + 0x82020000, + 0xda012003, + 0x00032607, + 0x00230022, + 0xed618224, + 0x00042809, + 0x001d001c, + 0x821f001e, + 0x830b4079, + 0x0300072e, + 0x05000400, + 0x07000600, + 0x09000800, + 0x11409582, + 0x000122c5, + 0xc1cb8212, + 0x00032605, + 0x00130011, + 0xed4b8214, + 0x00012209, + 0xc1bf8434, + 0x820f2005, + 0x00022447, + 0x8410000f, + 0x840e204f, + 0x840a2005, + 0x000a2213, + 0x2007860b, + 0x87078e0c, + 0x860d2017, + 0x83078717, + 0x00012227, + 0xc1438411, + 0x841b2005, + 0x2005c147, + 0xc1478415, + 0x841a2005, + 0x3805bf47, + 0x000d000c, + 0x0029001e, + 0x002c002a, + 0x002e002d, + 0x0030002f, + 0x00320031, + 0x105d8233, + 0x33011b00, + 0x19000125, + 0xc1000000, + 0x00052a05, + 0x00210020, + 0x00250023, + 0x404f8226, + 0x2a2b960d, + 0x00030058, + 0x002a0029, + 0x884e2a2b, + 0x88442009, + 0x883a2009, + 0x88302009, + 0x88262009, + 0x881c2009, + 0x88122009, + 0x87082009, + 0xfe292109, + 0xf4200988, + 0xea200988, + 0x0c282788, + 0x2c000200, + 0x042a2d00, + 0x29210785, + 0x200786fc, + 0x200786f4, + 0x200786ec, + 0x200786e4, + 0x200786dc, + 0x200786d4, + 0x200786cc, + 0x200786c4, + 0x200786bc, + 0x200786b4, + 0x240782f2, + 0x292f002e, + 0x200786ea, + 0x200786e2, + 0x200786da, + 0x200786d2, + 0x200786ca, + 0x200786c2, + 0x200786ba, + 0x200786b2, + 0x200786aa, + 0x200786a2, + 0x2007869a, + 0x26c982b6, + 0x00310030, + 0x88ac2932, + 0x88a22009, + 0x88982009, + 0x888e2009, + 0x88842009, + 0x887a2009, + 0x88702009, + 0x88662009, + 0x885c2009, + 0x88522009, + 0x87482009, + 0x98282709, + 0x27000100, + 0x05849228, + 0x05848c20, + 0x05848620, + 0x05848020, + 0x05847a20, + 0x05847420, + 0x05846e20, + 0x05846820, + 0x05846220, + 0x05845c20, + 0x05835620, + 0x82282221, + 0x220b2205, + 0x20058422, + 0x2005841c, + 0x20058416, + 0x20058410, + 0x2005840a, + 0x21058304, + 0x0584fe21, + 0x0584f820, + 0x0584f220, + 0x0584ec20, + 0x0583e620, + 0x823e2921, + 0x291e2205, + 0x20058438, + 0x20058432, + 0x2005842c, + 0x20058426, + 0x20058420, + 0x2005841a, + 0x20058414, + 0x2005840e, + 0x20058408, + 0x21058302, + 0x0583fc28, + 0x43447143, + 0x042805b3, + 0x16001500, + 0x18001700, + 0x0b405382, + 0x00012283, + 0xbddd8428, + 0x38720805, + 0x7a007200, + 0x8a008200, + 0xa6009a00, + 0xb600ae00, + 0xd000be00, + 0xe600de00, + 0xf600ee00, + 0x0601fe00, + 0x16010e01, + 0x26011e01, + 0x3a012e01, + 0x4a014201, + 0x5a015201, + 0x6a016201, + 0x7a017201, + 0x8a018201, + 0x9a019201, + 0xaa01a201, + 0xba01b201, + 0xca01c201, + 0xda01d201, + 0xea01e201, + 0xfa01f201, + 0x0a020202, + 0x1a021202, + 0x2a022202, + 0x3a023202, + 0x4a024202, + 0xb5830100, + 0x00922723, + 0x2b078303, + 0x0200062d, + 0x01000000, + 0x0600d001, + 0x052a0782, + 0xc00dae0d, + 0xe40dd20d, + 0x0f84f60d, + 0xf80d0328, + 0x200e0c0e, + 0x1b820400, + 0x260e0122, + 0x0f210785, + 0x21078528, + 0x23843a11, + 0xba1b062c, + 0xde1bcc1b, + 0x021cf01b, + 0x1184141c, + 0x141c0427, + 0x381c261c, + 0x216b861c, + 0x73854e1c, + 0x865a1c21, + 0x86582007, + 0x86562007, + 0x9e542007, + 0x8670201f, + 0x848a201f, + 0x1c03265d, + 0x1c9a1c88, + 0x201386ac, + 0x200786b4, + 0x200786ec, + 0x210785ea, + 0x07860a1d, + 0x07861020, + 0x07863020, + 0x1d217386, + 0x200f867c, + 0x2007867e, + 0x200786a4, + 0x200786a2, + 0x200786a0, + 0x210785e6, + 0x0785da1e, + 0x86462221, + 0x86442007, + 0x856a2007, + 0x40242107, + 0x27860786, + 0x8ed82421, + 0x86ee200f, + 0x20a7860f, + 0x210f8624, + 0x17852225, + 0x86242521, + 0x86362007, + 0x86382007, + 0x41522007, + 0x2521059f, + 0x200f8656, + 0x057b41b0, + 0x85ae2521, + 0x7a302107, + 0x30211785, + 0x27078684, + 0x300100ba, + 0x026e01d6, + 0x17475a19, + 0x032c0209, + 0x033c0334, + 0x034c0344, + 0x035c0354, + 0x036c0364, + 0x037a0374, + 0x03860380, + 0x0392038c, + 0x039e0398, + 0x03aa03a4, + 0x03b603b0, + 0x03c203bc, + 0x03ce03c8, + 0x03da03d4, + 0x03e603e0, + 0x03f203ec, + 0x04fe03f8, + 0x040a0404, + 0x041a0412, + 0x042a0422, + 0x04380432, + 0x04460440, + 0x0452044c, + 0x045e0458, + 0x046a0464, + 0x04760470, + 0x0482047c, + 0x048e0488, + 0x049a0494, + 0x04a604a0, + 0x04b204ac, + 0x04be04b8, + 0x04ca04c4, + 0x04d604d0, + 0x04e204dc, + 0x04ee04e8, + 0x05fa04f4, + 0x05080500, + 0x0514050e, + 0x0520051a, + 0x052c0526, + 0x05380532, + 0x0544053e, + 0x0550054a, + 0x055c0556, + 0x05680562, + 0x0574056e, + 0x0580057a, + 0x058c0586, + 0x059c0594, + 0x05ac05a4, + 0x05ba05b4, + 0x05c805c2, + 0x05d405ce, + 0x05e005da, + 0x05ec05e6, + 0x05f805f2, + 0x060406fe, + 0x0612060a, + 0x061e0618, + 0x062a0624, + 0x06360630, + 0x0642063c, + 0x064e0648, + 0x065a0654, + 0xe16c1960, + 0x8a4a090c, + 0x96069006, + 0xa2069c06, + 0xb006a806, + 0xc006b806, + 0xce06c806, + 0xda06d406, + 0xe606e006, + 0xf206ec06, + 0xfe06f806, + 0x0a070407, + 0x16071007, + 0x22071c07, + 0x2e072807, + 0x3a073407, + 0x46074007, + 0x52074c07, + 0x5e075807, + 0x6a076407, + 0x76077007, + 0x82077c07, + 0x8e078807, + 0x9a079407, + 0xa807a007, + 0xb807b007, + 0xc807c007, + 0xd807d007, + 0xe807e007, + 0xf607f007, + 0x0208fc07, + 0x0e080808, + 0x1a081408, + 0x26082008, + 0x32082c08, + 0x3e083808, + 0x4a084408, + 0x56085008, + 0x62085c08, + 0x6e086808, + 0x7a087408, + 0x86088008, + 0x96088e08, + 0xa6089e08, + 0xb408ae08, + 0xc208bc08, + 0xce08c808, + 0xda08d408, + 0xe608e008, + 0xf208ec08, + 0xfe08f808, + 0x0a090409, + 0x16091009, + 0x22091c09, + 0x2e092809, + 0x3a093409, + 0x46094009, + 0x52094c09, + 0x5e095809, + 0x6a096409, + 0x76097009, + 0x84097c09, + 0x90098a09, + 0x9c099609, + 0xa809a209, + 0xb409ae09, + 0xc009ba09, + 0xcc09c609, + 0xd809d209, + 0xe409de09, + 0xf009ea09, + 0xfc09f609, + 0x080a020a, + 0x180a100a, + 0x280a200a, + 0x360a300a, + 0x440a3e0a, + 0x500a4a0a, + 0x5c0a560a, + 0x680a620a, + 0x740a6e0a, + 0x800a7a0a, + 0x8e0a860a, + 0x9a0a940a, + 0x5c19a00a, + 0x61080b8b, + 0xd00aca0a, + 0xdc0ad60a, + 0xe80ae20a, + 0xf40aee0a, + 0x000bfa0a, + 0x0c0b060b, + 0x180b120b, + 0x240b1e0b, + 0x340b2c0b, + 0x440b3c0b, + 0x500b4a0b, + 0x5c0b560b, + 0x680b620b, + 0x740b6e0b, + 0x800b7a0b, + 0x8c0b860b, + 0x980b920b, + 0xa40b9e0b, + 0xb00baa0b, + 0xbc0bb60b, + 0xc80bc20b, + 0xd40bce0b, + 0xe00bda0b, + 0x02000200, + 0x05843b07, + 0x05843e20, + 0x05844120, + 0x05844320, + 0x05844f20, + 0x05844520, + 0x05844a20, + 0x05845320, + 0x05845720, + 0x05846920, + 0x03005122, + 0x41224182, + 0x07863e07, + 0x07863b20, + 0x43201787, + 0x69200f86, + 0x4a200784, + 0x4a202786, + 0x37837382, + 0x85074a21, + 0x074a2127, + 0x4a212785, + 0x20558307, + 0x2225824b, + 0x864e0002, + 0x82452005, + 0x07032267, + 0x2005844d, + 0x22058277, + 0x846e0704, + 0x22af8305, + 0x84410704, + 0x8457200b, + 0x21238305, + 0x0b830705, + 0x2f840520, + 0x4d840520, + 0x83070521, + 0x84062035, + 0x840620e5, + 0x84062053, + 0x84062035, + 0x07062229, + 0x213b824f, + 0x65830706, + 0x83070621, + 0x840620e5, + 0x8406203b, + 0x8206203b, + 0x0002229f, + 0x829d8406, + 0x83bd8435, + 0x83e58307, + 0x82512007, + 0x200783d5, + 0x83078643, + 0x866e20bd, + 0x84452025, + 0x8407206b, + 0x8408204d, + 0x8408200b, + 0x84082077, + 0x86082065, + 0x826c2017, + 0x8408207d, + 0x84082089, + 0x82082083, + 0x0002226b, + 0x20298409, + 0x22838409, + 0x82740709, + 0x84092023, + 0x840a20c5, + 0x840a20c5, + 0x840a204d, + 0x840a2023, + 0x840a202f, + 0x840a20c5, + 0x840a2041, + 0x840a204d, + 0x840a20b9, + 0x868b2041, + 0x20dd832f, + 0x2135840b, + 0x7783070c, + 0x1d840c20, + 0x59840c20, + 0x23840d20, + 0x3b840d20, + 0x1d840d20, + 0x1d820d20, + 0x82000321, + 0x20558405, + 0x2025840d, + 0x2025840e, + 0x20bb840e, + 0x203d840e, + 0x2011840f, + 0x2097840f, + 0x203d840f, + 0x2091840f, + 0x2043840f, + 0x2029840f, + 0x2029860f, + 0x20c78277, + 0x20298410, + 0x20358410, + 0x208b8410, + 0x202f8410, + 0x20c18410, + 0x226b8410, + 0x84550710, + 0x84572029, + 0x84692005, + 0x00512305, + 0x2f820003, + 0x07853782, + 0x0f863b20, + 0x43201787, + 0x2d850f86, + 0x0d844a20, + 0x20058141, + 0x206b84b8, + 0x227784b8, + 0x825107b8, + 0x84b8204d, + 0x84b82071, + 0x84be2095, + 0x8411201d, + 0x841320a7, + 0x8413200b, + 0x861320c5, + 0x826c2011, + 0x8213202f, + 0x00032129, + 0x9d840582, + 0x83071321, + 0x841420c7, + 0x8414202b, + 0x841420c1, + 0x07142231, + 0x202b826e, + 0x20f78414, + 0x203d8414, + 0x20618414, + 0x201d8415, + 0x20118415, + 0x20238415, + 0x20238415, + 0x831d8615, + 0x8415204d, + 0x841620fd, + 0x841620a3, + 0x84162059, + 0x84162059, + 0x861620a9, + 0x8245201d, + 0x0716225f, + 0x2005844a, + 0x20058453, + 0x20058455, + 0x82ed8257, + 0x219d8223, + 0x07830003, + 0x0f863e20, + 0x3b201787, + 0x69202584, + 0x51200584, + 0xe8200582, + 0xe8206184, + 0xe8216d84, + 0x20118507, + 0x83178443, + 0x84ee2023, + 0x8418201d, + 0x8618201d, + 0x8241200b, + 0x8418201d, + 0x841a2085, + 0x841a2017, + 0x841a2017, + 0x861a20a3, + 0x824d2017, + 0x841a2023, + 0x841a20d3, + 0x841a2053, + 0x841b20bb, + 0x071b2229, + 0x211d8257, + 0x2383071b, + 0x23841b20, + 0x83071b21, + 0x071c22f7, + 0x2217823a, + 0x843d071c, + 0x84402005, + 0x84422005, + 0x844e2005, + 0x84442005, + 0x84482005, + 0x84522005, + 0x84562005, + 0x22a78305, + 0x8250071c, + 0x071c22e7, + 0x213d8240, + 0x07830003, + 0x0f863a20, + 0x42201787, + 0x69200f86, + 0x48200784, + 0x48202786, + 0x2f837382, + 0x3f864820, + 0x85074821, + 0x83482027, + 0x1b012197, + 0x02222582, + 0x05861e01, + 0x6d824420, + 0xb5841d20, + 0xaf841d20, + 0x6d071e22, + 0x1d841182, + 0x071e0023, + 0x200b8440, + 0x20058456, + 0x2105824c, + 0x0b83071f, + 0x2f841f20, + 0xe5841f20, + 0x35841f20, + 0xe5842020, + 0xe5842020, + 0x35842020, + 0x29842020, + 0x4e072022, + 0x20213582, + 0x21658307, + 0xe5830720, + 0x4c072022, + 0x69201184, + 0x50200584, + 0x42200584, + 0x3582bd82, + 0x0783bd84, + 0x0783e583, + 0x17865020, + 0x33821f87, + 0x863e0121, + 0x84442025, + 0x8421206b, + 0x8422204d, + 0x8422200b, + 0x84222077, + 0x86222065, + 0x826c2017, + 0x8422205f, + 0x84222089, + 0x07222283, + 0x22118242, + 0x84410723, + 0x214f8205, + 0xbf842300, + 0x74072326, + 0x5c010200, + 0x0582c583, + 0x0b843d20, + 0x05844020, + 0x05844220, + 0x05844e20, + 0x05844420, + 0x05845620, + 0x2421b983, + 0x21418207, + 0x7d836502, + 0xdd823582, + 0x84d60121, + 0x07262183, + 0x26207783, + 0x00211d83, + 0x225f8426, + 0x823e0727, + 0x84272071, + 0x84272089, + 0x8227201d, + 0x0003211d, + 0x07210582, + 0x20198445, + 0x20058277, + 0x20c78428, + 0x20bb8428, + 0x203d8428, + 0x20118429, + 0x21978329, + 0x3d842900, + 0xc1842920, + 0x43842920, + 0x29842920, + 0x29862920, + 0x2a204183, + 0x2a202984, + 0x2a203584, + 0x2a208b84, + 0x2a212f84, + 0x22c18207, + 0x82072a00, + 0x200582c1, + 0x206b8254, + 0x204d842a, + 0x243b842a, + 0x0050072a, + 0x42178203, + 0x37820567, + 0x0f854582, + 0x42201787, + 0xef821f86, + 0x48202782, + 0x44200d84, + 0x8920f784, + 0x3a240586, + 0x89010200, + 0x05834782, + 0x0b844220, + 0x01212b82, + 0x2089848f, + 0x20a7842b, + 0x200b842d, + 0x20b9842d, + 0x207d842d, + 0x2017862d, + 0x224f8269, + 0x8469072d, + 0x072d219d, + 0x2e20c783, + 0x2e202b84, + 0x2e20c184, + 0x2e222b84, + 0xb5826d07, + 0x3d842e20, + 0x37842e20, + 0xbb842e20, + 0x1d842f20, + 0x11842f20, + 0x23842f20, + 0x23842f20, + 0x1d862f20, + 0x2f204d83, + 0x3020fd84, + 0x0222d582, + 0x59843000, + 0x59843020, + 0x82073021, + 0x201182a9, + 0x2059824e, + 0x227d8430, + 0x84480730, + 0x8452200b, + 0x84542005, + 0x82562005, + 0x0730229d, + 0x201f824e, + 0x822b8303, + 0x8707853f, + 0x82f98217, + 0x82ed8217, + 0x82502005, + 0x82b920f9, + 0x01022221, + 0x826d83b9, + 0x82118505, + 0x820b8267, + 0xbf012123, + 0x32207f84, + 0x32208b84, + 0x40200b86, + 0x32206782, + 0x3420a384, + 0x34201784, + 0x34201784, + 0x3420a384, + 0x4c201786, + 0x34202382, + 0x3421d384, + 0x21538207, + 0xbb843400, + 0x29843520, + 0x56073522, + 0x35211d82, + 0x20238307, + 0x21238435, + 0xf7830735, + 0x4f070a22, + 0x5c208f82, + 0x032c4182, + 0x01000000, + 0x0100de25, + 0x01006227, + 0x02200b82, + 0x2505cf4d, + 0x01007227, + 0x118b1228, + 0x82422821, + 0xa24e2011, + 0x8a3c2011, + 0x28022423, + 0x823e2838, + 0x84ca205b, + 0x85352013, + 0x3028275b, + 0xf4260200, + 0x1384b627, + 0x13863620, + 0x25821c20, + 0x1186a220, + 0x1828012e, + 0x10000500, + 0x64003a00, + 0xd800a600, + 0x0c300b82, + 0x18001200, + 0x24001e00, + 0x02009107, + 0x8f073a07, + 0x3d220582, + 0x05829507, + 0x9f074222, + 0x48220582, + 0x05829307, + 0x298c5020, + 0x29849920, + 0x29849720, + 0x29849d20, + 0x05829b20, + 0x83075021, + 0x007e220b, + 0x29518708, + 0x30002a00, + 0x3c003600, + 0x2f848707, + 0x05828920, + 0x85073c22, + 0x81203584, + 0x3f220582, + 0x3b848a07, + 0x05828b20, + 0x8d074422, + 0x56200582, + 0x7e301184, + 0x0e000600, + 0x1a001400, + 0x26002000, + 0xa2072c00, + 0x05833d84, + 0xa1073c22, + 0x05833d84, + 0xa3073f22, + 0x05833d84, + 0xa520318f, + 0x05833184, + 0xa4073c22, + 0x05833184, + 0xa6073f22, + 0x05833184, + 0x007e3e08, + 0x001c2701, + 0x003c001b, + 0x0078005a, + 0x00a00082, + 0x00dc00be, + 0x010401fa, + 0x01340122, + 0x015c0152, + 0x0184017a, + 0x01ac01a2, + 0x01c001b6, + 0x01d401ca, + 0x01e801de, + 0x02fc01f2, + 0x00100206, + 0x2ae38203, + 0x00180010, + 0x0703004d, + 0x846f073d, + 0x076f2407, + 0x824b003d, + 0x886f205f, + 0x8670201d, + 0x8307831d, + 0x846e201d, + 0x0001241d, + 0x827a0004, + 0x88422009, + 0x868c2027, + 0x83078327, + 0x8c8b2027, + 0x86bf2045, + 0x8307831d, + 0x8cbe201d, + 0x86ef201d, + 0x8307831d, + 0x8bee201d, + 0x1d01211d, + 0x07841d85, + 0x01211d82, + 0x821d841b, + 0x29012181, + 0x56200982, + 0x01218187, + 0x83278640, + 0x20278307, + 0x2627843e, + 0x00060002, + 0x824a010c, + 0x0142220b, + 0x20058247, + 0x202f886d, + 0x832f865a, + 0x202f8307, + 0x20578859, + 0x20578c63, + 0x83278690, + 0x20278307, + 0x2027888f, + 0x20278ca1, + 0x832786c1, + 0x20278307, + 0x082941bf, + 0x09824d20, + 0x82003d21, + 0x700021b1, + 0x8c200988, + 0x27830988, + 0xef201d85, + 0xeb821387, + 0x84070221, + 0x87d58213, + 0x885a2009, + 0x8890201d, + 0x88c12009, + 0x00e52409, + 0x83b80602, + 0x57022163, + 0x4c08e584, + 0x003c2501, + 0x01320016, + 0x02860144, + 0x03f20288, + 0x033e0334, + 0x058a0488, + 0x06ac056a, + 0x0706077c, + 0x075a0748, + 0x08b408e4, + 0x093809f6, + 0x0ad4097a, + 0x001e002e, + 0x0046003e, + 0x0056004e, + 0x0066005e, + 0x0076006e, + 0x0086007e, + 0x0096008e, + 0x0831529e, + 0x00c42208, + 0x00d000ca, + 0x00dc00d6, + 0x00e800e2, + 0x00f400ee, + 0x010001fa, + 0x020c0106, + 0x030300f7, + 0x025d0797, + 0x220784f6, + 0x84fb025f, + 0x02a12207, + 0x220784f9, + 0x84fd02a2, + 0x02a32207, + 0x220784fa, + 0x84f802a4, + 0x02a52207, + 0x200784fc, + 0x213f83a6, + 0x3f858207, + 0x3f840782, + 0x3f840782, + 0x3f840782, + 0x3f840782, + 0x3f840782, + 0x3f840782, + 0xa6280782, + 0x0200f502, + 0xb2029703, + 0x3a22fb82, + 0x0582b302, + 0xbb023d22, + 0x44220582, + 0x0582ba02, + 0xb1024822, + 0x5d220582, + 0x0582b002, + 0x29835f20, + 0x02820723, + 0x220b82b7, + 0x82b502a1, + 0x02a22205, + 0x220582b9, + 0x82b602a3, + 0x02a42205, + 0x220582b4, + 0x82b802a5, + 0x44a62005, + 0x02211103, + 0x205f84be, + 0x205f84bf, + 0x205384bd, + 0x205384bc, + 0x204d84c3, + 0x204d84c1, + 0x204784c2, + 0x300582c0, + 0x001c00a5, + 0x0042003a, + 0x0052004a, + 0x0062005a, + 0x0883536a, + 0x00922308, + 0x00a2009a, + 0x00b200aa, + 0x00c000ba, + 0x00cc00c6, + 0x00d800d2, + 0x00e400de, + 0x00f000ea, + 0x03fc00f6, + 0x4f410000, + 0x84ff2005, + 0x035f2207, + 0x22078404, + 0x840203a1, + 0x03a22207, + 0x22078406, + 0x840303a3, + 0x03a42207, + 0x22078401, + 0x840503a5, + 0x83a62007, + 0x8207243f, + 0x82025d07, + 0x8407823f, + 0x8407823f, + 0x8407823f, + 0x8407823f, + 0x8407823f, + 0x8407823f, + 0x2807823f, + 0x00fe02a6, + 0x02970302, + 0x20ef84c6, + 0x20ef84c7, + 0x220582c5, + 0x84c4025d, + 0x231d82ef, + 0xcb028207, + 0xc920f584, + 0xcd20f584, + 0xa3220582, + 0xfb84ca02, + 0x0582c820, + 0xcc02a522, + 0xa6220582, + 0x73190d00, + 0x402e0cab, + 0x4c004600, + 0x58005200, + 0x64005e00, + 0x6382d702, + 0xd002a222, + 0xd1206384, + 0xd9206384, + 0x44220582, + 0x0582d802, + 0x84024822, + 0x4e220582, + 0x7584cf02, + 0x7584ce20, + 0x6f84d520, + 0x6f84d320, + 0x6984d420, + 0x6984d220, + 0xad41d620, + 0x84dc2016, + 0x84dd2059, + 0x84db2059, + 0x84da2047, + 0x84e12047, + 0x84df2047, + 0x84e02047, + 0x82de2047, + 0x00a52605, + 0x02040001, + 0x220982e2, + 0x4509005d, + 0x002909b9, + 0x00380032, + 0x0244003e, + 0x204d84e4, + 0x204d84e5, + 0x20a784ea, + 0x20a784e9, + 0x20a78487, + 0x205f84e3, + 0x205984e7, + 0x205984e6, + 0x200582e8, + 0x3a0142a3, + 0x03000928, + 0x5d079703, + 0x07840803, + 0x0d035f22, + 0xa1220784, + 0x07840b03, + 0x0f03a222, + 0xa3220784, + 0x07840c03, + 0x0a03a422, + 0xa5220784, + 0x07840e03, + 0x0903a626, + 0x82070300, + 0x07823f85, + 0x07823f84, + 0x07823f84, + 0x07823f84, + 0x07823f84, + 0x07823f84, + 0x07823f84, + 0x0703a628, + 0x97030200, + 0x0582eb02, + 0xf1029922, + 0x9f220582, + 0xd182ed02, + 0xee023a22, + 0x3d220582, + 0x0582ec02, + 0x23835d20, + 0x02820723, + 0x20f584f2, + 0x20f584f0, + 0x220582f4, + 0x82ef02a3, + 0x02a52205, + 0x080582f3, + 0x1900a623, + 0x3c003400, + 0x4c004400, + 0x5c005400, + 0x6c006400, + 0x7c007400, + 0x8c008400, + 0x98009200, + 0xa4009e00, + 0x4f751900, + 0x00ce260b, + 0x03da00d4, + 0x22bb8468, + 0x8469033a, + 0x033d2207, + 0x22078467, + 0x8466035d, + 0x035f2207, + 0x22078470, + 0x846d037e, + 0x03a12207, + 0x2207846b, + 0x846f03a2, + 0x03a32207, + 0x2207846c, + 0x846a03a4, + 0x03a52207, + 0x2807846e, + 0x001203a6, + 0x033a0702, + 0x22058213, + 0x821b033d, + 0x03442205, + 0x2205821a, + 0x84110348, + 0x821020cd, + 0x035f2205, + 0x2205821c, + 0x8265037e, + 0x03822205, + 0x22058217, + 0x821503a1, + 0x03a22205, + 0x22058219, + 0x821603a3, + 0x03a42205, + 0x22058214, + 0x421803a5, + 0x03211577, + 0x2065841f, + 0x20658420, + 0x2059841e, + 0x2059841d, + 0x204d8424, + 0x204d8422, + 0x20478423, + 0x08058221, + 0x1700a532, + 0x38003000, + 0x48004000, + 0x58005000, + 0x68006000, + 0x78007000, + 0x88008000, + 0x94008e00, + 0xa0009a00, + 0xac00a600, + 0xb800b200, + 0xc400be00, + 0x7403ca00, + 0x3a22cd84, + 0x07847503, + 0x73033d22, + 0x5d220784, + 0x07847203, + 0x7c035f22, + 0x7e220784, + 0x07847903, + 0x7703a122, + 0xa2220784, + 0x07847b03, + 0x7803a322, + 0xa4220784, + 0x07847603, + 0x7a03a522, + 0xa6220784, + 0xb7842703, + 0xb7842820, + 0xb7842620, + 0xb7842520, + 0x05822f20, + 0x71037e22, + 0x82220582, + 0xc3842c03, + 0xc3842a20, + 0x05822e20, + 0x2b03a322, + 0x2920c984, + 0xa5220582, + 0x05822d03, + 0x1100a624, + 0x35492400, + 0x42002107, + 0x4e2cd582, + 0x5a005400, + 0x66006000, + 0x72006c00, + 0x7e24d982, + 0x32038400, + 0x33206b84, + 0x3b206b84, + 0x44220582, + 0x05823a03, + 0xa9024822, + 0x4e220582, + 0x7d843103, + 0x7d843020, + 0x7d843c20, + 0x05823e20, + 0x3d038522, + 0x87220582, + 0x05823f03, + 0x37038a22, + 0x35208984, + 0x39208984, + 0x36208984, + 0x34208984, + 0x38208984, + 0x20169b41, + 0x20778442, + 0x20778443, + 0x20658441, + 0x20658440, + 0x204d8447, + 0x204d8445, + 0x20478446, + 0x28058244, + 0x000200a5, + 0x030c0006, + 0x20298449, + 0x20058248, + 0x20dda45f, + 0x2065844c, + 0x2065844d, + 0x20dd8456, + 0x20dd8455, + 0x20dd84ac, + 0x204d844b, + 0x2077844a, + 0x20dd8454, + 0x20dd8458, + 0x20dd8457, + 0x20dd8459, + 0x208f8451, + 0x208f844f, + 0x20dd8453, + 0x20958450, + 0x20dd844e, + 0x42dd8452, + 0x80282f37, + 0x82070300, + 0x81033a07, + 0x3d220784, + 0x07847f03, + 0x7e035d22, + 0x5f220784, + 0x07848803, + 0x85037e22, + 0xa1220784, + 0x07848303, + 0x8703a222, + 0xa3220784, + 0x07848403, + 0x8203a422, + 0xa5220784, + 0x07848603, + 0x5c03a622, + 0x3a228d82, + 0xed845d03, + 0xdb845b20, + 0xdb845a20, + 0xdb846420, + 0x05827d20, + 0x61038222, + 0x5f20cf84, + 0x6320cf84, + 0x6020cf84, + 0x5e20cf84, + 0x6220cf84, + 0x2115ad41, + 0x1782f702, + 0xf6025d22, + 0x5f220582, + 0x0582fb02, + 0xf902a122, + 0xa2220582, + 0x0582fd02, + 0xfa02a322, + 0xa4220582, + 0x0582f802, + 0xfc02a522, + 0x03214195, + 0x20418400, + 0x208f84ff, + 0x20838404, + 0x20838402, + 0x20838406, + 0x20838403, + 0x20838401, + 0x20419605, + 0x20d18409, + 0x20418408, + 0x2041840d, + 0x2041840b, + 0x2041840f, + 0x2041840c, + 0x2041840a, + 0x2441840e, + 0x0018000b, + 0x1101431e, + 0x82680321, + 0x033a221d, + 0x22058269, + 0x8467033d, + 0x84662053, + 0x82702053, + 0x037e2205, + 0x2059846d, + 0x2059846b, + 0x2059846f, + 0x2059846c, + 0x2059846a, + 0x20599c6e, + 0x20598474, + 0x20598475, + 0x20598473, + 0x20598472, + 0x2059847c, + 0x20598479, + 0x20598477, + 0x2059847b, + 0x20598478, + 0x20598476, + 0x20599c7a, + 0x20598480, + 0x20598481, + 0x2059847f, + 0x2059847e, + 0x20598488, + 0x20598485, + 0x20598483, + 0x20598487, + 0x20598484, + 0x20598482, + 0x26598486, + 0x00000003, + 0x85e41a01, + 0x4d0b8203, + 0x1a2106cf, + 0x821182d8, + 0x20118a03, + 0x821182cc, + 0x22118603, + 0x82c01a01, + 0x82ae200f, + 0x8801200d, + 0x82b62011, + 0x8ca22011, + 0x82aa2011, + 0x8c962011, + 0x009e2411, + 0x8b081b01, + 0x201b2111, + 0xf6202382, + 0x3820118c, + 0x4c202382, + 0x0020118a, + 0x3a200f82, + 0x26210382, + 0x326b8500, + 0x002e1b02, + 0x01e10107, + 0x01ed01db, + 0x021402f4, + 0x82dd0106, + 0x822c201d, + 0x1901241d, + 0x82a80484, + 0x012e230b, + 0x25830034, + 0x3c070428, + 0x5d073f07, + 0x1f875f07, + 0x4b203982, + 0x0e221984, + 0xd0197006, + 0x7c261287, + 0x7a067d06, + 0x21827b06, + 0x0e000c2b, + 0x63066206, + 0x65066406, + 0xc5d01906, + 0x066e260b, + 0x066c066f, + 0x244f826d, + 0x00350200, + 0x82078303, + 0x860a2003, + 0x833720ad, + 0xfe1a2111, + 0x0e201182, + 0x0224118a, + 0x061b101b, + 0xfc20e582, + 0x02281388, + 0x1d00021b, + 0x9c069b06, + 0x30b3d019, + 0xbb06ba24, + 0x4b82bc06, + 0x06d82a08, + 0x1a02007f, + 0x061100dc, + 0x06410640, + 0x06430642, + 0x06450644, + 0x06470646, + 0x06490648, + 0x0650064f, + 0x064e064d, + 0x064b064a, + 0x2a27824c, + 0x060400d6, + 0x06c106c0, + 0x82c306c2, + 0x82a6200d, + 0x19512035, + 0x2c12c3d1, + 0x06610660, + 0x065f065e, + 0x065c065b, + 0x2427825d, + 0x041400ac, + 0x3b5a1958, + 0x202d8225, + 0x232d828e, + 0x04650464, + 0x2267d619, + 0x70262d82, + 0x7f000200, + 0x0982d600, + 0x006e2a08, + 0x07900314, + 0x073e073b, + 0x07430741, + 0x07470745, + 0x074b074a, + 0x074f074d, + 0x07530751, + 0x07570755, + 0x075b0759, + 0x0770076e, + 0x22f7827f, + 0x822c006c, + 0x00702205, + 0x24438401, + 0x05b90524, + 0xbbd319ba, + 0x82ca202c, + 0x05bd2e31, + 0x05c105bf, + 0x05c705d1, + 0x05d205cc, + 0x200982d0, + 0x224d82d2, + 0x82790032, + 0x96b9201b, + 0x05bd2103, + 0xbf20018d, + 0x03914382, + 0x5782c120, + 0xd1200395, + 0x71836582, + 0x7582c720, + 0xc9220389, + 0x8382c905, + 0x0396cc20, + 0x9d82d220, + 0xd0209f83, + 0x038fa382, + 0x9505d321, + 0x05d42101, + 0xd5210195, + 0x2a019405, + 0x00010000, + 0x40190200, + 0x1904b701, + 0x1933ff7a, + 0x310e3bd7, + 0xf004ef04, + 0xf204f104, + 0xf404f304, + 0xf604f504, + 0xd619f704, + 0x052e19e7, + 0x05060505, + 0x05080507, + 0x050a0509, + 0xd619050b, + 0x3d265fdd, + 0x3e053c05, + 0xd6193f05, + 0x6f224add, + 0xd6197005, + 0x360814e1, + 0x05720571, + 0x05730574, + 0x05760575, + 0x05780577, + 0x057a0579, + 0x057c057b, + 0x057e057d, + 0x0581057f, + 0x05830582, + 0x05850584, + 0x05870586, + 0x05890588, + 0x058b058a, + 0x198d058c, + 0x2186dbd6, + 0x1d4305b9, + 0x3b11430f, + 0x20150b43, + 0x0c0343c1, + 0x0d82c720, + 0x42110543, + 0x0f830fef, + 0x4211f142, + 0xe54211eb, + 0x19d62011, + 0x2e08c15e, + 0x05dc05db, + 0x05de05dd, + 0x05e005df, + 0x19e205e1, + 0x3b36a3d7, + 0x060006ff, + 0x06020601, + 0x06040603, + 0x06060605, + 0x06080607, + 0x060a0609, + 0x060c060b, + 0x28a1d719, + 0x15010036, + 0x00d701a2, + 0x00f41502, + 0x06220614, + 0x062e062d, + 0x0630062f, + 0x1c99d719, + 0xe2222d82, + 0xa743ec00, + 0x052d27be, + 0x0530052e, + 0xda19052f, + 0x39250d83, + 0x3b053a05, + 0x11a34305, + 0x4505463c, + 0x48054705, + 0x4a054905, + 0x4c054b05, + 0x4e054d05, + 0x50054f05, + 0x52055105, + 0xda195305, + 0xa3432281, + 0x0575241b, + 0x43730574, + 0x802014a3, + 0x203ea343, + 0x81da19a0, + 0x05b62628, + 0x05b505b7, + 0x27f9822c, + 0x14020038, + 0x054c0044, + 0x227fad42, + 0x19170618, + 0x2b114fda, + 0x0000d705, + 0x01000101, + 0x0b00b213, + 0xac220582, + 0x0f820a00, + 0x02000226, + 0x0b00aa13, + 0x1175e219, + 0x02bf0623, + 0x22258264, + 0x830700a8, + 0x1cfe2105, + 0x03202b82, + 0x38082b82, + 0x021b00a4, + 0x023a0239, + 0x023c023b, + 0x023e023d, + 0x0240023f, + 0x02420241, + 0x02440243, + 0x02460245, + 0x02480247, + 0x024a0249, + 0x024c024b, + 0x024e024d, + 0x0250024f, + 0x067f0651, + 0x224582bd, + 0x82180084, + 0x82042045, + 0x00802445, + 0x1952020a, + 0x210ff9e2, + 0x2382be06, + 0x13007c22, + 0x05202382, + 0x783e2382, + 0x2a020e00, + 0x2c022b02, + 0x2e022d02, + 0x30022f02, + 0x32023102, + 0x34023302, + 0x37023602, + 0x21823502, + 0x03006622, + 0x35222182, + 0x37823002, + 0xd3826420, + 0x22001c2b, + 0x2e002800, + 0x3a003400, + 0x09035300, + 0x2a020225, + 0x83009403, + 0x84a72005, + 0x84a82005, + 0x84a92005, + 0x20178505, + 0x200b84ab, + 0x200584ac, + 0x200584ad, + 0x200584ae, + 0x200584af, + 0x208f82b0, + 0x22618206, + 0x86010012, + 0x00082105, + 0x2205d557, + 0x82290216, + 0x00212a09, + 0x0025022f, + 0x02210002, + 0x27058228, + 0x1202002f, + 0x04bb02f4, + 0x21295347, + 0xde1904fd, + 0x51470c39, + 0x19202034, + 0x47222dde, + 0xb72ceb35, + 0x0005ff04, + 0x02050105, + 0x04050305, + 0x25145141, + 0x05120511, + 0xdf190513, + 0x4d41157d, + 0x052d2207, + 0x24e3442e, + 0x4877d344, + 0xb6285775, + 0x2c05b705, + 0x3d05b805, + 0x1910974b, + 0x481d51df, + 0x012b1075, + 0x02ed01e1, + 0x02f401a3, + 0x4bdd0114, + 0x33831691, + 0x4821934b, + 0x834b1381, + 0x4bc7200d, + 0x7d481283, + 0x90032148, + 0x1980d145, + 0x821421e0, + 0xb7e01995, + 0x2f13494b, + 0x63461820, + 0x22063513, + 0x70046f04, + 0x72047104, + 0x74047304, + 0x76047504, + 0x6e047704, + 0x06211391, + 0x142f49c0, + 0x3d063c34, + 0x3f063e06, + 0x3805ca04, + 0xbd067f06, + 0xbf06be06, + 0x534ec906, + 0x4e4b2008, + 0x5d221253, + 0x574e5f07, + 0x023d0805, + 0x0e010064, + 0x019200fc, + 0x0130012a, + 0x013c0136, + 0x01480142, + 0x0154014e, + 0x0162015a, + 0x016e0168, + 0x017a0174, + 0x01860180, + 0x0192018c, + 0x019e0198, + 0x01aa01a4, + 0x01b601b0, + 0x01c201bc, + 0xa59119c8, + 0x01f62a0c, + 0x020402fc, + 0x0210020a, + 0xa3911918, + 0x4e02250f, + 0x5a025402, + 0x08a19119, + 0x7e027825, + 0x19028402, + 0x080e9d91, + 0x02ba02a7, + 0x02c602c0, + 0x02d202cc, + 0x02de02d8, + 0x02ea02e4, + 0x02f602f0, + 0x030203fc, + 0x030e0308, + 0x031a0314, + 0x03260320, + 0x0332032c, + 0x033e0338, + 0x034a0344, + 0x03580352, + 0x0364035e, + 0x0370036a, + 0x037c0376, + 0x03880382, + 0x0394038e, + 0x03a0039a, + 0x03ac03a6, + 0x03b803b2, + 0x03c403be, + 0x03d003ca, + 0x03dc03d6, + 0x03e803e2, + 0x03f403ee, + 0x040004fa, + 0x040c0406, + 0x04280412, + 0x044c043a, + 0x0470045e, + 0x04940482, + 0x04b804a6, + 0x04d204ca, + 0x04e604dc, + 0x04f204ec, + 0x050405f8, + 0x05160510, + 0x0522051c, + 0x002e0528, + 0x06cd0402, + 0x22058281, + 0x828206ce, + 0x06cf2205, + 0x22058283, + 0x828406d0, + 0x06d12205, + 0x22058285, + 0x828606d2, + 0x06d32205, + 0x2a058287, + 0x008806d4, + 0x06d50403, + 0x822a0289, + 0x06d6220d, + 0x2205828a, + 0x828b06d7, + 0x06d82205, + 0x2205828c, + 0x828d06d9, + 0x06da2205, + 0x2205828e, + 0x828f06db, + 0x06dc2205, + 0x22058290, + 0x829106dd, + 0x06de2205, + 0x22058292, + 0x829306df, + 0x06e02205, + 0x22058294, + 0x829506e1, + 0x06e22205, + 0x22058296, + 0x829706e3, + 0x06e42205, + 0x22058298, + 0x829906e5, + 0x06e62205, + 0x246d829a, + 0x029b06cd, + 0x209f8439, + 0x209f849c, + 0x209f849d, + 0x209f849e, + 0x209f849f, + 0x242582a0, + 0x02a106d3, + 0x20a18452, + 0x200d82a2, + 0x20a382cc, + 0x20a184a3, + 0x20a184a4, + 0x241382a5, + 0x02a606d8, + 0x20a3845b, + 0x20a384a7, + 0x20a384a8, + 0x20a384a9, + 0x20a384aa, + 0x20a384ab, + 0x20a384ac, + 0x20a384ad, + 0x20a384ae, + 0x20a384af, + 0x20a384b0, + 0x220582b1, + 0x84b206e4, + 0x84b320a3, + 0x00b426a3, + 0x044c0002, + 0x280582fc, + 0x001f056f, + 0x02320502, + 0x2205822b, + 0x822c0233, + 0x02342205, + 0x2205822d, + 0x822e0235, + 0x02362205, + 0x2205822f, + 0x82300237, + 0x02382205, + 0x22058231, + 0x82320239, + 0x023a2205, + 0x22058233, + 0x8234023b, + 0x023d2205, + 0x22058236, + 0x8237023c, + 0x023e2805, + 0x02020035, + 0x82b60538, + 0x02e72265, + 0x2205823a, + 0x823b02e8, + 0x02e92205, + 0x2205823c, + 0x823d02ea, + 0x02eb2205, + 0x2205823e, + 0x823f02ec, + 0x02ed2205, + 0x22058240, + 0x824102ee, + 0x02ef2205, + 0x22058242, + 0x824302f0, + 0x02f12205, + 0x22058244, + 0x824502f2, + 0x02f32205, + 0x22058246, + 0x824702f4, + 0x02f52205, + 0x22058248, + 0x824902f6, + 0x02f72205, + 0x2205824a, + 0x824b02f8, + 0x02f92205, + 0x2205824c, + 0x824d02fa, + 0x02fb2a05, + 0x0103004e, + 0x02fc041c, + 0x220d824f, + 0x825002fd, + 0x02fe2205, + 0x229d8251, + 0x82ba060f, + 0x06102605, + 0x010200bb, + 0x22f7843f, + 0x82530224, + 0x02252211, + 0x22058254, + 0x82550226, + 0x02272205, + 0x22058256, + 0x82570228, + 0x02292205, + 0x22058258, + 0x8259022a, + 0x022b2205, + 0x2205825a, + 0x827f0030, + 0x02432205, + 0x2205825c, + 0x825d0244, + 0x02462205, + 0x2205825e, + 0x825f0245, + 0x02472205, + 0x22058260, + 0x82610248, + 0x02492205, + 0x22058262, + 0x8263024a, + 0x00882205, + 0x227182d6, + 0x82a005c0, + 0x06b5220b, + 0x220582bc, + 0x822a02c1, + 0x02db2811, + 0x020200a2, + 0x84a40206, + 0x84352011, + 0x82302005, + 0x493008ad, + 0x0200d705, + 0x5b021706, + 0x23060a00, + 0x62067006, + 0x51064006, + 0x64045804, + 0x56045704, + 0x08007804, + 0x71062406, + 0x41066306, + 0x59045206, + 0x79046504, + 0x252e1182, + 0x64067206, + 0x53064206, + 0x66045a04, + 0x11827a04, + 0x7306262e, + 0x43066506, + 0x5b045406, + 0x7b046704, + 0x272e1182, + 0x66067406, + 0x55064406, + 0x68045c04, + 0x11827c04, + 0x7506282e, + 0x45066706, + 0x5d045606, + 0x7d046904, + 0x292e1182, + 0x68067606, + 0x57064606, + 0x6a045e04, + 0x11827e04, + 0x77062a2e, + 0x47066906, + 0x5f045806, + 0x7f046b04, + 0x2b2e1182, + 0x6a067806, + 0x59064806, + 0x6c046004, + 0x11828004, + 0x062c2008, + 0x066b0679, + 0x045a0649, + 0x046d0461, + 0x04030081, + 0x0463046e, + 0x06040062, + 0x066e067c, + 0x8260064f, + 0x067d2609, + 0x0650066f, + 0x22d98261, + 0x82c10637, + 0x06382205, + 0x2e0582c2, + 0x00c30639, + 0x063a0605, + 0x066c067a, + 0x825e064d, + 0x063b280b, + 0x066d067b, + 0x825f064e, + 0x064a221d, + 0x2205825b, + 0x825c064b, + 0x064c2805, + 0x0702005d, + 0x823b073c, + 0x073f2205, + 0x2a05823e, + 0x004a0749, + 0x00160401, + 0x82080001, + 0x02042203, + 0x36138265, + 0x0a02006f, + 0x011c006e, + 0x02d6015c, + 0x02660265, + 0x04d90367, + 0x53fe0525, + 0x072125db, + 0x243d8284, + 0x070f006c, + 0x147755b1, + 0x97826c20, + 0x82066e21, + 0x27002961, + 0x4a003600, + 0x4d000000, + 0x4c080182, + 0x004f0015, + 0x00160050, + 0x005c0052, + 0x005e0018, + 0x0023006d, + 0x007a0070, + 0x007c0033, + 0x003e007f, + 0x00860081, + 0x00880042, + 0x0048008a, + 0x0094008c, + 0x0096004b, + 0x00540098, + 0x00b5009a, + 0x00b90057, + 0x007300bd, + 0x00ce00bf, + 0x00d00078, + 0x082782d6, + 0xe700d868, + 0xe9008f00, + 0x9f00ed00, + 0x0001ef00, + 0x0601a400, + 0xb6001a01, + 0x1d011d01, + 0x1f01cb00, + 0xcc002001, + 0x2c012201, + 0x2e01ce00, + 0xd9003d01, + 0x4e014001, + 0x5001e900, + 0xf8005801, + 0x5b015a01, + 0x5d010101, + 0x03016001, + 0x63016201, + 0x65010701, + 0x09016801, + 0x74016a01, + 0x76010d01, + 0x18018601, + 0x8e018a01, + 0x90012901, + 0x3f829f01, + 0x01a12608, + 0x013e01a7, + 0x01b801a9, + 0x01ba0145, + 0x015501be, + 0x01d201c1, + 0x03d8035a, + 0x046c01d8, + 0x01240424, + 0x0002006d, + 0x20ed8240, + 0x2aed823e, + 0x00440040, + 0x00460009, + 0x840e0049, + 0x841220f9, + 0x821320f9, + 0x005228f9, + 0x00550015, + 0x8216005a, + 0x00652eff, + 0x0067001c, + 0x0024006c, + 0x00760070, + 0x24d7822a, + 0x0031007a, + 0x2601827c, + 0x00810034, + 0x82350086, + 0x008938e3, + 0x008c003b, + 0x003d008e, + 0x00930092, + 0x009a0040, + 0x0042009b, + 0x82a0009d, + 0x00a22861, + 0x004800a2, + 0x82ac00a5, + 0x00ae3e67, + 0x005100b2, + 0x00b500b4, + 0x00b90056, + 0x005800bc, + 0x00c300bf, + 0x00c8005c, + 0x006100ca, + 0x2a0182cd, + 0x00d00064, + 0x006500d1, + 0x82e500d8, + 0x00e72875, + 0x007500e7, + 0x82ec00e9, + 0xefcb0879, + 0x7a00f800, + 0xfe00fa00, + 0x06018400, + 0x89000e01, + 0x14011001, + 0x16019200, + 0x97001901, + 0x1d011d01, + 0x1f019b00, + 0x9c002001, + 0x22012201, + 0x25019e00, + 0x9f002a01, + 0x35012e01, + 0x3701a500, + 0xad003c01, + 0x46014001, + 0x4801b300, + 0xba004b01, + 0x57015001, + 0x5a01be00, + 0xc6005b01, + 0x5d015d01, + 0x6201c800, + 0xc9006301, + 0x6b016a01, + 0x6d01cb00, + 0xcd007001, + 0x72017201, + 0x7601d100, + 0xd2007d01, + 0x83017f01, + 0x8501da00, + 0xdf008601, + 0x8d018a01, + 0x9001e100, + 0xe5009201, + 0x95019401, + 0x9901e800, + 0xea009b01, + 0x9e019e01, + 0xa101ed00, + 0xee00a201, + 0xb601a901, + 0xb801f000, + 0xfe00b801, + 0xbd01ba01, + 0xc101ff00, + 0x0301ca01, + 0xd001cc01, + 0x19000d01, + 0x0821558f, + 0x4e00014c, + 0x53003f00, + 0x5b005400, + 0x66005c00, + 0x7d007700, + 0x7f007e00, + 0x8f008a00, + 0x91009000, + 0x96009400, + 0x9c009800, + 0xa300a100, + 0xad00a400, + 0xc400bd00, + 0xc700c500, + 0xcc00cb00, + 0xd200ce00, + 0xd400d300, + 0xd600d500, + 0xed00e600, + 0x7d82f900, + 0x01009008, + 0x0123010f, + 0x012b0124, + 0x0136012c, + 0x014c0147, + 0x014e014d, + 0x015e0158, + 0x0160015f, + 0x01660165, + 0x016c0168, + 0x01730171, + 0x017e0174, + 0x0193018e, + 0x01980196, + 0x019d019c, + 0x01a3019f, + 0x01a501a4, + 0x01a701a6, + 0x01be01b7, + 0x01d101cb, + 0x000100d2, + 0x073a071f, + 0x073d073c, + 0x0740073f, + 0x07440742, + 0x07480746, + 0x074c0749, + 0x0750074e, + 0x07540752, + 0x07580756, + 0x075c075a, + 0x075e075d, + 0x0762075f, + 0x076d0763, + 0x0778076f, + 0x077e077d, + 0x82810780, + 0x00042841, + 0x01a70060, + 0x82780130, + 0x0701220b, + 0x26118448, + 0x01aa0063, + 0x847b0133, + 0x823d2011, + 0x03022405, + 0x822404d8, + 0x00012107, + 0x07210584, + 0x200b826f, + 0x260b8205, + 0x01590125, + 0x83f501f2, + 0x207f820d, + 0x22758248, + 0x825f075d, + 0x001b340d, + 0x00060002, + 0x000a0008, + 0x00160010, + 0x001f001c, + 0x82220020, + 0x0027342f, + 0x002f002a, + 0x004b0030, + 0x008b006e, + 0x01ee00be, + 0x823e011b, + 0x018f2643, + 0x02e401bf, + 0x33398252, + 0x02680216, + 0x026e026c, + 0x02760270, + 0x027b0278, + 0x0289027f, + 0x0c279219, + 0x02f5022b, + 0x030703fe, + 0x03710365, + 0x202f827d, + 0x21978501, + 0x0b83d803, + 0x82fd0521, + 0x04022405, + 0x82250423, + 0x03012207, + 0x201384d9, + 0x208b82fe, + 0x24038211, + 0x0000001b, + 0x2001821d, + 0x248d821a, + 0x001b001f, + 0x22018221, + 0x8223001c, + 0x001d2a01, + 0x00270026, + 0x0036001e, + 0x24a782ce, + 0x000501d0, + 0x088582b9, + 0xef008832, + 0x0f03b002, + 0xb1031001, + 0x7001d803, + 0xfc03da03, + 0xcd049801, + 0xbb017f05, + 0xb7058205, + 0xb9056e02, + 0xa402d205, + 0xfd05d605, + 0xff05be02, + 0xe6022106, + 0x13246f82, + 0x3d073a07, + 0x200a8b41, + 0x108b414b, + 0x6f076d24, + 0x29847e07, + 0x21261959, + 0xb5820800, + 0xad821f20, + 0xa7842320, + 0x0f022f22, + 0x01223d82, + 0x05828307, + 0x8902072e, + 0x8b028a02, + 0x9c029102, + 0x9e029d02, + 0x052a1182, + 0x6e004b00, + 0x3e011b01, + 0x0d82bf01, + 0x04010122, + 0x04200582, + 0x5c229384, + 0x0b825e07, + 0x48070224, + 0x07824a07, + 0xfe030138, + 0x03000200, + 0x55044c04, + 0x82040000, + 0x0a008304, + 0xa404a304, + 0x1b830c00, + 0x82a90421, + 0x0601281b, + 0x00790670, + 0x84010000, + 0x00022e01, + 0x06620602, + 0x0600006f, + 0x00de06dc, + 0x201f860e, + 0x221f827d, + 0x82010002, + 0x826b2019, + 0x22298209, + 0x8200b107, + 0x1c002f55, + 0x00003500, + 0x2f012e01, + 0xe4011a00, + 0x0f82e401, + 0x01000222, + 0x22068341, + 0x91050002, + 0xf4062b75, + 0x0e00f506, + 0xf906f906, + 0x29821000, + 0x84040428, + 0x98049704, + 0x33829904, + 0x2d860220, + 0x6d046424, + 0x0f8a0a00, + 0x61045822, + 0x55820f82, + 0x014d0123, + 0x223382a7, + 0x418f0314, + 0x8b82267b, + 0xeb845385, + 0x5383c920, + 0x0289022b, + 0x020000a1, + 0x00af02a5, + 0x240f8219, + 0x03100301, + 0x22d18288, + 0x86070002, + 0x362208b5, + 0x1a000501, + 0x38023802, + 0x6802ea00, + 0xeb008802, + 0x0f03b002, + 0xb1030c01, + 0x6c01d803, + 0xfc03da03, + 0x29829401, + 0x4b04042c, + 0x00004b04, + 0x90048704, + 0xc1820100, + 0x0b009928, + 0xa804a304, + 0x1b820e00, + 0x15410a20, + 0x06340806, + 0x1a005b01, + 0x60015d01, + 0x62017000, + 0x74007401, + 0xd5017601, + 0xd7018700, + 0xe700d701, + 0xe401e401, + 0xea01e800, + 0xe900ea01, + 0x65026502, + 0xcc04ea00, + 0xeb00cc04, + 0x02243f82, + 0x2404fd03, + 0x26245b82, + 0x28004904, + 0x0220b982, + 0x5820c382, + 0x0b220782, + 0x47822700, + 0x64016330, + 0x66016501, + 0x68016701, + 0xa6066901, + 0x1982b507, + 0x9d020122, + 0x3f24e184, + 0x04000200, + 0x1c267d82, + 0x06010000, + 0x04821d01, + 0x7e067e2a, + 0x9b061900, + 0x1a009b06, + 0x8a202784, + 0x03222182, + 0x01822200, + 0x43010024, + 0x21824a01, + 0xa106a124, + 0x1b840900, + 0x1b829020, + 0x0a000222, + 0x00240182, + 0x8d008100, + 0x00271383, + 0x02700203, + 0x83d902d8, + 0x83022919, + 0x00008302, + 0xd702ce02, + 0x01221984, + 0x0784c806, + 0xe1462120, + 0x4a580806, + 0x4c000000, + 0x15006d00, + 0x80006f00, + 0x8e003700, + 0x49000301, + 0x05010501, + 0x1e01bf00, + 0xc0002d01, + 0x3d013001, + 0x3f01d000, + 0xde004201, + 0x4c014b01, + 0x4e01e200, + 0xe4005b01, + 0x60015d01, + 0x6a01f200, + 0xf6007401, + 0xa6017601, + 0xa8010101, + 0x3201be01, + 0xd501c001, + 0xd7014901, + 0x5f220182, + 0x0182ea01, + 0x02601e09, + 0x01380238, + 0x02650261, + 0x02620165, + 0x016f0268, + 0x02710263, + 0x026b0189, + 0x018b028b, + 0x02900284, + 0x02850191, + 0x019c029c, + 0x029e0287, + 0x0288019e, + 0x01d702b0, + 0x03da0289, + 0x03b1010f, + 0x018f038f, + 0x03b103e7, + 0x03e801d8, + 0x02fd03da, + 0x04ff0310, + 0x04340224, + 0x023e0426, + 0x0440045a, + 0x04730249, + 0x024b044b, + 0x0459047d, + 0x047e0261, + 0x026d0464, + 0x04840487, + 0x04910284, + 0x02900487, + 0x04a50492, + 0x049c02a8, + 0x02c904c9, + 0x04cc04a0, + 0x06a102cc, + 0x027e067e, + 0x069b06a2, + 0x06a3029b, + 0x02a106a1, + 0x06a606a4, + 0x06a502a6, + 0x02c806c8, + 0x074007a6, + 0x07a70240, + 0x02420742, + 0x074407a8, + 0x07a90244, + 0x02460746, + 0x074a07aa, + 0x07ab024c, + 0x024e074e, + 0x075007ae, + 0x07af0250, + 0x02520752, + 0x075407b0, + 0x07b10254, + 0x02560756, + 0x075807b2, + 0x07b30258, + 0x025a075a, + 0x075c07b4, + 0x07b5025c, + 0x025e075e, + 0x076d07b6, + 0x07b7026d, + 0x026f076f, + 0x077e07b8, + 0x07b9027e, + 0x02b507b5, + 0x000200ba, + 0x2403821e, + 0x00000035, + 0x2201824b, + 0x826e0034, + 0x35a60801, + 0x8d008100, + 0x04013600, + 0x43000401, + 0x1d010601, + 0x2e014400, + 0x5c002f01, + 0x3e013e01, + 0x43015e00, + 0x5f004a01, + 0x4d014d01, + 0x62016700, + 0x68006901, + 0xa701a701, + 0xbf017000, + 0x7100bf01, + 0xe401e401, + 0x70027200, + 0x73007002, + 0x8a028a02, + 0x9d027400, + 0x75009d02, + 0xd902d802, + 0xfe037600, + 0x7800fe03, + 0x3f043f04, + 0x4c047900, + 0x7a005504, + 0x58045804, + 0x82048400, + 0x85008304, + 0x99049704, + 0xa3048700, + 0x8a00a404, + 0xf506f406, + 0xf9068c00, + 0x8e00f906, + 0x3a073a07, + 0x3d078f00, + 0x90003d07, + 0x48074807, + 0x01009100, + 0x5d461c00, + 0xd8032509, + 0xfd052404, + 0x2125db43, + 0xef828307, + 0x3f820220, + 0x00000130, + 0x7d067006, + 0x00000100, + 0x00000100, + 0xfa050000, + 0x0353aa07, + }; + + } +} diff --git a/src/editors/xrEUI/spectrum.h b/src/editors/xrEUI/spectrum.h new file mode 100644 index 00000000000..fafb554e0f6 --- /dev/null +++ b/src/editors/xrEUI/spectrum.h @@ -0,0 +1,213 @@ +#pragma once + +/* +Color definitions in ImGui are a good starting point, +but do not cover all the intricacies of Spectrum's possible colors +in controls and widgets. + +One big difference is that ImGui communicates widget activity +(hover, pressed) with their background, while spectrum uses a mix +of background and border, with border being the most common choice. + +Because of this, we reference extra colors in spectrum from +imgui.cpp and imgui_widgets.cpp directly, and to make that work, +we need to have them defined at here at compile time. +*/ + +/// Pick one +#define SPECTRUM_USE_LIGHT_THEME +//#define SPECTRUM_USE_DARK_THEME + +namespace ImGui +{ + namespace Spectrum + { + // a list of changes introduced to change the look of the widgets. + // Collected here as const rather than being magic numbers spread + // around imgui.cpp and imgui_widgets.cpp. + const float CHECKBOX_BORDER_SIZE = 2.0f; + const float CHECKBOX_ROUNDING = 2.0f; + + // Load SourceSansProRegular and sets it as a default font. + // You may want to call ImGui::GetIO().Fonts->Clear() before this + void LoadFont(float size = 16.0f); + + // Sets the ImGui style to Spectrum + void StyleColorsSpectrum(); + + namespace + { // Unnamed namespace, since we only use this here. + unsigned int Color(unsigned int c) + { + // add alpha. + // also swap red and blue channel for some reason. + // todo: figure out why, and fix it. + const short a = 0xFF; + const short r = (c >> 16) & 0xFF; + const short g = (c >> 8) & 0xFF; + const short b = (c >> 0) & 0xFF; + return (a << 24) | (r << 0) | (g << 8) | (b << 16); + } + } + // all colors are from http://spectrum.corp.adobe.com/color.html + + inline unsigned int color_alpha(unsigned int alpha, unsigned int c) + { + return ((alpha & 0xFF) << 24) | (c & 0x00FFFFFF); + } + + namespace Static + { // static colors + const unsigned int NONE = 0x00000000; // transparent + const unsigned int WHITE = Color(0xFFFFFF); + const unsigned int BLACK = Color(0x000000); + const unsigned int GRAY200 = Color(0xF4F4F4); + const unsigned int GRAY300 = Color(0xEAEAEA); + const unsigned int GRAY400 = Color(0xD3D3D3); + const unsigned int GRAY500 = Color(0xBCBCBC); + const unsigned int GRAY600 = Color(0x959595); + const unsigned int GRAY700 = Color(0x767676); + const unsigned int GRAY800 = Color(0x505050); + const unsigned int GRAY900 = Color(0x323232); + const unsigned int BLUE400 = Color(0x378EF0); + const unsigned int BLUE500 = Color(0x2680EB); + const unsigned int BLUE600 = Color(0x1473E6); + const unsigned int BLUE700 = Color(0x0D66D0); + const unsigned int RED400 = Color(0xEC5B62); + const unsigned int RED500 = Color(0xE34850); + const unsigned int RED600 = Color(0xD7373F); + const unsigned int RED700 = Color(0xC9252D); + const unsigned int ORANGE400 = Color(0xF29423); + const unsigned int ORANGE500 = Color(0xE68619); + const unsigned int ORANGE600 = Color(0xDA7B11); + const unsigned int ORANGE700 = Color(0xCB6F10); + const unsigned int GREEN400 = Color(0x33AB84); + const unsigned int GREEN500 = Color(0x2D9D78); + const unsigned int GREEN600 = Color(0x268E6C); + const unsigned int GREEN700 = Color(0x12805C); + } + +#ifdef SPECTRUM_USE_LIGHT_THEME + const unsigned int GRAY50 = Color(0xFFFFFF); + const unsigned int GRAY75 = Color(0xFAFAFA); + const unsigned int GRAY100 = Color(0xF5F5F5); + const unsigned int GRAY200 = Color(0xEAEAEA); + const unsigned int GRAY300 = Color(0xE1E1E1); + const unsigned int GRAY400 = Color(0xCACACA); + const unsigned int GRAY500 = Color(0xB3B3B3); + const unsigned int GRAY600 = Color(0x8E8E8E); + const unsigned int GRAY700 = Color(0x707070); + const unsigned int GRAY800 = Color(0x4B4B4B); + const unsigned int GRAY900 = Color(0x2C2C2C); + const unsigned int BLUE400 = Color(0x2680EB); + const unsigned int BLUE500 = Color(0x1473E6); + const unsigned int BLUE600 = Color(0x0D66D0); + const unsigned int BLUE700 = Color(0x095ABA); + const unsigned int RED400 = Color(0xE34850); + const unsigned int RED500 = Color(0xD7373F); + const unsigned int RED600 = Color(0xC9252D); + const unsigned int RED700 = Color(0xBB121A); + const unsigned int ORANGE400 = Color(0xE68619); + const unsigned int ORANGE500 = Color(0xDA7B11); + const unsigned int ORANGE600 = Color(0xCB6F10); + const unsigned int ORANGE700 = Color(0xBD640D); + const unsigned int GREEN400 = Color(0x2D9D78); + const unsigned int GREEN500 = Color(0x268E6C); + const unsigned int GREEN600 = Color(0x12805C); + const unsigned int GREEN700 = Color(0x107154); + const unsigned int INDIGO400 = Color(0x6767EC); + const unsigned int INDIGO500 = Color(0x5C5CE0); + const unsigned int INDIGO600 = Color(0x5151D3); + const unsigned int INDIGO700 = Color(0x4646C6); + const unsigned int CELERY400 = Color(0x44B556); + const unsigned int CELERY500 = Color(0x3DA74E); + const unsigned int CELERY600 = Color(0x379947); + const unsigned int CELERY700 = Color(0x318B40); + const unsigned int MAGENTA400 = Color(0xD83790); + const unsigned int MAGENTA500 = Color(0xCE2783); + const unsigned int MAGENTA600 = Color(0xBC1C74); + const unsigned int MAGENTA700 = Color(0xAE0E66); + const unsigned int YELLOW400 = Color(0xDFBF00); + const unsigned int YELLOW500 = Color(0xD2B200); + const unsigned int YELLOW600 = Color(0xC4A600); + const unsigned int YELLOW700 = Color(0xB79900); + const unsigned int FUCHSIA400 = Color(0xC038CC); + const unsigned int FUCHSIA500 = Color(0xB130BD); + const unsigned int FUCHSIA600 = Color(0xA228AD); + const unsigned int FUCHSIA700 = Color(0x93219E); + const unsigned int SEAFOAM400 = Color(0x1B959A); + const unsigned int SEAFOAM500 = Color(0x16878C); + const unsigned int SEAFOAM600 = Color(0x0F797D); + const unsigned int SEAFOAM700 = Color(0x096C6F); + const unsigned int CHARTREUSE400 = Color(0x85D044); + const unsigned int CHARTREUSE500 = Color(0x7CC33F); + const unsigned int CHARTREUSE600 = Color(0x73B53A); + const unsigned int CHARTREUSE700 = Color(0x6AA834); + const unsigned int PURPLE400 = Color(0x9256D9); + const unsigned int PURPLE500 = Color(0x864CCC); + const unsigned int PURPLE600 = Color(0x7A42BF); + const unsigned int PURPLE700 = Color(0x6F38B1); +#endif +#ifdef SPECTRUM_USE_DARK_THEME + const unsigned int GRAY50 = Color(0x252525); + const unsigned int GRAY75 = Color(0x2F2F2F); + const unsigned int GRAY100 = Color(0x323232); + const unsigned int GRAY200 = Color(0x393939); + const unsigned int GRAY300 = Color(0x3E3E3E); + const unsigned int GRAY400 = Color(0x4D4D4D); + const unsigned int GRAY500 = Color(0x5C5C5C); + const unsigned int GRAY600 = Color(0x7B7B7B); + const unsigned int GRAY700 = Color(0x999999); + const unsigned int GRAY800 = Color(0xCDCDCD); + const unsigned int GRAY900 = Color(0xFFFFFF); + const unsigned int BLUE400 = Color(0x2680EB); + const unsigned int BLUE500 = Color(0x378EF0); + const unsigned int BLUE600 = Color(0x4B9CF5); + const unsigned int BLUE700 = Color(0x5AA9FA); + const unsigned int RED400 = Color(0xE34850); + const unsigned int RED500 = Color(0xEC5B62); + const unsigned int RED600 = Color(0xF76D74); + const unsigned int RED700 = Color(0xFF7B82); + const unsigned int ORANGE400 = Color(0xE68619); + const unsigned int ORANGE500 = Color(0xF29423); + const unsigned int ORANGE600 = Color(0xF9A43F); + const unsigned int ORANGE700 = Color(0xFFB55B); + const unsigned int GREEN400 = Color(0x2D9D78); + const unsigned int GREEN500 = Color(0x33AB84); + const unsigned int GREEN600 = Color(0x39B990); + const unsigned int GREEN700 = Color(0x3FC89C); + const unsigned int INDIGO400 = Color(0x6767EC); + const unsigned int INDIGO500 = Color(0x7575F1); + const unsigned int INDIGO600 = Color(0x8282F6); + const unsigned int INDIGO700 = Color(0x9090FA); + const unsigned int CELERY400 = Color(0x44B556); + const unsigned int CELERY500 = Color(0x4BC35F); + const unsigned int CELERY600 = Color(0x51D267); + const unsigned int CELERY700 = Color(0x58E06F); + const unsigned int MAGENTA400 = Color(0xD83790); + const unsigned int MAGENTA500 = Color(0xE2499D); + const unsigned int MAGENTA600 = Color(0xEC5AAA); + const unsigned int MAGENTA700 = Color(0xF56BB7); + const unsigned int YELLOW400 = Color(0xDFBF00); + const unsigned int YELLOW500 = Color(0xEDCC00); + const unsigned int YELLOW600 = Color(0xFAD900); + const unsigned int YELLOW700 = Color(0xFFE22E); + const unsigned int FUCHSIA400 = Color(0xC038CC); + const unsigned int FUCHSIA500 = Color(0xCF3EDC); + const unsigned int FUCHSIA600 = Color(0xD951E5); + const unsigned int FUCHSIA700 = Color(0xE366EF); + const unsigned int SEAFOAM400 = Color(0x1B959A); + const unsigned int SEAFOAM500 = Color(0x20A3A8); + const unsigned int SEAFOAM600 = Color(0x23B2B8); + const unsigned int SEAFOAM700 = Color(0x26C0C7); + const unsigned int CHARTREUSE400 = Color(0x85D044); + const unsigned int CHARTREUSE500 = Color(0x8EDE49); + const unsigned int CHARTREUSE600 = Color(0x9BEC54); + const unsigned int CHARTREUSE700 = Color(0xA3F858); + const unsigned int PURPLE400 = Color(0x9256D9); + const unsigned int PURPLE500 = Color(0x9D64E1); + const unsigned int PURPLE600 = Color(0xA873E9); + const unsigned int PURPLE700 = Color(0xB483F0); +#endif + } +} diff --git a/src/editors/xrEUI/stdafx.h b/src/editors/xrEUI/stdafx.h new file mode 100644 index 00000000000..3dd5fc2eb94 --- /dev/null +++ b/src/editors/xrEUI/stdafx.h @@ -0,0 +1,20 @@ +#pragma once +#include "Common/Platform.hpp" +#include "..\..\xrCore\xrCore.h" +#ifdef XREUI_EXPORTS +#define XREUI_API __declspec(dllexport) +#else +#define XREUI_API __declspec(dllimport) +#endif +#include "xrUI.h" +#include +#include "xrUIManager.h" + +#define IMGUI_API XREUI_API +#define IMGUI_IMPL_API +using ImTextureID = IDirect3DBaseTexture9*; +#define ImTextureID ImTextureID +#define IMGUI_DISABLE_INCLUDE_IMCONFIG_H +#define IMGUI_INCLUDE_IMGUI_USER_H + +#include "imgui.h" diff --git a/src/editors/xrEUI/xrEUI.vcxproj b/src/editors/xrEUI/xrEUI.vcxproj new file mode 100644 index 00000000000..66458fe5046 --- /dev/null +++ b/src/editors/xrEUI/xrEUI.vcxproj @@ -0,0 +1,73 @@ + + + + + + + {7E28883C-DB86-4EE8-813A-991BA20C68C9} + xrEUI + xrEUI + + + + + + + + + + + + + + + + NotUsing + XREUI_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {a0f7d1fb-59a7-4717-a7e4-96f37e91998e} + + + + + + \ No newline at end of file diff --git a/src/editors/xrEUI/xrEUI.vcxproj.filters b/src/editors/xrEUI/xrEUI.vcxproj.filters new file mode 100644 index 00000000000..ca6ec0c7f8a --- /dev/null +++ b/src/editors/xrEUI/xrEUI.vcxproj.filters @@ -0,0 +1,97 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + Исходные файлы + + + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + Файлы заголовков + + + + + + + \ No newline at end of file diff --git a/src/editors/xrEUI/xrUI.cpp b/src/editors/xrEUI/xrUI.cpp new file mode 100644 index 00000000000..f2b651cdf26 --- /dev/null +++ b/src/editors/xrEUI/xrUI.cpp @@ -0,0 +1,15 @@ +#include "stdafx.h" + +#pragma comment(lib,"xrCore.lib") + +xrUI::~xrUI() +{ +} + +void xrUI::ResetBegin() +{ +} + +void xrUI::ResetEnd() +{ +} diff --git a/src/editors/xrEUI/xrUI.h b/src/editors/xrEUI/xrUI.h new file mode 100644 index 00000000000..d5582bb5f9e --- /dev/null +++ b/src/editors/xrEUI/xrUI.h @@ -0,0 +1,20 @@ +#pragma once +class XREUI_API xrUI +{ +public: + xrUI() : bOpen(true) {} + enum FUI + { + F_NoDelete = 1, + }; + Flags32 Flags; + virtual ~xrUI(); + /* */ + virtual void ResetBegin(); + virtual void ResetEnd(); + bool IsClosed() const { return !bOpen; } + virtual void Draw() = 0; + +protected: + bool bOpen; +}; diff --git a/src/editors/xrEUI/xrUIManager.cpp b/src/editors/xrEUI/xrUIManager.cpp new file mode 100644 index 00000000000..7db0098f32d --- /dev/null +++ b/src/editors/xrEUI/xrUIManager.cpp @@ -0,0 +1,380 @@ +#include "stdafx.h" +#include "imgui_impl_dx9.h" +#include "imgui_impl_win32.h" + +#define USE_OLD_STYLE 1 + +xrUIManager::xrUIManager() +{ +} + +xrUIManager::~xrUIManager() +{ +} + +inline void Style() +{ + ImGuiStyle& style = ImGui::GetStyle(); + ImVec4* colors = style.Colors; + + /// 0 = FLAT APPEARENCE + /// 1 = MORE "3D" LOOK + int is3D = 0; + + colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.40f, 0.40f, 0.40f, 1.00f); + colors[ImGuiCol_ChildBg] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); + colors[ImGuiCol_Border] = ImVec4(0.12f, 0.12f, 0.12f, 0.71f); + colors[ImGuiCol_BorderShadow] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); + colors[ImGuiCol_FrameBg] = ImVec4(0.42f, 0.42f, 0.42f, 0.54f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.42f, 0.42f, 0.42f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.56f, 0.56f, 0.56f, 0.67f); + colors[ImGuiCol_TitleBg] = ImVec4(0.19f, 0.19f, 0.19f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.22f, 0.22f, 0.22f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.17f, 0.17f, 0.17f, 0.90f); + colors[ImGuiCol_MenuBarBg] = ImVec4(0.335f, 0.335f, 0.335f, 1.000f); + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.24f, 0.24f, 0.24f, 0.53f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.52f, 0.52f, 0.52f, 1.00f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.76f, 0.76f, 0.76f, 1.00f); + colors[ImGuiCol_CheckMark] = ImVec4(0.65f, 0.65f, 0.65f, 1.00f); + colors[ImGuiCol_SliderGrab] = ImVec4(0.52f, 0.52f, 0.52f, 1.00f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.64f, 0.64f, 0.64f, 1.00f); + colors[ImGuiCol_Button] = ImVec4(0.54f, 0.54f, 0.54f, 0.35f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.52f, 0.52f, 0.52f, 0.59f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.76f, 0.76f, 0.76f, 1.00f); + colors[ImGuiCol_Header] = ImVec4(0.38f, 0.38f, 0.38f, 1.00f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.47f, 0.47f, 0.47f, 1.00f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.76f, 0.76f, 0.76f, 0.77f); + colors[ImGuiCol_Separator] = ImVec4(0.000f, 0.000f, 0.000f, 0.137f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.700f, 0.671f, 0.600f, 0.290f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.702f, 0.671f, 0.600f, 0.674f); + colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.25f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); + colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.73f, 0.73f, 0.73f, 0.35f); + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); + colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); + colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + + style.PopupRounding = 3; + + style.WindowPadding = ImVec2(4, 4); + style.FramePadding = ImVec2(6, 4); + style.ItemSpacing = ImVec2(6, 2); + + style.ScrollbarSize = 18; + + style.WindowBorderSize = 1; + style.ChildBorderSize = 1; + style.PopupBorderSize = 1; + style.FrameBorderSize = static_cast(is3D); + + style.WindowRounding = 3; + style.ChildRounding = 3; + style.FrameRounding = 3; + style.ScrollbarRounding = 2; + style.GrabRounding = 3; + +#ifdef IMGUI_HAS_DOCK + style.TabBorderSize = static_cast(is3D); + style.TabRounding = 3; + + colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.38f, 0.38f, 0.38f, 1.00f); + colors[ImGuiCol_Tab] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); + colors[ImGuiCol_TabHovered] = ImVec4(0.40f, 0.40f, 0.40f, 1.00f); + colors[ImGuiCol_TabActive] = ImVec4(0.33f, 0.33f, 0.33f, 1.00f); + colors[ImGuiCol_TabUnfocused] = ImVec4(0.25f, 0.25f, 0.25f, 1.00f); + colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.33f, 0.33f, 0.33f, 1.00f); + colors[ImGuiCol_DockingPreview] = ImVec4(0.85f, 0.85f, 0.85f, 0.28f); + + if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + style.WindowRounding = 0.0f; + style.Colors[ImGuiCol_WindowBg].w = 1.0f; + } +#endif +} + +void xrUIManager::Initialize(HWND hWnd, IDirect3DDevice9 *device, const char *ini_path) +{ + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO &io = ImGui::GetIO(); + (void)io; + xr_strcpy(m_name_ini, ini_path); + io.IniFilename = m_name_ini; + // io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + // io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + // io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking + io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows + // Setup Dear ImGui style + ImGui::StyleColorsClassic(); + +#ifndef USE_OLD_STYLE + ImGui::Spectrum::LoadFont(); + Style(); +#endif + + ImGui::GetStyle().ItemSpacing = ImVec2(3, 3); + ImGui::GetStyle().FramePadding = ImVec2(3, 1); + ImGui_ImplWin32_Init(hWnd); + ImGui_ImplDX9_Init(device); +} + +void xrUIManager::Destroy() +{ + ImGui_ImplDX9_Shutdown(); + ImGui_ImplWin32_Shutdown(); + ImGui::DestroyContext(); +} + +void xrUIManager::ResetBegin() +{ + ImGui_ImplDX9_InvalidateDeviceObjects(); +} + +void xrUIManager::ResetEnd() +{ + ImGui_ImplDX9_CreateDeviceObjects(); +} + +void xrUIManager::OnDrawUI() +{ +} + +void xrUIManager::ApplyShortCut(DWORD Key) +{ + if ((ImGui::GetIO().WantTextInput)) + return; + bool IsFail = true; + if (Key >= 'A' && Key <= 'Z') + { + IsFail = false; + } + else if (Key >= '0' && Key <= '9') + { + IsFail = false; + } + else + { + switch (Key) + { + case VK_LEFT: + case VK_RIGHT: + case VK_UP: + case VK_DOWN: + case VK_NUMPAD0: + case VK_NUMPAD1: + case VK_NUMPAD2: + case VK_NUMPAD3: + case VK_NUMPAD4: + case VK_NUMPAD5: + case VK_NUMPAD6: + case VK_NUMPAD7: + case VK_NUMPAD8: + case VK_NUMPAD9: + case VK_F1: + case VK_F2: + case VK_F3: + case VK_F4: + case VK_F5: + case VK_F6: + case VK_F7: + case VK_F8: + case VK_F9: + case VK_F10: + case VK_F11: + case VK_F12: + case VK_DELETE: + case VK_ADD: + case VK_SUBTRACT: + case VK_MULTIPLY: + case VK_DIVIDE: + case VK_OEM_PLUS: + case VK_OEM_MINUS: + case VK_OEM_1: + case VK_OEM_COMMA: + case VK_OEM_PERIOD: + case VK_OEM_2: + case VK_OEM_4: + case VK_OEM_5: + case VK_OEM_6: + case VK_OEM_7: + case VK_SPACE: + case VK_CANCEL: + case VK_RETURN: + IsFail = false; + break; + default: + break; + } + } + if (IsFail) + return; + + int ShiftState = ssNone; + + if (ImGui::GetIO().KeyShift) + ShiftState |= ssShift; + if (ImGui::GetIO().KeyCtrl) + ShiftState |= ssCtrl; + if (ImGui::GetIO().KeyAlt) + ShiftState |= ssAlt; + + if (ImGui::IsMouseDown(ImGuiMouseButton_Left)) + ShiftState |= ssLeft; + if (ImGui::IsMouseDown(ImGuiMouseButton_Right)) + ShiftState |= ssRight; + ApplyShortCut(Key, ShiftState); +} + +void xrUIManager::Push(xrUI *ui, bool need_deleted) +{ + m_UIArray.push_back(ui); + ui->Flags.set(!need_deleted, xrUI::F_NoDelete); +} + +void xrUIManager::Draw() +{ + ImGui_ImplDX9_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); + // ImGui::DockSpaceOverViewport(); + { + ImGuiViewport *viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + UIToolBarSize)); + ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, viewport->Size.y - UIToolBarSize)); + ImGui::SetNextWindowViewport(viewport->ID); + ImGuiWindowFlags window_flags = 0 | ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(3, 2)); + ImGui::Begin("Master DockSpace", NULL, window_flags); + ImGuiID dockMain = ImGui::GetID("MyDockspace"); + + m_MenuBarHeight = ImGui::GetWindowBarHeight(); + // Save off menu bar height for later. + + ImGui::DockSpace(dockMain); + ImGui::End(); + ImGui::PopStyleVar(4); + } + for (xrUI *ui : m_UIArray) + { + ui->Draw(); + } + + OnDrawUI(); + ImGui::EndFrame(); + ImGui::Render(); + ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData()); + for (size_t i = m_UIArray.size(); i > 0; i--) + { + if (m_UIArray[i - 1]->IsClosed()) + { + if (!m_UIArray[i - 1]->Flags.test(xrUI::F_NoDelete)) + { + xr_delete(m_UIArray[i - 1]); + } + m_UIArray.erase(m_UIArray.begin() + (i - 1)); + i = m_UIArray.size(); + if (i == 0) + return; + } + } +} +static bool ImGui_ImplWin32_UpdateMouseCursor() +{ + ImGuiIO &io = ImGui::GetIO(); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) + return false; + + ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); + if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) + { + // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor + ::SetCursor(NULL); + } + else + { + // Show OS mouse cursor + LPTSTR win32_cursor = IDC_ARROW; + switch (imgui_cursor) + { + case ImGuiMouseCursor_Arrow: + win32_cursor = IDC_ARROW; + break; + case ImGuiMouseCursor_TextInput: + win32_cursor = IDC_IBEAM; + break; + case ImGuiMouseCursor_ResizeAll: + win32_cursor = IDC_SIZEALL; + break; + case ImGuiMouseCursor_ResizeEW: + win32_cursor = IDC_SIZEWE; + break; + case ImGuiMouseCursor_ResizeNS: + win32_cursor = IDC_SIZENS; + break; + case ImGuiMouseCursor_ResizeNESW: + win32_cursor = IDC_SIZENESW; + break; + case ImGuiMouseCursor_ResizeNWSE: + win32_cursor = IDC_SIZENWSE; + break; + case ImGuiMouseCursor_Hand: + win32_cursor = IDC_HAND; + break; + case ImGuiMouseCursor_NotAllowed: + win32_cursor = IDC_NO; + break; + } + ::SetCursor(::LoadCursor(NULL, win32_cursor)); + } + return true; +} +#ifndef WM_MOUSEHWHEEL +#define WM_MOUSEHWHEEL 0x020E +#endif +#ifndef DBT_DEVNODES_CHANGED +#define DBT_DEVNODES_CHANGED 0x0007 +#endif +IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); +LRESULT xrUIManager::WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch (msg) + { + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; + case WM_KEYDOWN: + case WM_SYSKEYDOWN: + switch (wParam) + { + case VK_MENU: + case VK_CONTROL: + case VK_SHIFT: + break; + default: + ApplyShortCut(wParam); + break; + } + default: + break; + } + return ImGui_ImplWin32_WndProcHandler(hwnd, msg, wParam, lParam); + ; +} diff --git a/src/editors/xrEUI/xrUIManager.h b/src/editors/xrEUI/xrUIManager.h new file mode 100644 index 00000000000..0cca52b2431 --- /dev/null +++ b/src/editors/xrEUI/xrUIManager.h @@ -0,0 +1,42 @@ +#pragma once +enum TShiftState_ +{ + ssNone = 0, + ssShift = 1, + ssLeft = 2, + ssRight = 4, + ssCtrl = 8, + ssAlt = 16, +}; +using TShiftState = int; +constexpr int UIToolBarSize = 24; +class XREUI_API xrUIManager +{ +public: + xrUIManager(); + void Push(xrUI *ui, bool need_deleted = true); + void Draw(); + + virtual ~xrUIManager(); + + LRESULT WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); + void Initialize(HWND hWnd, IDirect3DDevice9 *device, const char *ini_path); + void Destroy(); + + void ResetBegin(); + void ResetEnd(); + virtual bool ApplyShortCut(DWORD Key, TShiftState Shift) = 0; + + inline float GetMenuBarHeight() const { return m_MenuBarHeight; } + inline TShiftState GetShiftState() const { return m_ShiftState; }; + +protected: + virtual void OnDrawUI(); + +private: + float m_MenuBarHeight; + void ApplyShortCut(DWORD Key); + TShiftState m_ShiftState; + xr_vector m_UIArray; + string_path m_name_ini; +}; diff --git a/src/engine.sln b/src/engine.sln index 98f5a9c8350..31f60b3c05d 100644 --- a/src/engine.sln +++ b/src/engine.sln @@ -1,15 +1,15 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29009.5 +# Visual Studio Version 17 +VisualStudioVersion = 17.6.33717.318 MinimumVisualStudioVersion = 15.0.27130.2024 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "XR_3DA", "xr_3da\xr_3da.vcxproj", "{F4757631-E6E8-469B-AD5A-516BAA01DABD}" ProjectSection(ProjectDependencies) = postProject {200652A6-043E-4634-8837-87983B3BD5E0} = {200652A6-043E-4634-8837-87983B3BD5E0} {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6} = {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6} + {492D3DFE-9068-4E7E-A008-7C2420A651C0} = {492D3DFE-9068-4E7E-A008-7C2420A651C0} {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2} = {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2} {963BA4E5-499A-454D-B002-1D5ECE0527A6} = {963BA4E5-499A-454D-B002-1D5ECE0527A6} {AC9B12ED-A2D7-4337-A981-5BD8430E96D8} = {AC9B12ED-A2D7-4337-A981-5BD8430E96D8} - {492D3DFE-9068-4E7E-A008-7C2420A651C0} = {492D3DFE-9068-4E7E-A008-7C2420A651C0} EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "utils", "utils", "{89F6A7EE-3BBE-45D3-A8A8-5D9366CD987B}" @@ -30,34 +30,34 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ctool", "utils\ctool\ctool. EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ETools", "utils\ETools\ETools.vcxproj", "{65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}" ProjectSection(ProjectDependencies) = postProject + {15CBFEFF-7965-41F5-B4E2-21E8795C9159} = {15CBFEFF-7965-41F5-B4E2-21E8795C9159} {3A214E06-B95E-4D61-A291-1F8DF2EC10FD} = {3A214E06-B95E-4D61-A291-1F8DF2EC10FD} {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC} = {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC} - {15CBFEFF-7965-41F5-B4E2-21E8795C9159} = {15CBFEFF-7965-41F5-B4E2-21E8795C9159} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xrAI", "utils\xrAI\xrAI.vcxproj", "{EA5932F3-02FE-4AD3-89E8-7072DC465D25}" ProjectSection(ProjectDependencies) = postProject - {B90BDC22-A891-4B33-B562-29D701F65DBD} = {B90BDC22-A891-4B33-B562-29D701F65DBD} {2578C6D8-660D-48AE-9322-7422F8664F06} = {2578C6D8-660D-48AE-9322-7422F8664F06} - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} = {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} {A0F7D1FB-59A7-4717-A7E4-96F37E91998E} = {A0F7D1FB-59A7-4717-A7E4-96F37E91998E} + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} = {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} + {B90BDC22-A891-4B33-B562-29D701F65DBD} = {B90BDC22-A891-4B33-B562-29D701F65DBD} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xrCompress", "utils\xrCompress\xrCompress.vcxproj", "{EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xrDO_Light", "utils\xrDO_Light\xrDO_Light.vcxproj", "{B730F54D-1199-481A-AAD0-5DB684E067C0}" ProjectSection(ProjectDependencies) = postProject - {EFB76D6F-0092-439C-A783-C0BE10BD17C9} = {EFB76D6F-0092-439C-A783-C0BE10BD17C9} - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} = {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} {A0F7D1FB-59A7-4717-A7E4-96F37E91998E} = {A0F7D1FB-59A7-4717-A7E4-96F37E91998E} + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} = {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} + {EFB76D6F-0092-439C-A783-C0BE10BD17C9} = {EFB76D6F-0092-439C-A783-C0BE10BD17C9} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DXT", "utils\xrDXT\DXT.vcxproj", "{EBF9B543-0830-4866-9B48-DC0740E87E8A}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xrLC", "utils\xrLC\xrLC.vcxproj", "{A4ABD75E-825B-4D09-B3B2-2709682E40C8}" ProjectSection(ProjectDependencies) = postProject - {EFB76D6F-0092-439C-A783-C0BE10BD17C9} = {EFB76D6F-0092-439C-A783-C0BE10BD17C9} {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33} = {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33} + {EFB76D6F-0092-439C-A783-C0BE10BD17C9} = {EFB76D6F-0092-439C-A783-C0BE10BD17C9} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xrQSlim", "utils\xrQSlim\xrQSlim.vcxproj", "{F1836CE2-59EF-4189-8B9C-D103A511CB27}" @@ -128,23 +128,23 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "luabind", "..\Externals\lua EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Common", "Common\Common.vcxproj", "{EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}" ProjectSection(ProjectDependencies) = postProject - {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8} = {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8} {0899B131-F1D4-4876-9BA1-67AC821DB9E1} = {0899B131-F1D4-4876-9BA1-67AC821DB9E1} - {7885CF3C-EE04-4C67-9467-1FBF9A36B037} = {7885CF3C-EE04-4C67-9467-1FBF9A36B037} - {98D24A3D-7666-4C11-9D6E-B10393CE8CBA} = {98D24A3D-7666-4C11-9D6E-B10393CE8CBA} - {CCCA7859-EB86-493E-9B53-C4235F45B3C5} = {CCCA7859-EB86-493E-9B53-C4235F45B3C5} - {94A1C366-3D19-48E6-8170-4ADC2E70DF97} = {94A1C366-3D19-48E6-8170-4ADC2E70DF97} - {435BAC9A-B225-457D-AB40-C9BD0CC8838C} = {435BAC9A-B225-457D-AB40-C9BD0CC8838C} + {132C62DE-DE85-4978-9675-C78ED4DA46F0} = {132C62DE-DE85-4978-9675-C78ED4DA46F0} + {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8} = {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8} {200652A6-043E-4634-8837-87983B3BD5E0} = {200652A6-043E-4634-8837-87983B3BD5E0} + {2578C6D8-660D-48AE-9322-7422F8664F06} = {2578C6D8-660D-48AE-9322-7422F8664F06} + {435BAC9A-B225-457D-AB40-C9BD0CC8838C} = {435BAC9A-B225-457D-AB40-C9BD0CC8838C} {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7} = {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7} {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2} = {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2} {5CB057D8-4464-40A6-AF10-C26B826D1D90} = {5CB057D8-4464-40A6-AF10-C26B826D1D90} - {2578C6D8-660D-48AE-9322-7422F8664F06} = {2578C6D8-660D-48AE-9322-7422F8664F06} - {132C62DE-DE85-4978-9675-C78ED4DA46F0} = {132C62DE-DE85-4978-9675-C78ED4DA46F0} + {7885CF3C-EE04-4C67-9467-1FBF9A36B037} = {7885CF3C-EE04-4C67-9467-1FBF9A36B037} + {94A1C366-3D19-48E6-8170-4ADC2E70DF97} = {94A1C366-3D19-48E6-8170-4ADC2E70DF97} {963BA4E5-499A-454D-B002-1D5ECE0527A6} = {963BA4E5-499A-454D-B002-1D5ECE0527A6} - {AC9B12ED-A2D7-4337-A981-5BD8430E96D8} = {AC9B12ED-A2D7-4337-A981-5BD8430E96D8} - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} = {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} + {98D24A3D-7666-4C11-9D6E-B10393CE8CBA} = {98D24A3D-7666-4C11-9D6E-B10393CE8CBA} {A0F7D1FB-59A7-4717-A7E4-96F37E91998E} = {A0F7D1FB-59A7-4717-A7E4-96F37E91998E} + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} = {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5} + {AC9B12ED-A2D7-4337-A981-5BD8430E96D8} = {AC9B12ED-A2D7-4337-A981-5BD8430E96D8} + {CCCA7859-EB86-493E-9B53-C4235F45B3C5} = {CCCA7859-EB86-493E-9B53-C4235F45B3C5} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GameSpy", "..\Externals\GameSpy.vcxproj", "{67FF193E-2C20-402A-9026-9F5F6327503C}" @@ -199,6 +199,21 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xrWeatherEngine", "editors\ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "imgui", "..\Externals\imgui.vcxproj", "{C8FBC3CE-D6DE-4FC3-BC15-7B647614DB09}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ActorEditor", "editors\ActorEditor\ActorEditor.vcxproj", "{3145D38A-574B-4841-8AA9-CCD160B95124}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeMagic", "editors\FreeMagic\FreeMagic.vcxproj", "{DCC5B76D-BE13-4D1F-BE14-75D0FA678340}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LevelEditor", "editors\LevelEditor\LevelEditor.vcxproj", "{7E13BFCC-55B0-4715-8BBB-84A143CCE84B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ParticleEditor", "editors\ParticleEditor\ParticleEditor.vcxproj", "{19DC7E82-12AF-4110-93CA-E7C30500A3F5}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ShaderEditor", "editors\ShaderEditor\ShaderEditor.vcxproj", "{3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xrECore", "editors\XrECore\XrECore.vcxproj", "{9187BE98-531A-4276-B78E-DBA3C8AB8447}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xrEProps", "editors\XrEProps\XrEProps.vcxproj", "{6D47AFC7-0557-4BBF-8902-B248F3621419}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xrEUI", "editors\XrEUI\XrEUI.vcxproj", "{7E28883C-DB86-4EE8-813A-991BA20C68C9}" Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xrLuaFix", "..\Externals\xrLuaFix\xrLuaFix.vcxproj", "{4E076FEB-DC78-4BF7-99C7-AC8267247989}" EndProject Global @@ -221,10 +236,10 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|ARM.ActiveCfg = Debug|Win32 - {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|ARM.Build.0 = Debug|Win32 - {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|ARM64.ActiveCfg = Debug|x64 - {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|ARM64.Build.0 = Debug|x64 + {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|ARM.ActiveCfg = Debug|ARM + {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|ARM.Build.0 = Debug|ARM + {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|ARM64.Build.0 = Debug|ARM64 {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|x64.ActiveCfg = Debug|x64 {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|x64.Build.0 = Debug|x64 {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Debug|x86.ActiveCfg = Debug|Win32 @@ -245,18 +260,18 @@ Global {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|ARM.ActiveCfg = Release|Win32 - {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|ARM.Build.0 = Release|Win32 - {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|ARM64.ActiveCfg = Release|x64 - {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|ARM64.Build.0 = Release|x64 + {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|ARM.ActiveCfg = Release|ARM + {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|ARM.Build.0 = Release|ARM + {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|ARM64.ActiveCfg = Release|ARM64 + {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|ARM64.Build.0 = Release|ARM64 {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|x64.ActiveCfg = Release|x64 {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|x64.Build.0 = Release|x64 {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|x86.ActiveCfg = Release|Win32 {F4757631-E6E8-469B-AD5A-516BAA01DABD}.Release|x86.Build.0 = Release|Win32 - {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|ARM.ActiveCfg = Debug|Win32 - {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|ARM.Build.0 = Debug|Win32 - {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|ARM64.ActiveCfg = Debug|x64 - {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|ARM64.Build.0 = Debug|x64 + {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|ARM.ActiveCfg = Debug|ARM + {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|ARM.Build.0 = Debug|ARM + {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|ARM64.Build.0 = Debug|ARM64 {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|x64.ActiveCfg = Debug|x64 {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|x64.Build.0 = Debug|x64 {1BF75FEB-87DD-486C-880B-227987D191C2}.Debug|x86.ActiveCfg = Debug|Win32 @@ -277,18 +292,18 @@ Global {1BF75FEB-87DD-486C-880B-227987D191C2}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {1BF75FEB-87DD-486C-880B-227987D191C2}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {1BF75FEB-87DD-486C-880B-227987D191C2}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|ARM.ActiveCfg = Release|Win32 - {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|ARM.Build.0 = Release|Win32 - {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|ARM64.ActiveCfg = Release|x64 - {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|ARM64.Build.0 = Release|x64 + {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|ARM.ActiveCfg = Release|ARM + {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|ARM.Build.0 = Release|ARM + {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|ARM64.ActiveCfg = Release|ARM64 + {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|ARM64.Build.0 = Release|ARM64 {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|x64.ActiveCfg = Release|x64 {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|x64.Build.0 = Release|x64 {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|x86.ActiveCfg = Release|Win32 {1BF75FEB-87DD-486C-880B-227987D191C2}.Release|x86.Build.0 = Release|Win32 - {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|ARM.ActiveCfg = Debug|Win32 - {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|ARM.Build.0 = Debug|Win32 - {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|ARM64.ActiveCfg = Debug|x64 - {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|ARM64.Build.0 = Debug|x64 + {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|ARM.ActiveCfg = Debug|ARM + {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|ARM.Build.0 = Debug|ARM + {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|ARM64.Build.0 = Debug|ARM64 {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|x64.ActiveCfg = Debug|x64 {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|x64.Build.0 = Debug|x64 {566551F4-4EF1-4CB4-A131-F982E7606907}.Debug|x86.ActiveCfg = Debug|Win32 @@ -309,10 +324,10 @@ Global {566551F4-4EF1-4CB4-A131-F982E7606907}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {566551F4-4EF1-4CB4-A131-F982E7606907}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {566551F4-4EF1-4CB4-A131-F982E7606907}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|ARM.ActiveCfg = Release|Win32 - {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|ARM.Build.0 = Release|Win32 - {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|ARM64.ActiveCfg = Release|x64 - {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|ARM64.Build.0 = Release|x64 + {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|ARM.ActiveCfg = Release|ARM + {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|ARM.Build.0 = Release|ARM + {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|ARM64.ActiveCfg = Release|ARM64 + {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|ARM64.Build.0 = Release|ARM64 {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|x64.ActiveCfg = Release|x64 {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|x64.Build.0 = Release|x64 {566551F4-4EF1-4CB4-A131-F982E7606907}.Release|x86.ActiveCfg = Release|Win32 @@ -349,10 +364,10 @@ Global {0899B131-F1D4-4876-9BA1-67AC821DB9E1}.Release|x64.Build.0 = Release|x64 {0899B131-F1D4-4876-9BA1-67AC821DB9E1}.Release|x86.ActiveCfg = Release|Win32 {0899B131-F1D4-4876-9BA1-67AC821DB9E1}.Release|x86.Build.0 = Release|Win32 - {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|ARM.ActiveCfg = Debug|Win32 - {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|ARM.Build.0 = Debug|Win32 - {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|ARM64.ActiveCfg = Debug|x64 - {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|ARM64.Build.0 = Debug|x64 + {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|ARM.ActiveCfg = Debug|ARM + {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|ARM.Build.0 = Debug|ARM + {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|ARM64.Build.0 = Debug|ARM64 {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|x64.ActiveCfg = Debug|x64 {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|x64.Build.0 = Debug|x64 {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Debug|x86.ActiveCfg = Debug|Win32 @@ -369,18 +384,18 @@ Global {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|ARM.ActiveCfg = Release|Win32 - {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|ARM.Build.0 = Release|Win32 - {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|ARM64.ActiveCfg = Release|x64 - {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|ARM64.Build.0 = Release|x64 + {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|ARM.ActiveCfg = Release|ARM + {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|ARM.Build.0 = Release|ARM + {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|ARM64.ActiveCfg = Release|ARM64 + {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|ARM64.Build.0 = Release|ARM64 {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|x64.ActiveCfg = Release|x64 {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|x64.Build.0 = Release|x64 {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|x86.ActiveCfg = Release|Win32 {C961EA19-716C-4A6D-BB13-689F8FB78B01}.Release|x86.Build.0 = Release|Win32 - {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|ARM.ActiveCfg = Debug|Win32 - {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|ARM.Build.0 = Debug|Win32 - {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|ARM64.ActiveCfg = Debug|x64 - {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|ARM64.Build.0 = Debug|x64 + {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|ARM.ActiveCfg = Debug|ARM + {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|ARM.Build.0 = Debug|ARM + {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|ARM64.Build.0 = Debug|ARM64 {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|x64.ActiveCfg = Debug|x64 {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|x64.Build.0 = Debug|x64 {2FAAC8BA-369F-465E-B465-2235963FD377}.Debug|x86.ActiveCfg = Debug|Win32 @@ -397,18 +412,18 @@ Global {2FAAC8BA-369F-465E-B465-2235963FD377}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {2FAAC8BA-369F-465E-B465-2235963FD377}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {2FAAC8BA-369F-465E-B465-2235963FD377}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|ARM.ActiveCfg = Release|Win32 - {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|ARM.Build.0 = Release|Win32 - {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|ARM64.ActiveCfg = Release|x64 - {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|ARM64.Build.0 = Release|x64 + {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|ARM.ActiveCfg = Release|ARM + {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|ARM.Build.0 = Release|ARM + {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|ARM64.ActiveCfg = Release|ARM64 + {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|ARM64.Build.0 = Release|ARM64 {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|x64.ActiveCfg = Release|x64 {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|x64.Build.0 = Release|x64 {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|x86.ActiveCfg = Release|Win32 {2FAAC8BA-369F-465E-B465-2235963FD377}.Release|x86.Build.0 = Release|Win32 - {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|ARM.ActiveCfg = Debug|Win32 - {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|ARM.Build.0 = Debug|Win32 - {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|ARM64.ActiveCfg = Debug|x64 - {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|ARM64.Build.0 = Debug|x64 + {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|ARM.ActiveCfg = Debug|ARM + {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|ARM.Build.0 = Debug|ARM + {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|ARM64.Build.0 = Debug|ARM64 {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|x64.ActiveCfg = Debug|x64 {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|x64.Build.0 = Debug|x64 {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Debug|x86.ActiveCfg = Debug|Win32 @@ -425,18 +440,18 @@ Global {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|ARM.ActiveCfg = Release|Win32 - {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|ARM.Build.0 = Release|Win32 - {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|ARM64.ActiveCfg = Release|x64 - {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|ARM64.Build.0 = Release|x64 + {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|ARM.ActiveCfg = Release|ARM + {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|ARM.Build.0 = Release|ARM + {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|ARM64.ActiveCfg = Release|ARM64 + {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|ARM64.Build.0 = Release|ARM64 {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|x64.ActiveCfg = Release|x64 {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|x64.Build.0 = Release|x64 {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|x86.ActiveCfg = Release|Win32 {65CBB9D0-FBC6-41A4-8316-F5E9B5D7FB33}.Release|x86.Build.0 = Release|Win32 - {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|ARM.ActiveCfg = Debug|Win32 - {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|ARM.Build.0 = Debug|Win32 - {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|ARM64.ActiveCfg = Debug|x64 - {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|ARM64.Build.0 = Debug|x64 + {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|ARM.ActiveCfg = Debug|ARM + {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|ARM.Build.0 = Debug|ARM + {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|ARM64.Build.0 = Debug|ARM64 {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|x64.ActiveCfg = Debug|x64 {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|x64.Build.0 = Debug|x64 {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Debug|x86.ActiveCfg = Debug|Win32 @@ -453,18 +468,18 @@ Global {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|ARM.ActiveCfg = Release|Win32 - {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|ARM.Build.0 = Release|Win32 - {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|ARM64.ActiveCfg = Release|x64 - {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|ARM64.Build.0 = Release|x64 + {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|ARM.ActiveCfg = Release|ARM + {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|ARM.Build.0 = Release|ARM + {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|ARM64.ActiveCfg = Release|ARM64 + {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|ARM64.Build.0 = Release|ARM64 {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|x64.ActiveCfg = Release|x64 {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|x64.Build.0 = Release|x64 {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|x86.ActiveCfg = Release|Win32 {EA5932F3-02FE-4AD3-89E8-7072DC465D25}.Release|x86.Build.0 = Release|Win32 - {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|ARM.ActiveCfg = Debug|Win32 - {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|ARM.Build.0 = Debug|Win32 - {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|ARM64.ActiveCfg = Debug|x64 - {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|ARM64.Build.0 = Debug|x64 + {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|ARM.ActiveCfg = Debug|ARM + {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|ARM.Build.0 = Debug|ARM + {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|ARM64.Build.0 = Debug|ARM64 {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|x64.ActiveCfg = Debug|x64 {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|x64.Build.0 = Debug|x64 {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Debug|x86.ActiveCfg = Debug|Win32 @@ -485,18 +500,18 @@ Global {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|ARM.ActiveCfg = Release|Win32 - {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|ARM.Build.0 = Release|Win32 - {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|ARM64.ActiveCfg = Release|x64 - {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|ARM64.Build.0 = Release|x64 + {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|ARM.ActiveCfg = Release|ARM + {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|ARM.Build.0 = Release|ARM + {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|ARM64.ActiveCfg = Release|ARM64 + {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|ARM64.Build.0 = Release|ARM64 {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|x64.ActiveCfg = Release|x64 {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|x64.Build.0 = Release|x64 {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|x86.ActiveCfg = Release|Win32 {EF76867B-6EB8-4DC0-A1D6-E964FAD6FC7B}.Release|x86.Build.0 = Release|Win32 - {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|ARM.ActiveCfg = Debug|Win32 - {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|ARM.Build.0 = Debug|Win32 - {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|ARM64.ActiveCfg = Debug|x64 - {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|ARM64.Build.0 = Debug|x64 + {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|ARM.ActiveCfg = Debug|ARM + {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|ARM.Build.0 = Debug|ARM + {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|ARM64.Build.0 = Debug|ARM64 {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|x64.ActiveCfg = Debug|x64 {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|x64.Build.0 = Debug|x64 {B730F54D-1199-481A-AAD0-5DB684E067C0}.Debug|x86.ActiveCfg = Debug|Win32 @@ -513,18 +528,18 @@ Global {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|ARM.ActiveCfg = Release|Win32 - {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|ARM.Build.0 = Release|Win32 - {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|ARM64.ActiveCfg = Release|x64 - {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|ARM64.Build.0 = Release|x64 + {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|ARM.ActiveCfg = Release|ARM + {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|ARM.Build.0 = Release|ARM + {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|ARM64.ActiveCfg = Release|ARM64 + {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|ARM64.Build.0 = Release|ARM64 {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|x64.ActiveCfg = Release|x64 {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|x64.Build.0 = Release|x64 {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|x86.ActiveCfg = Release|Win32 {B730F54D-1199-481A-AAD0-5DB684E067C0}.Release|x86.Build.0 = Release|Win32 - {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|ARM.ActiveCfg = Debug|Win32 - {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|ARM.Build.0 = Debug|Win32 - {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|ARM64.ActiveCfg = Debug|x64 - {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|ARM64.Build.0 = Debug|x64 + {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|ARM.ActiveCfg = Debug|ARM + {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|ARM.Build.0 = Debug|ARM + {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|ARM64.Build.0 = Debug|ARM64 {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|x64.ActiveCfg = Debug|x64 {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|x64.Build.0 = Debug|x64 {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Debug|x86.ActiveCfg = Debug|Win32 @@ -541,18 +556,18 @@ Global {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|ARM.ActiveCfg = Release|Win32 - {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|ARM.Build.0 = Release|Win32 - {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|ARM64.ActiveCfg = Release|x64 - {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|ARM64.Build.0 = Release|x64 + {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|ARM.ActiveCfg = Release|ARM + {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|ARM.Build.0 = Release|ARM + {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|ARM64.ActiveCfg = Release|ARM64 + {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|ARM64.Build.0 = Release|ARM64 {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|x64.ActiveCfg = Release|x64 {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|x64.Build.0 = Release|x64 {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|x86.ActiveCfg = Release|Win32 {EBF9B543-0830-4866-9B48-DC0740E87E8A}.Release|x86.Build.0 = Release|Win32 - {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|ARM.ActiveCfg = Debug|Win32 - {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|ARM.Build.0 = Debug|Win32 - {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|ARM64.ActiveCfg = Debug|x64 - {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|ARM64.Build.0 = Debug|x64 + {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|ARM.ActiveCfg = Debug|ARM + {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|ARM.Build.0 = Debug|ARM + {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|ARM64.Build.0 = Debug|ARM64 {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|x64.ActiveCfg = Debug|x64 {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|x64.Build.0 = Debug|x64 {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Debug|x86.ActiveCfg = Debug|Win32 @@ -569,18 +584,18 @@ Global {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|ARM.ActiveCfg = Release|Win32 - {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|ARM.Build.0 = Release|Win32 - {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|ARM64.ActiveCfg = Release|x64 - {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|ARM64.Build.0 = Release|x64 + {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|ARM.ActiveCfg = Release|ARM + {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|ARM.Build.0 = Release|ARM + {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|ARM64.ActiveCfg = Release|ARM64 + {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|ARM64.Build.0 = Release|ARM64 {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|x64.ActiveCfg = Release|x64 {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|x64.Build.0 = Release|x64 {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|x86.ActiveCfg = Release|Win32 {A4ABD75E-825B-4D09-B3B2-2709682E40C8}.Release|x86.Build.0 = Release|Win32 - {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|ARM.ActiveCfg = Debug|Win32 - {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|ARM.Build.0 = Debug|Win32 - {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|ARM64.ActiveCfg = Debug|x64 - {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|ARM64.Build.0 = Debug|x64 + {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|ARM.ActiveCfg = Debug|ARM + {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|ARM.Build.0 = Debug|ARM + {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|ARM64.Build.0 = Debug|ARM64 {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|x64.ActiveCfg = Debug|x64 {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|x64.Build.0 = Debug|x64 {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Debug|x86.ActiveCfg = Debug|Win32 @@ -597,18 +612,18 @@ Global {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|ARM.ActiveCfg = Release|Win32 - {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|ARM.Build.0 = Release|Win32 - {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|ARM64.ActiveCfg = Release|x64 - {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|ARM64.Build.0 = Release|x64 + {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|ARM.ActiveCfg = Release|ARM + {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|ARM.Build.0 = Release|ARM + {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|ARM64.ActiveCfg = Release|ARM64 + {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|ARM64.Build.0 = Release|ARM64 {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|x64.ActiveCfg = Release|x64 {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|x64.Build.0 = Release|x64 {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|x86.ActiveCfg = Release|Win32 {F1836CE2-59EF-4189-8B9C-D103A511CB27}.Release|x86.Build.0 = Release|Win32 - {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|ARM.ActiveCfg = Debug|Win32 - {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|ARM.Build.0 = Debug|Win32 - {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|ARM64.ActiveCfg = Debug|x64 - {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|ARM64.Build.0 = Debug|x64 + {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|ARM.ActiveCfg = Debug|ARM + {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|ARM.Build.0 = Debug|ARM + {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|ARM64.Build.0 = Debug|ARM64 {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|x64.ActiveCfg = Debug|x64 {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|x64.Build.0 = Debug|x64 {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Debug|x86.ActiveCfg = Debug|Win32 @@ -626,18 +641,18 @@ Global {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|ARM.ActiveCfg = Release|Win32 - {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|ARM.Build.0 = Release|Win32 - {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|ARM64.ActiveCfg = Release|x64 - {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|ARM64.Build.0 = Release|x64 + {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|ARM.ActiveCfg = Release|ARM + {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|ARM.Build.0 = Release|ARM + {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|ARM64.ActiveCfg = Release|ARM64 + {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|ARM64.Build.0 = Release|ARM64 {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|x64.ActiveCfg = Release|x64 {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|x64.Build.0 = Release|x64 {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|x86.ActiveCfg = Release|Win32 {3AD26FD3-4F52-4E22-A4CF-AD4C49E74C61}.Release|x86.Build.0 = Release|Win32 - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|ARM.ActiveCfg = Debug|Win32 - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|ARM.Build.0 = Debug|Win32 - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|ARM64.ActiveCfg = Debug|x64 - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|ARM64.Build.0 = Debug|x64 + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|ARM.ActiveCfg = Debug|ARM + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|ARM.Build.0 = Debug|ARM + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|ARM64.Build.0 = Debug|ARM64 {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|x64.ActiveCfg = Debug|x64 {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|x64.Build.0 = Debug|x64 {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Debug|x86.ActiveCfg = Debug|Win32 @@ -658,18 +673,18 @@ Global {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|ARM.ActiveCfg = Release|Win32 - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|ARM.Build.0 = Release|Win32 - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|ARM64.ActiveCfg = Release|x64 - {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|ARM64.Build.0 = Release|x64 + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|ARM.ActiveCfg = Release|ARM + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|ARM.Build.0 = Release|ARM + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|ARM64.ActiveCfg = Release|ARM64 + {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|ARM64.Build.0 = Release|ARM64 {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|x64.ActiveCfg = Release|x64 {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|x64.Build.0 = Release|x64 {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|x86.ActiveCfg = Release|Win32 {A19B1DF2-82EC-4364-8BDF-85D13A1C89B5}.Release|x86.Build.0 = Release|Win32 - {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|ARM.ActiveCfg = Debug|Win32 - {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|ARM.Build.0 = Debug|Win32 - {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|ARM64.ActiveCfg = Debug|x64 - {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|ARM64.Build.0 = Debug|x64 + {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|ARM.ActiveCfg = Debug|ARM + {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|ARM.Build.0 = Debug|ARM + {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|ARM64.Build.0 = Debug|ARM64 {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|x64.ActiveCfg = Debug|x64 {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|x64.Build.0 = Debug|x64 {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Debug|x86.ActiveCfg = Debug|Win32 @@ -690,18 +705,18 @@ Global {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|ARM.ActiveCfg = Release|Win32 - {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|ARM.Build.0 = Release|Win32 - {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|ARM64.ActiveCfg = Release|x64 - {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|ARM64.Build.0 = Release|x64 + {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|ARM.ActiveCfg = Release|ARM + {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|ARM.Build.0 = Release|ARM + {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|ARM64.ActiveCfg = Release|ARM64 + {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|ARM64.Build.0 = Release|ARM64 {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|x64.ActiveCfg = Release|x64 {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|x64.Build.0 = Release|x64 {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|x86.ActiveCfg = Release|Win32 {A0F7D1FB-59A7-4717-A7E4-96F37E91998E}.Release|x86.Build.0 = Release|Win32 - {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|ARM.ActiveCfg = Debug|Win32 - {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|ARM.Build.0 = Debug|Win32 - {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|ARM64.ActiveCfg = Debug|x64 - {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|ARM64.Build.0 = Debug|x64 + {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|ARM.ActiveCfg = Debug|ARM + {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|ARM.Build.0 = Debug|ARM + {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|ARM64.Build.0 = Debug|ARM64 {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|x64.ActiveCfg = Debug|x64 {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|x64.Build.0 = Debug|x64 {200652A6-043E-4634-8837-87983B3BD5E0}.Debug|x86.ActiveCfg = Debug|Win32 @@ -722,18 +737,18 @@ Global {200652A6-043E-4634-8837-87983B3BD5E0}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {200652A6-043E-4634-8837-87983B3BD5E0}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {200652A6-043E-4634-8837-87983B3BD5E0}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {200652A6-043E-4634-8837-87983B3BD5E0}.Release|ARM.ActiveCfg = Release|Win32 - {200652A6-043E-4634-8837-87983B3BD5E0}.Release|ARM.Build.0 = Release|Win32 - {200652A6-043E-4634-8837-87983B3BD5E0}.Release|ARM64.ActiveCfg = Release|x64 - {200652A6-043E-4634-8837-87983B3BD5E0}.Release|ARM64.Build.0 = Release|x64 + {200652A6-043E-4634-8837-87983B3BD5E0}.Release|ARM.ActiveCfg = Release|ARM + {200652A6-043E-4634-8837-87983B3BD5E0}.Release|ARM.Build.0 = Release|ARM + {200652A6-043E-4634-8837-87983B3BD5E0}.Release|ARM64.ActiveCfg = Release|ARM64 + {200652A6-043E-4634-8837-87983B3BD5E0}.Release|ARM64.Build.0 = Release|ARM64 {200652A6-043E-4634-8837-87983B3BD5E0}.Release|x64.ActiveCfg = Release|x64 {200652A6-043E-4634-8837-87983B3BD5E0}.Release|x64.Build.0 = Release|x64 {200652A6-043E-4634-8837-87983B3BD5E0}.Release|x86.ActiveCfg = Release|Win32 {200652A6-043E-4634-8837-87983B3BD5E0}.Release|x86.Build.0 = Release|Win32 - {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|ARM.ActiveCfg = Debug|Win32 - {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|ARM.Build.0 = Debug|Win32 - {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|ARM64.ActiveCfg = Debug|x64 - {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|ARM64.Build.0 = Debug|x64 + {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|ARM.ActiveCfg = Debug|ARM + {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|ARM.Build.0 = Debug|ARM + {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|ARM64.Build.0 = Debug|ARM64 {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|x64.ActiveCfg = Debug|x64 {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|x64.Build.0 = Debug|x64 {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Debug|x86.ActiveCfg = Debug|Win32 @@ -754,18 +769,18 @@ Global {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|ARM.ActiveCfg = Release|Win32 - {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|ARM.Build.0 = Release|Win32 - {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|ARM64.ActiveCfg = Release|x64 - {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|ARM64.Build.0 = Release|x64 + {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|ARM.ActiveCfg = Release|ARM + {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|ARM.Build.0 = Release|ARM + {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|ARM64.ActiveCfg = Release|ARM64 + {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|ARM64.Build.0 = Release|ARM64 {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|x64.ActiveCfg = Release|x64 {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|x64.Build.0 = Release|x64 {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|x86.ActiveCfg = Release|Win32 {5535F6B4-7AE6-4B66-8AEA-CC31C14D7AB7}.Release|x86.Build.0 = Release|Win32 - {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|ARM.ActiveCfg = Debug|Win32 - {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|ARM.Build.0 = Debug|Win32 - {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|ARM64.ActiveCfg = Debug|x64 - {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|ARM64.Build.0 = Debug|x64 + {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|ARM.ActiveCfg = Debug|ARM + {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|ARM.Build.0 = Debug|ARM + {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|ARM64.Build.0 = Debug|ARM64 {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|x64.ActiveCfg = Debug|x64 {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|x64.Build.0 = Debug|x64 {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Debug|x86.ActiveCfg = Debug|Win32 @@ -786,18 +801,18 @@ Global {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|ARM.ActiveCfg = Release|Win32 - {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|ARM.Build.0 = Release|Win32 - {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|ARM64.ActiveCfg = Release|x64 - {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|ARM64.Build.0 = Release|x64 + {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|ARM.ActiveCfg = Release|ARM + {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|ARM.Build.0 = Release|ARM + {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|ARM64.ActiveCfg = Release|ARM64 + {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|ARM64.Build.0 = Release|ARM64 {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|x64.ActiveCfg = Release|x64 {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|x64.Build.0 = Release|x64 {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|x86.ActiveCfg = Release|Win32 {435BAC9A-B225-457D-AB40-C9BD0CC8838C}.Release|x86.Build.0 = Release|Win32 - {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|ARM.ActiveCfg = Debug|Win32 - {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|ARM.Build.0 = Debug|Win32 - {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|ARM64.ActiveCfg = Debug|x64 - {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|ARM64.Build.0 = Debug|x64 + {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|ARM.ActiveCfg = Debug|ARM + {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|ARM.Build.0 = Debug|ARM + {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|ARM64.Build.0 = Debug|ARM64 {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|x64.ActiveCfg = Debug|x64 {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|x64.Build.0 = Debug|x64 {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Debug|x86.ActiveCfg = Debug|Win32 @@ -818,18 +833,18 @@ Global {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|ARM.ActiveCfg = Release|Win32 - {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|ARM.Build.0 = Release|Win32 - {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|ARM64.ActiveCfg = Release|x64 - {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|ARM64.Build.0 = Release|x64 + {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|ARM.ActiveCfg = Release|ARM + {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|ARM.Build.0 = Release|ARM + {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|ARM64.ActiveCfg = Release|ARM64 + {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|ARM64.Build.0 = Release|ARM64 {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|x64.ActiveCfg = Release|x64 {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|x64.Build.0 = Release|x64 {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|x86.ActiveCfg = Release|Win32 {94A1C366-3D19-48E6-8170-4ADC2E70DF97}.Release|x86.Build.0 = Release|Win32 - {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|ARM.ActiveCfg = Debug|Win32 - {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|ARM.Build.0 = Debug|Win32 - {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|ARM64.ActiveCfg = Debug|x64 - {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|ARM64.Build.0 = Debug|x64 + {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|ARM.ActiveCfg = Debug|ARM + {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|ARM.Build.0 = Debug|ARM + {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|ARM64.Build.0 = Debug|ARM64 {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|x64.ActiveCfg = Debug|x64 {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|x64.Build.0 = Debug|x64 {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Debug|x86.ActiveCfg = Debug|Win32 @@ -850,18 +865,18 @@ Global {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|ARM.ActiveCfg = Release|Win32 - {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|ARM.Build.0 = Release|Win32 - {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|ARM64.ActiveCfg = Release|x64 - {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|ARM64.Build.0 = Release|x64 + {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|ARM.ActiveCfg = Release|ARM + {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|ARM.Build.0 = Release|ARM + {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|ARM64.ActiveCfg = Release|ARM64 + {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|ARM64.Build.0 = Release|ARM64 {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|x64.ActiveCfg = Release|x64 {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|x64.Build.0 = Release|x64 {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|x86.ActiveCfg = Release|Win32 {57A498C9-A741-4DDF-8EFC-BFB9EB6B00E2}.Release|x86.Build.0 = Release|Win32 - {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|ARM.ActiveCfg = Debug|Win32 - {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|ARM.Build.0 = Debug|Win32 - {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|ARM64.ActiveCfg = Debug|x64 - {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|ARM64.Build.0 = Debug|x64 + {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|ARM.ActiveCfg = Debug|ARM + {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|ARM.Build.0 = Debug|ARM + {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|ARM64.Build.0 = Debug|ARM64 {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|x64.ActiveCfg = Debug|x64 {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|x64.Build.0 = Debug|x64 {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Debug|x86.ActiveCfg = Debug|Win32 @@ -882,18 +897,18 @@ Global {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|ARM.ActiveCfg = Release|Win32 - {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|ARM.Build.0 = Release|Win32 - {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|ARM64.ActiveCfg = Release|x64 - {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|ARM64.Build.0 = Release|x64 + {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|ARM.ActiveCfg = Release|ARM + {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|ARM.Build.0 = Release|ARM + {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|ARM64.ActiveCfg = Release|ARM64 + {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|ARM64.Build.0 = Release|ARM64 {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|x64.ActiveCfg = Release|x64 {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|x64.Build.0 = Release|x64 {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|x86.ActiveCfg = Release|Win32 {963BA4E5-499A-454D-B002-1D5ECE0527A6}.Release|x86.Build.0 = Release|Win32 - {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|ARM.ActiveCfg = Debug|Win32 - {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|ARM.Build.0 = Debug|Win32 - {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|ARM64.ActiveCfg = Debug|x64 - {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|ARM64.Build.0 = Debug|x64 + {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|ARM.ActiveCfg = Debug|ARM + {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|ARM.Build.0 = Debug|ARM + {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|ARM64.Build.0 = Debug|ARM64 {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|x64.ActiveCfg = Debug|x64 {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|x64.Build.0 = Debug|x64 {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Debug|x86.ActiveCfg = Debug|Win32 @@ -914,18 +929,18 @@ Global {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|ARM.ActiveCfg = Release|Win32 - {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|ARM.Build.0 = Release|Win32 - {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|ARM64.ActiveCfg = Release|x64 - {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|ARM64.Build.0 = Release|x64 + {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|ARM.ActiveCfg = Release|ARM + {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|ARM.Build.0 = Release|ARM + {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|ARM64.ActiveCfg = Release|ARM64 + {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|ARM64.Build.0 = Release|ARM64 {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|x64.ActiveCfg = Release|x64 {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|x64.Build.0 = Release|x64 {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|x86.ActiveCfg = Release|Win32 {CCCA7859-EB86-493E-9B53-C4235F45B3C5}.Release|x86.Build.0 = Release|Win32 - {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|ARM.ActiveCfg = Debug|Win32 - {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|ARM.Build.0 = Debug|Win32 - {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|ARM64.ActiveCfg = Debug|x64 - {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|ARM64.Build.0 = Debug|x64 + {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|ARM.ActiveCfg = Debug|ARM + {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|ARM.Build.0 = Debug|ARM + {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|ARM64.Build.0 = Debug|ARM64 {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|x64.ActiveCfg = Debug|x64 {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|x64.Build.0 = Debug|x64 {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Debug|x86.ActiveCfg = Debug|Win32 @@ -946,18 +961,18 @@ Global {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|ARM.ActiveCfg = Release|Win32 - {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|ARM.Build.0 = Release|Win32 - {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|ARM64.ActiveCfg = Release|x64 - {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|ARM64.Build.0 = Release|x64 + {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|ARM.ActiveCfg = Release|ARM + {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|ARM.Build.0 = Release|ARM + {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|ARM64.ActiveCfg = Release|ARM64 + {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|ARM64.Build.0 = Release|ARM64 {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|x64.ActiveCfg = Release|x64 {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|x64.Build.0 = Release|x64 {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|x86.ActiveCfg = Release|Win32 {1DAEC516-E52C-4A3C-A4DA-AE3553E6E0F8}.Release|x86.Build.0 = Release|Win32 - {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|ARM.ActiveCfg = Debug|Win32 - {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|ARM.Build.0 = Debug|Win32 - {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|ARM64.ActiveCfg = Debug|x64 - {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|ARM64.Build.0 = Debug|x64 + {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|ARM.ActiveCfg = Debug|ARM + {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|ARM.Build.0 = Debug|ARM + {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|ARM64.Build.0 = Debug|ARM64 {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|x64.ActiveCfg = Debug|x64 {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|x64.Build.0 = Debug|x64 {2578C6D8-660D-48AE-9322-7422F8664F06}.Debug|x86.ActiveCfg = Debug|Win32 @@ -978,18 +993,18 @@ Global {2578C6D8-660D-48AE-9322-7422F8664F06}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {2578C6D8-660D-48AE-9322-7422F8664F06}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {2578C6D8-660D-48AE-9322-7422F8664F06}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|ARM.ActiveCfg = Release|Win32 - {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|ARM.Build.0 = Release|Win32 - {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|ARM64.ActiveCfg = Release|x64 - {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|ARM64.Build.0 = Release|x64 + {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|ARM.ActiveCfg = Release|ARM + {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|ARM.Build.0 = Release|ARM + {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|ARM64.ActiveCfg = Release|ARM64 + {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|ARM64.Build.0 = Release|ARM64 {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|x64.ActiveCfg = Release|x64 {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|x64.Build.0 = Release|x64 {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|x86.ActiveCfg = Release|Win32 {2578C6D8-660D-48AE-9322-7422F8664F06}.Release|x86.Build.0 = Release|Win32 - {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|ARM.ActiveCfg = Debug|Win32 - {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|ARM.Build.0 = Debug|Win32 - {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|ARM64.ActiveCfg = Debug|x64 - {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|ARM64.Build.0 = Debug|x64 + {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|ARM.ActiveCfg = Debug|ARM + {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|ARM.Build.0 = Debug|ARM + {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|ARM64.Build.0 = Debug|ARM64 {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|x64.ActiveCfg = Debug|x64 {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|x64.Build.0 = Debug|x64 {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1006,18 +1021,18 @@ Global {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|ARM.ActiveCfg = Release|Win32 - {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|ARM.Build.0 = Release|Win32 - {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|ARM64.ActiveCfg = Release|x64 - {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|ARM64.Build.0 = Release|x64 + {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|ARM.ActiveCfg = Release|ARM + {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|ARM.Build.0 = Release|ARM + {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|ARM64.ActiveCfg = Release|ARM64 + {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|ARM64.Build.0 = Release|ARM64 {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|x64.ActiveCfg = Release|x64 {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|x64.Build.0 = Release|x64 {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|x86.ActiveCfg = Release|Win32 {EFB76D6F-0092-439C-A783-C0BE10BD17C9}.Release|x86.Build.0 = Release|Win32 - {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|ARM.ActiveCfg = Debug|Win32 - {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|ARM.Build.0 = Debug|Win32 - {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|ARM64.ActiveCfg = Debug|x64 - {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|ARM64.Build.0 = Debug|x64 + {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|ARM.ActiveCfg = Debug|ARM + {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|ARM.Build.0 = Debug|ARM + {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|ARM64.Build.0 = Debug|ARM64 {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|x64.ActiveCfg = Debug|x64 {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|x64.Build.0 = Debug|x64 {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1034,18 +1049,18 @@ Global {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|ARM.ActiveCfg = Release|Win32 - {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|ARM.Build.0 = Release|Win32 - {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|ARM64.ActiveCfg = Release|x64 - {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|ARM64.Build.0 = Release|x64 + {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|ARM.ActiveCfg = Release|ARM + {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|ARM.Build.0 = Release|ARM + {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|ARM64.ActiveCfg = Release|ARM64 + {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|ARM64.Build.0 = Release|ARM64 {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|x64.ActiveCfg = Release|x64 {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|x64.Build.0 = Release|x64 {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|x86.ActiveCfg = Release|Win32 {EC924B9B-4991-4931-8623-E1DB9AE005CA}.Release|x86.Build.0 = Release|Win32 - {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|ARM.ActiveCfg = Debug|Win32 - {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|ARM.Build.0 = Debug|Win32 - {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|ARM64.ActiveCfg = Debug|x64 - {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|ARM64.Build.0 = Debug|x64 + {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|ARM.ActiveCfg = Debug|ARM + {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|ARM.Build.0 = Debug|ARM + {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|ARM64.Build.0 = Debug|ARM64 {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|x64.ActiveCfg = Debug|x64 {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|x64.Build.0 = Debug|x64 {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1066,18 +1081,18 @@ Global {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|ARM.ActiveCfg = Release|Win32 - {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|ARM.Build.0 = Release|Win32 - {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|ARM64.ActiveCfg = Release|x64 - {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|ARM64.Build.0 = Release|x64 + {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|ARM.ActiveCfg = Release|ARM + {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|ARM.Build.0 = Release|ARM + {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|ARM64.ActiveCfg = Release|ARM64 + {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|ARM64.Build.0 = Release|ARM64 {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|x64.ActiveCfg = Release|x64 {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|x64.Build.0 = Release|x64 {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|x86.ActiveCfg = Release|Win32 {98D24A3D-7666-4C11-9D6E-B10393CE8CBA}.Release|x86.Build.0 = Release|Win32 - {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|ARM.ActiveCfg = Debug|Win32 - {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|ARM.Build.0 = Debug|Win32 - {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|ARM64.ActiveCfg = Debug|x64 - {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|ARM64.Build.0 = Debug|x64 + {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|ARM.ActiveCfg = Debug|ARM + {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|ARM.Build.0 = Debug|ARM + {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|ARM64.Build.0 = Debug|ARM64 {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|x64.ActiveCfg = Debug|x64 {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|x64.Build.0 = Debug|x64 {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1098,18 +1113,18 @@ Global {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|ARM.ActiveCfg = Release|Win32 - {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|ARM.Build.0 = Release|Win32 - {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|ARM64.ActiveCfg = Release|x64 - {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|ARM64.Build.0 = Release|x64 + {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|ARM.ActiveCfg = Release|ARM + {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|ARM.Build.0 = Release|ARM + {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|ARM64.ActiveCfg = Release|ARM64 + {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|ARM64.Build.0 = Release|ARM64 {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|x64.ActiveCfg = Release|x64 {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|x64.Build.0 = Release|x64 {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|x86.ActiveCfg = Release|Win32 {AC9B12ED-A2D7-4337-A981-5BD8430E96D8}.Release|x86.Build.0 = Release|Win32 - {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|ARM.ActiveCfg = Debug|Win32 - {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|ARM.Build.0 = Debug|Win32 - {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|ARM64.ActiveCfg = Debug|x64 - {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|ARM64.Build.0 = Debug|x64 + {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|ARM.ActiveCfg = Debug|ARM + {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|ARM.Build.0 = Debug|ARM + {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|ARM64.Build.0 = Debug|ARM64 {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|x64.ActiveCfg = Debug|x64 {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|x64.Build.0 = Debug|x64 {032A10AB-E44C-4751-A290-001EF99E664A}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1130,18 +1145,18 @@ Global {032A10AB-E44C-4751-A290-001EF99E664A}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {032A10AB-E44C-4751-A290-001EF99E664A}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {032A10AB-E44C-4751-A290-001EF99E664A}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {032A10AB-E44C-4751-A290-001EF99E664A}.Release|ARM.ActiveCfg = Release|Win32 - {032A10AB-E44C-4751-A290-001EF99E664A}.Release|ARM.Build.0 = Release|Win32 - {032A10AB-E44C-4751-A290-001EF99E664A}.Release|ARM64.ActiveCfg = Release|x64 - {032A10AB-E44C-4751-A290-001EF99E664A}.Release|ARM64.Build.0 = Release|x64 + {032A10AB-E44C-4751-A290-001EF99E664A}.Release|ARM.ActiveCfg = Release|ARM + {032A10AB-E44C-4751-A290-001EF99E664A}.Release|ARM.Build.0 = Release|ARM + {032A10AB-E44C-4751-A290-001EF99E664A}.Release|ARM64.ActiveCfg = Release|ARM64 + {032A10AB-E44C-4751-A290-001EF99E664A}.Release|ARM64.Build.0 = Release|ARM64 {032A10AB-E44C-4751-A290-001EF99E664A}.Release|x64.ActiveCfg = Release|x64 {032A10AB-E44C-4751-A290-001EF99E664A}.Release|x64.Build.0 = Release|x64 {032A10AB-E44C-4751-A290-001EF99E664A}.Release|x86.ActiveCfg = Release|Win32 {032A10AB-E44C-4751-A290-001EF99E664A}.Release|x86.Build.0 = Release|Win32 - {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|ARM.ActiveCfg = Debug|Win32 - {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|ARM.Build.0 = Debug|Win32 - {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|ARM64.ActiveCfg = Debug|x64 - {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|ARM64.Build.0 = Debug|x64 + {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|ARM.ActiveCfg = Debug|ARM + {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|ARM.Build.0 = Debug|ARM + {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|ARM64.Build.0 = Debug|ARM64 {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|x64.ActiveCfg = Debug|x64 {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|x64.Build.0 = Debug|x64 {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1162,18 +1177,18 @@ Global {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|ARM.ActiveCfg = Release|Win32 - {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|ARM.Build.0 = Release|Win32 - {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|ARM64.ActiveCfg = Release|x64 - {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|ARM64.Build.0 = Release|x64 + {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|ARM.ActiveCfg = Release|ARM + {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|ARM.Build.0 = Release|ARM + {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|ARM64.ActiveCfg = Release|ARM64 + {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|ARM64.Build.0 = Release|ARM64 {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|x64.ActiveCfg = Release|x64 {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|x64.Build.0 = Release|x64 {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|x86.ActiveCfg = Release|Win32 {1924EF23-A05E-40E5-93F2-6CCD64BE1F8B}.Release|x86.Build.0 = Release|Win32 - {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|ARM.ActiveCfg = Debug|Win32 - {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|ARM.Build.0 = Debug|Win32 - {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|ARM64.ActiveCfg = Debug|x64 - {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|ARM64.Build.0 = Debug|x64 + {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|ARM.ActiveCfg = Debug|ARM + {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|ARM.Build.0 = Debug|ARM + {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|ARM64.Build.0 = Debug|ARM64 {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|x64.ActiveCfg = Debug|x64 {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|x64.Build.0 = Debug|x64 {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1194,18 +1209,18 @@ Global {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|ARM.ActiveCfg = Release|Win32 - {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|ARM.Build.0 = Release|Win32 - {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|ARM64.ActiveCfg = Release|x64 - {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|ARM64.Build.0 = Release|x64 + {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|ARM.ActiveCfg = Release|ARM + {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|ARM.Build.0 = Release|ARM + {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|ARM64.ActiveCfg = Release|ARM64 + {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|ARM64.Build.0 = Release|ARM64 {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|x64.ActiveCfg = Release|x64 {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|x64.Build.0 = Release|x64 {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|x86.ActiveCfg = Release|Win32 {880CD250-BA77-4DAF-A8D4-552F12DD3AE4}.Release|x86.Build.0 = Release|Win32 - {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|ARM.ActiveCfg = Debug|Win32 - {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|ARM.Build.0 = Debug|Win32 - {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|ARM64.ActiveCfg = Debug|x64 - {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|ARM64.Build.0 = Debug|x64 + {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|ARM.ActiveCfg = Debug|ARM + {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|ARM.Build.0 = Debug|ARM + {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|ARM64.Build.0 = Debug|ARM64 {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|x64.ActiveCfg = Debug|x64 {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|x64.Build.0 = Debug|x64 {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1226,10 +1241,10 @@ Global {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|ARM.ActiveCfg = Release|Win32 - {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|ARM.Build.0 = Release|Win32 - {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|ARM64.ActiveCfg = Release|x64 - {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|ARM64.Build.0 = Release|x64 + {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|ARM.ActiveCfg = Release|ARM + {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|ARM.Build.0 = Release|ARM + {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|ARM64.ActiveCfg = Release|ARM64 + {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|ARM64.Build.0 = Release|ARM64 {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|x64.ActiveCfg = Release|x64 {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|x64.Build.0 = Release|x64 {0EB257DC-5CFC-44B0-82C9-CE6B158BE473}.Release|x86.ActiveCfg = Release|Win32 @@ -1266,10 +1281,10 @@ Global {492D3DFE-9068-4E7E-A008-7C2420A651C0}.Release|ARM64.ActiveCfg = Release|x64 {492D3DFE-9068-4E7E-A008-7C2420A651C0}.Release|x64.ActiveCfg = Release|x64 {492D3DFE-9068-4E7E-A008-7C2420A651C0}.Release|x86.ActiveCfg = Release|Win32 - {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|ARM.ActiveCfg = Debug|Win32 - {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|ARM.Build.0 = Debug|Win32 - {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|ARM64.ActiveCfg = Debug|x64 - {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|ARM64.Build.0 = Debug|x64 + {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|ARM.ActiveCfg = Debug|ARM + {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|ARM.Build.0 = Debug|ARM + {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|ARM64.Build.0 = Debug|ARM64 {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|x64.ActiveCfg = Debug|x64 {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|x64.Build.0 = Debug|x64 {B90BDC22-A891-4B33-B562-29D701F65DBD}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1286,18 +1301,18 @@ Global {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|ARM.ActiveCfg = Release|Win32 - {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|ARM.Build.0 = Release|Win32 - {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|ARM64.ActiveCfg = Release|x64 - {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|ARM64.Build.0 = Release|x64 + {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|ARM.ActiveCfg = Release|ARM + {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|ARM.Build.0 = Release|ARM + {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|ARM64.ActiveCfg = Release|ARM64 + {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|ARM64.Build.0 = Release|ARM64 {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|x64.ActiveCfg = Release|x64 {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|x64.Build.0 = Release|x64 {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|x86.ActiveCfg = Release|Win32 {B90BDC22-A891-4B33-B562-29D701F65DBD}.Release|x86.Build.0 = Release|Win32 - {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|ARM.ActiveCfg = Debug|Win32 - {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|ARM.Build.0 = Debug|Win32 - {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|ARM64.ActiveCfg = Debug|x64 - {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|ARM64.Build.0 = Debug|x64 + {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|ARM.ActiveCfg = Debug|ARM + {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|ARM.Build.0 = Debug|ARM + {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|ARM64.Build.0 = Debug|ARM64 {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|x64.ActiveCfg = Debug|x64 {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|x64.Build.0 = Debug|x64 {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1318,18 +1333,18 @@ Global {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|ARM.ActiveCfg = Release|Win32 - {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|ARM.Build.0 = Release|Win32 - {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|ARM64.ActiveCfg = Release|x64 - {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|ARM64.Build.0 = Release|x64 + {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|ARM.ActiveCfg = Release|ARM + {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|ARM.Build.0 = Release|ARM + {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|ARM64.ActiveCfg = Release|ARM64 + {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|ARM64.Build.0 = Release|ARM64 {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|x64.ActiveCfg = Release|x64 {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|x64.Build.0 = Release|x64 {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|x86.ActiveCfg = Release|Win32 {5CB057D8-4464-40A6-AF10-C26B826D1D90}.Release|x86.Build.0 = Release|Win32 - {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|ARM.ActiveCfg = Debug|Win32 - {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|ARM.Build.0 = Debug|Win32 - {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|ARM64.ActiveCfg = Debug|x64 - {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|ARM64.Build.0 = Debug|x64 + {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|ARM.ActiveCfg = Debug|ARM + {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|ARM.Build.0 = Debug|ARM + {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|ARM64.Build.0 = Debug|ARM64 {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|x64.ActiveCfg = Debug|x64 {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|x64.Build.0 = Debug|x64 {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1350,18 +1365,18 @@ Global {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|ARM.ActiveCfg = Release|Win32 - {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|ARM.Build.0 = Release|Win32 - {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|ARM64.ActiveCfg = Release|x64 - {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|ARM64.Build.0 = Release|x64 + {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|ARM.ActiveCfg = Release|ARM + {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|ARM.Build.0 = Release|ARM + {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|ARM64.ActiveCfg = Release|ARM64 + {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|ARM64.Build.0 = Release|ARM64 {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|x64.ActiveCfg = Release|x64 {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|x64.Build.0 = Release|x64 {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|x86.ActiveCfg = Release|Win32 {132C62DE-DE85-4978-9675-C78ED4DA46F0}.Release|x86.Build.0 = Release|Win32 - {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|ARM.ActiveCfg = Debug|Win32 - {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|ARM.Build.0 = Debug|Win32 - {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|ARM64.ActiveCfg = Debug|x64 - {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|ARM64.Build.0 = Debug|x64 + {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|ARM.ActiveCfg = Debug|ARM + {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|ARM.Build.0 = Debug|ARM + {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|ARM64.Build.0 = Debug|ARM64 {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|x64.ActiveCfg = Debug|x64 {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|x64.Build.0 = Debug|x64 {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1382,16 +1397,16 @@ Global {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|ARM.ActiveCfg = Release|Win32 - {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|ARM.Build.0 = Release|Win32 - {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|ARM64.ActiveCfg = Release|x64 - {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|ARM64.Build.0 = Release|x64 + {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|ARM.ActiveCfg = Release|ARM + {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|ARM.Build.0 = Release|ARM + {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|ARM64.ActiveCfg = Release|ARM64 + {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|ARM64.Build.0 = Release|ARM64 {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|x64.ActiveCfg = Release|x64 {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|x64.Build.0 = Release|x64 {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|x86.ActiveCfg = Release|Win32 {CCD4AFAE-AA10-42C6-A452-FDEE497CCDF1}.Release|x86.Build.0 = Release|Win32 - {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Debug|ARM.ActiveCfg = Debug|Win32 - {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Debug|ARM64.ActiveCfg = Debug|x64 + {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Debug|ARM.ActiveCfg = Debug|ARM + {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Debug|ARM64.ActiveCfg = Debug|ARM64 {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Debug|x64.ActiveCfg = Debug|x64 {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Debug|x86.ActiveCfg = Debug|Win32 {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Mixed|ARM.ActiveCfg = Mixed|ARM @@ -1402,14 +1417,14 @@ Global {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Release|ARM.ActiveCfg = Release|Win32 - {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Release|ARM64.ActiveCfg = Release|x64 + {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Release|ARM.ActiveCfg = Release|ARM + {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Release|ARM64.ActiveCfg = Release|ARM64 {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Release|x64.ActiveCfg = Release|x64 {EDB0DFAF-5D6F-4D74-AE66-0DDADE12A7F6}.Release|x86.ActiveCfg = Release|Win32 - {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|ARM.ActiveCfg = Debug|Win32 - {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|ARM.Build.0 = Debug|Win32 - {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|ARM64.ActiveCfg = Debug|x64 - {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|ARM64.Build.0 = Debug|x64 + {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|ARM.ActiveCfg = Debug|ARM + {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|ARM.Build.0 = Debug|ARM + {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|ARM64.Build.0 = Debug|ARM64 {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|x64.ActiveCfg = Debug|x64 {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|x64.Build.0 = Debug|x64 {67FF193E-2C20-402A-9026-9F5F6327503C}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1430,18 +1445,18 @@ Global {67FF193E-2C20-402A-9026-9F5F6327503C}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {67FF193E-2C20-402A-9026-9F5F6327503C}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {67FF193E-2C20-402A-9026-9F5F6327503C}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|ARM.ActiveCfg = Release|Win32 - {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|ARM.Build.0 = Release|Win32 - {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|ARM64.ActiveCfg = Release|x64 - {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|ARM64.Build.0 = Release|x64 + {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|ARM.ActiveCfg = Release|ARM + {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|ARM.Build.0 = Release|ARM + {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|ARM64.ActiveCfg = Release|ARM64 + {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|ARM64.Build.0 = Release|ARM64 {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|x64.ActiveCfg = Release|x64 {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|x64.Build.0 = Release|x64 {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|x86.ActiveCfg = Release|Win32 {67FF193E-2C20-402A-9026-9F5F6327503C}.Release|x86.Build.0 = Release|Win32 - {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|ARM.ActiveCfg = Debug|Win32 - {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|ARM.Build.0 = Debug|Win32 - {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|ARM64.ActiveCfg = Debug|x64 - {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|ARM64.Build.0 = Debug|x64 + {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|ARM.ActiveCfg = Debug|ARM + {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|ARM.Build.0 = Debug|ARM + {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|ARM64.Build.0 = Debug|ARM64 {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|x64.ActiveCfg = Debug|x64 {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|x64.Build.0 = Debug|x64 {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1462,18 +1477,18 @@ Global {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|ARM.ActiveCfg = Release|Win32 - {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|ARM.Build.0 = Release|Win32 - {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|ARM64.ActiveCfg = Release|x64 - {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|ARM64.Build.0 = Release|x64 + {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|ARM.ActiveCfg = Release|ARM + {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|ARM.Build.0 = Release|ARM + {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|ARM64.ActiveCfg = Release|ARM64 + {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|ARM64.Build.0 = Release|ARM64 {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|x64.ActiveCfg = Release|x64 {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|x64.Build.0 = Release|x64 {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|x86.ActiveCfg = Release|Win32 {614AA57F-58D7-45A8-A5FF-93F04B05FAC6}.Release|x86.Build.0 = Release|Win32 - {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|ARM.ActiveCfg = Debug|Win32 - {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|ARM.Build.0 = Debug|Win32 - {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|ARM64.ActiveCfg = Debug|x64 - {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|ARM64.Build.0 = Debug|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|ARM.ActiveCfg = Debug|ARM + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|ARM.Build.0 = Debug|ARM + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|ARM64.Build.0 = Debug|ARM64 {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64 {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64 {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1494,18 +1509,18 @@ Global {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|ARM.ActiveCfg = Release|Win32 - {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|ARM.Build.0 = Release|Win32 - {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|ARM64.ActiveCfg = Release|x64 - {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|ARM64.Build.0 = Release|x64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|ARM.ActiveCfg = Release|ARM + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|ARM.Build.0 = Release|ARM + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|ARM64.ActiveCfg = Release|ARM64 + {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|ARM64.Build.0 = Release|ARM64 {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64 {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64 {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x86.ActiveCfg = Release|Win32 {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x86.Build.0 = Release|Win32 - {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|ARM.ActiveCfg = Debug|Win32 - {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|ARM.Build.0 = Debug|Win32 - {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|ARM64.ActiveCfg = Debug|x64 - {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|ARM64.Build.0 = Debug|x64 + {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|ARM.ActiveCfg = Debug|ARM + {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|ARM.Build.0 = Debug|ARM + {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|ARM64.Build.0 = Debug|ARM64 {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|x64.ActiveCfg = Debug|x64 {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|x64.Build.0 = Debug|x64 {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1526,18 +1541,18 @@ Global {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|ARM.ActiveCfg = Release|Win32 - {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|ARM.Build.0 = Release|Win32 - {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|ARM64.ActiveCfg = Release|x64 - {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|ARM64.Build.0 = Release|x64 + {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|ARM.ActiveCfg = Release|ARM + {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|ARM.Build.0 = Release|ARM + {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|ARM64.ActiveCfg = Release|ARM64 + {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|ARM64.Build.0 = Release|ARM64 {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|x64.ActiveCfg = Release|x64 {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|x64.Build.0 = Release|x64 {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|x86.ActiveCfg = Release|Win32 {15CBFEFF-7965-41F5-B4E2-21E8795C9159}.Release|x86.Build.0 = Release|Win32 - {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|ARM.ActiveCfg = Debug|Win32 - {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|ARM.Build.0 = Debug|Win32 - {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|ARM64.ActiveCfg = Debug|x64 - {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|ARM64.Build.0 = Debug|x64 + {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|ARM.ActiveCfg = Debug|ARM + {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|ARM.Build.0 = Debug|ARM + {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|ARM64.Build.0 = Debug|ARM64 {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|x64.ActiveCfg = Debug|x64 {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|x64.Build.0 = Debug|x64 {653F3841-3F26-49B9-AFCF-091DB4B67031}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1558,18 +1573,18 @@ Global {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|ARM.ActiveCfg = Release|Win32 - {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|ARM.Build.0 = Release|Win32 - {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|ARM64.ActiveCfg = Release|x64 - {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|ARM64.Build.0 = Release|x64 + {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|ARM.ActiveCfg = Release|ARM + {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|ARM.Build.0 = Release|ARM + {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|ARM64.ActiveCfg = Release|ARM64 + {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|ARM64.Build.0 = Release|ARM64 {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|x64.ActiveCfg = Release|x64 {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|x64.Build.0 = Release|x64 {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|x86.ActiveCfg = Release|Win32 {653F3841-3F26-49B9-AFCF-091DB4B67031}.Release|x86.Build.0 = Release|Win32 - {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|ARM.ActiveCfg = Debug|Win32 - {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|ARM.Build.0 = Debug|Win32 - {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|ARM64.ActiveCfg = Debug|x64 - {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|ARM64.Build.0 = Debug|x64 + {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|ARM.ActiveCfg = Debug|ARM + {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|ARM.Build.0 = Debug|ARM + {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|ARM64.Build.0 = Debug|ARM64 {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|x64.ActiveCfg = Debug|x64 {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|x64.Build.0 = Debug|x64 {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1590,18 +1605,18 @@ Global {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|ARM.ActiveCfg = Release|Win32 - {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|ARM.Build.0 = Release|Win32 - {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|ARM64.ActiveCfg = Release|x64 - {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|ARM64.Build.0 = Release|x64 + {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|ARM.ActiveCfg = Release|ARM + {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|ARM.Build.0 = Release|ARM + {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|ARM64.ActiveCfg = Release|ARM64 + {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|ARM64.Build.0 = Release|ARM64 {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|x64.ActiveCfg = Release|x64 {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|x64.Build.0 = Release|x64 {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|x86.ActiveCfg = Release|Win32 {3A214E06-B95E-4D61-A291-1F8DF2EC10FD}.Release|x86.Build.0 = Release|Win32 - {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|ARM.ActiveCfg = Debug|Win32 - {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|ARM.Build.0 = Debug|Win32 - {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|ARM64.ActiveCfg = Debug|x64 - {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|ARM64.Build.0 = Debug|x64 + {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|ARM.ActiveCfg = Debug|ARM + {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|ARM.Build.0 = Debug|ARM + {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|ARM64.Build.0 = Debug|ARM64 {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|x64.ActiveCfg = Debug|x64 {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|x64.Build.0 = Debug|x64 {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1622,18 +1637,18 @@ Global {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|ARM.ActiveCfg = Release|Win32 - {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|ARM.Build.0 = Release|Win32 - {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|ARM64.ActiveCfg = Release|x64 - {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|ARM64.Build.0 = Release|x64 + {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|ARM.ActiveCfg = Release|ARM + {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|ARM.Build.0 = Release|ARM + {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|ARM64.ActiveCfg = Release|ARM64 + {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|ARM64.Build.0 = Release|ARM64 {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|x64.ActiveCfg = Release|x64 {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|x64.Build.0 = Release|x64 {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|x86.ActiveCfg = Release|Win32 {CEBDE98B-A6AA-46E6-BC79-FAAF823DB9EC}.Release|x86.Build.0 = Release|Win32 - {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|ARM.ActiveCfg = Debug|Win32 - {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|ARM.Build.0 = Debug|Win32 - {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|ARM64.ActiveCfg = Debug|x64 - {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|ARM64.Build.0 = Debug|x64 + {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|ARM.ActiveCfg = Debug|ARM + {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|ARM.Build.0 = Debug|ARM + {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|ARM64.Build.0 = Debug|ARM64 {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|x64.ActiveCfg = Debug|x64 {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|x64.Build.0 = Debug|x64 {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1654,18 +1669,18 @@ Global {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|ARM.ActiveCfg = Release|Win32 - {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|ARM.Build.0 = Release|Win32 - {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|ARM64.ActiveCfg = Release|x64 - {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|ARM64.Build.0 = Release|x64 + {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|ARM.ActiveCfg = Release|ARM + {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|ARM.Build.0 = Release|ARM + {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|ARM64.ActiveCfg = Release|ARM64 + {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|ARM64.Build.0 = Release|ARM64 {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|x64.ActiveCfg = Release|x64 {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|x64.Build.0 = Release|x64 {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|x86.ActiveCfg = Release|Win32 {E8CF1ADA-264A-4127-86C2-FD7057D3792C}.Release|x86.Build.0 = Release|Win32 - {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|ARM.ActiveCfg = Debug|Win32 - {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|ARM.Build.0 = Debug|Win32 - {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|ARM64.ActiveCfg = Debug|x64 - {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|ARM64.Build.0 = Debug|x64 + {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|ARM.ActiveCfg = Debug|ARM + {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|ARM.Build.0 = Debug|ARM + {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|ARM64.Build.0 = Debug|ARM64 {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|x64.ActiveCfg = Debug|x64 {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|x64.Build.0 = Debug|x64 {848E8AB3-9962-4C04-B813-5690399C8A3E}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1686,18 +1701,18 @@ Global {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|ARM.ActiveCfg = Release|Win32 - {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|ARM.Build.0 = Release|Win32 - {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|ARM64.ActiveCfg = Release|x64 - {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|ARM64.Build.0 = Release|x64 + {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|ARM.ActiveCfg = Release|ARM + {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|ARM.Build.0 = Release|ARM + {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|ARM64.ActiveCfg = Release|ARM64 + {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|ARM64.Build.0 = Release|ARM64 {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|x64.ActiveCfg = Release|x64 {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|x64.Build.0 = Release|x64 {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|x86.ActiveCfg = Release|Win32 {848E8AB3-9962-4C04-B813-5690399C8A3E}.Release|x86.Build.0 = Release|Win32 - {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|ARM.ActiveCfg = Debug|Win32 - {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|ARM.Build.0 = Debug|Win32 - {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|ARM64.ActiveCfg = Debug|x64 - {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|ARM64.Build.0 = Debug|x64 + {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|ARM.ActiveCfg = Debug|ARM + {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|ARM.Build.0 = Debug|ARM + {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|ARM64.Build.0 = Debug|ARM64 {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|x64.ActiveCfg = Debug|x64 {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|x64.Build.0 = Debug|x64 {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1718,10 +1733,10 @@ Global {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|ARM.ActiveCfg = Release|Win32 - {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|ARM.Build.0 = Release|Win32 - {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|ARM64.ActiveCfg = Release|x64 - {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|ARM64.Build.0 = Release|x64 + {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|ARM.ActiveCfg = Release|ARM + {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|ARM.Build.0 = Release|ARM + {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|ARM64.ActiveCfg = Release|ARM64 + {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|ARM64.Build.0 = Release|ARM64 {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|x64.ActiveCfg = Release|x64 {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|x64.Build.0 = Release|x64 {61D4856F-FA82-4F02-BB88-909DDFB1FE74}.Release|x86.ActiveCfg = Release|Win32 @@ -1758,8 +1773,8 @@ Global {C39F4B46-6E89-4074-902E-CA57073044D2}.Release|x64.Build.0 = Release|x64 {C39F4B46-6E89-4074-902E-CA57073044D2}.Release|x86.ActiveCfg = Release|Win32 {C39F4B46-6E89-4074-902E-CA57073044D2}.Release|x86.Build.0 = Release|Win32 - {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Debug|ARM.ActiveCfg = Debug|Win32 - {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Debug|ARM64.ActiveCfg = Debug|x64 + {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Debug|ARM.ActiveCfg = Debug|ARM + {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Debug|ARM64.ActiveCfg = Debug|ARM64 {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Debug|x64.ActiveCfg = Debug|x64 {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Debug|x86.ActiveCfg = Debug|Win32 {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Mixed|ARM.ActiveCfg = Mixed|ARM @@ -1770,14 +1785,14 @@ Global {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Release Master Gold|x64.ActiveCfg = Release Master Gold|x64 {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 - {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Release|ARM.ActiveCfg = Release|Win32 - {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Release|ARM64.ActiveCfg = Release|x64 + {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Release|ARM.ActiveCfg = Release|ARM + {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Release|ARM64.ActiveCfg = Release|ARM64 {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Release|x64.ActiveCfg = Release|x64 {B5A3098C-C768-45FF-8B6C-1F707C0344F0}.Release|x86.ActiveCfg = Release|Win32 - {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|ARM.ActiveCfg = Debug|Win32 - {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|ARM.Build.0 = Debug|Win32 - {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|ARM64.ActiveCfg = Debug|x64 - {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|ARM64.Build.0 = Debug|x64 + {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|ARM.ActiveCfg = Debug|ARM + {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|ARM.Build.0 = Debug|ARM + {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|ARM64.Build.0 = Debug|ARM64 {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|x64.ActiveCfg = Debug|x64 {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|x64.Build.0 = Debug|x64 {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1798,18 +1813,18 @@ Global {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|ARM.ActiveCfg = Release|Win32 - {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|ARM.Build.0 = Release|Win32 - {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|ARM64.ActiveCfg = Release|x64 - {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|ARM64.Build.0 = Release|x64 + {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|ARM.ActiveCfg = Release|ARM + {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|ARM.Build.0 = Release|ARM + {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|ARM64.ActiveCfg = Release|ARM64 + {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|ARM64.Build.0 = Release|ARM64 {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|x64.ActiveCfg = Release|x64 {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|x64.Build.0 = Release|x64 {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|x86.ActiveCfg = Release|Win32 {7885CF3C-EE04-4C67-9467-1FBF9A36B037}.Release|x86.Build.0 = Release|Win32 - {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|ARM.ActiveCfg = Debug|Win32 - {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|ARM.Build.0 = Debug|Win32 - {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|ARM64.ActiveCfg = Debug|x64 - {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|ARM64.Build.0 = Debug|x64 + {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|ARM.ActiveCfg = Debug|ARM + {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|ARM.Build.0 = Debug|ARM + {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|ARM64.Build.0 = Debug|ARM64 {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|x64.ActiveCfg = Debug|x64 {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|x64.Build.0 = Debug|x64 {58AE014E-0DA3-4D9B-9034-21984C305447}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1830,18 +1845,18 @@ Global {58AE014E-0DA3-4D9B-9034-21984C305447}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {58AE014E-0DA3-4D9B-9034-21984C305447}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {58AE014E-0DA3-4D9B-9034-21984C305447}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|ARM.ActiveCfg = Release|Win32 - {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|ARM.Build.0 = Release|Win32 - {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|ARM64.ActiveCfg = Release|x64 - {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|ARM64.Build.0 = Release|x64 + {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|ARM.ActiveCfg = Release|ARM + {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|ARM.Build.0 = Release|ARM + {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|ARM64.ActiveCfg = Release|ARM64 + {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|ARM64.Build.0 = Release|ARM64 {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|x64.ActiveCfg = Release|x64 {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|x64.Build.0 = Release|x64 {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|x86.ActiveCfg = Release|Win32 {58AE014E-0DA3-4D9B-9034-21984C305447}.Release|x86.Build.0 = Release|Win32 - {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|ARM.ActiveCfg = Debug|Win32 - {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|ARM.Build.0 = Debug|Win32 - {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|ARM64.ActiveCfg = Debug|x64 - {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|ARM64.Build.0 = Debug|x64 + {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|ARM.ActiveCfg = Debug|ARM + {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|ARM.Build.0 = Debug|ARM + {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|ARM64.Build.0 = Debug|ARM64 {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|x64.ActiveCfg = Debug|x64 {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|x64.Build.0 = Debug|x64 {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1862,18 +1877,18 @@ Global {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|ARM.ActiveCfg = Release|Win32 - {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|ARM.Build.0 = Release|Win32 - {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|ARM64.ActiveCfg = Release|x64 - {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|ARM64.Build.0 = Release|x64 + {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|ARM.ActiveCfg = Release|ARM + {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|ARM.Build.0 = Release|ARM + {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|ARM64.ActiveCfg = Release|ARM64 + {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|ARM64.Build.0 = Release|ARM64 {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|x64.ActiveCfg = Release|x64 {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|x64.Build.0 = Release|x64 {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|x86.ActiveCfg = Release|Win32 {CDC5E78D-FF1C-4164-AE72-3578F60A27BA}.Release|x86.Build.0 = Release|Win32 - {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|ARM.ActiveCfg = Debug|Win32 - {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|ARM.Build.0 = Debug|Win32 - {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|ARM64.ActiveCfg = Debug|x64 - {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|ARM64.Build.0 = Debug|x64 + {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|ARM.ActiveCfg = Debug|ARM + {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|ARM.Build.0 = Debug|ARM + {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|ARM64.Build.0 = Debug|ARM64 {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|x64.ActiveCfg = Debug|x64 {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|x64.Build.0 = Debug|x64 {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1894,18 +1909,18 @@ Global {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|ARM.ActiveCfg = Release|Win32 - {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|ARM.Build.0 = Release|Win32 - {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|ARM64.ActiveCfg = Release|x64 - {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|ARM64.Build.0 = Release|x64 + {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|ARM.ActiveCfg = Release|ARM + {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|ARM.Build.0 = Release|ARM + {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|ARM64.ActiveCfg = Release|ARM64 + {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|ARM64.Build.0 = Release|ARM64 {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|x64.ActiveCfg = Release|x64 {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|x64.Build.0 = Release|x64 {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|x86.ActiveCfg = Release|Win32 {632AEEB6-DC06-4E15-9551-B2B09A4B73C5}.Release|x86.Build.0 = Release|Win32 - {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|ARM.ActiveCfg = Debug|Win32 - {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|ARM.Build.0 = Debug|Win32 - {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|ARM64.ActiveCfg = Debug|x64 - {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|ARM64.Build.0 = Debug|x64 + {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|ARM.ActiveCfg = Debug|ARM + {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|ARM.Build.0 = Debug|ARM + {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|ARM64.Build.0 = Debug|ARM64 {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|x64.ActiveCfg = Debug|x64 {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|x64.Build.0 = Debug|x64 {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1926,18 +1941,18 @@ Global {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|ARM.ActiveCfg = Release|Win32 - {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|ARM.Build.0 = Release|Win32 - {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|ARM64.ActiveCfg = Release|x64 - {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|ARM64.Build.0 = Release|x64 + {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|ARM.ActiveCfg = Release|ARM + {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|ARM.Build.0 = Release|ARM + {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|ARM64.ActiveCfg = Release|ARM64 + {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|ARM64.Build.0 = Release|ARM64 {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|x64.ActiveCfg = Release|x64 {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|x64.Build.0 = Release|x64 {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|x86.ActiveCfg = Release|Win32 {DAFD6D98-3DCD-40AD-BC85-EC71797B6767}.Release|x86.Build.0 = Release|Win32 - {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|ARM.ActiveCfg = Debug|Win32 - {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|ARM.Build.0 = Debug|Win32 - {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|ARM64.ActiveCfg = Debug|x64 - {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|ARM64.Build.0 = Debug|x64 + {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|ARM.ActiveCfg = Debug|ARM + {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|ARM.Build.0 = Debug|ARM + {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|ARM64.Build.0 = Debug|ARM64 {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|x64.ActiveCfg = Debug|x64 {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|x64.Build.0 = Debug|x64 {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1958,18 +1973,18 @@ Global {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|ARM.ActiveCfg = Release|Win32 - {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|ARM.Build.0 = Release|Win32 - {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|ARM64.ActiveCfg = Release|x64 - {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|ARM64.Build.0 = Release|x64 + {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|ARM.ActiveCfg = Release|ARM + {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|ARM.Build.0 = Release|ARM + {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|ARM64.ActiveCfg = Release|ARM64 + {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|ARM64.Build.0 = Release|ARM64 {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|x64.ActiveCfg = Release|x64 {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|x64.Build.0 = Release|x64 {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|x86.ActiveCfg = Release|Win32 {2C5AF8C8-96A6-45B2-860B-5E9C9911DDD6}.Release|x86.Build.0 = Release|Win32 - {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|ARM.ActiveCfg = Debug|Win32 - {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|ARM.Build.0 = Debug|Win32 - {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|ARM64.ActiveCfg = Debug|x64 - {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|ARM64.Build.0 = Debug|x64 + {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|ARM.ActiveCfg = Debug|ARM + {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|ARM.Build.0 = Debug|ARM + {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|ARM64.Build.0 = Debug|ARM64 {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|x64.ActiveCfg = Debug|x64 {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|x64.Build.0 = Debug|x64 {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Debug|x86.ActiveCfg = Debug|Win32 @@ -1990,10 +2005,10 @@ Global {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release Master Gold|x64.Build.0 = Release Master Gold|x64 {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release Master Gold|x86.ActiveCfg = Release Master Gold|Win32 {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release Master Gold|x86.Build.0 = Release Master Gold|Win32 - {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|ARM.ActiveCfg = Release|Win32 - {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|ARM.Build.0 = Release|Win32 - {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|ARM64.ActiveCfg = Release|x64 - {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|ARM64.Build.0 = Release|x64 + {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|ARM.ActiveCfg = Release|ARM + {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|ARM.Build.0 = Release|ARM + {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|ARM64.ActiveCfg = Release|ARM64 + {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|ARM64.Build.0 = Release|ARM64 {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|x64.ActiveCfg = Release|x64 {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|x64.Build.0 = Release|x64 {37B3642C-B706-4C93-BC54-BADADC8FC9B1}.Release|x86.ActiveCfg = Release|Win32 @@ -2046,6 +2061,262 @@ Global {C8FBC3CE-D6DE-4FC3-BC15-7B647614DB09}.Release|x64.Build.0 = Release|x64 {C8FBC3CE-D6DE-4FC3-BC15-7B647614DB09}.Release|x86.ActiveCfg = Release|Win32 {C8FBC3CE-D6DE-4FC3-BC15-7B647614DB09}.Release|x86.Build.0 = Release|Win32 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Debug|ARM.ActiveCfg = Debug|ARM + {3145D38A-574B-4841-8AA9-CCD160B95124}.Debug|ARM.Build.0 = Debug|ARM + {3145D38A-574B-4841-8AA9-CCD160B95124}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Debug|ARM64.Build.0 = Debug|ARM64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Debug|x64.ActiveCfg = Debug|x64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Debug|x64.Build.0 = Debug|x64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Debug|x86.ActiveCfg = Debug|Win32 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Debug|x86.Build.0 = Debug|Win32 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Mixed|ARM.ActiveCfg = Mixed|ARM + {3145D38A-574B-4841-8AA9-CCD160B95124}.Mixed|ARM.Build.0 = Mixed|ARM + {3145D38A-574B-4841-8AA9-CCD160B95124}.Mixed|ARM64.ActiveCfg = Mixed|ARM64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Mixed|ARM64.Build.0 = Mixed|ARM64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Mixed|x64.ActiveCfg = Mixed|x64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Mixed|x64.Build.0 = Mixed|x64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Mixed|x86.ActiveCfg = Mixed|Win32 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Mixed|x86.Build.0 = Mixed|Win32 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release Master Gold|ARM.ActiveCfg = Release Master Gold|ARM + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release Master Gold|ARM.Build.0 = Release Master Gold|ARM + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release Master Gold|ARM64.Build.0 = Release Master Gold|ARM64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release Master Gold|x64.ActiveCfg = Release|x64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release Master Gold|x64.Build.0 = Release|x64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release Master Gold|x86.ActiveCfg = Release|Win32 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release Master Gold|x86.Build.0 = Release|Win32 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release|ARM.ActiveCfg = Release|ARM + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release|ARM.Build.0 = Release|ARM + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release|ARM64.ActiveCfg = Release|ARM64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release|ARM64.Build.0 = Release|ARM64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release|x64.ActiveCfg = Release|x64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release|x64.Build.0 = Release|x64 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release|x86.ActiveCfg = Release|Win32 + {3145D38A-574B-4841-8AA9-CCD160B95124}.Release|x86.Build.0 = Release|Win32 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Debug|ARM.ActiveCfg = Debug|ARM + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Debug|ARM.Build.0 = Debug|ARM + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Debug|ARM64.Build.0 = Debug|ARM64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Debug|x64.ActiveCfg = Debug|x64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Debug|x64.Build.0 = Debug|x64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Debug|x86.ActiveCfg = Debug|Win32 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Debug|x86.Build.0 = Debug|Win32 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Mixed|ARM.ActiveCfg = Mixed|ARM + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Mixed|ARM.Build.0 = Mixed|ARM + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Mixed|ARM64.ActiveCfg = Mixed|ARM64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Mixed|ARM64.Build.0 = Mixed|ARM64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Mixed|x64.ActiveCfg = Mixed|x64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Mixed|x64.Build.0 = Mixed|x64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Mixed|x86.ActiveCfg = Mixed|Win32 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Mixed|x86.Build.0 = Mixed|Win32 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release Master Gold|ARM.ActiveCfg = Release Master Gold|ARM + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release Master Gold|ARM.Build.0 = Release Master Gold|ARM + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release Master Gold|ARM64.Build.0 = Release Master Gold|ARM64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release Master Gold|x64.ActiveCfg = Release|x64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release Master Gold|x64.Build.0 = Release|x64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release Master Gold|x86.ActiveCfg = Release|Win32 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release Master Gold|x86.Build.0 = Release|Win32 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release|ARM.ActiveCfg = Release|ARM + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release|ARM.Build.0 = Release|ARM + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release|ARM64.ActiveCfg = Release|ARM64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release|ARM64.Build.0 = Release|ARM64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release|x64.ActiveCfg = Release|x64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release|x64.Build.0 = Release|x64 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release|x86.ActiveCfg = Release|Win32 + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340}.Release|x86.Build.0 = Release|Win32 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Debug|ARM.ActiveCfg = Debug|ARM + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Debug|ARM.Build.0 = Debug|ARM + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Debug|ARM64.Build.0 = Debug|ARM64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Debug|x64.ActiveCfg = Debug|x64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Debug|x64.Build.0 = Debug|x64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Debug|x86.ActiveCfg = Debug|Win32 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Debug|x86.Build.0 = Debug|Win32 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Mixed|ARM.ActiveCfg = Mixed|ARM + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Mixed|ARM.Build.0 = Mixed|ARM + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Mixed|ARM64.ActiveCfg = Mixed|ARM64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Mixed|ARM64.Build.0 = Mixed|ARM64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Mixed|x64.ActiveCfg = Mixed|x64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Mixed|x64.Build.0 = Mixed|x64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Mixed|x86.ActiveCfg = Mixed|Win32 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Mixed|x86.Build.0 = Mixed|Win32 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release Master Gold|ARM.ActiveCfg = Release Master Gold|ARM + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release Master Gold|ARM.Build.0 = Release Master Gold|ARM + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release Master Gold|ARM64.Build.0 = Release Master Gold|ARM64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release Master Gold|x64.ActiveCfg = Release|x64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release Master Gold|x64.Build.0 = Release|x64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release Master Gold|x86.ActiveCfg = Release|Win32 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release Master Gold|x86.Build.0 = Release|Win32 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release|ARM.ActiveCfg = Release|ARM + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release|ARM.Build.0 = Release|ARM + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release|ARM64.ActiveCfg = Release|ARM64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release|ARM64.Build.0 = Release|ARM64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release|x64.ActiveCfg = Release|x64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release|x64.Build.0 = Release|x64 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release|x86.ActiveCfg = Release|Win32 + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B}.Release|x86.Build.0 = Release|Win32 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Debug|ARM.ActiveCfg = Debug|ARM + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Debug|ARM.Build.0 = Debug|ARM + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Debug|ARM64.Build.0 = Debug|ARM64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Debug|x64.ActiveCfg = Debug|x64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Debug|x64.Build.0 = Debug|x64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Debug|x86.ActiveCfg = Debug|Win32 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Debug|x86.Build.0 = Debug|Win32 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Mixed|ARM.ActiveCfg = Mixed|ARM + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Mixed|ARM.Build.0 = Mixed|ARM + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Mixed|ARM64.ActiveCfg = Mixed|ARM64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Mixed|ARM64.Build.0 = Mixed|ARM64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Mixed|x64.ActiveCfg = Mixed|x64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Mixed|x64.Build.0 = Mixed|x64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Mixed|x86.ActiveCfg = Mixed|Win32 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Mixed|x86.Build.0 = Mixed|Win32 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release Master Gold|ARM.ActiveCfg = Release Master Gold|ARM + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release Master Gold|ARM.Build.0 = Release Master Gold|ARM + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release Master Gold|ARM64.Build.0 = Release Master Gold|ARM64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release Master Gold|x64.ActiveCfg = Release|x64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release Master Gold|x64.Build.0 = Release|x64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release Master Gold|x86.ActiveCfg = Release|Win32 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release Master Gold|x86.Build.0 = Release|Win32 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release|ARM.ActiveCfg = Release|ARM + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release|ARM.Build.0 = Release|ARM + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release|ARM64.ActiveCfg = Release|ARM64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release|ARM64.Build.0 = Release|ARM64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release|x64.ActiveCfg = Release|x64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release|x64.Build.0 = Release|x64 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release|x86.ActiveCfg = Release|Win32 + {19DC7E82-12AF-4110-93CA-E7C30500A3F5}.Release|x86.Build.0 = Release|Win32 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Debug|ARM.ActiveCfg = Debug|ARM + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Debug|ARM.Build.0 = Debug|ARM + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Debug|ARM64.Build.0 = Debug|ARM64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Debug|x64.ActiveCfg = Debug|x64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Debug|x64.Build.0 = Debug|x64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Debug|x86.ActiveCfg = Debug|Win32 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Debug|x86.Build.0 = Debug|Win32 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Mixed|ARM.ActiveCfg = Mixed|ARM + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Mixed|ARM.Build.0 = Mixed|ARM + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Mixed|ARM64.ActiveCfg = Mixed|ARM64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Mixed|ARM64.Build.0 = Mixed|ARM64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Mixed|x64.ActiveCfg = Mixed|x64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Mixed|x64.Build.0 = Mixed|x64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Mixed|x86.ActiveCfg = Mixed|Win32 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Mixed|x86.Build.0 = Mixed|Win32 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release Master Gold|ARM.ActiveCfg = Release Master Gold|ARM + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release Master Gold|ARM.Build.0 = Release Master Gold|ARM + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release Master Gold|ARM64.Build.0 = Release Master Gold|ARM64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release Master Gold|x64.ActiveCfg = Release|x64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release Master Gold|x64.Build.0 = Release|x64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release Master Gold|x86.ActiveCfg = Release|Win32 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release Master Gold|x86.Build.0 = Release|Win32 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release|ARM.ActiveCfg = Release|ARM + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release|ARM.Build.0 = Release|ARM + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release|ARM64.ActiveCfg = Release|ARM64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release|ARM64.Build.0 = Release|ARM64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release|x64.ActiveCfg = Release|x64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release|x64.Build.0 = Release|x64 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release|x86.ActiveCfg = Release|Win32 + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A}.Release|x86.Build.0 = Release|Win32 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Debug|ARM.ActiveCfg = Debug|ARM + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Debug|ARM.Build.0 = Debug|ARM + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Debug|ARM64.Build.0 = Debug|ARM64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Debug|x64.ActiveCfg = Debug|x64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Debug|x64.Build.0 = Debug|x64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Debug|x86.ActiveCfg = Debug|Win32 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Debug|x86.Build.0 = Debug|Win32 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Mixed|ARM.ActiveCfg = Mixed|ARM + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Mixed|ARM.Build.0 = Mixed|ARM + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Mixed|ARM64.ActiveCfg = Mixed|ARM64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Mixed|ARM64.Build.0 = Mixed|ARM64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Mixed|x64.ActiveCfg = Mixed|x64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Mixed|x64.Build.0 = Mixed|x64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Mixed|x86.ActiveCfg = Mixed|Win32 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Mixed|x86.Build.0 = Mixed|Win32 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release Master Gold|ARM.ActiveCfg = Release Master Gold|ARM + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release Master Gold|ARM.Build.0 = Release Master Gold|ARM + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release Master Gold|ARM64.Build.0 = Release Master Gold|ARM64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release Master Gold|x64.ActiveCfg = Release|x64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release Master Gold|x64.Build.0 = Release|x64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release Master Gold|x86.ActiveCfg = Release|Win32 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release Master Gold|x86.Build.0 = Release|Win32 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release|ARM.ActiveCfg = Release|ARM + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release|ARM.Build.0 = Release|ARM + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release|ARM64.ActiveCfg = Release|ARM64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release|ARM64.Build.0 = Release|ARM64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release|x64.ActiveCfg = Release|x64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release|x64.Build.0 = Release|x64 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release|x86.ActiveCfg = Release|Win32 + {9187BE98-531A-4276-B78E-DBA3C8AB8447}.Release|x86.Build.0 = Release|Win32 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Debug|ARM.ActiveCfg = Debug|ARM + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Debug|ARM.Build.0 = Debug|ARM + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Debug|ARM64.Build.0 = Debug|ARM64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Debug|x64.ActiveCfg = Debug|x64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Debug|x64.Build.0 = Debug|x64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Debug|x86.ActiveCfg = Debug|Win32 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Debug|x86.Build.0 = Debug|Win32 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Mixed|ARM.ActiveCfg = Mixed|ARM + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Mixed|ARM.Build.0 = Mixed|ARM + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Mixed|ARM64.ActiveCfg = Mixed|ARM64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Mixed|ARM64.Build.0 = Mixed|ARM64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Mixed|x64.ActiveCfg = Mixed|x64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Mixed|x64.Build.0 = Mixed|x64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Mixed|x86.ActiveCfg = Mixed|Win32 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Mixed|x86.Build.0 = Mixed|Win32 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release Master Gold|ARM.ActiveCfg = Release Master Gold|ARM + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release Master Gold|ARM.Build.0 = Release Master Gold|ARM + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release Master Gold|ARM64.Build.0 = Release Master Gold|ARM64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release Master Gold|x64.ActiveCfg = Release|x64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release Master Gold|x64.Build.0 = Release|x64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release Master Gold|x86.ActiveCfg = Release|Win32 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release Master Gold|x86.Build.0 = Release|Win32 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release|ARM.ActiveCfg = Release|ARM + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release|ARM.Build.0 = Release|ARM + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release|ARM64.ActiveCfg = Release|ARM64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release|ARM64.Build.0 = Release|ARM64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release|x64.ActiveCfg = Release|x64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release|x64.Build.0 = Release|x64 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release|x86.ActiveCfg = Release|Win32 + {6D47AFC7-0557-4BBF-8902-B248F3621419}.Release|x86.Build.0 = Release|Win32 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Debug|ARM.ActiveCfg = Debug|ARM + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Debug|ARM.Build.0 = Debug|ARM + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Debug|ARM64.Build.0 = Debug|ARM64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Debug|x64.ActiveCfg = Debug|x64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Debug|x64.Build.0 = Debug|x64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Debug|x86.ActiveCfg = Debug|Win32 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Debug|x86.Build.0 = Debug|Win32 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Mixed|ARM.ActiveCfg = Mixed|ARM + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Mixed|ARM.Build.0 = Mixed|ARM + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Mixed|ARM64.ActiveCfg = Mixed|ARM64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Mixed|ARM64.Build.0 = Mixed|ARM64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Mixed|x64.ActiveCfg = Mixed|x64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Mixed|x64.Build.0 = Mixed|x64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Mixed|x86.ActiveCfg = Mixed|Win32 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Mixed|x86.Build.0 = Mixed|Win32 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release Master Gold|ARM.ActiveCfg = Release Master Gold|ARM + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release Master Gold|ARM.Build.0 = Release Master Gold|ARM + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release Master Gold|ARM64.ActiveCfg = Release Master Gold|ARM64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release Master Gold|ARM64.Build.0 = Release Master Gold|ARM64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release Master Gold|x64.ActiveCfg = Release|x64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release Master Gold|x64.Build.0 = Release|x64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release Master Gold|x86.ActiveCfg = Release|Win32 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release Master Gold|x86.Build.0 = Release|Win32 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release|ARM.ActiveCfg = Release|ARM + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release|ARM.Build.0 = Release|ARM + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release|ARM64.ActiveCfg = Release|ARM64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release|ARM64.Build.0 = Release|ARM64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release|x64.ActiveCfg = Release|x64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release|x64.Build.0 = Release|x64 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release|x86.ActiveCfg = Release|Win32 + {7E28883C-DB86-4EE8-813A-991BA20C68C9}.Release|x86.Build.0 = Release|Win32 {4E076FEB-DC78-4BF7-99C7-AC8267247989}.Debug|ARM.ActiveCfg = Debug|ARM {4E076FEB-DC78-4BF7-99C7-AC8267247989}.Debug|ARM.Build.0 = Debug|ARM {4E076FEB-DC78-4BF7-99C7-AC8267247989}.Debug|ARM64.ActiveCfg = Debug|ARM64 @@ -2126,14 +2397,19 @@ Global {DAFD6D98-3DCD-40AD-BC85-EC71797B6767} = {2BFC806B-CE92-4EA4-8FE8-5F2EA54BA348} {FABD5BBF-EA6F-4633-A34F-95CDC553CA36} = {CB0C814D-FB4E-453B-B7A0-716F4A1EACA4} {C8FBC3CE-D6DE-4FC3-BC15-7B647614DB09} = {2BFC806B-CE92-4EA4-8FE8-5F2EA54BA348} + {3145D38A-574B-4841-8AA9-CCD160B95124} = {CB0C814D-FB4E-453B-B7A0-716F4A1EACA4} + {DCC5B76D-BE13-4D1F-BE14-75D0FA678340} = {CB0C814D-FB4E-453B-B7A0-716F4A1EACA4} + {7E13BFCC-55B0-4715-8BBB-84A143CCE84B} = {CB0C814D-FB4E-453B-B7A0-716F4A1EACA4} + {19DC7E82-12AF-4110-93CA-E7C30500A3F5} = {CB0C814D-FB4E-453B-B7A0-716F4A1EACA4} + {3B20191B-7CA1-4D9C-8306-4D9EBB29E24A} = {CB0C814D-FB4E-453B-B7A0-716F4A1EACA4} + {9187BE98-531A-4276-B78E-DBA3C8AB8447} = {CB0C814D-FB4E-453B-B7A0-716F4A1EACA4} + {6D47AFC7-0557-4BBF-8902-B248F3621419} = {CB0C814D-FB4E-453B-B7A0-716F4A1EACA4} + {7E28883C-DB86-4EE8-813A-991BA20C68C9} = {CB0C814D-FB4E-453B-B7A0-716F4A1EACA4} {4E076FEB-DC78-4BF7-99C7-AC8267247989} = {49438080-78B8-4056-BDCB-4DACAD652C21} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {C5A32302-94F5-41B8-9606-017BB6BA69A6} EndGlobalSection - GlobalSection(CppDepend) = preSolution - Project = ".\engine.cdproj" - EndGlobalSection GlobalSection(DPCodeReviewSolutionGUID) = preSolution DPCodeReviewSolutionGUID = {00000000-0000-0000-0000-000000000000} EndGlobalSection diff --git a/src/utils/ETools/ETools.cpp b/src/utils/ETools/ETools.cpp index 3cc7cda7247..ed7399071c9 100644 --- a/src/utils/ETools/ETools.cpp +++ b/src/utils/ETools/ETools.cpp @@ -1,21 +1,212 @@ #include "stdafx.h" - #include "ETools.h" - +#include "xrXRC.h" +auto __vsnprintf = _vsnprintf; #pragma warning(disable : 4267) -BOOL APIENTRY DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved) +namespace ETOOLS { - switch (fdwReason) - { - case DLL_PROCESS_ATTACH: - //xrDebug::Initialize(); - //Core.Initialize("XRayEditorTools", 0, FALSE); - // FPU::m64r (); - break; - case DLL_THREAD_ATTACH: break; - case DLL_THREAD_DETACH: break; - case DLL_PROCESS_DETACH: break;//Core._destroy(); break; - } - return TRUE; + ETOOLS_API bool TestRayTriA(const Fvector &C, const Fvector &D, Fvector **p, float &u, float &v, float &range, bool bCull) + { + Fvector edge1, edge2, tvec, pvec, qvec; + float det, inv_det; + // find vectors for two edges sharing vert0 + edge1.sub(*p[1], *p[0]); + edge2.sub(*p[2], *p[0]); + // begin calculating determinant - also used to calculate U parameter + pvec.crossproduct(D, edge2); + // if determinant is near zero, ray lies in plane of triangle + det = edge1.dotproduct(pvec); + if (bCull) + { // define TEST_CULL if culling is desired + if (det < EPS) + return false; + tvec.sub(C, *p[0]); // calculate distance from vert0 to ray origin + u = tvec.dotproduct(pvec); // calculate U parameter and test bounds + if (u < 0.0 || u > det) + return false; + qvec.crossproduct(tvec, edge1); // prepare to test V parameter + v = D.dotproduct(qvec); // calculate V parameter and test bounds + if (v < 0.0 || u + v > det) + return false; + range = edge2.dotproduct(qvec); // calculate t, scale parameters, ray intersects triangle + inv_det = 1.0f / det; + range *= inv_det; + u *= inv_det; + v *= inv_det; + } + else + { // the non-culling branch + if (det > -EPS && det < EPS) + return false; + inv_det = 1.0f / det; + tvec.sub(C, *p[0]); // calculate distance from vert0 to ray origin + u = tvec.dotproduct(pvec) * inv_det; // calculate U parameter and test bounds + if (u < 0.0f || u > 1.0f) + return false; + qvec.crossproduct(tvec, edge1); // prepare to test V parameter + v = D.dotproduct(qvec) * inv_det; // calculate V parameter and test bounds + if (v < 0.0f || u + v > 1.0f) + return false; + range = edge2.dotproduct(qvec) * inv_det; // calculate t, ray intersects triangle + } + return true; + } + //-- Ray-Triangle : 1st level of indirection -------------------------------- + ETOOLS_API bool TestRayTriB(const Fvector &C, const Fvector &D, Fvector *p, float &u, float &v, float &range, bool bCull) + { + Fvector edge1, edge2, tvec, pvec, qvec; + float det, inv_det; + // find vectors for two edges sharing vert0 + edge1.sub(p[1], p[0]); + edge2.sub(p[2], p[0]); + // begin calculating determinant - also used to calculate U parameter + pvec.crossproduct(D, edge2); + // if determinant is near zero, ray lies in plane of triangle + det = edge1.dotproduct(pvec); + if (bCull) + { // define TEST_CULL if culling is desired + if (det < EPS) + return false; + tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin + u = tvec.dotproduct(pvec); // calculate U parameter and test bounds + if (u < 0.0f || u > det) + return false; + qvec.crossproduct(tvec, edge1); // prepare to test V parameter + v = D.dotproduct(qvec); // calculate V parameter and test bounds + if (v < 0.0f || u + v > det) + return false; + range = edge2.dotproduct(qvec); // calculate t, scale parameters, ray intersects triangle + inv_det = 1.0f / det; + range *= inv_det; + u *= inv_det; + v *= inv_det; + } + else + { // the non-culling branch + if (det > -EPS && det < EPS) + return false; + inv_det = 1.0f / det; + tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin + u = tvec.dotproduct(pvec) * inv_det; // calculate U parameter and test bounds + if (u < 0.0f || u > 1.0f) + return false; + qvec.crossproduct(tvec, edge1); // prepare to test V parameter + v = D.dotproduct(qvec) * inv_det; // calculate V parameter and test bounds + if (v < 0.0f || u + v > 1.0f) + return false; + range = edge2.dotproduct(qvec) * inv_det; // calculate t, ray intersects triangle + } + return true; + } + //-- Ray-Triangle(always return range) : 1st level of indirection -------------------------------- + ETOOLS_API bool TestRayTri2(const Fvector &C, const Fvector &D, Fvector *p, float &range) + { + Fvector edge1, edge2, tvec, pvec, qvec; + float det, inv_det, u, v; + + // find vectors for two edges sharing vert0 + edge1.sub(p[1], p[0]); + edge2.sub(p[2], p[0]); + // begin calculating determinant - also used to calculate U parameter + pvec.crossproduct(D, edge2); + // if determinant is near zero, ray lies in plane of triangle + det = edge1.dotproduct(pvec); + + if (_abs(det) < EPS_S) + { + range = -1; + return false; + } + inv_det = 1.0f / det; + tvec.sub(C, p[0]); // calculate distance from vert0 to ray origin + u = tvec.dotproduct(pvec) * inv_det; // calculate U parameter and test bounds + qvec.crossproduct(tvec, edge1); // prepare to test V parameter + range = edge2.dotproduct(qvec) * inv_det; // calculate t, ray intersects plane + if (u < 0.0f || u > 1.0f) + return false; + v = D.dotproduct(qvec) * inv_det; // calculate V parameter and test bounds + if (v < 0.0f || u + v > 1.0f) + return false; + return true; + } + + ETOOLS_API CDB::Collector *create_collector() + { + return xr_new(); + } + ETOOLS_API void destroy_collector(CDB::Collector *&M) + { + xr_delete(M); + } + ETOOLS_API void collector_add_face_d(CDB::Collector *CL, const Fvector &v0, const Fvector &v1, const Fvector &v2, u32 dummy) + { + CL->add_face_D(v0, v1, v2, dummy); + } + ETOOLS_API void collector_add_face_pd(CDB::Collector *CL, const Fvector &v0, const Fvector &v1, const Fvector &v2, u32 dummy, float eps) + { + CL->add_face_packed_D(v0, v1, v2, dummy, eps); + } + + ETOOLS_API CDB::CollectorPacked *create_collectorp(const Fbox &bb, int apx_vertices, int apx_faces) + { + return xr_new(bb, apx_vertices, apx_faces); + } + ETOOLS_API void destroy_collectorp(CDB::CollectorPacked *&M) + { + xr_delete(M); + } + ETOOLS_API void collectorp_add_face_d(CDB::CollectorPacked *CL, const Fvector &v0, const Fvector &v1, const Fvector &v2, u32 dummy) + { + CL->add_face_D(v0, v1, v2, dummy, u32(-1)); + } + + ETOOLS_API CDB::COLLIDER *get_collider() { return XRC.collider(); } + + ETOOLS_API CDB::MODEL *create_model_clp(CDB::CollectorPacked *CL) + { + return create_model(CL->getV(), CL->getVS(), CL->getT(), CL->getTS()); + } + + ETOOLS_API CDB::MODEL *create_model_cl(CDB::Collector *CL) + { + return create_model(CL->getV(), CL->getVS(), CL->getT(), CL->getTS()); + } + ETOOLS_API CDB::MODEL *create_model(Fvector *V, int Vcnt, CDB::TRI *T, int Tcnt) + { + CDB::MODEL *M = xr_new(); + M->build(V, Vcnt, T, Tcnt); + return M; + } + ETOOLS_API void destroy_model(CDB::MODEL *&M) + { + xr_delete(M); + } + ETOOLS_API CDB::RESULT *r_begin() { return XRC.r_begin(); }; + ETOOLS_API CDB::RESULT *r_end() { return XRC.r_end(); }; + ETOOLS_API int r_count() { return XRC.r_count(); }; + ETOOLS_API void ray_options(u32 flags) + { + XRC.ray_options(flags); + } + ETOOLS_API void ray_query(const CDB::MODEL *m_def, const Fvector &r_start, const Fvector &r_dir, float r_range) + { + XRC.ray_query(m_def, r_start, r_dir, r_range); + } + ETOOLS_API void ray_query_m(const Fmatrix &inv_parent, const CDB::MODEL *m_def, const Fvector &r_start, const Fvector &r_dir, float r_range) + { + XRC.ray_query(inv_parent, m_def, r_start, r_dir, r_range); + } + ETOOLS_API void box_options(u32 flags) + { + XRC.box_options(flags); + } + ETOOLS_API void box_query(const CDB::MODEL *m_def, const Fvector &b_center, const Fvector &b_dim) + { + XRC.box_query(m_def, b_center, b_dim); + } + ETOOLS_API void box_query_m(const Fmatrix &inv_parent, const CDB::MODEL *m_def, const Fbox &src) + { + XRC.box_query(inv_parent, m_def, src); + } } diff --git a/src/utils/ETools/ETools.h b/src/utils/ETools/ETools.h index 56cf017dc52..71f459fbc2b 100644 --- a/src/utils/ETools/ETools.h +++ b/src/utils/ETools/ETools.h @@ -5,3 +5,48 @@ #else #define ETOOLS_API __declspec(dllimport) #endif + +#include "../../xrCDB/xrCDB.h" + +class IKinematics; + +extern "C" +{ + // fast functions + namespace ETOOLS + { + ETOOLS_API bool TestRayTriA(const Fvector &C, const Fvector &D, Fvector **p, float &u, float &v, float &range, bool bCull); + ETOOLS_API bool TestRayTriB(const Fvector &C, const Fvector &D, Fvector *p, float &u, float &v, float &range, bool bCull); + ETOOLS_API bool TestRayTri2(const Fvector &C, const Fvector &D, Fvector *p, float &range); + + typedef void pb_callback(void *user_data, float &val); + ETOOLS_API void SimplifyCubeMap(u32 *src_data, u32 src_width, u32 src_height, u32 *dst_data, u32 dst_width, u32 dst_height, float sample_factor = 1.f, pb_callback cb = 0, void *pb_data = 0); + + ETOOLS_API CDB::Collector *create_collector(); + ETOOLS_API void destroy_collector(CDB::Collector *&); + ETOOLS_API void collector_add_face_d(CDB::Collector *CL, const Fvector &v0, const Fvector &v1, const Fvector &v2, u32 dummy); + ETOOLS_API void collector_add_face_pd(CDB::Collector *CL, const Fvector &v0, const Fvector &v1, const Fvector &v2, u32 dummy, float eps = EPS); + ETOOLS_API CDB::CollectorPacked *create_collectorp(const Fbox &bb, int apx_vertices = 5000, int apx_faces = 5000); + ETOOLS_API void destroy_collectorp(CDB::CollectorPacked *&); + ETOOLS_API void collectorp_add_face_d(CDB::CollectorPacked *CL, const Fvector &v0, const Fvector &v1, const Fvector &v2, u32 dummy); + + ETOOLS_API CDB::COLLIDER *get_collider(); + ETOOLS_API CDB::MODEL *create_model_cl(CDB::Collector *); + ETOOLS_API CDB::MODEL *create_model_clp(CDB::CollectorPacked *); + ETOOLS_API CDB::MODEL *create_model(Fvector *V, int Vcnt, CDB::TRI *T, int Tcnt); + ETOOLS_API void destroy_model(CDB::MODEL *&); + ETOOLS_API CDB::RESULT *r_begin(); + ETOOLS_API CDB::RESULT *r_end(); + ETOOLS_API int r_count(); + ETOOLS_API void ray_options(u32 flags); + ETOOLS_API void ray_query(const CDB::MODEL *m_def, const Fvector &r_start, const Fvector &r_dir, float r_range); + ETOOLS_API void ray_query_m(const Fmatrix &inv_parent, const CDB::MODEL *m_def, const Fvector &r_start, const Fvector &r_dir, float r_range); + ETOOLS_API void box_options(u32 flags); + ETOOLS_API void box_query(const CDB::MODEL *m_def, const Fvector &b_center, const Fvector &b_dim); + ETOOLS_API void box_query_m(const Fmatrix &inv_parent, const CDB::MODEL *m_def, const Fbox &src); + + ETOOLS_API int ogg_enc(const char *in_fn, const char *out_fn, float quality, void *comment, int comment_size); + + ETOOLS_API bool intersect(const Fmatrix &object_transform, const IKinematics &K, const Fvector &origin, const Fvector &direction, u16 &bone_id, float &dist, Fvector &norm); + }; +}; diff --git a/src/utils/ETools/ETools.vcxproj b/src/utils/ETools/ETools.vcxproj index a1713c1f3ad..8d128d402b8 100644 --- a/src/utils/ETools/ETools.vcxproj +++ b/src/utils/ETools/ETools.vcxproj @@ -35,13 +35,22 @@ + + + + + + + + Create + diff --git a/src/utils/ETools/ETools.vcxproj.filters b/src/utils/ETools/ETools.vcxproj.filters index eba73561b30..10fe1e17c77 100644 --- a/src/utils/ETools/ETools.vcxproj.filters +++ b/src/utils/ETools/ETools.vcxproj.filters @@ -24,6 +24,33 @@ VIPM + + Kernel + + + Kernel + + + Kernel + + + Kernel + + + Kernel + + + Kernel + + + Kernel + + + Kernel + + + Kernel + diff --git a/src/utils/ETools/ETools_cm.cpp b/src/utils/ETools/ETools_cm.cpp new file mode 100644 index 00000000000..fcad5bc4638 --- /dev/null +++ b/src/utils/ETools/ETools_cm.cpp @@ -0,0 +1,195 @@ +#include "stdafx.h" +#include "ETools.h" +#include "xrCore/_plane.h" + +class CCubeMapHelper +{ +public: + enum ECubeSide + { + CUBE_POSITIVE_X = 0, + CUBE_NEGATIVE_X = 1, + CUBE_POSITIVE_Y = 2, + CUBE_NEGATIVE_Y = 3, + CUBE_POSITIVE_Z = 4, + CUBE_NEGATIVE_Z = 5, + CUBE_SIDE_COUNT = 6, + CUBE_forced_u32 = u32(-1) + }; + +protected: + Fplane planes[CUBE_SIDE_COUNT]; + +public: + CCubeMapHelper() + { + planes[CUBE_POSITIVE_X].build(Fvector().set(+0.5f, 0, 0), Fvector().set(-1, 0, 0)); + planes[CUBE_NEGATIVE_X].build(Fvector().set(-0.5f, 0, 0), Fvector().set(+1, 0, 0)); + planes[CUBE_POSITIVE_Y].build(Fvector().set(0, +0.5f, 0), Fvector().set(0, -1, 0)); + planes[CUBE_NEGATIVE_Y].build(Fvector().set(0, -0.5f, 0), Fvector().set(0, +1, 0)); + planes[CUBE_POSITIVE_Z].build(Fvector().set(0, 0, +0.5f), Fvector().set(0, 0, -1)); + planes[CUBE_NEGATIVE_Z].build(Fvector().set(0, 0, -0.5f), Fvector().set(0, 0, +1)); + } + void vector_from_point(Fvector3 &normal, ECubeSide side, u32 x, u32 y, u32 width, u32 height) + { + float w, h; + w = (float)x / ((float)(width - 1)); + w *= 2.0f; + w -= 1.0f; + h = (float)y / ((float)(height - 1)); + h *= 2.0f; + h -= 1.0f; + switch (side) + { + case CUBE_POSITIVE_X: + normal.set(+1.0f, -h, -w); + break; + case CUBE_NEGATIVE_X: + normal.set(-1.0f, -h, +w); + break; + case CUBE_POSITIVE_Y: + normal.set(+w, +1.0f, +h); + break; + case CUBE_NEGATIVE_Y: + normal.set(+w, -1.0f, -h); + break; + case CUBE_POSITIVE_Z: + normal.set(+w, -h, +1.0f); + break; + case CUBE_NEGATIVE_Z: + normal.set(-w, -h, -1.0f); + break; + default: + break; + } + // Normalize and store + normal.normalize(); + } + u32 &pixel_from_side(u32 *pixels, u32 width, u32 height, u32 side, u32 x, u32 y) + { + u32 offset = width * side; + offset += (y * width * 6 + x); + VERIFY(offset < width * 6 * height); + return pixels[offset]; + } + void xys_from_vector(u32 &ux, u32 &uy, u32 &t_side, const Fvector &n, u32 *pixels, u32 width, u32 height) + { + float t_dist = flt_max; + t_side = CUBE_POSITIVE_X; + for (u32 side = CUBE_POSITIVE_X; side <= CUBE_NEGATIVE_Z; side++) + { + float cur_dist = flt_max; + if (planes[side].intersectRayDist(Fvector().set(0, 0, 0), n, cur_dist)) + { + if (cur_dist < t_dist) + { + t_dist = cur_dist; + t_side = side; + } + } + } + Fvector coord; + coord.mad(Fvector().set(0, 0, 0), n, t_dist); + + float x, y; + switch (t_side) + { + case CUBE_POSITIVE_X: + x = -coord.z; + y = -coord.y; + break; + case CUBE_NEGATIVE_X: + x = coord.z; + y = -coord.y; + break; + case CUBE_POSITIVE_Y: + x = coord.x; + y = coord.z; + break; + case CUBE_NEGATIVE_Y: + x = coord.x; + y = coord.z; + break; + case CUBE_POSITIVE_Z: + x = coord.x; + y = -coord.y; + break; + case CUBE_NEGATIVE_Z: + x = -coord.x; + y = -coord.y; + break; + } + clamp(x, -0.5f, 0.5f); + clamp(y, -0.5f, 0.5f); + ux = iFloor((x + 0.5f) * (width - 1) + 0.5f); + uy = iFloor((y + 0.5f) * (height - 1) + 0.5f); + } + u32 &pixel_from_vector(const Fvector &n, u32 *pixels, u32 width, u32 height) + { + u32 ux, uy, side; + xys_from_vector(ux, uy, side, n, pixels, width, height); + return pixel_from_side(pixels, width, height, side, ux, uy); + } + void scale_map(u32 *src_data, u32 src_width, u32 src_height, u32 *dst_data, u32 dst_width, u32 dst_height, float sample_factor, ETOOLS::pb_callback cb, void *pb_data) + { + VERIFY((src_width == src_height) && (dst_width == dst_height)); + Fvector3 normal; + Fvector3 dir; + float d_size = sample_factor * float(src_width) / dst_width; + float t_angle = sample_factor * PI_DIV_2 / float(dst_width); + VERIFY(t_angle < PI_DIV_2); + float d_angle = t_angle / d_size; + float h_angle = t_angle / 2; + float pb_weight = 1.f / (CUBE_SIDE_COUNT * dst_height * dst_width); + float pb_cur = 0.f; + for (u32 side = CUBE_POSITIVE_X; side < CUBE_SIDE_COUNT; side++) + { + for (u32 y_dst = 0; y_dst < dst_height; y_dst++) + { + for (u32 x_dst = 0; x_dst < dst_width; x_dst++) + { + pb_cur += pb_weight; + cb(pb_data, pb_cur); + vector_from_point(normal, ECubeSide(side), x_dst, y_dst, dst_width, dst_height); + u32 &out = pixel_from_side(dst_data, dst_width, dst_height, side, x_dst, y_dst); + Fcolor sum, sample_color; + sum.set(0, 0, 0, 0); + float src_h, src_p; + normal.getHP(src_h, src_p); + u32 ds = 0; + for (float p = src_p - h_angle; p < src_p + h_angle; p += d_angle) + { + for (float h = src_h - h_angle; h < src_h + h_angle; h += d_angle) + { + dir.setHP(h, p); + sample_color.set(pixel_from_vector(dir, src_data, src_width, src_height)); + sum.r += sample_color.r * sample_color.r; + sum.g += sample_color.g * sample_color.g; + sum.b += sample_color.b * sample_color.b; + sum.a += sample_color.a * sample_color.a; + ds++; + } + } + sum.mul_rgba(1.f / ds); + sum.r = _sqrt(sum.r); + sum.g = _sqrt(sum.g); + sum.b = _sqrt(sum.b); + sum.a = _sqrt(sum.a); + out = sum.get(); + } + } + } + } +}; + +CCubeMapHelper cm; +extern "C" +{ + namespace ETOOLS + { + ETOOLS_API void SimplifyCubeMap(u32 *src_data, u32 src_width, u32 src_height, u32 *dst_data, u32 dst_width, u32 dst_height, float sample_factor, pb_callback cb, void *pb_data) + { + cm.scale_map(src_data, src_width, src_height, dst_data, dst_width, dst_height, sample_factor, cb, pb_data); + } + } +} diff --git a/src/utils/ETools/Intersect.cpp b/src/utils/ETools/Intersect.cpp new file mode 100644 index 00000000000..e46ebd1781e --- /dev/null +++ b/src/utils/ETools/Intersect.cpp @@ -0,0 +1,311 @@ +#include "stdafx.h" +#include "etools.h" +#include "Include/xrRender/Kinematics.h" + +#define ECORE_API +#include "xrCore/Animation/Bone.hpp" + +namespace ETOOLS +{ + + enum box_axis + { + a_px, + a_nx, + a_py, + a_ny, + a_pz, + a_nz, + a_none + } ax; + + IC static bool clip(float fDenom, float fNumer, float &rfT0, float &rfT1, bool &code0, bool &code1) + { + // Return value is 'true' if line segment intersects the current test + // plane. Otherwise 'false' is returned in which case the line segment + // is entirely clipped. + code0 = code1 = false; + if (fDenom > 0.0f) + { + if (fNumer > fDenom * rfT1) + return false; + if (fNumer > fDenom * rfT0) + { + rfT0 = fNumer / fDenom; + code0 = true; + } + return true; + } + else if (fDenom < 0.0f) + { + if (fNumer > fDenom * rfT0) + return false; + if (fNumer > fDenom * rfT1) + { + rfT1 = fNumer / fDenom; + code1 = true; + } + return true; + } + else + { + return fNumer <= 0.0f; + } + } + IC static bool clip(float fDenom, float fNumer, float &rfT0, float &rfT1, box_axis &ax0, box_axis &ax1, box_axis ax) + { + bool b0 = false, b1 = false; + if (!clip(fDenom, fNumer, rfT0, rfT1, b0, b1)) + return false; + + if (b0) + ax0 = ax; + + if (b1) + ax1 = ax; + + return true; + } + static bool intersect(const Fvector &start, const Fvector &dir, const Fvector &extent, float &rfT0, float &rfT1, box_axis &ax0, box_axis &ax1) + { + // float fSaveT0 = rfT0, fSaveT1 = rfT1; + + bool bNotEntirelyClipped = + clip(+dir.x, -start.x - extent[0], rfT0, rfT1, ax0, ax1, a_nx) && + clip(-dir.x, +start.x - extent[0], rfT0, rfT1, ax0, ax1, a_px) && + clip(+dir.y, -start.y - extent[1], rfT0, rfT1, ax0, ax1, a_ny) && + clip(-dir.y, +start.y - extent[1], rfT0, rfT1, ax0, ax1, a_py) && + clip(+dir.z, -start.z - extent[2], rfT0, rfT1, ax0, ax1, a_nz) && + clip(-dir.z, +start.z - extent[2], rfT0, rfT1, ax0, ax1, a_pz); + + return bNotEntirelyClipped && (ax0 != a_none || ax1 != a_none); //( rfT0 != fSaveT0 || rfT1 != fSaveT1 ); + } + + bool intersect(const Fobb &box, const Fvector &origin, const Fvector &direction, float &dist, Fvector &norm) + { + + // convert ray to box coordinates + Fvector kDiff; + kDiff.sub(origin, box.m_translate); + Fvector kOrigin; + kOrigin.set(kDiff.dotproduct(box.m_rotate.i), kDiff.dotproduct(box.m_rotate.j), kDiff.dotproduct(box.m_rotate.k)); + Fvector kDirection; + kDirection.set(direction.dotproduct(box.m_rotate.i), direction.dotproduct(box.m_rotate.j), direction.dotproduct(box.m_rotate.k)); + + float fT0 = 0.0f, fT1 = type_max; + box_axis ax0 = a_none; + box_axis ax1 = a_none; + box_axis ax = a_none; + if (intersect(kOrigin, kDirection, box.m_halfsize, fT0, fT1, ax0, ax1)) + { + bool bPick = false; + + if (fT0 > 0.0f) + { + + if (fT0 < dist) + { + dist = fT0; + ax = ax0; + bPick = true; + } + + if (fT1 < dist) + { + dist = fT1; + ax = ax1; + bPick = true; + } + } + else + { + + if (fT1 < dist) + { + dist = fT1; + ax = ax1; + bPick = true; + } + } + + if (bPick) + { + switch (ax) + { + case a_px: + norm.set(box.m_rotate.i); + break; + case a_nx: + norm.invert(box.m_rotate.i); + break; + case a_py: + norm.set(box.m_rotate.j); + break; + case a_ny: + norm.invert(box.m_rotate.j); + break; + case a_pz: + norm.set(box.m_rotate.k); + break; + case a_nz: + norm.invert(box.m_rotate.k); + break; + case a_none: + NODEFAULT; + } + } + + return bPick; + } + + return false; + } + + bool intersect(const Fsphere &sphere, const Fvector &origin, const Fvector &direction, float &dist, Fvector &norm) + { + bool b_result = !!sphere.intersect2(origin, direction, dist); + if (b_result) + { + const Fvector pt = Fvector().mad(origin, direction, dist); + norm.sub(pt, sphere.P).normalize_safe(); + } + + return b_result; + } + bool intersect(const Fcylinder &cylinder, const Fvector &origin, const Fvector &direction, float &dist, Fvector &norm) + { + + float afT[2]; + Fcylinder::ecode code[2] = {Fcylinder::cyl_none, Fcylinder::cyl_none}; + Fcylinder::ecode r_code = Fcylinder::cyl_none; + bool b_result = false; + int cnt; + if (0 != (cnt = cylinder.intersect(origin, direction, afT, code))) + { + // bool o_inside = false; + + for (int k = 0; k < cnt; k++) + { + if (afT[k] < 0.f) + continue; + + if (afT[k] < dist) + { + dist = afT[k]; + r_code = code[k]; + b_result = true; + } + } + } + else + { + return false; + } + + if (b_result) + { + const Fvector pt = Fvector().mad(origin, direction, dist); + const Fvector c_pt = Fvector().sub(pt, cylinder.m_center); + VERIFY(r_code != Fcylinder::cyl_none); + + if (r_code == Fcylinder::cyl_cap) + { + if (c_pt.dotproduct(cylinder.m_direction) > 0.f) + norm.set(cylinder.m_direction); + else + norm.invert(cylinder.m_direction); + } + if (r_code == Fcylinder::cyl_wall) + { + const Fvector r_dir = Fvector().mad(pt, cylinder.m_direction, -pt.dotproduct(cylinder.m_direction)); + norm = Fvector().normalize_safe(r_dir); + } + } + + return b_result; + } + + bool bone_intersect(u16 bone, const IKinematics &K, const Fvector &origin, const Fvector &direction, float &dist, Fvector &norm) + { + const IBoneData &d = K.GetBoneData(bone); + const Fmatrix &bone_transform = K.LL_GetTransform(bone); + const Fmatrix bone_invert_transform = Fmatrix().invert(bone_transform); + + Fvector l_origin; + bone_invert_transform.transform_tiny(l_origin, origin); + Fvector l_direction; + bone_invert_transform.transform_dir(l_direction, direction); + const SBoneShape &bone_shape = d.get_shape(); + + bool result = false; + switch (bone_shape.type) + { + case SBoneShape::stNone: + return false; + case SBoneShape::stBox: + result = intersect(bone_shape.box, l_origin, l_direction, dist, norm); + break; + case SBoneShape::stSphere: + result = intersect(bone_shape.sphere, l_origin, l_direction, dist, norm); + break; + case SBoneShape::stCylinder: + result = intersect(bone_shape.cylinder, l_origin, l_direction, dist, norm); + break; + default: + NODEFAULT; + return false; + }; + + if (result) + bone_transform.transform_dir(norm); + + return result; + } + + bool intersect(const IKinematics &K, const Fvector &origin, const Fvector &direction, u16 &bone_id, float &dist, Fvector &norm) + { + + bool b_res = false; + const u16 bc = K.LL_BoneCount(); + for (u16 i = 0; i < bc; ++i) + { + + float l_dist = FLT_MAX; + Fvector l_norm; + + if (!bone_intersect(i, K, origin, direction, l_dist, l_norm)) + continue; + + if (!b_res || l_dist < dist) + { + dist = l_dist; + norm = l_norm; + bone_id = i; + } + b_res = true; + } + return b_res; + } + + bool intersect(const Fmatrix &object_transform, const IKinematics &K, const Fvector &origin, const Fvector &direction, u16 &bone_id, float &dist, Fvector &norm) + { + + const Fmatrix inverce_object_transform = Fmatrix().invert(object_transform); + + Fvector l_origin; + inverce_object_transform.transform_tiny(l_origin, origin); + Fvector l_direction; + inverce_object_transform.transform_dir(l_direction, direction); + + bool res = intersect(K, l_origin, l_direction, bone_id, dist, norm); + + if (res) + { + + object_transform.transform_dir(norm); + } + + return res; + } + +} diff --git a/src/utils/ETools/audio.cpp b/src/utils/ETools/audio.cpp new file mode 100644 index 00000000000..18397d9696d --- /dev/null +++ b/src/utils/ETools/audio.cpp @@ -0,0 +1,825 @@ +/* OggEnc + ** + ** This program is distributed under the GNU General Public License, version 2. + ** A copy of this license is included with this source. + ** + ** Copyright 2000-2002, Michael Smith + ** + ** AIFF/AIFC support from OggSquish, (c) 1994-1996 Monty + **/ +#include "stdafx.h" + +#include +#include +#include + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "audio.h" +#include "platform.h" +//#include "i18n.h" +#include "resample.h" + +#define _(a) a +#define N_(a) a + +#ifdef HAVE_LIBFLAC +#include "flac.h" +#endif + +#pragma warning(disable : 4995) +#pragma warning(disable : 4267) +#pragma warning(disable : 4244) + +#define WAV_HEADER_SIZE 44 + +/* Macros to read header data */ +#define READ_U32_LE(buf) \ + (((buf)[3] << 24) | ((buf)[2] << 16) | ((buf)[1] << 8) | ((buf)[0] & 0xff)) + +#define READ_U16_LE(buf) \ + (((buf)[1] << 8) | ((buf)[0] & 0xff)) + +#define READ_U32_BE(buf) \ + (((buf)[0] << 24) | ((buf)[1] << 16) | ((buf)[2] << 8) | ((buf)[3] & 0xff)) + +#define READ_U16_BE(buf) \ + (((buf)[0] << 8) | ((buf)[1] & 0xff)) + +/* Define the supported formats here */ +input_format formats[] = { + {wav_id, 12, wav_open, wav_close, "wav", N_("WAV file reader")}, + {aiff_id, 12, aiff_open, wav_close, "aiff", N_("AIFF/AIFC file reader")}, +#ifdef HAVE_LIBFLAC + {flac_id, 4, flac_open, flac_close, "flac", N_("FLAC file reader")}, + {oggflac_id, 32, flac_open, flac_close, "ogg", N_("Ogg FLAC file reader")}, +#endif + {NULL, 0, NULL, NULL, NULL, NULL}}; + +input_format *open_audio_file(FILE *in, oe_enc_opt *opt) +{ + int j = 0; + unsigned char *buf = NULL; + int buf_size = 0, buf_filled = 0; + int size, ret; + + while (formats[j].id_func) + { + size = formats[j].id_data_len; + if (size >= buf_size) + { + buf = (unsigned char *)realloc(buf, size); + buf_size = size; + } + + if (size > buf_filled) + { + ret = fread(buf + buf_filled, 1, buf_size - buf_filled, in); + buf_filled += ret; + + if (buf_filled < size) + { /* File truncated */ + j++; + continue; + } + } + + if (formats[j].id_func(buf, buf_filled)) + { + /* ok, we now have something that can handle the file */ + if (formats[j].open_func(in, opt, buf, buf_filled)) + { + free(buf); + return &formats[j]; + } + } + j++; + } + + free(buf); + + return NULL; +} + +static int seek_forward(FILE *in, int length) +{ + if (fseek(in, length, SEEK_CUR)) + { + /* Failed. Do it the hard way. */ + unsigned char buf[1024]; + int seek_needed = length, seeked; + while (seek_needed > 0) + { + seeked = fread(buf, 1, seek_needed > 1024 ? 1024 : seek_needed, in); + if (!seeked) + return 0; /* Couldn't read more, can't read file */ + else + seek_needed -= seeked; + } + } + return 1; +} + +static int find_wav_chunk(FILE *in, char *type, unsigned int *len) +{ + unsigned char buf[8]; + + while (1) + { + if (fread(buf, 1, 8, in) < 8) /* Suck down a chunk specifier */ + { + fprintf(stderr, _("Warning: Unexpected EOF in reading WAV header\n")); + return 0; /* EOF before reaching the appropriate chunk */ + } + + if (memcmp(buf, type, 4)) + { + *len = READ_U32_LE(buf + 4); + if (!seek_forward(in, *len)) + return 0; + + buf[4] = 0; + fprintf(stderr, _("Skipping chunk of type \"%s\", length %d\n"), buf, *len); + } + else + { + *len = READ_U32_LE(buf + 4); + return 1; + } + } +} + +static int find_aiff_chunk(FILE *in, char *type, unsigned int *len) +{ + unsigned char buf[8]; + + while (1) + { + if (fread(buf, 1, 8, in) < 8) + { + fprintf(stderr, _("Warning: Unexpected EOF in AIFF chunk\n")); + return 0; + } + + *len = READ_U32_BE(buf + 4); + + if (memcmp(buf, type, 4)) + { + if ((*len) & 0x1) + (*len)++; + + if (!seek_forward(in, *len)) + return 0; + } + else + return 1; + } +} + +double read_IEEE80(unsigned char *buf) +{ + int s = buf[0] & 0xff; + int e = ((buf[0] & 0x7f) << 8) | (buf[1] & 0xff); + double f = ((unsigned long)(buf[2] & 0xff) << 24) | + ((buf[3] & 0xff) << 16) | + ((buf[4] & 0xff) << 8) | + (buf[5] & 0xff); + + if (e == 32767) + { + if (buf[2] & 0x80) + return HUGE_VAL; /* Really NaN, but this won't happen in reality */ + else + { + if (s) + return -HUGE_VAL; + else + return HUGE_VAL; + } + } + + f = ldexp(f, 32); + f += ((buf[6] & 0xff) << 24) | + ((buf[7] & 0xff) << 16) | + ((buf[8] & 0xff) << 8) | + (buf[9] & 0xff); + + return ldexp(f, e - 16446); +} + +/* AIFF/AIFC support adapted from the old OggSQUISH application */ +int aiff_id(unsigned char *buf, int len) +{ + if (len < 12) + return 0; /* Truncated file, probably */ + + if (memcmp(buf, "FORM", 4)) + return 0; + + if (memcmp(buf + 8, "AIF", 3)) + return 0; + + if (buf[11] != 'C' && buf[11] != 'F') + return 0; + + return 1; +} + +int aiff_open(FILE *in, oe_enc_opt *opt, unsigned char *buf, int buflen) +{ + int aifc; /* AIFC or AIFF? */ + unsigned int len; + unsigned char *buffer; + unsigned char buf2[8]; + aiff_fmt format; + aifffile *aiff = (aifffile *)malloc(sizeof(aifffile)); + + if (buf[11] == 'C') + aifc = 1; + else + aifc = 0; + + if (!find_aiff_chunk(in, "COMM", &len)) + { + fprintf(stderr, _("Warning: No common chunk found in AIFF file\n")); + return 0; /* EOF before COMM chunk */ + } + + if (len < 18) + { + fprintf(stderr, _("Warning: Truncated common chunk in AIFF header\n")); + return 0; /* Weird common chunk */ + } + + buffer = (unsigned char *)alloca(len); + + if (fread(buffer, 1, len, in) < len) + { + fprintf(stderr, _("Warning: Unexpected EOF in reading AIFF header\n")); + return 0; + } + + format.channels = READ_U16_BE(buffer); + format.totalframes = READ_U32_BE(buffer + 2); + format.samplesize = READ_U16_BE(buffer + 6); + format.rate = (int)read_IEEE80(buffer + 8); + + aiff->bigendian = 1; + + if (aifc) + { + if (len < 22) + { + fprintf(stderr, _("Warning: AIFF-C header truncated.\n")); + return 0; + } + + if (!memcmp(buffer + 18, "NONE", 4)) + { + aiff->bigendian = 1; + } + else if (!memcmp(buffer + 18, "sowt", 4)) + { + aiff->bigendian = 0; + } + else + { + fprintf(stderr, _("Warning: Can't handle compressed AIFF-C (%c%c%c%c)\n"), *(buffer + 18), *(buffer + 19), *(buffer + 20), *(buffer + 21)); + return 0; /* Compressed. Can't handle */ + } + } + + if (!find_aiff_chunk(in, "SSND", &len)) + { + fprintf(stderr, _("Warning: No SSND chunk found in AIFF file\n")); + return 0; /* No SSND chunk -> no actual audio */ + } + + if (len < 8) + { + fprintf(stderr, _("Warning: Corrupted SSND chunk in AIFF header\n")); + return 0; + } + + if (fread(buf2, 1, 8, in) < 8) + { + fprintf(stderr, _("Warning: Unexpected EOF reading AIFF header\n")); + return 0; + } + + format.offset = READ_U32_BE(buf2); + format.blocksize = READ_U32_BE(buf2 + 4); + + if (format.blocksize == 0 && + (format.samplesize == 16 || format.samplesize == 8)) + { + /* From here on, this is very similar to the wav code. Oh well. */ + + opt->rate = format.rate; + opt->channels = format.channels; + opt->read_samples = wav_read; /* Similar enough, so we use the same */ + opt->total_samples_per_channel = format.totalframes; + + aiff->f = in; + aiff->samplesread = 0; + aiff->channels = format.channels; + aiff->samplesize = format.samplesize; + aiff->totalsamples = format.totalframes; + + opt->readdata = (void *)aiff; + + seek_forward(in, format.offset); /* Swallow some data */ + return 1; + } + else + { + fprintf(stderr, + _("Warning: OggEnc does not support this type of AIFF/AIFC file\n" + " Must be 8 or 16 bit PCM.\n")); + return 0; + } +} + +int wav_id(unsigned char *buf, int len) +{ + unsigned int flen; + + if (len < 12) + return 0; /* Something screwed up */ + + if (memcmp(buf, "RIFF", 4)) + return 0; /* Not wave */ + + flen = READ_U32_LE(buf + 4); /* We don't use this */ + + if (memcmp(buf + 8, "WAVE", 4)) + return 0; /* RIFF, but not wave */ + + return 1; +} + +int wav_open(FILE *in, oe_enc_opt *opt, unsigned char *oldbuf, int buflen) +{ + unsigned char buf[16]; + unsigned int len; + int samplesize; + wav_fmt format; + wavfile *wav = (wavfile *)malloc(sizeof(wavfile)); + + /* Ok. At this point, we know we have a WAV file. Now we have to detect + * whether we support the subtype, and we have to find the actual data + * We don't (for the wav reader) need to use the buffer we used to id this + * as a wav file (oldbuf) + */ + + if (!find_wav_chunk(in, "fmt ", &len)) + return 0; /* EOF */ + + if (len < 16) + { + fprintf(stderr, _("Warning: Unrecognised format chunk in WAV header\n")); + return 0; /* Weird format chunk */ + } + + /* A common error is to have a format chunk that is not 16 or 18 bytes + * in size. This is incorrect, but not fatal, so we only warn about + * it instead of refusing to work with the file. Please, if you + * have a program that's creating format chunks of sizes other than + * 16 or 18 bytes in size, report a bug to the author. + */ + if (len != 16 && len != 18) + fprintf(stderr, + _("Warning: INVALID format chunk in wav header.\n" + " Trying to read anyway (may not work)...\n")); + + if (fread(buf, 1, 16, in) < 16) + { + fprintf(stderr, _("Warning: Unexpected EOF in reading WAV header\n")); + return 0; + } + + /* Deal with stupid broken apps. Don't use these programs. + */ + if (len - 16 > 0 && !seek_forward(in, len - 16)) + return 0; + + format.format = READ_U16_LE(buf); + format.channels = READ_U16_LE(buf + 2); + format.samplerate = READ_U32_LE(buf + 4); + format.bytespersec = READ_U32_LE(buf + 8); + format.align = READ_U16_LE(buf + 12); + format.samplesize = READ_U16_LE(buf + 14); + + if (!find_wav_chunk(in, "data", &len)) + return 0; /* EOF */ + + if (format.format == 1) + { + samplesize = format.samplesize / 8; + opt->read_samples = wav_read; + } + else if (format.format == 3) + { + samplesize = 4; + opt->read_samples = wav_ieee_read; + } + else + { + fprintf(stderr, + _("ERROR: Wav file is unsupported type (must be standard PCM\n" + " or type 3 floating point PCM\n")); + return 0; + } + + if (format.align == format.channels * samplesize && + format.samplesize == samplesize * 8 && + (format.samplesize == 24 || format.samplesize == 16 || + format.samplesize == 8 || + (format.samplesize == 32 && format.format == 3))) + { + /* OK, good - we have the one supported format, + now we want to find the size of the file */ + opt->rate = format.samplerate; + opt->channels = format.channels; + + wav->f = in; + wav->samplesread = 0; + wav->bigendian = 0; + wav->channels = format.channels; /* This is in several places. The price + of trying to abstract stuff. */ + wav->samplesize = format.samplesize; + + if (len) + { + opt->total_samples_per_channel = len / (format.channels * samplesize); + } + else + { + long pos; + pos = ftell(in); + if (fseek(in, 0, SEEK_END) == -1) + { + opt->total_samples_per_channel = 0; /* Give up */ + } + else + { + opt->total_samples_per_channel = (ftell(in) - pos) / + (format.channels * samplesize); + fseek(in, pos, SEEK_SET); + } + } + wav->totalsamples = opt->total_samples_per_channel; + + opt->readdata = (void *)wav; + return 1; + } + else + { + fprintf(stderr, + _("ERROR: Wav file is unsupported subformat (must be 8,16, or 24 bit PCM\n" + "or floating point PCM\n")); + return 0; + } +} + +long wav_read(void *in, float **buffer, int samples) +{ + wavfile *f = (wavfile *)in; + int sampbyte = f->samplesize / 8; + signed char *buf = (signed char *)alloca(samples * sampbyte * f->channels); + long bytes_read = fread(buf, 1, samples * sampbyte * f->channels, f->f); + int i, j; + long realsamples; + + if (f->totalsamples && f->samplesread + + bytes_read / (sampbyte * f->channels) > + f->totalsamples) + { + bytes_read = sampbyte * f->channels * (f->totalsamples - f->samplesread); + } + + realsamples = bytes_read / (sampbyte * f->channels); + f->samplesread += realsamples; + + if (f->samplesize == 8) + { + unsigned char *bufu = (unsigned char *)buf; + for (i = 0; i < realsamples; i++) + { + for (j = 0; j < f->channels; j++) + { + buffer[j][i] = ((int)(bufu[i * f->channels + j]) - 128) / 128.0f; + } + } + } + else if (f->samplesize == 16) + { + if (!f->bigendian) + { + for (i = 0; i < realsamples; i++) + { + for (j = 0; j < f->channels; j++) + { + buffer[j][i] = ((buf[i * 2 * f->channels + 2 * j + 1] << 8) | + (buf[i * 2 * f->channels + 2 * j] & 0xff)) / + 32768.0f; + } + } + } + else + { + for (i = 0; i < realsamples; i++) + { + for (j = 0; j < f->channels; j++) + { + buffer[j][i] = ((buf[i * 2 * f->channels + 2 * j] << 8) | + (buf[i * 2 * f->channels + 2 * j + 1] & 0xff)) / + 32768.0f; + } + } + } + } + else if (f->samplesize == 24) + { + if (!f->bigendian) + { + for (i = 0; i < realsamples; i++) + { + for (j = 0; j < f->channels; j++) + { + buffer[j][i] = ((buf[i * 3 * f->channels + 3 * j + 2] << 16) | + (((unsigned char *)buf)[i * 3 * f->channels + 3 * j + 1] << 8) | + (((unsigned char *)buf)[i * 3 * f->channels + 3 * j] & 0xff)) / + 8388608.0f; + } + } + } + else + { + fprintf(stderr, _("Big endian 24 bit PCM data is not currently " + "supported, aborting.\n")); + return 0; + } + } + else + { + fprintf(stderr, _("Internal error: attempt to read unsupported " + "bitdepth %d\n"), + f->samplesize); + return 0; + } + + return realsamples; +} + +long wav_ieee_read(void *in, float **buffer, int samples) +{ + wavfile *f = (wavfile *)in; + float *buf = (float *)alloca(samples * 4 * f->channels); /* de-interleave buffer */ + long bytes_read = fread(buf, 1, samples * 4 * f->channels, f->f); + int i, j; + long realsamples; + + if (f->totalsamples && f->samplesread + + bytes_read / (4 * f->channels) > + f->totalsamples) + bytes_read = 4 * f->channels * (f->totalsamples - f->samplesread); + realsamples = bytes_read / (4 * f->channels); + f->samplesread += realsamples; + + for (i = 0; i < realsamples; i++) + for (j = 0; j < f->channels; j++) + buffer[j][i] = buf[i * f->channels + j]; + + return realsamples; +} + +void wav_close(void *info) +{ + wavfile *f = (wavfile *)info; + + free(f); +} + +int raw_open(FILE *in, oe_enc_opt *opt) +{ + wav_fmt format; /* fake wave header ;) */ + wavfile *wav = (wavfile *)malloc(sizeof(wavfile)); + + /* construct fake wav header ;) */ + format.format = 2; + format.channels = opt->channels; + format.samplerate = opt->rate; + format.samplesize = opt->samplesize; + format.bytespersec = opt->channels * opt->rate * opt->samplesize / 8; + format.align = format.bytespersec; + wav->f = in; + wav->samplesread = 0; + wav->bigendian = opt->endianness; + wav->channels = format.channels; + wav->samplesize = opt->samplesize; + wav->totalsamples = 0; + + opt->read_samples = wav_read; + opt->readdata = (void *)wav; + opt->total_samples_per_channel = 0; /* raw mode, don't bother */ + return 1; +} + +typedef struct +{ + res_state resampler; + audio_read_func real_reader; + void *real_readdata; + float **bufs; + int channels; + int bufsize; + int done; +} resampler; + +static long read_resampled(void *d, float **buffer, int samples) +{ + resampler *rs = (resampler *)d; + long in_samples; + int out_samples; + + in_samples = res_push_max_input(&rs->resampler, samples); + if (in_samples > rs->bufsize) + in_samples = rs->bufsize; + + in_samples = rs->real_reader(rs->real_readdata, rs->bufs, in_samples); + + if (in_samples <= 0) + { + if (!rs->done) + { + rs->done = 1; + out_samples = res_drain(&rs->resampler, buffer); + return out_samples; + } + return 0; + } + + out_samples = res_push(&rs->resampler, buffer, (float const **)rs->bufs, in_samples); + + if (out_samples <= 0) + { + fprintf(stderr, _("BUG: Got zero samples from resampler: your file will be truncated. Please report this.\n")); + } + + return out_samples; +} + +int setup_resample(oe_enc_opt *opt) +{ + resampler *rs = (resampler *)calloc(1, sizeof(resampler)); + int c; + + rs->bufsize = 4096; /* Shrug */ + rs->real_reader = opt->read_samples; + rs->real_readdata = opt->readdata; + rs->bufs = (float **)malloc(sizeof(float *) * opt->channels); + rs->channels = opt->channels; + rs->done = 0; + if (res_init(&rs->resampler, rs->channels, opt->resamplefreq, opt->rate, RES_END)) + { + fprintf(stderr, _("Couldn't initialise resampler\n")); + return -1; + } + + for (c = 0; c < opt->channels; c++) + rs->bufs[c] = (float *)malloc(sizeof(float) * rs->bufsize); + + opt->read_samples = read_resampled; + opt->readdata = rs; + if (opt->total_samples_per_channel) + opt->total_samples_per_channel = (int)((float)opt->total_samples_per_channel * + ((float)opt->resamplefreq / (float)opt->rate)); + opt->rate = opt->resamplefreq; + + return 0; +} + +void clear_resample(oe_enc_opt *opt) +{ + resampler *rs = (resampler *)opt->readdata; + int i; + + opt->read_samples = rs->real_reader; + opt->readdata = rs->real_readdata; + res_clear(&rs->resampler); + + for (i = 0; i < rs->channels; i++) + free(rs->bufs[i]); + + free(rs->bufs); + + free(rs); +} + +typedef struct +{ + audio_read_func real_reader; + void *real_readdata; + int channels; + float scale_factor; +} scaler; + +static long read_scaler(void *data, float **buffer, int samples) +{ + scaler *d = (scaler *)data; + long in_samples = d->real_reader(d->real_readdata, buffer, samples); + int i, j; + + for (i = 0; i < d->channels; i++) + { + for (j = 0; j < in_samples; j++) + { + buffer[i][j] *= d->scale_factor; + } + } + + return in_samples; +} + +void setup_scaler(oe_enc_opt *opt, float scale) +{ + scaler *d = (scaler *)calloc(1, sizeof(scaler)); + + d->real_reader = opt->read_samples; + d->real_readdata = opt->readdata; + + opt->read_samples = read_scaler; + opt->readdata = d; + d->channels = opt->channels; + d->scale_factor = scale; +} + +void clear_scaler(oe_enc_opt *opt) +{ + scaler *d = (scaler *)opt->readdata; + + opt->read_samples = d->real_reader; + opt->readdata = d->real_readdata; + + free(d); +} + +typedef struct +{ + audio_read_func real_reader; + void *real_readdata; + float **bufs; +} downmix; + +static long read_downmix(void *data, float **buffer, int samples) +{ + downmix *d = (downmix *)data; + long in_samples = d->real_reader(d->real_readdata, d->bufs, samples); + int i; + + for (i = 0; i < in_samples; i++) + { + buffer[0][i] = (d->bufs[0][i] + d->bufs[1][i]) * 0.5f; + } + + return in_samples; +} + +void setup_downmix(oe_enc_opt *opt) +{ + downmix *d = (downmix *)calloc(1, sizeof(downmix)); + + if (opt->channels != 2) + { + fprintf(stderr, "Internal error! Please report this bug.\n"); + return; + } + + d->bufs = (float **)malloc(2 * sizeof(float *)); + d->bufs[0] = (float *)malloc(4096 * sizeof(float)); + d->bufs[1] = (float *)malloc(4096 * sizeof(float)); + d->real_reader = opt->read_samples; + + d->real_readdata = opt->readdata; + + opt->read_samples = read_downmix; + opt->readdata = d; + + opt->channels = 1; +} +void clear_downmix(oe_enc_opt *opt) +{ + downmix *d = (downmix *)opt->readdata; + + opt->read_samples = d->real_reader; + opt->readdata = d->real_readdata; + opt->channels = 2; /* other things in cleanup rely on this */ + + free(d->bufs[0]); + free(d->bufs[1]); + free(d->bufs); + free(d); +} diff --git a/src/utils/ETools/audio.h b/src/utils/ETools/audio.h new file mode 100644 index 00000000000..b465ab61522 --- /dev/null +++ b/src/utils/ETools/audio.h @@ -0,0 +1,71 @@ + +#ifndef __AUDIO_H +#define __AUDIO_H + +#include "encode.h" +#include + +int setup_resample(oe_enc_opt *opt); +void clear_resample(oe_enc_opt *opt); +void setup_downmix(oe_enc_opt *opt); +void clear_downmix(oe_enc_opt *opt); +void setup_scaler(oe_enc_opt *opt, float scale); +void clear_scaler(oe_enc_opt *opt); + +typedef struct +{ + int (*id_func)(unsigned char *buf, int len); /* Returns true if can load file */ + int id_data_len; /* Amount of data needed to id whether this can load the file */ + int (*open_func)(FILE *in, oe_enc_opt *opt, unsigned char *buf, int buflen); + void (*close_func)(void *); + char *format; + char *description; +} input_format; + +typedef struct +{ + short format; + short channels; + int samplerate; + int bytespersec; + short align; + short samplesize; +} wav_fmt; + +typedef struct +{ + short channels; + short samplesize; + long totalsamples; + long samplesread; + FILE *f; + short bigendian; +} wavfile; + +typedef struct +{ + short channels; + int totalframes; + short samplesize; + int rate; + int offset; + int blocksize; +} aiff_fmt; + +typedef wavfile aifffile; /* They're the same */ + +input_format *open_audio_file(FILE *in, oe_enc_opt *opt); + +int raw_open(FILE *in, oe_enc_opt *opt); +int wav_open(FILE *in, oe_enc_opt *opt, unsigned char *buf, int buflen); +int aiff_open(FILE *in, oe_enc_opt *opt, unsigned char *buf, int buflen); +int wav_id(unsigned char *buf, int len); +int aiff_id(unsigned char *buf, int len); +void wav_close(void *); +void raw_close(void *); + +long wav_read(void *, float **buffer, int samples); +long wav_ieee_read(void *, float **buffer, int samples); +long raw_read_stereo(void *, float **buffer, int samples); + +#endif /* __AUDIO_H */ diff --git a/src/utils/ETools/encode.cpp b/src/utils/ETools/encode.cpp new file mode 100644 index 00000000000..0313bf506ad --- /dev/null +++ b/src/utils/ETools/encode.cpp @@ -0,0 +1,534 @@ +/* OggEnc + ** + ** This program is distributed under the GNU General Public License, version 2. + ** A copy of this license is included with this source. + ** + ** Copyright 2000-2002, Michael Smith + ** + ** Portions from Vorbize, (c) Kenneth Arnold + ** and libvorbis examples, (c) Monty + **/ +#include "stdafx.h" + +#include +#include + +#include "platform.h" +#include +#include "encode.h" +//#include "i18n.h" + +#define READSIZE 1024 +#define _(a) a + +int oe_write_page(ogg_page *page, FILE *fp); + +#define SETD(toset) \ + do \ + { \ + if (sscanf(opts[i].val, "%lf", &dval) != 1) \ + fprintf(stderr, "For option %s, couldn't read value %s as double\n", \ + opts[i].arg, opts[i].val); \ + else \ + toset = dval; \ + } while (0) + +#define SETL(toset) \ + do \ + { \ + if (sscanf(opts[i].val, "%ld", &lval) != 1) \ + fprintf(stderr, "For option %s, couldn't read value %s as integer\n", \ + opts[i].arg, opts[i].val); \ + else \ + toset = lval; \ + } while (0) + +static void set_advanced_encoder_options(adv_opt *opts, int count, + vorbis_info *vi) +{ + int manage = 0; + struct ovectl_ratemanage2_arg ai; + int i; + double dval; + long lval; + + vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_GET, &ai); + + for (i = 0; i < count; i++) + { + fprintf(stderr, _("Setting advanced encoder option \"%s\" to %s\n"), + opts[i].arg, opts[i].val); + + if (!xr_strcmp(opts[i].arg, "bitrate_average_damping")) + { + SETD(ai.bitrate_average_damping); + manage = 1; + } + else if (!xr_strcmp(opts[i].arg, "bitrate_average")) + { + SETL(ai.bitrate_average_kbps); + manage = 1; + } + else if (!xr_strcmp(opts[i].arg, "bit_reservoir_bias")) + { + SETD(ai.bitrate_limit_reservoir_bias); + manage = 1; + } + else if (!xr_strcmp(opts[i].arg, "bit_reservoir_bits")) + { + SETL(ai.bitrate_limit_reservoir_bits); + manage = 1; + } + else if (!xr_strcmp(opts[i].arg, "bitrate_hard_min")) + { + SETL(ai.bitrate_limit_min_kbps); + manage = 1; + } + else if (!xr_strcmp(opts[i].arg, "bitrate_hard_max")) + { + SETL(ai.bitrate_limit_max_kbps); + manage = 1; + } + else if (!xr_strcmp(opts[i].arg, "impulse_noisetune")) + { + double val; + SETD(val); + vorbis_encode_ctl(vi, OV_ECTL_IBLOCK_SET, &val); + } + else if (!xr_strcmp(opts[i].arg, "lowpass_frequency")) + { + double _prev, _new; + SETD(_new); + vorbis_encode_ctl(vi, OV_ECTL_LOWPASS_GET, &_prev); + vorbis_encode_ctl(vi, OV_ECTL_LOWPASS_SET, &_new); + fprintf(stderr, _("Changed lowpass frequency from %f kHz to %f kHz\n"), _prev, _new); + } + else + { + fprintf(stderr, _("Unrecognised advanced option \"%s\"\n"), + opts[i].arg); + } + } + + if (manage) + { + if (vorbis_encode_ctl(vi, OV_ECTL_RATEMANAGE2_SET, &ai)) + { + fprintf(stderr, "Failed to set advanced rate management parameters\n"); + } + } +} + +int oe_encode(oe_enc_opt *opt) +{ + + ogg_stream_state os; + ogg_page og; + ogg_packet op; + + vorbis_dsp_state vd; + vorbis_block vb; + vorbis_info vi; + long bitrate; + + long samplesdone = 0; + int eos; + long bytes_written = 0, packetsdone = 0; + double time_elapsed; + int ret = 0; + TIMER *timer; + + if (opt->channels > 255) + { + fprintf(stderr, _("255 channels should be enough for anyone. (Sorry, vorbis doesn't support more)\n")); + return 1; + } + + /* get start time. */ + timer = timer_start(); + + if (!opt->managed && (opt->min_bitrate >= 0 || opt->max_bitrate >= 0)) + { + fprintf(stderr, _("Requesting a minimum or maximum bitrate requires --managed\n")); + return 1; + } + + /* if we had no quality or bitrate spec at all from the user, use + the default quality with no management --Monty 20020711 */ + if (opt->bitrate < 0 && opt->min_bitrate < 0 && opt->max_bitrate < 0) + { + opt->quality_set = 1; + } + + opt->start_encode(opt->infilename, opt->filename, opt->bitrate, opt->quality, + opt->quality_set, opt->managed, opt->min_bitrate, opt->max_bitrate); + + /* Have vorbisenc choose a mode for us */ + vorbis_info_init(&vi); + + if (opt->quality_set > 0) + { + if (vorbis_encode_setup_vbr(&vi, opt->channels, opt->rate, opt->quality)) + { + fprintf(stderr, _("Mode initialisation failed: invalid parameters for quality\n")); + vorbis_info_clear(&vi); + return 1; + } + + /* do we have optional hard bitrate restrictions? */ + if (opt->max_bitrate > 0 || opt->min_bitrate > 0) + { + struct ovectl_ratemanage2_arg ai; + vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE2_GET, &ai); + + /* libvorbis 1.1 (and current svn) doesn't actually fill this in, + which looks like a bug. It'll then reject it when we call the + SET version below. So, fill it in with the values that libvorbis + would have used to fill in this structure if we were using the + bitrate-oriented setup functions. Unfortunately, some of those + values are dependent on the bitrate, and libvorbis has no way to + get a nominal bitrate from a quality value. Well, except by doing + a full setup... So, we do that. + Also, note that this won't work correctly unless you have a very + recent (2005/03/04 or later) version of libvorbis from svn). + */ + + { + vorbis_info vi2; + vorbis_info_init(&vi2); + vorbis_encode_setup_vbr(&vi2, opt->channels, opt->rate, opt->quality); + vorbis_encode_setup_init(&vi2); + bitrate = vi2.bitrate_nominal; + vorbis_info_clear(&vi2); + } + + ai.bitrate_average_kbps = bitrate / 1000; + ai.bitrate_average_damping = 1.5; + ai.bitrate_limit_reservoir_bits = bitrate * 2; + ai.bitrate_limit_reservoir_bias = .1; + + /* And now the ones we actually wanted to set */ + ai.bitrate_limit_min_kbps = opt->min_bitrate; + ai.bitrate_limit_max_kbps = opt->max_bitrate; + ai.management_active = 1; + + if (vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE2_SET, &ai) == 0) + fprintf(stderr, _("Set optional hard quality restrictions\n")); + else + { + fprintf(stderr, _("Failed to set bitrate min/max in quality mode\n")); + vorbis_info_clear(&vi); + return 1; + } + } + } + else + { + if (vorbis_encode_setup_managed(&vi, opt->channels, opt->rate, + opt->max_bitrate > 0 ? opt->max_bitrate * 1000 : -1, + opt->bitrate * 1000, + opt->min_bitrate > 0 ? opt->min_bitrate * 1000 : -1)) + { + fprintf(stderr, _("Mode initialisation failed: invalid parameters for bitrate\n")); + vorbis_info_clear(&vi); + return 1; + } + } + + if (opt->managed && opt->bitrate < 0) + { + struct ovectl_ratemanage2_arg ai; + vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE2_GET, &ai); + ai.bitrate_average_kbps = -1; + vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE2_SET, &ai); + } + else if (!opt->managed) + { + /* Turn off management entirely (if it was turned on). */ + vorbis_encode_ctl(&vi, OV_ECTL_RATEMANAGE2_SET, NULL); + } + + set_advanced_encoder_options(opt->advopt, opt->advopt_count, &vi); + + vorbis_encode_setup_init(&vi); + + /* Now, set up the analysis engine, stream encoder, and other + preparation before the encoding begins. + */ + + vorbis_analysis_init(&vd, &vi); + vorbis_block_init(&vd, &vb); + + ogg_stream_init(&os, opt->serialno); + + /* Now, build the three header packets and send through to the stream + output stage (but defer actual file output until the main encode loop) */ + + { + ogg_packet header_main; + ogg_packet header_comments; + ogg_packet header_codebooks; + int result; + + /* Build the packets */ + vorbis_analysis_headerout(&vd, opt->comments, + &header_main, &header_comments, &header_codebooks); + + /* And stream them out */ + ogg_stream_packetin(&os, &header_main); + ogg_stream_packetin(&os, &header_comments); + ogg_stream_packetin(&os, &header_codebooks); + + while ((result = ogg_stream_flush(&os, &og)) != 0) + { + if (!result) + break; + ret = oe_write_page(&og, opt->out); + if (ret != og.header_len + og.body_len) + { + opt->error(_("Failed writing header to output stream\n")); + ret = 1; + goto cleanup; /* Bail and try to clean up stuff */ + } + } + } + + eos = 0; + + /* Main encode loop - continue until end of file */ + while (!eos) + { + float **buffer = vorbis_analysis_buffer(&vd, READSIZE); + long samples_read = opt->read_samples(opt->readdata, + buffer, READSIZE); + + if (samples_read == 0) + /* Tell the library that we wrote 0 bytes - signalling the end */ + vorbis_analysis_wrote(&vd, 0); + else + { + samplesdone += samples_read; + + /* Call progress update every 40 pages */ + if (packetsdone >= 40) + { + double time; + + packetsdone = 0; + time = timer_time(timer); + + opt->progress_update(opt->filename, opt->total_samples_per_channel, + samplesdone, time); + } + + /* Tell the library how many samples (per channel) we wrote + into the supplied buffer */ + vorbis_analysis_wrote(&vd, samples_read); + } + + /* While we can get enough data from the library to analyse, one + block at a time... */ + while (vorbis_analysis_blockout(&vd, &vb) == 1) + { + + /* Do the main analysis, creating a packet */ + vorbis_analysis(&vb, NULL); + vorbis_bitrate_addblock(&vb); + + while (vorbis_bitrate_flushpacket(&vd, &op)) + { + /* Add packet to bitstream */ + ogg_stream_packetin(&os, &op); + packetsdone++; + + /* If we've gone over a page boundary, we can do actual output, + so do so (for however many pages are available) */ + + while (!eos) + { + int result = ogg_stream_pageout(&os, &og); + if (!result) + break; + + ret = oe_write_page(&og, opt->out); + if (ret != og.header_len + og.body_len) + { + opt->error(_("Failed writing data to output stream\n")); + ret = 1; + goto cleanup; /* Bail */ + } + else + bytes_written += ret; + + if (ogg_page_eos(&og)) + eos = 1; + } + } + } + } + + ret = 0; /* Success, set return value to 0 since other things reuse it + * for nefarious purposes. */ + + /* Cleanup time */ +cleanup: + + ogg_stream_clear(&os); + + vorbis_block_clear(&vb); + vorbis_dsp_clear(&vd); + vorbis_info_clear(&vi); + + time_elapsed = timer_time(timer); + opt->end_encode(opt->filename, time_elapsed, opt->rate, samplesdone, bytes_written); + + timer_clear(timer); + + return ret; +} + +void update_statistics_full(char *fn, long total, long done, double time) +{ + static char *spinner = "|/-\\"; + static int spinpoint = 0; + double remain_time; + int minutes = 0, seconds = 0; + + remain_time = time / ((double)done / (double)total) - time; + minutes = ((int)remain_time) / 60; + seconds = (int)(remain_time - (double)((int)remain_time / 60) * 60); + + fprintf(stderr, "\r"); + fprintf(stderr, _("\t[%5.1f%%] [%2dm%.2ds remaining] %c "), + done * 100.0 / total, minutes, seconds, spinner[spinpoint++ % 4]); +} + +void update_statistics_notime(char *fn, long total, long done, double time) +{ + static char *spinner = "|/-\\"; + static int spinpoint = 0; + + fprintf(stderr, "\r"); + fprintf(stderr, _("\tEncoding [%2dm%.2ds so far] %c "), + ((int)time) / 60, (int)(time - (double)((int)time / 60) * 60), + spinner[spinpoint++ % 4]); +} + +int oe_write_page(ogg_page *page, FILE *fp) +{ + int written; + written = (int)fwrite(page->header, 1, page->header_len, fp); + written += (int)fwrite(page->body, 1, page->body_len, fp); + + return written; +} + +void final_statistics(char *fn, double time, int rate, long samples, long bytes) +{ + double speed_ratio; + if (fn) + fprintf(stderr, _("\n\nDone encoding file \"%s\"\n"), fn); + else + fprintf(stderr, _("\n\nDone encoding.\n")); + + speed_ratio = (double)samples / (double)rate / time; + + fprintf(stderr, _("\n\tFile length: %dm %04.1fs\n"), + (int)(samples / rate / 60), + (double)(samples / rate - + samples / rate / 60 * 60)); + fprintf(stderr, _("\tElapsed time: %dm %04.1fs\n"), + (int)(time / 60), + time - iFloor((float)time / 60) * 60); + fprintf(stderr, _("\tRate: %.4f\n"), speed_ratio); + fprintf(stderr, _("\tAverage bitrate: %.1f kb/s\n\n"), + 8. / 1000. * ((double)bytes / ((double)samples / (double)rate))); +} + +void final_statistics_null(char *fn, double time, int rate, long samples, + long bytes) +{ + /* Don't do anything, this is just a placeholder function for quiet mode */ +} + +void update_statistics_null(char *fn, long total, long done, double time) +{ + /* So is this */ +} + +void encode_error(char *errmsg) +{ + fprintf(stderr, "\n%s\n", errmsg); +} + +static void print_brconstraints(int min, int max) +{ + if (min > 0 && max > 0) + fprintf(stderr, "(min %d kbps, max %d kbps)", min, max); + else if (min > 0) + fprintf(stderr, "(min %d kbps, no max)", min); + else if (max > 0) + fprintf(stderr, "(no min, max %d kbps)", max); + else + fprintf(stderr, "(no min or max)"); +} + +void start_encode_full(char *fn, char *outfn, int bitrate, float quality, int qset, + int managed, int min, int max) +{ + if (bitrate > 0) + { + if (managed > 0) + { + fprintf(stderr, _("Encoding %s%s%s to \n " + "%s%s%s \nat average bitrate %d kbps "), + fn ? "\"" : "", fn ? fn : _("standard input"), fn ? "\"" : "", + outfn ? "\"" : "", outfn ? outfn : _("standard output"), outfn ? "\"" : "", + bitrate); + print_brconstraints(min, max); + fprintf(stderr, ", \nusing full bitrate management engine\n"); + } + else + { + fprintf(stderr, _("Encoding %s%s%s to \n %s%s%s \nat approximate bitrate %d kbps (VBR encoding enabled)\n"), + fn ? "\"" : "", fn ? fn : _("standard input"), fn ? "\"" : "", + outfn ? "\"" : "", outfn ? outfn : _("standard output"), outfn ? "\"" : "", + bitrate); + } + } + else + { + if (qset > 0) + { + if (managed > 0) + { + fprintf(stderr, _("Encoding %s%s%s to \n %s%s%s \nat quality level %2.2f using constrained VBR "), + fn ? "\"" : "", fn ? fn : _("standard input"), fn ? "\"" : "", + outfn ? "\"" : "", outfn ? outfn : _("standard output"), outfn ? "\"" : "", + quality * 10); + print_brconstraints(min, max); + fprintf(stderr, "\n"); + } + else + { + fprintf(stderr, _("Encoding %s%s%s to \n %s%s%s \nat quality %2.2f\n"), + fn ? "\"" : "", fn ? fn : _("standard input"), fn ? "\"" : "", + outfn ? "\"" : "", outfn ? outfn : _("standard output"), outfn ? "\"" : "", + quality * 10); + } + } + else + { + fprintf(stderr, _("Encoding %s%s%s to \n %s%s%s \nusing bitrate management "), + fn ? "\"" : "", fn ? fn : _("standard input"), fn ? "\"" : "", + outfn ? "\"" : "", outfn ? outfn : _("standard output"), outfn ? "\"" : ""); + print_brconstraints(min, max); + fprintf(stderr, "\n"); + } + } +} + +void start_encode_null(char *fn, char *outfn, int bitrate, float quality, int qset, + int managed, int min, int max) +{ +} diff --git a/src/utils/ETools/encode.h b/src/utils/ETools/encode.h new file mode 100644 index 00000000000..774b9edadee --- /dev/null +++ b/src/utils/ETools/encode.h @@ -0,0 +1,129 @@ +#ifndef __ENCODE_H +#define __ENCODE_H + +#include +#include + +typedef void TIMER; +typedef long (*audio_read_func)(void *src, float **buffer, int samples); +typedef void (*progress_func)(char *fn, long totalsamples, + long samples, double time); +typedef void (*enc_end_func)(char *fn, double time, int rate, + long samples, long bytes); +typedef void (*enc_start_func)(char *fn, char *outfn, int bitrate, + float quality, int qset, int managed, int min_br, int max_br); +typedef void (*error_func)(char *errormessage); + +void *timer_start(void); +double timer_time(void *); +void timer_clear(void *); +int create_directories(char *); + +void update_statistics_full(char *fn, long total, long done, double time); +void update_statistics_notime(char *fn, long total, long done, double time); +void update_statistics_null(char *fn, long total, long done, double time); +void start_encode_full(char *fn, char *outfn, int bitrate, float quality, int qset, + int managed, int min, int max); +void start_encode_null(char *fn, char *outfn, int bitrate, float quality, int qset, + int managed, int min, int max); +void final_statistics(char *fn, double time, int rate, long total_samples, + long bytes); +void final_statistics_null(char *fn, double time, int rate, long total_samples, + long bytes); +void encode_error(char *errmsg); + +typedef struct +{ + char *arg; + char *val; +} adv_opt; + +typedef struct +{ + char **title; + int title_count; + char **artist; + int artist_count; + char **album; + int album_count; + char **comments; + int comment_count; + char **tracknum; + int track_count; + char **dates; + int date_count; + char **genre; + int genre_count; + adv_opt *advopt; + int advopt_count; + int copy_comments; + + int quiet; + + int rawmode; + int raw_samplesize; + int raw_samplerate; + int raw_channels; + int raw_endianness; + + char *namefmt; + char *namefmt_remove; + char *namefmt_replace; + char *outfile; + + /* All 3 in kbps */ + int managed; + int min_bitrate; + int nominal_bitrate; + int max_bitrate; + + /* Float from 0 to 1 (low->high) */ + float quality; + int quality_set; + + int resamplefreq; + int downmix; + float scale; + + unsigned int serial; +} oe_options; + +typedef struct +{ + vorbis_comment *comments; + unsigned int serialno; + + audio_read_func read_samples; + progress_func progress_update; + enc_end_func end_encode; + enc_start_func start_encode; + error_func error; + + void *readdata; + + long total_samples_per_channel; + int channels; + long rate; + int samplesize; + int endianness; + int resamplefreq; + int copy_comments; + + /* Various bitrate/quality options */ + int managed; + int bitrate; + int min_bitrate; + int max_bitrate; + float quality; + int quality_set; + adv_opt *advopt; + int advopt_count; + + FILE *out; + char *filename; + char *infilename; +} oe_enc_opt; + +int oe_encode(oe_enc_opt *opt); + +#endif /* __ENCODE_H */ diff --git a/src/utils/ETools/ogg_enc.cpp b/src/utils/ETools/ogg_enc.cpp new file mode 100644 index 00000000000..0b293f22aaf --- /dev/null +++ b/src/utils/ETools/ogg_enc.cpp @@ -0,0 +1,98 @@ +#include "stdafx.h" +#include "ETools.h" + +#include "encode.h" +#include "platform.h" +#include "audio.h" + +#pragma warning(disable : 4995) + +namespace ETOOLS +{ + ETOOLS_API int ogg_enc(const char *in_fn, const char *out_fn, float quality, void *comment, int comment_size) + { + /* Default values */ + oe_options opt = {NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, + 0, NULL, 0, NULL, 0, NULL, 0, 1, 0, 0, 16, 44100, 2, 0, NULL, + DEFAULT_NAMEFMT_REMOVE, DEFAULT_NAMEFMT_REPLACE, + NULL, 0, -1, -1, -1, -.3f, -1, 0, 0, 0.f, 0}; + + oe_enc_opt enc_opts; + vorbis_comment vc; + FILE *in, *out = NULL; + // int foundformat = 0; + // int closeout = 0, closein = 0; + input_format *format; + int res = 1; + + /* Set various encoding defaults */ + enc_opts.serialno = 0; + enc_opts.progress_update = update_statistics_full; + enc_opts.start_encode = start_encode_full; + enc_opts.end_encode = final_statistics; + enc_opts.error = encode_error; + enc_opts.comments = &vc; + + in = fopen(in_fn, "rb"); + + if (in == NULL) + return 0; + + format = open_audio_file(in, &enc_opts); + if (!format) + { + fclose(in); + return 0; + }; + + out = fopen(out_fn, "wb"); + if (out == NULL) + { + return 0; + } + + /* OK, let's build the vorbis_comments structure */ + memset(&vc, 0, sizeof(vc)); + + vc.user_comments = (char **)_ogg_malloc(sizeof(*vc.user_comments)); + vc.comment_lengths = (int *)_ogg_malloc(sizeof(*vc.comment_lengths)); + vc.comments = 1; + vc.user_comments[0] = (char *)_ogg_malloc(comment_size); + memcpy(vc.user_comments[0], comment, comment_size); + vc.comment_lengths[0] = comment_size; + + /* Now, set the rest of the options */ + enc_opts.out = out; + enc_opts.comments = &vc; + enc_opts.filename = (char *)out_fn; + enc_opts.infilename = (char *)in_fn; + enc_opts.quality = quality; + enc_opts.quality_set = opt.quality_set; + enc_opts.managed = opt.managed; + enc_opts.bitrate = opt.nominal_bitrate; + enc_opts.min_bitrate = opt.min_bitrate; + enc_opts.max_bitrate = opt.max_bitrate; + enc_opts.advopt = opt.advopt; + enc_opts.advopt_count = opt.advopt_count; + + // encode + if (oe_encode(&enc_opts)) + res = 0; + + // clear comment + if (vc.user_comments[0]) + _ogg_free(vc.user_comments[0]); + if (vc.user_comments) + _ogg_free(vc.user_comments); + if (vc.comment_lengths) + _ogg_free(vc.comment_lengths); + if (vc.vendor) + _ogg_free(vc.vendor); + + // close files + fclose(in); + fclose(out); + + return res; + } +} diff --git a/src/utils/ETools/optimize_vertex_order.cpp b/src/utils/ETools/optimize_vertex_order.cpp new file mode 100644 index 00000000000..62832b1e9cf --- /dev/null +++ b/src/utils/ETools/optimize_vertex_order.cpp @@ -0,0 +1,1548 @@ +#include "stdafx.h" +#pragma hdrstop + +#include "ArbitraryList.h" +#include "BinaryHeap.h" + +// The table of what score increase you get for reducing a valence to a certain amount. +// Any valence over the max value gets the max value boost. +// Bear in mind that three of these get added each tri. +const int c_iMaxValenceBoost = 5; +float fValenceBoost[c_iMaxValenceBoost] = + { + 0.0f, + 0.68f, + 1.0f, + 1.1f, + 1.15f}; + +int LOOKAHEAD = 5; +// Limit the number of tris to lookahead with. +int iLookaheadCutoff = 16; +// Limits how bad tris can be when adding to the heap. +const float fCutoffFactor = 2.0f; +// Another slightly different limit. +const float fExpensiveFactor = 1.5f; + +// This stuff simulates a FIFO cache. There are lots of types, but (a) this is the +// easiest to model and (b) it's actually used in lots of real hardware (mainly +// because it's also the easiest to construct). + +// Some data structures to track cache scores. + +struct ScoreTri +{ + WORD wIndex[3]; + bool bUsed; + bool bAllowed; // TRUE if we're even going to consider this tri. +}; + +struct ScoreVertex +{ + ArbitraryList stri; // The tris that use this vertex. + int iCurrentValence; // Current unused valence of the vertex. +}; + +ArbitraryList svVertex; +ArbitraryList stTri; +ArbitraryList pstTri; + +struct CacheTypeInfo +{ + // How long the FIFO is. + int iLength; + // The score for a vertex miss. + // If they all sum to 1.0f, you get a weighted average + // of the number of vertices loaded coming out the end. + float fMissScore; +}; + +// The lengths of the various FIFOs and their relative weightings. +// These weightings are purely arbitrary - bias them to whichever +// your target hardware area is. You can usually find out FIFO +// lengths (or equivalent) from your friendly IHV devrel team. + +#if 0 + +// General settings. +const int c_iCacheNumTypes = 4; +const CacheTypeInfo c_ctiCacheTypeSize[c_iCacheNumTypes] = +{ + { 3, 0.15f }, // Sort of strip simulation. Sort of. + { 4, 0.15f }, // Some hardware knows about quads. + { 12, 0.35f }, // Newer hardware is around 12-16. Heavier weighting on them. + { 16, 0.35f } +}; + +#elif 0 + +// Dedicated 12-entry cache. +const int c_iCacheNumTypes = 1; +const CacheTypeInfo c_ctiCacheTypeSize[c_iCacheNumTypes] = + { + {12, 1.0f}}; + +#else + +// 12-entry cache, with some weighting towards sharing that last tri. +// This slightly speeds up things that have a decent-sized secondary cache, +// but also a lightning-fast primary cache of the last tri. +// Only needs a tiny weighting to clean up the 12-entry-only stuff, +// which tends to look a bit fragmented, since it doesn't care where in +// the last 12 the used vertices are. +// Note that using this will increase the displayed "miss" count a bit, even +// though there are (usually) no extra misses for the second-level cache, +// and the result will still be optimal. +const int c_iCacheNumTypes = 2; +const CacheTypeInfo c_ctiCacheTypeSize[c_iCacheNumTypes] = + { + {20, 0.95f}, + {3, 0.05f}}; + +#endif + +struct CacheTypeTriInfo +{ + int iIndicesAdded; // Were 0, 1, 2 or 3 indices added to the start of the FIFO. + WORD wIndicesBinned[4]; // And the indices that fell off the end. +}; + +struct CacheTri +{ + WORD wIndex[3]; // The tri added this time. + CacheTypeTriInfo ctti[c_iCacheNumTypes]; // The FIFO histories. +}; + +struct CacheVert +{ + BYTE bRefcount[c_iCacheNumTypes]; // How many times each vertex is referenced by the cache. +}; + +ArbitraryList cvCacheStatus; +ArbitraryList ctCacheHistory; // The cache history. + +struct CurrentCacheState +{ + int iCacheCurrentMisses; // The current number of vertex loads for each type. + WORD *pwCacheFifoState; // The current FIFO contents (circular buffer). + int iCacheFifoWritePos; // Where the current "tail" of the FIFO is. +} ccsState[c_iCacheNumTypes]; + +#ifdef _DEBUG +// Set this to 1 if you want to check the cache works, but it's pretty slow. +#define CACHE_DEBUG 0 +#else +#define CACHE_DEBUG 0 +#endif + +void CacheInit(int iNumberOfVertices) +{ + int i; + for (i = 0; i < c_iCacheNumTypes; i++) + { + ccsState[i].iCacheCurrentMisses = 0; + ccsState[i].pwCacheFifoState = new WORD[c_ctiCacheTypeSize[i].iLength]; + for (int j = 0; j < c_ctiCacheTypeSize[i].iLength; j++) + { + ccsState[i].pwCacheFifoState[j] = 0xFFFF; // "unused" value - won't cause a cache hit. + } + ccsState[i].iCacheFifoWritePos = 0; + } + ctCacheHistory.resize(0); + cvCacheStatus.resize(iNumberOfVertices); + for (i = 0; i < iNumberOfVertices; i++) + { + for (int j = 0; j < c_iCacheNumTypes; j++) + { + (cvCacheStatus.item(i))->bRefcount[j] = 0; + } + } +} + +void CacheBin(void) +{ + for (int i = 0; i < c_iCacheNumTypes; i++) + { + VERIFY(ccsState[i].pwCacheFifoState != NULL); + delete[] ccsState[i].pwCacheFifoState; + ccsState[i].pwCacheFifoState = NULL; + } + ctCacheHistory.resize(0); + cvCacheStatus.resize(0); +} + +// Returns the number of extra vertex misses due to this addition. +// Set bDontActuallyAdd to TRUE to just find the number of cache misses if this tri was added. +float CacheAddTri(WORD wIndex1, WORD wIndex2, WORD wIndex3, BOOL bDontActuallyAdd = FALSE) +{ + WORD wIndex[3]; + wIndex[0] = wIndex1; + wIndex[1] = wIndex2; + wIndex[2] = wIndex3; + + CacheTri *pct = NULL; + if (!bDontActuallyAdd) + { + pct = ctCacheHistory.append(); + pct->wIndex[0] = wIndex[0]; + pct->wIndex[1] = wIndex[1]; + pct->wIndex[2] = wIndex[2]; + } + + float fTotalScore = 0.0f; + for (int iType = 0; iType < c_iCacheNumTypes; iType++) + { + CurrentCacheState &ccs = ccsState[iType]; + + int iCurNumMisses = ccs.iCacheCurrentMisses; + + // We must scan all three indices before adding any, otherwise you get nasty cases like: + // 0,1,2 followed by 3,0,1. If you add as you go along, the 3 kicks out the 0, + // then the 0 kicks out the 1, then the 1 kicks out the 2. And you have + // 0 cache hits, rather than 2. + // Most hardware does all three checks before adding as well. + // NOTE! If your target hardware doesn't, shorten the FIFO a bit to get roughly the same behaviour. + BOOL bFound[3]; + int iVert; + for (iVert = 0; iVert < 3; iVert++) + { + bFound[iVert] = ((cvCacheStatus.item(wIndex[iVert]))->bRefcount[iType] > 0); + +#if CACHE_DEBUG + WORD wInd = wIndex[iVert]; + // Is this in the cache already? + int j; + BOOL bFoundThis = FALSE; + // bFound[iVert] = FALSE; + for (j = c_ctiCacheTypeSize[iType].iLength - 1; j >= 0; j--) + { + if (ccs.pwCacheFifoState[j] == wInd) + { + // Found. + // bFound[iVert] = TRUE; + bFoundThis = TRUE; + break; + } + } + VERIFY(bFoundThis == bFound[iVert]); +#endif + } + + if (bDontActuallyAdd) + { + // Just find what the cost is. + for (iVert = 0; iVert < 3; iVert++) + { + if (!bFound[iVert]) + { + fTotalScore += c_ctiCacheTypeSize[iType].fMissScore; + } + } + } + else + { + // Actually add the thing. + pct->ctti[iType].iIndicesAdded = 0; + for (iVert = 0; iVert < 3; iVert++) + { + if (!bFound[iVert]) + { + // Not in the cache. Add it to the FIFO. + WORD wInd = wIndex[iVert]; + + // Store the current tail of the FIFO. + pct->ctti[iType].wIndicesBinned[pct->ctti[iType].iIndicesAdded] = ccs.pwCacheFifoState[ccs.iCacheFifoWritePos]; + pct->ctti[iType].iIndicesAdded++; + + // This vert just fell off the end. + WORD wOldInd = ccs.pwCacheFifoState[ccs.iCacheFifoWritePos]; + if (wOldInd != 0xffff) + { + (cvCacheStatus.item(wOldInd))->bRefcount[iType]--; + VERIFY((cvCacheStatus.item(wOldInd))->bRefcount[iType] == 0); + } + + // Put this index in. + ccs.pwCacheFifoState[ccs.iCacheFifoWritePos] = wInd; + + // This vert is in. + (cvCacheStatus.item(wInd))->bRefcount[iType]++; + VERIFY((cvCacheStatus.item(wInd))->bRefcount[iType] == 1); + + // Move the tail on. + ccs.iCacheFifoWritePos++; + if (ccs.iCacheFifoWritePos >= c_ctiCacheTypeSize[iType].iLength) + { + ccs.iCacheFifoWritePos = 0; + } + + // And we missed. + ccs.iCacheCurrentMisses++; + + // And if this tri is degenerate, we need to spot that we've loaded the others. + if (iVert == 0) + { + if (wIndex[0] == wIndex[1]) + { + VERIFY(!bFound[1]); + bFound[1] = TRUE; + } + if (wIndex[0] == wIndex[2]) + { + VERIFY(!bFound[2]); + bFound[2] = TRUE; + } + } + else if (iVert == 1) + { + if (wIndex[1] == wIndex[2]) + { + VERIFY(!bFound[2]); + bFound[2] = TRUE; + } + } + } + else + { + // Found. Do nothing. + } + } + fTotalScore += c_ctiCacheTypeSize[iType].fMissScore * (ccs.iCacheCurrentMisses - iCurNumMisses); + } + } + + return fTotalScore; +} + +void CacheRemoveTri(void) +{ + // Copy the last tri info. + CacheTri ct = *(ctCacheHistory.item(ctCacheHistory.size() - 1)); + // And bin the recorded one. + ctCacheHistory.erase_fast(ctCacheHistory.size() - 1); + + // Now undo the tri info. + for (int iType = 0; iType < c_iCacheNumTypes; iType++) + { + CurrentCacheState &ccs = ccsState[iType]; + + // Unroll the FIFO. + for (int i = ct.ctti[iType].iIndicesAdded - 1; i >= 0; i--) + { + // Move the tail back. + ccs.iCacheFifoWritePos--; + if (ccs.iCacheFifoWritePos < 0) + { + ccs.iCacheFifoWritePos = c_ctiCacheTypeSize[iType].iLength - 1; + } + + // This vert just fell off the start. + WORD wOldInd = ccs.pwCacheFifoState[ccs.iCacheFifoWritePos]; + (cvCacheStatus.item(wOldInd))->bRefcount[iType]--; + VERIFY((cvCacheStatus.item(wOldInd))->bRefcount[iType] == 0); + + // Stuff this into the last entry in the fifo. + WORD wInd = ct.ctti[iType].wIndicesBinned[i]; + ccs.pwCacheFifoState[ccs.iCacheFifoWritePos] = wInd; + + // Push this vert into the end. + if (wInd != 0xffff) + { + (cvCacheStatus.item(wInd))->bRefcount[iType]++; + VERIFY((cvCacheStatus.item(wInd))->bRefcount[iType] == 1); + } + + // And we un-missed. :-) + ccs.iCacheCurrentMisses--; + } + } +} + +// Find the tri that was last added to the cache. +bool CacheGetLastTri(WORD pwIndices[3]) +{ + if (ctCacheHistory.size() > 0) + { + CacheTri ct = *(ctCacheHistory.item(ctCacheHistory.size() - 1)); + pwIndices[0] = ct.wIndex[0]; + pwIndices[1] = ct.wIndex[1]; + pwIndices[2] = ct.wIndex[2]; + return TRUE; + } + else + { + pwIndices[0] = -1; + pwIndices[1] = -1; + pwIndices[2] = -1; + return FALSE; + } +} + +float GetNumVerticesLoadedTriList(WORD *pwList, int iHowManyTris) +{ + // What's the top index? + WORD wHighest = 0; + int i; + for (i = 0; i < iHowManyTris * 3; i++) + { + if (wHighest < pwList[i]) + { + wHighest = pwList[i]; + } + } + + CacheInit(wHighest + 1); + + // Let's find the current score of this list. + float fScore = 0.0f; + WORD *pwCurTri = pwList; + for (i = 0; i < iHowManyTris; i++) + { + fScore += CacheAddTri(pwCurTri[0], pwCurTri[1], pwCurTri[2]); + pwCurTri += 3; + } + + CacheBin(); + + return fScore; +} + +float FindBestScoreLookahead(int iCountdown, float fCurrentScore, float fInputBestSoFar, + int iNumTris, WORD *pwResult) +{ + + VERIFY(iCountdown <= LOOKAHEAD); + + int iLookahead = iCountdown; + if (iLookahead > LOOKAHEAD) + { + iLookahead = LOOKAHEAD; + } + + float fBestSoFar = fInputBestSoFar; + + // Given the BestSoFar score, what is the average cost of each lookahead tri? + float fAverageCost = (fBestSoFar - fCurrentScore) / (int)iLookahead; + // And now allow tris that are a bit worse. + float fExpensiveCutoff = fAverageCost * fExpensiveFactor; + + VERIFY(iCountdown > 0); + VERIFY(iNumTris > 0); + + int j; + +#if 0 + if ( iNumTris == 1 ) + { + // Well, that's an easy decision then. + + // Find score after removal. + //float fTriScore = CacheAddTri ( pwIndices[0], pwIndices[1], pwIndices[2], TRUE ); + ScoreTri *pstCur = ppstCurTris[0]; + float fTriScore = CacheAddTri ( pstCur->wIndex[0], pstCur->wIndex[1], pstCur->wIndex[2], TRUE ); + for ( j = 0; j < 3; j++ ) + { + // Use the valence score after the tri has been removed. + //int iValence = (*(iValenceCounts.item(pwIndices[j]))) - 1; + int iValence = (svVertex.item(pstCur->wIndex[j])->iCurrentValence) - 1; + VERIFY ( iValence >= 0 ); + if ( iValence < c_iMaxValenceBoost ) + { + fTriScore += fValenceBoost[iValence]; + } + else + { + fTriScore += fValenceBoost[c_iMaxValenceBoost-1]; + } + } + + fTriScore += fCurrentScore; + + //pwResult[0] = pwIndices[0]; + //pwResult[1] = pwIndices[1]; + //pwResult[2] = pwIndices[2]; + pwResult[0] = pstCur->wIndex[0]; + pwResult[1] = pstCur->wIndex[1]; + pwResult[2] = pstCur->wIndex[2]; + + if ( fTriScore > fBestSoFar ) + { + // Oh well. + // (actually, not sure this ever happens). + return fInputBestSoFar; + } + else + { + return fTriScore; + } + } +#endif + +#if 0 +#ifdef _DEBUG + for ( int k = 0; k < iNumTris; k++ ) + { + VERIFY ( !ppstCurTris[k]->bAllowed ); + VERIFY ( !ppstCurTris[k]->bUsed ); + } +#endif +#endif + + // Should we limit ourselves to tris that share at least one vert with the previous one? + bool bNoMadJumps = FALSE; + WORD wPrevIndices[3]; + // if ( ( fBestSoFar - fCurrentScore ) < (float)iCountdown ) + // The lookahead score is lower than the countdown, so doing mad jumps + // is not going to do sensible things. + + ArbitraryList pstTriLocal; + + // if ( iCountdown == iLookahead ) + { + // Ah - this is probably a lookahead, not assembling the real list. + // Find the previous indices from the cache (a bit of a roundabout method). + int iNumAllowed = 0; + BOOL bRes = CacheGetLastTri(wPrevIndices); + VERIFY(bRes); + { + bNoMadJumps = TRUE; + // And mark all the tris that these used as "allowed" + for (int i = 0; i < 3; i++) + { + ScoreVertex *psv = svVertex.item(wPrevIndices[i]); + for (int j = 0; j < psv->stri.size(); j++) + { + ScoreTri *pst = (*(psv->stri.item(j))); + if ((!pst->bUsed) && (!pst->bAllowed)) + { + pst->bAllowed = TRUE; + *(pstTriLocal.append()) = pst; + iNumAllowed++; + } + } + } + + if (iNumAllowed < 1) + { + // Oops - we've gone into a dead-end, so that very few tris + // are allowed. So open the selection up again. + pstTriLocal.resize(0); + bNoMadJumps = FALSE; + int i; + for (i = 0; i < 3; i++) + { + ScoreVertex *psv = svVertex.item(wPrevIndices[i]); + for (int j = 0; j < psv->stri.size(); j++) + { + ScoreTri *pst = (*(psv->stri.item(j))); + if (!pst->bUsed) + { + pst->bAllowed = FALSE; + } + } + } + + for (i = 0; i < stTri.size(); i++) + { + if (!(stTri.item(i))->bUsed) + { + *(pstTriLocal.append()) = stTri.item(i); + } + } + } + } + } + + // Add the tris to a new priority queue, sorting by score. + // BinaryHeap NewHeap; + BinaryHeap NewHeap; + + int i; + // WORD *pwCurIndex = pwIndices; + for (i = pstTriLocal.size() - 1; i >= 0; i--) + { + ScoreTri *pstCurTri = *(pstTriLocal.item(i)); + float fTriScore = 0.0f; + if (bNoMadJumps) + { + if (!pstCurTri->bAllowed) + { + continue; + } + +#if IGNORE_VALENCE_FOR_LOOKAHEADS + // Only use the valence stuff on non-lookaheads. + // To make the scores comparable, add the maximum valence boost all the time. + fTriScore += 3.0f * fValenceBoost[c_iMaxValenceBoost - 1]; +#endif + } +#if IGNORE_VALENCE_FOR_LOOKAHEADS + else +#endif + { + // Only use the valence stuff on non-lookaheads. + for (j = 0; j < 3; j++) + { + // Use the valence score after the tri has been removed. + // int iValence = (*(iValenceCounts.item(pwCurIndex[j]))) - 1; + int iValence = (svVertex.item(pstCurTri->wIndex[j])->iCurrentValence) - 1; + VERIFY(iValence >= 0); + if (iValence < c_iMaxValenceBoost) + { + fTriScore += fValenceBoost[iValence]; + } + else + { + fTriScore += fValenceBoost[c_iMaxValenceBoost - 1]; + } + } + } + + if (fTriScore > fExpensiveCutoff) + { + // This tri is a lot more expensive than the average cost of the BestSoFar tris. + // It's very unlikely to give us a good result. + continue; + } + + if (fCurrentScore + fTriScore >= fBestSoFar) + { + // We've already gone more than the best score. + // pwCurIndex += 3; + continue; + } + + // And the vertex cost. + fTriScore += CacheAddTri(pstCurTri->wIndex[0], pstCurTri->wIndex[1], pstCurTri->wIndex[2], TRUE); + + if (fTriScore > fExpensiveCutoff) + { + // This tri is a lot more expensive than the average cost of the BestSoFar tris. + // It's very unlikely to give us a good result. + continue; + } + + if (fCurrentScore + fTriScore >= fBestSoFar) + { + // We've already gone more than the best score. + // pwCurIndex += 3; + continue; + } + + // And bung it in the heap. + // We -ve the score so that the first in the heap is the one with the _least_ score. + NewHeap.Add(pstCurTri, -fTriScore); + // pwCurIndex += 3; + } + + // Undo the "allowed" flags. + if (bNoMadJumps) + { + for (int i = 0; i < 3; i++) + { + ScoreVertex *psv = svVertex.item(wPrevIndices[i]); + for (int j = 0; j < psv->stri.size(); j++) + { + (*(psv->stri.item(j)))->bAllowed = FALSE; + } + } + } + + // Now extract from the heap, best score to worst. + // This attempts to get early-outs very quickly and prevent too much recursion. + // WORD *pwBest = NULL; + // WORD *pwCur = NewHeap.FindFirst(); + ScoreTri *pstBest = NULL; + ScoreTri *pstCur = NewHeap.FindFirst(); + + // if ( pwCur == NULL ) + if (pstCur == NULL) + { + // Found nothing that was better. + return fBestSoFar; + } + + // Above this score, just don't bother. + float fCutoffScore = fCutoffFactor * NewHeap.GetCurrentSort(); + +#ifdef _DEBUG + float fPrevScore = 1.0f; +#endif + + int iTried = 0; + // while ( pwCur != NULL ) + while (pstCur != NULL) + { + float fThisTriNegScore = NewHeap.GetCurrentSort(); + NewHeap.RemoveFirst(); + +#ifdef _DEBUG + // Check this heap actually works! + VERIFY(fThisTriNegScore <= fPrevScore); + fPrevScore = fThisTriNegScore; +#endif + + if (fThisTriNegScore < fCutoffScore) + { + // Reached the cutoff for this tri - don't bother continuing. + break; + } + + float fScore = fCurrentScore - fThisTriNegScore; + + if (fScore >= fBestSoFar) + { + // We've already gone more than the best score. + // The reast of the heap is bound to be greater, so don't bother continuing. + break; + } + + if (bNoMadJumps) + { + iTried++; + if (iTried > iLookaheadCutoff) + { + // Tried enough tris - don't want to cause a combinatorial explosion. + break; + } + } + + // Do the valencies. +#ifdef _DEBUG + float fValenceScore = 0.0f; +#endif +#if IGNORE_VALENCE_FOR_LOOKAHEADS + if (bNoMadJumps) + { + // Only use the valence stuff on non-lookaheads. + // To make the scores comparable, add the maximum valence boost all the time. + fValenceScore = 3.0f * fValenceBoost[c_iMaxValenceBoost - 1]; + } + else +#endif + { + for (j = 0; j < 3; j++) + { + // int iValence = --(*(iValenceCounts.item(pwCur[j]))); + int iValence = --(svVertex.item(pstCur->wIndex[j])->iCurrentValence); +#ifdef _DEBUG + VERIFY(iValence >= 0); + if (iValence < c_iMaxValenceBoost) + { + fValenceScore += fValenceBoost[iValence]; + } + else + { + fValenceScore += fValenceBoost[c_iMaxValenceBoost - 1]; + } +#endif + } + } + + // Add it to the cache. + float fScoreTemp = CacheAddTri(pstCur->wIndex[0], pstCur->wIndex[1], pstCur->wIndex[2]); + + VERIFY(!pstCur->bUsed); + pstCur->bUsed = TRUE; + +#ifdef _DEBUG + fScoreTemp += fValenceScore; + VERIFY(fabs(fScoreTemp + fThisTriNegScore) < 0.0001f); +#endif + + if (iLookahead > 1) + { + // Swap pwCur to the start of the list. + // And look ahead a bit more. + // fScore = FindBestScoreLookahead ( iLookahead - 1, fScore, fBestSoFar, pwIndices + 3, iNumTris - 1, pwResult + 3 ); + float fNewScore = FindBestScoreLookahead(iLookahead - 1, fScore, fBestSoFar, iNumTris - 1, pwResult + 3); + // VERIFY ( fNewScore < 1e9 ); + fScore = fNewScore; + } + // VERIFY ( fScore < 1e9 ); + if (fScore < fBestSoFar) + { + fBestSoFar = fScore; + // pwBest = pwCur; + pstBest = pstCur; + } + + CacheRemoveTri(); + VERIFY(pstCur->bUsed); + pstCur->bUsed = FALSE; + +#if IGNORE_VALENCE_FOR_LOOKAHEADS + if (!bNoMadJumps) +#endif + { + // Restore the valencies. + for (j = 0; j < 3; j++) + { + //++(*(iValenceCounts.item(pwCur[j]))); + ++(svVertex.item(pstCur->wIndex[j])->iCurrentValence); + } + } + + // pwCur = NewHeap.FindFirst(); + pstCur = NewHeap.FindFirst(); + } + + // if ( pwBest == NULL ) + if (pstBest == NULL) + { + // We didn't find a solution that was better than the existing one. + // VERIFY ( fBestSoFar < 1e9 ); + return fInputBestSoFar; + } + else + { + // Found a better solution. + + // Swap the best tri to the start of the list. + float fNewBestScore = fBestSoFar; + + // Dump the tri to the result buffer. + // ScoreTri *pstBest = *ppstBest; + // pwResult[0] = pwBest[0]; + // pwResult[1] = pwBest[1]; + // pwResult[2] = pwBest[2]; + pwResult[0] = pstBest->wIndex[0]; + pwResult[1] = pstBest->wIndex[1]; + pwResult[2] = pstBest->wIndex[2]; + if (iCountdown > 1) + { + // float fScore = CacheAddTri ( wTemp[0], wTemp[1], wTemp[2] ); + float fScore = CacheAddTri(pstBest->wIndex[0], pstBest->wIndex[1], pstBest->wIndex[2]); + VERIFY(!pstBest->bUsed); + pstBest->bUsed = TRUE; + + // And the valence. + float fValenceScore = 0.0f; +#if IGNORE_VALENCE_FOR_LOOKAHEADS + // if ( !bNoMadJumps ) +#endif + { + for (j = 0; j < 3; j++) + { + // int iValence = --(*(iValenceCounts.item(wTemp[j]))); + int iValence = --(svVertex.item(pstBest->wIndex[j])->iCurrentValence); + VERIFY(iValence >= 0); + if (iValence < c_iMaxValenceBoost) + { + fValenceScore += fValenceBoost[iValence]; + } + else + { + fValenceScore += fValenceBoost[c_iMaxValenceBoost - 1]; + } + } + } + + fScore += fValenceScore + fCurrentScore; + +#ifdef DEBUG + // Keep track of our progress. + if (iCountdown > LOOKAHEAD) + { + // Ah - we must be assembling the real list. + //. TRACE ( "Countdown %i\n", iCountdown ); + } +#endif + + // VERIFY ( fScore < 1e9 ); + + // fNewBestScore = FindBestScoreLookahead ( iCountdown - 1, fScore, 1e10, pwIndices + 3, iNumTris - 1, pwResult + 3 ); + fNewBestScore = FindBestScoreLookahead(iCountdown - 1, fScore, 1e10, iNumTris - 1, pwResult + 3); + + // VERIFY ( fNewBestScore < 1e9 ); + + CacheRemoveTri(); + VERIFY(pstBest->bUsed); + pstBest->bUsed = FALSE; + + // Restore the valencies. +#if IGNORE_VALENCE_FOR_LOOKAHEADS + // if ( !bNoMadJumps ) +#endif + { + for (j = 0; j < 3; j++) + { + //++(*(iValenceCounts.item(wTemp[j]))); + ++(svVertex.item(pstBest->wIndex[j])->iCurrentValence); + } + } + } + + return fNewBestScore; + } +} + +float FindBestScore(int iCountdown, float fCurrentScore, float fInputBestSoFar, + // WORD *pwIndices, + ScoreTri **ppstCurTris, // Pointer to a list of pointers to ScoreTris + int iNumTris, WORD *pwResult) + +{ + int iLookahead = iCountdown; + if (iLookahead > LOOKAHEAD) + { + iLookahead = LOOKAHEAD; + } + + // VERIFY ( fCurrentScore < 1e9 ); + + // At the start, limit the lookahead, or it takes ages. + if ((iNumTris > 100) && (fCurrentScore < 50.0f) && (iLookahead > 2)) + { + iLookahead = 2; + } + + float fBestSoFar = fInputBestSoFar; + + // Given the BestSoFar score, what is the average cost of each lookahead tri? + float fAverageCost = (fBestSoFar - fCurrentScore) / (int)iLookahead; + // And now allow tris that are a bit worse. + float fExpensiveCutoff = fAverageCost * fExpensiveFactor; + + VERIFY(iCountdown > 0); + VERIFY(iNumTris > 0); + + int j; + + if (iNumTris == 1) + { + // Well, that's an easy decision then. + + // Find score after removal. + // float fTriScore = CacheAddTri ( pwIndices[0], pwIndices[1], pwIndices[2], TRUE ); + ScoreTri *pstCur = ppstCurTris[0]; + float fTriScore = CacheAddTri(pstCur->wIndex[0], pstCur->wIndex[1], pstCur->wIndex[2], TRUE); + for (j = 0; j < 3; j++) + { + // Use the valence score after the tri has been removed. + // int iValence = (*(iValenceCounts.item(pwIndices[j]))) - 1; + int iValence = (svVertex.item(pstCur->wIndex[j])->iCurrentValence) - 1; + VERIFY(iValence >= 0); + if (iValence < c_iMaxValenceBoost) + { + fTriScore += fValenceBoost[iValence]; + } + else + { + fTriScore += fValenceBoost[c_iMaxValenceBoost - 1]; + } + } + + fTriScore += fCurrentScore; + + // pwResult[0] = pwIndices[0]; + // pwResult[1] = pwIndices[1]; + // pwResult[2] = pwIndices[2]; + pwResult[0] = pstCur->wIndex[0]; + pwResult[1] = pstCur->wIndex[1]; + pwResult[2] = pstCur->wIndex[2]; + + if (fTriScore > fBestSoFar) + { + // Oh well. + // (actually, not sure this ever happens). + return fInputBestSoFar; + } + else + { + return fTriScore; + } + } + +#ifdef _DEBUG + for (int k = 0; k < iNumTris; k++) + { + VERIFY(!ppstCurTris[k]->bAllowed); + VERIFY(!ppstCurTris[k]->bUsed); + } +#endif + + // Should we limit ourselves to tris that share at least one vert with the previous one? + bool bNoMadJumps = FALSE; + WORD wPrevIndices[3]; + // if ( ( fBestSoFar - fCurrentScore ) < (float)iCountdown ) + // The lookahead score is lower than the countdown, so doing mad jumps + // is not going to do sensible things. + if (iCountdown == iLookahead) + { + // Ah - this is probably a lookahead, not assembling the real list. + // Find the previous indices from the cache (a bit of a roundabout method). + int iNumAllowed = 0; + if (CacheGetLastTri(wPrevIndices)) + { + bNoMadJumps = TRUE; + // And mark all the tris that these used as "allowed" + for (int i = 0; i < 3; i++) + { + ScoreVertex *psv = svVertex.item(wPrevIndices[i]); + for (int j = 0; j < psv->stri.size(); j++) + { + ScoreTri *pst = (*(psv->stri.item(j))); + if ((!pst->bUsed) && (!pst->bAllowed)) + { + pst->bAllowed = TRUE; + iNumAllowed++; + } + } + } + if (iNumAllowed < 1) + { + // Oops - we've probably gone into a dead-end, so that very few tris + // are allowed. So open the selection up again. + bNoMadJumps = FALSE; + for (int i = 0; i < 3; i++) + { + ScoreVertex *psv = svVertex.item(wPrevIndices[i]); + for (int j = 0; j < psv->stri.size(); j++) + { + ScoreTri *pst = (*(psv->stri.item(j))); + if (!pst->bUsed) + { + pst->bAllowed = FALSE; + } + } + } + } + } + } + + // Add the tris to a new priority queue, sorting by score. + // BinaryHeap NewHeap; + BinaryHeap NewHeap; + + int i; + // WORD *pwCurIndex = pwIndices; + for (i = 0; i < iNumTris; i++) + { + ScoreTri *pstCurTri = ppstCurTris[i]; + float fTriScore = 0.0f; + if (bNoMadJumps) + { + if (!pstCurTri->bAllowed) + { + continue; + } + +#if IGNORE_VALENCE_FOR_LOOKAHEADS + // Only use the valence stuff on non-lookaheads. + // To make the scores comparable, add the maximum valence boost all the time. + fTriScore += 3.0f * fValenceBoost[c_iMaxValenceBoost - 1]; +#endif + } +#if IGNORE_VALENCE_FOR_LOOKAHEADS + else +#endif + { + // Only use the valence stuff on non-lookaheads. + for (j = 0; j < 3; j++) + { + // Use the valence score after the tri has been removed. + // int iValence = (*(iValenceCounts.item(pwCurIndex[j]))) - 1; + int iValence = (svVertex.item(pstCurTri->wIndex[j])->iCurrentValence) - 1; + VERIFY(iValence >= 0); + if (iValence < c_iMaxValenceBoost) + { + fTriScore += fValenceBoost[iValence]; + } + else + { + fTriScore += fValenceBoost[c_iMaxValenceBoost - 1]; + } + } + } + + if (fTriScore > fExpensiveCutoff) + { + // This tri is a lot more expensive than the average cost of the BestSoFar tris. + // It's very unlikely to give us a good result. + continue; + } + + if (fCurrentScore + fTriScore >= fBestSoFar) + { + // We've already gone more than the best score. + // pwCurIndex += 3; + continue; + } + + // And the vertex cost. + fTriScore += CacheAddTri(pstCurTri->wIndex[0], pstCurTri->wIndex[1], pstCurTri->wIndex[2], TRUE); + + if (fTriScore > fExpensiveCutoff) + { + // This tri is a lot more expensive than the average cost of the BestSoFar tris. + // It's very unlikely to give us a good result. + continue; + } + + if (fCurrentScore + fTriScore >= fBestSoFar) + { + // We've already gone more than the best score. + // pwCurIndex += 3; + continue; + } + + // And bung it in the heap. + // We -ve the score so that the first in the heap is the one with the _least_ score. + NewHeap.Add(&(ppstCurTris[i]), -fTriScore); + // pwCurIndex += 3; + } + + // Undo the "allowed" flags. + if (bNoMadJumps) + { + for (int i = 0; i < 3; i++) + { + ScoreVertex *psv = svVertex.item(wPrevIndices[i]); + for (int j = 0; j < psv->stri.size(); j++) + { + (*(psv->stri.item(j)))->bAllowed = FALSE; + } + } + } + +#ifdef _DEBUG + for (int k = 0; k < iNumTris; k++) + { + VERIFY(!ppstCurTris[k]->bAllowed); + VERIFY(!ppstCurTris[k]->bUsed); + } +#endif + + // Now extract from the heap, best score to worst. + // This attempts to get early-outs very quickly and prevent too much recursion. + // WORD *pwBest = NULL; + // WORD *pwCur = NewHeap.FindFirst(); + ScoreTri **ppstBest = NULL; + ScoreTri **ppstCur = NewHeap.FindFirst(); + + // if ( pwCur == NULL ) + if (ppstCur == NULL) + { + // Found nothing that was better. + return fBestSoFar; + } + + // Above this score, just don't bother. + float fCutoffScore = fCutoffFactor * NewHeap.GetCurrentSort(); + +#ifdef _DEBUG + float fPrevScore = 1.0f; +#endif + + int iTried = 0; + // while ( pwCur != NULL ) + while (ppstCur != NULL) + { + ScoreTri *pstCur = *ppstCur; + + float fThisTriNegScore = NewHeap.GetCurrentSort(); + NewHeap.RemoveFirst(); + +#ifdef _DEBUG + // Check this heap actually works! + VERIFY(fThisTriNegScore <= fPrevScore); + fPrevScore = fThisTriNegScore; +#endif + + if (fThisTriNegScore < fCutoffScore) + { + // Reached the cutoff for this tri - don't bother continuing. + break; + } + + float fScore = fCurrentScore - fThisTriNegScore; + + if (fScore >= fBestSoFar) + { + // We've already gone more than the best score. + // The reast of the heap is bound to be greater, so don't bother continuing. + break; + } + + if (bNoMadJumps) + { + iTried++; + if (iTried > iLookaheadCutoff) + { + // Tried enough tris - don't want to cause a combinatorial explosion. + break; + } + } + + // Do the valencies. +#ifdef _DEBUG + float fValenceScore = 0.0f; +#endif +#if IGNORE_VALENCE_FOR_LOOKAHEADS + if (bNoMadJumps) + { + // Only use the valence stuff on non-lookaheads. + // To make the scores comparable, add the maximum valence boost all the time. + fValenceScore = 3.0f * fValenceBoost[c_iMaxValenceBoost - 1]; + } + else +#endif + { + for (j = 0; j < 3; j++) + { + // int iValence = --(*(iValenceCounts.item(pwCur[j]))); + int iValence = --(svVertex.item(pstCur->wIndex[j])->iCurrentValence); +#ifdef _DEBUG + VERIFY(iValence >= 0); + if (iValence < c_iMaxValenceBoost) + { + fValenceScore += fValenceBoost[iValence]; + } + else + { + fValenceScore += fValenceBoost[c_iMaxValenceBoost - 1]; + } +#endif + } + } + + // Add it to the cache. + float fScoreTemp = CacheAddTri(pstCur->wIndex[0], pstCur->wIndex[1], pstCur->wIndex[2]); + + VERIFY(!pstCur->bUsed); + pstCur->bUsed = TRUE; + +#ifdef _DEBUG + fScoreTemp += fValenceScore; + VERIFY(fabs(fScoreTemp + fThisTriNegScore) < 0.0001f); +#endif + + if (iLookahead > 1) + { + // Swap pwCur to the start of the list. +#if 0 + WORD wTemp0 = pwCur[0]; + WORD wTemp1 = pwCur[1]; + WORD wTemp2 = pwCur[2]; + pwCur[0] = pwIndices[0]; + pwCur[1] = pwIndices[1]; + pwCur[2] = pwIndices[2]; + //pwIndices[0] = wTemp0; + //pwIndices[1] = wTemp1; + //pwIndices[2] = wTemp2; +#else + ScoreTri *pstTemp = *ppstCur; + *ppstCur = *ppstCurTris; + //*ppstCurTris = pstTemp; +#endif + + // VERIFY ( fScore < 1e9 ); + + // And look ahead a bit more. + // fScore = FindBestScoreLookahead ( iLookahead - 1, fScore, fBestSoFar, pwIndices + 3, iNumTris - 1, pwResult + 3 ); + float fNewScore = FindBestScoreLookahead(iLookahead - 1, fScore, fBestSoFar, iNumTris - 1, pwResult + 3); + // VERIFY ( fNewScore < 1e9 ); + fScore = fNewScore; + +#if 0 + // And swap it back. + //wTemp0 = pwIndices[0]; + //wTemp1 = pwIndices[1]; + //wTemp2 = pwIndices[2]; + pwIndices[0] = pwCur[0]; + pwIndices[1] = pwCur[1]; + pwIndices[2] = pwCur[2]; + pwCur[0] = wTemp0; + pwCur[1] = wTemp1; + pwCur[2] = wTemp2; +#else + // pstTemp = *ppstCurTris; + *ppstCurTris = *ppstCur; + *ppstCur = pstTemp; +#endif + } + // VERIFY ( fScore < 1e9 ); + if (fScore < fBestSoFar) + { + fBestSoFar = fScore; + // pwBest = pwCur; + ppstBest = ppstCur; + } + + CacheRemoveTri(); + VERIFY(pstCur->bUsed); + pstCur->bUsed = FALSE; + +#if IGNORE_VALENCE_FOR_LOOKAHEADS + if (!bNoMadJumps) +#endif + { + // Restore the valencies. + for (j = 0; j < 3; j++) + { + //++(*(iValenceCounts.item(pwCur[j]))); + ++(svVertex.item(pstCur->wIndex[j])->iCurrentValence); + } + } + + // pwCur = NewHeap.FindFirst(); + ppstCur = NewHeap.FindFirst(); + } + + VERIFY(ppstBest != NULL); + { + // Found a better solution. + + // Swap the best tri to the start of the list. + float fNewBestScore = fBestSoFar; + + // Dump the tri to the result buffer. + ScoreTri *pstBest = *ppstBest; + // pwResult[0] = pwBest[0]; + // pwResult[1] = pwBest[1]; + // pwResult[2] = pwBest[2]; + pwResult[0] = pstBest->wIndex[0]; + pwResult[1] = pstBest->wIndex[1]; + pwResult[2] = pstBest->wIndex[2]; + if (iCountdown > 1) + { +#if 0 + WORD wTemp[3]; + wTemp[0] = pwBest[0]; + wTemp[1] = pwBest[1]; + wTemp[2] = pwBest[2]; + pwBest[0] = pwIndices[0]; + pwBest[1] = pwIndices[1]; + pwBest[2] = pwIndices[2]; +#else + ScoreTri *pTemp; + pTemp = *ppstBest; + *ppstBest = *ppstCurTris; +#endif + + // float fScore = CacheAddTri ( wTemp[0], wTemp[1], wTemp[2] ); + float fScore = CacheAddTri(pstBest->wIndex[0], pstBest->wIndex[1], pstBest->wIndex[2]); + VERIFY(!pstBest->bUsed); + pstBest->bUsed = TRUE; + + // And the valence. + float fValenceScore = 0.0f; +#if IGNORE_VALENCE_FOR_LOOKAHEADS + // if ( !bNoMadJumps ) +#endif + { + for (j = 0; j < 3; j++) + { + // int iValence = --(*(iValenceCounts.item(wTemp[j]))); + int iValence = --(svVertex.item(pstBest->wIndex[j])->iCurrentValence); + VERIFY(iValence >= 0); + if (iValence < c_iMaxValenceBoost) + { + fValenceScore += fValenceBoost[iValence]; + } + else + { + fValenceScore += fValenceBoost[c_iMaxValenceBoost - 1]; + } + } + } + + fScore += fValenceScore + fCurrentScore; + +#ifdef DEBUG + //. TRACE ( "Countdown %i\n", iCountdown ); +#endif + +#if ALLOW_PROGRESS_BARS + if (g_hProgress2 != NULL) + { + // Step one. + SendMessage(g_hProgress2, PBM_STEPIT, 0, 0); + } +#endif + + // VERIFY ( fScore < 1e9 ); + + // fNewBestScore = FindBestScore ( iCountdown - 1, fScore, 1e10, pwIndices + 3, iNumTris - 1, pwResult + 3 ); + fNewBestScore = FindBestScore(iCountdown - 1, fScore, 1e10, ppstCurTris + 1, iNumTris - 1, pwResult + 3); + + // VERIFY ( fNewBestScore < 1e9 ); + + CacheRemoveTri(); + VERIFY(pstBest->bUsed); + pstBest->bUsed = FALSE; + + // Restore the valencies. +#if IGNORE_VALENCE_FOR_LOOKAHEADS + // if ( !bNoMadJumps ) +#endif + { + for (j = 0; j < 3; j++) + { + //++(*(iValenceCounts.item(wTemp[j]))); + ++(svVertex.item(pstBest->wIndex[j])->iCurrentValence); + } + } + + // And swap it back. +#if 0 + pwIndices[0] = pwBest[0]; + pwIndices[1] = pwBest[1]; + pwIndices[2] = pwBest[2]; + pwBest[0] = wTemp[0]; + pwBest[1] = wTemp[1]; + pwBest[2] = wTemp[2]; +#else + *ppstCurTris = *ppstBest; + *ppstBest = pTemp; +#endif + } + + return fNewBestScore; + } +} + +// Call this to reorder the tris in this trilist to get good vertex-cache coherency. +// *pwList is modified (but obviously not changed in size or memory location). +void _OptimiseVertexCoherencyTriList(WORD *pwList, int iHowManyTris, u32 optimize_mode) +{ + if (iHowManyTris <= 2) + { + // Silly. + return; + } + + switch (optimize_mode) + { + case 1: + // Very cheap'n'cheerful. + LOOKAHEAD = 1; + iLookaheadCutoff = 4; + break; + case 2: + // Expensive, but better. + LOOKAHEAD = 5; + iLookaheadCutoff = 16; + break; + } + +#ifdef _DEBUG + // Find current score (probably rubbish). + float fCurrentScore = GetNumVerticesLoadedTriList(pwList, iHowManyTris); +#endif + + // First scan to find the biggest index. + WORD *pwIndex = pwList; + int iBiggestIndex = 0; + int i; + for (i = 0; i < iHowManyTris * 3; i++) + { + if (iBiggestIndex < *pwIndex) + { + iBiggestIndex = *pwIndex; + } + pwIndex++; + } + +#if 0 + iValenceCounts.resize(iBiggestIndex+1); + for ( i = 0; i <= iBiggestIndex; i++ ) + { + *(iValenceCounts.item(i)) = 0; + } + + + // And set up the valencies. + pwIndex = pwList; + for ( i = 0; i < iHowManyTris * 3; i++ ) + { + ++(*(iValenceCounts.item(*pwIndex))); + pwIndex++; + } +#else + + svVertex.resize(iBiggestIndex + 1); + for (i = 0; i <= iBiggestIndex; i++) + { + ScoreVertex *sv = svVertex.item(i); + sv->iCurrentValence = 0; + sv->stri.resize(0); + } + + stTri.resize(iHowManyTris); + pstTri.resize(iHowManyTris); + WORD *pwCurTri = pwList; + for (i = 0; i < iHowManyTris; i++) + { + ScoreTri *pstCur = stTri.item(i); + *(pstTri.item(i)) = pstCur; + pstCur->bUsed = FALSE; + pstCur->bAllowed = FALSE; + for (int j = 0; j < 3; j++) + { + pstCur->wIndex[j] = pwCurTri[j]; + svVertex.item(pwCurTri[j])->iCurrentValence++; + *(svVertex.item(pwCurTri[j])->stri.append()) = pstCur; + } + pwCurTri += 3; + } + +#endif + + WORD *pwNewIndex = new WORD[iHowManyTris * 3]; + + CacheInit(iBiggestIndex + 1); + +#if 0 + // If you try to optimise from the very first tri, it takes ages to find the "best" + // first tri - almost none of the early-outs work, because there is no cache history, + // and indeed the whole concept of a "best" first tri is madness - you have to start + // somewhere. + // So I just pick the first one, and let it carry on from there. Once the cache has + // been "seeded" the early-outs come thick and fast and it's a decent speed. + pwNewIndex[0] = pwList[0]; + pwNewIndex[1] = pwList[1]; + pwNewIndex[2] = pwList[2]; + --(*(iValenceCounts.item(pwList[0]))); + --(*(iValenceCounts.item(pwList[1]))); + --(*(iValenceCounts.item(pwList[2]))); + CacheAddTri ( pwList[0], pwList[1], pwList[2] ); + // No need to actually increase the score - everything is relative anyway. + + float fTemp = FindBestScore ( iHowManyTris - 1, + 0.0f, + 1e10, + pwList + 3, + iHowManyTris - 1, + pwNewIndex + 3 ); +#else + float fTemp = FindBestScore(iHowManyTris, + 0.0f, + 1e10, + (pstTri.item(0)), + iHowManyTris, + pwNewIndex); +#endif + + CacheBin(); + +#if 0 + iValenceCounts.resize(0); +#else + svVertex.resize(0); + stTri.resize(0); +#endif + +#ifdef _DEBUG + // Find new score (hopefully better). + float fNewScore = GetNumVerticesLoadedTriList(pwNewIndex, iHowManyTris); + fNewScore /= (float)iHowManyTris; // The verts per tri score. + // And if you definately use indices 0 to iBiggestIndex (which all this code does), then this is the max possible: + float fMaxPossible = iBiggestIndex / (float)iHowManyTris; +#endif + + memcpy(pwList, pwNewIndex, sizeof(WORD) * 3 * iHowManyTris); + + delete[] pwNewIndex; +} diff --git a/src/utils/ETools/platform.cpp b/src/utils/ETools/platform.cpp new file mode 100644 index 00000000000..41b81043a12 --- /dev/null +++ b/src/utils/ETools/platform.cpp @@ -0,0 +1,186 @@ +/* OggEnc + ** + ** This program is distributed under the GNU General Public License, version 2. + ** A copy of this license is included with this source. + ** + ** Copyright 2000, Michael Smith + ** + ** Portions from Vorbize, (c) Kenneth Arnold + ** and libvorbis examples, (c) Monty + **/ + +/* Platform support routines - win32, OS/2, unix */ +#include "stdafx.h" + +#include "platform.h" +#include "encode.h" +//#include "i18n.h" +#include +#include +#if defined(_WIN32) || defined(__EMX__) || defined(__WATCOMC__) +#include +#include +#include +#endif + +#pragma warning(disable : 4995) + +#define _(a) a + +#if defined(_WIN32) && defined(_MSC_VER) + +void setbinmode(FILE *f) +{ + _setmode(_fileno(f), _O_BINARY); +} +#endif /* win32 */ + +#ifdef __EMX__ +void setbinmode(FILE *f) +{ + _fsetmode(f, "b"); +} +#endif + +#if defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__) +void setbinmode(FILE *f) +{ + setmode(fileno(f), O_BINARY); +} +#endif + +#if defined(_WIN32) || defined(__EMX__) || defined(__WATCOMC__) +void *timer_start(void) +{ + time_t *start = (time_t *)malloc(sizeof(time_t)); + time(start); + return (void *)start; +} + +double timer_time(void *timer) +{ + time_t now = time(NULL); + time_t start = *((time_t *)timer); + + if (now - start) + return (double)(now - start); + else + return 1; /* To avoid division by zero later, for very short inputs */ +} + +void timer_clear(void *timer) +{ + free((time_t *)timer); +} + +#else /* unix. Or at least win32 */ + +#include +#include + +void *timer_start(void) +{ + struct timeval *start = malloc(sizeof(struct timeval)); + gettimeofday(start, NULL); + return (void *)start; +} + +double timer_time(void *timer) +{ + struct timeval now; + struct timeval start = *((struct timeval *)timer); + + gettimeofday(&now, NULL); + + return (double)now.tv_sec - (double)start.tv_sec + + ((double)now.tv_usec - (double)start.tv_usec) / 1000000.0; +} + +void timer_clear(void *timer) +{ + free((time_t *)timer); +} + +#endif + +#include +#include +#include + +#ifdef _WIN32 + +#include + +#define PATH_SEPS "/\\" +#define mkdir(x, y) _mkdir((x)) + +/* MSVC does this, borland doesn't? */ +#ifndef __BORLANDC__ +#define stat _stat +#endif + +#else + +#define PATH_SEPS "/" + +#endif + +int create_directories(char *fn) +{ + char *end, *start; + struct stat statbuf; + char *segment = (char *)malloc(strlen(fn) + 1); + + start = fn; +#ifdef _WIN32 + if (strlen(fn) >= 3 && isalpha(fn[0]) && fn[1] == ':') + start = start + 2; +#endif + + while ((end = strpbrk(start + 1, PATH_SEPS)) != NULL) + { + memcpy(segment, fn, end - fn); + segment[end - fn] = 0; + + if (stat(segment, &statbuf)) + { + if (errno == ENOENT) + { + if (mkdir(segment, 0777)) + { + fprintf(stderr, _("Couldn't create directory \"%s\": %s\n"), + segment, strerror(errno)); + free(segment); + return -1; + } + } + else + { + fprintf(stderr, _("Error checking for existence of directory %s: %s\n"), + segment, strerror(errno)); + free(segment); + return -1; + } + } +#if defined(_WIN32) && !defined(__BORLANDC__) + else if (!(_S_IFDIR & statbuf.st_mode)) + { +#elif defined(__BORLANDC__) + else if (!(S_IFDIR & statbuf.st_mode)) + { +#else + else if (!S_ISDIR(statbuf.st_mode)) + { +#endif + fprintf(stderr, _("Error: path segment \"%s\" is not a directory\n"), + segment); + free(segment); + return -1; + } + + start = end + 1; + } + + free(segment); + return 0; +} diff --git a/src/utils/ETools/platform.h b/src/utils/ETools/platform.h new file mode 100644 index 00000000000..d1488a84806 --- /dev/null +++ b/src/utils/ETools/platform.h @@ -0,0 +1,36 @@ +#ifndef __PLATFORM_H +#define __PLATFORM_H + +#include + +#ifdef HAVE_ALLOCA_H +#include +#endif + +#ifdef __OS2__ +#define INCL_DOS +#define INCL_NOPMAPI +#include +#endif + +#if defined(_WIN32) || defined(__OS2__) +#pragma warning(push) +#pragma warning(disable : 4995) +#pragma warning(pop) + +void setbinmode(FILE *); + +#define DEFAULT_NAMEFMT_REMOVE "/\\:<>|" +#define DEFAULT_NAMEFMT_REPLACE NULL + +#else /* Unix, mostly */ + +#define setbinmode(x) \ + { \ + } +#define DEFAULT_NAMEFMT_REMOVE "/" +#define DEFAULT_NAMEFMT_REPLACE NULL + +#endif + +#endif /* __PLATFORM_H */ diff --git a/src/utils/ETools/resample.cpp b/src/utils/ETools/resample.cpp new file mode 100644 index 00000000000..84d1a864cfc --- /dev/null +++ b/src/utils/ETools/resample.cpp @@ -0,0 +1,432 @@ +/* resample.c: see resample.h for interesting stuff */ + +#include "stdafx.h" + +#include +#include +#include + +#include "resample.h" + +#pragma warning(disable : 4995) +#pragma warning(disable : 4244) +#pragma warning(disable : 4130) +#pragma warning(disable : 4018) +#pragma warning(disable : 4267) + +/* Some systems don't define this */ +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +static int hcf(int arg1, int arg2) +{ + int mult = 1; + + while (~(arg1 | arg2) & 1) + arg1 >>= 1, arg2 >>= 1, mult <<= 1; + + while (arg1 > 0) + { + if (~(arg1 & arg2) & 1) + { + arg1 >>= (~arg1 & 1); + arg2 >>= (~arg2 & 1); + } + else if (arg1 < arg2) + arg2 = (arg2 - arg1) >> 1; + else + arg1 = (arg1 - arg2) >> 1; + } + + return arg2 * mult; +} + +static void filt_sinc(float *dest, int N, int step, double fc, double gain, int width) +{ + double s = fc / step; + int mid, x; + float *endpoint = dest + N, + *base = dest, + *origdest = dest; + + assert(width <= N); + + if ((N & 1) == 0) + { + *dest = 0.0; + dest += width; + if (dest >= endpoint) + dest = ++base; + N--; + } + + mid = N / 2; + x = -mid; + + while (N--) + { + *dest = (x ? sin(x * M_PI * s) / (x * M_PI) * step : fc) * gain; + x++; + dest += width; + if (dest >= endpoint) + dest = ++base; + } + assert(dest == origdest + width); +} + +static double I_zero(double x) +{ + int n = 0; + double u = 1.0, + s = 1.0, + t; + + do + { + n += 2; + t = x / n; + u *= t * t; + s += u; + } while (u > 1e-21 * s); + + return s; +} + +static void win_kaiser(float *dest, int N, double alpha, int width) +{ + double I_alpha, midsq; + int x; + float *endpoint = dest + N, + *base = dest, + *origdest = dest; + + assert(width <= N); + + if ((N & 1) == 0) + { + *dest = 0.0; + dest += width; + if (dest >= endpoint) + dest = ++base; + N--; + } + + x = -(N / 2); + midsq = (double)(x - 1) * (double)(x - 1); + I_alpha = I_zero(alpha); + + while (N--) + { + *dest *= I_zero(alpha * sqrt(1.0 - ((double)x * (double)x) / midsq)) / I_alpha; + x++; + dest += width; + if (dest >= endpoint) + dest = ++base; + } + assert(dest == origdest + width); +} + +int res_init(res_state *state, int channels, int outfreq, int infreq, res_parameter op1, ...) +{ + double beta = 16.0, + cutoff = 0.80, + gain = 1.0; + int taps = 45; + + int factor; + + assert(state); + assert(channels > 0); + assert(outfreq > 0); + assert(infreq > 0); + assert(taps > 0); + + if (state == NULL || channels <= 0 || outfreq <= 0 || infreq <= 0 || taps <= 0) + return -1; + + if (op1 != RES_END) + { + va_list argp; + va_start(argp, op1); + do + { + switch (op1) + { + case RES_GAIN: + gain = va_arg(argp, double); + break; + + case RES_CUTOFF: + cutoff = va_arg(argp, double); + assert(cutoff > 0.01 && cutoff <= 1.0); + break; + + case RES_TAPS: + taps = va_arg(argp, int); + assert(taps > 2 && taps < 1000); + break; + + case RES_BETA: + beta = va_arg(argp, double); + assert(beta > 2.0); + break; + default: + assert("arglist" == "valid"); + return -1; + } + op1 = va_arg(argp, res_parameter); + } while (op1 != RES_END); + va_end(argp); + } + + factor = hcf(infreq, outfreq); + outfreq /= factor; + infreq /= factor; + + /* adjust to rational values for downsampling */ + if (outfreq < infreq) + { + /* push the cutoff frequency down to the output frequency */ + cutoff = cutoff * outfreq / infreq; + + /* compensate for the sharper roll-off requirement + * by using a bigger hammer */ + taps = taps * infreq / outfreq; + } + + assert(taps >= (infreq + outfreq - 1) / outfreq); + + if ((state->table = (float *)calloc(outfreq * taps, sizeof(float))) == NULL) + return -1; + if ((state->pool = (SAMPLE *)calloc(channels * taps, sizeof(SAMPLE))) == NULL) + { + free(state->table); + state->table = NULL; + return -1; + } + + state->poolfill = taps / 2 + 1; + state->channels = channels; + state->outfreq = outfreq; + state->infreq = infreq; + state->taps = taps; + state->offset = 0; + + filt_sinc(state->table, outfreq * taps, outfreq, cutoff, gain, taps); + win_kaiser(state->table, outfreq * taps, beta, taps); + + return 0; +} + +static SAMPLE sum(float const *scale, int count, SAMPLE const *source, SAMPLE const *trigger, SAMPLE const *reset, int srcstep) +{ + float total = 0.0; + + while (count--) + { + total += *source * *scale; + + if (source == trigger) + source = reset, srcstep = 1; + source -= srcstep; + scale++; + } + + return total; +} + +static int push(res_state const *const state, SAMPLE *pool, int *const poolfill, int *const offset, SAMPLE *dest, int dststep, SAMPLE const *source, int srcstep, size_t srclen) +{ + SAMPLE *const destbase = dest, + *poolhead = pool + *poolfill, + *poolend = pool + state->taps, + *newpool = pool; + SAMPLE const *refill, *base, *endpoint; + int lencheck; + + assert(state); + assert(pool); + assert(poolfill); + assert(dest); + assert(source); + + assert(state->poolfill != -1); + + lencheck = res_push_check(state, srclen); + + /* fill the pool before diving in */ + while (poolhead < poolend && srclen > 0) + { + *poolhead++ = *source; + source += srcstep; + srclen--; + } + + if (srclen <= 0) + return 0; + + base = source; + endpoint = source + srclen * srcstep; + + while (source < endpoint) + { + *dest = sum(state->table + *offset * state->taps, state->taps, source, base, poolend, srcstep); + dest += dststep; + *offset += state->infreq; + while (*offset >= state->outfreq) + { + *offset -= state->outfreq; + source += srcstep; + } + } + + assert(dest == destbase + lencheck * dststep); + + /* pretend that source has that underrun data we're not going to get */ + srclen += (source - endpoint) / srcstep; + + /* if we didn't get enough to completely replace the pool, then shift things about a bit */ + if (srclen < state->taps) + { + refill = pool + srclen; + while (refill < poolend) + *newpool++ = *refill++; + + refill = source - srclen * srcstep; + } + else + refill = source - state->taps * srcstep; + + /* pull in fresh pool data */ + while (refill < endpoint) + { + *newpool++ = *refill; + refill += srcstep; + } + + assert(newpool > pool); + assert(newpool <= poolend); + + *poolfill = newpool - pool; + + return (dest - destbase) / dststep; +} + +int res_push_max_input(res_state const *const state, size_t maxoutput) +{ + return maxoutput * state->infreq / state->outfreq; +} + +int res_push_check(res_state const *const state, size_t srclen) +{ + if (state->poolfill < state->taps) + srclen -= state->taps - state->poolfill; + + return (srclen * state->outfreq - state->offset + state->infreq - 1) / state->infreq; +} + +int res_push(res_state *state, SAMPLE **dstlist, SAMPLE const **srclist, size_t srclen) +{ + int result = -1, poolfill = -1, offset = -1, i; + + assert(state); + assert(dstlist); + assert(srclist); + assert(state->poolfill >= 0); + + for (i = 0; i < state->channels; i++) + { + poolfill = state->poolfill; + offset = state->offset; + result = push(state, state->pool + i * state->taps, &poolfill, &offset, dstlist[i], 1, srclist[i], 1, srclen); + } + state->poolfill = poolfill; + state->offset = offset; + + return result; +} + +int res_push_interleaved(res_state *state, SAMPLE *dest, SAMPLE const *source, size_t srclen) +{ + int result = -1, poolfill = -1, offset = -1, i; + + assert(state); + assert(dest); + assert(source); + assert(state->poolfill >= 0); + + for (i = 0; i < state->channels; i++) + { + poolfill = state->poolfill; + offset = state->offset; + result = push(state, state->pool + i * state->taps, &poolfill, &offset, dest + i, state->channels, source + i, state->channels, srclen); + } + state->poolfill = poolfill; + state->offset = offset; + + return result; +} + +int res_drain(res_state *state, SAMPLE **dstlist) +{ + SAMPLE *tail; + int result = -1, poolfill = -1, offset = -1, i; + + assert(state); + assert(dstlist); + assert(state->poolfill >= 0); + + if ((tail = (SAMPLE *)calloc(state->taps, sizeof(SAMPLE))) == NULL) + return -1; + + for (i = 0; i < state->channels; i++) + { + poolfill = state->poolfill; + offset = state->offset; + result = push(state, state->pool + i * state->taps, &poolfill, &offset, dstlist[i], 1, tail, 1, state->taps / 2 - 1); + } + + free(tail); + + state->poolfill = -1; + + return result; +} + +int res_drain_interleaved(res_state *state, SAMPLE *dest) +{ + SAMPLE *tail; + int result = -1, poolfill = -1, offset = -1, i; + + assert(state); + assert(dest); + assert(state->poolfill >= 0); + + if ((tail = (SAMPLE *)calloc(state->taps, sizeof(SAMPLE))) == NULL) + return -1; + + for (i = 0; i < state->channels; i++) + { + poolfill = state->poolfill; + offset = state->offset; + result = push(state, state->pool + i * state->taps, &poolfill, &offset, dest + i, state->channels, tail, 1, state->taps / 2 - 1); + } + + free(tail); + + state->poolfill = -1; + + return result; +} + +void res_clear(res_state *state) +{ + assert(state); + assert(state->table); + assert(state->pool); + + free(state->table); + free(state->pool); + memset(state, 0, sizeof(*state)); +} diff --git a/src/utils/ETools/resample.h b/src/utils/ETools/resample.h new file mode 100644 index 00000000000..b247b968807 --- /dev/null +++ b/src/utils/ETools/resample.h @@ -0,0 +1,101 @@ +/* This program is licensed under the GNU Library General Public License, + * version 2, a copy of which is included with this program (LICENCE.LGPL). + * + * (c) 2002 Simon Hosie + * + * + * A resampler + * + * reference: + * 'Digital Filters', third edition, by R. W. Hamming ISBN 0-486-65088-X + * + * history: + * 2002-05-31 ready for the world (or some small section thereof) + * + * + * TOOD: + * zero-crossing clipping in coefficient table + */ + +#ifndef _RESAMPLE_H_INCLUDED +#define _RESAMPLE_H_INCLUDED + +typedef float SAMPLE; + +typedef struct +{ + unsigned int channels, infreq, outfreq, taps; + float *table; + SAMPLE *pool; + + /* dynamic bits */ + int poolfill; + int offset; +} res_state; + +typedef enum +{ + RES_END, + RES_GAIN, /* (double)1.0 */ + RES_CUTOFF, /* (double)0.80 */ + RES_TAPS, /* (int)45 */ + RES_BETA /* (double)16.0 */ +} res_parameter; + +int res_init(res_state *state, int channels, int outfreq, int infreq, res_parameter op1, ...); +/* + * Configure *state to manage a data stream with the specified parameters. The + * string 'params' is currently unspecified, but will configure the parameters + * of the filter. + * + * This function allocates memory, and requires that res_clear() be called when + * the buffer is no longer needed. + * + * + * All counts/lengths used in the following functions consider only the data in + * a single channel, and in numbers of samples rather than bytes, even though + * functionality will be mirrored across as many channels as specified here. + */ + +int res_push_max_input(res_state const *state, size_t maxoutput); +/* + * Returns the maximum number of input elements that may be provided without + * risk of flooding an output buffer of size maxoutput. maxoutput is + * specified in counts of elements, NOT in bytes. + */ + +int res_push_check(res_state const *state, size_t srclen); +/* + * Returns the number of elements that will be returned if the given srclen + * is used in the next call to res_push(). + */ + +int res_push(res_state *state, SAMPLE **dstlist, SAMPLE const **srclist, size_t srclen); +int res_push_interleaved(res_state *state, SAMPLE *dest, SAMPLE const *source, size_t srclen); +/* + * Pushes srclen samples into the front end of the filter, and returns the + * number of resulting samples. + * + * res_push(): srclist and dstlist point to lists of pointers, each of which + * indicates the beginning of a list of samples. + * + * res_push_interleaved(): source and dest point to the beginning of a list of + * interleaved samples. + */ + +int res_drain(res_state *state, SAMPLE **dstlist); +int res_drain_interleaved(res_state *state, SAMPLE *dest); +/* + * Recover the remaining elements by flushing the internal pool with 0 values, + * and storing the resulting samples. + * + * After either of these functions are called, *state should only re-used in a + * final call to res_clear(). + */ + +void res_clear(res_state *state); +/* + * Free allocated buffers, etc. + */ + +#endif diff --git a/src/utils/ETools/xrXRC.cpp b/src/utils/ETools/xrXRC.cpp new file mode 100644 index 00000000000..7ecf9970201 --- /dev/null +++ b/src/utils/ETools/xrXRC.cpp @@ -0,0 +1,14 @@ +// xrXRC.cpp: implementation of the xrXRC class. +// +////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#pragma hdrstop + +#include "xrXRC.h" + +ENGINE_API xrXRC XRC; + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// diff --git a/src/utils/ETools/xrXRC.h b/src/utils/ETools/xrXRC.h new file mode 100644 index 00000000000..eee7ef438b1 --- /dev/null +++ b/src/utils/ETools/xrXRC.h @@ -0,0 +1,83 @@ +#pragma once +#include "xrCore/_fbox.h" +#include "xrCDB/xrCDB.h" + +class ENGINE_API xrXRC +{ + CDB::COLLIDER CL; + u32 m_RayMode; + u32 m_BoxMode; + u32 m_FrustumMode; + +public: + IC CDB::COLLIDER *collider() { return &CL; } + IC void ray_options(DWORD f) + { + m_RayMode = f; + } + IC void ray_query(const CDB::MODEL *m_def, const Fvector &r_start, const Fvector &r_dir, float r_range) + { +#ifndef NO_XRC_STATS + Device.Statistic->clRAY.Begin(); +#endif + CL.ray_query(m_RayMode, m_def, r_start, r_dir, r_range); +#ifndef NO_XRC_STATS + Device.Statistic->clRAY.End(); +#endif + } + IC void ray_query(const Fmatrix &inv_parent, const CDB::MODEL *m_def, const Fvector &r_start, const Fvector &r_dir, float r_range) + { + // transform + Fvector S, D; + inv_parent.transform_tiny(S, r_start); + inv_parent.transform_dir(D, r_dir); + ray_query(m_def, S, D, r_range); + } + + IC void box_options(DWORD f) + { + m_BoxMode = f; + } + IC void box_query(const CDB::MODEL *m_def, const Fvector &b_center, const Fvector &b_dim) + { +#ifndef NO_XRC_STATS + Device.Statistic->clBOX.Begin(); +#endif + CL.box_query(m_BoxMode, m_def, b_center, b_dim); +#ifndef NO_XRC_STATS + Device.Statistic->clBOX.End(); +#endif + } + IC void box_query(const Fmatrix &inv_parent, const CDB::MODEL *m_def, const Fbox &src) + { + Fbox dest; + dest.xform(src, inv_parent); + Fvector c, d; + dest.getcenter(c); + dest.getradius(d); + box_query(m_def, c, d); + } + + IC void frustum_options(DWORD f) + { + m_FrustumMode=f; + } + IC void frustum_query(const CDB::MODEL *m_def, const CFrustum &F) + { +#ifndef NO_XRC_STATS + Device.Statistic->clFRUSTUM.Begin(); +#endif + CL.frustum_query(m_FrustumMode, m_def, F); +#ifndef NO_XRC_STATS + Device.Statistic->clFRUSTUM.End(); +#endif + } + + IC CDB::RESULT *r_begin() { return CL.r_begin(); }; + IC CDB::RESULT *r_end() { return CL.r_end(); }; + IC void r_free() { CL.r_free(); } + IC int r_count() { return CL.r_count(); }; + IC void r_clear() { CL.r_clear(); }; +}; + +ENGINE_API extern xrXRC XRC; diff --git a/src/utils/xrAI/factory_api.h b/src/utils/xrAI/factory_api.h index f866058ebea..0eb8526e6cf 100644 --- a/src/utils/xrAI/factory_api.h +++ b/src/utils/xrAI/factory_api.h @@ -1,18 +1,11 @@ #pragma once #include "xrServerEntities/xrServer_Object_Base.h" +#include "utils/xrSE_Factory/xrSE_Factory_import_export.h" -extern "C" { -using CreateEntity = XR_IMPORT IServerEntity*(LPCSTR section); -using DestroyEntity = XR_IMPORT void(IServerEntity*&); -}; - -extern CreateEntity* create_entity; -extern DestroyEntity* destroy_entity; - -IC CSE_Abstract* F_entity_Create(LPCSTR section) -{ - IServerEntity* i = create_entity(section); +IC CSE_Abstract* F_entity_Create(LPCSTR section) +{ + IServerEntity* i = xrSE_Factory::create_entity(section); CSE_Abstract* j = smart_cast(i); return (j); } @@ -20,6 +13,6 @@ IC CSE_Abstract* F_entity_Create(LPCSTR section) IC void F_entity_Destroy(CSE_Abstract*& i) { IServerEntity* j = i; - destroy_entity(j); + xrSE_Factory::destroy_entity(j); i = 0; } diff --git a/src/utils/xrAI/xrAI.cpp b/src/utils/xrAI/xrAI.cpp index 36a9888d42d..bbc77747965 100644 --- a/src/utils/xrAI/xrAI.cpp +++ b/src/utils/xrAI/xrAI.cpp @@ -12,10 +12,6 @@ #include "xrCore/ModuleLookup.hpp" #include "factory_api.h" - -CreateEntity* create_entity = nullptr; -DestroyEntity* destroy_entity = nullptr; - extern void xrCompiler(LPCSTR name, bool draft_mode, bool pure_covers, LPCSTR out_name); extern void verify_level_graph(LPCSTR name, bool verbose); @@ -102,27 +98,9 @@ void execute(pstr cmd) char* no_separator_check = strstr(cmd, "-no_separator_check"); clear_temp_folder(); - const auto hFactory = XRay::LoadModule("xrSE_Factory"); - - R_ASSERT2(hFactory->IsLoaded(), "Factory DLL raised exception during loading or there is no factory DLL at all"); - -#if defined(XR_ARCHITECTURE_X64) || defined(XR_ARCHITECTURE_E2K) - pcstr create_entity_name = "create_entity"; - pcstr destroy_entity_name = "destroy_entity"; -#else - pcstr create_entity_name = "_create_entity@4"; - pcstr destroy_entity_name = "_destroy_entity@4"; -#endif - create_entity = static_cast(hFactory->GetProcAddress(create_entity_name)); - destroy_entity = static_cast(hFactory->GetProcAddress(destroy_entity_name)); - - R_ASSERT(create_entity); - R_ASSERT(destroy_entity); - + xrSE_Factory::initialize(); CGameSpawnConstructor(name, output, start, !!no_separator_check); - - create_entity = nullptr; - destroy_entity = nullptr; + xrSE_Factory::destroy(); } else if (strstr(cmd, "-verify")) { diff --git a/src/utils/xrAI/xrAI.vcxproj b/src/utils/xrAI/xrAI.vcxproj index 9424d043bdd..5d0fdd96b52 100644 --- a/src/utils/xrAI/xrAI.vcxproj +++ b/src/utils/xrAI/xrAI.vcxproj @@ -109,6 +109,9 @@ {2578c6d8-660d-48ae-9322-7422f8664f06} + + {3ad26fd3-4f52-4e22-a4cf-ad4c49e74c61} + diff --git a/src/utils/xrSE_Factory/xrSE_Factory.cpp b/src/utils/xrSE_Factory/xrSE_Factory.cpp index 8bad3dd08d1..8652cc5505e 100644 --- a/src/utils/xrSE_Factory/xrSE_Factory.cpp +++ b/src/utils/xrSE_Factory/xrSE_Factory.cpp @@ -22,53 +22,44 @@ extern CSE_Abstract* F_entity_Create(LPCSTR section, bool no_assert); extern CScriptPropertiesListHelper* g_property_list_helper; extern XRay::Module prop_helper_module; -extern "C" { -FACTORY_API IServerEntity* create_entity(LPCSTR section) { return F_entity_Create(section, true); } -FACTORY_API void destroy_entity(IServerEntity*& abstract) +namespace xrSE_Factory +{ +IServerEntity* create_entity(LPCSTR section) { return F_entity_Create(section, true); } + +void destroy_entity(IServerEntity*& abstract) { auto object = smart_cast(abstract); F_entity_Destroy(object); abstract = 0; } -}; -BOOL APIENTRY DllMain(HANDLE module_handle, DWORD call_reason, LPVOID reserved) +void initialize() { - switch (call_reason) - { - case DLL_PROCESS_ATTACH: - { - //xrDebug::Initialize(); - //Core.Initialize("xrSE_Factory", nullptr, true, "fsfactory.ltx"); - string_path SYSTEM_LTX; - FS.update_path(SYSTEM_LTX, "$game_config$", "system.ltx"); - pSettings = xr_new(SYSTEM_LTX); + string_path SYSTEM_LTX; + FS.update_path(SYSTEM_LTX, "$game_config$", "system.ltx"); + pSettings = xr_new(SYSTEM_LTX); - CCharacterInfo::InitInternal(); - CSpecificCharacter::InitInternal(); + CCharacterInfo::InitInternal(); + CSpecificCharacter::InitInternal(); +} - break; - } - case DLL_PROCESS_DETACH: - { - CCharacterInfo::DeleteSharedData(); - CCharacterInfo::DeleteIdToIndexData(); - CSpecificCharacter::DeleteSharedData(); - CSpecificCharacter::DeleteIdToIndexData(); +void destroy() +{ + CCharacterInfo::DeleteSharedData(); + CCharacterInfo::DeleteIdToIndexData(); + CSpecificCharacter::DeleteSharedData(); + CSpecificCharacter::DeleteIdToIndexData(); - auto s = (CInifile**)&pSettings; - xr_delete(*s); - xr_delete(g_property_list_helper); - xr_delete(g_ai_space); - xr_delete(g_object_factory); - prop_helper_module = nullptr; - //Core._destroy(); - break; - } - } - return (TRUE); + auto s = (CInifile**)&pSettings; + xr_delete(*s); + xr_delete(g_property_list_helper); + xr_delete(g_ai_space); + xr_delete(g_object_factory); + prop_helper_module = nullptr; } +}; // xrSE_Factory + void _destroy_item_data_vector_cont(T_VECTOR* vec) { auto it = vec->begin(); diff --git a/src/utils/xrSE_Factory/xrSE_Factory_import_export.h b/src/utils/xrSE_Factory/xrSE_Factory_import_export.h index 470daa11459..53b3e0eeaf3 100644 --- a/src/utils/xrSE_Factory/xrSE_Factory_import_export.h +++ b/src/utils/xrSE_Factory/xrSE_Factory_import_export.h @@ -1,6 +1,4 @@ -#ifndef XRSE_FACTORY_IMPORT_EXPORTH -#define XRSE_FACTORY_IMPORT_EXPORTH - +#pragma once #include "Common/Common.hpp" #ifdef XRAY_STATIC_BUILD @@ -13,9 +11,11 @@ # endif #endif -extern "C" { +namespace xrSE_Factory +{ FACTORY_API IServerEntity* create_entity(LPCSTR section); FACTORY_API void destroy_entity(IServerEntity*&); -}; +FACTORY_API void initialize(); +FACTORY_API void destroy(); +} // namespace XrSE_Factory -#endif diff --git a/src/xrCDB/xrCDB.h b/src/xrCDB/xrCDB.h index 432dbe622a5..29f67fa963e 100644 --- a/src/xrCDB/xrCDB.h +++ b/src/xrCDB/xrCDB.h @@ -157,7 +157,7 @@ class XRCDB_API COLLIDER void frustum_query(u32 frustum_mode, const MODEL* m_def, const CFrustum& F); ICF RESULT* r_begin() { return &*rd.begin(); }; - //ICF RESULT* r_end() { return &*rd.end(); }; + ICF RESULT* r_end() { return &*rd.end(); }; ICF xr_vector* r_get() { return &rd; }; RESULT& r_add(); void r_free(); diff --git a/src/xrCore/Animation/Bone.hpp b/src/xrCore/Animation/Bone.hpp index ec0c6dc472d..37fc422c290 100644 --- a/src/xrCore/Animation/Bone.hpp +++ b/src/xrCore/Animation/Bone.hpp @@ -278,11 +278,13 @@ class XRCORE_API IBoneData // refs class CBone; using BoneVec = xr_vector; +using BoneIt = BoneVec::iterator; class XRCORE_API CBone final : public CBoneInstance, public IBoneData { public: friend class LWBoneParser; + friend bool BoneExportOGF(CBone* bone, IWriter& F); private: shared_str name; @@ -405,8 +407,6 @@ class XRCORE_API CBone final : public CBoneInstance, public IBoneData [[nodiscard]] bool Selected() const { return flags.is(flSelected); } void ClampByLimits(); - bool ExportOGF(IWriter& F); // XXX: implementation is missing. Probably it is in the SDK code? - private: [[nodiscard]] IBoneData& GetChild(u16 id) override { return *children[id]; } [[nodiscard]] const IBoneData& GetChild(u16 id) const override { return *children[id]; } diff --git a/src/xrCore/ChooseTypes.H b/src/xrCore/ChooseTypes.H index 5ac6522c94a..df4dcb2c1ef 100644 --- a/src/xrCore/ChooseTypes.H +++ b/src/xrCore/ChooseTypes.H @@ -42,17 +42,20 @@ enum EChooseFlags struct SChooseItem { + SChooseItem() = default; shared_str name; shared_str hint; SChooseItem(LPCSTR nm, LPCSTR ht) : name(nm), hint(ht) {} }; -using ChooseItemVec = xr_vector; - +DEFINE_VECTOR(SChooseItem, ChooseItemVec, ChooseItemVecIt); +#ifndef ImTextureID +using ImTextureID = void *; +#endif // typedef -typedef fastdelegate::FastDelegate2 TOnChooseFillItems; -typedef fastdelegate::FastDelegate2 TOnChooseSelectItem; -typedef fastdelegate::FastDelegate3 TOnDrawThumbnail; +typedef fastdelegate::FastDelegate2 TOnChooseFillItems; +typedef fastdelegate::FastDelegate2 TOnChooseSelectItem; +typedef fastdelegate::FastDelegate2 TGetTexture; typedef fastdelegate::FastDelegate0<> TOnChooseClose; typedef void (*TOnChooseFillEvents)(); @@ -62,11 +65,12 @@ struct SChooseEvents enum { flAnimated = (1 << 0), + flClearTexture = (1 << 1), }; shared_str caption; TOnChooseFillItems on_fill; TOnChooseSelectItem on_sel; - TOnDrawThumbnail on_thm; + TGetTexture on_get_texture; TOnChooseClose on_close; Flags32 flags; SChooseEvents() @@ -74,17 +78,16 @@ struct SChooseEvents caption = "Select Item"; flags.zero(); } - SChooseEvents( - LPCSTR capt, TOnChooseFillItems f, TOnChooseSelectItem s, TOnDrawThumbnail t, TOnChooseClose c, u32 fl) + SChooseEvents(LPCSTR capt, TOnChooseFillItems f, TOnChooseSelectItem s, TGetTexture t, TOnChooseClose c, u32 fl) { Set(capt, f, s, t, c, fl); } - void Set(LPCSTR capt, TOnChooseFillItems f, TOnChooseSelectItem s, TOnDrawThumbnail t, TOnChooseClose c, u32 fl) + void Set(LPCSTR capt, TOnChooseFillItems f, TOnChooseSelectItem s, TGetTexture t, TOnChooseClose c, u32 fl) { caption = capt; on_fill = f; on_sel = s; - on_thm = t; + on_get_texture = t; on_close = c; flags.assign(fl); } diff --git a/src/xrCore/ELocatorAPI.cpp b/src/xrCore/ELocatorAPI.cpp new file mode 100644 index 00000000000..5946e881939 --- /dev/null +++ b/src/xrCore/ELocatorAPI.cpp @@ -0,0 +1,656 @@ +#include "stdafx.h" +#include "ELocatorAPI.h" + +#pragma warning(disable : 4995) +#include +#include +#pragma warning(default : 4995) + +extern void CloseLog(); +DEFINE_VECTOR(xr_string, SStringVec, SStringVecIt); + +#include "xrCore/FS_internal.h" + +// hack +struct _utimbuf +{ + time_t actime; // access time + time_t modtime; // modification time +}; + +#define _CRT_NO_TIME_T 1 +#include + +ELocatorAPI::ELocatorAPI() +{ + m_Flags.zero(); + // get page size + SYSTEM_INFO sys_inf; + GetSystemInfo(&sys_inf); + dwAllocGranularity = sys_inf.dwAllocationGranularity; + dwOpenCounter = 0; +} + +void ELocatorAPI::_initialize(u32 flags, pcstr target_folder, pcstr fs_fname) +{ + const char* FSLTX = "fs.ltx"; + + char _delimiter = '|'; //',' + if (m_Flags.is(flReady)) + return; + + Log("Initializing File System..."); + m_Flags.set(flags, TRUE); + string_path tmpAppPath; + + if (m_Flags.is(flScanAppRoot)) + { + string_path tmpFsPath; + xr_strcpy(tmpAppPath, sizeof(tmpAppPath), Core.ApplicationPath); + xr_strcpy(tmpFsPath, sizeof(tmpAppPath), tmpAppPath); + xr_strcat(tmpFsPath, sizeof(tmpAppPath), FSLTX); + + while (xr_strlen(tmpAppPath) && !exist(tmpFsPath)) + { + // remove last slash if exists + if (tmpAppPath[xr_strlen(tmpAppPath) - 1] == '\\') + tmpAppPath[xr_strlen(tmpAppPath) - 1] = '\0'; + + // go one folder up + if (strrchr(tmpAppPath, '\\')) + *(strrchr(tmpAppPath, '\\') + 1) = '\0'; + + // update path to FSLTX + xr_strcpy(tmpFsPath, sizeof(tmpAppPath), tmpAppPath); + xr_strcat(tmpFsPath, sizeof(tmpAppPath), FSLTX); + + // remove last slash + tmpAppPath[xr_strlen(tmpAppPath) - 1] = '\0'; + } + + append_path("$app_root$", tmpAppPath, 0, FALSE); + append_path("$fs_root$", tmpAppPath, 0, FALSE); + } + else + append_path("$fs_root$", "", 0, FALSE); + + xr_strcat(tmpAppPath, "\\"); + IReader *F = r_open(FSLTX); + + if (!F && m_Flags.is(flScanAppRoot)) + F = r_open("$app_root$", FSLTX); + + R_ASSERT3(F, "Can't open file:", FSLTX); + // append all pathes + string_path buf; + string_path id, temp, root, add, def, capt; + pcstr lp_add, lp_def, lp_capt; + string16 b_v; + Core.SocSdk = true; + + while (!F->eof()) + { + F->r_string(buf, sizeof(buf)); + _GetItem(buf, 0, id, '='); + + if (id[0] == ';') + continue; + + if (!strcmp(id, "$server_data_root$")) + Core.SocSdk = false; + + _GetItem(buf, 1, temp, '='); + int cnt = _GetItemCount(temp, _delimiter); + R_ASSERT(cnt >= 3); + u32 fl = 0; + _GetItem(temp, 0, b_v, _delimiter); + if (CInifile::isBool(b_v)) + fl |= FS_Path::flRecurse; + _GetItem(temp, 1, b_v, _delimiter); + if (CInifile::isBool(b_v)) + fl |= FS_Path::flNotif; + _GetItem(temp, 2, root, _delimiter); + _GetItem(temp, 3, add, _delimiter); + _GetItem(temp, 4, def, _delimiter); + _GetItem(temp, 5, capt, _delimiter); + xr_strlwr(id); + if (!m_Flags.is(flBuildCopy) && (0 == xr_strcmp(id, "$build_copy$"))) + continue; + xr_strlwr(root); + lp_add = (cnt >= 4) ? xr_strlwr(add) : 0; + lp_def = (cnt >= 5) ? def : 0; + lp_capt = (cnt >= 6) ? capt : 0; + + PathPairIt p_it = pathes.find(root); + const char* rootDir; + + if (p_it != pathes.end()) + rootDir = p_it->second->m_Path; + else + { + // to find path when working directory is not sdk root, and root not specified + rootDir = tmpAppPath; + lp_add = root; + } + + std::pair I; + FS_Path *P = xr_new(rootDir, lp_add, lp_def, lp_capt, fl); + I = pathes.insert(std::make_pair(xr_strdup(id), P)); + + R_ASSERT(I.second); + } + + r_close(F); + + m_Flags.set(flReady, TRUE); + CreateLog(0 != strstr(Core.Params, "-nolog")); +} + +void ELocatorAPI::_destroy() +{ + CloseLog(); + + for (PathPairIt p_it = pathes.begin(); p_it != pathes.end(); p_it++) + { + char *str = LPSTR(p_it->first); + xr_free(str); + xr_delete(p_it->second); + } + pathes.clear(); +} + +bool ELocatorAPI::file_find(pcstr full_name, FS_File &f) +{ + intptr_t hFile; + _FINDDATA_T sFile; + // find all files + if (-1 != (hFile = _findfirst((LPSTR)full_name, &sFile))) + { + f = FS_File(sFile); + _findclose(hFile); + return TRUE; + } + else + { + return FALSE; + } +} + +FileStatus ELocatorAPI::exist(pcstr fn, FSType) +{ + return FileStatus(::GetFileAttributes(fn) != u32(-1), false); +} + +FileStatus ELocatorAPI::exist(pcstr path, pcstr name, FSType) +{ + string_path temp; + update_path(temp, path, name); + return exist(temp); +} + +FileStatus ELocatorAPI::exist(string_path& fn, pcstr path, pcstr name, FSType) +{ + update_path(fn, path, name); + return exist(fn); +} + +FileStatus ELocatorAPI::exist(string_path& fn, pcstr path, pcstr name, pcstr ext, FSType) +{ + string_path nm; + strconcat(sizeof(nm), nm, name, ext); + update_path(fn, path, nm); + return exist(fn); +} + +extern bool ignore_name(const char* _name); + +typedef void(__stdcall *TOnFind)(_finddata_t &, void *); +void Recurse(pcstr, bool, TOnFind, void *); +void ProcessOne(pcstr path, _finddata_t &F, bool root_only, TOnFind on_find_cb, void *data) +{ + string_path N; + strcpy(N, path); + strcat(N, F.name); + xr_strlwr(N); + + if (ignore_name(N)) + return; + + if (F.attrib & _A_HIDDEN) + return; + + if (F.attrib & _A_SUBDIR) + { + if (root_only) + return; + if (0 == xr_strcmp(F.name, ".")) + return; + if (0 == xr_strcmp(F.name, "..")) + return; + strcat(N, "\\"); + strcpy(F.name, N); + on_find_cb(F, data); + Recurse(F.name, root_only, on_find_cb, data); + } + else + { + strcpy(F.name, N); + on_find_cb(F, data); + } +} + +void Recurse(pcstr path, bool root_only, TOnFind on_find_cb, void *data) +{ + xr_string fpath = path; + fpath += "*.*"; + + // begin search + _finddata_t sFile; + intptr_t hFile; + + // find all files + if (-1 == (hFile = _findfirst((LPSTR)fpath.c_str(), &sFile))) + return; + do + { + ProcessOne(path, sFile, root_only, on_find_cb, data); + } while (_findnext(hFile, &sFile) == 0); + _findclose(hFile); +} + +struct file_list_cb_data +{ + size_t base_len; + u32 flags; + SStringVec *masks; + FS_FileSet *dest; +}; + +void __stdcall file_list_cb(_finddata_t &entry, void *data) +{ + file_list_cb_data *D = (file_list_cb_data *)data; + + pcstr end_symbol = entry.name + xr_strlen(entry.name) - 1; + if ((*end_symbol) != '\\') + { + // file + if ((D->flags & FS_ListFiles) == 0) + return; + pcstr entry_begin = entry.name + D->base_len; + if ((D->flags & FS_RootOnly) && strstr(entry_begin, "\\")) + return; // folder in folder + // check extension + if (D->masks) + { + bool bOK = false; + for (auto it = D->masks->begin(); it != D->masks->end(); it++) + if (PatternMatch(entry_begin, it->c_str())) + { + bOK = true; + break; + } + if (!bOK) + return; + } + xr_string fn = entry_begin; + // insert file entry + if (D->flags & FS_ClampExt) + fn = EFS.ChangeFileExt(fn, ""); + D->dest->insert(FS_File(fn, entry)); + } + else + { + // folder + if ((D->flags & FS_ListFolders) == 0) + return; + pcstr entry_begin = entry.name + D->base_len; + D->dest->insert(FS_File(entry_begin, entry)); + } +} + +size_t ELocatorAPI::file_list(FS_FileSet &dest, pcstr path, u32 flags, pcstr mask) +{ + R_ASSERT(path); + VERIFY(flags); + + string_path fpath; + if (path_exist(path)) + update_path(fpath, path, ""); + else + strcpy(fpath, path); + + // build mask + SStringVec masks; + _SequenceToList(masks, mask); + + file_list_cb_data data; + data.base_len = xr_strlen(fpath); + data.flags = flags; + data.masks = masks.empty() ? 0 : &masks; + data.dest = &dest; + + Recurse(fpath, !!(flags & FS_RootOnly), file_list_cb, &data); + return dest.size(); +} + +IReader *ELocatorAPI::r_open(pcstr path, pcstr _fname) +{ + IReader *R = 0; + + // correct path + string_path fname; + strcpy(fname, _fname); + xr_strlwr(fname); + if (path && path[0]) + update_path(fname, path, fname); + + // Search entry + FS_File desc; + if (!file_find(fname, desc)) + return NULL; + + dwOpenCounter++; + + pcstr source_name = &fname[0]; + + // open file + if (desc.size < 256 * 1024) + R = xr_new(fname); + else + R = xr_new(fname); + +#ifdef DEBUG + if (R && m_Flags.is(flBuildCopy | flReady)) + { + string_path cpy_name; + string_path e_cpy_name; + FS_Path *P; + if (source_name == strstr(source_name, (P = get_path("$server_root$"))->m_Path) || + source_name == strstr(source_name, (P = get_path("$server_data_root$"))->m_Path)) + { + update_path(cpy_name, "$build_copy$", source_name + xr_strlen(P->m_Path)); + IWriter *W = w_open(cpy_name); + if (W) + { + W->w(R->pointer(), R->length()); + w_close(W); + set_file_age(cpy_name, get_file_age(source_name)); + if (m_Flags.is(flEBuildCopy)) + { + pcstr ext = strext(cpy_name); + if (ext) + { + IReader *R = 0; + if (0 == xr_strcmp(ext, ".dds")) + { + P = get_path("$game_textures$"); + update_path(e_cpy_name, "$textures$", source_name + xr_strlen(P->m_Path)); + // tga + *strext(e_cpy_name) = 0; + strcat(e_cpy_name, ".tga"); + r_close(R = r_open(e_cpy_name)); + // thm + *strext(e_cpy_name) = 0; + strcat(e_cpy_name, ".thm"); + r_close(R = r_open(e_cpy_name)); + } + else if (0 == xr_strcmp(ext, ".ogg")) + { + P = get_path("$game_sounds$"); + update_path(e_cpy_name, "$sounds$", source_name + xr_strlen(P->m_Path)); + // wav + *strext(e_cpy_name) = 0; + strcat(e_cpy_name, ".wav"); + r_close(R = r_open(e_cpy_name)); + // thm + *strext(e_cpy_name) = 0; + strcat(e_cpy_name, ".thm"); + r_close(R = r_open(e_cpy_name)); + } + else if (0 == xr_strcmp(ext, ".object")) + { + strcpy(e_cpy_name, source_name); + // object thm + *strext(e_cpy_name) = 0; + strcat(e_cpy_name, ".thm"); + R = r_open(e_cpy_name); + if (R) + r_close(R); + } + } + } + } + else + { + Log("!Can't build:", source_name); + } + } + } +#endif // DEBUG + return R; +} + +void ELocatorAPI::r_close(IReader *&fs) +{ + xr_delete(fs); +} + +IWriter *ELocatorAPI::w_open(pcstr path, pcstr _fname) +{ + string_path fname; + xr_strlwr(strcpy(fname, _fname)); //,".$"); + if (path && path[0]) + update_path(fname, path, fname); + CFileWriter *W = xr_new(fname, false); +#ifdef _EDITOR + if (!W->valid()) + xr_delete(W); +#endif + return W; +} + +IWriter *ELocatorAPI::w_open_ex(pcstr path, pcstr _fname) +{ + string_path fname; + xr_strlwr(strcpy(fname, _fname)); //,".$"); + if (path && path[0]) + update_path(fname, path, fname); + CFileWriter *W = xr_new(fname, true); +#ifdef _EDITOR + if (!W->valid()) + xr_delete(W); +#endif + return W; +} + +void ELocatorAPI::w_close(IWriter *&S) +{ + if (S) + { + R_ASSERT(S->fName.size()); + xr_delete(S); + } +} + +struct dir_delete_cb_data +{ + FS_FileSet *folders; + BOOL remove_files; +}; + +void __stdcall dir_delete_cb(_finddata_t &entry, void *data) +{ + dir_delete_cb_data *D = (dir_delete_cb_data *)data; + + if (entry.attrib & _A_SUBDIR) + D->folders->insert(FS_File(entry)); + else if (D->remove_files) + FS.file_delete(entry.name); +} + +bool ELocatorAPI::dir_delete(pcstr initial, pcstr nm, bool remove_files) +{ + string_path fpath; + if (initial && initial[0]) + update_path(fpath, initial, nm); + else + strcpy(fpath, nm); + + FS_FileSet folders; + folders.insert(FS_File(fpath)); + + // recurse find + dir_delete_cb_data data; + data.folders = &folders; + data.remove_files = remove_files; + Recurse(fpath, false, dir_delete_cb, &data); + + // remove folders + FS_FileSet::reverse_iterator r_it = folders.rbegin(); + for (; r_it != folders.rend(); r_it++) + _rmdir(r_it->name.c_str()); + return TRUE; +} + +void ELocatorAPI::file_delete(pcstr path, pcstr nm) +{ + string_path fname; + if (path && path[0]) + update_path(fname, path, nm); + else + strcpy(fname, nm); + unlink(fname); +} + +void ELocatorAPI::file_copy(pcstr src, pcstr dest) +{ + if (exist(src)) + { + IReader *S = r_open(src); + if (S) + { + IWriter *D = w_open(dest); + if (D) + { + D->w(S->pointer(), S->length()); + w_close(D); + } + r_close(S); + } + } +} + +void ELocatorAPI::file_rename(pcstr src, pcstr dest, bool bOwerwrite) +{ + if (bOwerwrite && exist(dest)) + unlink(dest); + // physically rename file + VerifyPath(dest); + rename(src, dest); +} + +int ELocatorAPI::file_length(pcstr src) +{ + FS_File F; + return (file_find(src, F)) ? F.size : -1; +} + +bool ELocatorAPI::path_exist(pcstr path) +{ + PathPairIt P = pathes.find(path); + return (P != pathes.end()); +} + +FS_Path *ELocatorAPI::append_path(pcstr path_alias, pcstr root, pcstr add, bool recursive) +{ + VERIFY(root /*&&root[0]*/); + VERIFY(false == path_exist(path_alias)); + FS_Path *P = xr_new(root, add, pcstr(0), pcstr(0), 0); + pathes.insert(std::make_pair(xr_strdup(path_alias), P)); + return P; +} + +FS_Path *ELocatorAPI::get_path(pcstr path) +{ + PathPairIt P = pathes.find(path); + R_ASSERT2(P != pathes.end(), path); + return P->second; +} + +pcstr ELocatorAPI::update_path(string_path &dest, pcstr initial, pcstr src, bool) +{ + return get_path(initial)->_update(dest, src); +} +/* +void ELocatorAPI::update_path(xr_string& dest, pcstr initial, pcstr src) +{ + return get_path(initial)->_update(dest,src); +} */ + +u32 ELocatorAPI::get_file_age(pcstr nm) +{ + FS_File F; + return (file_find(nm, F)) ? F.time_write : -1; +} + +void ELocatorAPI::set_file_age(pcstr nm, u32 age) +{ + // set file + _utimbuf tm; + tm.actime = age; + tm.modtime = age; + int res = _utime32(nm, reinterpret_cast<__utimbuf32*>(&tm)); + if (0 != res) + Msg("!Can't set file age: '%s'. Error: '%s'", nm, _sys_errlist[errno]); +} + +bool ELocatorAPI::can_write_to_folder(pcstr path) +{ + if (path && path[0]) + { + string_path temp; + pcstr fn = "$!#%TEMP%#!$.$$$"; + strconcat(sizeof(temp), temp, path, path[xr_strlen(path) - 1] != '\\' ? "\\" : "", fn); + FILE *hf = fopen(temp, "wb"); + if (hf == 0) + return FALSE; + else + { + fclose(hf); + unlink(temp); + return TRUE; + } + } + else + { + return FALSE; + } +} + +bool ELocatorAPI::can_write_to_alias(pcstr path) +{ + string_path temp; + update_path(temp, path, ""); + return can_write_to_folder(temp); +} + +bool ELocatorAPI::can_modify_file(pcstr fname) +{ + FILE *hf = fopen(fname, "r+b"); + if (hf) + { + fclose(hf); + return TRUE; + } + else + { + return FALSE; + } +} + +bool ELocatorAPI::can_modify_file(pcstr path, pcstr name) +{ + string_path temp; + update_path(temp, path, name); + return can_modify_file(temp); +} diff --git a/src/xrCore/ELocatorAPI.h b/src/xrCore/ELocatorAPI.h new file mode 100644 index 00000000000..5f862f23eed --- /dev/null +++ b/src/xrCore/ELocatorAPI.h @@ -0,0 +1,58 @@ +#pragma once +#include "xrCore/LocatorAPI_defs.h" + +class ELocatorAPI : Noncopyable, public ILocatorAPI +{ + friend class FS_Path; + +public: +private: + DEFINE_MAP_PRED(pcstr, FS_Path *, PathMap, PathPairIt, pred_str); + PathMap pathes; + +public: + ELocatorAPI(); + ~ELocatorAPI() = default; + + void _initialize(u32 flags, pcstr target_folder = 0, pcstr fs_fname = 0) override; + void _destroy(); + + IReader *r_open(pcstr initial, pcstr N); + IC IReader *r_open(pcstr N) { return r_open(0, N); } + void r_close(IReader *&S); + + IWriter *w_open(pcstr initial, pcstr N); + IWriter *w_open_ex(pcstr initial, pcstr N); + IC IWriter *w_open(pcstr N) { return w_open(0, N); } + IC IWriter *w_open_ex(pcstr N) { return w_open_ex(0, N); } + void w_close(IWriter *&S); + + FileStatus exist(pcstr N, FSType fsType = FSType::Virtual); + FileStatus exist(pcstr path, pcstr name, FSType fsType = FSType::Virtual); + FileStatus exist(string_path& fn, pcstr path, pcstr name, FSType fsType = FSType::Virtual); + FileStatus exist(string_path& fn, pcstr path, pcstr name, pcstr ext, FSType fsType = FSType::Virtual); + + bool can_write_to_folder(pcstr path); + bool can_write_to_alias(pcstr path); + bool can_modify_file(pcstr fname); + bool can_modify_file(pcstr path, pcstr name); + + bool dir_delete(pcstr initial, pcstr N, bool remove_files); + bool dir_delete(pcstr full_path, bool remove_files) { return dir_delete(0, full_path, remove_files); } + void file_delete(pcstr path, pcstr nm); + void file_delete(pcstr full_path) { file_delete(0, full_path); } + void file_copy(pcstr src, pcstr dest); + void file_rename(pcstr src, pcstr dest, bool bOwerwrite = true); + int file_length(pcstr src); + + u32 get_file_age(pcstr nm); + void set_file_age(pcstr nm, u32 age); + + bool path_exist(pcstr path); + FS_Path *get_path(pcstr path); + FS_Path *append_path(pcstr path_alias, pcstr root, pcstr add, bool recursive); + pcstr update_path(string_path& dest, pcstr initial, pcstr src, bool crashOnNotFound = false); + + bool file_find(pcstr full_name, FS_File &f); + size_t file_list(FS_FileSet &dest, pcstr path, u32 flags = FS_ListFiles, pcstr mask = 0); +}; diff --git a/src/xrCore/FMesh.hpp b/src/xrCore/FMesh.hpp index 598dca51d9a..807e82f795a 100644 --- a/src/xrCore/FMesh.hpp +++ b/src/xrCore/FMesh.hpp @@ -65,21 +65,6 @@ enum OGF_SkeletonVertType const u16 xrOGF_SMParamsVersion = 4; -// OGF_DESC -struct XRCORE_API ogf_desc -{ - shared_str source_file; - shared_str build_name; - time_t build_time; - shared_str create_name; - time_t create_time; - shared_str modif_name; - time_t modif_time; - ogf_desc() : build_time(0), create_time(0), modif_time(0) {} - void Load(IReader& F); - void Save(IWriter& F); -}; - // OGF_BBOX struct ogf_bbox { diff --git a/src/xrCore/FS_internal.h b/src/xrCore/FS_internal.h index ce7cafe3976..79d5a7be24f 100644 --- a/src/xrCore/FS_internal.h +++ b/src/xrCore/FS_internal.h @@ -138,7 +138,7 @@ class CCompressedReader final : public IReader CCompressedReader(const char* name, const char* sign); ~CCompressedReader() override; }; -class CVirtualFileReader final : public IReader +class XRCORE_API CVirtualFileReader final : public IReader { private: #if defined(XR_PLATFORM_WINDOWS) diff --git a/src/xrCore/FileSystem.cpp b/src/xrCore/FileSystem.cpp index e3a0f75969e..5428a889c88 100644 --- a/src/xrCore/FileSystem.cpp +++ b/src/xrCore/FileSystem.cpp @@ -120,7 +120,7 @@ UINT_PTR CALLBACK OFNHookProcOldStyle(HWND, UINT, WPARAM, LPARAM) } #endif -bool EFS_Utils::GetOpenNameInternal( +bool EFS_Utils::GetOpenNameInternal(HWND hWnd, LPCSTR initial, pstr buffer, size_t sz_buf, bool bMulti /*= false*/, LPCSTR offset /*= 0*/, int start_flt_ext /*= -1*/) { VERIFY(buffer && (sz_buf > 0)); @@ -148,7 +148,7 @@ bool EFS_Utils::GetOpenNameInternal( } } ofn.lStructSize = sizeof(OPENFILENAME); - ofn.hwndOwner = GetForegroundWindow(); + ofn.hwndOwner = hWnd; ofn.lpstrDefExt = P.m_DefExt; ofn.lpstrFile = buffer; ofn.nMaxFile = sz_buf; diff --git a/src/xrCore/FileSystem.h b/src/xrCore/FileSystem.h index 366ae395f29..4f37acb8736 100644 --- a/src/xrCore/FileSystem.h +++ b/src/xrCore/FileSystem.h @@ -10,7 +10,7 @@ class XRCORE_API EFS_Utils { protected: - bool GetOpenNameInternal( + bool GetOpenNameInternal(HWND hWnd, LPCSTR initial, pstr buffer, size_t sz_buf, bool bMulti = false, LPCSTR offset = 0, int start_flt_ext = -1); public: @@ -20,7 +20,7 @@ class XRCORE_API EFS_Utils bool GetOpenName(LPCSTR initial, string_path& buffer, int sz_buf, bool bMulti = false, LPCSTR offset = 0, int start_flt_ext = -1); - bool GetOpenName(LPCSTR initial, xr_string& buf, bool bMulti = false, LPCSTR offset = 0, int start_flt_ext = -1); + bool GetOpenName(HWND hWnd, LPCSTR initial, xr_string& buf, bool bMulti = false, LPCSTR offset = 0, int start_flt_ext = -1); bool GetSaveName(LPCSTR initial, string_path& buffer, LPCSTR offset = 0, int start_flt_ext = -1); bool GetSaveName(LPCSTR initial, xr_string& buf, LPCSTR offset = 0, int start_flt_ext = -1); diff --git a/src/xrCore/FileSystem_borland.cpp b/src/xrCore/FileSystem_borland.cpp index 7ef7fe9d8a0..8569b111954 100644 --- a/src/xrCore/FileSystem_borland.cpp +++ b/src/xrCore/FileSystem_borland.cpp @@ -19,7 +19,7 @@ int CALLBACK BrowseCallbackProc(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpDa return 0; } -bool EFS_Utils::GetOpenName(LPCSTR initial, xr_string& buffer, bool bMulti, LPCSTR offset, int start_flt_ext) +bool EFS_Utils::GetOpenName(HWND hWnd, LPCSTR initial, xr_string& buffer, bool bMulti, LPCSTR offset, int start_flt_ext) { char buf[255 * 255]; // max files to select xr_strcpy(buf, buffer.c_str()); @@ -42,7 +42,7 @@ bool EFS_Utils::GetOpenName(LPCSTR initial, xr_string& buffer, bool bMulti, LPCS } */ // bool bRes = false; - bool bRes = GetOpenNameInternal(initial, buf, sizeof(buf), bMulti, offset, start_flt_ext); + bool bRes = GetOpenNameInternal(hWnd, initial, buf, sizeof(buf), bMulti, offset, start_flt_ext); if (bRes) buffer = (char*)buf; diff --git a/src/xrCore/ILocatorApi.h b/src/xrCore/ILocatorApi.h new file mode 100644 index 00000000000..2aaeeb3e83e --- /dev/null +++ b/src/xrCore/ILocatorApi.h @@ -0,0 +1,134 @@ +#pragma once +#include "LocatorAPI_defs.h" +#include "xrCommon/xr_smart_pointers.h" + +enum class FSType +{ + Virtual = 1, + External = 2, + Any = Virtual | External, +}; + +class FileStatus +{ +public: + bool Exists; + bool External; // File can be accessed only as external + + FileStatus(bool exists, bool external) : Exists(exists), External(external) {} + + operator bool() const { return Exists; } +}; + +class XRCORE_API CStreamReader; +class XRCORE_API ILocatorAPI +{ + friend class FS_Path; + +public: + + struct archive + { + size_t size = 0; + size_t vfs_idx = size_t(-1); + shared_str path; + u32 modif = 0; +#if defined(XR_PLATFORM_WINDOWS) + void *hSrcFile = nullptr; + void *hSrcMap = nullptr; +#elif defined(XR_PLATFORM_LINUX) || defined(XR_PLATFORM_BSD) || defined(XR_PLATFORM_APPLE) + int hSrcFile = 0; +#else +# error Select or add implementation for your platform +#endif + CInifile* header = nullptr; + + archive() = default; + void open(); + void close(); + }; + + enum : u32 + { + flNeedRescan = (1 << 0), + flBuildCopy = (1 << 1), + flReady = (1 << 2), + flEBuildCopy = (1 << 3), + flEventNotificator = (1 << 4), + flTargetFolderOnly = (1 << 5), + flCacheFiles = (1 << 6), + flScanAppRoot = (1 << 7), + flNeedCheck = (1 << 8), + flDumpFileActivity = (1 << 9), + }; + + using archives_vec = xr_vector; + archives_vec m_archives; + + virtual void LoadArchive(archive& A, pcstr entrypoint = nullptr) { R_ASSERT(false); } + virtual bool load_all_unloaded_archives() { R_ASSERT(false); return false; } + virtual void unload_archive(archive& A) { R_ASSERT(false); } + + virtual ~ILocatorAPI() = default; + virtual void _initialize(u32 flags, pcstr target_folder = 0, pcstr fs_fname = 0) = 0; + virtual void _destroy() = 0; + + virtual IReader* r_open(pcstr initial, pcstr N) = 0; + virtual void r_close(IReader*& S) = 0; + IC IReader* r_open(pcstr N) { return r_open(0, N); } + + virtual IWriter* w_open(pcstr initial, pcstr N) = 0; + virtual IWriter* w_open_ex(pcstr initial, pcstr N) = 0; + virtual void w_close(IWriter*& S) = 0; + IC IWriter* w_open(pcstr N) { return w_open(0, N); } + IC IWriter* w_open_ex(pcstr N) { return w_open_ex(0, N); } + + virtual FileStatus exist(pcstr N, FSType fsType = FSType::Virtual) = 0; + virtual FileStatus exist(pcstr path, pcstr name, FSType fsType = FSType::Virtual) = 0; + virtual FileStatus exist(string_path& fn, pcstr path, pcstr name, FSType fsType = FSType::Virtual) = 0; + virtual FileStatus exist(string_path& fn, pcstr path, pcstr name, pcstr ext, FSType fsType = FSType::Virtual) = 0; + + virtual bool can_write_to_folder(pcstr path) = 0; + virtual bool can_write_to_alias(pcstr path) = 0; + virtual bool can_modify_file(pcstr fname) = 0; + virtual bool can_modify_file(pcstr path, pcstr name) = 0; + + virtual bool dir_delete(pcstr initial, pcstr N, bool remove_files) = 0; + virtual bool dir_delete(pcstr full_path, bool remove_files) { return dir_delete(0, full_path, remove_files); } + virtual void file_delete(pcstr path, pcstr nm) = 0; + virtual void file_delete(pcstr full_path) { file_delete(0, full_path); } + virtual void file_copy(pcstr src, pcstr dest) = 0; + virtual void file_rename(pcstr src, pcstr dest, bool bOwerwrite = true) = 0; + virtual int file_length(pcstr src) = 0; + + virtual u32 get_file_age(pcstr nm) = 0; + virtual void set_file_age(pcstr nm, u32 age) = 0; + + virtual bool path_exist(pcstr path) = 0; + virtual FS_Path* get_path(pcstr path) = 0; + virtual FS_Path* append_path(pcstr path_alias, pcstr root, pcstr add, bool recursive) = 0; + virtual pcstr update_path(string_path& dest, pcstr initial, pcstr src, bool crashOnNotFound = true) = 0; + + virtual bool file_find(pcstr full_name, FS_File& f) { R_ASSERT(false); return false; }; + virtual size_t file_list(FS_FileSet& dest, pcstr path, u32 flags = FS_ListFiles, pcstr mask = 0) = 0; + virtual void r_close(CStreamReader*& fs) { R_ASSERT(false); } + virtual CStreamReader* rs_open(pcstr initial, pcstr N) { R_ASSERT(false); return nullptr; }; + + virtual xr_vector* file_list_open(pcstr initial, pcstr folder, u32 flags = FS_ListFiles) { R_ASSERT(false); return nullptr; }; + virtual xr_vector* file_list_open(pcstr path, u32 flags = FS_ListFiles) { R_ASSERT(false); return nullptr; }; + virtual void file_list_close(xr_vector*& lst) { R_ASSERT(false); }; + + virtual void auth_generate(xr_vector& ignore, xr_vector& important) { R_ASSERT(false); }; + virtual u64 auth_get() { R_ASSERT(false); return 0; }; + virtual void auth_runtime(void*) { R_ASSERT(false); }; + + virtual void rescan_path(pcstr full_path, bool bRecurse) { R_ASSERT(false); } + virtual void rescan_pathes() { R_ASSERT(false); } + + Flags32 m_Flags; + u32 dwAllocGranularity; + u32 dwOpenCounter; +}; + +extern XRCORE_API xr_unique_ptr xr_FS; +#define FS (*xr_FS) diff --git a/src/xrCore/LocatorAPI.cpp b/src/xrCore/LocatorAPI.cpp index 18a416e19f1..6def726d93c 100644 --- a/src/xrCore/LocatorAPI.cpp +++ b/src/xrCore/LocatorAPI.cpp @@ -27,7 +27,7 @@ constexpr size_t VFS_STANDARD_FILE = std::numeric_limits::max(); const u32 BIG_FILE_READER_WINDOW_SIZE = 1024 * 1024; -xr_unique_ptr xr_FS; +xr_unique_ptr xr_FS; #ifdef _EDITOR static constexpr pcstr FSLTX = "fs.ltx" diff --git a/src/xrCore/LocatorAPI.h b/src/xrCore/LocatorAPI.h index bc4a895b2ea..a014d65ece5 100644 --- a/src/xrCore/LocatorAPI.h +++ b/src/xrCore/LocatorAPI.h @@ -10,7 +10,6 @@ #include "LocatorAPI_defs.h" //#include "xrCore/Threading/Lock.hpp" #include "xrCommon/xr_map.h" -#include "xrCommon/xr_smart_pointers.h" #include "xrCommon/predicates.h" #include "Common/Noncopyable.hpp" @@ -53,28 +52,9 @@ struct _finddata32_t class CStreamReader; class Lock; -enum class FSType -{ - Virtual = 1, - External = 2, - Any = Virtual | External, -}; - IMPLEMENT_ENUM_FLAG_OPERATORS(FSType, int); -class FileStatus -{ -public: - bool Exists; - bool External; // File can be accessed only as external - - FileStatus(bool exists, bool external) - : Exists(exists), External(external) {} - - operator bool() const { return Exists; } -}; - -class XRCORE_API CLocatorAPI : Noncopyable +class XRCORE_API CLocatorAPI : Noncopyable, public ILocatorAPI { friend class FS_Path; @@ -93,27 +73,6 @@ class XRCORE_API CLocatorAPI : Noncopyable u32 modif; // for editor }; - struct archive - { - size_t size = 0; - size_t vfs_idx = size_t(-1); - shared_str path; - u32 modif = 0; -#if defined(XR_PLATFORM_WINDOWS) - void *hSrcFile = nullptr; - void *hSrcMap = nullptr; -#elif defined(XR_PLATFORM_LINUX) || defined(XR_PLATFORM_BSD) || defined(XR_PLATFORM_APPLE) - int hSrcFile = 0; -#else -# error Select or add implementation for your platform -#endif - CInifile* header = nullptr; - - archive() = default; - void open(); - void close(); - }; - // IMPORTNT: don't replace u32 with size_t for this struct // (Letter A in the first word is forgotten intentionally, // size_t will blow up the engine compatibility with it's resources) @@ -134,8 +93,6 @@ class XRCORE_API CLocatorAPI : Noncopyable archive_file_header(IWriter& writer, pcstr file_name, u32 real_size, u32 compressed_size, u32 crc_sum, u32 pointer); }; - using archives_vec = xr_vector; - archives_vec m_archives; void LoadArchive(archive& A, pcstr entrypoint = nullptr); private: @@ -170,24 +127,6 @@ class XRCORE_API CLocatorAPI : Noncopyable files_it file_find_it(pcstr n); -public: - enum : u32 - { - flNeedRescan = (1 << 0), - flBuildCopy = (1 << 1), - flReady = (1 << 2), - flEBuildCopy = (1 << 3), - flEventNotificator = (1 << 4), - flTargetFolderOnly = (1 << 5), - flCacheFiles = (1 << 6), - flScanAppRoot = (1 << 7), - flNeedCheck = (1 << 8), - flDumpFileActivity = (1 << 9), - }; - Flags32 m_Flags; - u32 dwAllocGranularity; - u32 dwOpenCounter; - private: void check_cached_files(pstr fname, const size_t& fname_size, const file& desc, pcstr& source_name); @@ -279,6 +218,3 @@ class XRCORE_API CLocatorAPI : Noncopyable void lock_rescan(); void unlock_rescan(); }; - -extern XRCORE_API xr_unique_ptr xr_FS; -#define FS (*xr_FS) diff --git a/src/xrCore/LocatorAPI_defs.h b/src/xrCore/LocatorAPI_defs.h index c17b7aadae4..d514cb1264a 100644 --- a/src/xrCore/LocatorAPI_defs.h +++ b/src/xrCore/LocatorAPI_defs.h @@ -39,16 +39,8 @@ class XRCORE_API FS_Path void rescan_path_cb(); }; -#ifdef _EDITOR -namespace std -{ -struct _finddata_t; -}; -#define _FINDDATA_T std::_finddata_t -#else struct _finddata64i32_t; #define _FINDDATA_T _finddata64i32_t -#endif struct XRCORE_API FS_File { diff --git a/src/xrCore/log.cpp b/src/xrCore/log.cpp index 7ef6aa480b8..d94d4857eac 100644 --- a/src/xrCore/log.cpp +++ b/src/xrCore/log.cpp @@ -246,7 +246,7 @@ void CreateLog(BOOL nl) ForceFlushLog = true; } -void CloseLog(void) +void XRCORE_API CloseLog(void) { FlushLog(); if (LogWriter) diff --git a/src/xrCore/log.h b/src/xrCore/log.h index c378bcd9ea7..e8c946a140c 100644 --- a/src/xrCore/log.h +++ b/src/xrCore/log.h @@ -48,7 +48,7 @@ struct LogCallback LogCallback XRCORE_API SetLogCB(const LogCallback& cb); void XRCORE_API CreateLog(BOOL no_log = FALSE); void InitLog(); -void CloseLog(); +void XRCORE_API CloseLog(); void XRCORE_API FlushLog(); extern XRCORE_API xr_vector LogFile; diff --git a/src/xrCore/xrCore.cpp b/src/xrCore/xrCore.cpp index 7bbe6b8d19a..509b7e21853 100644 --- a/src/xrCore/xrCore.cpp +++ b/src/xrCore/xrCore.cpp @@ -156,7 +156,7 @@ void xrCore::PrintBuildInfo() Log(buf); // "%s build %s from commit[%s] branch[%s] (built by %s)" } -void xrCore::Initialize(pcstr _ApplicationName, pcstr commandLine, LogCallback cb, bool init_fs, pcstr fs_fname, bool plugin) +void xrCore::Initialize(pcstr _ApplicationName, pcstr commandLine, LogCallback cb, bool init_fs, pcstr fs_fname, bool plugin, bool editor) { Threading::SetCurrentThreadName("Primary thread"); xr_strcpy(ApplicationName, _ApplicationName); @@ -198,16 +198,6 @@ void xrCore::Initialize(pcstr _ApplicationName, pcstr commandLine, LogCallback c # error Select or add implementation for your platform #endif -#ifdef _EDITOR - // working path - if (strstr(Params, "-wf")) - { - string_path c_name; - sscanf(strstr(Core.Params, "-wf ") + 4, "%[^ ] ", c_name); - SetCurrentDirectory(c_name); - } -#endif - #if defined(XR_PLATFORM_WINDOWS) GetCurrentDirectory(sizeof(WorkingPath), WorkingPath); #elif defined(XR_PLATFORM_LINUX) || defined(XR_PLATFORM_BSD) || defined(XR_PLATFORM_APPLE) @@ -254,7 +244,14 @@ void xrCore::Initialize(pcstr _ApplicationName, pcstr commandLine, LogCallback c rtc_initialize(); +#if defined(XR_PLATFORM_WINDOWS) + if (editor) + xr_FS = xr_unique_ptr(xr_new()); + else + xr_FS = xr_unique_ptr(xr_new()); +#else xr_FS = xr_make_unique(); +#endif xr_EFS = xr_make_unique(); //. R_ASSERT (co_res==S_OK); diff --git a/src/xrCore/xrCore.h b/src/xrCore/xrCore.h index 0ced1370128..23154c0e8f8 100644 --- a/src/xrCore/xrCore.h +++ b/src/xrCore/xrCore.h @@ -65,17 +65,22 @@ struct XRCORE_API xr_rtoken bool equal(pcstr _nm) const { return (0 == xr_strcmp(*name, _nm)); } }; +DEFINE_VECTOR(xr_rtoken, RTokenVec, RTokenVecIt); + #include "xr_shortcut.h" #include "FS.h" #include "log.h" #include "xr_trims.h" #include "xr_ini.h" -#ifdef NO_FS_SCAN -#include "ELocatorAPI.h" -#else + +#include "ILocatorApi.h" #include "LocatorAPI.h" + +#if defined(XR_PLATFORM_WINDOWS) +#include "ELocatorAPI.h" #endif + #include "FileSystem.h" #include "FTimer.h" #include "fastdelegate.h" @@ -118,9 +123,10 @@ class XRCORE_API xrCore char* Params; u32 dwFrame; bool PluginMode; + bool SocSdk; void Initialize( - pcstr ApplicationName, pcstr commandLine = nullptr, LogCallback cb = nullptr, bool init_fs = true, pcstr fs_fname = nullptr, bool plugin = false); + pcstr ApplicationName, pcstr commandLine = nullptr, LogCallback cb = nullptr, bool init_fs = true, pcstr fs_fname = nullptr, bool plugin = false, bool editor = false); void _destroy(); u32 GetBuildId() const { return buildId; } diff --git a/src/xrCore/xrCore.vcxproj b/src/xrCore/xrCore.vcxproj index 377f18227a8..6612987ba1c 100644 --- a/src/xrCore/xrCore.vcxproj +++ b/src/xrCore/xrCore.vcxproj @@ -55,6 +55,7 @@ call .GitInfo.cmd + @@ -68,7 +69,6 @@ call .GitInfo.cmd - @@ -161,6 +161,7 @@ call .GitInfo.cmd + @@ -172,6 +173,7 @@ call .GitInfo.cmd + diff --git a/src/xrCore/xrCore.vcxproj.filters b/src/xrCore/xrCore.vcxproj.filters index 45d2a51cf57..4da095b281d 100644 --- a/src/xrCore/xrCore.vcxproj.filters +++ b/src/xrCore/xrCore.vcxproj.filters @@ -216,9 +216,6 @@ Animation - - FMesh - PostProcess @@ -327,6 +324,9 @@ Math + + FS + @@ -704,6 +704,12 @@ Threading + + FS + + + FS + diff --git a/src/xrCore/xrstring.h b/src/xrCore/xrstring.h index 1101a579861..54bc3eed735 100644 --- a/src/xrCore/xrstring.h +++ b/src/xrCore/xrstring.h @@ -184,6 +184,9 @@ class shared_str } }; +DEFINE_VECTOR(shared_str, RStringVec, RStringVecIt); +DEFINE_SET(shared_str, RStringSet, RStringSetIt); + #ifdef BREAK_AT_STRCMP XRCORE_API int xr_strcmp(const char* S1, const char* S2); #else diff --git a/src/xrEngine/GameFont.cpp b/src/xrEngine/GameFont.cpp index baa5f749c04..b9e71d74344 100644 --- a/src/xrEngine/GameFont.cpp +++ b/src/xrEngine/GameFont.cpp @@ -8,6 +8,8 @@ #include "Render.h" #endif +#include "Common/RDevice.h" + extern ENGINE_API bool g_bRendering; ENGINE_API Fvector2 g_current_font_scale = {1.0f, 1.0f}; @@ -300,7 +302,7 @@ u16 CGameFont::SplitByWidth(u16* puBuffer, u16 uBufferSize, float fTargetWidth, void CGameFont::MasterOut(bool bCheckDevice, bool bUseCoords, bool bScaleCoords, bool bUseSkip, float _x, float _y, float _skip, pcstr fmt, va_list p) { - if (bCheckDevice && (!Device.b_is_Active)) + if (bCheckDevice && (!RDEVICE.b_is_Active)) return; String rs; @@ -447,7 +449,7 @@ float CGameFont::CurrentHeight_() { return fCurrentHeight * vInterval.y; } void CGameFont::SetHeightI(float S) { VERIFY(uFlags & fsDeviceIndependent); - fCurrentHeight = S * Device.dwHeight; + fCurrentHeight = S * RDEVICE.dwHeight; }; void CGameFont::SetHeight(float S) diff --git a/src/xrEngine/GameMtlLib.h b/src/xrEngine/GameMtlLib.h index 834d3219606..77edc69a444 100644 --- a/src/xrEngine/GameMtlLib.h +++ b/src/xrEngine/GameMtlLib.h @@ -160,6 +160,11 @@ struct MTL_EXPORT_API SGameMtlPair }; CGameMtlLibrary* m_Owner; +#ifdef _EDITOR + bool m_EditParent; + bool m_EditCommand; +#endif + private: int mtl0; int mtl1; @@ -188,6 +193,11 @@ struct MTL_EXPORT_API SGameMtlPair public: SGameMtlPair(CGameMtlLibrary* owner) { +#ifdef _EDITOR + m_EditParent = false; + m_EditCommand = false; +#endif + mtl0 = -1; mtl1 = -1; ID = -1; @@ -221,7 +231,6 @@ struct MTL_EXPORT_API SGameMtlPair PropValue* propCollideParticles; PropValue* propCollideMarks; - SGameMtlPair(const SGameMtlPair& src); void OnFlagChange(PropValue* sender); void OnParentClick(ButtonValue* sender, bool& bModif, bool& bSafe); void OnCommandClick(ButtonValue* sender, bool& bModif, bool& bSafe); @@ -229,6 +238,8 @@ struct MTL_EXPORT_API SGameMtlPair void FillProp(PropItemVec& values); void TransferFromParent(SGameMtlPair* parent); bool SetParent(int parentId); + void OnDrawUI(); + void CopyFrom(SGameMtlPair* parent); #endif }; @@ -311,7 +322,7 @@ class MTL_EXPORT_API CGameMtlLibrary GameMtlIt FirstMaterial() { return materials.begin(); } GameMtlIt LastMaterial() { return materials.end(); } u32 CountMaterial() const { return materials.size(); } -#ifdef EDITOR +#ifdef _EDITOR SGameMtl* AppendMaterial(SGameMtl* parent); void RemoveMaterial(pcstr name); void CopyMtlPairs(SGameMtl* src, SGameMtl* dst); @@ -326,7 +337,7 @@ class MTL_EXPORT_API CGameMtlLibrary void RemoveMaterialPair(GameMtlPairIt rem_it); void RemoveMaterialPair(int mtl); void RemoveMaterialPair(int mtl0, int mtl1); - GameMtlPairIt GetMaterialPairIt(int id); + GameMtlPairIt GetMaterialPairIt(int id); GameMtlPairIt GetMaterialPairIt(int mtl0, int mtl1); SGameMtlPair* GetMaterialPair(int id); SGameMtlPair* GetMaterialPair(int mtl0, int mtl1); diff --git a/src/xrEngine/IGame_Persistent.cpp b/src/xrEngine/IGame_Persistent.cpp index 3f27910a798..e29339a2cee 100644 --- a/src/xrEngine/IGame_Persistent.cpp +++ b/src/xrEngine/IGame_Persistent.cpp @@ -3,10 +3,11 @@ #include "IGame_Persistent.h" #include "GameFont.h" -#include "PerformanceAlert.hpp" +#include "Common/RDevice.h" #ifndef _EDITOR #include "Environment.h" +#include "PerformanceAlert.hpp" #include "x_ray.h" #include "IGame_Level.h" #include "XR_IOConsole.h" @@ -23,33 +24,37 @@ bool IGame_Persistent::IsMainMenuActive() return g_pGamePersistent && g_pGamePersistent->m_pMainMenu && g_pGamePersistent->m_pMainMenu->IsActive(); } +#ifndef _EDITOR bool IGame_Persistent::MainMenuActiveOrLevelNotExist() { return !g_pGameLevel || g_pGamePersistent->m_pMainMenu && g_pGamePersistent->m_pMainMenu->IsActive(); } +#endif IGame_Persistent::IGame_Persistent() { - Device.seqAppStart.Add(this); - Device.seqAppEnd.Add(this); - Device.seqFrame.Add(this, REG_PRIORITY_HIGH + 1); - Device.seqAppActivate.Add(this); - Device.seqAppDeactivate.Add(this); + RDEVICE.seqAppStart.Add(this); + RDEVICE.seqAppEnd.Add(this); + RDEVICE.seqFrame.Add(this, REG_PRIORITY_HIGH + 1); + RDEVICE.seqAppActivate.Add(this); + RDEVICE.seqAppDeactivate.Add(this); m_pMainMenu = nullptr; +#ifndef _EDITOR pEnvironment = xr_new(); +#endif m_pGShaderConstants = xr_new(); //--#SM+#-- } IGame_Persistent::~IGame_Persistent() { - Device.seqFrame.Remove(this); - Device.seqAppStart.Remove(this); - Device.seqAppEnd.Remove(this); - Device.seqAppActivate.Remove(this); - Device.seqAppDeactivate.Remove(this); + RDEVICE.seqFrame.Remove(this); + RDEVICE.seqAppStart.Remove(this); + RDEVICE.seqAppEnd.Remove(this); + RDEVICE.seqAppActivate.Remove(this); + RDEVICE.seqAppDeactivate.Remove(this); #ifndef _EDITOR xr_delete(pEnvironment); #endif diff --git a/src/xrEngine/IGame_Persistent.h b/src/xrEngine/IGame_Persistent.h index 0aaa926014d..d12dcdc5785 100644 --- a/src/xrEngine/IGame_Persistent.h +++ b/src/xrEngine/IGame_Persistent.h @@ -92,10 +92,10 @@ class ENGINE_API IGame_Persistent : CEnvironment* pEnvironment; CEnvironment& Environment() { return *pEnvironment; }; void Prefetch(); + static bool MainMenuActiveOrLevelNotExist(); #endif IMainMenu* m_pMainMenu; static bool IsMainMenuActive(); - static bool MainMenuActiveOrLevelNotExist(); ParticleStatistics stats; diff --git a/src/xrEngine/ObjectAnimator.cpp b/src/xrEngine/ObjectAnimator.cpp index 188b08d07a8..56a2bb69799 100644 --- a/src/xrEngine/ObjectAnimator.cpp +++ b/src/xrEngine/ObjectAnimator.cpp @@ -133,8 +133,8 @@ float CObjectAnimator::GetLength() const #ifdef _EDITOR -#include "editors/ECore/Editor/d3dutils.h" -#include "envelope.h" +#include "editors/xrECore/Editor/d3dutils.h" +#include "xrCore/Animation/envelope.hpp" static xr_vector path_points; // XXX: can cause crash on launch/exit @@ -160,7 +160,7 @@ void CObjectAnimator::DrawPath() RCache.set_xform_world(Fidentity); if (!path_points.empty()) DU_impl.DrawPrimitiveL( - D3DPT_LINESTRIP, path_points.size() - 1, path_points.begin(), path_points.size(), clr, true, false); + D3DPT_LINESTRIP, path_points.size() - 1, path_points.data(), path_points.size(), clr, true, false); CEnvelope* E = m_Current->Envelope(); for (KeyIt k_it = E->keys.begin(); k_it != E->keys.end(); k_it++) { @@ -168,7 +168,7 @@ void CObjectAnimator::DrawPath() if (EDevice.m_Camera.GetPosition().distance_to_sqr(T) < 50.f * 50.f) { DU_impl.DrawCross(T, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, clr, false); - DU_impl.OutText(T, AnsiString().sprintf("K: %3.3f", (*k_it)->time).c_str(), 0xffffffff, 0x00000000); + DU_impl.OutText(T, make_string("K: %3.3f", (*k_it)->time).c_str(), 0xffffffff, 0x00000000); } } } diff --git a/src/xrEngine/Render.h b/src/xrEngine/Render.h index e5b706f578b..11c2ee2ed91 100644 --- a/src/xrEngine/Render.h +++ b/src/xrEngine/Render.h @@ -1,6 +1,9 @@ #pragma once +#ifndef _EDITOR #include "xrEngine/Engine.h" +#endif + #include "xrCDB/Frustum.h" #include "xrCDB/ISpatial.h" #include "vis_common.h" @@ -330,16 +333,16 @@ class ENGINE_API IRender // Lighting/glowing virtual IRender_Light* light_create() = 0; - virtual void light_destroy(IRender_Light* p_){}; + virtual void light_destroy(IRender_Light* p_) {} virtual IRender_Glow* glow_create() = 0; - virtual void glow_destroy(IRender_Glow* p_){}; + virtual void glow_destroy(IRender_Glow* p_) {} // Models virtual IRenderVisual* model_CreateParticles(pcstr name) = 0; // virtual IRender_DetailModel* model_CreateDM (IReader* F) = 0; // virtual IRenderDetailModel* model_CreateDM (IReader* F) = 0; // virtual IRenderVisual* model_Create (pcstr name, IReader* data=0) = 0; - virtual IRenderVisual* model_Create(pcstr name, IReader* data = 0) = 0; + virtual IRenderVisual* model_Create(pcstr name, IReader* data = nullptr) = 0; virtual IRenderVisual* model_CreateChild(pcstr name, IReader* data) = 0; virtual IRenderVisual* model_Duplicate(IRenderVisual* V) = 0; // virtual void model_Delete (IRenderVisual* & V, bool bDiscard=false) = 0; @@ -362,7 +365,7 @@ class ENGINE_API IRender virtual void BeforeWorldRender() = 0; //--#SM+#-- Перед рендерингом мира virtual void AfterWorldRender() = 0; //--#SM+#-- После рендеринга мира (до UI) - virtual void Screenshot(ScreenshotMode mode = SM_NORMAL, pcstr name = 0) = 0; + virtual void Screenshot(ScreenshotMode mode = SM_NORMAL, pcstr name = nullptr) = 0; virtual void Screenshot(ScreenshotMode mode, CMemoryWriter& memory_writer) = 0; virtual void ScreenshotAsyncBegin() = 0; virtual void ScreenshotAsyncEnd(CMemoryWriter& memory_writer) = 0; diff --git a/src/xrEngine/pure.h b/src/xrEngine/pure.h index 01adba69d05..db40df2b44f 100644 --- a/src/xrEngine/pure.h +++ b/src/xrEngine/pure.h @@ -25,6 +25,10 @@ DECLARE_MESSAGE(AppEnd); DECLARE_MESSAGE(DeviceReset); DECLARE_MESSAGE(UIReset); +#ifdef _EDITOR +DECLARE_MESSAGE(DrawUI); +#endif + template class MessageRegistry { diff --git a/src/xrEngine/stdafx.h b/src/xrEngine/stdafx.h index 24238016600..cdc398bdae7 100644 --- a/src/xrEngine/stdafx.h +++ b/src/xrEngine/stdafx.h @@ -3,7 +3,7 @@ #include "Common/Common.hpp" #ifdef _EDITOR -#include "editors/ECore/stdafx.h" +#include "editors/XrECore/stdafx.h" #else #if 1//ndef NDEBUG diff --git a/src/xrEngine/tntQAVI.cpp b/src/xrEngine/tntQAVI.cpp index 565d5ea0578..f804ede0fa5 100644 --- a/src/xrEngine/tntQAVI.cpp +++ b/src/xrEngine/tntQAVI.cpp @@ -2,6 +2,7 @@ #pragma hdrstop #include "tntQAVI.h" +#include "Common/RDevice.h" #pragma comment(lib, "winmm.lib") @@ -467,10 +468,11 @@ int CAviPlayerCustom::SetSpeed(int nPercent) return res; } + u32 CAviPlayerCustom::CalcFrame() { if (0 == m_dwFirstFrameOffset) - m_dwFirstFrameOffset = Device.dwTimeContinual - 1; + m_dwFirstFrameOffset = RDEVICE.dwTimeContinual - 1; - return u32(floor((Device.dwTimeContinual - m_dwFirstFrameOffset) * m_fCurrentRate / 1000.0f)) % m_dwFrameTotal; + return u32(floor((RDEVICE.dwTimeContinual - m_dwFirstFrameOffset) * m_fCurrentRate / 1000.0f)) % m_dwFrameTotal; } diff --git a/src/xrEngine/xr_input.cpp b/src/xrEngine/xr_input.cpp index 5c07e9387f6..d106a590e05 100644 --- a/src/xrEngine/xr_input.cpp +++ b/src/xrEngine/xr_input.cpp @@ -6,6 +6,7 @@ #include "GameFont.h" #include "xrCore/Text/StringConversion.hpp" #include "xrCore/xr_token.h" +#include "Common/RDevice.h" #include @@ -51,9 +52,9 @@ CInput::CInput(const bool exclusive) SDL_StopTextInput(); // sanity SDL_SetHint(SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4, "1"); // We need to handle it manually - Device.seqAppActivate.Add(this); - Device.seqAppDeactivate.Add(this, REG_PRIORITY_HIGH); - Device.seqFrame.Add(this, REG_PRIORITY_HIGH); + RDEVICE.seqAppActivate.Add(this); + RDEVICE.seqAppDeactivate.Add(this, REG_PRIORITY_HIGH); + RDEVICE.seqFrame.Add(this, REG_PRIORITY_HIGH); if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == 0) { @@ -64,15 +65,17 @@ CInput::CInput(const bool exclusive) CInput::~CInput() { +#ifndef _EDITOR GrabInput(false); +#endif for (auto& controller : controllers) SDL_GameControllerClose(controller); SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER); - Device.seqFrame.Remove(this); - Device.seqAppDeactivate.Remove(this); - Device.seqAppActivate.Remove(this); + RDEVICE.seqFrame.Remove(this); + RDEVICE.seqAppDeactivate.Remove(this); + RDEVICE.seqAppActivate.Remove(this); } void CInput::OpenController(int idx) @@ -215,6 +218,7 @@ void CInput::KeyUpdate() } } +#ifndef _EDITOR if (keyboardState[SDL_SCANCODE_F4] && (keyboardState[SDL_SCANCODE_LALT] || keyboardState[SDL_SCANCODE_RALT])) { AltF4Pressed = true; @@ -222,6 +226,7 @@ void CInput::KeyUpdate() Engine.Event.Defer("KERNEL:quit"); return; } +#endif if (count) SetCurrentInputType(KeyboardMouse); @@ -507,6 +512,7 @@ void CInput::iGetAsyncMousePos(Ivector2& p) const SDL_GetMouseState(&p.x, &p.y); } +#ifndef _EDITOR void CInput::iSetMousePos(const Ivector2& p) const { SDL_WarpMouseInWindow(Device.m_sdlWnd, p.x, p.y); @@ -528,6 +534,7 @@ void CInput::GrabInput(const bool grab) // We're done here. inputGrabbed = grab; } +#endif bool CInput::InputIsGrabbed() const { @@ -613,7 +620,9 @@ void CInput::OnFrame(void) stats.FrameStart(); stats.FrameTime.Begin(); +#ifndef _EDITOR if (Device.dwPrecacheFrame == 0 && !Device.IsAnselActive) +#endif { ControllerUpdate(); KeyUpdate(); @@ -632,6 +641,7 @@ IInputReceiver* CInput::CurrentIR() return nullptr; } +#ifndef _EDITOR void CInput::ExclusiveMode(const bool exclusive) { GrabInput(false); @@ -649,6 +659,7 @@ bool CInput::IsExclusiveMode() const { return exclusiveInput; } +#endif void CInput::Feedback(FeedbackType type, float s1, float s2, float duration) { diff --git a/src/xrEngine/xr_input.h b/src/xrEngine/xr_input.h index b8f0e94486c..897384fcced 100644 --- a/src/xrEngine/xr_input.h +++ b/src/xrEngine/xr_input.h @@ -139,9 +139,12 @@ class ENGINE_API CInput void iGetAsyncScrollPos(Ivector2& p) const; void iGetAsyncMousePos(Ivector2& p) const; - void iSetMousePos(const Ivector2& p) const; +#ifndef _EDITOR + void iSetMousePos(const Ivector2& p) const; void GrabInput(const bool grab); +#endif + bool InputIsGrabbed() const; void RegisterKeyMapChangeWatcher(pureKeyMapChanged* watcher, int priority = REG_PRIORITY_NORMAL); @@ -161,8 +164,12 @@ class ENGINE_API CInput auto GetCurrentInputType() { return currentInputType; } public: + +#ifndef _EDITOR void ExclusiveMode(const bool exclusive); bool IsExclusiveMode() const; +#endif + bool GetKeyName(const int dik, pstr dest, int dest_sz); /** diff --git a/src/xrGame/fs_registrator_script.cpp b/src/xrGame/fs_registrator_script.cpp index a4ffd96e61f..a47071bd6a4 100644 --- a/src/xrGame/fs_registrator_script.cpp +++ b/src/xrGame/fs_registrator_script.cpp @@ -3,7 +3,7 @@ #include "xrScriptEngine/ScriptExporter.hpp" LPCSTR get_file_age_str(CLocatorAPI* fs, LPCSTR nm); -CLocatorAPI* getFS() { return &FS; } +CLocatorAPI* getFS() { return dynamic_cast(&FS); } LPCSTR update_path_script(CLocatorAPI* fs, LPCSTR initial, LPCSTR src) { string_path temp; diff --git a/src/xrPhysics/iphysics_scripted.h b/src/xrPhysics/iphysics_scripted.h index cdab4e4ef15..b78f1502f59 100644 --- a/src/xrPhysics/iphysics_scripted.h +++ b/src/xrPhysics/iphysics_scripted.h @@ -1,6 +1,8 @@ #pragma once +#ifndef _EDITOR #include "xrServerEntities/smart_cast.h" // get_script_wrapper() needs it +#endif class iphysics_scripted; @@ -49,6 +51,7 @@ class cphysics_game_scripted : public iphysics_game_scripted, private Noncopyabl typedef T type_impl; }; +#ifndef _EDITOR template wrap* get_script_wrapper(typename wrap::type_impl& E) { @@ -63,3 +66,4 @@ wrap* get_script_wrapper(typename wrap::type_impl& E) return e; } +#endif diff --git a/src/xrServerEntities/ItemListTypes.h b/src/xrServerEntities/ItemListTypes.h index 50d0c6f6ee8..a1a215f9263 100644 --- a/src/xrServerEntities/ItemListTypes.h +++ b/src/xrServerEntities/ItemListTypes.h @@ -7,7 +7,7 @@ class ListItem { friend class CListHelper; - friend class TItemList; + friend class UIItemListForm; shared_str key; int type; void* item; @@ -17,13 +17,16 @@ class ListItem typedef fastdelegate::FastDelegate1 TOnClick; TOnClick OnClickEvent; TOnListItemFocused OnItemFocused; - TOnDrawThumbnail OnDrawThumbnail; public: +#ifdef XR_PLATFORM_WINDOWS + UIItemListForm* Parent; +#endif int tag; LPVOID m_Object; int icon_index; u32 prop_color; + bool selected; public: enum @@ -39,8 +42,8 @@ class ListItem public: ListItem(int _type) - : type(_type), prop_color(0), item(nullptr), key(nullptr), tag(0), icon_index(-1), OnDrawThumbnail(nullptr), OnItemFocused(nullptr), - m_Object(nullptr) + : type(_type), prop_color(0), item(nullptr), key(nullptr), tag(0), icon_index(-1), OnItemFocused(nullptr), + m_Object(nullptr), selected(false) { m_Flags.zero(); } @@ -54,6 +57,6 @@ class ListItem IC void SetIcon(int index) { icon_index = index; } }; -using ListItemsVec = xr_vector; +DEFINE_VECTOR(ListItem*, ListItemsVec, ListItemsIt); //--------------------------------------------------------------------------- #endif diff --git a/src/xrServerEntities/PropertiesListTypes.h b/src/xrServerEntities/PropertiesListTypes.h index 305eb02a7cf..00dba3bef72 100644 --- a/src/xrServerEntities/PropertiesListTypes.h +++ b/src/xrServerEntities/PropertiesListTypes.h @@ -55,7 +55,7 @@ enum EPropType struct xr_token; class PropValue; class PropItem; -using PropItemVec = xr_vector; +DEFINE_VECTOR(PropItem *, PropItemVec, PropItemIt); //------------------------------------------------------------------------------ #include "xrCore/ChooseTypes.H" @@ -73,7 +73,7 @@ class PropValue PropItem* m_Owner; public: - u32 tag; + size_t tag; // base events typedef fastdelegate::FastDelegate1 TOnChange; @@ -128,7 +128,7 @@ class CustomValue : public PropValue virtual const T& GetValue() { return *value; } virtual void ResetValue() { set_value(*value, init_value); } - + bool ApplyValue(const T& val) { if (!(*value == val)) @@ -143,18 +143,18 @@ class CustomValue : public PropValue class PropItem { friend class CPropHelper; - friend class TProperties; + friend class UIPropertiesForm; shared_str key; EPropType type; void* item; public: - using PropValueVec = xr_vector; + DEFINE_VECTOR(PropValue *, PropValueVec, PropValueIt); private: PropValueVec values; #ifdef XR_PLATFORM_WINDOWS - TProperties* m_Owner; + UIPropertiesForm* m_Owner; #endif // events public: @@ -177,6 +177,7 @@ class PropItem flMixed = (1 << 3), flDrawThumbnail = (1 << 4), flSorted = (1 << 5), + flIgnoreMixed = (1 << 6), }; Flags32 m_Flags; @@ -193,7 +194,7 @@ class PropItem xr_delete(*it); } #ifdef XR_PLATFORM_WINDOWS - TProperties* Owner() { return m_Owner; } + IC UIPropertiesForm* Owner() { return m_Owner; } #endif void SetName(const shared_str& name) { key = name; } @@ -214,7 +215,7 @@ class PropItem xr_string GetDrawText() { VERIFY(!values.empty()); - return m_Flags.is(flMixed) ? xr_string("(mixed)") : values.front()->GetDrawText(OnDrawTextEvent); + return (m_Flags.is(flMixed) && !m_Flags.is(flIgnoreMixed)) ? xr_string("(mixed)") : values.front()->GetDrawText(OnDrawTextEvent); } void CheckMixed() @@ -269,26 +270,27 @@ class PropItem CV->OnChangeEvent(*it); } if (!CV->Equal(values.front())) + { m_Flags.set(flMixed, true); + m_Flags.set(flIgnoreMixed, false); + } } return bChanged; } PropValueVec& Values() { return values; } - + PropValue* GetFrontValue() { VERIFY(!values.empty()); return values.front(); }; EPropType Type() { return type; } -#ifdef __BORLANDC__ - IC TElTreeItem* Item() { return (TElTreeItem*)item; } -#endif + LPCSTR Key() { return key.c_str(); } void Enable(BOOL val) { m_Flags.set(flDisabled, !val); } BOOL Enabled() { return !m_Flags.is(flDisabled); } - + void OnChange() { for (auto it = values.begin(); values.end() != it; ++it) @@ -332,7 +334,7 @@ class CanvasValue : public PropValue public: typedef fastdelegate::FastDelegate3 TOnTestEqual; - typedef fastdelegate::FastDelegate3 TOnDrawCanvasEvent; + typedef fastdelegate::FastDelegate1 TOnDrawCanvasEvent; int height; TOnTestEqual OnTestEqual; @@ -504,7 +506,7 @@ class ChooseValue : public RTextValue ChooseItemVec* m_Items; typedef fastdelegate::FastDelegate1 TOnChooseValueFill; TOnChooseValueFill OnChooseFillEvent; - TOnDrawThumbnail OnDrawThumbnailEvent; + void* m_FillParam; // utils void AppendChooseItem(LPCSTR name, LPCSTR hint) @@ -513,9 +515,9 @@ class ChooseValue : public RTextValue m_Items->push_back(SChooseItem(name, hint)); } - ChooseValue(shared_str* val, u32 cid, LPCSTR path, void* param, u32 sub_item_count, u32 choose_flags) + ChooseValue(shared_str* val, u32 cid, LPCSTR path, void* param, u32 sub_item_count, u32 choose_flags) : RTextValue(val), m_ChooseID(cid), m_StartPath(path), subitem(sub_item_count), m_Items(nullptr), m_FillParam(param), - OnChooseFillEvent(nullptr), OnDrawThumbnailEvent(nullptr), m_ChooseFlags(choose_flags) + OnChooseFillEvent(nullptr), m_ChooseFlags(choose_flags) {} }; @@ -673,7 +675,7 @@ class FlagValue : public CustomValue, public FlagValueCustom FLAG_TYPE mask; - FlagValue(T* val, FLAG_TYPE _mask, LPCSTR c0, LPCSTR c1, u32 flags) + FlagValue(T* val, FLAG_TYPE _mask, LPCSTR c0, LPCSTR c1, u32 flags) : CustomValue(val), FlagValueCustom(flags, c0, c1), mask(_mask) {} diff --git a/src/xrServerEntities/xrEProps.h b/src/xrServerEntities/xrEProps.h index fe0b7443db0..6331cdd66f4 100644 --- a/src/xrServerEntities/xrEProps.h +++ b/src/xrServerEntities/xrEProps.h @@ -1,4 +1,3 @@ -#pragma once #ifndef xrEPropsH #define xrEPropsH @@ -20,21 +19,17 @@ enum EItemType TYPE_OBJECT = 1 }; +typedef fastdelegate::FastDelegate2 TOnItemClone; +typedef fastdelegate::FastDelegate1 TOnItemCreate; + typedef fastdelegate::FastDelegate1 TOnILItemsFocused; typedef fastdelegate::FastDelegate0<> TOnILCloseEvent; typedef fastdelegate::FastDelegate3 TOnItemRename; -typedef fastdelegate::FastDelegate3 TOnItemRemove; +typedef fastdelegate::FastDelegate2 TOnItemRemove; typedef fastdelegate::FastDelegate0<> TOnItemAfterRemove; typedef fastdelegate::FastDelegate0<> TOnCloseEvent; typedef fastdelegate::FastDelegate0<> TOnModifiedEvent; - -#ifdef __BORLANDC__ -#include "mxPlacemnt.hpp" -typedef fastdelegate::FastDelegate1 TOnILItemFocused; -//--------------------------------------------------------------------------- -void XR_EPROPS_API CheckWindowPos(TForm* form); -//--------------------------------------------------------------------------- -#endif +typedef fastdelegate::FastDelegate1 TOnILItemFocused; //------------------------------------------------------------------------------ // Prepare Key @@ -117,7 +112,7 @@ class XR_EPROPS_API IPropHelper PropItemVec& items, shared_str key, Flags16* val, u16 mask, LPCSTR c0 = nullptr, LPCSTR c1 = nullptr, u32 flags = 0) = 0; virtual Flag32Value* CreateFlag32( PropItemVec& items, shared_str key, Flags32* val, u32 mask, LPCSTR c0 = nullptr, LPCSTR c1 = nullptr, u32 flags = 0) = 0; - virtual Token8Value* CreateToken8(PropItemVec& items, shared_str key, u8* val, const xr_token* token) = 0; + virtual Token8Value* CreateToken8(PropItemVec& items, shared_str key, u8* val, xr_token* token) = 0; virtual Token16Value* CreateToken16(PropItemVec& items, shared_str key, u16* val, xr_token* token) = 0; virtual Token32Value* CreateToken32(PropItemVec& items, shared_str key, u32* val, xr_token* token) = 0; virtual RToken8Value* CreateRToken8( @@ -157,13 +152,12 @@ class XR_EPROPS_API IPropHelper PropItemVec& items, shared_str key, u32* val, const TokenValueSH::Item* lst, u32 cnt) = 0; virtual CTextValue* CreateTexture(PropItemVec& items, shared_str key, pstr val, u32 sz) = 0; }; -//--------------------------------------------------------------------------- -#ifdef __BORLANDC__ -extern "C" XR_EPROPS_API IPropHelper& PHelper(); -#else -extern IPropHelper& PHelper(); + +#ifndef XREPROPS_API +#define XREPROPS_API #endif -//--------------------------------------------------------------------------- + +extern XREPROPS_API IPropHelper& PHelper(); //------------------------------------------------------------------------------ // List @@ -179,8 +173,6 @@ class XR_EPROPS_API IListHelper ListItemsVec& items, LPCSTR key, int type, u32 item_flags = 0, void* object = nullptr) = 0; }; -#ifdef __BORLANDC__ -extern "C" XR_EPROPS_API IListHelper& LHelper(); -#endif +XREPROPS_API IListHelper& LHelper(); #endif diff --git a/src/xrServerEntities/xrServer_Objects_ALife.cpp b/src/xrServerEntities/xrServer_Objects_ALife.cpp index c247a6a0616..2102db9ef7d 100644 --- a/src/xrServerEntities/xrServer_Objects_ALife.cpp +++ b/src/xrServerEntities/xrServer_Objects_ALife.cpp @@ -739,7 +739,7 @@ void CSE_ALifeSpaceRestrictor::STATE_Write(NET_Packet& tNetPacket) void CSE_ALifeSpaceRestrictor::UPDATE_Read(NET_Packet& tNetPacket) { inherited1::UPDATE_Read(tNetPacket); } void CSE_ALifeSpaceRestrictor::UPDATE_Write(NET_Packet& tNetPacket) { inherited1::UPDATE_Write(tNetPacket); } -const xr_token defaul_retrictor_types[] = {{"NOT A restrictor", RestrictionSpace::eRestrictorTypeNone}, +xr_token defaul_retrictor_types[] = {{"NOT A restrictor", RestrictionSpace::eRestrictorTypeNone}, {"NONE default restrictor", RestrictionSpace::eDefaultRestrictorTypeNone}, {"OUT default restrictor", RestrictionSpace::eDefaultRestrictorTypeOut}, {"IN default restrictor", RestrictionSpace::eDefaultRestrictorTypeIn}, {nullptr, 0}};