id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,533,650
|
callbackDelay.hpp
|
xavieran_BaKGL/gui/callbackDelay.hpp
|
#pragma once
#include "gui/IAnimator.hpp"
#include <functional>
namespace Gui {
class CallbackDelay : public IAnimator
{
public:
CallbackDelay(
std::function<void()>&& callback,
double delay)
:
mAlive{true},
mDelay{delay},
mCallback{std::move(callback)}
{
}
void OnTimeDelta(double delta) override
{
mDelay -= delta;
if (mDelay <= 0)
{
mCallback();
mAlive = false;
}
}
bool IsAlive() const override
{
return mAlive;
}
bool mAlive;
double mDelay;
std::function<void()> mCallback;
};
}
| 648
|
C++
|
.h
| 34
| 13.235294
| 43
| 0.574257
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,651
|
backgrounds.hpp
|
xavieran_BaKGL/gui/backgrounds.hpp
|
#pragma once
#include "bak/textureFactory.hpp"
#include "graphics/IGuiElement.hpp"
#include "graphics/texture.hpp"
#include "graphics/sprites.hpp"
#include "gui/core/widget.hpp"
#include "gui/colors.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <variant>
namespace Gui {
class Backgrounds
{
public:
Backgrounds(
Graphics::SpriteManager& spriteManager)
:
mSpriteSheet{spriteManager.AddSpriteSheet()},
mScxToSprite{},
mLogger{Logging::LogState::GetLogger("Gui::Backgrounds")}
{
unsigned i = 0;
auto textures = Graphics::TextureStore{};
const auto AddScreen = [this, &i, &textures](
const std::string& scx,
const std::string& pal)
{
mScxToSprite.emplace(
std::make_pair(scx, i++));
BAK::TextureFactory::AddScreenToTextureStore(
textures, scx, pal);
};
const auto AddBackground = [this, &i, &textures](
const std::string& bmx,
const std::string& pal)
{
mScxToSprite.emplace(
std::make_pair(bmx, i++));
BAK::TextureFactory::AddToTextureStore(
textures, bmx, pal);
};
for (const auto& [scx, pal] : {
std::make_pair("ENCAMP.SCX", "OPTIONS.PAL"),
std::make_pair("FRAME.SCX", "OPTIONS.PAL"),
std::make_pair("CONTENTS.SCX", "CONTENTS.PAL"),
std::make_pair("CONT2.SCX", "CONTENTS.PAL"),
std::make_pair("FULLMAP.SCX", "FULLMAP.PAL"),
std::make_pair("RIFTMAP.SCX", "OPTIONS.PAL"),
std::make_pair("INT_BORD.SCX", "FULLMAP.PAL"),
std::make_pair("DIALOG.SCX", "INVENTOR.PAL"),
std::make_pair("INVENTOR.SCX", "INVENTOR.PAL"),
std::make_pair("OPTIONS0.SCX", "OPTIONS.PAL"),
std::make_pair("OPTIONS1.SCX", "OPTIONS.PAL"),
std::make_pair("OPTIONS2.SCX", "OPTIONS.PAL"),
std::make_pair("PUZZLE.SCX", "PUZZLE.PAL"),
std::make_pair("C42.SCX", "TELEPORT.PAL"),
std::make_pair("CAST.SCX", "OPTIONS.PAL"),
std::make_pair("CFRAME.SCX", "OPTIONS.PAL"),
std::make_pair("BOOK.SCX", "BOOK.PAL")
})
{
AddScreen(scx, pal);
}
// Add this screen and cut out the center so we can use
// it in the main view without any scissoring
{
mScxToSprite.emplace(std::make_pair("DIALOG_BG_MAIN.SCX", i++));
BAK::TextureFactory::AddScreenToTextureStore(
textures, "DIALOG.SCX", "OPTIONS.PAL");
auto& tex = textures.GetTexture(i - 1);
for (auto& pixel : tex.GetTexture())
{
if (pixel.a == 0)
{
pixel = Color::black;
}
}
for (unsigned x = 13; x < (294 + 13); x++)
{
for (unsigned y = (200 - 13); y > (200 - (100 + 13)); y--)
{
tex.SetPixel(x, y, glm::vec4{0});
}
}
for (unsigned x = 13; x < (294 + 13); x++)
{
tex.SetPixel(x, (200 - (100 + 13)), Color::frameMaroon);
tex.SetPixel(x, (200 - 13), Color::frameMaroon);
}
for (unsigned y = (200 - 13); y > (200 - (100 + 14)); y--)
{
tex.SetPixel(12, y, Color::frameMaroon);
tex.SetPixel(294 + 13, y, Color::frameMaroon);
}
}
for (const auto& [bmx, pal] : {
std::make_pair("TELEPORT.BMX", "TELEPORT.PAL"),
})
{
AddBackground(bmx, pal);
}
spriteManager
.GetSpriteSheet(mSpriteSheet)
.LoadTexturesGL(textures);
}
Graphics::SpriteSheetIndex GetSpriteSheet() const
{
return mSpriteSheet;
}
Graphics::TextureIndex GetScreen(const std::string& scx) const
{
ASSERT(mScxToSprite.contains(scx));
return mScxToSprite.find(scx)->second;
}
private:
Graphics::SpriteSheetIndex mSpriteSheet;
std::unordered_map<std::string, Graphics::TextureIndex> mScxToSprite;
const Logging::Logger& mLogger;
};
}
| 4,312
|
C++
|
.h
| 120
| 25.6
| 76
| 0.530441
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,652
|
teleportDest.hpp
|
xavieran_BaKGL/gui/teleportDest.hpp
|
#pragma once
#include "com/logger.hpp"
#include "com/visit.hpp"
#include "gui/core/clickable.hpp"
#include "gui/core/highlightable.hpp"
#include "gui/core/widget.hpp"
#include "gui/icons.hpp"
#include <functional>
namespace Gui {
namespace detail {
class TeleportDest : public Widget
{
static constexpr auto sNormalIcon = 15;
static constexpr auto sHighlightedIcon = 13;
public:
TeleportDest(
const Icons& icons,
glm::vec2 pos,
std::function<void(bool)>&& selected)
:
Widget{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(icons.GetTeleportIcon(sNormalIcon)),
std::get<Graphics::TextureIndex>(icons.GetTeleportIcon(sNormalIcon)),
pos,
std::get<glm::vec2>(icons.GetTeleportIcon(sNormalIcon)),
false
},
mIcons{icons},
mSelected{},
mCanReach{},
mCallback{selected}
{
}
void SetSelected()
{
mSelected = true;
SetTexture(std::get<Graphics::TextureIndex>(mIcons.GetTeleportIcon(sHighlightedIcon)));
}
void SetUnselected()
{
mSelected = false;
SetTexture(std::get<Graphics::TextureIndex>(mIcons.GetTeleportIcon(sNormalIcon)));
}
bool OnMouseEvent(const MouseEvent& event) override
{
return false;
}
bool IsCanReach() const
{
return mCanReach;
}
void SetCanReach(bool canReach)
{
mCanReach = canReach;
}
//protected: would be great if concept could enforce
// existence of protected members...
public:
void Entered()
{
if (mSelected) return;
SetTexture(std::get<Graphics::TextureIndex>(mIcons.GetTeleportIcon(sHighlightedIcon)));
mCallback(true);
}
void Exited()
{
if (mSelected) return;
SetTexture(std::get<Graphics::TextureIndex>(mIcons.GetTeleportIcon(sNormalIcon)));
mCallback(false);
}
const Icons& mIcons;
bool mSelected;
bool mCanReach;
std::function<void(bool)> mCallback;
};
}
using TeleportDest = Highlightable<
Clickable<
detail::TeleportDest,
LeftMousePress,
std::function<void()>>,
true>;
}
| 2,221
|
C++
|
.h
| 84
| 20.404762
| 95
| 0.650142
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,653
|
clickButton.hpp
|
xavieran_BaKGL/gui/clickButton.hpp
|
#pragma once
#include "gui/button.hpp"
#include "gui/colors.hpp"
#include "gui/core/mouseEvent.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include "com/assert.hpp"
#include "com/visit.hpp"
#include <variant>
namespace Gui {
class ClickButtonBase : public Widget
{
public:
ClickButtonBase(
glm::vec2 pos,
glm::vec2 dims,
std::function<void()>&& onLeftMousePress,
std::function<void()>&& onRightMousePress)
:
Widget{
RectTag{},
pos,
dims,
glm::vec4{0},
true
},
mLeftPressedCallback{std::move(onLeftMousePress)},
mRightPressedCallback{std::move(onRightMousePress)}
{
ASSERT(mLeftPressedCallback);
ASSERT(mRightPressedCallback);
}
bool OnMouseEvent(const MouseEvent& event) override
{
return std::visit(overloaded{
[this](const LeftMousePress& p){ return LeftMousePressed(p.mValue); },
[this](const RightMousePress& p){ return RightMousePressed(p.mValue); },
[](const auto& p){ return false; }
},
event);
}
bool LeftMousePressed(glm::vec2 click)
{
if (Within(click))
{
Logging::LogSpam("ClickButtonBase") << "Got LMC: " << this << " " << click << std::endl;
std::invoke(mLeftPressedCallback);
return true;
}
return false;
}
bool RightMousePressed(glm::vec2 click)
{
if (Within(click))
{
Logging::LogSpam("ClickButtonBase") << "Got RMC: " << this << " " << click << std::endl;
std::invoke(mRightPressedCallback);
return true;
}
return false;
}
private:
std::function<void()> mLeftPressedCallback;
std::function<void()> mRightPressedCallback;
};
class ClickButton : public ClickButtonBase
{
public:
ClickButton(
glm::vec2 pos,
glm::vec2 dims,
const Font& font,
const std::string& label,
std::function<void()>&& onLeftMousePress)
:
ClickButtonBase{
pos,
dims,
std::move(onLeftMousePress),
[](){}
},
mFont{font},
mNormal{
glm::vec2{0, 0},
dims,
Color::buttonBackground,
Color::buttonHighlight,
Color::buttonShadow},
mPressed{
glm::vec2{0, 0},
dims,
Color::buttonPressed,
Color::buttonShadow,
Color::buttonHighlight},
mButtonPressed{false},
mText{
glm::vec2{3, 2},
dims}
{
SetText(label);
AddChildren();
}
void SetText(std::string_view label)
{
const auto textPos = glm::vec2{3, 2};
const auto& dims = GetPositionInfo().mDimensions;
const auto& [endPos, text] = mText.SetText(mFont, label);
mText.SetPosition(
glm::vec2{
textPos.x + (dims.x - endPos.x) / 2,
textPos.y});
}
bool OnMouseEvent(const MouseEvent& event) override
{
const bool dirty = std::visit(overloaded{
[this](const LeftMousePress& p){ return LeftMousePressed(p.mValue); },
[this](const LeftMouseRelease& p){ return LeftMouseReleased(p.mValue); },
[this](const MouseMove& p){ return MouseMoved(p.mValue); },
[](const auto& p){ return false; }
},
event);
const bool handled = ClickButtonBase::OnMouseEvent(event);
if (dirty || std::holds_alternative<LeftMouseRelease>(event))
{
AddChildren();
}
return handled;
}
bool LeftMousePressed(glm::vec2 click)
{
if (Within(click))
{
return UpdateState(true);
}
return false;
}
bool LeftMouseReleased(glm::vec2 click)
{
UpdateState(false);
return false;
}
bool MouseMoved(glm::vec2 pos)
{
if (!Within(pos))
{
return UpdateState(false);
}
return false;
}
private:
void AddChildren()
{
ClearChildren();
if (mButtonPressed)
{
AddChildBack(&mPressed);
}
else
{
AddChildBack(&mNormal);
}
AddChildBack(&mText);
}
bool UpdateState(bool newState)
{
const bool tmp = mButtonPressed;
mButtonPressed = newState;
return mButtonPressed != tmp;
}
const Font& mFont;
Button mNormal;
Button mPressed;
bool mButtonPressed;
TextBox mText;
};
class ClickButtonImage : public ClickButtonBase
{
public:
ClickButtonImage(
glm::vec2 pos,
glm::vec2 dims,
Graphics::SpriteSheetIndex spriteSheet,
Graphics::TextureIndex normal,
Graphics::TextureIndex pressed,
std::function<void()>&& onLeftMousePress,
std::function<void()>&& onRightMousePress)
:
ClickButtonBase{
pos,
dims,
std::move(onLeftMousePress),
std::move(onRightMousePress)
},
mIsPressed{false},
mNormal{
Graphics::DrawMode::Sprite,
spriteSheet,
normal,
Graphics::ColorMode::Texture,
Color::black,
glm::vec2{0},
dims,
true},
mPressed{
Graphics::DrawMode::Sprite,
spriteSheet,
pressed,
Graphics::ColorMode::Texture,
Color::black,
glm::vec2{0},
dims,
true}
{
AddChildren();
}
bool OnMouseEvent(const MouseEvent& event) override
{
std::visit(overloaded{
[this](const LeftMousePress& p){ return LeftMousePressed(p.mValue); },
[this](const LeftMouseRelease& p){ return LeftMouseReleased(p.mValue); },
[this](const MouseMove& p){ return MouseMoved(p.mValue); },
[](const auto& p){ return false; }
},
event);
return ClickButtonBase::OnMouseEvent(event);
}
bool LeftMousePressed(glm::vec2 click)
{
if (Within(click))
{
mIsPressed = true;
AddChildren();
}
return false;
}
bool LeftMouseReleased(glm::vec2 click)
{
mIsPressed = false;
AddChildren();
return false;
}
bool MouseMoved(glm::vec2 pos)
{
if (!Within(pos))
{
mIsPressed = false;
AddChildren();
}
return false;
}
void CenterImage(glm::vec2 dims)
{
// Set the image to its normal size and center it
mNormal.SetDimensions(dims);
mNormal.SetCenter(GetCenter() - GetTopLeft());
mPressed.SetDimensions(dims);
mPressed.SetCenter(GetCenter() - GetTopLeft());
}
void SetTexture(Graphics::SpriteSheetIndex ss, Graphics::TextureIndex ti)
{
mNormal.SetSpriteSheet(ss);
mNormal.SetTexture(ti);
mPressed.SetSpriteSheet(ss);
mPressed.SetTexture(ti);
}
void SetColor(glm::vec4 color)
{
mNormal.SetColor(color);
mPressed.SetColor(color);
}
void SetColorMode(Graphics::ColorMode mode)
{
mNormal.SetColorMode(mode);
mPressed.SetColorMode(mode);
}
private:
void AddChildren()
{
ClearChildren();
if (mIsPressed)
{
AddChildBack(&mPressed);
}
else
{
AddChildBack(&mNormal);
}
}
bool mIsPressed;
Widget mNormal;
Widget mPressed;
};
}
| 7,792
|
C++
|
.h
| 293
| 18.146758
| 100
| 0.556524
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,654
|
compass.hpp
|
xavieran_BaKGL/gui/compass.hpp
|
#pragma once
#include "bak/coordinates.hpp"
#include "com/logger.hpp"
#include "gui/button.hpp"
#include "gui/colors.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
namespace Gui {
class Compass : public Widget
{
public:
Compass(
glm::vec2 pos,
glm::vec2 dims,
glm::vec2 compassSheetDims,
Graphics::SpriteSheetIndex spriteSheet,
Graphics::TextureIndex texture)
:
Widget{
ClipRegionTag{},
pos,
dims,
true
},
mCompassLeft{
Graphics::DrawMode::Sprite,
spriteSheet,
texture,
Graphics::ColorMode::Texture,
Color::debug,
glm::vec2{-compassSheetDims.x, 0},
compassSheetDims,
true},
mCompassCenter{
Graphics::DrawMode::Sprite,
spriteSheet,
texture,
Graphics::ColorMode::Texture,
Color::debug,
glm::vec2{0},
compassSheetDims,
true},
mCompassDims{compassSheetDims},
mHeading{0}
{
AddChildBack(&mCompassLeft);
AddChildBack(&mCompassCenter);
}
void SetHeading(BAK::GameHeading gameHeading)
{
const double heading = static_cast<double>(gameHeading) / static_cast<double>(0xff);
mHeading = heading;
UpdateCompassHeading(mCompassLeft, -mCompassDims.x);
UpdateCompassHeading(mCompassCenter, 0);
}
private:
void UpdateCompassHeading(Widget& compass, double zeroedXPos)
{
const auto newX = mHeading * compass.GetPositionInfo().mDimensions.x;
compass.SetPosition(
glm::vec2{
newX + zeroedXPos,
0});
}
Widget mCompassLeft;
Widget mCompassCenter;
glm::vec2 mCompassDims;
double mHeading;
};
}
| 1,890
|
C++
|
.h
| 70
| 18.814286
| 92
| 0.595909
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,655
|
fontManager.hpp
|
xavieran_BaKGL/gui/fontManager.hpp
|
#pragma once
#include "bak/font.hpp"
#include "bak/fileBufferFactory.hpp"
#include "graphics/glm.hpp"
#include "graphics/sprites.hpp"
namespace Gui {
class Font
{
public:
Font(
const std::string& font,
Graphics::SpriteManager& spriteManager)
:
mFont{std::invoke([&]{
auto fb = BAK::FileBufferFactory::Get().CreateDataBuffer(font);
return BAK::LoadFont(fb);
})},
mSpriteSheet{spriteManager.AddSpriteSheet()}
{
spriteManager.GetSpriteSheet(mSpriteSheet)
.LoadTexturesGL(mFont.GetCharacters());
}
const auto& GetFont() const { return mFont; }
const auto& GetSpriteSheet() const { return mSpriteSheet; }
private:
BAK::Font mFont;
Graphics::SpriteSheetIndex mSpriteSheet;
};
class FontManager
{
public:
FontManager(
Graphics::SpriteManager& spriteManager)
:
mAlien{"ALIEN.FNT", spriteManager},
mBook{"BOOK.FNT", spriteManager},
mGame{"GAME.FNT", spriteManager},
mPuzzle{"PUZZLE.FNT", spriteManager},
mSpell{"SPELL.FNT", spriteManager}
{}
const Font& GetAlienFont() const { return mAlien; }
const Font& GetBookFont() const { return mBook; }
const Font& GetGameFont() const { return mGame; }
const Font& GetPuzzleFont() const { return mPuzzle; }
const Font& GetSpellFont() const { return mSpell; }
private:
Font mAlien;
Font mBook;
Font mGame;
Font mPuzzle;
Font mSpell;
};
}
| 1,497
|
C++
|
.h
| 53
| 22.943396
| 75
| 0.666899
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,656
|
centeredImage.hpp
|
xavieran_BaKGL/gui/centeredImage.hpp
|
#pragma once
#include "gui/core/widget.hpp"
namespace Gui {
class CenteredImage : public Widget
{
public:
CenteredImage(
glm::vec2 pos,
glm::vec2 dims)
:
Widget{
RectTag{},
pos,
dims,
//glm::vec4{1,0,0,.3},
glm::vec4{},
true
},
mImage{
ImageTag{},
Graphics::SpriteSheetIndex{0},
Graphics::TextureIndex{0},
pos,
glm::vec2{},
true
}
{
AddChildren();
}
void SetImage(
Graphics::SpriteSheetIndex spriteSheet,
Graphics::TextureIndex textureIndex,
glm::vec2 dims)
{
mImage.SetSpriteSheet(spriteSheet);
mImage.SetTexture(textureIndex);
mImage.SetDimensions(dims);
mImage.SetCenter(GetCenter() - GetTopLeft());
}
private:
void AddChildren()
{
ClearChildren();
AddChildBack(&mImage);
}
Widget mImage;
};
}
| 1,021
|
C++
|
.h
| 48
| 13.520833
| 53
| 0.531606
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,657
|
staticTTM.hpp
|
xavieran_BaKGL/gui/staticTTM.hpp
|
#pragma once
#include "bak/scene.hpp"
#include "com/logger.hpp"
#include "graphics/guiTypes.hpp"
#include "graphics/sprites.hpp"
#include "gui/scene.hpp"
#include "gui/core/widget.hpp"
namespace Gui {
/*
* Display a static TTM, e.g. Lamut, Inn, etc.
* */
class StaticTTM
{
public:
StaticTTM(
Graphics::SpriteManager& spriteManager,
const BAK::Scene& sceneInit,
const BAK::Scene& sceneContent);
Widget* GetScene();
Widget* GetBackground();
private:
Graphics::SpriteManager::TemporarySpriteSheet mSpriteSheet;
Widget mSceneFrame;
std::optional<Widget> mDialogBackground;
std::vector<Widget> mSceneElements;
std::optional<Widget> mClipRegion;
const Logging::Logger& mLogger;
};
}
| 750
|
C++
|
.h
| 29
| 22.344828
| 63
| 0.727145
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,658
|
IGuiManager.hpp
|
xavieran_BaKGL/gui/IGuiManager.hpp
|
#pragma once
#include "gui/IDialogScene.hpp"
#include "gui/screenStack.hpp"
#include "gui/IAnimator.hpp"
#include "bak/dialog.hpp"
#include "bak/cutscenes.hpp"
#include "bak/entityType.hpp"
#include "bak/encounter/teleport.hpp"
#include "bak/hotspot.hpp"
#include "bak/saveManager.hpp"
#include "bak/types.hpp"
namespace Gui {
class IGuiManager
{
public:
virtual void DoFade(double duration, std::function<void()>&&) = 0;
virtual bool InMainView() const = 0;
virtual void EnterMainView() = 0;
virtual void EnterMainMenu(bool gameRunning) = 0;
virtual void EnterGDSScene(
const BAK::HotspotRef&,
std::function<void()>&& finished) = 0;
virtual void ExitGDSScene() = 0;
virtual void StartDialog(BAK::Target, bool tooltip, bool drawWorldFrame, IDialogScene*) = 0;
virtual void PlayCutscene(std::vector<BAK::CutsceneAction> actions, std::function<void()>&&) = 0;
virtual void DoChapterTransition() = 0;
virtual void ShowCharacterPortrait(BAK::ActiveCharIndex) = 0;
virtual void ExitSimpleScreen() = 0;
virtual void ShowInventory(BAK::ActiveCharIndex) = 0;
virtual void ShowContainer(BAK::GenericContainer*, BAK::EntityType containerType) = 0;
virtual void SelectItem(std::function<void(std::optional<std::pair<BAK::ActiveCharIndex, BAK::InventoryIndex>>)>&&) = 0;
virtual void ExitInventory() = 0;
virtual void ShowLock(BAK::IContainer*, std::function<void()>&& finished) = 0;
virtual void ShowCamp(bool isInn, BAK::ShopStats* inn) = 0;
virtual void ShowCast(bool inCombat) = 0;
virtual void ShowFullMap() = 0;
virtual void ShowGameStartMap() = 0;
virtual void ShowTeleport(unsigned sourceTemple, BAK::ShopStats* temple) = 0;
virtual void ShowCureScreen(
unsigned templeNumber,
unsigned cureFactor,
std::function<void()>&& finished) = 0;
virtual void ExitLock() = 0;
virtual bool IsLockOpened() const = 0;
virtual bool IsWordLockOpened() const = 0;
virtual void AddAnimator(std::unique_ptr<IAnimator>&&) = 0;
virtual ScreenStack& GetScreenStack() = 0;
virtual void LoadGame(std::string, std::optional<BAK::Chapter>) = 0;
virtual void SaveGame(const BAK::SaveFile&) = 0;
virtual void DoTeleport(BAK::Encounter::Teleport) = 0;
};
}
| 2,298
|
C++
|
.h
| 52
| 39.865385
| 124
| 0.717421
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,659
|
choiceScreen.hpp
|
xavieran_BaKGL/gui/choiceScreen.hpp
|
#pragma once
#include "bak/dialog.hpp"
#include "bak/gameState.hpp"
#include "bak/types.hpp"
#include "com/algorithm.hpp"
#include "com/assert.hpp"
#include "com/ostream.hpp"
#include "com/visit.hpp"
#include "gui/clickButton.hpp"
#include "gui/colors.hpp"
#include "gui/screenStack.hpp"
#include "gui/core/widget.hpp"
namespace Gui {
class ChoiceScreen : public Widget
{
public:
using FinishedCallback = std::function<void(BAK::ChoiceIndex)>;
static constexpr auto mMaxChoices = 16;
ChoiceScreen(
glm::vec2 pos,
glm::vec2 dims,
const Font& font,
ScreenStack& screenStack,
FinishedCallback&& finished)
:
Widget{
RectTag{},
pos,
dims,
glm::vec4{0},
true
},
mButtons{},
mFont{font},
mScreenStack{screenStack},
mFinished{std::move(finished)},
mLogger{Logging::LogState::GetLogger("Gui::ChoiceScreen")}
{
ASSERT(mFinished);
// there's never more than this many choices
mButtons.reserve(mMaxChoices);
}
void StartChoices(
const std::vector<std::pair<BAK::ChoiceIndex, std::string>>& choices,
glm::vec2 buttonSize)
{
mLogger.Debug() << __FUNCTION__ << " choices: " << choices << "\n";
ClearChildren();
mButtons.clear();
ASSERT(choices.size() <= mMaxChoices);
auto pos = glm::vec2{0};
const auto margin = 5;
const auto limit = GetPositionInfo().mDimensions;
for (const auto& [index, label] : choices)
{
mButtons.emplace_back(
pos,
buttonSize,
mFont,
label,
[this, choice=index](){
Choose(choice);
});
pos.x += buttonSize.x + margin;
// if the next button would overflow...
if ((pos.x + buttonSize.x) > limit.x)
{
pos.x = 0;
pos.y += buttonSize.y + margin;
}
}
for (auto& button : mButtons)
AddChildBack(&button);
}
void Choose(BAK::ChoiceIndex index)
{
std::invoke(mFinished, index);
}
private:
std::vector<ClickButton> mButtons;
const Font& mFont;
ScreenStack& mScreenStack;
FinishedCallback mFinished;
const Logging::Logger& mLogger;
};
}
| 2,441
|
C++
|
.h
| 86
| 20.325581
| 77
| 0.567949
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,660
|
list.hpp
|
xavieran_BaKGL/gui/list.hpp
|
#pragma once
#include "gui/backgrounds.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
namespace Gui {
template <ImplementsWidget T>
class List : public Widget
{
public:
List(
std::size_t expectedSize,
float spacing,
bool isVerticallyAligned)
:
Widget{
RectTag{},
glm::vec2{0, 0},
glm::vec2{0, 0},
Color::black,
true
},
mMultiplier{
isVerticallyAligned ? 0 : 1,
isVerticallyAligned ? 1 : 0},
mSpacing{spacing},
mEnd{0, 0},
mElements{},
mLogger{Logging::LogState::GetLogger("Gui::List")}
{
//mElements.reserve(expectedSize);
}
template <typename ...Args>
void AddWidget(Args&&... args)
{
ClearChildren();
auto& widget = mElements.emplace_back(std::make_unique<T>(std::forward<Args>(args)...));
widget->SetPosition(widget->GetPositionInfo().mPosition + mEnd);
mEnd += widget->GetPositionInfo().mDimensions * mMultiplier;
mEnd += mSpacing * mMultiplier;
AddChildren();
SetDimensions(mEnd + glm::vec2{widget->GetPositionInfo().mDimensions.x, 0});
}
void ClearWidgets()
{
ClearChildren();
mElements.clear();
mEnd = glm::vec2{0, 0};
SetDimensions(mEnd);
}
private:
void AddChildren()
{
ClearChildren();
for (auto& widget : mElements)
{
AddChildBack(widget.get());
}
}
glm::vec2 mMultiplier;
float mSpacing;
glm::vec2 mEnd;
// Because mElements can grow, make these unique_ptrs so that
// they remain stable when mElements grows and they are moved.
std::vector<std::unique_ptr<T>> mElements;
const Logging::Logger& mLogger;
};
}
| 1,916
|
C++
|
.h
| 70
| 20.671429
| 96
| 0.601524
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,661
|
contents.hpp
|
xavieran_BaKGL/gui/contents.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include "bak/cutscenes.hpp"
#include "bak/types.hpp"
#include <glm/glm.hpp>
namespace Gui {
class ContentsScreen: public Widget
{
public:
static constexpr auto sLayoutFile = "CONTENTS.DAT";
//static constexpr auto sBackground = "CONT2.SCX";
static constexpr auto sBackground = "CONTENTS.SCX";
static constexpr auto sUnlockedChapters = "CONTENTS.SCX";
static constexpr auto sExit = 9;
using LeaveContentsFn = std::function<void()>;
ContentsScreen(
IGuiManager& guiManager,
Graphics::SpriteManager& spriteManager,
const Backgrounds& backgrounds,
const Font& font,
LeaveContentsFn&& leaveContentsFn)
:
Widget{
RectTag{},
glm::vec2{0, 0},
glm::vec2{320, 200},
Color::black,
false
},
mGuiManager{guiManager},
mSpriteSheet{spriteManager.AddTemporarySpriteSheet()},
mFont{font},
mBackgrounds{backgrounds},
mLayout{sLayoutFile},
mLeaveContentsFn{std::move(leaveContentsFn)},
mFrame{
ImageTag{},
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen(sBackground),
glm::vec2{0},
GetPositionInfo().mDimensions,
true
},
mChapterButtons{},
mExit{
mLayout.GetWidgetLocation(sExit),
mLayout.GetWidgetDimensions(sExit),
mFont,
"#Exit",
[this]{ std::invoke(mLeaveContentsFn); }
},
mLogger{Logging::LogState::GetLogger("Gui::ContentsScreen")}
{
auto screen = Graphics::TextureStore{};
BAK::TextureFactory::AddScreenToTextureStore(screen, sUnlockedChapters, "CONTENTS.PAL");
const auto source = screen.GetTexture(0);
auto textures = Graphics::TextureStore{};
for (unsigned i = 0; i < 9; i++)
{
textures.AddTexture(
source.GetRegion(
// Why this offset... ?
mLayout.GetWidgetLocation(i) + glm::vec2{0, 17},
mLayout.GetWidgetDimensions(i)));
}
spriteManager.GetSpriteSheet(mSpriteSheet->mSpriteSheet).LoadTexturesGL(textures);
AddChildren();
}
private:
void AddChildren()
{
ClearChildren();
AddChildBack(&mFrame);
mChapterButtons.clear();
mChapterButtons.reserve(9);
for (unsigned i = 0 ; i < 9; i++)
{
mChapterButtons.emplace_back(
[this, i]()
{
PlayChapter(BAK::Chapter{i + 1});
},
ImageTag{},
mSpriteSheet->mSpriteSheet,
Graphics::TextureIndex{8 - i},
mLayout.GetWidgetLocation(i),
mLayout.GetWidgetDimensions(i),
false);
AddChildBack(&mChapterButtons.back());
}
mExit.SetPosition(mLayout.GetWidgetLocation(sExit));
AddChildBack(&mExit);
}
void PlayChapter(BAK::Chapter chapter)
{
auto start = BAK::CutsceneList::GetStartScene(chapter);
auto finish = BAK::CutsceneList::GetFinishScene(chapter);
start.insert(start.end(), finish.begin(), finish.end());
mGuiManager.PlayCutscene(start, []{});
}
IGuiManager& mGuiManager;
Graphics::SpriteManager::TemporarySpriteSheet mSpriteSheet;
const Font& mFont;
const Backgrounds& mBackgrounds;
BAK::Layout mLayout;
LeaveContentsFn mLeaveContentsFn;
using ChapterButton = Clickable<Widget, LeftMousePress, std::function<void()>>;
Widget mFrame;
std::vector<ChapterButton> mChapterButtons;
ClickButton mExit;
const Logging::Logger& mLogger;
};
}
| 4,037
|
C++
|
.h
| 120
| 24.925
| 96
| 0.613963
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,662
|
teleportScreen.hpp
|
xavieran_BaKGL/gui/teleportScreen.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "bak/dialogSources.hpp"
#include "bak/encounter/teleport.hpp"
#include "bak/layout.hpp"
#include "bak/shop.hpp"
#include "bak/sounds.hpp"
#include "bak/temple.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/teleportDest.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class TeleportScreen : public Widget, public IDialogScene
{
enum class State
{
Idle,
Teleported,
Cancelled
};
public:
static constexpr auto sLayoutFile = "REQ_TELE.DAT";
static constexpr auto sCancelWidget = 12;
TeleportScreen(
IGuiManager& guiManager,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font,
BAK::GameState& gameState)
:
Widget{
Graphics::DrawMode::Sprite,
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen("DIALOG.SCX"),
Graphics::ColorMode::Texture,
glm::vec4{1},
glm::vec2{0},
glm::vec2{320, 200},
true
},
mGuiManager{guiManager},
mFont{font},
mGameState{gameState},
mIcons{icons},
mLayout{sLayoutFile},
mState{State::Idle},
mSource{},
mHighlightedDest{},
mChosenDest{},
mNeedRefresh{false},
mTeleportWord{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(icons.GetTeleportIcon(12)),
std::get<Graphics::TextureIndex>(icons.GetTeleportIcon(12)),
glm::vec2{30, 10},
std::get<glm::vec2>(icons.GetTeleportIcon(12)),
false
},
mTeleportFromText{
glm::vec2{30, 36},
glm::vec2{80, 40}
},
mTeleportFrom{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(icons.GetTeleportIcon(0)),
std::get<Graphics::TextureIndex>(icons.GetTeleportIcon(0)),
glm::vec2{40, 58},
std::get<glm::vec2>(icons.GetTeleportIcon(0)),
false
},
mTeleportToText{
glm::vec2{30, 108},
glm::vec2{80, 40}
},
mTeleportTo{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(icons.GetTeleportIcon(1)),
std::get<Graphics::TextureIndex>(icons.GetTeleportIcon(1)),
glm::vec2{40, 130},
std::get<glm::vec2>(icons.GetTeleportIcon(1)),
false
},
mCostText{
glm::vec2{18, 180},
glm::vec2{180, 40}
},
mMapSnippet{
ClipRegionTag{},
glm::vec2{127, 15},
glm::vec2{172, 160},
false
},
mMap{
Graphics::DrawMode::Sprite,
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen("FULLMAP.SCX"),
Graphics::ColorMode::Texture,
glm::vec4{1},
glm::vec2{23, 2},
glm::vec2{320, 200},
true
},
mCancelButton{
mLayout.GetWidgetLocation(sCancelWidget),
mLayout.GetWidgetDimensions(sCancelWidget),
mFont,
"#Cancel",
[this]{
if (mState != State::Cancelled)
{
mState = State::Cancelled;
mGuiManager.StartDialog(BAK::DialogSources::mTeleportDialogCancel, false, false, this);
}
}
},
mTeleportDests{},
mLogger{Logging::LogState::GetLogger("Gui::TeleportScreen")}
{
mTeleportDests.reserve(mLayout.GetSize());
for (unsigned i = 0; i < mLayout.GetSize() - 1; i++)
{
mTeleportDests.emplace_back(
[this, i=i]{
HandleTempleClicked(i + 1);
},
icons,
mLayout.GetWidgetLocation(i),
[this, i=i](bool selected){
HandleTempleHighlighted(i + 1, selected);
}
);
}
mTeleportFromText.SetText(mFont, "From:", true);
mTeleportToText.SetText(mFont, "To:", true);
mCostText.SetText(mFont, "Cost: ");
mMapSnippet.AddChildBack(&mMap);
AddChildren();
}
void DisplayNPCBackground() override {}
void DisplayPlayerBackground() override {}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice) override
{
mLogger.Debug() << "Finished dialog with choice : " << choice << "\n";
if (mState == State::Cancelled)
{
mGuiManager.DoFade(.8, [this]{
mGuiManager.ExitSimpleScreen();
});
}
else if (mState == State::Teleported)
{
ASSERT(mChosenDest);
mGuiManager.ExitSimpleScreen();
// This is probably a hack, likely need to fix this for other teleport things..
AudioA::AudioManager::Get().PopTrack();
auto factory = BAK::Encounter::TeleportFactory{};
mGuiManager.DoTeleport(factory.Get(*mChosenDest - 1));
}
}
void SetSourceTemple(unsigned sourceTemple, BAK::ShopStats* temple)
{
mState = State::Idle;
assert(temple);
mTemple = temple;
mSource = sourceTemple;
mChosenDest = std::nullopt;
for (unsigned i = 0; i < mTeleportDests.size(); i++)
{
if (sourceTemple - 1 == i)
{
mTeleportDests.at(i).SetSelected();
mTeleportFromText.SetText(mFont, MakeTempleString("From:", sourceTemple), true);
}
else
{
mTeleportDests.at(i).SetUnselected();
}
mTeleportDests.at(i).SetCanReach(true);//mGameState.GetTempleSeen(i + 1));
}
AddChildren();
}
bool OnMouseEvent(const MouseEvent& me) override
{
const bool result = Widget::OnMouseEvent(me);
if (mNeedRefresh)
{
AddChildren();
mNeedRefresh = false;
}
return result;
}
private:
void HandleTempleClicked(unsigned templeNumber)
{
if (templeNumber == mSource)
{
mGuiManager.StartDialog(BAK::DialogSources::mTeleportDialogTeleportedToSameTemple, false, false, this);
}
else if (mGameState.GetChapter() == BAK::Chapter{6}
&& templeNumber == BAK::Temple::sChapelOfIshap
&& !mGameState.ReadEventBool(BAK::GameData::sPantathiansEventFlag))
{
mGuiManager.StartDialog(BAK::DialogSources::mTeleportDialogTeleportBlockedMalacsCrossDest, false, false, this);
}
else
{
const auto cost = CalculateCost(templeNumber);
if (cost < mGameState.GetMoney())
{
mGameState.GetParty().LoseMoney(cost);
mState = State::Teleported;
mChosenDest = templeNumber;
AudioA::AudioManager::Get().PlaySound(AudioA::SoundIndex{BAK::sTeleportSound});
mGuiManager.StartDialog(BAK::DialogSources::mTeleportDialogPostTeleport, false, false, this);
}
else
{
mGuiManager.StartDialog(BAK::DialogSources::mTeleportDialogCantAfford, false, false, this);
}
}
}
void HandleTempleHighlighted(unsigned templeNumber, bool selected)
{
if (selected)
{
mHighlightedDest = templeNumber;
mTeleportToText.SetText(mFont, MakeTempleString("To:", templeNumber), true);
mCostText.SetText(mFont, MakeCostString(templeNumber));
mTeleportTo.SetTexture(std::get<Graphics::TextureIndex>(mIcons.GetTeleportIcon(templeNumber - 1)));
}
else
{
mTeleportToText.SetText(mFont, "To:", true);
mCostText.SetText(mFont, "Cost: ");
mHighlightedDest.reset();
}
mNeedRefresh = true;
}
std::string MakeTempleString(const std::string& prefix, unsigned templeNumber)
{
std::stringstream ss{};
ss << prefix << "\n#" << mLayout.GetWidget(templeNumber - 1).mLabel;
return ss.str();
}
std::string MakeCostString(unsigned templeNumber)
{
std::stringstream ss{};
ss << "Cost: " << BAK::ToShopDialogString(CalculateCost(templeNumber));
return ss.str();
}
void AddChildren()
{
ClearChildren();
AddChildBack(&mMapSnippet);
AddChildBack(&mTeleportWord);
AddChildBack(&mTeleportFromText);
AddChildBack(&mTeleportFrom);
AddChildBack(&mTeleportToText);
if (mHighlightedDest)
{
AddChildBack(&mTeleportTo);
}
AddChildBack(&mCostText);
for (auto& dst : mTeleportDests)
{
if (dst.IsCanReach())
AddChildBack(&dst);
}
AddChildBack(&mCancelButton);
}
private:
BAK::Royals CalculateCost(unsigned templeNumber)
{
assert(mTemple);
const auto srcPos = mLayout.GetWidget(mSource - 1).mPosition;
const auto dstPos = mLayout.GetWidget(templeNumber - 1).mPosition;
return BAK::Temple::CalculateTeleportCost(
mSource,
templeNumber,
srcPos,
dstPos,
mTemple->mHaggleAnnoyanceFactor,
mTemple->mCategories);
}
IGuiManager& mGuiManager;
const Font& mFont;
BAK::GameState& mGameState;
const Icons& mIcons;
BAK::Layout mLayout;
State mState;
unsigned mSource;
BAK::ShopStats* mTemple;
std::optional<unsigned> mHighlightedDest;
std::optional<unsigned> mChosenDest;
bool mNeedRefresh;
Widget mTeleportWord;
TextBox mTeleportFromText;
Widget mTeleportFrom;
TextBox mTeleportToText;
Widget mTeleportTo;
TextBox mCostText;
Widget mMapSnippet;
Widget mMap;
ClickButton mCancelButton;
std::vector<TeleportDest> mTeleportDests;
const Logging::Logger& mLogger;
};
}
| 10,298
|
C++
|
.h
| 316
| 23.113924
| 123
| 0.581531
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,663
|
symbol.hpp
|
xavieran_BaKGL/gui/cast/symbol.hpp
|
#pragma once
#include "bak/gameState.hpp"
#include "bak/spells.hpp"
#include "gui/fontManager.hpp"
#include "gui/core/line.hpp"
#include "gui/core/clickable.hpp"
#include "gui/core/highlightable.hpp"
#include "gui/core/widget.hpp"
namespace Gui::Cast {
namespace detail {
class Icon : public Widget
{
public:
Icon(
unsigned icon,
glm::vec2 pos,
const Font& font,
std::function<void(bool)>&& selected)
:
Widget{
Graphics::DrawMode::Sprite,
font.GetSpriteSheet(),
static_cast<Graphics::TextureIndex>(
font.GetFont().GetIndex(icon + 1)),
Graphics::ColorMode::Texture,
glm::vec4{1.0f, 0.f, 0.f, 1.f},
pos,
glm::vec2{font.GetFont().GetWidth(icon), font.GetFont().GetHeight()},
true},
mCallback{selected}
{
}
void SetHighlighted()
{
SetColorMode(Graphics::ColorMode::ReplaceColor);
}
public:
void Entered()
{
SetColorMode(Graphics::ColorMode::TintColor);
mCallback(true);
}
void Exited()
{
SetColorMode(Graphics::ColorMode::Texture);
mCallback(false);
}
std::function<void(bool)> mCallback;
};
}
class Symbol : public Widget
{
public:
Symbol(
const Font& spellFont,
BAK::GameState& gameState,
std::function<void(BAK::SpellIndex)> clickedCallback,
std::function<void(BAK::SpellIndex, bool)> highlightCallback)
:
Widget{
RectTag{},
glm::vec2{-4, -4},
glm::vec2{100,100},
glm::vec4{},
true
},
mGameState{gameState},
mSpellFont{spellFont},
mLines{},
mClickedCallback{std::move(clickedCallback)},
mHighlightCallback{std::move(highlightCallback)},
mSymbolIndex{0},
mHidden{false}
{
}
void Hide()
{
mHidden = true;
AddChildren();
}
void SetActiveCharacter(BAK::ActiveCharIndex character)
{
mSelectedCharacter = character;
}
void SetSymbol(unsigned symbolIndex)
{
mHidden = false;
mSymbolIndex = symbolIndex;
const auto& symbol = BAK::SpellDatabase::Get().GetSymbols()[mSymbolIndex - 1];
mSpells.clear();
mSpells.reserve(symbol.GetSymbolSlots().size());
for (const auto& slot : symbol.GetSymbolSlots())
{
const auto icon = slot.mSpellIcon;
const auto spellIndex = slot.mSpell;
if (!mGameState.CanCastSpell(spellIndex, mSelectedCharacter)) continue;
mSpells.emplace_back(
[this, spellIndex=spellIndex]{ mClickedCallback(spellIndex); },
icon,
slot.mPosition,
mSpellFont,
[this, spellIndex=spellIndex](bool selected){ mHighlightCallback(spellIndex, selected); });
}
AddChildren();
}
bool OnMouseEvent(const MouseEvent& event) override
{
bool handled = false;
for (auto& widget : mSpells)
{
handled |= widget.OnMouseEvent(event);
}
return handled;
}
const auto& GetSpells()
{
return BAK::SpellDatabase::Get().GetSymbols()[mSymbolIndex - 1].GetSymbolSlots();
}
unsigned GetSymbolIndex() const
{
return mSymbolIndex;
}
private:
void AddChildren()
{
ClearChildren();
if (mHidden) return;
for (auto& spell : mSpells)
{
AddChildBack(&spell);
}
}
using SpellIcon = Highlightable<
Clickable<
detail::Icon,
LeftMousePress,
std::function<void()>>,
true>;
BAK::GameState& mGameState;
const Font& mSpellFont;
BAK::ActiveCharIndex mSelectedCharacter;
std::vector<SpellIcon> mSpells;
std::vector<Line> mLines;
std::function<void(BAK::SpellIndex)> mClickedCallback;
std::function<void(BAK::SpellIndex, bool)> mHighlightCallback;
unsigned mSymbolIndex;
bool mHidden;
};
}
| 4,125
|
C++
|
.h
| 149
| 20.067114
| 107
| 0.597416
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,664
|
powerRing.hpp
|
xavieran_BaKGL/gui/cast/powerRing.hpp
|
#pragma once
#include "gui/core/clickable.hpp"
#include "gui/core/highlightable.hpp"
#include "gui/core/widget.hpp"
#include "gui/icons.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/tickAnimator.hpp"
#include "bak/spells.hpp"
namespace Gui::Cast {
namespace detail {
class PowerTick : public Widget
{
static constexpr auto sLit = 1;
static constexpr auto sUnlit = 2;
static constexpr auto sMajorLit = 3;
static constexpr auto sMajorUnlit = 4;
static constexpr auto sHighlighted = 5;
public:
PowerTick(
const Icons& icons,
glm::vec2 pos,
unsigned index,
std::function<void(bool)>&& selected)
:
Widget{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(icons.GetCastIcon(sUnlit)),
std::get<Graphics::TextureIndex>(icons.GetCastIcon(sUnlit)),
pos,
{8, 3},
false
},
mIcons{icons},
mIsMajor{((index + 1) % 5) == 0},
mEnabled{false},
mCallback{std::move(selected)}
{
}
void SetEnabledState(bool state)
{
mEnabled = state;
Reset();
}
public:
void Reset()
{
if (mIsMajor)
{
if (mEnabled)
{
SetSprite(sMajorLit);
}
else
{
SetSprite(sMajorUnlit);
}
}
else
{
if (mEnabled)
{
SetSprite(sLit);
}
else
{
SetSprite(sUnlit);
}
}
}
void SetSprite(unsigned sprite)
{
SetTexture(std::get<Graphics::TextureIndex>(mIcons.GetCastIcon(sprite)));
}
void Entered()
{
if (mEnabled)
{
SetSprite(sHighlighted);
mCallback(true);
}
}
void Exited()
{
if (mEnabled)
{
Reset();
mCallback(false);
}
}
const Icons& mIcons;
bool mIsMajor;
bool mEnabled;
std::function<void(bool)> mCallback;
};
}
class PowerRing : public Widget
{
static constexpr auto sTickSpeed = .005;
public:
PowerRing(
const Icons& icons,
glm::vec2 pos,
std::function<void(unsigned)>&& callback)
:
Widget{
RectTag{},
pos,
glm::vec2{320, 200},
glm::vec4{},
true},
mIcons{icons},
mCurrentTick{},
mActiveRange{std::make_pair(0, 0)},
mAnimator{},
mTicks{},
mCallback{std::move(callback)}
{
const auto& points = BAK::PowerRing::Get().GetPoints();
mTicks.reserve(points.size());
for (unsigned i = 0; i < points.size(); i++)
{
mTicks.emplace_back(
[this, i=i]{ HandleTickClicked(i); },
mIcons,
points[i] - glm::ivec2{1},
i,
[](bool){});
mTicks.back().SetEnabledState(false);
}
}
void Animate(std::pair<unsigned, unsigned> activeRange, IGuiManager& manager)
{
ClearChildren();
mActiveRange = activeRange;
mCurrentTick = 0;
auto animator = std::make_unique<TickAnimator>(sTickSpeed, [&](){ HandleTimeTick(); });
mAnimator = animator.get();
manager.AddAnimator(std::move(animator));
}
private:
void HandleTickClicked(unsigned i)
{
mCallback(i);
}
void Ready()
{
}
void HandleTimeTick()
{
if (mCurrentTick < mTicks.size())
{
mTicks[mCurrentTick].SetEnabledState(false);
AddChildBack(&mTicks[(mTicks.size() - 1) - mCurrentTick]);
}
else if (mCurrentTick >= mTicks.size())
{
auto tick = mCurrentTick - mTicks.size();
if (tick < mActiveRange.first)
{
}
else if (tick >= mActiveRange.first && tick <= mActiveRange.second)
{
mTicks[tick].SetEnabledState(true);
}
else
{
mAnimator->Stop();
Ready();
}
}
mCurrentTick++;
}
using PowerTick = Highlightable<
Clickable<
detail::PowerTick,
LeftMousePress,
std::function<void()>>,
true>;
const Icons& mIcons;
unsigned mCurrentTick;
std::pair<unsigned, unsigned> mActiveRange;
TickAnimator* mAnimator;
std::vector<PowerTick> mTicks;
std::function<void(unsigned)> mCallback;
};
}
| 4,644
|
C++
|
.h
| 186
| 16.430108
| 95
| 0.525271
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,665
|
castScreen.hpp
|
xavieran_BaKGL/gui/cast/castScreen.hpp
|
#pragma once
#include "bak/fileBufferFactory.hpp"
#include "bak/layout.hpp"
#include "bak/dialog.hpp"
#include "bak/skills.hpp"
#include "graphics/texture.hpp"
#include "gui/cast/symbol.hpp"
#include "gui/cast/powerRing.hpp"
#include "gui/animator.hpp"
#include "gui/core/clickable.hpp"
#include "gui/core/highlightable.hpp"
#include "gui/core/line.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/clickButton.hpp"
#include "gui/icons.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui::Cast {
class CastScreen : public Widget, public NullDialogScene
{
enum class State
{
Idle,
SpellSelected,
};
static constexpr auto sLayoutFile = "REQ_CAST.DAT";
static constexpr auto sCombatLayoutFile = "SPELL.DAT";
static constexpr auto sCastPanel = "CAST.SCX";
static constexpr auto sScreen = "CFRAME.SCX";
static constexpr auto sSymbol6 = 0;
static constexpr auto sSymbol5 = 1;
static constexpr auto sSymbol2 = 2;
static constexpr auto sSymbol4 = 3;
static constexpr auto sExit = 6;
static constexpr auto sCharacterWidgetBegin = 7;
static constexpr auto sSymbolTransitionTimeSeconds = .5;
public:
CastScreen(
IGuiManager& guiManager,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font,
const Font& spellFont,
BAK::GameState& gameState)
:
Widget{
Graphics::DrawMode::Sprite,
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen(sCastPanel),
Graphics::ColorMode::Texture,
glm::vec4{1},
glm::vec2{0},
glm::vec2{320, 200},
true
},
mGameState{gameState},
mGuiManager{guiManager},
mFont{font},
mIcons{icons},
mLayout{sLayoutFile},
mCombatLayout{sCombatLayoutFile},
mState{State::Idle},
mInCombat{true},
mSelectedSpell{},
mSymbol{
spellFont,
mGameState,
[&](auto spell){ HandleSpellClicked(spell); },
[&](auto spell, bool selected){ HandleSpellHighlighted(spell, selected); }},
mLines{},
mButtons{},
mSpellDesc{
glm::vec2{134, 18},
glm::vec2{176, 88}},
mPowerRing{mIcons, glm::vec2{}, [&](unsigned power){ HandleSpellPower(power); }},
mLogger{Logging::LogState::GetLogger("Gui::Cast")}
{
for (unsigned i = 0; i < 6; i++)
{
mLines.emplace_back(
glm::vec2{72, 62.5},
glm::vec2{72, 62.5},
.5, glm::vec4{1,0,0,1});
}
AddChildren();
}
bool OnMouseEvent(const MouseEvent& event) override
{
bool handled = false;
if (mState == State::Idle)
{
handled |= mSymbol.OnMouseEvent(event);
for (auto& widget : mButtons)
{
handled |= widget.OnMouseEvent(event);
}
}
else
{
handled |= mPowerRing.OnMouseEvent(event);
}
return handled;
}
void BeginCast(bool inCombat)
{
mInCombat = inCombat;
if (mSymbol.GetSymbolIndex() == 0)
{
ChangeSymbol(mInCombat ? 3 : 5);
}
assert(mGameState.GetParty().GetSpellcaster());
SetActiveCharacter(*mGameState.GetParty().GetSpellcaster());
}
private:
void PrepareLayout()
{
const auto& layout = mInCombat ? mCombatLayout : mLayout;
mButtons.clear();
mButtons.reserve(layout.GetSize());
auto& party = mGameState.GetParty();
BAK::ActiveCharIndex person{0};
do
{
const auto [spriteSheet, image, dimss] = mIcons.GetCharacterHead(
party.GetCharacter(person).GetIndex().mValue);
mButtons.emplace_back(
mLayout.GetWidgetLocation(person.mValue + sCharacterWidgetBegin),
mLayout.GetWidgetDimensions(person.mValue + sCharacterWidgetBegin),
spriteSheet,
image,
image,
[this, character=person]{
SetActiveCharacter(character);
},
[this, character=person]{
SetActiveCharacter(character);
}
);
if (mSelectedCharacter != person)
{
mButtons.back().SetColor(glm::vec4{.05, .05, .05, 1});
mButtons.back().SetColorMode(Graphics::ColorMode::TintColor);
}
person = party.NextActiveCharacter(person);
} while (person != BAK::ActiveCharIndex{0});
for (unsigned i = 0; i < layout.GetSize(); i++)
{
const auto& w = layout.GetWidget(i);
if (w.mWidget == 0)
{
continue;
}
auto image = w.mImage;
if ((w.mImage < 35 || w.mImage > 39) && !(w.mImage == 55 || w.mImage == 56) && (w.mImage != 13))
{
image = 25;
}
mButtons.emplace_back(
layout.GetWidgetLocation(i),
layout.GetWidgetDimensions(i) + (mInCombat ? glm::vec2{2, 3} : glm::vec2{}),
std::get<Graphics::SpriteSheetIndex>(mIcons.GetButton(image)),
std::get<Graphics::TextureIndex>(mIcons.GetButton(image)),
std::get<Graphics::TextureIndex>(mIcons.GetPressedButton(image)),
[this, i]{ HandleButton(i); },
[]{});
}
}
void SetActiveCharacter(BAK::ActiveCharIndex character)
{
if (!mGameState.GetParty().GetCharacter(character).IsSpellcaster())
{
mGuiManager.StartDialog(BAK::DialogSources::mCharacterIsNotASpellcaster, false, false, this);
}
else
{
mSelectedCharacter = character;
mGameState.SetActiveCharacter(mGameState.GetParty().GetCharacter(mSelectedCharacter).mCharacterIndex);
mSymbol.SetActiveCharacter(character);
if (mSymbol.GetSymbolIndex() > 0)
{
mSymbol.SetSymbol(mSymbol.GetSymbolIndex());
}
PrepareLayout();
AddChildren();
}
}
void HandleSpellClicked(BAK::SpellIndex spellIndex)
{
Logging::LogDebug(__FUNCTION__) << "(" << spellIndex << ")\n";
const auto& spell = BAK::SpellDatabase::Get().GetSpell(spellIndex);
auto& character = mGameState.GetParty().GetCharacter(mSelectedCharacter);
mSelectedSpell = spellIndex;
if (spell.mMinCost != spell.mMaxCost)
{
const auto health = character.GetSkill(BAK::SkillType::TotalHealth);
mState = State::SpellSelected;
mPowerRing.Animate(std::make_pair(spell.mMinCost, std::min(spell.mMaxCost, health)), mGuiManager);
AddChildren();
}
else
{
CastSpell(0);
}
}
void HandleSpellPower(unsigned power)
{
CastSpell(power);
mState = State::Idle;
HandleSpellHighlighted(BAK::SpellIndex{0}, false);
AddChildren();
}
void CastSpell(unsigned power)
{
assert(mSelectedSpell);
const auto spellIndex = *mSelectedSpell;
mGameState.CastStaticSpell(BAK::ToStaticSpell(spellIndex), BAK::Times::OneHour * power);
mSelectedSpell.reset();
auto& character = mGameState.GetParty().GetCharacter(mSelectedCharacter);
character.ImproveSkill(BAK::SkillType::TotalHealth, BAK::SkillChange::HealMultiplier_100, (-power) << 8);
mGuiManager.StartDialog(
BAK::DialogSources::GetSpellCastDialog(static_cast<unsigned>(BAK::ToStaticSpell(spellIndex))),
false,
false,
this);
}
void HandleSpellHighlighted(BAK::SpellIndex spellIndex, bool selected)
{
Logging::LogDebug(__FUNCTION__) << "(" << spellIndex << ", " << selected << ")\n";
const auto& db = BAK::SpellDatabase::Get();
std::stringstream ss{};
if (selected)
{
const auto& doc = db.GetSpellDoc(spellIndex);
ss << doc.mTitle << "\n";
ss << "Cost: " << doc.mCost << "\n";
if (!doc.mDamage.empty()) ss << doc.mDamage << "\n";
if (!doc.mDuration.empty()) ss << doc.mDuration<< "\n";
if (!doc.mLineOfSight.empty()) ss << doc.mLineOfSight << "\n";
ss << doc.mDescription << "\n";
ss << "\n";
const auto& character = mGameState.GetParty().GetCharacter(mSelectedCharacter);
const auto health = character.GetSkill(BAK::SkillType::TotalHealth);
const auto maxHealth = character.GetMaxSkill(BAK::SkillType::TotalHealth);
ss << "Health/Stamina: " << health << " of " << maxHealth << "\n";
}
else
{
if (mSymbol.GetSymbolIndex() > 0)
{
for (const auto& spell : mSymbol.GetSpells())
{
if (mGameState.CanCastSpell(spell.mSpell, mSelectedCharacter))
{
ss << db.GetSpellName(spell.mSpell) << "\n";
}
}
}
}
mSpellDesc.SetText(mFont, ss.str(), true, true);
AddChildren();
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice) override
{
Exit();
}
void Exit()
{
// exit lock happens to do exactly what I want.. should probably rename it
mGuiManager.DoFade(.8, [this]{ mGuiManager.ExitLock(); });
}
void HandleButton(unsigned i)
{
if (i == sExit)
{
Exit();
}
else if (i == sSymbol5)
{
if (mInCombat)
ChangeSymbol(3);
else
ChangeSymbol(5);
}
else if (i == sSymbol6)
{
if (mInCombat)
ChangeSymbol(1);
else
ChangeSymbol(6);
}
else if (i == sSymbol2 && mInCombat)
{
ChangeSymbol(2);
}
else if (i == sSymbol4 && mInCombat)
{
ChangeSymbol(4);
}
AddChildren();
}
void ChangeSymbol(unsigned newSymbol)
{
if (newSymbol == mSymbol.GetSymbolIndex()) return;
mSymbol.Hide();
const auto& points = BAK::SymbolLines::GetPoints(newSymbol - 1);
for (unsigned i = 0; i < 6; i++)
{
const auto start = mLines[i].GetStart();
const auto end = mLines[i].GetEnd();
const auto startF = points[i];
const auto endF = points[(i + 1) % 6];
mGuiManager.AddAnimator(std::make_unique<LinearAnimator>(
.5,
glm::vec4{start.x, start.y, end.x, end.y},
glm::vec4{startF.x, startF.y, endF.x, endF.y},
[this, i](const auto& delta){
auto start = mLines[i].GetStart();
auto end = mLines[i].GetEnd();
mLines[i].SetPoints(
start + glm::vec2{delta.x, delta.y},
end + glm::vec2{delta.z, delta.w});
return false;
},
[this, startF, endF, i, newSymbol](){
mLines[i].SetPoints(startF, endF);
mSymbol.SetSymbol(newSymbol);
HandleSpellHighlighted(BAK::SpellIndex{}, false);
}));
}
}
void AddChildren()
{
ClearChildren();
for (auto& widget : mButtons)
{
AddChildBack(&widget);
}
AddChildBack(&mSymbol);
AddChildBack(&mSpellDesc);
for (auto& line : mLines)
{
AddChildBack(&line);
}
if (mState == State::SpellSelected)
{
AddChildBack(&mPowerRing);
}
}
BAK::GameState& mGameState;
IGuiManager& mGuiManager;
const Font& mFont;
const Icons& mIcons;
BAK::Layout mLayout;
BAK::Layout mCombatLayout;
State mState;
bool mInCombat;
std::optional<BAK::SpellIndex> mSelectedSpell;
BAK::ActiveCharIndex mSelectedCharacter;
Symbol mSymbol;
std::vector<Line> mLines;
std::vector<ClickButtonImage> mButtons;
TextBox mSpellDesc;
PowerRing mPowerRing;
const Logging::Logger& mLogger;
};
}
| 12,663
|
C++
|
.h
| 369
| 24.208672
| 114
| 0.55511
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,666
|
dragEndpoint.hpp
|
xavieran_BaKGL/gui/core/dragEndpoint.hpp
|
#pragma once
#include "gui/core/draggable.hpp"
#include "gui/core/widget.hpp"
namespace Gui {
template <typename Base, typename DraggedT>
class DragEndpoint : public Base
{
public:
using Functor = std::function<void(DraggedT&)>;
template <typename ...Args>
DragEndpoint(
Functor&& callback,
Args&&... args)
:
Base{std::forward<Args>(args)...},
mCallback{std::move(callback)}
{}
bool OnDragEvent(const DragEvent& event) override
{
return evaluate_if<DragEnded>(event, [&](const auto& e){
if (Base::Within(e.mValue))
{
ASSERT(e.mWidget);
ASSERT(dynamic_cast<DraggedT*>(e.mWidget) != nullptr);
std::invoke(
mCallback,
static_cast<DraggedT&>(*e.mWidget));
return true;
}
return false;
});
}
private:
Functor mCallback;
};
}
| 964
|
C++
|
.h
| 36
| 19
| 70
| 0.56413
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,667
|
dragEvent.hpp
|
xavieran_BaKGL/gui/core/dragEvent.hpp
|
#pragma once
#include <glm/glm.hpp>
#include <ostream>
#include <variant>
namespace Gui {
class Widget;
struct DragStarted
{
bool operator==(const DragStarted&) const = default;
Widget* mWidget;
glm::vec2 mValue;
};
struct Dragging
{
bool operator==(const Dragging&) const = default;
Widget* mWidget;
glm::vec2 mValue;
};
struct DragEnded
{
bool operator==(const DragEnded&) const = default;
Widget* mWidget;
glm::vec2 mValue;
};
using DragEvent = std::variant<
DragStarted,
Dragging,
DragEnded
>;
std::ostream& operator<<(std::ostream& os, const DragEvent&);
const glm::vec2& GetValue(const DragEvent& event);
}
| 677
|
C++
|
.h
| 32
| 18.15625
| 61
| 0.71248
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,668
|
doubleClickStateMachine.hpp
|
xavieran_BaKGL/gui/core/doubleClickStateMachine.hpp
|
#pragma once
#include <glm/glm.hpp>
#include <functional>
#include <optional>
namespace Gui {
/*
* I don't use this right now as I feel it introduces a bit
* too much lag into the input.
*/
class DoubleClickStateMachine
{
struct Event
{
float mClickTime;
glm::vec2 mClickPos;
};
public:
DoubleClickStateMachine(
std::function<void(glm::vec2)>&& singlePress,
std::function<void(glm::vec2)>&& singleRelease,
std::function<void(glm::vec2)>&& doublePress);
void HandlePress(glm::vec2 click, float time);
void HandleRelease(glm::vec2 click, float time);
void UpdateTime(float time);
private:
float mReleaseTimeout{.1};
float mDoubleClickTimeout{.3};
std::optional<Event> mPress;
std::optional<Event> mRelease;
std::function<void(glm::vec2)> mSinglePress;
std::function<void(glm::vec2)> mSingleRelease;
std::function<void(glm::vec2)> mDoublePress;
};
}
| 957
|
C++
|
.h
| 34
| 23.911765
| 59
| 0.696272
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,669
|
keyEvent.hpp
|
xavieran_BaKGL/gui/core/keyEvent.hpp
|
#pragma once
#include <ostream>
#include <variant>
namespace Gui {
struct KeyPress
{
bool operator==(const KeyPress&) const = default;
int mValue;
};
struct Character
{
bool operator==(const Character&) const = default;
char mValue;
};
using KeyEvent = std::variant<
KeyPress,
Character>;
std::ostream& operator<<(std::ostream& os, const KeyEvent&);
}
| 383
|
C++
|
.h
| 19
| 17.526316
| 60
| 0.717087
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,670
|
clickable.hpp
|
xavieran_BaKGL/gui/core/clickable.hpp
|
#pragma once
#include "gui/core/widget.hpp"
#include "com/assert.hpp"
#include "com/visit.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <type_traits>
#include <utility>
#include <variant>
namespace Gui {
template <typename Base, typename EventT, typename Functor>
requires ImplementsWidget<Base>
class Clickable : public Base
{
public:
template <typename ...Args>
Clickable(Functor&& callback, Args&&... args)
:
Base{std::forward<Args>(args)...},
mCallback{std::move(callback)}
{
ASSERT(mCallback);
}
bool OnMouseEvent(const MouseEvent& event) override
{
const auto result = std::visit(overloaded{
[this](const EventT& p){ return DoCallback(p); },
[](const auto& p){ return false; }
},
event);
if (result)
return result;
return Base::OnMouseEvent(event);
}
bool DoCallback(const EventT& event)
{
if (Base::Within(event.mValue))
{
if constexpr (std::is_same_v<decltype(mCallback()), bool>)
{
return mCallback();
}
else
{
mCallback();
}
return true;
}
return false;
}
private:
Functor mCallback;
};
}
| 1,352
|
C++
|
.h
| 55
| 17.745455
| 70
| 0.579439
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,671
|
mouseEvent.hpp
|
xavieran_BaKGL/gui/core/mouseEvent.hpp
|
#pragma once
#include <glm/glm.hpp>
#include <ostream>
#include <variant>
namespace Gui {
struct LeftMousePress
{
bool operator==(const LeftMousePress&) const = default;
glm::vec2 mValue;
};
struct LeftMouseRelease
{
bool operator==(const LeftMouseRelease&) const = default;
glm::vec2 mValue;
};
struct LeftMouseDoublePress
{
bool operator==(const LeftMouseDoublePress&) const = default;
glm::vec2 mValue;
};
struct RightMousePress
{
bool operator==(const RightMousePress&) const = default;
glm::vec2 mValue;
};
struct RightMouseRelease
{
bool operator==(const RightMouseRelease&) const = default;
glm::vec2 mValue;
};
struct MouseMove
{
bool operator==(const MouseMove&) const = default;
glm::vec2 mValue;
};
struct MouseScroll
{
bool operator==(const MouseScroll&) const = default;
glm::vec2 mValue;
};
using MouseEvent = std::variant<
LeftMousePress,
LeftMouseRelease,
LeftMouseDoublePress,
RightMousePress,
RightMouseRelease,
MouseMove,
MouseScroll>;
std::ostream& operator<<(std::ostream& os, const MouseEvent&);
const glm::vec2& GetValue(const MouseEvent& event);
}
| 1,170
|
C++
|
.h
| 51
| 20.019608
| 65
| 0.740271
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,672
|
draggable.hpp
|
xavieran_BaKGL/gui/core/draggable.hpp
|
#pragma once
#include "gui/core/widget.hpp"
#include "com/visit.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <optional>
#include <utility>
#include <variant>
namespace Gui {
template <typename Base>
class Draggable : public Base
{
public:
template <typename ...Args>
Draggable(Args&&... args)
:
Base{std::forward<Args>(args)...},
mOriginalPosition{Base::GetPositionInfo().mPosition},
mDragStart{},
mDragging{false}
{
}
bool OnMouseEvent(const MouseEvent& event) override
{
const auto result = std::visit(overloaded{
[this](const LeftMousePress& p){ return LeftMousePressed(p.mValue); },
[this](const LeftMouseRelease& p){ return LeftMouseReleased(p.mValue); },
[this](const MouseMove& p){ return MouseMoved(p.mValue); },
[this](const RightMousePress& p){ return HandleRightMouse(); },
[this](const RightMouseRelease& p){ return HandleRightMouse(); },
[](const auto& p){ return false; }
},
event);
if (result)
return result;
return Base::OnMouseEvent(event);
}
// If this widget is being dragged it
// shouldn't accept right mouse events
bool HandleRightMouse()
{
return mDragging;
}
bool LeftMousePressed(glm::vec2 click)
{
if (Base::Within(click))
{
Logging::LogDebug("Gui::Draggable") << "DragStart: " << this << "\n";
mDragStart = click;
}
return false;
}
bool MouseMoved(glm::vec2 pos)
{
if (!mDragging
&& mDragStart
&& glm::distance(*mDragStart, pos) > 4)
{
mDragging = true;
Widget::PropagateUp(DragEvent{DragStarted{this, pos}});
}
if (mDragging)
{
Base::SetCenter(pos);
}
return false;
}
bool LeftMouseReleased(glm::vec2 click)
{
mDragStart.reset();
if (mDragging)
{
Logging::LogDebug("Gui::Draggable") << "DragEnded: " << this << "\n";
mDragging = false;
Base::SetPosition(mOriginalPosition);
Base::PropagateUp(DragEvent{DragEnded{this, click}});
}
return false;
}
private:
glm::vec2 mOriginalPosition;
std::optional<glm::vec2> mDragStart;
bool mDragging;
};
}
| 2,467
|
C++
|
.h
| 86
| 21.127907
| 85
| 0.583759
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,673
|
highlightable.hpp
|
xavieran_BaKGL/gui/core/highlightable.hpp
|
#pragma once
#include "gui/core/widget.hpp"
#include "com/assert.hpp"
#include "com/logger.hpp"
#include "com/visit.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <optional>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
template<typename T>
concept HighlightableWidget = requires(T a)
{
a.Entered();
a.Exited();
};
template <typename Base, bool HandleBaseFirst>
requires ImplementsWidget<Base> && HighlightableWidget<Base>
class Highlightable : public Base
{
public:
template <typename ...Args>
Highlightable(Args&&... args)
:
Base(std::forward<Args>(args)...),
mWithinWidget{}
{
}
bool OnMouseEvent(const MouseEvent& event) override
{
std::visit(overloaded{
[this](const MouseMove& p){ return MouseMoved(p.mValue); },
[](const auto& p){ return false; }
}, event);
return Base::OnMouseEvent(event);
}
private:
bool MouseMoved(glm::vec2 pos)
{
if (!mWithinWidget)
{
if (Base::Within(pos))
{
Base::Entered();
mWithinWidget = true;
}
else
{
Base::Exited();
mWithinWidget = false;
}
}
else
{
// Mouse entered widget
if (Base::Within(pos) && !(*mWithinWidget))
{
Base::Entered();
mWithinWidget = true;
}
// Mouse exited widget
else if (!Base::Within(pos) && *mWithinWidget)
{
Base::Exited();
mWithinWidget = false;
}
}
return false;
}
private:
std::optional<bool> mWithinWidget;
};
}
| 1,811
|
C++
|
.h
| 75
| 16.573333
| 71
| 0.544399
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,674
|
line.hpp
|
xavieran_BaKGL/gui/core/line.hpp
|
#pragma once
#include "gui/core/widget.hpp"
#include "graphics/glm.hpp"
#include "com/logger.hpp"
#include <cmath>
namespace Gui
{
class Line : public Widget
{
public:
Line(glm::vec2 p1, glm::vec2 p2, float width, glm::vec4 color)
:
Widget{
RectTag{},
{},
{},
{},
true},
mStart{p1},
mEnd{p2},
mWidth{width}
{
CalculateLine();
SetColor(color);
}
void SetPoints(glm::vec2 start, glm::vec2 end)
{
mStart = start;
mEnd = end;
CalculateLine();
}
glm::vec2 GetStart() const { return mStart; }
glm::vec2 GetEnd() const { return mEnd; }
private:
void CalculateLine()
{
auto length = glm::distance(mStart, mEnd);
auto rotation = -atanf((mEnd.y - mStart.y) / (mEnd.x - mStart.x));
if (std::abs(mEnd.x - mStart.x) < .001)
rotation = -1.5708;
SetPosition((mStart.x > mEnd.x) ? mEnd : mStart);
SetDimensions(glm::vec2{length, mWidth});
SetRotation(rotation);
}
glm::vec2 mStart;
glm::vec2 mEnd;
float mWidth;
};
}
| 1,165
|
C++
|
.h
| 49
| 17.408163
| 75
| 0.554751
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,675
|
widget.hpp
|
xavieran_BaKGL/gui/core/widget.hpp
|
#pragma once
#include "com/logger.hpp"
#include "gui/core/dragEvent.hpp"
#include "gui/core/keyEvent.hpp"
#include "gui/core/mouseEvent.hpp"
#include "graphics/IGuiElement.hpp"
#include "graphics/guiTypes.hpp"
namespace Gui {
struct ClipRegionTag {};
struct ImageTag {};
struct RectTag {};
class Widget : public Graphics::IGuiElement
{
public:
Widget(
Graphics::DrawMode drawMode,
Graphics::SpriteSheetIndex spriteSheet,
Graphics::TextureIndex texture,
Graphics::ColorMode colorMode,
glm::vec4 color,
glm::vec2 pos,
glm::vec2 dims,
bool childrenRelative);
Widget(
ImageTag,
Graphics::SpriteSheetIndex spriteSheet,
Graphics::TextureIndex texture,
glm::vec2 pos,
glm::vec2 dims,
bool childrenRelative);
Widget(
ClipRegionTag,
glm::vec2 pos,
glm::vec2 dims,
bool childrenRelative);
Widget(
RectTag,
glm::vec2 pos,
glm::vec2 dims,
glm::vec4 color,
bool childrenRelative);
virtual ~Widget();
virtual void SetActive();
virtual void SetInactive();
[[nodiscard]] virtual bool OnDragEvent(
const DragEvent& event);
[[nodiscard]] virtual bool OnKeyEvent(
const KeyEvent& event);
[[nodiscard]] virtual bool OnMouseEvent(
const MouseEvent& event);
virtual void PropagateUp(
const DragEvent& event);
const Graphics::DrawInfo& GetDrawInfo() const override;
const Graphics::PositionInfo& GetPositionInfo() const override;
void AddChildFront(Widget* widget);
void AddChildBack(Widget* widget);
bool HaveChild(Widget* widget);
void RemoveChild(Widget* elem);
void PopChild();
void ClearChildren();
void SetParent(Widget*);
void SetCenter(glm::vec2 pos);
glm::vec2 GetCenter() const;
glm::vec2 GetTopLeft() const;
glm::vec2 GetDimensions() const;
void SetPosition(glm::vec2 pos);
void AdjustPosition(glm::vec2 adj);
void SetRotation(float);
virtual void SetDimensions(glm::vec2 dims);
void SetSpriteSheet(Graphics::SpriteSheetIndex);
void SetTexture(Graphics::TextureIndex);
void SetColorMode(Graphics::ColorMode);
void SetColor(glm::vec4);
std::size_t size() const;
protected:
bool Within(glm::vec2 click);
glm::vec2 TransformPosition(const glm::vec2&);
glm::vec2 InverseTransformPosition(const glm::vec2&);
MouseEvent TransformEvent(const MouseEvent&);
DragEvent TransformEvent(const DragEvent&);
DragEvent InverseTransformEvent(const DragEvent&);
Graphics::DrawInfo mDrawInfo;
Graphics::PositionInfo mPositionInfo;
Widget* mParent;
std::vector<Widget*> mChildren;
bool mActive;
};
template <typename T>
concept ImplementsWidget = std::derived_from<T, Widget>;
}
| 2,864
|
C++
|
.h
| 90
| 26.188889
| 67
| 0.696981
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,676
|
campScreen.hpp
|
xavieran_BaKGL/gui/camp/campScreen.hpp
|
#pragma once
#include "bak/camp.hpp"
#include "bak/dialogSources.hpp"
#include "bak/fileBufferFactory.hpp"
#include "bak/layout.hpp"
#include "bak/shop.hpp"
#include "bak/time.hpp"
#include "graphics/texture.hpp"
#include "gui/core/clickable.hpp"
#include "gui/core/highlightable.hpp"
#include "gui/tickAnimator.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/camp/clock.hpp"
#include "gui/clickButton.hpp"
#include "gui/icons.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui::Camp {
class CampScreen : public Widget, public NullDialogScene
{
enum class State
{
Idle,
Camping,
CampingTilHealed
};
static constexpr auto sLayoutFile = "REQ_CAMP.DAT";
static constexpr auto sScreen = "ENCAMP.SCX";
static constexpr auto sCampUntilHealed = 0;
static constexpr auto sStop = 1;
static constexpr auto sExit = 2;
public:
CampScreen(
IGuiManager& guiManager,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font,
BAK::GameState& gameState)
:
Widget{
Graphics::DrawMode::Sprite,
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen(sScreen),
Graphics::ColorMode::Texture,
glm::vec4{1},
glm::vec2{0},
glm::vec2{320, 200},
true
},
mGuiManager{guiManager},
mFont{font},
mGameState{gameState},
mIcons{icons},
mLayout{sLayoutFile},
mCampData{},
mFrame{
Graphics::DrawMode::Sprite,
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen("DIALOG_BG_MAIN.SCX"),
Graphics::ColorMode::Texture,
glm::vec4{1},
glm::vec2{0},
glm::vec2{320, 200},
true
},
mNamesColumn{
{130, 20},
{60, 200}
},
mHealthColumn{
{180, 20},
{70, 200}
},
mRationsColumn{
{250, 20},
{60, 200}
},
mPartyGold{
{140, 90},
{240, 60}
},
mButtons{},
mDots{},
mIsInInn{false},
mState{State::Idle},
mTimeElapser{nullptr},
mLogger{Logging::LogState::GetLogger("Gui::Encamp")}
{
mButtons.reserve(mLayout.GetSize());
for (unsigned i = 0; i < mLayout.GetSize(); i++)
{
const auto& w = mLayout.GetWidget(i);
mButtons.emplace_back(
mLayout.GetWidgetLocation(i),
mLayout.GetWidgetDimensions(i),
std::get<Graphics::SpriteSheetIndex>(mIcons.GetButton(w.mImage)),
std::get<Graphics::TextureIndex>(mIcons.GetButton(w.mImage)),
std::get<Graphics::TextureIndex>(mIcons.GetPressedButton(w.mImage)),
[this, i]{ HandleButton(i); },
[]{});
}
mDots.reserve(mCampData.GetClockTicks().size());
for (unsigned i = 0; i < mCampData.GetClockTicks().size(); i++)
{
auto dot = mDots.emplace_back(
[this, i=i]{ HandleDotClicked(i); },
mIcons,
mCampData.GetClockTicks().at(i),
[](bool selected){});
dot.SetCurrent(false);
}
AddChildren();
}
bool OnMouseEvent(const MouseEvent& event) override
{
bool handled = false;
if (mState == State::Idle)
{
for (auto& widget : mDots)
{
handled |= widget.OnMouseEvent(event);
}
}
for (auto& widget : mButtons)
{
handled |= widget.OnMouseEvent(event);
}
return handled;
}
void BeginCamp(bool isInn, BAK::ShopStats* shopStats)
{
const auto hour = mGameState.GetWorldTime().GetTime().GetHour();
for (unsigned i = 0; i < mCampData.GetClockTicks().size(); i++)
{
mDots.at(i).SetCurrent(i == hour);
}
mIsInInn = isInn;
assert(!isInn || shopStats);
mShopStats = shopStats;
SetText();
AddChildren();
if (mIsInInn)
{
ShowInnDialog(false);
}
}
void DialogFinished(const std::optional<BAK::ChoiceIndex>& choice) override
{
assert(choice);
if (mGameState.GetEndOfDialogState() == -1 || choice->mValue == BAK::Keywords::sNoIndex)
{
Exit();
}
else
{
StartCamping(mShopStats->mInnSleepTilHour);
}
}
private:
BAK::Royals GetInnCost()
{
assert(mShopStats);
return BAK::GetRoyals(BAK::Sovereigns{mShopStats->mInnCost});
}
void ShowInnDialog(bool haveSlept)
{
auto sleepTil = mShopStats->mInnSleepTilHour;
assert(sleepTil < mDots.size());
mDots[sleepTil].SetHighlighted();
mGameState.SetItemValue(GetInnCost());
mGameState.SetDialogContext_7530(haveSlept);
mGuiManager.StartDialog(
BAK::DialogSources::mInnDialog, false, false, this);
}
void SetText()
{
std::stringstream namesSS{};
namesSS << "\n";
std::stringstream healthSS{};
healthSS << "Health/Stamina\n";
std::stringstream rationsSS{};
rationsSS << "Rations\n";
mGameState.GetParty().ForEachActiveCharacter(
[&](auto& character){
auto highlight = character.HaveNegativeCondition() ? "\xf5" : "";
namesSS << highlight << character.GetName() << "\n";
const auto health = character.GetSkill(BAK::SkillType::TotalHealth);
const auto maxHealth = character.GetMaxSkill(BAK::SkillType::TotalHealth);
// for the purposes of the highlight it's always 80%
highlight = character.CanHeal(false) ? "\xf5" : " ";
healthSS << highlight << " " << health << " " << highlight
<< " of " << maxHealth << "\n";
const auto rations = character.GetTotalItem(
std::vector<BAK::ItemIndex>{BAK::sPoisonedRations, BAK::sRations, BAK::sSpoiledRations});
const auto rhighlight = rations == 0 ? '\xf5' : ' ';
rationsSS << rhighlight << " " << rations << " " << rhighlight << "\n";
return BAK::Loop::Continue;
});
mNamesColumn.SetText(mFont, namesSS.str(), true, false, false, 1.5);
mHealthColumn.SetText(mFont, healthSS.str(), true, false, false, 1.5);
mRationsColumn.SetText(mFont, rationsSS.str(), true, false, false, 1.5);
if (mIsInInn)
{
const auto partyGold = mGameState.GetParty().GetGold();
const auto highlight = partyGold.mValue < GetInnCost().mValue ? '\xf5' : ' ';
std::stringstream ss{};
ss << "Party Gold: " << highlight << BAK::ToShopString(partyGold);
mPartyGold.SetText(mFont, ss.str());
}
}
bool AnyCharacterCanHeal()
{
bool canHeal = false;
mGameState.GetParty().ForEachActiveCharacter(
[&](auto& character){
canHeal |= character.CanHeal(mIsInInn);
canHeal |= character.HaveNegativeCondition();
return BAK::Loop::Continue;
});
return canHeal;
}
void HandleDotClicked(unsigned i)
{
StartCamping(i);
}
unsigned GetHour()
{
return mGameState.GetWorldTime().GetTime().GetHour();
}
void StartCamping(std::optional<unsigned> hourTil)
{
mTargetHour = hourTil;
mTimeBeganCamping = mGameState.GetWorldTime().GetTime();
if ((!mIsInInn && hourTil && mDots.at(*hourTil).GetCurrent())
|| mState == State::Camping)
{
return;
}
const auto it = std::find_if(mDots.begin(), mDots.end(),
[](const auto& dot){ return dot.GetCurrent(); });
assert(it != mDots.end());
mState = hourTil ? State::Camping : State::CampingTilHealed;
auto timeElapser = std::make_unique<TickAnimator>(
.02,
[this]{
this->HandleTick();
});
mTimeElapser = timeElapser.get();
mGuiManager.AddAnimator(std::move(timeElapser));
AddChildren();
}
void HandleTick()
{
auto camp = BAK::TimeChanger(mGameState);
camp.ElapseTimeInSleepView(
BAK::Times::OneHour,
mIsInInn ? 0x85 : 0x64,
mIsInInn ? 0x64 : 0x50);
if ((mGameState.GetWorldTime().GetTime() - mTimeBeganCamping) > BAK::Times::ThirteenHours)
{
mGameState.GetParty().ForEachActiveCharacter([&](auto& character){
character.AdjustCondition(BAK::Condition::Sick, -100);
return BAK::Loop::Continue;
});
}
bool isLast = GetHour() == mTargetHour;
if (isLast || (mState == State::CampingTilHealed && !AnyCharacterCanHeal()))
{
FinishedTicking();
}
if (mState == State::CampingTilHealed || mIsInInn)
{
for (unsigned i = 0; i < mDots.size(); i++)
{
mDots.at(i).SetCurrent(false);
}
}
mDots.at(GetHour()).SetCurrent(true);
SetText();
}
void FinishedTicking()
{
if (mTimeElapser)
{
mTimeElapser->Stop();
}
mTimeElapser = nullptr;
for (unsigned i = 0; i < mCampData.GetClockTicks().size(); i++)
{
mDots.at(i).SetCurrent(i == GetHour());
}
const auto prevState = mState;
mState = State::Idle;
AddChildren();
if (mIsInInn)
{
mGameState.GetParty().LoseMoney(BAK::GetRoyals(BAK::Sovereigns{mShopStats->mInnCost}));
if (!AnyCharacterCanHeal())
{
Exit();
}
else
{
ShowInnDialog(true);
}
}
else if (prevState != State::CampingTilHealed)
{
Exit();
}
}
void HandleButton(unsigned button)
{
if (button == sCampUntilHealed)
{
const auto hour = mGameState.GetWorldTime().GetTime().GetHour();
mLogger.Spam() << "Hour: "<< hour << "\n";
StartCamping(std::nullopt);
}
else if (button == sStop)
{
if (mTimeElapser != nullptr)
{
FinishedTicking();
}
}
else if (button == sExit)
{
Exit();
}
}
void Exit()
{
// exit lock happens to do exactly what I want.. should probably rename it
mGuiManager.DoFade(.8, [this]{mGuiManager.ExitLock(); });
}
void AddChildren()
{
ClearChildren();
if (!mIsInInn)
{
if (mState == State::Camping || mState == State::CampingTilHealed)
{
AddChildBack(&mButtons[sStop]);
}
else
{
if (AnyCharacterCanHeal())
{
AddChildBack(&mButtons[sCampUntilHealed]);
}
AddChildBack(&mButtons[sExit]);
}
}
for (auto& dot : mDots)
AddChildBack(&dot);
AddChildBack(&mNamesColumn);
AddChildBack(&mHealthColumn);
AddChildBack(&mRationsColumn);
if (mIsInInn)
{
AddChildBack(&mPartyGold);
AddChildBack(&mFrame);
SetInactive();
}
else
{
SetActive();
}
}
IGuiManager& mGuiManager;
const Font& mFont;
BAK::GameState& mGameState;
const Icons& mIcons;
BAK::Layout mLayout;
BAK::CampData mCampData;
Widget mFrame;
TextBox mNamesColumn;
TextBox mHealthColumn;
TextBox mRationsColumn;
TextBox mPartyGold;
std::vector<ClickButtonImage> mButtons;
using ClockTick = Highlightable<
Clickable<
detail::CampDest,
LeftMousePress,
std::function<void()>>,
true>;
std::vector<ClockTick> mDots;
bool mIsInInn;
State mState;
std::optional<unsigned> mTargetHour;
BAK::Time mTimeBeganCamping;
TickAnimator* mTimeElapser;
BAK::ShopStats* mShopStats;
const Logging::Logger& mLogger;
};
}
| 12,678
|
C++
|
.h
| 401
| 21.990025
| 109
| 0.546162
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,677
|
clock.hpp
|
xavieran_BaKGL/gui/camp/clock.hpp
|
#pragma once
#include "gui/icons.hpp"
#include "gui/core/widget.hpp"
namespace Gui::Camp {
namespace detail {
class CampDest : public Widget
{
static constexpr auto sBlank = 0;
static constexpr auto sUnlit = 1;
static constexpr auto sHighlighted = 2;
static constexpr auto sCurrent = 3;
static constexpr auto sBlank2 = 4;
public:
CampDest(
const Icons& icons,
glm::vec2 pos,
std::function<void(bool)>&& selected)
:
Widget{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(icons.GetEncampIcon(sUnlit)),
std::get<Graphics::TextureIndex>(icons.GetEncampIcon(sUnlit)),
pos,
{8, 3},
false
},
mIcons{icons},
mCurrent{},
mCallback{std::move(selected)}
{
}
bool GetCurrent() const
{
return mCurrent;
}
void SetCurrent(bool current)
{
mCurrent = current;
SetTexture(std::get<Graphics::TextureIndex>(
mCurrent
? mIcons.GetEncampIcon(sCurrent)
: mIcons.GetEncampIcon(sUnlit)));
}
void SetHighlighted()
{
SetTexture(std::get<Graphics::TextureIndex>(mIcons.GetEncampIcon(sHighlighted)));
}
public:
void Entered()
{
SetTexture(std::get<Graphics::TextureIndex>(mIcons.GetEncampIcon(sHighlighted)));
mCallback(true);
}
void Exited()
{
SetCurrent(mCurrent);
mCallback(false);
}
const Icons& mIcons;
bool mCurrent;
std::function<void(bool)> mCallback;
};
}
}
| 1,605
|
C++
|
.h
| 64
| 18.390625
| 89
| 0.609549
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,678
|
ratings.hpp
|
xavieran_BaKGL/gui/info/ratings.hpp
|
#pragma once
#include "bak/character.hpp"
#include "bak/condition.hpp"
#include "bak/skills.hpp"
#include "gui/actors.hpp"
#include "gui/colors.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class Ratings : public Widget
{
public:
Ratings(
glm::vec2 pos,
glm::vec2 dims,
const Font& font,
Graphics::SpriteSheetIndex spriteSheet,
Graphics::TextureIndex verticalBorder,
Graphics::TextureIndex horizontalBorder)
:
Widget{
RectTag{},
pos,
dims,
Color::infoBackground,
true
},
mFont{font},
mClipRegion{
ClipRegionTag{},
glm::vec2{0},
dims,
true},
mRatings{
RectTag{},
glm::vec2{0},
dims,
Color::infoBackground,
true},
mRatingsText{
glm::vec2{10, 8},
dims
},
mConditionsText{
glm::vec2{120, 8},
dims
},
mLeftBorder{
ImageTag{},
spriteSheet,
verticalBorder,
glm::vec2{0},
glm::vec2{2, 72},
true},
mRightBorder{
ImageTag{},
spriteSheet,
verticalBorder,
glm::vec2{220, 0},
glm::vec2{2, 72},
true},
mTopBorder{
ImageTag{},
spriteSheet,
horizontalBorder,
glm::vec2{2, 0},
glm::vec2{222, 2},
true},
mBottomBorder{
ImageTag{},
spriteSheet,
horizontalBorder,
glm::vec2{1, 71},
glm::vec2{222, 2},
true},
mLogger{Logging::LogState::GetLogger("Gui::Ratings")}
{
AddChildBack(&mClipRegion);
mClipRegion.AddChildBack(&mRatings);
mClipRegion.AddChildBack(&mRatingsText);
mClipRegion.AddChildBack(&mConditionsText);
mClipRegion.AddChildBack(&mLeftBorder);
mClipRegion.AddChildBack(&mRightBorder);
mClipRegion.AddChildBack(&mTopBorder);
mClipRegion.AddChildBack(&mBottomBorder);
}
void SetCharacter(
const BAK::Character& character)
{
{
std::stringstream ss{};
ss << "\xf6Ratings: \n";
const auto health = character.GetSkill(BAK::SkillType::Health);
const auto maxHealth = character.GetMaxSkill(BAK::SkillType::Health);
//if (health.mUnseenImprovement) ss << "\xf5";
//else ss << "\xf6";
ss << "\xf6";
ss << " Health " << health << " of " << maxHealth << "\n";
const auto stamina = character.GetSkill(BAK::SkillType::Stamina);
const auto maxStamina = character.GetMaxSkill(BAK::SkillType::Stamina);
//if (stamina.mUnseenImprovement) ss << "\xf5";
//else ss << "\xf6";
ss << "\xf6";
ss << " Stamina " << stamina << " of " << maxStamina << "\n";
const auto speed = character.GetSkill(BAK::SkillType::Speed);
//if (speed.mUnseenImprovement) ss << "\xf5";
//else ss << "\xf6";
ss << "\xf6";
ss << " Speed " << +speed << "\n";
const auto strength = character.GetSkill(BAK::SkillType::Strength);
//if (strength.mUnseenImprovement) ss << "\xf5";
//else ss << "\xf6";
ss << "\xf6";
ss << " Strength " << strength << "\n";
mLogger.Debug() << ss.str();
mRatingsText.SetText(mFont, ss.str());
}
{
std::stringstream ss{};
ss << "\xf6" "Condition: \n";
if (character.GetConditions().NoConditions())
{
ss << "\xf6 Normal";
}
else
{
for (unsigned i = 0; i < static_cast<unsigned>(character.GetConditions().sNumConditions); i++)
{
const auto type = static_cast<BAK::Condition>(i);
const auto value = character.GetConditions().GetCondition(type);
if (value != 0)
{
ss << "\xf5 " << BAK::ToString(type) << " (" << value << "%)\n";
}
}
}
mConditionsText.SetText(mFont, ss.str());
}
}
private:
const Font& mFont;
Widget mClipRegion;
Widget mRatings;
TextBox mRatingsText;
TextBox mConditionsText;
Widget mLeftBorder;
Widget mRightBorder;
Widget mTopBorder;
Widget mBottomBorder;
const Logging::Logger& mLogger;
};
}
| 4,867
|
C++
|
.h
| 156
| 20.858974
| 110
| 0.507024
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,679
|
spells.hpp
|
xavieran_BaKGL/gui/info/spells.hpp
|
#pragma once
#include "bak/gameState.hpp"
#include "gui/backgrounds.hpp"
#include "gui/button.hpp"
#include "gui/fontManager.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/icons.hpp"
#include "gui/textBox.hpp"
namespace Gui {
class SpellList : public Button
{
public:
SpellList(
unsigned symbolButtonIndex,
glm::vec2 pos,
const Icons& icons)
:
Button{
pos,
std::get<glm::vec2>(icons.GetButton(symbolButtonIndex)) + glm::vec2{3, 2},
Color::infoBackground,
Color::frameMaroon,
Color::frameMaroon
},
mSymbolImage{
Graphics::DrawMode::Sprite,
std::get<Graphics::SpriteSheetIndex>(icons.GetButton(symbolButtonIndex)),
std::get<Graphics::TextureIndex>(icons.GetButton(symbolButtonIndex)),
Graphics::ColorMode::Texture,
Color::black,
glm::vec2{2, 1},
std::get<glm::vec2>(icons.GetButton(symbolButtonIndex)),
true},
mSpells{
glm::vec2{
std::get<glm::vec2>(icons.GetButton(symbolButtonIndex)).x + 5,
2},
glm::vec2{260, std::get<glm::vec2>(icons.GetButton(symbolButtonIndex)).y - 2}}
{
AddChildBack(&mSymbolImage);
AddChildBack(&mSpells);
}
void SetSpells(const Font& font, std::string text)
{
mSpells.SetText(font, text, false, true, true);
}
private:
Widget mSymbolImage;
TextBox mSpells;
};
class SpellsScreen : public Widget
{
static constexpr std::array<unsigned, 6> sSpellSymbolIndexToButtonIndex =
{
37, 36, 38, 39, 56, 55
};
public:
SpellsScreen(
IGuiManager& guiManager,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font,
BAK::GameState& gameState)
:
Widget{
Graphics::DrawMode::Sprite,
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen("DIALOG.SCX"),
Graphics::ColorMode::Texture,
glm::vec4{1},
glm::vec2{0},
glm::vec2{320, 200},
true
},
mGuiManager{guiManager},
mFont{font},
mGameState{gameState},
mSelectedCharacter{0},
mLogger{Logging::LogState::GetLogger("Gui::SpellsScreen")}
{
const auto& [_, __, dims] = icons.GetButton(36);
glm::vec2 pos{4,8};
mSpellLists.reserve(6);
for (unsigned i = 0; i < 6; i++)
{
mSpellLists.emplace_back(
sSpellSymbolIndexToButtonIndex[i],
pos,
icons);
pos += glm::vec2{0, dims.y + 3};
}
AddChildren();
}
void SetSelectedCharacter(BAK::ActiveCharIndex character)
{
mSelectedCharacter = character;
assert(mGameState.GetParty().GetCharacter(character).IsSpellcaster());
const auto& characterSpells = mGameState.GetParty().GetCharacter(character).GetSpells();
const auto& spellDb = BAK::SpellDatabase::Get();
const auto& symbols = spellDb.GetSymbols();
for (unsigned i = 0; i < 6; i++)
{
std::stringstream spellText{};
std::string sep{""};
for (const auto& spell : symbols[i].GetSymbolSlots())
{
if (characterSpells.HaveSpell(spell.mSpell))
{
spellText << sep << spellDb.GetSpellName(spell.mSpell);
sep = ", ";
}
}
mSpellLists[i].SetSpells(mFont, spellText.str());
}
}
bool OnMouseEvent(const MouseEvent& event) override
{
return std::visit(overloaded{
[this](const LeftMousePress& p){ Exit(); return true; },
[this](const RightMousePress& p){ Exit(); return true; },
[](const auto& p){ return false; }
},
event);
}
private:
void Exit()
{
mGuiManager.DoFade(0.5, [this]{ mGuiManager.ExitSimpleScreen(); });
}
void AddChildren()
{
for (auto& spellList : mSpellLists)
{
AddChildBack(&spellList);
}
}
IGuiManager& mGuiManager;
const Font& mFont;
BAK::GameState& mGameState;
BAK::ActiveCharIndex mSelectedCharacter;
std::vector<SpellList> mSpellLists;
const Logging::Logger& mLogger;
};
}
| 4,450
|
C++
|
.h
| 144
| 22.180556
| 96
| 0.574528
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,680
|
skills.hpp
|
xavieran_BaKGL/gui/info/skills.hpp
|
#pragma once
#include "bak/layout.hpp"
#include "bak/skills.hpp"
#include "graphics/IGuiElement.hpp"
#include "graphics/texture.hpp"
#include "graphics/sprites.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/colors.hpp"
#include "gui/compass.hpp"
#include "gui/clickButton.hpp"
#include "gui/core/widget.hpp"
#include "gui/scene.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <utility>
#include <variant>
#include <vector>
namespace Gui {
class Blood : public Widget
{
public:
Blood(
glm::vec2 pos,
glm::vec2 dims,
Graphics::SpriteSheetIndex spriteSheet,
Graphics::TextureIndex image)
:
Widget{
ClipRegionTag{},
pos,
dims,
false
},
mImage{
ImageTag{},
spriteSheet,
image,
glm::vec2{pos},
glm::vec2{101, 4},
false
}
{
AddChildBack(&mImage);
}
void UpdateValue(unsigned value)
{
const auto& pos = mImage.GetPositionInfo().mPosition;
const auto& dims = GetPositionInfo().mDimensions;
SetPosition(glm::vec2{pos.x + 101 - value, pos.y});
SetDimensions(glm::vec2{value, dims.y});
}
Widget mImage;
};
class Skill : public Widget
{
public:
Skill(
glm::vec2 pos,
glm::vec2 dims,
Graphics::SpriteSheetIndex spriteSheet,
Graphics::TextureIndex swordImage,
Graphics::TextureIndex bloodImage,
Graphics::TextureIndex selectedImage,
std::function<void()>&& toggleSkillSelected)
:
Widget{
ImageTag{},
spriteSheet,
swordImage,
pos,
dims,
true
},
mText{
glm::vec2{34, -5},
glm::vec2{100, 16}
},
mBlood{
glm::vec2{31, 5},
glm::vec2{101, 4},
spriteSheet,
bloodImage},
mSelected{
ImageTag{},
spriteSheet,
selectedImage,
glm::vec2{-1, 5},
glm::vec2{5,5},
false
},
mSkillSelected{false},
mToggleSkillSelected{std::move(toggleSkillSelected)}
{
AddChildren();
}
void UpdateValue(
const Font& font,
BAK::SkillType skill,
unsigned value,
bool skillSelected,
bool unseenIprovement)
{
const auto skillStr = BAK::ToString(skill);
std::stringstream ss;
if (unseenIprovement)
ss << "\xf5";
else
ss << "#";
ss << skillStr << std::setw(18 - skillStr.size())
<< std::setfill(' ') << value << "%";
mText.SetText(font, ss.str());
mBlood.UpdateValue(value);
if (skillSelected)
mSkillSelected = true;
else
mSkillSelected = false;
AddChildren();
}
void AddChildren()
{
ClearChildren();
AddChildBack(&mText);
AddChildBack(&mBlood);
if (mSkillSelected)
AddChildBack(&mSelected);
}
bool OnMouseEvent(const MouseEvent& event) override
{
return std::visit(overloaded{
[this](const LeftMousePress& p){ return LeftMousePressed(p.mValue); },
[](const auto& p){ return false; }
},
event);
}
bool LeftMousePressed(glm::vec2 click)
{
if (Within(click))
{
std::invoke(mToggleSkillSelected);
return true;
}
return false;
}
TextBox mText;
Blood mBlood;
Widget mSelected;
bool mSkillSelected;
std::function<void()> mToggleSkillSelected;
};
class Skills : public ClickButtonBase
{
public:
static constexpr auto sSkillWidgetStart = 3;
static constexpr auto sSelectableSkillsOffset = 4;
Skills(
glm::vec2 pos,
glm::vec2 dims,
Graphics::SpriteSheetIndex spriteSheet,
Graphics::TextureIndex spriteOffset,
const BAK::Layout& layout,
std::function<void(BAK::SkillType)>&& toggleSkill,
std::function<void()>&& onRightMousePress)
:
ClickButtonBase{
pos,
dims,
[]{},
std::move(onRightMousePress)
},
mSkills{},
mToggleSkillSelected{std::move(toggleSkill)},
mLogger{Logging::LogState::GetLogger("Gui::Skills")}
{
mSkills.reserve(layout.GetSize());
for (unsigned i = sSkillWidgetStart; i < layout.GetSize(); i++)
{
auto& s = mSkills.emplace_back(
layout.GetWidgetLocation(i) - pos + glm::vec2{0, 8},
layout.GetWidgetDimensions(i),
spriteSheet,
Graphics::TextureIndex{spriteOffset.mValue + 21},
Graphics::TextureIndex{spriteOffset.mValue + 22},
Graphics::TextureIndex{spriteOffset.mValue + 23},
[this, skill=static_cast<BAK::SkillType>(i +1)](){
mToggleSkillSelected(skill);
});
}
for (auto& skill : mSkills)
AddChildBack(&skill);
}
bool OnMouseEvent(const MouseEvent& event) override
{
const auto result = Widget::OnMouseEvent(event);
ClickButtonBase::OnMouseEvent(event);
return result;
}
void UpdateSkills(
const Font& font,
const BAK::Skills& skills)
{
for (unsigned i = sSelectableSkillsOffset; i < BAK::Skills::sSkills; i++)
{
const auto skill = skills.GetSkill(static_cast<BAK::SkillType>(i));
mSkills[i - sSelectableSkillsOffset].UpdateValue(
font,
static_cast<BAK::SkillType>(i),
skill.mCurrent,
skill.mSelected,
skill.mUnseenImprovement);
}
}
private:
std::vector<Skill> mSkills;
std::function<void(BAK::SkillType)> mToggleSkillSelected;
const Logging::Logger& mLogger;
};
}
| 6,084
|
C++
|
.h
| 217
| 19.40553
| 82
| 0.565568
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,681
|
portrait.hpp
|
xavieran_BaKGL/gui/info/portrait.hpp
|
#pragma once
#include "bak/types.hpp"
#include "gui/actors.hpp"
#include "gui/colors.hpp"
#include "gui/label.hpp"
#include "gui/clickButton.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class Portrait : public Widget
{
public:
Portrait(
glm::vec2 pos,
glm::vec2 dims,
const Actors& actors,
const Font& font,
Graphics::SpriteSheetIndex spriteSheet,
Graphics::TextureIndex verticalBorder,
Graphics::TextureIndex horizontalBorder,
std::function<void()>&& onLeftMousePress,
std::function<void()>&& onRightMousePress)
:
Widget{
RectTag{},
pos,
dims,
Color::infoBackground,
true
},
mActors{actors},
mFont{font},
mClickButton{
glm::vec2{0},
dims,
std::move(onLeftMousePress),
std::move(onRightMousePress)},
mClipRegion{
ClipRegionTag{},
glm::vec2{0},
dims,
true},
mPortrait{
ImageTag{},
mActors.GetSpriteSheet(),
Graphics::TextureIndex{0},
glm::vec2{0},
dims,
true},
mLeftBorder{
ImageTag{},
spriteSheet,
verticalBorder,
glm::vec2{0},
glm::vec2{2, 72},
true},
mRightBorder{
ImageTag{},
spriteSheet,
verticalBorder,
glm::vec2{70, 0},
glm::vec2{2, 72},
true},
mTopBorder{
ImageTag{},
spriteSheet,
horizontalBorder,
glm::vec2{2, 0},
glm::vec2{222, 2},
true},
mBottomBorder{
ImageTag{},
spriteSheet,
horizontalBorder,
glm::vec2{1, 71},
glm::vec2{222, 2},
true},
mLabel{
glm::vec2{35, 72},
dims,
font,
"#None"},
mLogger{Logging::LogState::GetLogger("Gui::Portrait")}
{
AddChildBack(&mClickButton);
AddChildBack(&mClipRegion);
mClipRegion.AddChildBack(&mPortrait);
mClipRegion.AddChildBack(&mLeftBorder);
mClipRegion.AddChildBack(&mRightBorder);
mClipRegion.AddChildBack(&mTopBorder);
mClipRegion.AddChildBack(&mBottomBorder);
AddChildBack(&mLabel);
}
void SetCharacter(BAK::CharIndex character, std::string_view name)
{
mLogger.Debug() << "Setting char: " << character << " " << name <<"\n";
const auto s = "#" + std::string{name};
mLabel.SetText(s);
mLabel.SetCenter(glm::vec2{35, 72});
const auto& [texture, dims] = mActors.GetActorA(character.mValue + 1);
mPortrait.SetTexture(texture);
}
private:
const Actors& mActors;
const Font& mFont;
ClickButtonBase mClickButton;
Widget mClipRegion;
Widget mPortrait;
Widget mLeftBorder;
Widget mRightBorder;
Widget mTopBorder;
Widget mBottomBorder;
Label mLabel;
const Logging::Logger& mLogger;
};
}
| 3,261
|
C++
|
.h
| 119
| 18.495798
| 79
| 0.5536
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,682
|
infoScreen.hpp
|
xavieran_BaKGL/gui/info/infoScreen.hpp
|
#pragma once
#include "bak/dialogSources.hpp"
#include "bak/layout.hpp"
#include "bak/textureFactory.hpp"
#include "gui/info/portrait.hpp"
#include "gui/info/ratings.hpp"
#include "gui/info/skills.hpp"
#include "gui/info/spells.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/actors.hpp"
#include "gui/backgrounds.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class InfoScreen : public Widget
{
public:
static constexpr auto sLayoutFile = "REQ_INFO.DAT";
static constexpr auto sSkillRightClickDialog = BAK::KeyTarget{0x143};
static constexpr auto sPortraitWidget = 0;
static constexpr auto sExitWidget = 1;
static constexpr auto sSpellsWidget = 2;
InfoScreen(
IGuiManager& guiManager,
const Actors& actors,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font,
BAK::GameState& gameState)
:
Widget{
Graphics::DrawMode::Sprite,
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen("OPTIONS1.SCX"),
Graphics::ColorMode::Texture,
glm::vec4{1},
glm::vec2{0},
glm::vec2{320, 200},
true
},
mGuiManager{guiManager},
mFont{font},
mGameState{gameState},
mDialogScene{},
mSelectedCharacter{0},
mLayout{sLayoutFile},
mExitButton{
mLayout.GetWidgetLocation(sExitWidget),
mLayout.GetWidgetDimensions(sExitWidget),
mFont,
"#Exit",
[this]{ mGuiManager.DoFade(0.5, [this]{ mGuiManager.ExitSimpleScreen(); }); }
},
mSpellsButton{
mLayout.GetWidgetLocation(sSpellsWidget),
mLayout.GetWidgetDimensions(sSpellsWidget),
mFont,
"#Spells",
[this]{ mGuiManager.DoFade(0.5, [this]{
mSpells.SetSelectedCharacter(mSelectedCharacter);
mGuiManager.GetScreenStack().PushScreen(&mSpells); }); },
},
mPortrait{
mLayout.GetWidgetLocation(sPortraitWidget),
mLayout.GetWidgetDimensions(sPortraitWidget),
actors,
mFont,
std::get<Graphics::SpriteSheetIndex>(icons.GetStippledBorderVertical()),
std::get<Graphics::TextureIndex>(icons.GetStippledBorderHorizontal()),
std::get<Graphics::TextureIndex>(icons.GetStippledBorderVertical()),
[this](){
AdvanceCharacter(); },
[this](){
const auto character = mGameState
.GetParty()
.GetCharacter(BAK::ActiveCharIndex{mSelectedCharacter})
.GetIndex();
mGameState.SetDialogContext_7530(character.mValue);
mGuiManager.StartDialog(
BAK::DialogSources::mCharacterFlavourDialog, false, false, &mDialogScene);
}
},
mRatings{
mPortrait.GetPositionInfo().mPosition
+ glm::vec2{mPortrait.GetPositionInfo().mDimensions.x + 4, 0},
glm::vec2{222, mPortrait.GetPositionInfo().mDimensions.y},
mFont,
std::get<Graphics::SpriteSheetIndex>(icons.GetStippledBorderVertical()),
std::get<Graphics::TextureIndex>(icons.GetStippledBorderHorizontal()),
std::get<Graphics::TextureIndex>(icons.GetStippledBorderVertical())
},
mSkills{
glm::vec2{15, 100},
glm::vec2{200,200},
std::get<Graphics::SpriteSheetIndex>(icons.GetInventoryIcon(120)),
std::get<Graphics::TextureIndex>(icons.GetInventoryIcon(120)),
mLayout,
[this](auto skill){
ToggleSkill(skill);
},
[this](){
mGuiManager.StartDialog(
sSkillRightClickDialog, false, false, &mDialogScene);
}
},
mSpells{
mGuiManager,
backgrounds,
icons,
font,
gameState
},
mLogger{Logging::LogState::GetLogger("Gui::InfoScreen")}
{
AddChildren();
}
void SetSelectedCharacter(BAK::ActiveCharIndex character)
{
mSelectedCharacter = character;
mGameState.GetParty().GetCharacter(character).UpdateSkills();
AddChildren();
}
void UpdateCharacter()
{
auto& character = mGameState.GetParty().GetCharacter(mSelectedCharacter);
mSkills.UpdateSkills(mFont, character.mSkills);
mPortrait.SetCharacter(character.GetIndex(), character.mName);
mRatings.SetCharacter(character);
character.mSkills.ClearUnseenImprovements();
AddChildren();
}
void AdvanceCharacter()
{
SetSelectedCharacter(
mGameState.GetParty().NextActiveCharacter(mSelectedCharacter));
UpdateCharacter();
}
private:
void ToggleSkill(BAK::SkillType skill)
{
mLogger.Debug() << "Toggle Skill: " << BAK::ToString(skill) << "\n";
mGameState
.GetParty()
.GetCharacter(mSelectedCharacter)
.mSkills.ToggleSkill(skill);
UpdateCharacter();
}
void AddChildren()
{
ClearChildren();
AddChildBack(&mExitButton);
AddChildBack(&mSkills);
AddChildBack(&mPortrait);
AddChildBack(&mRatings);
if (mGameState.GetParty().GetCharacter(mSelectedCharacter).IsSpellcaster())
{
AddChildBack(&mSpellsButton);
}
}
IGuiManager& mGuiManager;
const Font& mFont;
BAK::GameState& mGameState;
NullDialogScene mDialogScene;
BAK::ActiveCharIndex mSelectedCharacter;
BAK::Layout mLayout;
ClickButton mExitButton;
ClickButton mSpellsButton;
Portrait mPortrait;
Ratings mRatings;
Skills mSkills;
SpellsScreen mSpells;
const Logging::Logger& mLogger;
};
}
| 6,153
|
C++
|
.h
| 181
| 24.977901
| 94
| 0.61956
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,683
|
lock.hpp
|
xavieran_BaKGL/gui/lock/lock.hpp
|
#pragma once
#include "bak/lock.hpp"
#include "bak/IContainer.hpp"
#include "bak/dialogSources.hpp"
#include "bak/inventory.hpp"
#include "bak/layout.hpp"
#include "bak/objectInfo.hpp"
#include "bak/textureFactory.hpp"
#include "gui/inventory/containerDisplay.hpp"
#include "gui/inventory/inventorySlot.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/core/dragEndpoint.hpp"
#include "gui/core/draggable.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class Lock :
public Widget
{
public:
Lock(const Icons& icons, glm::vec2 pos)
:
Widget{
RectTag{},
pos,
glm::vec2{80, 120},
glm::vec4{0},
true
},
mIcons{icons},
mShackle{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(mIcons.GetInventoryLockIcon(0)),
std::get<Graphics::TextureIndex>(mIcons.GetInventoryLockIcon(0)),
glm::vec2{13, 17},
std::get<glm::vec2>(mIcons.GetInventoryLockIcon(0)),
true
},
mLock{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(mIcons.GetInventoryLockIcon(4)),
std::get<Graphics::TextureIndex>(mIcons.GetInventoryLockIcon(4)),
glm::vec2{0, 54},
std::get<glm::vec2>(mIcons.GetInventoryLockIcon(4)),
true
},
mLogger{Logging::LogState::GetLogger("Gui::Lock")}
{
AddChildren();
}
void AdjustShacklePosition(glm::vec2 diff)
{
mShackle.AdjustPosition(diff);
}
void SetLocked()
{
mShackle.SetPosition({13, 17});
}
void SetUnlocked()
{
mShackle.SetPosition({13, 2});
}
void SetImageBasedOnLockType(BAK::LockType lock)
{
const auto lockIndex = std::invoke([&](){
switch (lock)
{
case BAK::LockType::Easy: return 1;
case BAK::LockType::Medium: return 2;
case BAK::LockType::Hard: return 3;
case BAK::LockType::Unpickable: return 4;
default: return 0;
}
});
if (lockIndex > 1)
mLock.SetPosition({ 6, 54});
else
mLock.SetPosition({ 0, 54});
const auto [ss, ti, dims] = mIcons.GetInventoryLockIcon(lockIndex);
mLock.SetSpriteSheet(ss);
mLock.SetTexture(ti);
mLock.SetDimensions(dims);
}
private:
void AddChildren()
{
AddChildBack(&mShackle);
AddChildBack(&mLock);
}
private:
const Icons& mIcons;
Widget mShackle;
Widget mLock;
const Logging::Logger& mLogger;
};
}
| 2,927
|
C++
|
.h
| 106
| 20.811321
| 81
| 0.610635
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,684
|
moredhelScreen.hpp
|
xavieran_BaKGL/gui/lock/moredhelScreen.hpp
|
#pragma once
#include "bak/lock.hpp"
#include "bak/IContainer.hpp"
#include "bak/dialogSources.hpp"
#include "bak/layout.hpp"
#include "gui/lock/tumbler.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/core/clickable.hpp"
#include "gui/core/dragEndpoint.hpp"
#include "gui/core/draggable.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class MoredhelScreen :
public Widget
{
public:
static constexpr auto sLayoutFile = "REQ_PUZL.DAT";
static constexpr auto sBackground = "PUZZLE.SCX";
// Request offsets
static constexpr auto mExitRequest = 0;
static constexpr auto mExitButton = 13;
MoredhelScreen(
IGuiManager& guiManager,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& alienFont,
const Font& puzzleFont,
BAK::GameState& gameState)
:
// Black background
Widget{
RectTag{},
glm::vec2{0, 0},
glm::vec2{320, 200},
Color::black,
true
},
mGuiManager{guiManager},
mAlienFont{alienFont},
mPuzzleFont{puzzleFont},
mIcons{icons},
mGameState{gameState},
mDialogScene{
[]{},
[]{},
[](const auto&){ }
},
mFairyChest{},
mLayout{sLayoutFile},
mFrame{
ImageTag{},
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen(sBackground),
glm::vec2{0},
GetPositionInfo().mDimensions,
true
},
mExit{
mLayout.GetWidgetLocation(mExitRequest),
mLayout.GetWidgetDimensions(mExitRequest),
std::get<Graphics::SpriteSheetIndex>(mIcons.GetButton(mExitButton)),
std::get<Graphics::TextureIndex>(mIcons.GetButton(mExitButton)),
std::get<Graphics::TextureIndex>(mIcons.GetPressedButton(mExitButton)),
[this]{ CantOpenLock(); },
[]{}
},
mLeftClasp{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(mIcons.GetInventoryMiscIcon(11)),
std::get<Graphics::TextureIndex>(mIcons.GetInventoryMiscIcon(11)),
mLayout.GetWidgetLocation(1),
mLayout.GetWidgetDimensions(1),
true
},
mRightClasp{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(mIcons.GetInventoryMiscIcon(11)),
std::get<Graphics::TextureIndex>(mIcons.GetInventoryMiscIcon(11)),
mLayout.GetWidgetLocation(1),
mLayout.GetWidgetDimensions(1),
true
},
mDescription{
{40, 100},
{240, 64}
},
mTumblers{},
mReqLocs{},
mContainer{nullptr},
mNeedRefresh{false},
mUnlocked{false},
mLogger{Logging::LogState::GetLogger("Gui::MoredhelScreen")}
{
}
void ResetUnlocked()
{
mUnlocked = false;
}
bool IsUnlocked() const
{
return mUnlocked;
}
BAK::IContainer* GetContainer() const
{
return mContainer;
}
void SetContainer(BAK::IContainer* container)
{
ASSERT(container != nullptr);
mContainer = container;
const auto& snippet = BAK::DialogSources::GetFairyChestKey(
container->GetLock().mFairyChestIndex);
mFairyChest = BAK::GenerateFairyChest(
std::string{BAK::DialogStore::Get().GetSnippet(snippet).GetText()});
ResetUnlocked();
RefreshGui();
}
private:
void RefreshGui()
{
ClearChildren();
UpdateTumblers();
mDescription.SetText(
mPuzzleFont,
"\xf7" + mFairyChest->mHint, true, true);
mReqLocs.clear();
mReqLocs.reserve(mLayout.GetSize());
for (unsigned i = 0; i < mLayout.GetSize(); i++)
{
mReqLocs.emplace_back(
mLayout.GetWidgetLocation(i),
mLayout.GetWidgetDimensions(i));
std::stringstream ss{};
ss << i;
mReqLocs.back().SetText(mPuzzleFont, ss.str());
}
AddChildren();
}
void UpdateTumblers()
{
ASSERT(mFairyChest);
mTumblers.clear();
const auto tumblers = mFairyChest->mAnswer.size();
ASSERT(tumblers <= 15);
unsigned margin = 15 - tumblers;
unsigned startLocation = margin / 2;
mTumblers.reserve(tumblers);
for (unsigned i = 0; i < tumblers; i++)
{
mTumblers.emplace_back(
[this, i](){ IncrementTumbler(i); },
mLayout.GetWidgetLocation(1 + startLocation + i)
+ glm::vec2{0, 56},
mLayout.GetWidgetDimensions(1 + startLocation + i),
mPuzzleFont);
mTumblers.back().SetDigits(i, *mFairyChest);
// if char == ' ' dont add the tumbler...?
}
}
void IncrementTumbler(unsigned tumblerIndex)
{
ASSERT(tumblerIndex < mTumblers.size());
mTumblers[tumblerIndex].NextDigit();
EvaluateLock();
}
void EvaluateLock()
{
std::string guess{};
for (const auto& t : mTumblers)
guess.push_back(t.GetDigit());
if (guess == mFairyChest->mAnswer)
{
Unlocked();
}
}
void Unlocked()
{
mUnlocked = true;
mDialogScene.SetDialogFinished(
[this](const auto&)
{
mGuiManager.ExitLock();
mDialogScene.ResetDialogFinished();
});
mGuiManager.StartDialog(
BAK::DialogSources::mOpenedWordlock,
false,
false,
&mDialogScene);
}
void CantOpenLock()
{
mUnlocked = false;
mDialogScene.SetDialogFinished(
[this](const auto&)
{
mGuiManager.ExitLock();
mDialogScene.ResetDialogFinished();
});
mGuiManager.StartDialog(
BAK::DialogSources::mCantOpenWorldock,
false,
false,
&mDialogScene);
}
void AddChildren()
{
AddChildBack(&mFrame);
AddChildBack(&mExit);
AddChildBack(&mDescription);
for (auto& t : mTumblers)
AddChildBack(&t);
}
private:
IGuiManager& mGuiManager;
const Font& mAlienFont;
const Font& mPuzzleFont;
const Icons& mIcons;
BAK::GameState& mGameState;
DynamicDialogScene mDialogScene;
std::optional<BAK::FairyChest> mFairyChest;
BAK::Layout mLayout;
Widget mFrame;
ClickButtonImage mExit;
Widget mLeftClasp;
Widget mRightClasp;
TextBox mDescription;
using ClickableTumbler = Clickable<
Tumbler,
LeftMousePress,
std::function<void()>>;
std::vector<ClickableTumbler> mTumblers;
std::vector<TextBox> mReqLocs;
BAK::IContainer* mContainer;
bool mNeedRefresh;
bool mUnlocked;
const Logging::Logger& mLogger;
};
}
| 7,384
|
C++
|
.h
| 250
| 20.928
| 83
| 0.58645
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,685
|
tumbler.hpp
|
xavieran_BaKGL/gui/lock/tumbler.hpp
|
#pragma once
#include "bak/lock.hpp"
#include "bak/IContainer.hpp"
#include "bak/dialogSources.hpp"
#include "bak/inventory.hpp"
#include "bak/layout.hpp"
#include "bak/objectInfo.hpp"
#include "bak/textureFactory.hpp"
#include "gui/core/clickable.hpp"
#include "gui/core/dragEndpoint.hpp"
#include "gui/core/draggable.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class Tumbler :
public Widget
{
public:
Tumbler(
glm::vec2 pos,
glm::vec2 dims,
const Font& font)
:
Widget{
RectTag{},
pos,
dims,
Color::tumblerBackground,
true
},
mFont{font},
mSelectedDigit{0},
mDigits{},
mCharacter{
{0,0},
dims
}
{
AddChildren();
}
void SetDigits(unsigned charIndex, const BAK::FairyChest& chest)
{
for (unsigned i = 0; i < chest.mOptions.size(); i++)
{
ASSERT(charIndex < chest.mOptions[i].size());
mDigits.emplace_back(chest.mOptions[i][charIndex]);
}
SetDigit(0);
}
void NextDigit()
{
const auto nextDigit = (mSelectedDigit + 1) % mDigits.size();
SetDigit(nextDigit);
}
char GetDigit() const
{
return mDigits[mSelectedDigit];
}
private:
void SetDigit(unsigned digitIndex)
{
ASSERT(digitIndex < mDigits.size());
mSelectedDigit = digitIndex;
mCharacter.SetText(mFont, "\xf7" + std::string{mDigits[digitIndex]}, true, true);
}
void AddChildren()
{
ClearChildren();
AddChildBack(&mCharacter);
}
const Font& mFont;
unsigned mSelectedDigit;
std::vector<char> mDigits;
TextBox mCharacter;
};
}
| 1,998
|
C++
|
.h
| 84
| 17.952381
| 89
| 0.617089
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,686
|
lockScreen.hpp
|
xavieran_BaKGL/gui/lock/lockScreen.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "bak/lock.hpp"
#include "bak/IContainer.hpp"
#include "bak/itemNumbers.hpp"
#include "bak/dialogSources.hpp"
#include "bak/inventory.hpp"
#include "bak/layout.hpp"
#include "bak/objectInfo.hpp"
#include "bak/textureFactory.hpp"
#include "bak/state/lock.hpp"
#include "gui/animator.hpp"
#include "gui/lock/lock.hpp"
#include "gui/inventory/containerDisplay.hpp"
#include "gui/inventory/details.hpp"
#include "gui/inventory/inventorySlot.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/core/clickable.hpp"
#include "gui/core/dragEndpoint.hpp"
#include "gui/core/draggable.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class LockScreen :
public Widget
{
public:
static constexpr auto sLayoutFile = "REQ_INV.DAT";
static constexpr auto sBackground = "INVENTOR.SCX";
static constexpr auto sPickBrokeSound = AudioA::SoundIndex{0x5};
static constexpr auto sPickedLockSound = AudioA::SoundIndex{0x16};
static constexpr auto sUseKeySound = AudioA::SoundIndex{0x1e};
static constexpr auto sKeyBrokeSound = AudioA::SoundIndex{0x2b};
static constexpr auto sOpenLockSound = AudioA::SoundIndex{30};
// Request offsets
static constexpr auto mContainerTypeRequest = 3;
static constexpr auto mNextPageButton = 52;
static constexpr auto mNextPageRequest = 4;
static constexpr auto mExitRequest = 5;
static constexpr auto mExitButton = 13;
static constexpr auto mGoldRequest = 6;
LockScreen(
IGuiManager& guiManager,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font,
BAK::GameState& gameState)
:
// Black background
Widget{
RectTag{},
glm::vec2{0, 0},
glm::vec2{320, 200},
Color::black,
true
},
mGuiManager{guiManager},
mFont{font},
mIcons{icons},
mGameState{gameState},
mDialogScene{
[]{},
[]{},
[](const auto&){}
},
mLayout{sLayoutFile},
mFrame{
ImageTag{},
backgrounds.GetSpriteSheet(),
backgrounds.GetScreen(sBackground),
glm::vec2{0},
GetPositionInfo().mDimensions,
true
},
mCharacters{},
mExit{
mLayout.GetWidgetLocation(mExitRequest),
mLayout.GetWidgetDimensions(mExitRequest),
std::get<Graphics::SpriteSheetIndex>(mIcons.GetButton(mExitButton)),
std::get<Graphics::TextureIndex>(mIcons.GetButton(mExitButton)),
std::get<Graphics::TextureIndex>(mIcons.GetPressedButton(mExitButton)),
[this]{ mGuiManager.ExitLock(); },
[]{}
},
mGoldDisplay{
mLayout.GetWidgetLocation(mGoldRequest),
mLayout.GetWidgetDimensions(mGoldRequest),
},
mDetails{
glm::vec2{},
glm::vec2{},
mIcons,
mFont,
[this]{ ExitDetails(); }
},
mDisplayDetails{},
mLock{
[this](){ ShowLockDescription(); },
[this](const auto& item){ AttemptLock(item); },
icons,
glm::vec2{13, 12}},
mContainerTypeDisplay{
mLayout.GetWidgetLocation(mContainerTypeRequest),
mLayout.GetWidgetDimensions(mContainerTypeRequest),
std::get<Graphics::SpriteSheetIndex>(mIcons.GetInventoryMiscIcon(11)),
std::get<Graphics::TextureIndex>(mIcons.GetInventoryMiscIcon(11)),
std::get<Graphics::TextureIndex>(mIcons.GetInventoryMiscIcon(11)),
[]{},
[]{}
},
mContainerScreen{
{105, 11},
{200, 121},
mIcons,
mFont,
[this](const auto& item){
ShowItemDescription(item);
}
},
mSelectedCharacter{},
mContainer{nullptr},
mNeedRefresh{false},
mUnlocked{false},
mLogger{Logging::LogState::GetLogger("Gui::LockScreen")}
{
mCharacters.reserve(3);
mContainerTypeDisplay.CenterImage(
std::get<2>(mIcons.GetInventoryMiscIcon(11)));
}
void SetSelectedCharacter(
BAK::ActiveCharIndex character)
{
mLogger.Debug() << "Setting seleted character to: " << character << "\n";
mSelectedCharacter = character;
mNeedRefresh = true;
}
void ResetUnlocked()
{
mUnlocked = false;
}
bool IsUnlocked() const
{
return mUnlocked;
}
BAK::IContainer* GetContainer() const
{
return mContainer;
}
void SetContainer(BAK::IContainer* container)
{
ASSERT(container != nullptr);
mContainer = container;
mLock.SetImageBasedOnLockType(
BAK::ClassifyLock(container->GetLock().mRating));
mLock.SetLocked();
ResetUnlocked();
// Automatically set to the highest skilled character
const auto [character, _] = mGameState.GetPartySkill(
BAK::SkillType::Lockpick,
true);
ASSERT(mGameState.GetParty().FindActiveCharacter(character));
SetSelectedCharacter(
*mGameState.GetParty().FindActiveCharacter(character));
mContainerScreen.SetContainer(
&mGameState.GetParty().GetKeys());
RefreshGui();
}
/* Widget */
bool OnMouseEvent(const MouseEvent& event) override
{
const bool handled = Widget::OnMouseEvent(event);
// Don't refresh things until we have finished
// processing this event. This prevents deleting
// children that are about to handle it.
if (mNeedRefresh)
{
RefreshGui();
mNeedRefresh = false;
}
return handled;
}
void PropagateUp(const DragEvent& event) override
{
mLogger.Debug() << __FUNCTION__ << " ev: " << event << "\n";
bool handled = Widget::OnDragEvent(event);
if (handled)
return;
}
private:
void RefreshGui()
{
ClearChildren();
UpdatePartyMembers();
UpdateGold();
mContainerScreen.RefreshGui();
AddChildren();
}
auto& GetCharacter(BAK::ActiveCharIndex i)
{
return mGameState.GetParty().GetCharacter(i);
}
void ShowLockDescription()
{
unsigned context = 0;
auto dialog = BAK::DialogSources::mLockDialog;
const auto lockRating = mContainer->GetLock().mRating;
const auto lockIndex = BAK::GetLockIndex(lockRating);
const auto lockpickSkill = GetCharacter(*mSelectedCharacter)
.GetSkill(BAK::SkillType::Lockpick);
if (!lockIndex)
{
context = BAK::DescribeLock(lockpickSkill, lockRating);
}
else
{
if (BAK::State::CheckLockHasBeenSeen(mGameState, *lockIndex))
{
const auto item = BAK::GetCorrespondingKey(*lockIndex);
if (mGameState.GetParty().HaveItem(item))
context = 0;
else
context = 1;
mGameState.SetInventoryItem(
BAK::InventoryItemFactory::MakeItem(item, 1));
dialog = BAK::DialogSources::mLockKnown;
}
else
{
context = BAK::DescribeLock(lockpickSkill, lockRating);
}
}
mGameState.SetDialogContext_7530(context);
mGuiManager.StartDialog(
dialog,
false,
false,
&mDialogScene);
}
void AttemptLock(const InventorySlot& itemSlot)
{
ASSERT(mContainer);
ASSERT(mSelectedCharacter);
auto context = 0;
auto dialog = BAK::KeyTarget{0};
mGameState.SetActiveCharacter(GetCharacter(*mSelectedCharacter).mCharacterIndex);
const auto& item = itemSlot.GetItem();
ASSERT(item.IsKey());
const auto& skill = GetCharacter(*mSelectedCharacter)
.GetSkill(BAK::SkillType::Lockpick);
const auto lockRating = mContainer->GetLock().mRating;
if (item.GetItemIndex() == BAK::sPicklock)
{
if (BAK::CanPickLock(skill, lockRating))
{
AudioA::AudioManager::Get().PlaySound(sPickedLockSound);
GetCharacter(*mSelectedCharacter)
.ImproveSkill(BAK::SkillType::Lockpick, BAK::SkillChange::ExercisedSkill, 2);
mGuiManager.AddAnimator(
std::make_unique<LinearAnimator>(
.25,
glm::vec4{13, 17, 0, 0},
glm::vec4{13, 2, 0, 0},
[&](const auto& delta){
mLock.AdjustShacklePosition(glm::vec2{delta});
return false;
},
[&](){ Unlocked(BAK::DialogSources::mLockPicked); }
));
mUnlocked = true;
}
else
{
if (BAK::PicklockSkillImproved())
{
GetCharacter(*mSelectedCharacter).ImproveSkill(
BAK::SkillType::Lockpick,
BAK::SkillChange::ExercisedSkill,
2);
}
if (BAK::PicklockBroken(skill, lockRating))
{
// Remove a picklock from inventory...
dialog = BAK::DialogSources::mPicklockBroken;
mGameState.GetParty().RemoveItem('P', 1);
AudioA::AudioManager::Get().PlaySound(sPickBrokeSound);
}
else
{
dialog = BAK::DialogSources::mFailedToPickLock;
}
}
}
else
{
AudioA::AudioManager::Get().PlaySound(sUseKeySound);
if (BAK::TryOpenLockWithKey(item, lockRating))
{
AudioA::AudioManager::Get().PlaySound(sOpenLockSound);
// succeeded..
ASSERT(BAK::GetLockIndex(lockRating));
mGameState.Apply(BAK::State::SetLockHasBeenSeen, *BAK::GetLockIndex(lockRating));
//mLock.SetUnlocked();
mGuiManager.AddAnimator(
std::make_unique<LinearAnimator>(
.2,
glm::vec4{13, 17, 0, 0},
glm::vec4{13, 2, 0, 0},
[&](const auto& delta){
mLock.AdjustShacklePosition(glm::vec2{delta});
return false;
},
[&](){ Unlocked(BAK::DialogSources::mKeyOpenedLock); }
));
mUnlocked = true;
}
else
{
if (BAK::WouldKeyBreak(item, lockRating)
&& BAK::KeyBroken(item, skill, lockRating))
{
mGameState.GetParty().RemoveItem(item.GetItemIndex().mValue, 1);
dialog = BAK::DialogSources::mKeyBroken;
AudioA::AudioManager::Get().PlaySound(sKeyBrokeSound);
}
else
{
dialog = BAK::DialogSources::mKeyDoesntFit;
}
}
}
mNeedRefresh = true;
if (!mUnlocked)
{
mGameState.SetDialogContext_7530(context);
mGuiManager.StartDialog(
dialog,
false,
false,
&mDialogScene);
}
}
void Unlocked(BAK::KeyTarget dialog)
{
mGameState.SetDialogContext_7530(0);
mDialogScene.SetDialogFinished(
[this](const auto&)
{
mGuiManager.ExitLock();
mDialogScene.ResetDialogFinished();
});
mGuiManager.StartDialog(
dialog,
false,
false,
&mDialogScene);
}
void ShowItemDescription(const BAK::InventoryItem& item)
{
mDetails.AddItem(item, mGameState);
mDisplayDetails = true;
AddChildren();
}
void ExitDetails()
{
mDisplayDetails = false;
AddChildren();
}
void UpdatePartyMembers()
{
mCharacters.clear();
const auto& party = mGameState.GetParty();
BAK::ActiveCharIndex person{0};
do
{
const auto [spriteSheet, image, _] = mIcons.GetCharacterHead(
party.GetCharacter(person).GetIndex().mValue);
mCharacters.emplace_back(
[this, character=person]{
// Switch character
SetSelectedCharacter(character);
},
[this, character=person]{
mGuiManager.ShowCharacterPortrait(character);
},
ImageTag{},
spriteSheet,
image,
mLayout.GetWidgetLocation(person.mValue),
mLayout.GetWidgetDimensions(person.mValue),
true
);
if (person != mSelectedCharacter)
{
mCharacters[person.mValue].SetColor(glm::vec4{.05, .05, .05, 1});
mCharacters[person.mValue].SetColorMode(Graphics::ColorMode::TintColor);
}
person = party.NextActiveCharacter(person);
} while (person != BAK::ActiveCharIndex{0});
}
void UpdateGold()
{
const auto gold = mGameState.GetParty().GetGold();
const auto text = ToString(gold);
const auto [textDims, _] = mGoldDisplay.SetText(mFont, text);
// Justify text to the right
const auto basePos = mLayout.GetWidgetLocation(mGoldRequest);
const auto newPos = basePos
+ glm::vec2{
3 + mLayout.GetWidgetDimensions(mGoldRequest).x - textDims.x,
4};
mGoldDisplay.SetPosition(newPos);
}
void AddChildren()
{
ClearChildren();
AddChildBack(&mFrame);
if (mDisplayDetails)
AddChildBack(&mDetails);
AddChildBack(&mExit);
AddChildBack(&mGoldDisplay);
AddChildBack(&mContainerTypeDisplay);
for (auto& character : mCharacters)
AddChildBack(&character);
if (mDisplayDetails)
return;
AddChildBack(&mLock);
AddChildBack(&mContainerScreen);
}
private:
IGuiManager& mGuiManager;
const Font& mFont;
const Icons& mIcons;
BAK::GameState& mGameState;
DynamicDialogScene mDialogScene;
BAK::Layout mLayout;
Widget mFrame;
using CharacterButton = Clickable<
Clickable<
Widget,
RightMousePress,
std::function<void()>>,
LeftMousePress,
std::function<void()>>;
std::vector<CharacterButton> mCharacters;
ClickButtonImage mExit;
TextBox mGoldDisplay;
Details mDetails;
bool mDisplayDetails;
Clickable<
ItemEndpoint<Lock>,
RightMousePress,
std::function<void()>> mLock;
ClickButtonImage mContainerTypeDisplay;
ContainerDisplay mContainerScreen;
std::optional<BAK::ActiveCharIndex> mSelectedCharacter;
BAK::IContainer* mContainer;
bool mNeedRefresh;
bool mUnlocked;
const Logging::Logger& mLogger;
};
}
| 15,963
|
C++
|
.h
| 471
| 23.142251
| 97
| 0.564698
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,687
|
containerDisplay.hpp
|
xavieran_BaKGL/gui/inventory/containerDisplay.hpp
|
#pragma once
#include "bak/IContainer.hpp"
#include "bak/dialogSources.hpp"
#include "bak/inventory.hpp"
#include "bak/layout.hpp"
#include "bak/objectInfo.hpp"
#include "gui/inventory/equipmentSlot.hpp"
#include "gui/inventory/inventorySlot.hpp"
#include "gui/inventory/itemArranger.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/core/dragEndpoint.hpp"
#include "gui/core/draggable.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class ContainerDisplay :
public Widget
{
public:
ContainerDisplay(
glm::vec2 pos,
glm::vec2 dims,
const Icons& icons,
const Font& font,
std::function<void(const BAK::InventoryItem&)>&& showDescription)
:
// Black background
Widget{
RectTag{},
pos,
dims,
Color::black,
true
},
mFont{font},
mIcons{icons},
mInventoryItems{},
mContainer{nullptr},
mShowDescription{std::move(showDescription)},
mLogger{Logging::LogState::GetLogger("Gui::ContainerDisplay")}
{
assert(mShowDescription);
mInventoryItems.reserve(20);
}
void SetContainer(BAK::IContainer* container)
{
ASSERT(container);
mContainer = container;
}
void RefreshGui()
{
ClearChildren();
UpdateInventoryContents();
AddChildren();
}
private:
void ShowItemDescription(const BAK::InventoryItem& item)
{
mShowDescription(item);
}
void UpdateInventoryContents()
{
ASSERT(mContainer != nullptr);
mInventoryItems.clear();
const auto& inventory = mContainer->GetInventory();
std::vector<
std::pair<
BAK::InventoryIndex,
const BAK::InventoryItem*>> items{};
const auto numItems = inventory.GetItems().size();
mInventoryItems.reserve(numItems);
items.reserve(numItems);
unsigned index{0};
std::transform(
inventory.GetItems().begin(), inventory.GetItems().end(),
std::back_inserter(items),
[&index](const auto& i) -> std::pair<BAK::InventoryIndex, const BAK::InventoryItem*> {
return std::make_pair(BAK::InventoryIndex{index++}, &i);
});
const auto slotDims = glm::vec2{40, 29};
auto arranger = ItemArranger{};
if ( mContainer->GetContainerType() == BAK::ContainerType::Shop
|| mContainer->GetContainerType() == BAK::ContainerType::Inn)
{
arranger.PlaceItems(
items.begin(), items.begin() + 6,
3, 2,
glm::vec2{98, 60},
true,
[&](auto invIndex, const auto& item, const auto itemPos, const auto dims)
{
mInventoryItems.emplace_back(
itemPos,
dims,
mFont,
mIcons,
invIndex,
item,
[]{},
[&]{
ShowItemDescription(item);
});
});
}
else
{
std::sort(
items.begin(), items.end(),
[](const auto& l, const auto& r){
return (std::get<1>(l)->GetObject().mImageSize
> std::get<1>(r)->GetObject().mImageSize);
});
arranger.PlaceItems(
items.begin(), items.end(),
12, 4,
slotDims,
false,
[&](auto invIndex, const auto& item, const auto itemPos, const auto dims)
{
mInventoryItems.emplace_back(
itemPos,
dims,
mFont,
mIcons,
invIndex,
item,
[]{},
[&]{
ShowItemDescription(item);
});
});
}
}
void AddChildren()
{
for (auto& item : mInventoryItems)
AddChildBack(&item);
}
private:
const Font& mFont;
const Icons& mIcons;
std::vector<DraggableItem> mInventoryItems;
BAK::IContainer* mContainer;
std::function<void(const BAK::InventoryItem&)> mShowDescription;
const Logging::Logger& mLogger;
};
}
| 4,849
|
C++
|
.h
| 157
| 20.242038
| 98
| 0.526248
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,688
|
inventoryScreen.hpp
|
xavieran_BaKGL/gui/inventory/inventoryScreen.hpp
|
#pragma once
#include "audio/audio.hpp"
#include "bak/IContainer.hpp"
#include "bak/dialogSources.hpp"
#include "bak/gameState.hpp"
#include "bak/inventory.hpp"
#include "bak/layout.hpp"
#include "bak/objectInfo.hpp"
#include "bak/textureFactory.hpp"
#include "gui/inventory/containerDisplay.hpp"
#include "gui/inventory/details.hpp"
#include "gui/inventory/equipmentSlot.hpp"
#include "gui/inventory/inventorySlot.hpp"
#include "gui/inventory/itemArranger.hpp"
#include "gui/inventory/shopDisplay.hpp"
#include "gui/inventory/splitStackDialog.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/core/clickable.hpp"
#include "gui/core/dragEndpoint.hpp"
#include "gui/core/draggable.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <optional>
#include <utility>
#include <variant>
namespace Gui {
static constexpr auto BUY_SOUND = AudioA::SoundIndex{60};
static constexpr auto DRAG_SOUND = AudioA::SoundIndex{61};
class InventoryScreen : public Widget
{
public:
static constexpr auto sLayoutFile = "REQ_INV.DAT";
static constexpr auto sBackground = "INVENTOR.SCX";
// Request offsets
static constexpr auto mContainerTypeRequest = 3;
static constexpr auto mNextPageButton = 52;
static constexpr auto mNextPageRequest = 4;
static constexpr auto mExitRequest = 5;
static constexpr auto mExitButton = 13;
static constexpr auto mGoldRequest = 6;
InventoryScreen(
IGuiManager& guiManager,
const Backgrounds& backgrounds,
const Icons& icons,
const Font& font,
BAK::GameState& gameState);
void SetSelectedCharacter(
BAK::ActiveCharIndex character);
void SetSelectionMode(bool, std::function<void(std::optional<std::pair<BAK::ActiveCharIndex, BAK::InventoryIndex>>)>&&);
void ClearContainer();
// containerType determines the image used from INVMISC.BMX
void SetContainer(BAK::IContainer* container, BAK::EntityType entityType);
/* Widget */
bool OnMouseEvent(const MouseEvent& event) override;
void PropagateUp(const DragEvent& event) override;
std::optional<std::pair<BAK::ActiveCharIndex, BAK::InventoryIndex>> GetSelectedItem() const;
private:
auto& GetCharacter(BAK::ActiveCharIndex i)
{
return mGameState.GetParty().GetCharacter(i);
}
void StartDialog(BAK::Target target)
{
mGuiManager.StartDialog(
target,
false,
false,
&mDialogScene);
}
void RefreshGui();
void ExitDetails();
void SetContainerTypeImage(unsigned containerType);
void ShowContainer();
void ShowCharacter(BAK::ActiveCharIndex character);
void TransferItemFromCharacterToCharacter(
InventorySlot& slot,
unsigned amount,
BAK::ActiveCharIndex source,
BAK::ActiveCharIndex dest);
void TransferItemFromContainerToCharacter(
InventorySlot& slot,
BAK::ActiveCharIndex character,
bool share,
unsigned amount);
void SellItem(
InventorySlot& slot,
BAK::ActiveCharIndex character);
void BuyItem(
InventorySlot& slot,
BAK::ActiveCharIndex character,
bool share,
unsigned amount);
void HaggleItem(
InventorySlot& slot,
BAK::ActiveCharIndex character);
void TransferItemToShop(
InventorySlot& slot,
BAK::ActiveCharIndex character);
void TransferItemFromShopToCharacter(
InventorySlot& slot,
BAK::ActiveCharIndex character,
bool share,
unsigned amount);
// This happens at the callback on characters
void TransferItemToCharacter(
InventorySlot& slot,
BAK::ActiveCharIndex character,
bool share,
unsigned amount);
void SplitStackBeforeTransferItemToCharacter(
InventorySlot& slot,
BAK::ActiveCharIndex character);
// This happens at the callback on container display
void MoveItemToContainer(InventorySlot& slot, bool share, unsigned amount);
void SplitStackBeforeMoveItemToContainer(InventorySlot& slot);
// This happens at the callback on equipment slots
void MoveItemToEquipmentSlot(
InventorySlot& item,
BAK::ItemType slot);
void CompleteTransferStack(bool share, unsigned amount);
void UseItem(BAK::InventoryIndex inventoryIndex);
void UseItem(InventorySlot& item, BAK::InventoryIndex itemIndex);
void AdvanceNextPage();
void ShowItemDescription(const BAK::InventoryItem& item);
void HighlightValidDrops(const InventorySlot& slot);
void UnhighlightDrops();
void UpdatePartyMembers();
void UpdateGold();
void UpdateInventoryContents();
void AddChildren();
void CheckExclusivity();
void HandleItemSelected();
private:
IGuiManager& mGuiManager;
const Font& mFont;
const Icons& mIcons;
BAK::GameState& mGameState;
DynamicDialogScene mDialogScene;
BAK::Layout mLayout;
Widget mFrame;
using CharacterButton = Clickable<
Clickable<
Widget,
RightMousePress,
std::function<void()>>,
LeftMousePress,
std::function<void()>>;
std::vector<ItemEndpoint<CharacterButton>> mCharacters;
ClickButtonImage mNextPage;
ClickButtonImage mExit;
TextBox mGoldDisplay;
// click into shop or keys, etc.
ItemEndpoint<ClickButtonImage> mContainerTypeDisplay;
ContainerDisplay mContainerScreen;
ShopDisplay mShopScreen;
using ItemEndpointEquipmentSlot = ItemEndpoint<EquipmentSlot>;
Details mDetails;
ItemEndpointEquipmentSlot mWeapon;
ItemEndpointEquipmentSlot mCrossbow;
ItemEndpointEquipmentSlot mArmor;
std::vector<ItemEndpoint<DraggableItem>> mInventoryItems;
SplitStackDialog mSplitStackDialog;
std::optional<BAK::ActiveCharIndex> mSelectedCharacter;
bool mDisplayContainer;
bool mItemSelectionMode;
bool mDisplayDetails;
std::function<void(std::optional<std::pair<BAK::ActiveCharIndex, BAK::InventoryIndex>>)> mItemSelectionCallback;
std::optional<BAK::InventoryIndex> mSelectedItem;
BAK::IContainer* mContainer;
bool mNeedRefresh;
const Logging::Logger& mLogger;
};
}
| 6,492
|
C++
|
.h
| 181
| 30.099448
| 124
| 0.732797
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,689
|
modifiers.hpp
|
xavieran_BaKGL/gui/inventory/modifiers.hpp
|
#pragma once
#include "bak/inventoryItem.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
namespace Gui {
class Modifiers :
public Widget
{
public:
Modifiers(
glm::vec2 pos,
glm::vec2 dims,
const Icons& icons,
const BAK::InventoryItem& item)
:
Widget{
RectTag{},
pos,
dims,
glm::vec4{},
true
},
mIcons{icons},
mItemRef{item},
mModifiers{}
{
UpdateModifiers();
AddChildren();
}
void UpdateModifiers()
{
mModifiers.clear();
const auto mods = mItemRef.GetModifiers();
glm::vec2 pos = glm::vec2{0, 0};
if (mItemRef.IsPoisoned())
{
const auto [ss, ti, dims] = mIcons.GetInventoryModifierIcon(0);
pos.x += dims.x + 2;
mModifiers.emplace_back(
ImageTag{},
ss,
ti,
pos,
dims,
true);
}
for (const auto& mod : mods)
{
const auto [ss, ti, dims] = mIcons.GetInventoryModifierIcon(
static_cast<unsigned>(mod) + 1);
pos.x += dims.x + 2;
mModifiers.emplace_back(
ImageTag{},
ss,
ti,
pos,
dims,
true);
}
}
private:
void AddChildren()
{
ClearChildren();
for (auto& mod : mModifiers)
AddChildBack(&mod);
}
const Icons& mIcons;
const BAK::InventoryItem& mItemRef;
std::vector<Widget> mModifiers;
};
}
| 1,771
|
C++
|
.h
| 74
| 14.445946
| 75
| 0.479762
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,690
|
details.hpp
|
xavieran_BaKGL/gui/inventory/details.hpp
|
#pragma once
#include "bak/dialogSources.hpp"
#include "bak/spells.hpp"
#include "bak/gameState.hpp"
#include "bak/inventoryItem.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/centeredImage.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
namespace Gui {
class Details : public Widget
{
public:
Details(
glm::vec2 pos,
glm::vec2 dims,
const Icons& icons,
const Font& font,
std::function<void()>&& finished)
:
Widget{
RectTag{},
glm::vec2{13, 11},
glm::vec2{289, 121},
Color::black,
true
},
mIcons{icons},
mFont{font},
mName{
glm::vec2{6, 3},
glm::vec2{90, 40}
},
mItem{
glm::vec2{8, 31},
glm::vec2{80, 58}
},
mStatusText{
glm::vec2{8, 27 + 58},
glm::vec2{90, 22}
},
mDescriptionBackground{
glm::vec2{98, 0},
glm::vec2{196, 121},
Color::buttonBackground,
Color::buttonHighlight,
Color::buttonShadow
},
mDescriptionText{
glm::vec2{104, 0},
glm::vec2{182, 120}
},
mMoreInfo{
glm::vec2{8, 5 + 28 + 58 + 12},
glm::vec2{80, 14},
mFont,
"#More Info",
[this]{ ShowMoreInfo(); }
},
mHasMoreInfo{},
mShowingMoreInfo{},
mMoreInfoDescription{""},
mDescription{""},
mFinished{std::move(finished)}
{
}
bool OnMouseEvent(const MouseEvent& event)
{
const auto handled = Widget::OnMouseEvent(event);
if (!handled)
{
return std::visit(overloaded{
[this](const LeftMousePress& p){ return MousePressed(); },
[this](const RightMousePress& p){ return MousePressed(); },
[](const auto& p){ return true; }
},
event);
}
return true;
}
void AddItem(const BAK::InventoryItem& item, BAK::GameState& gameState)
{
const auto [ss, ti, dims] = mIcons.GetInventoryIcon(item.GetObject().mImageIndex);
mItem.SetImage(ss, ti, dims);
Logging::LogDebug(__FUNCTION__) << " Adding item: " << item << "\n";
{
std::stringstream ss{};
ss << "#" << item.GetObject().mName << "\n";
if (item.DisplayNumber())
{
if (item.DisplayCondition())
{
ss << "Condition: " << item.GetCondition() << "%";
}
else
{
ss << "Amount: " << item.GetCondition();
}
}
mName.SetText(mFont, ss.str(), true);
Logging::LogDebug(__FUNCTION__) << " Name: " << ss.str() << "\n";
}
if (item.IsItemType(BAK::ItemType::Scroll))
{
mDescription = gameState.GetTextVariableStore()
.SubstituteVariables(
std::string{BAK::DialogSources::GetScrollDescription(item.GetSpell())});
}
else
{
mDescription = gameState.GetTextVariableStore()
.SubstituteVariables(
std::string{BAK::DialogSources::GetItemDescription(item.GetItemIndex().mValue)});
}
mDescriptionText.SetText(mFont, mDescription, true, true);
mShowingMoreInfo = false;
{
std::stringstream ss{};
bool comma{};
ss << "#";
if (item.IsEquipped())
{
comma = true;
ss << "Using";
}
if (item.IsBroken())
{
if (comma) ss << ", ";
comma = true;
ss << "Broken";
}
if (item.IsRepairable()
&& (item.IsItemType(BAK::ItemType::Armor)
|| item.IsItemType(BAK::ItemType::Crossbow)
|| item.IsItemType(BAK::ItemType::Sword)))
{
if (comma) ss << ", ";
comma = true;
ss << "Repairable";
}
if (HasMoreInfo(item))
{
Logging::LogDebug(__FUNCTION__) << " Status: " << ss.str();
mStatusText.SetText(mFont, ss.str(), true, true);
mHasMoreInfo = true;
mMoreInfoDescription = MakeMoreInfo(item);
}
else
{
mHasMoreInfo = false;
}
}
AddChildren();
}
private:
bool HasMoreInfo(const BAK::InventoryItem& item)
{
const auto isQuarrel = item.IsItemType(BAK::ItemType::Unspecified)
&& ((item.GetObject().mCategories
& static_cast<std::uint16_t>(BAK::SaleCategory::CrossbowRelated)) != 0);
return item.IsItemType(BAK::ItemType::Sword)
|| item.IsItemType(BAK::ItemType::Armor)
|| item.IsItemType(BAK::ItemType::Crossbow)
|| item.IsItemType(BAK::ItemType::Staff)
|| item.IsItemType(BAK::ItemType::ArmorOil)
|| item.IsItemType(BAK::ItemType::SpecialOil)
|| item.IsItemType(BAK::ItemType::WeaponOil)
|| (item.IsSkillModifier() && item.IsEquipped())
|| isQuarrel;
}
void ShowMoreInfo()
{
if (mShowingMoreInfo)
{
mDescriptionText.SetText(mFont, mDescription, true, true);
mShowingMoreInfo = false;
}
else
{
mDescriptionText.SetText(mFont, mMoreInfoDescription, false, true);
mShowingMoreInfo = true;
}
}
std::string MakeMoreInfo(const BAK::InventoryItem& item)
{
std::stringstream ss{};
const auto& object = item.GetObject();
const auto GetMods = [&]{
if (item.HasModifier(BAK::Modifier::Flaming)) return "Flaming";
if (item.HasModifier(BAK::Modifier::SteelFire)) return "Steelfired";
if (item.HasModifier(BAK::Modifier::Frost)) return "Frosted";
if (item.HasModifier(BAK::Modifier::Enhancement1)) return "Enhanced";
if (item.HasModifier(BAK::Modifier::Enhancement2)) return "Enhanced";
if (item.IsPoisoned()) return "Poisoned";
const auto effect = object.mEffectMask >> 8;
if (CheckBitSet(effect, BAK::Modifier::Flaming)) return "Flame";
if (CheckBitSet(effect, BAK::Modifier::SteelFire)) return "Steelfire";
if (CheckBitSet(effect, BAK::Modifier::Frost)) return "Frost";
if (CheckBitSet(effect, BAK::Modifier::Enhancement1)) return "Enhancement";
if (CheckBitSet(effect, BAK::Modifier::Enhancement2)) return "Enhancement";
if (CheckBitSet(object.mEffectMask, BAK::ItemStatus::Poisoned)) return "Poison";
return "None";
};
const auto GetBlessing = [&]{
if (item.HasModifier(BAK::Modifier::Blessing1)) return "No. 1 (+5%)";
if (item.HasModifier(BAK::Modifier::Blessing2)) return "No. 2 (+10%)";
if (item.HasModifier(BAK::Modifier::Blessing3)) return "No. 3 (+15%)";
return "None";
};
if (item.IsItemType(BAK::ItemType::Armor))
{
ss << "Armor Mod: #" << object.mAccuracySwing << "%#\n\n";
ss << "Resistances: #" << GetMods() << "#\n";
ss << "Bless Type: #" << GetBlessing() << "#\n\n";
ss << "Racial Mod: #" << BAK::ToString(object.mRace) << "#\n";
}
else if (item.IsItemType(BAK::ItemType::Sword))
{
ss << " #" << "Thrust Swing#\n";
ss << "Base Dmg: #" << object.mStrengthThrust << "+Strength " << object.mStrengthSwing << "+Strength#\n";
ss << "Accuracy: #" << object.mAccuracyThrust << "+Skill " << object.mAccuracySwing << "+Skill#\n\n";
ss << "Active Mods: #" << GetMods() << "#\n";
ss << "Bless Type: #" << GetBlessing() << "#\n\n";
ss << "Racial Mod: #" << BAK::ToString(object.mRace) << "#\n";
}
else if (item.IsItemType(BAK::ItemType::Staff))
{
ss << " #" << "Thrust Swing#\n";
ss << "Base Dmg: #" << object.mStrengthThrust << "+Strength " << object.mStrengthSwing << "+Strength#\n";
ss << "Accuracy: #" << object.mAccuracyThrust << "+Skill " << object.mAccuracySwing << "+Skill#\n\n";
ss << "Racial Mod: #" << BAK::ToString(object.mRace) << "#\n";
}
else if (item.IsItemType(BAK::ItemType::Crossbow))
{
ss << "Base Damage: #" << object.mStrengthSwing << "+Quarrel#\n";
ss << "Accuracy: #" << object.mAccuracySwing<< "+Quarrel+Skill#\n\n";
ss << "Racial Mod: #" << BAK::ToString(object.mRace) << "#\n";
}
else if (item.IsItemType(BAK::ItemType::Unspecified)
&& ((object.mCategories & static_cast<std::uint16_t>(BAK::SaleCategory::CrossbowRelated)) != 0))
{
ss << "Base Damage: #" << object.mStrengthSwing << "#\n";
ss << "Accuracy: #" << object.mAccuracySwing << "+Skill#\n\n";
ss << "Racial Mod: #" << BAK::ToString(object.mRace) << "#\n";
}
else if (item.IsItemType(BAK::ItemType::WeaponOil)
|| item.IsItemType(BAK::ItemType::ArmorOil)
|| item.IsItemType(BAK::ItemType::SpecialOil))
{
ss << "Modifier: #" << GetMods() << "#\n";
}
else if (item.IsSkillModifier())
{
ss << "#Affecting player statistics\n";
}
return ss.str();
}
bool MousePressed()
{
ASSERT(mFinished);
std::invoke(mFinished);
return true;
}
void AddChildren()
{
ClearChildren();
AddChildBack(&mName);
AddChildBack(&mItem);
AddChildBack(&mDescriptionBackground);
AddChildBack(&mDescriptionText);
AddChildBack(&mStatusText);
if (mHasMoreInfo)
AddChildBack(&mMoreInfo);
}
const Icons& mIcons;
const Font& mFont;
TextBox mName;
CenteredImage mItem;
TextBox mStatusText;
Button mDescriptionBackground;
TextBox mDescriptionText;
ClickButton mMoreInfo;
bool mHasMoreInfo;
bool mShowingMoreInfo;
std::string mMoreInfoDescription;
std::string mDescription;
std::function<void()> mFinished;
};
}
| 10,726
|
C++
|
.h
| 292
| 26.181507
| 120
| 0.521092
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,691
|
shopItemSlot.hpp
|
xavieran_BaKGL/gui/inventory/shopItemSlot.hpp
|
#pragma once
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/inventory/inventorySlot.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class ShopItemSlot;
using DraggableShopItem = Draggable<ShopItemSlot>;
class ShopItemSlot :
public InventorySlot
{
public:
ShopItemSlot(
glm::vec2 pos,
glm::vec2 dims,
const Font& font,
const Icons& icons,
BAK::InventoryIndex itemIndex,
const BAK::InventoryItem& item,
BAK::Royals sellPrice,
bool available,
std::function<void()>&& showItemDescription)
:
InventorySlot{
pos,
dims,
font,
icons,
itemIndex,
item,
[]{},
std::move(showItemDescription)
},
mAvailable{available},
mSellPrice{sellPrice},
mDescription{
glm::vec2{0, 0},
glm::vec2{84, 50}
}
{
ClearChildren();
UpdateDescription(font, item);
AddChildren();
}
bool GetAvailable() const
{
return mAvailable;
}
void UpdateDescription(
const Font& font,
const BAK::InventoryItem& item)
{
ASSERT(item.GetObject().mValue >= 0);
std::stringstream ss{};
ss << "#";
if (item.IsItemType(BAK::ItemType::Scroll))
{
const auto& spells = BAK::SpellDatabase::Get();
ss << std::string{spells.GetSpellName(item.GetSpell())};
}
else
{
ss << item.GetObject().mName;
}
if (item.IsStackable() || item.IsChargeBased() || item.IsQuantityBased())
ss << " (" << +item.GetQuantity() << ")";
else if (item.IsConditionBased())
ss << " (" << +item.GetCondition() << "%)";
ss << "\n" << ToShopString(
mAvailable ? mSellPrice : BAK::sUnpurchaseablePrice);
// First calculate text dims, trim the textbox to that size,
// then add the text again, centered
const auto& [textDims, _] = mDescription.SetText(font, ss.str());
mDescription.SetDimensions(textDims);
mDescription.SetText(font, ss.str(), true);
const auto& dims = GetPositionInfo().mDimensions;
auto diff = dims - textDims;
if (diff.x < 0) diff.x = 0;
else diff.x = diff.x / 2;
mDescription.SetPosition(
glm::vec2{diff.x, diff.y} + glm::vec2{4, 2});
}
private:
void AddChildren()
{
ClearChildren();
AddItem(true);
AddChildBack(&mDescription);
}
bool mAvailable;
BAK::Royals mSellPrice;
TextBox mDescription;
};
}
| 2,942
|
C++
|
.h
| 103
| 21.135922
| 81
| 0.5836
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,692
|
splitStackDialog.hpp
|
xavieran_BaKGL/gui/inventory/splitStackDialog.hpp
|
#pragma once
#include "gui/button.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <iostream>
namespace Gui {
class SplitStackDialog
: public Widget
{
public:
static constexpr auto sDims = glm::vec2{76, 38};
using Callback = std::function<void(bool, unsigned)>;
SplitStackDialog(
glm::vec2 pos,
const Font& font)
:
Widget{
RectTag{},
pos,
sDims,
glm::vec4{1.0, 0, 0, .3},
true},
mFont{font},
mFrame{
glm::vec2{0},
sDims,
Color::buttonBackground,
Color::buttonHighlight,
Color::buttonShadow
},
mGive{
{4, 4},
{sDims.x - 9, 14},
mFont,
"Give",
[this]{ TransferItem(false); }
},
mDecrease{
{4, 20},
{32, 14},
mFont,
"<",
[this]{ Decrease(); }
},
mIncrease{
{32 + 8, 20},
{32, 14},
mFont,
">",
[this]{ Increase(); }
},
mTransfer{},
mAmount{0},
mMaxAmount{0},
mLogger{Logging::LogState::GetLogger("Gui::SplitStackDialog")}
{
ASSERT(!mTransfer);
AddChildBack(&mFrame);
AddChildBack(&mIncrease);
AddChildBack(&mDecrease);
AddChildBack(&mGive);
}
void BeginSplitDialog(
Callback&& callback,
unsigned amount)
{
mTransfer = std::move(callback);
mAmount = amount;
mMaxAmount = amount;
UpdateAmountText();
}
private:
void Increase()
{
if (++mAmount > mMaxAmount) mAmount = mMaxAmount;
UpdateAmountText();
}
void Decrease()
{
if (mAmount > 1) mAmount--;
UpdateAmountText();
}
void UpdateAmountText()
{
std::stringstream ss{};
ss << "#Give: " << mAmount << "/" << mMaxAmount;
mGive.SetText(ss.str());
}
void TransferItem(bool share)
{
ASSERT(mTransfer);
mTransfer(share, mAmount);
}
private:
const Font& mFont;
Button mFrame;
ClickButton mGive;
ClickButton mDecrease;
ClickButton mIncrease;
std::function<void(bool, unsigned)> mTransfer;
unsigned mAmount;
unsigned mMaxAmount;
const Logging::Logger& mLogger;
};
}
| 2,511
|
C++
|
.h
| 107
| 15.607477
| 70
| 0.526868
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,693
|
equipmentSlot.hpp
|
xavieran_BaKGL/gui/inventory/equipmentSlot.hpp
|
#pragma once
#include "gui/inventory/inventorySlot.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
namespace Gui {
class EquipmentSlot : public Widget
{
public:
EquipmentSlot(
glm::vec2 pos,
glm::vec2 dims,
const Icons& mIcons,
int icon)
:
Widget{
RectTag{},
pos,
dims,
glm::vec4{},
true
},
mBlank{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(
mIcons.GetInventoryIcon(icon)),
std::get<Graphics::TextureIndex>(
mIcons.GetInventoryIcon(icon)),
glm::vec2{0},
dims,
true
}
{
ClearItem();
}
void PropagateUp(const DragEvent& event)
{
// Display blank slot image when you lift the equipment off the slot
evaluate_if<DragStarted>(event, [&](const auto&){
AddChildFront(&mBlank);
});
evaluate_if<DragEnded>(event, [&](const auto&){
RemoveChild(&mBlank);
});
Widget::PropagateUp(event);
}
template <typename ...Args>
void AddItem(Args&&... args)
{
ClearChildren();
mItem.emplace(std::forward<Args>(args)...);
AddChildBack(&(*mItem));
}
void ClearItem()
{
ClearChildren();
AddChildBack(&mBlank);
}
bool HasItem() const
{
return bool{mItem};
}
InventorySlot& GetInventorySlot()
{
return *mItem;
}
private:
std::optional<DraggableItem> mItem;
Widget mBlank;
};
}
| 1,759
|
C++
|
.h
| 74
| 16.243243
| 76
| 0.553293
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,694
|
inventorySlot.hpp
|
xavieran_BaKGL/gui/inventory/inventorySlot.hpp
|
#pragma once
#include "bak/dialogSources.hpp"
#include "bak/inventory.hpp"
#include "bak/spells.hpp"
#include "bak/layout.hpp"
#include "bak/textureFactory.hpp"
#include "gui/inventory/modifiers.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/core/dragEndpoint.hpp"
#include "gui/core/draggable.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/mouseEvent.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class InventorySlot;
using DraggableItem = Draggable<InventorySlot>;
template <typename Base>
using ItemEndpoint = DragEndpoint<
Base,
InventorySlot>;
class InventorySlot :
public Widget
{
public:
InventorySlot(
glm::vec2 pos,
glm::vec2 dims,
const Font& font,
const Icons& icons,
BAK::InventoryIndex itemIndex,
const BAK::InventoryItem& item,
std::function<void()>&& useItemDirectly,
std::function<void()>&& showItemDescription)
:
Widget{
RectTag{},
pos,
dims,
glm::vec4{},
true
},
mItemIndex{itemIndex},
mItemRef{item},
mUseItemDirectly{std::move(useItemDirectly)},
mShowItemDescription{std::move(showItemDescription)},
mIsSelected{false},
mQuantity{
glm::vec2{0, 0},
glm::vec2{40, 30}
},
mItem{
ImageTag{},
std::get<Graphics::SpriteSheetIndex>(
icons.GetInventoryIcon(item.GetObject().mImageIndex
+ (item.IsActivated() ? 44 : 0))), // FIXME: This doesn't work for ring of prandur
std::get<Graphics::TextureIndex>(
icons.GetInventoryIcon(item.GetObject().mImageIndex
+ (item.IsActivated() ? 44 : 0))),
pos,
std::get<glm::vec2>(
icons.GetInventoryIcon(item.GetObject().mImageIndex)),
true
},
mModifiers{
glm::vec2{0},
glm::vec2{0},
icons,
item
}
{
assert(mShowItemDescription);
mItem.SetCenter(GetCenter() - GetTopLeft());
UpdateQuantity(font, item);
AddChildren();
}
BAK::InventoryIndex GetItemIndex() const
{
return mItemIndex;
}
const BAK::InventoryItem& GetItem() const
{
return mItemRef;
}
bool OnMouseEvent(const MouseEvent& event) override
{
const auto result = std::visit(overloaded{
[this](const LeftMousePress& p){ return LeftMousePressed(p.mValue); },
[this](const RightMousePress& p){ return RightMousePressed(p.mValue); },
[](const auto& p){ return false; }
},
event);
UpdateSelected();
return result;
}
bool LeftMousePressed(glm::vec2 click)
{
if (Within(click))
{
if (mIsSelected)
{
mUseItemDirectly();
}
mIsSelected = true;
}
else
{
mIsSelected = false;
}
return false;
}
bool RightMousePressed(glm::vec2 click)
{
if (Within(click))
{
mIsSelected = true;
mShowItemDescription();
}
else
mIsSelected = false;
return false;
}
void UpdateSelected()
{
if (mIsSelected)
SetColor(Color::itemHighlighted);
else
SetColor(glm::vec4{});
}
void UpdateQuantity(
const Font& font,
const BAK::InventoryItem& item)
{
if (item.DisplayNumber())
{
std::stringstream ss{};
ss << "#" << +item.GetCondition() <<
(item.DisplayCondition() ? "%" : "");
const auto& [textDims, _] = mQuantity.SetText(font, ss.str());
const auto& dims = GetPositionInfo().mDimensions;
mQuantity.SetPosition(
dims - textDims
+ glm::vec2{4, 2});
}
}
bool IsSelected() const
{
return mIsSelected;
}
void ResetSelected()
{
mIsSelected = false;
}
protected:
void AddItem(bool snapToTop)
{
if (snapToTop)
mItem.SetPosition(
glm::vec2{mItem.GetPositionInfo().mPosition.x, 8});
AddChildBack(&mItem);
}
private:
void AddChildren()
{
ClearChildren();
AddItem(false);
AddChildBack(&mQuantity);
AddChildBack(&mModifiers);
}
const BAK::InventoryIndex mItemIndex;
const BAK::InventoryItem& mItemRef;
std::function<void()> mUseItemDirectly;
std::function<void()> mShowItemDescription;
bool mIsSelected;
TextBox mQuantity;
Widget mItem;
Modifiers mModifiers;
};
}
| 5,088
|
C++
|
.h
| 188
| 19.106383
| 102
| 0.577065
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,695
|
shopDisplay.hpp
|
xavieran_BaKGL/gui/inventory/shopDisplay.hpp
|
#pragma once
#include "bak/IContainer.hpp"
#include "bak/dialogSources.hpp"
#include "bak/inventory.hpp"
#include "bak/layout.hpp"
#include "bak/gameState.hpp"
#include "bak/objectInfo.hpp"
#include "bak/shop.hpp"
#include "bak/state/money.hpp"
#include "gui/inventory/equipmentSlot.hpp"
#include "gui/inventory/itemArranger.hpp"
#include "gui/inventory/shopItemSlot.hpp"
#include "gui/IDialogScene.hpp"
#include "gui/IGuiManager.hpp"
#include "gui/backgrounds.hpp"
#include "gui/core/dragEndpoint.hpp"
#include "gui/core/draggable.hpp"
#include "gui/icons.hpp"
#include "gui/colors.hpp"
#include "gui/clickButton.hpp"
#include "gui/textBox.hpp"
#include "gui/core/widget.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <iostream>
#include <utility>
#include <variant>
namespace Gui {
class ShopDisplay :
public Widget
{
public:
static constexpr auto mItemsPerPage = 6;
ShopDisplay(
glm::vec2 pos,
glm::vec2 dims,
const Icons& icons,
const Font& font,
const BAK::GameState& gameState,
std::function<void(const BAK::InventoryItem&)>&& showDescription)
:
// Black background
Widget{
RectTag{},
pos,
dims,
Color::black,
true
},
mFont{font},
mIcons{icons},
mShopPage{0},
mInventoryItems{},
mDiscount{},
mContainer{nullptr},
mGameState(gameState),
mShowDescription{std::move(showDescription)},
mLogger{Logging::LogState::GetLogger("Gui::ShopDisplay")}
{
assert(mShowDescription);
}
void SetContainer(BAK::IContainer* container)
{
ASSERT(container);
mContainer = container;
mShopPage = 0;
ClearDiscounts();
}
void RefreshGui()
{
ClearChildren();
UpdateInventoryContents();
AddChildren();
}
void AdvanceNextPage()
{
if ((++mShopPage) == GetMaxPages())
mShopPage = 0;
}
std::size_t GetMaxPages()
{
ASSERT(mContainer);
const auto nItems = mContainer->GetInventory().GetNumberItems();
const auto fullPages = nItems / mItemsPerPage;
const auto partialPages = (nItems % mItemsPerPage) != 0;
return fullPages + partialPages;
}
BAK::Royals GetSellPrice(
BAK::InventoryIndex itemIndex,
unsigned amount)
{
ASSERT(mContainer);
auto item = mContainer->GetInventory().GetAtIndex(itemIndex);
item.SetQuantity(amount);
return BAK::Shop::GetSellPrice(
item,
mContainer->GetShop(),
mDiscount[item.GetItemIndex()],
BAK::State::IsRomneyGuildWars(mGameState, mContainer->GetShop()));
}
BAK::Royals GetBuyPrice(const BAK::InventoryItem& item) const
{
ASSERT(mContainer);
return BAK::Shop::GetBuyPrice(item, mContainer->GetShop(), BAK::State::IsRomneyGuildWars(mGameState, mContainer->GetShop()));
}
bool CanBuyItem(const BAK::InventoryItem& item) const
{
ASSERT(mContainer);
return BAK::Shop::CanBuyItem(item, *mContainer);
}
void SetItemDiscount(BAK::InventoryIndex itemIndex, BAK::Royals discount)
{
mLogger.Debug() << " Setting discount to: " << discount << "\n";
ASSERT(mContainer);
const auto& item = mContainer->GetInventory().GetAtIndex(itemIndex);
mDiscount[item.GetItemIndex()] = discount;
}
BAK::Royals GetDiscount(BAK::InventoryIndex itemIndex)
{
ASSERT(mContainer);
const auto& item = mContainer->GetInventory().GetAtIndex(itemIndex);
return mDiscount[item.GetItemIndex()];
}
private:
void ShowItemDescription(const BAK::InventoryItem& item)
{
mShowDescription(item);
}
void ClearDiscounts()
{
mDiscount.clear();
const auto& inventory = mContainer->GetInventory();
}
void UpdateInventoryContents()
{
ASSERT(mContainer != nullptr);
mInventoryItems.clear();
const auto& inventory = mContainer->GetInventory();
std::vector<
std::pair<
BAK::InventoryIndex,
const BAK::InventoryItem*>> items{};
const auto numItems = inventory.GetItems().size();
mInventoryItems.reserve(numItems);
items.reserve(numItems);
unsigned index{0};
std::transform(
inventory.GetItems().begin(), inventory.GetItems().end(),
std::back_inserter(items),
[&index](const auto& i) -> std::pair<BAK::InventoryIndex, const BAK::InventoryItem*> {
return std::make_pair(BAK::InventoryIndex{index++}, &i);
});
auto arranger = ItemArranger{};
if ( mContainer->GetContainerType() == BAK::ContainerType::Shop
|| mContainer->GetContainerType() == BAK::ContainerType::Inn )
{
ASSERT(items.size() > mShopPage * mItemsPerPage);
const auto begin = std::next(items.begin(), mShopPage * mItemsPerPage);
const auto nItems = std::distance(begin, items.end());
const auto end = std::next(
begin,
std::min(
static_cast<size_t>(mItemsPerPage),
static_cast<size_t>(nItems)));
arranger.PlaceItems(
begin, end,
3, 2,
glm::vec2{98, 60},
true,
[&](auto invIndex, const auto& item, const auto itemPos, const auto dims)
{
const auto discount = mDiscount[item.GetItemIndex()];
mInventoryItems.emplace_back(
itemPos,
dims,
mFont,
mIcons,
invIndex,
item,
BAK::Shop::GetSellPrice(
item,
mContainer->GetShop(),
discount,
BAK::State::IsRomneyGuildWars(mGameState, mContainer->GetShop())
),
discount != BAK::sUnpurchaseablePrice,
[&]{
ShowItemDescription(item);
});
});
}
}
void AddChildren()
{
for (auto& item : mInventoryItems)
AddChildBack(&item);
}
private:
const Font& mFont;
const Icons& mIcons;
unsigned mShopPage;
std::vector<DraggableShopItem> mInventoryItems;
std::unordered_map<BAK::ItemIndex, BAK::Royals> mDiscount;
BAK::IContainer* mContainer;
const BAK::GameState& mGameState;
std::function<void(const BAK::InventoryItem&)> mShowDescription;
const Logging::Logger& mLogger;
};
}
| 6,936
|
C++
|
.h
| 209
| 23.985646
| 133
| 0.586882
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,696
|
itemArranger.hpp
|
xavieran_BaKGL/gui/inventory/itemArranger.hpp
|
#pragma once
#include "com/assert.hpp"
#include "com/logger.hpp"
#include "graphics/glm.hpp"
#include <glm/glm.hpp>
#include <algorithm>
#include <functional>
#include <iostream>
#include <optional>
namespace Gui {
class Grid
{
public:
Grid(
unsigned columns,
unsigned rows);
void Occupy(
unsigned columns,
unsigned rows);
glm::vec<2, unsigned> GetNextSlot() const;
const auto& GetGrid() const;
bool Get(unsigned column, unsigned row) const;
private:
unsigned mColumns;
unsigned mRows;
std::vector<std::vector<bool>> mGrid;
};
std::ostream& operator<<(std::ostream& os, const Grid& grid);
class ItemArranger
{
public:
ItemArranger();
template <typename It, typename AddItem>
void PlaceItems(
const It& begin,
const It& end,
unsigned columns,
unsigned rows,
glm::vec2 slotDims,
bool homogenousSlots,
AddItem&& addItem)
{
const auto GetSlotDims = [&](const auto& item){
if (homogenousSlots)
return slotDims;
switch (item.GetObject().mImageSize)
{
case 1:
return slotDims;
case 2:
return slotDims * glm::vec2{2, 1};
case 4:
return slotDims * glm::vec2{2, 2};
default:
ASSERT(false);
return slotDims;
}
};
auto grid = Grid{columns, rows};
const auto UpdateNextSlot = [&](const auto& item)
{
if (homogenousSlots)
grid.Occupy(1, 1);
else
{
switch (item.GetObject().mImageSize)
{
case 1:
grid.Occupy(1, 1); break;
case 2:
grid.Occupy(2, 1); break;
case 4:
grid.Occupy(2, 2); break;
default:
ASSERT(false);
break;
}
}
};
for (auto it = begin; it != end; it++)
{
ASSERT(it != end);
const auto& [invIndex, itemPtr] = *it;
ASSERT(itemPtr);
const auto& item = *itemPtr;
const auto slot = grid.GetNextSlot();
const auto itemPos = glm::cast<float>(slot) * slotDims;
mLogger.Spam() << "Item: " << item << " slot: " << slot << "\n";
UpdateNextSlot(item);
mLogger.Spam() << "Grid:\n" << grid << "\n";
addItem(invIndex, item, itemPos, GetSlotDims(item));
}
}
private:
const Logging::Logger& mLogger;
};
}
| 2,718
|
C++
|
.h
| 97
| 18.453608
| 76
| 0.510786
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,698
|
imguiWrapper.hpp
|
xavieran_BaKGL/imgui/imguiWrapper.hpp
|
#pragma once
#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
class ImguiWrapper
{
public:
static void Initialise(GLFWwindow* window)
{
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
// Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
// Enable Gamepad Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// Setup Platform/Renderer backends
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 330 core");
}
static void Draw(GLFWwindow* window)
{
// Rendering
ImGui::Render();
int display_w, display_h;
glfwGetFramebufferSize(window, &display_w, &display_h);
glViewport(0, 0, display_w, display_h);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
static void Shutdown()
{
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
};
| 1,315
|
C++
|
.h
| 42
| 24.738095
| 68
| 0.64664
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,700
|
gdsEntry.ipp
|
xavieran_BaKGL/bak/encounter/gdsEntry.ipp
|
#pragma once
#include "bak/encounter/gdsEntry.hpp"
#include "com/assert.hpp"
#include "bak/fileBufferFactory.hpp"
namespace BAK::Encounter {
template <typename S>
GDSEntryFactory<S>::GDSEntryFactory()
:
mGDSEntrys{}
{
Load();
}
template <typename S>
GDSEntry GDSEntryFactory<S>::Get(unsigned i, glm::vec<2, unsigned> tile) const
{
ASSERT(i < mGDSEntrys.size());
const auto& rawGds = mGDSEntrys[i];
return GDSEntry{
rawGds.mHotspot,
rawGds.mEntryDialog,
rawGds.mExitDialog,
GamePositionAndHeading{
MakeGamePositionFromTileAndCell(
tile,
rawGds.mExitOffset),
rawGds.mExitHeading},
rawGds.mWalkToDest
};
}
template <typename S>
void GDSEntryFactory<S>::Load()
{
auto fb = FileBufferFactory::Get().CreateDataBuffer(
sFilename);
const auto count = fb.GetUint32LE();
for (unsigned i = 0; i < count; i++)
{
fb.Skip(3);
const auto gdsNumber = fb.GetUint8();
const auto gdsChar = MakeHotspotChar(fb.GetUint8());
fb.Skip(2);
const auto entry = KeyTarget{fb.GetUint32LE()};
const auto exit = KeyTarget{fb.GetUint32LE()};
const auto xoff = fb.GetUint8();
const auto yoff = fb.GetUint8();
// ... ???
const auto heading = fb.GetUint16LE() >> 8;
const auto walkToDest = fb.GetUint8();
ASSERT(fb.GetUint16LE() == 0);
mGDSEntrys.emplace_back(
HotspotRef{gdsNumber, gdsChar},
entry,
exit,
glm::vec<2, unsigned>(xoff, yoff),
heading,
walkToDest == 1);
}
}
}
| 1,679
|
C++
|
.ipp
| 59
| 21.779661
| 78
| 0.610938
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,701
|
combat.ipp
|
xavieran_BaKGL/bak/encounter/combat.ipp
|
#pragma once
#include "bak/dialog.hpp"
#include "bak/encounter/combat.hpp"
#include "com/assert.hpp"
#include "com/logger.hpp"
#include "com/ostream.hpp"
#include "bak/fileBufferFactory.hpp"
namespace BAK::Encounter {
template <bool isTrap>
GenericCombatFactory<isTrap>::GenericCombatFactory()
:
mCombats{}
{
Load();
}
template <bool isTrap>
const Combat& GenericCombatFactory<isTrap>::Get(unsigned i) const
{
ASSERT(i < mCombats.size());
return mCombats[i];
}
template <bool isTrap>
void GenericCombatFactory<isTrap>::Load()
{
auto fb = FileBufferFactory::Get().CreateDataBuffer(
isTrap ? sTrapFilename : sCombatFilename);
const auto logger = Logging::LogState::GetLogger("Combat");
const auto count = fb.GetUint32LE();
logger.Debug() << "Combats: " << count <<"\n";
for (unsigned i = 0; i < count; i++)
{
logger.Spam() << "Combat #" << i << " @"
<< std::hex << fb.Tell() << std::dec << "\n";
fb.Skip(3);
const auto combatIndex = fb.GetUint32LE();
const auto entryDialog = fb.GetUint32LE();
const auto scoutDialog = fb.GetUint32LE();
const auto zero = fb.GetUint32LE();
const auto GetPosAndHeading = [&fb]{
const auto x = fb.GetUint32LE();
const auto y = fb.GetUint32LE();
const auto heading = static_cast<std::uint16_t>(fb.GetUint16LE() >> 8);
return GamePositionAndHeading{{x, y}, heading};
};
const auto trap = std::invoke([&]() -> std::optional<GamePositionAndHeading>
{
if (isTrap)
return GetPosAndHeading();
else
return std::optional<GamePositionAndHeading>{};
});
const auto north = GetPosAndHeading();
const auto west = GetPosAndHeading();
const auto south = GetPosAndHeading();
const auto east = GetPosAndHeading();
const auto numEnemies = fb.GetUint8();
auto combatants = std::vector<CombatantData>{};
for (unsigned i = 0; i < numEnemies; i++)
{
const auto monsterIndex = fb.GetUint16LE();
const auto movementType = fb.GetUint16LE();
const auto pos = GetPosAndHeading();
logger.Debug() << "Combatant #" << i << " " << monsterIndex
<< " mvTp: " << movementType << " pos: " << pos << "\n";
combatants.emplace_back(monsterIndex, movementType, pos);
fb.Skip(48 - 14);
//std::vector<std::int16_t> d{};
//for (unsigned i = 0; i < 17; i++)
//{
// d.emplace_back(fb.GetSint16LE());
//}
//logger.Debug() << "Datas: " << d << "\n";
}
constexpr unsigned maxCombatants = 7;
for (unsigned i = 0; i < (maxCombatants - numEnemies); i++)
{
fb.Skip(48);
}
auto unknown = fb.GetUint16LE();
const bool isAmbush = fb.GetUint16LE() == 0x1;
mCombats.emplace_back(
combatIndex,
KeyTarget{entryDialog},
KeyTarget{scoutDialog},
trap,
north,
west,
south,
east,
combatants,
unknown,
isAmbush);
logger.Spam() << "Index: " << i << " COMBAT #" << combatIndex << " ";
logger.Spam() << mCombats.back() << "\n";
}
}
}
| 3,435
|
C++
|
.ipp
| 97
| 26.845361
| 85
| 0.559517
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,702
|
eventFlag.ipp
|
xavieran_BaKGL/bak/encounter/eventFlag.ipp
|
#pragma once
#include "bak/encounter/eventFlag.hpp"
#include "com/assert.hpp"
#include "bak/fileBufferFactory.hpp"
namespace BAK::Encounter {
template <bool isEnable>
EventFlagFactory<isEnable>::EventFlagFactory()
:
mEventFlags{}
{
Load();
}
template <bool isEnable>
EventFlag EventFlagFactory<isEnable>::Get(unsigned i) const
{
ASSERT(i < mEventFlags.size());
return mEventFlags[i];
}
template <bool isEnable>
void EventFlagFactory<isEnable>::EventFlagFactory::Load()
{
auto fb = FileBufferFactory::Get().CreateDataBuffer(
isEnable ? sEnable : sDisable);
const auto count = fb.GetUint32LE();
for (unsigned i = 0; i < count; i++)
{
fb.Skip(3);
const auto chance = fb.GetUint8();
const auto eventPointer = fb.GetUint16LE();
ASSERT(fb.GetUint16LE() == 0);
mEventFlags.emplace_back(chance, eventPointer, isEnable);
}
}
}
| 911
|
C++
|
.ipp
| 34
| 23.058824
| 65
| 0.702765
|
xavieran/BaKGL
| 39
| 2
| 32
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,703
|
main.cpp
|
stuomas_disorient/src/main.cpp
|
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); // DPI support
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); //HiDPI pixmaps
QApplication a(argc, argv);
a.setFont(QFont("Tahoma", 10, QFont::Normal), "QWidget");
a.setFont(QFont("Consolas", 10, QFont::Normal), "QTextEdit");
MainWindow w;
QString windowTitle = "Disorient " + QCoreApplication::applicationVersion();
windowTitle.chop(2);
w.setWindowTitle(windowTitle);
return a.exec();
}
| 581
|
C++
|
.cpp
| 15
| 34.933333
| 80
| 0.719858
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,705
|
mainwindow.cpp
|
stuomas_disorient/src/mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "constants.h"
#include <QJsonArray>
#include <QFileDialog>
#include <QJsonDocument>
#include "comboboxitemdelegate.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), m_ui(new Ui::MainWindow), m_endpoint(new Endpoint), m_iWebSocket(new InputWebSocket), m_iMqtt(new InputMqtt), m_audioDevice(new AudioEndpointController)
{
connect(m_endpoint, &Endpoint::statusToLog, this, &MainWindow::onStatusReceived);
connect(m_iWebSocket, &InputWebSocket::statusToLog, this, &MainWindow::onStatusReceived);
connect(m_iMqtt, &InputMqtt::statusToLog, this, &MainWindow::onStatusReceived);
connect(this, &MainWindow::mqttPublish, m_iMqtt, &InputMqtt::onPublish);
connect(this, &MainWindow::websocketPublish, m_iWebSocket, &InputWebSocket::onPublish);
connect(m_endpoint, &Endpoint::mqttPublish, m_iMqtt, &InputMqtt::onPublish);
connect(m_endpoint, &Endpoint::websocketPublish, m_iWebSocket, &InputWebSocket::onPublish);
connect(m_endpoint, &Endpoint::changeAudioDevice, m_audioDevice, &AudioEndpointController::onChangeRequest);
connect(m_iWebSocket, &InputWebSocket::messageToEndpoint, m_endpoint, &Endpoint::onMessageReceived);
connect(m_iMqtt, &InputMqtt::messageToEndpoint, m_endpoint, &Endpoint::onMessageReceived);
m_ui->setupUi(this);
log(QString("%1 started").arg(Names::SettingApplication));
setupSysTray();
setupDisplayCombobox(m_endpoint->getDisplays());
setupAudioCombobox(m_audioDevice->getAllAudioDevices());
setupHotkeys();
setupPayloadTable();
loadSettingsFromRegistry();
setupStyles();
m_ui->verticalLayout_3->setAlignment(Qt::AlignTop);
m_ui->checkBoxPublishOutput->setDisabled(!m_ui->checkBoxExecPermission->isChecked());
m_ui->checkBoxPublishOutput->setText(QString("Publish output in topic %1/%2").arg(m_ui->lineEditMqttTopic->text()).arg(Names::MqttPowershellSubtopic));
m_ui->tabWidget->setCurrentIndex(0);
if(m_firstStart) {
show(); //start minimized to system tray after first start
writeToRegistry(Names::SettingFirstStart, false);
}
}
MainWindow::~MainWindow()
{
delete m_endpoint;
delete m_iWebSocket;
delete m_iMqtt;
delete m_audioDevice;
delete m_sysTrayIcon;
delete m_ui;
}
QString MainWindow::timestamp()
{
return QDateTime::currentDateTime().toString("HH:mm:ss");
}
QVector<QString> MainWindow::getAllAudioDevices()
{
return m_audioDevice->getAllAudioDevices();
}
void MainWindow::log(const QString &logtext)
{
if(logtext.isEmpty()) return;
bool dateChanged = false;
static QString datestr = "";
if(datestr != QDateTime::currentDateTime().date().toString()) {
dateChanged = true;
}
datestr = QDateTime::currentDateTime().date().toString();
QString daySeparator = QString("<p style=\"font-family:'Segoe UI'; margin:0;\">📅 <b>%1</b></p>").arg(datestr);
if(dateChanged) {
m_ui->textLog->append(daySeparator);
}
m_ui->textLog->append(QString("<b>[%1]</b> %2").arg(timestamp()).arg(logtext));
m_ui->textLog->repaint();
}
QVariant MainWindow::readFromRegistry(const QString &key)
{
QSettings settings(Names::SettingOrganization, Names::SettingApplication);
return settings.value(key, ""); //If setting doesn't exist, return empty string
}
void MainWindow::writeToRegistry(const QString &key, const QVariant &value)
{
QSettings settings(Names::SettingOrganization, Names::SettingApplication);
settings.setValue(key, value);
}
void MainWindow::removeFromRegistry(const QString &key)
{
QSettings settings(Names::SettingOrganization, Names::SettingApplication);
settings.remove(key);
}
void MainWindow::onStatusReceived(const QString &status, const QString &sender)
{
if(sender.isEmpty()) {
log(status);
} else if(sender == "InputMqtt") {
log(QString("<font color='purple'>[MQTT]</font> %2").arg(status));
} else if(sender == "InputWebSocket") {
log(QString("<font color='orange'>[WebSocket]</font> %2").arg(status));
} else {
log(QString("[%1] %2").arg(sender).arg(status));
}
if(m_ui->checkBoxAllowPopups->isChecked()) {
m_sysTrayIcon->showMessage("Status update", status);
}
//m_sysTrayIcon->setToolTip(QString("%1\n%2").arg(Names::SettingApplication).arg(status));
}
void MainWindow::onAddRowClicked()
{
auto row = m_ui->tableWidget->rowCount();
auto col = m_ui->tableWidget->columnCount();
m_ui->tableWidget->insertRow(row);
for(int j = 0; j < col; ++j) {
QTableWidgetItem *pCell = m_ui->tableWidget->item(row, j);
if(!pCell) {
pCell = new QTableWidgetItem;
m_ui->tableWidget->setItem(row, j, pCell);
}
pCell->setText("");
}
}
void MainWindow::setupDisplayCombobox(const QVector<DISPLAY_DEVICE> &displays)
{
int n = 0;
for(auto i : displays) {
m_ui->comboBoxDisplayList->addItem(QString::number(n) + QString(". ") + QString::fromWCharArray(i.DeviceString));
++n;
}
}
void MainWindow::setupAudioCombobox(const QVector<QString> &audio)
{
for(auto i : audio) {
m_ui->comboBoxAudioList->addItem(i);
}
}
void MainWindow::setupHotkeys()
{
if(!RegisterHotKey(HWND(winId()), 101, MOD_CONTROL | MOD_ALT, VK_UP) ||
!RegisterHotKey(HWND(winId()), 102, MOD_CONTROL | MOD_ALT, VK_LEFT) ||
!RegisterHotKey(HWND(winId()), 103, MOD_CONTROL | MOD_ALT, VK_DOWN) ||
!RegisterHotKey(HWND(winId()), 104, MOD_CONTROL | MOD_ALT, VK_RIGHT)) {
log("Some global hotkeys could not be registered.");
}
}
void MainWindow::setupPayloadTable()
{
auto payloadTable = m_ui->tableWidget;
ComboBoxItemDelegate* cbid = new ComboBoxItemDelegate(payloadTable);
payloadTable->setItemDelegateForColumn(1, cbid);
payloadTable->setColumnCount(3);
payloadTable->setHorizontalHeaderLabels({"Payload", "Function", "Arguments"});
//payloadTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
//payloadTable->horizontalHeader()->setStretchLastSection(true);
payloadTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Interactive);
payloadTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Interactive);
payloadTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
payloadTable->setColumnWidth(0, 130);
payloadTable->setColumnWidth(1, 200);
payloadTable->setRowCount(10);
QPushButton *pushButtonAdd = new QPushButton("", m_ui->tableWidget);
pushButtonAdd->setIcon(QIcon(":/icons/plus.png"));
pushButtonAdd->setIconSize(QSize(10, 10));
pushButtonAdd->setToolTip("Add new row");
pushButtonAdd->move(5,5);
pushButtonAdd->resize(22,22);
pushButtonAdd->show();
connect(pushButtonAdd, &QPushButton::clicked, this, &MainWindow::onAddRowClicked);
}
void MainWindow::setupStyles()
{
QFile style(":/styles.qss");
style.open(QFile::ReadOnly);
setStyleSheet(QString::fromLatin1(style.readAll()));
style.close();
}
void MainWindow::setupSysTray()
{
//Adapted from amin-ahmadi.com
m_closing = false;
auto exitAction = new QAction(tr("&Exit"), this);
exitAction->setIcon(QIcon(":/icons/icon.ico"));
connect(exitAction, &QAction::triggered, [this]() {
m_closing = true;
close();
});
auto trayIconMenu = new QMenu(this);
trayIconMenu->addAction(exitAction);
m_sysTrayIcon = new QSystemTrayIcon(this);
m_sysTrayIcon->setContextMenu(trayIconMenu);
m_sysTrayIcon->setIcon(QIcon(":/icons/icon.ico"));
m_sysTrayIcon->show();
connect(m_sysTrayIcon, &QSystemTrayIcon::activated, [this](auto reason) {
if(reason == QSystemTrayIcon::Trigger) {
if(isVisible()) {
hide();
} else {
show();
activateWindow();
}
}
});
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if(m_closing) {
event->accept();
}
else {
this->hide();
event->ignore();
if(m_firstHide) {
m_firstHide = false;
m_sysTrayIcon->showMessage("Still here!", "Select Exit from the right-click menu to exit.");
}
}
}
//Override QWidget::nativeEvent to catch registered global hotkey events
bool MainWindow::nativeEvent(const QByteArray& eventType, void* message, long* result)
{
Q_UNUSED(eventType)
Q_UNUSED(result)
MSG* msg = static_cast<MSG*>(message);
if(msg->message == WM_HOTKEY) {
switch(msg->wParam) {
case 101:
m_endpoint->flip(0);
break;
case 102:
m_endpoint->flip(90);
break;
case 103:
m_endpoint->flip(180);
break;
case 104:
m_endpoint->flip(270);
break;
}
return true;
} else if(msg->message == WM_POWERBROADCAST) {
switch(msg->wParam) {
case PBT_APMSUSPEND: {
log("System suspending");
mqttPublish("System suspending");
websocketPublish("System suspending");
break;
}
case PBT_APMRESUMESUSPEND: {
log("System waking up, reconnecting...");
mqttPublish("System up");
websocketPublish("System up");
break;
}
}
}
return false;
}
void MainWindow::loadSettingsFromRegistry()
{
restoreGeometry(readFromRegistry("geometry").toByteArray());
restoreState(readFromRegistry("windowState").toByteArray());
//Setting for last known WebSocket address
QUrl lastWsUrl = readFromRegistry(Names::SettingLastWsAddress).toUrl();
m_ui->lineEditWebSocketAddr->setText(lastWsUrl.toString());
m_iWebSocket->connectToServer(lastWsUrl);
//Setting for automatic startup
m_ui->checkBoxAutostart->setChecked(readFromRegistry(Names::SettingAutostartEnabled).toBool());
//Setting for popups
m_ui->checkBoxAllowPopups->setChecked(readFromRegistry(Names::SettingShowPopups).toBool());
//Setting for last selected display
int index = readFromRegistry(Names::SettingSelectedMonitor).toInt();
if(index >= 0) {
m_ui->comboBoxDisplayList->setCurrentIndex(index);
m_endpoint->setChosenDisplay(index);
}
//Setting for MQTT credentials saving
m_ui->checkBoxSaveCredentials->setChecked(readFromRegistry(Names::SettingSaveCredentials).toBool());
//Setting for MQTT username
QString user = readFromRegistry(Names::SettingMqttUser).toString();
m_ui->lineEditMqttUsername->setText(user);
m_iMqtt->setUsername(user);
//Setting for MQTT password
QString pw = QString::fromLatin1(QByteArray::fromHex(readFromRegistry(Names::SettingMqttPassword).toByteArray()));
m_ui->lineEditMqttPassword->setText(pw);
m_iMqtt->setPassword(pw);
//Setting for MQTT topic
QString topic = readFromRegistry(Names::SettingMqttTopic).toString();
m_iMqtt->setTopic(topic);
m_ui->lineEditMqttTopic->setText(topic);
//Setting for MQTT QoS
int qos = readFromRegistry(Names::SettingMqttQos).toInt();
m_ui->spinBoxMqttQos->setValue(qos);
m_iMqtt->setQos(qos);
//Setting for last known MQTT address
QUrl lastMqttUrl = readFromRegistry(Names::SettingLastMqttAddress).toUrl();
m_ui->lineEditMqttBroker->setText(lastMqttUrl.toString());
m_iMqtt->setBroker(lastMqttUrl);
//Allow positional arguments
bool wildcardPerm = readFromRegistry(Names::SettingAllowWildcards).toBool();
m_ui->checkBoxAllowWildcards->setChecked(wildcardPerm);
m_endpoint->setAllowWildcards(wildcardPerm);
//Raw message execution permission
bool execPerm = readFromRegistry(Names::SettingRawExecPermission).toBool();
m_ui->checkBoxExecPermission->setChecked(execPerm);
m_endpoint->setRawExecPermission(execPerm);
//Raw message output publish permission
bool publishPerm = readFromRegistry(Names::SettingPublishOutput).toBool();
m_ui->checkBoxPublishOutput->setChecked(publishPerm);
m_endpoint->setRawExecPublish(publishPerm);
//Payload map
loadPayloadMap();
//Setting for first start flag
m_firstStart = readFromRegistry(Names::SettingFirstStart).toBool();
}
void MainWindow::savePayloadMap()
{
QJsonObject payloadObject;
QJsonArray payloadArr, functionArr, argumentArr;
QList<int> emptyRows;
auto payloadTable = m_ui->tableWidget;
for(int i = 0; i < payloadTable->rowCount(); ++i) {
QTableWidgetItem *payload = m_ui->tableWidget->item(i, 0);
QTableWidgetItem *function = m_ui->tableWidget->item(i, 1);
QTableWidgetItem *argument = m_ui->tableWidget->item(i, 2);
if(payload->text().isEmpty() && argument->text().isEmpty()) {
emptyRows.push_back(i);
} else {
payloadArr.push_back(payload->text());
functionArr.push_back(function->text());
argumentArr.push_back(argument->text());
}
}
std::reverse(emptyRows.begin(), emptyRows.end());
for(int i : emptyRows) {
payloadTable->removeRow(i);
}
payloadObject.insert("payload", payloadArr);
payloadObject.insert("function", functionArr);
payloadObject.insert("argument", argumentArr);
m_payloadMap = payloadObject;
m_endpoint->setPayloadMap(m_payloadMap);
payloadTable->repaint();
}
void MainWindow::loadPayloadMap(const QJsonDocument &file)
{
QJsonObject payloadObject;
if(file.isEmpty()) {
payloadObject = readFromRegistry(Names::SettingPayloadMap).toJsonObject();
} else {
payloadObject = file.object();
}
auto payloadTable = m_ui->tableWidget;
payloadTable->setRowCount(payloadObject.value("payload").toArray().size());
for(int i = 0; i < payloadTable->rowCount(); ++i) {
QTableWidgetItem *payload = m_ui->tableWidget->item(i, 0);
QTableWidgetItem *function = m_ui->tableWidget->item(i, 1);
QTableWidgetItem *argument = m_ui->tableWidget->item(i, 2);
if(!payload) {
payload = new QTableWidgetItem(QString(""));
payloadTable->setItem(i, 0, payload);
}
if(!function) {
function = new QTableWidgetItem(QString(""));
payloadTable->setItem(i, 1, function);
}
if(!argument) {
argument = new QTableWidgetItem(QString(""));
payloadTable->setItem(i, 2, argument);
}
payload->setText(payloadObject.value("payload").toArray()[i].toString());
function->setText(payloadObject.value("function").toArray()[i].toString());
argument->setText(payloadObject.value("argument").toArray()[i].toString());
}
m_payloadMap = payloadObject;
m_endpoint->setPayloadMap(m_payloadMap);
}
void MainWindow::on_pushButtonSaveSettings_clicked()
{
writeToRegistry("geometry", saveGeometry());
writeToRegistry("windowState", saveState());
//Autostart enabled
QSettings bootSettings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
QString path = QDir::toNativeSeparators(QCoreApplication::applicationFilePath());
if(m_ui->checkBoxAutostart->isChecked()) {
writeToRegistry(Names::SettingAutostartEnabled, true);
bootSettings.setValue(Names::SettingApplication, path);
} else {
writeToRegistry(Names::SettingAutostartEnabled, false);
bootSettings.remove(Names::SettingApplication);
}
//Allow popups
if(m_ui->checkBoxAllowPopups->isChecked()) {
writeToRegistry(Names::SettingShowPopups, Qt::Checked);
} else {
writeToRegistry(Names::SettingShowPopups, Qt::Unchecked);
}
//Select display
m_endpoint->enumerateSettings(m_ui->comboBoxDisplayList->currentIndex());
writeToRegistry(Names::SettingSelectedMonitor, m_ui->comboBoxDisplayList->currentIndex());
//Websocket server
QUrl wsUrl = QUrl(m_ui->lineEditWebSocketAddr->text());
m_iWebSocket->connectToServer(wsUrl);
writeToRegistry(Names::SettingLastWsAddress, wsUrl);
//Save credentials
if(m_ui->checkBoxSaveCredentials->isChecked()) {
writeToRegistry(Names::SettingSaveCredentials, Qt::Checked);
} else {
writeToRegistry(Names::SettingSaveCredentials, Qt::Unchecked);
}
//MQTT broker server
QUrl mqttUrl = QUrl(m_ui->lineEditMqttBroker->text());
m_iMqtt->setBroker(mqttUrl);
writeToRegistry(Names::SettingLastMqttAddress, mqttUrl);
//MQTT username
QString user = m_ui->lineEditMqttUsername->text();
m_iMqtt->setUsername(user);
//MQTT password
QString pw = m_ui->lineEditMqttPassword->text();
m_iMqtt->setPassword(pw);
if(m_ui->checkBoxSaveCredentials->isChecked()) {
writeToRegistry(Names::SettingMqttUser, user);
writeToRegistry(Names::SettingMqttPassword, pw.toLatin1().toHex()); //Save as hex just to prevent casual peeking
} else {
removeFromRegistry(Names::SettingMqttUser);
removeFromRegistry(Names::SettingMqttPassword);
}
//MQTT topic
QString topic = m_ui->lineEditMqttTopic->text();
m_iMqtt->setTopic(topic);
writeToRegistry(Names::SettingMqttTopic, topic);
//MQTT QoS
m_iMqtt->setQos(m_ui->spinBoxMqttQos->value());
writeToRegistry(Names::SettingMqttQos, m_ui->spinBoxMqttQos->value());
//Payload mapping
savePayloadMap();
writeToRegistry(Names::SettingPayloadMap, m_payloadMap);
//Allow positional arguments
m_endpoint->setAllowWildcards(m_ui->checkBoxAllowWildcards->isChecked());
writeToRegistry(Names::SettingAllowWildcards, m_ui->checkBoxAllowWildcards->isChecked());
//Raw message execution permission
m_endpoint->setRawExecPermission(m_ui->checkBoxExecPermission->isChecked());
writeToRegistry(Names::SettingRawExecPermission, m_ui->checkBoxExecPermission->isChecked());
//Raw message output publish permission
m_endpoint->setRawExecPublish(m_ui->checkBoxPublishOutput->isChecked());
writeToRegistry(Names::SettingPublishOutput, m_ui->checkBoxPublishOutput->isChecked());
}
void MainWindow::on_checkBoxExecPermission_stateChanged(int arg1)
{
m_ui->checkBoxPublishOutput->setDisabled(!arg1);
}
void MainWindow::on_lineEditMqttTopic_textChanged(const QString &arg1)
{
m_ui->checkBoxPublishOutput->setText(QString("Publish output in topic %1/%2").arg(arg1).arg(Names::MqttPowershellSubtopic));
}
void MainWindow::on_pushButtonRefreshDisplays_clicked()
{
m_ui->comboBoxDisplayList->clear();
m_endpoint->enumerateDevices();
setupDisplayCombobox(m_endpoint->getDisplays());
}
void MainWindow::on_pushButtonRefreshAudio_clicked()
{
m_audioDevice->refreshList();
m_ui->comboBoxAudioList->clear();
setupAudioCombobox(m_audioDevice->getAllAudioDevices());
}
void MainWindow::on_pushButtonExportPayloadMap_clicked()
{
QJsonDocument doc;
doc.setObject(m_payloadMap);
QString fileName = QFileDialog::getSaveFileName(this, "Save Payload Mapping", "", "JSON (*.json)");
if(fileName.isEmpty())
return;
else {
QFile file(fileName);
file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
file.write(doc.toJson(QJsonDocument::Compact));
file.close();
}
}
void MainWindow::on_pushButtonImportPayloadMap_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this, "Load Payload Mapping", "", "JSON (*.json)");
QFile file(fileName);
file.open(QIODevice::ReadOnly | QIODevice::Text);
QJsonParseError jsonParseError;
QJsonDocument importFile = QJsonDocument::fromJson(file.readAll(), &jsonParseError);
file.close();
loadPayloadMap(importFile);
}
| 19,813
|
C++
|
.cpp
| 483
| 35.225673
| 215
| 0.696628
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,706
|
audioendpointcontroller.cpp
|
stuomas_disorient/src/audioendpointcontroller.cpp
|
// Adapted from https://github.com/DanStevens/AudioEndPointController
#include "audioendpointcontroller.h"
#include <QDebug>
AudioEndpointController::AudioEndpointController()
{
m_state->pDeviceFormatStr = nullptr;
m_state->pDeviceFormatStr = _T(DEVICE_OUTPUT_FORMAT);
m_state->deviceStateFilter = DEVICE_STATE_ACTIVE;
m_state->option = 0;
createDeviceEnumerator(m_state);
}
AudioEndpointController::~AudioEndpointController()
{
delete m_state;
}
void AudioEndpointController::refreshList()
{
allAudioDevices.clear();
m_state->option = 0;
createDeviceEnumerator(m_state);
}
void AudioEndpointController::onChangeRequest(QString device)
{
m_requestedDevice = device;
m_state->option = 0;
//Option 0 iterates over all audio devices. If there is a device name matching to
//requested device, createDeviceEnumerator sets m_state->option to corresponding index.
createDeviceEnumerator(m_state);
//If match was found, run again and this time the matching device will be set default.
if(m_state->option != 0) {
createDeviceEnumerator(m_state);
}
}
// Create a multimedia device enumerator.
void AudioEndpointController::createDeviceEnumerator(TGlobalState* state)
{
state->pEnum = NULL;
state->hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
(void**)&state->pEnum);
if(SUCCEEDED(state->hr)) {
prepareDeviceEnumerator(state);
}
}
// Prepare the device enumerator
void AudioEndpointController::prepareDeviceEnumerator(TGlobalState* state)
{
state->hr = state->pEnum->EnumAudioEndpoints(eRender, state->deviceStateFilter, &state->pDevices);
if(SUCCEEDED(state->hr)) {
enumerateOutputDevices(state);
}
state->pEnum->Release();
}
// Enumerate the output devices
void AudioEndpointController::enumerateOutputDevices(TGlobalState* state)
{
UINT count;
state->pDevices->GetCount(&count);
// If option is less than 1, list devices
if(state->option < 1) {
// Get default device
IMMDevice* pDefaultDevice;
state->hr = state->pEnum->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDefaultDevice);
if(SUCCEEDED(state->hr)) {
state->hr = pDefaultDevice->GetId(&state->strDefaultDeviceID);
// Iterate all devices
for (int i = 1; i <= (int)count; i++) {
state->hr = state->pDevices->Item(i - 1, &state->pCurrentDevice);
if(SUCCEEDED(state->hr)) {
state->hr = printDeviceInfo(state->pCurrentDevice, i);
state->pCurrentDevice->Release();
}
}
}
}
// If option corresponds with the index of an audio device, set it to default
else if (state->option <= (int)count) {
state->hr = state->pDevices->Item(state->option - 1, &state->pCurrentDevice);
if(SUCCEEDED(state->hr)) {
LPWSTR strID = NULL;
state->hr = state->pCurrentDevice->GetId(&strID);
if (SUCCEEDED(state->hr)) {
state->hr = SetDefaultAudioPlaybackDevice(strID);
}
state->pCurrentDevice->Release();
}
}
// Otherwise inform user than option doesn't correspond with a device
else {
qDebug() << "No audio device with index" << state->option;
}
state->pDevices->Release();
}
std::wstring AudioEndpointController::getDeviceProperty(IPropertyStore* pStore, const PROPERTYKEY key)
{
PROPVARIANT prop;
PropVariantInit(&prop);
HRESULT hr = pStore->GetValue(key, &prop);
if(SUCCEEDED(hr)) {
std::wstring result (prop.pwszVal);
PropVariantClear(&prop);
return result;
} else {
return std::wstring (L"");
}
}
QVector<QString> AudioEndpointController::getAllAudioDevices()
{
return allAudioDevices;
}
HRESULT AudioEndpointController::printDeviceInfo(IMMDevice* pDevice, int index)
{
// Device ID
LPWSTR strID = NULL;
HRESULT hr = pDevice->GetId(&strID);
if(!SUCCEEDED(hr)) {
return hr;
}
// Device state
DWORD dwState;
hr = pDevice->GetState(&dwState);
if(!SUCCEEDED(hr)) {
return hr;
}
IPropertyStore *pStore;
hr = pDevice->OpenPropertyStore(STGM_READ, &pStore);
if(SUCCEEDED(hr)) {
std::wstring friendlyName = getDeviceProperty(pStore, PKEY_Device_FriendlyName);
std::wstring description = getDeviceProperty(pStore, PKEY_Device_DeviceDesc);
std::wstring interfaceFriendlyName = getDeviceProperty(pStore, PKEY_DeviceInterface_FriendlyName);
allAudioDevices.push_back(QString::fromStdWString(description));
if(m_requestedDevice == QString::fromStdWString(description)) {
m_state->option = index;
}
pStore->Release();
}
return hr;
}
HRESULT AudioEndpointController::SetDefaultAudioPlaybackDevice(LPCWSTR devID)
{
IPolicyConfig *pPolicyConfig;
ERole reserved = eConsole;
HRESULT hr = CoCreateInstance(__uuidof(CPolicyConfigClient),
NULL, CLSCTX_ALL, __uuidof(IPolicyConfig), (LPVOID *)&pPolicyConfig);
if (SUCCEEDED(hr)) {
hr = pPolicyConfig->SetDefaultEndpoint(devID, reserved);
pPolicyConfig->Release();
}
return hr;
}
| 5,323
|
C++
|
.cpp
| 149
| 29.798658
| 111
| 0.679791
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,707
|
inputmqtt.cpp
|
stuomas_disorient/src/inputmqtt.cpp
|
#include "inputmqtt.h"
#include <QtMqtt/QMqttClient>
InputMqtt::InputMqtt()
{
m_client = new QMqttClient(this);
connect(m_client, &QMqttClient::stateChanged, this, &InputMqtt::onStateChanged);
connect(m_client, &QMqttClient::messageReceived, this, &InputMqtt::onMessageReceived);
connect(m_autoReconnectTimer, &QTimer::timeout, this, &InputMqtt::reconnect);
setObjectName("InputMqtt");
}
InputMqtt::~InputMqtt()
{
delete m_client;
}
bool InputMqtt::validateUrl(const QUrl &url)
{
return url.isEmpty() || (url.isValid() && (url.scheme() == "http" || url.scheme() == "https"));
}
void InputMqtt::reconnect()
{
m_autoReconnectInProgress = true;
m_client->connectToHost();
}
void InputMqtt::disconnect()
{
m_client->disconnectFromHost();
}
void InputMqtt::subscribeToTopic()
{
auto subOk = m_client->subscribe(m_topic, m_qos);
if(m_client->state() == QMqttClient::Connected && !subOk) {
emit statusToLog("Could not subscribe. Is there a valid connection?");
} else if(subOk) {
emit statusToLog("Subscribed to topic: " + m_topic);
}
}
void InputMqtt::setBroker(const QUrl &addr)
{
m_autoReconnectTimer->stop();
if(m_client->state() == QMqttClient::Connected && addr.host() == m_brokerHostname && addr.port() == m_brokerPort) return;
m_brokerHostname = addr.host();
m_brokerPort = addr.port();
m_client->disconnectFromHost();
if(!addr.isEmpty() && validateUrl(addr)) {
m_client->setHostname(m_brokerHostname);
m_client->setPort(m_brokerPort);
m_client->connectToHost();
} else if(!validateUrl(addr)) {
emit statusToLog("Invalid broker address!");
}
}
void InputMqtt::setPassword(const QString &pw)
{
if(pw == m_password) return;
m_password = pw;
m_client->setPassword(m_password);
}
void InputMqtt::setUsername(const QString &user)
{
if(user == m_username) return;
m_username = user;
m_client->setUsername(m_username);
}
void InputMqtt::setQos(int qos)
{
if(qos == m_qos) return;
m_qos = qos;
}
void InputMqtt::setTopic(const QString &topic)
{
if(topic == m_topic) return;
if(!m_topic.isEmpty()) {
m_client->unsubscribe(m_topic);
emit statusToLog("Unsubscribed from topic: " + m_topic);
}
m_topic = topic;
subscribeToTopic();
}
void InputMqtt::onStateChanged()
{
if(m_client->state() == QMqttClient::Disconnected) {
if(!m_brokerHostname.isEmpty()) {
m_autoReconnectTimer->setInterval(10000);
m_autoReconnectTimer->setSingleShot(true);
m_autoReconnectTimer->start();
} else {
qDebug() << "MQTT autoreconnecting...";
}
if(!m_autoReconnectInProgress) {
emit statusToLog("<font color='red'>Broker disconnected!</font>");
}
} else if(m_client->state() == QMqttClient::Connecting) {
if(!m_autoReconnectInProgress) {
emit statusToLog("Connecting...");
}
} else if(m_client->state() == QMqttClient::Connected) {
m_autoReconnectInProgress = false;
emit statusToLog("Broker connected!");
subscribeToTopic();
}
}
void InputMqtt::setClientPort(int p)
{
m_client->setPort(p);
}
void InputMqtt::onPublish(const QString &msg, const QString &subtopic)
{
m_client->publish(QMqttTopicName(QString("%1/%2").arg(m_topic).arg(subtopic)), msg.toUtf8(), m_qos);
}
void InputMqtt::onMessageReceived(const QString &msg)
{
emit messageToEndpoint(msg);
}
| 3,531
|
C++
|
.cpp
| 113
| 26.628319
| 125
| 0.664408
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,708
|
inputwebsocket.cpp
|
stuomas_disorient/src/inputwebsocket.cpp
|
#include "inputwebsocket.h"
InputWebSocket::InputWebSocket() : m_wsock(new QWebSocket)
{
connect(m_wsock, &QWebSocket::connected, this, &InputWebSocket::onConnected);
connect(m_wsock, &QWebSocket::disconnected, this, &InputWebSocket::onDisconnected);
connect(m_wsock, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error), this, &InputWebSocket::onError);
connect(m_autoReconnectTimer, &QTimer::timeout, this, &InputWebSocket::reconnect);
setObjectName("InputWebSocket");
//Does not work with static linking yet...
//QSslConfiguration sslConfiguration = m_wsock->sslConfiguration();
//sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyPeer);
//m_wsock->setSslConfiguration(sslConfiguration);
}
InputWebSocket::~InputWebSocket()
{
delete m_wsock;
}
void InputWebSocket::connectToServer(const QUrl &addr)
{
if(m_wsock->state() == QAbstractSocket::ConnectedState && addr == m_serverUrl) return;
m_serverUrl = addr;
if(!addr.isEmpty() && validateUrl(addr)) {
m_wsock->open(m_serverUrl);
} else if(!validateUrl(addr)) {
emit statusToLog("Invalid address!");
}
}
bool InputWebSocket::validateUrl(const QUrl &url)
{
return url.isEmpty() || (url.isValid() && (url.scheme() == "ws" || url.scheme() == "wss"));
}
void InputWebSocket::closeConnection()
{
m_wsock->close(QWebSocketProtocol::CloseCodeNormal, "User closed application");
}
void InputWebSocket::reconnect()
{
m_autoReconnectInProgress = true;
m_wsock->open(m_serverUrl);
}
void InputWebSocket::onConnected()
{
connect(m_wsock, &QWebSocket::textMessageReceived, this, &InputWebSocket::onTextMessageReceived);
m_wsock->sendTextMessage(QStringLiteral("Hello, server!"));
emit statusToLog("Connected to server!");
m_autoReconnectInProgress = false;
}
void InputWebSocket::onPublish(const QString &msg, const QString &subtopic)
{
m_wsock->sendTextMessage(QString("%1/%2").arg(subtopic).arg(msg));
}
void InputWebSocket::onDisconnected()
{
if(!m_autoReconnectInProgress) {
emit statusToLog("<font color='red'>Disconnected from server.</font>");
} else {
qDebug() << "WebSocket autoreconnecting...";
}
if(!m_serverUrl.isEmpty()) {
m_autoReconnectTimer->setInterval(10000);
m_autoReconnectTimer->setSingleShot(true);
m_autoReconnectTimer->start();
}
}
void InputWebSocket::onTextMessageReceived(const QString &msg)
{
emit messageToEndpoint(msg);
}
void InputWebSocket::onError(const QAbstractSocket::SocketError &error)
{
if(!m_autoReconnectInProgress) {
emit statusToLog(m_wsock->errorString() + QString(" (error code %1)").arg(error));
}
}
| 2,705
|
C++
|
.cpp
| 74
| 32.77027
| 118
| 0.722583
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,709
|
endpoint.cpp
|
stuomas_disorient/src/endpoint.cpp
|
#include "endpoint.h"
#include "constants.h"
#include <QProcess>
#include <QJsonArray>
#include <QDir>
#include <QUrlQuery>
Endpoint::Endpoint()
{
//The primary display is used by default
dm.dmSize = sizeof(dm);
dm.dmDriverExtra = 0;
EnumDisplaySettings(nullptr, ENUM_CURRENT_SETTINGS, &dm);
enumerateDevices();
chosenDisplay = allDisplayAdapters[0];
}
void Endpoint::enumerateDevices()
{
allDisplayMonitors.clear();
allDisplayAdapters.clear();
DISPLAY_DEVICE ddev;
ddev.cb = sizeof(ddev);
ddev.StateFlags = DISPLAY_DEVICE_ACTIVE;
DWORD devNum = 0;
while(EnumDisplayDevices(nullptr, devNum, &ddev, EDD_GET_DEVICE_INTERFACE_NAME)) {
DISPLAY_DEVICE dmon;
dmon.cb = sizeof(dmon);
allDisplayAdapters.push_back(ddev);
if(EnumDisplayDevices(ddev.DeviceName, 0, &dmon, 0)) { //Second call needed to get monitor name
allDisplayMonitors.push_back(dmon);
}
++devNum;
}
}
void Endpoint::enumerateSettings(int displayNum)
{
if(EnumDisplaySettings(allDisplayAdapters[displayNum].DeviceName, ENUM_CURRENT_SETTINGS, &dm)) {
chosenDisplay = allDisplayAdapters[displayNum];
}
}
QString Endpoint::getWinApiStatus(LONG status)
{
switch(status) {
case DISP_CHANGE_SUCCESSFUL:
return "DISP_CHANGE_SUCCESSFUL";
case DISP_CHANGE_BADDUALVIEW:
return "DISP_CHANGE_BADDUALVIEW";
case DISP_CHANGE_BADFLAGS:
return "DISP_CHANGE_BADFLAGS";
case DISP_CHANGE_BADMODE:
return "DISP_CHANGE_BADMODE";
case DISP_CHANGE_BADPARAM:
return "DISP_CHANGE_BADPARAM";
case DISP_CHANGE_FAILED:
return "DISP_CHANGE_FAILED";
case DISP_CHANGE_NOTUPDATED:
return "DISP_CHANGE_NOTUPDATED";
case DISP_CHANGE_RESTART:
return "DISP_CHANGE_RESTART";
default:
return "Unknown status";
}
}
QString Endpoint::flip(int angle)
{
switch(angle) {
case 0:
dm.dmDisplayOrientation = DMDO_DEFAULT;
adjustResolution(angle, dm.dmPelsWidth, dm.dmPelsHeight);
break;
case 90:
dm.dmDisplayOrientation = DMDO_90;
adjustResolution(angle, dm.dmPelsWidth, dm.dmPelsHeight);
break;
case 180:
dm.dmDisplayOrientation = DMDO_180;
adjustResolution(angle, dm.dmPelsWidth, dm.dmPelsHeight);
break;
case 270:
dm.dmDisplayOrientation = DMDO_270;
adjustResolution(angle, dm.dmPelsWidth, dm.dmPelsHeight);
break;
default:
return "Invalid angle";
}
if(dm.dmFields | DM_DISPLAYORIENTATION) {
return getWinApiStatus(ChangeDisplaySettingsEx(chosenDisplay.DeviceName, &dm, nullptr, 0, nullptr));
} else {
return "Unknown error";
}
}
QString Endpoint::rearrangeDisplays(int idxPrimary, int idxSecondary)
{
DEVMODE dmPri, dmSec;
dmPri.dmSize = sizeof(dmPri);
dmPri.dmDriverExtra = 0;
dmSec.dmSize = sizeof(dmSec);
dmSec.dmDriverExtra = 0;
EnumDisplaySettings(allDisplayAdapters[idxPrimary].DeviceName, ENUM_CURRENT_SETTINGS, &dmPri);
EnumDisplaySettings(allDisplayAdapters[idxSecondary].DeviceName, ENUM_CURRENT_SETTINGS, &dmSec);
qDebug() << "Primary" << allDisplayAdapters[idxPrimary].DeviceName;
qDebug() << "Secondary" << allDisplayAdapters[idxSecondary].DeviceName;
//Save position of current secondary monitor
auto oldPosX = dmPri.dmPosition.x;
auto oldPosY = dmPri.dmPosition.y;
//New primary, must be at position (0,0)
dmPri.dmFields = DM_POSITION;
dmPri.dmPosition.x = 0;
dmPri.dmPosition.y = 0;
//New secondary, use position of previous secondary monitor (negated) to keep same arrangement as set in Windows display properties
dmSec.dmFields = DM_POSITION;
dmSec.dmPosition.x = -oldPosX;
dmSec.dmPosition.y = -oldPosY;
LONG status = ChangeDisplaySettingsEx(allDisplayAdapters[idxPrimary].DeviceName, &dmPri, NULL, CDS_SET_PRIMARY | CDS_UPDATEREGISTRY | CDS_NORESET, NULL);
ChangeDisplaySettingsEx(allDisplayAdapters[idxSecondary].DeviceName, &dmSec, NULL, CDS_UPDATEREGISTRY | CDS_NORESET, NULL);
ChangeDisplaySettingsEx(0,0,0,0,0);
return getWinApiStatus(status);
}
void Endpoint::adjustResolution(int angle, unsigned long &w, unsigned long &h)
{
switch(angle) {
case 0:
case 180:
if(w < h)
std::swap(w, h);
break;
case 90:
case 270:
if(w > h)
std::swap(w, h);
break;
}
}
//TODO: support multiple (comma-separated) payloads in one message
void Endpoint::onMessageReceived(const QString &msg)
{
QString origin = sender()->objectName();
QString lastActionStatus, functionName, functionArg, payloadName;
QStringList wildcardList;
QStringList splitMsg = msg.split("?");
QString baseMsg = splitMsg.at(0);
QMap<QString, QString> wildcardMap;
QRegExp queryPairDelimiter("(\\,|\\&)"); // accepts '&' and ',' between pairs
if(splitMsg.size() > 1) {
wildcardList = splitMsg.at(1).split(queryPairDelimiter);
for(auto str : wildcardList) {
if(str.split("=").size() > 1) {
wildcardMap.insert("$" + str.split("=").at(0).trimmed(), str.split("=").at(1).trimmed());
}
}
}
qDebug() << wildcardMap;
QJsonObject payloads = m_payloadMap;
QJsonArray payloadArr = payloads.value("payload").toArray();
QJsonArray functionArr = payloads.value("function").toArray();
QJsonArray argumentArr = payloads.value("argument").toArray();
bool unrecognizedMsg = false;
for(int i = 0; i < payloadArr.size(); ++i) {
if(payloadArr[i].toString() == baseMsg) {
functionName = functionArr[i].toString();
functionArg = argumentArr[i].toString();
payloadName = payloadArr[i].toString();
}
}
QStringList args = functionArg.split(",");
for(auto& str : args) {
str = str.trimmed();
str.replace("$$", payloadName); //Replace $$ in arguments with the payloadName, might be useful
if(m_wildcardsAllowed) {
for(auto wc : wildcardMap.toStdMap()) {
str.replace(wc.first, wc.second);
}
}
}
/************************************************************************
** Unrecognized message when functionName and payloadName are still empty
*************************************************************************/
if(functionName.isEmpty() && payloadName.isEmpty()) {
unrecognizedMsg = true;
emit statusToLog("Unrecognized message: " + msg, origin);
}
/************************************************************************
** Rotate screen (index, angle)
*************************************************************************/
else if(functionName == Names::Functions.at(1)) {
if(args.size() < 2) {
lastActionStatus = "Invalid arguments";
} else {
bool ok;
int angle = args.at(1).toInt(&ok);
lastActionStatus = "Invalid angle";
if(ok) {
enumerateSettings(args.at(0).toInt());
lastActionStatus = flip(angle);
}
}
}
/************************************************************************
** Set audio device (name)
*************************************************************************/
else if(functionName == Names::Functions.at(2)) {
emit changeAudioDevice(functionArg);
}
/************************************************************************
** Arrange displays (index1, index2)
*************************************************************************/
else if(functionName == Names::Functions.at(3)) {
if(args.size() < 2) {
lastActionStatus = "Invalid arguments";
} else {
lastActionStatus = rearrangeDisplays(args.at(0).toInt(), args.at(1).toInt());
}
}
/************************************************************************
** Run executable (path)
*************************************************************************/
else if(functionName == Names::Functions.at(4)) {
QString path = args.at(0);
if(path.endsWith(".ps1") || path.endsWith(".bat") || path.endsWith(".cmd")) {
lastActionStatus = runInPowershell(args);
} else {
args.takeFirst();
QProcess::startDetached(path, args);
}
}
if(m_rawExecPermission && unrecognizedMsg && !msg.trimmed().isEmpty()) {
emit statusToLog("Attempting to execute in PowerShell");
QString output = runInPowershell({msg});
emit statusToLog("Output: " + output);
if(m_rawExecPublish) {
sendResponse(origin, output, Names::MqttPowershellSubtopic);
}
} else if(!unrecognizedMsg) {
emit statusToLog(QString("%1 (%2)").arg(payloadName).arg(lastActionStatus), origin);
sendResponse(origin, lastActionStatus, QString("%1/%2").arg(payloadName).arg(Names::MqttResponseSubtopic));
} else {
sendResponse(origin, "Unrecognized message", QString("%1/%2").arg(msg).arg(Names::MqttResponseSubtopic));
}
}
QString Endpoint::runInPowershell(const QStringList &args)
{
QProcess powershell;
QString cmd("powershell");
QStringList parameters{args};
powershell.setProcessChannelMode(QProcess::MergedChannels);
powershell.setReadChannel(QProcess::StandardOutput);
powershell.start(cmd, parameters, QIODevice::ReadWrite);
powershell.waitForFinished(3000);
QString stdOut = powershell.readAllStandardOutput().trimmed();
powershell.close();
return stdOut;
}
void Endpoint::sendResponse(const QString &sender, const QString &response, const QString &topic)
{
if(sender == "InputMqtt") {
emit mqttPublish(response, topic);
} else if(sender == "InputWebSocket") {
emit websocketPublish(response, topic);
}
}
| 10,017
|
C++
|
.cpp
| 259
| 32.243243
| 157
| 0.608982
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,711
|
inputmqtt.h
|
stuomas_disorient/include/inputmqtt.h
|
#ifndef INPUTMQTT_H
#define INPUTMQTT_H
#include <QMqttClient>
#include <QUrl>
#include <QTimer>
#include "constants.h"
class InputMqtt : public QObject
{
Q_OBJECT
signals:
void messageToEndpoint(const QString &msg);
void statusToLog(const QString &msg, const QString &sender = Names::InputMqttName);
public:
InputMqtt();
~InputMqtt();
bool validateUrl(const QUrl &url);
void disconnect();
void subscribeToTopic();
//Setters
void setBroker(const QUrl &addr);
void setPassword(const QString &pw);
void setUsername(const QString &user);
void setQos(int qos);
void setTopic(const QString &topic);
//Getters
QUrl getBroker() {
QUrl broker;
broker.setHost(m_brokerHostname);
broker.setPort(m_brokerPort);
return broker;
}
QString getUsername() { return m_username; }
QString getPassword() { return m_password; }
QString getTopic() { return m_topic; }
int getQos() { return m_qos; }
public slots:
void setClientPort(int p);
void onPublish(const QString &msg, const QString &subtopic = "");
void reconnect();
private slots:
void onStateChanged();
void onMessageReceived(const QString &msg);
private:
QMqttClient *m_client;
QString m_brokerHostname;
int m_brokerPort;
QString m_username;
QString m_password;
int m_qos;
QString m_topic;
QTimer *m_autoReconnectTimer = new QTimer(this);
bool m_autoReconnectInProgress = false;
};
#endif // INPUTMQTT_H
| 1,525
|
C++
|
.h
| 54
| 23.851852
| 87
| 0.699315
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,712
|
audioendpointcontroller.h
|
stuomas_disorient/include/audioendpointcontroller.h
|
#ifndef AUDIOENDPOINTCONTROLLER_H
#define AUDIOENDPOINTCONTROLLER_H
#include <PolicyConfig.h>
#include <QObject>
#include <QVector>
#define DEVICE_OUTPUT_FORMAT "Audio Device %d: %ws"
typedef struct TGlobalState
{
HRESULT hr;
int option;
IMMDeviceEnumerator *pEnum;
IMMDeviceCollection *pDevices;
LPWSTR strDefaultDeviceID;
IMMDevice *pCurrentDevice;
LPCWSTR pDeviceFormatStr;
int deviceStateFilter;
} TGlobalState;
class AudioEndpointController : public QObject
{
Q_OBJECT
public:
AudioEndpointController();
~AudioEndpointController();
HRESULT SetDefaultAudioPlaybackDevice(LPCWSTR devID);
HRESULT printDeviceInfo(IMMDevice* pDevice, int index);
void createDeviceEnumerator(TGlobalState* state);
void prepareDeviceEnumerator(TGlobalState* state);
void enumerateOutputDevices(TGlobalState* state);
std::wstring getDeviceProperty(IPropertyStore* pStore, const PROPERTYKEY key);
QVector<QString> getAllAudioDevices();
void refreshList();
public slots:
void onChangeRequest(QString device);
private:
TGlobalState *m_state = new TGlobalState;
QString m_requestedDevice;
QVector<QString> allAudioDevices;
};
#endif // AUDIOENDPOINTCONTROLLER_H
| 1,239
|
C++
|
.h
| 39
| 28.205128
| 82
| 0.791107
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,714
|
constants.h
|
stuomas_disorient/include/constants.h
|
#ifndef CONSTANTS_H
#define CONSTANTS_H
#include <QStringList>
namespace Names {
//Names used in Windows registry
const QString SettingOrganization = "Disorient";
const QString SettingApplication = "Disorient";
const QString SettingFirstStart = "dis_opt_1";
const QString SettingLastWsAddress = "dis_opt_2";
const QString SettingLastMqttAddress = "dis_opt_3";
const QString SettingAutostartEnabled = "dis_opt_4";
const QString SettingShowPopups = "dis_opt_5";
const QString SettingSelectedMonitor = "dis_opt_6";
const QString SettingMqttUser = "dis_opt_7";
const QString SettingMqttPassword = "dis_opt_8";
const QString SettingMqttTopic = "dis_opt_9";
const QString SettingMqttQos = "dis_opt_10";
const QString SettingPayloadMap = "dis_opt_11";
const QString SettingRawExecPermission = "dis_opt_12";
const QString SettingPublishOutput = "dis_opt_13";
const QString SettingSaveCredentials = "dis_opt_14";
const QString SettingAllowWildcards = "dis_opt_15";
//Other stuff
const QString InputMqttName = "InputMqtt";
const QString InputWebSocketName = "InputWebSocket";
const QString MqttResponseSubtopic = "response";
const QString MqttPowershellSubtopic = QString("%1/%2").arg("powershell").arg(MqttResponseSubtopic);
const QStringList Functions = {"", "Rotate screen (index, angle)", "Set audio device (name)", "Arrange displays (index1, index2)", "Run executable (path, args)"};
}
#endif // CONSTANTS_H
| 1,407
|
C++
|
.h
| 30
| 45.766667
| 162
| 0.789512
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,715
|
mainwindow.h
|
stuomas_disorient/include/mainwindow.h
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStatusBar>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QAction>
#include <QMessageBox>
#include <QCloseEvent>
#include <QSettings>
#include <QDir>
#include <QDateTime>
#include <QComboBox>
#include <QJsonObject>
#include <QJsonDocument>
#include "endpoint.h"
#include "inputwebsocket.h"
#include "inputmqtt.h"
#include "constants.h"
#include "windows.h"
#include "audioendpointcontroller.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
QVariant readFromRegistry(const QString &key);
void writeToRegistry(const QString &key, const QVariant &value);
void loadSettingsFromRegistry();
bool nativeEvent(const QByteArray& eventType, void* message, long* result);
void log(const QString &logtext);
void setupDisplayCombobox(const QVector<DISPLAY_DEVICE> &displays);
void setupAudioCombobox(const QVector<QString> &audio);
void setupHotkeys();
void setupPayloadTable();
void setupStyles();
void savePayloadMap();
void loadPayloadMap(const QJsonDocument &file = QJsonDocument());
QString timestamp();
QVector<QString> getAllAudioDevices();
void removeFromRegistry(const QString &key);
signals:
void mqttPublish(const QString &msg, const QString &subtopic = "");
void websocketPublish(const QString &msg, const QString &subtopic = "");
private slots:
void onStatusReceived(const QString &status, const QString &sender);
void onAddRowClicked();
void on_pushButtonSaveSettings_clicked();
void on_checkBoxExecPermission_stateChanged(int arg1);
void on_lineEditMqttTopic_textChanged(const QString &arg1);
void on_pushButtonRefreshDisplays_clicked();
void on_pushButtonRefreshAudio_clicked();
void on_pushButtonExportPayloadMap_clicked();
void on_pushButtonImportPayloadMap_clicked();
private:
Ui::MainWindow *m_ui;
Endpoint *m_endpoint;
InputWebSocket *m_iWebSocket;
InputMqtt *m_iMqtt;
QString m_statusMsg;
QSystemTrayIcon *m_sysTrayIcon;
bool m_closing;
bool m_firstStart;
bool m_firstHide = true;
QJsonObject m_payloadMap;
AudioEndpointController *m_audioDevice;
void setupSysTray();
protected:
void closeEvent(QCloseEvent *event);
};
#endif // MAINWINDOW_H
| 2,420
|
C++
|
.h
| 75
| 28.906667
| 79
| 0.762414
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,716
|
inputwebsocket.h
|
stuomas_disorient/include/inputwebsocket.h
|
#ifndef INPUTWEBSOCKET_H
#define INPUTWEBSOCKET_H
/* Disorient acts as a WebSocket client.
* Give the WebSocket server address in the GUI
* and it will be automatically connected to and
* the server can start pushing text messages.
*/
#include <QString>
#include <QtWebSockets/QWebSocket>
#include <QTimer>
#include "constants.h"
class InputWebSocket : public QObject
{
Q_OBJECT
public:
InputWebSocket();
~InputWebSocket();
void connectToServer(const QUrl &addr);
bool validateUrl(const QUrl &url);
void closeConnection();
void reconnect();
signals:
void messageToEndpoint(const QString &msg);
void statusToLog(const QString &msg, const QString &sender = Names::InputWebSocketName);
public slots:
void onPublish(const QString &msg, const QString &subtopic = "");
private slots:
void onConnected();
void onDisconnected();
void onTextMessageReceived(const QString &msg);
void onError(const QAbstractSocket::SocketError &error);
private:
QWebSocket *m_wsock;
QUrl m_serverUrl;
QTimer *m_autoReconnectTimer = new QTimer(this);
bool m_autoReconnectInProgress = false;
};
#endif // INPUTWEBSOCKET_H
| 1,176
|
C++
|
.h
| 38
| 27.763158
| 92
| 0.755752
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,717
|
endpoint.h
|
stuomas_disorient/include/endpoint.h
|
#ifndef SCREEN_H
#define SCREEN_H
#include <QString>
#include <QObject>
#include <QVector>
#include <QJsonObject>
#include <algorithm>
#include "windows.h"
class Endpoint : public QObject
{
Q_OBJECT
public:
Endpoint();
QString flip(int angle);
QString rearrangeDisplays(int idxPrimary, int idxSecondary);
void adjustResolution(int angle, unsigned long &w, unsigned long &h);
void enumerateDevices();
void enumerateSettings(int displayNum);
QVector<DISPLAY_DEVICE> getDisplays() { return allDisplayMonitors; }
void setChosenDisplay(int displayNum) { chosenDisplay = allDisplayAdapters[displayNum]; }
void setRawExecPermission(bool setting) { m_rawExecPermission = setting; }
void setAllowWildcards(bool setting) { m_wildcardsAllowed = setting; }
void setRawExecPublish(bool setting) { m_rawExecPublish = setting; }
void setPayloadMap(QJsonObject payload) { m_payloadMap = payload; }
QString getWinApiStatus(LONG status);
void sendResponse(const QString &sender, const QString &topic, const QString &response);
QString runInPowershell(const QStringList &args);
signals:
void statusToLog(const QString &status, const QString &sender = "");
void mqttPublish(const QString &msg, const QString &subtopic = "");
void websocketPublish(const QString &msg, const QString &subtopic = "");
void changeAudioDevice(const QString &dev);
public slots:
void onMessageReceived(const QString &msg);
private:
DEVMODE dm;
bool m_rawExecPermission = false;
bool m_rawExecPublish = false;
bool m_wildcardsAllowed = false;
QJsonObject m_payloadMap;
//Some weird WinAPI quirks, maybe there is a better way
QVector<DISPLAY_DEVICE> allDisplayMonitors;
QVector<DISPLAY_DEVICE> allDisplayAdapters;
DISPLAY_DEVICE chosenDisplay;
};
#endif // SCREEN_H
| 1,849
|
C++
|
.h
| 46
| 36.413043
| 93
| 0.756546
|
stuomas/disorient
| 38
| 0
| 1
|
LGPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,718
|
timer.cpp
|
RobertIndie_moss/example/Chat/timer/timer.cpp
|
#include "Timer.h"
Timer::Timer(Run* instance)
:m_second(0), m_u_second(0), exec(instance) {}
Timer::Timer(Run* instance, const long& second, const long& u_second)
: m_second(second), m_u_second(u_second), exec(instance) {}
Timer::~Timer() { this->Stop(); }
void Timer::SetTime(const long& second, const long& u_second)
{
this->m_second = second;
this->m_u_second = u_second;
}
void Timer::Start()
{
pthread_create(&(this->TimerThread), NULL, TimerCore, this);
}
void Timer::Stop()
{
pthread_cancel(TimerThread);
pthread_join(TimerThread, NULL);
}
void* Timer::TimerCore(void* obejct_self)
{
(static_cast<Timer*>(obejct_self))->ProThread();
}
void Timer::ProThread()
{
while (true)
{
this->exec->start();
pthread_testcancel();
struct timeval tmpVarTime;
tmpVarTime.tv_sec = this->m_second;
tmpVarTime.tv_usec = this->m_u_second;
select(0, NULL, NULL, NULL, &tmpVarTime);
}
}
| 934
|
C++
|
.cpp
| 36
| 23.305556
| 70
| 0.6767
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,719
|
Client.cpp
|
RobertIndie_moss/example/Chat/Client/Client.cpp
|
#include "Client.h"
Client::Client(const std::string& UserID,
const std::string& ServerIP,
const unsigned short& Port)
:ServerAddress(ServerIP), ServerPort(Port), UserID(UserID)
{
channel.Connect(this->ServerAddress, this->ServerPort);
char* recv_buff = new char[RecvBuff] {'\0'};
this->recv_data = new Data(recv_buff, RecvBuff);
if (this->recv_data == nullptr)
{
std::cout << "Creating Data Failed" << std::endl;
}
}
Client::~Client()
{
if (recv_data != nullptr)
delete recv_data;
if (send_data != nullptr)
delete send_data;
}
ssize_t Client::SendAndRecv()
{
channel.Send(this->send_data, this->recv_data);
}
Data* Client::Packag(const std::string& str)
{
char* C_str = new char[str.length() + 1];
for (int i = 0; i <= str.length() + 1; ++i)
{
*(C_str + i) = str[i];
}
if (C_str != nullptr && (this->send_data = new Data(C_str, str.length() + 1)) == nullptr)
{
std::cout << "Creating Data failed!!" << std::endl;
return nullptr;
}
else {
//std::cout<<this->recv_data<<std::endl;
return this->send_data;
}
}
void Client::SelfControlSend(const std::string& DirID)
{
std::cout << "please Enter context:" << std::endl;
std::string str;
std::cin >> str;
std::string Header = DirID + std::string("\t") + this->UserID + std::string("\t");
std::string result = Header + str;
std::cout << result << std::endl;
Packag(result);
//std::cout<<"this"<<std::endl;
this->SendAndRecv();
}
void Client::autoRequest()
{
std::cout << "SendToAutoRequest" << std::endl;
this->Packag(std::string("Request:") + this->UserID);
this->SendAndRecv();
std::cout << "OutPut:Message" << std::endl;
for (unsigned int i = 0; i <= this->recv_data->len &&
*(this->recv_data->buff) != '\0'; ++i)
{
std::cout << *(this->recv_data->buff + i);
}
std::cout << std::endl;
}
void Client::run()
{
bool flag = true;
char c;
while (flag)
{
std::cout << "what do you want to do:\n"
<< "u : SendMessageToUser\n"
<< "a : SendRequest"
<< "q : quit\n"
<< std::endl;
//this->autoRequest();
std::cin >> c;
switch (c)
{
case 'q':
case 'Q':
flag = false;
break;
case 'u':
case 'U':
this->core();
break;
case 'a':
case 'A':
this->autoRequest();
break;
}
}
}
void Client::core()
{
std::cout << "please enter UserID:" << std::endl;
std::string DirID;
std::cin >> DirID;
this->SelfControlSend(DirID);
//this->autoRequest();
}
| 2,528
|
C++
|
.cpp
| 105
| 20.609524
| 91
| 0.602258
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,720
|
ProRequest.cpp
|
RobertIndie_moss/example/Chat/server/ProRequest.cpp
|
#include "ProRequest.h"
Data* ProRequest::MakeErrorData()
{
char* buff = new char[16];
static std::string tmpStr("ErrorDataType");
for (unsigned int i = 0; i <= tmpStr.length(); ++i)
{
*(buff + i) = tmpStr[i];
}
return new Data(buff, 16);
}
Data* ProRequest::MakeRespoData(const std::string& name)
{
unsigned int g = SerchID(this->ID_List, name);
std::string result = this->Context_List[g];
char* buff = new char[result.length()];
for (unsigned int i = 0; i <= result.length(); ++i)
{
*(buff + i) = result[i];
}
this->ID_List.erase(this->ID_List.begin() + (g - 1));
this->Context_List.erase(this->Context_List.begin() + (g - 1));
return new Data(buff, result.length());
}
int ProRequest::Analysis(const std::string& tmpStr)
{
std::vector<std::string*> Spilter;
std::cout << tmpStr << std::endl;
bool MaBool = MatchStr("Request:", tmpStr);
std::cout << ((MaBool) ? "Has" : "not") << std::endl;
if (MaBool)
{
std::cout << "match request" << std::endl;
return Respond;
}
else
{
Spilter = SpiltStr(tmpStr, '\t');
if (Spilter.size() == 3)
{
//若检测到发送数据将他发送到请求表
this->ID_List.push_back(*(Spilter[0]));
this->Context_List.push_back(*(Spilter[1]) + *(Spilter[2]));
return SucData;
}
else
{
std::cout << "Data Struct Failed!";
return ErrData;
}
}
}
| 1,403
|
C++
|
.cpp
| 52
| 22.846154
| 65
| 0.615031
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,721
|
Str.cpp
|
RobertIndie_moss/example/Chat/server/Str.cpp
|
std::vector<std::string*> SpiltStr(const std::string& TotalStr, const char& spiltChar)
{
std::vector<std::string*> SpiliterResult;
std::string tmpStr;
for (unsigned int i = 0; i <= TotalStr.length(); ++i)
{
if (TotalStr[i] != spiltChar)
{
tmpStr.push_back(TotalStr[i]);
}
else
{
SpiliterResult.push_back(new std::string(tmpStr));
tmpStr.clear();
}
}
if (tmpStr.length())
{
SpiliterResult.push_back(new std::string(tmpStr));
}
return SpiliterResult;
}
//匹配第个字符串时候包含第一个字符串
bool MatchStr(const std::string& Match_Str, const std::string& Source_Str)
{
//unsigned int d = 0;
for (unsigned int i = 0; i < Match_Str.length(); ++i)
{
if (Source_Str[i] == Match_Str[i])
{
continue;
}
else
{
return false;
}
}
return true;
}
int SerchID(const std::vector<std::string> str, const std::string& ID)
{
for (unsigned int i = 0; i < str.size(); ++i)
{
if (MatchStr(ID, str[i]))
{
return i;
}
}
return -1;
}
| 1,033
|
C++
|
.cpp
| 50
| 16.84
| 88
| 0.621875
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,722
|
Server.cpp
|
RobertIndie_moss/example/Chat/server/Server.cpp
|
#include "Server.h"
Server::Server(const unsigned short& port)
{
Channel.Bind("0.0.0.0", port);
}
void Server::Run(HandleFUN fun)
{
Channel.Serve(fun);
}
Data* fun(Data* const request)
{
static ProRequest funs;
std::string reStr(request->buff);
std::cout << reStr << std::endl;
const int respon = funs.Analysis(reStr);
std::vector<std::string*> result;
switch (respon)
{
case Respond:
result = SpiltStr(reStr, ':');
std::cout << "Who::" << *(result[1]) << std::endl;
if (SerchID(funs.ID_List, *result[1]) == -1)
{
return funs.MakeErrorData();
}
//std::cout<<"size:"<<result.size()<<*(result[0])<<std::endl;
return funs.MakeRespoData(*(result[1]));
case ErrData:
return funs.MakeErrorData();
case SucData:
return funs.MakeSucData();
}
}
| 813
|
C++
|
.cpp
| 33
| 21.30303
| 64
| 0.644993
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,723
|
Client.cpp
|
RobertIndie_moss/example/HeartChat/Client/Client.cpp
|
#include "Client.h"
class TimerSend : public Run {
public:
TimerSend(Client* pClient)
:pClient(pClient), Run() {}
virtual ~TimerSend() {}
private:
virtual void CorePro()override
{
std::cout << "SendToAutoRequest" << std::endl;
this->pClient->Packag(std::string("Request:") + this->pClient->UserID);
this->pClient->SendAndRecv();
if (*(this->pClient->recv_data->buff) != '\0')
{
std::cout << "OutPut:Message" << std::endl;
for (unsigned int i = 0; i <= this->pClient->recv_data->len &&
*(this->pClient->recv_data->buff + i) != '\0'; ++i)
{
std::cout << *(this->pClient->recv_data->buff + i);
}
std::cout << std::endl;
}
}
private:
class Client* pClient;
};
Client::Client(const std::string& UserID,
const std::string& ServerIP,
const unsigned short& Port)
:ServerAddress(ServerIP), ServerPort(Port), UserID(UserID)
{
channel.Connect(this->ServerAddress, this->ServerPort);
char* recv_buff = new char[RecvBuff] {'\0'};
this->recv_data = new Data(recv_buff, RecvBuff);
if (this->recv_data == nullptr)
{
std::cout << "Creating Data Failed" << std::endl;
}
this->autoRequest();
}
Client::~Client()
{
if (recv_data != nullptr)
delete recv_data;
if (send_data != nullptr)
delete send_data;
}
ssize_t Client::SendAndRecv()
{
channel.Send(this->send_data, this->recv_data);
}
Data* Client::Packag(const std::string& str)
{
char* C_str = new char[str.length() + 1];
for (int i = 0; i <= str.length() + 1; ++i)
{
*(C_str + i) = str[i];
}
if (C_str != nullptr && (this->send_data = new Data(C_str, str.length() + 1)) == nullptr)
{
std::cout << "Creating Data failed!!" << std::endl;
return nullptr;
}
else {
//std::cout<<this->recv_data<<std::endl;
return this->send_data;
}
}
void Client::SelfControlSend(const std::string& DirID)
{
std::cout << "please Enter context:" << std::endl;
std::string str;
std::cin >> str;
std::string Header = DirID + std::string("\t") + this->UserID + std::string("\t");
std::string result = Header + str;
std::cout << result << std::endl;
Packag(result);
//std::cout<<"this"<<std::endl;
this->SendAndRecv();
}
void Client::autoRequest()
{
static Timer t(new TimerSend(this), 20);
t.Start();
}
void Client::run()
{
bool flag = true;
char c;
while (flag)
{
std::cout << "what do you want to do:\n"
<< "u : SendMessageToUser\n"
<< "q : quit\n"
<< std::endl;
//this->autoRequest();
std::cin >> c;
switch (c)
{
case 'q':
case 'Q':
flag = false;
break;
case 'u':
case 'U':
this->core();
break;
}
}
}
void Client::core()
{
std::cout << "please enter UserID:" << std::endl;
std::string DirID;
std::cin >> DirID;
this->SelfControlSend(DirID);
//this->autoRequest();
}
| 2,872
|
C++
|
.cpp
| 118
| 20.855932
| 91
| 0.609846
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,724
|
server_main.cc
|
RobertIndie_moss/example/server/server_main.cc
|
/**
* Copyright 2019 Aaron Robert
* */
#include <errno.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <iostream>
#include <sstream>
#include <string>
#include "common/common.h"
#include "util/util.h"
const size_t MAXSIZE = 65535;
char const hex_chars[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
std::string DataToHex(char *data, size_t len) {
std::stringstream ss;
for (int i = 0; i < len; i++) {
ss << hex_chars[(data[i] & 0xF0) >> 4];
ss << hex_chars[(data[i] & 0x0F) >> 0];
ss << ' ';
}
return ss.str();
}
int old_main() {
int iRet;
int iSockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (iSockfd == -1) std::cout << "socket error:" << errno << std::endl;
sockaddr_in *sSvrAddr = new sockaddr_in;
sockaddr_in *sCliAddr = new sockaddr_in;
sSvrAddr->sin_family = AF_INET;
sSvrAddr->sin_addr.s_addr = htonl(INADDR_ANY);
sSvrAddr->sin_port = htons(9877);
iRet =
bind(iSockfd, reinterpret_cast<sockaddr *>(sSvrAddr), sizeof(*sSvrAddr));
if (iRet == -1) std::cout << "bind error:" << errno << std::endl;
while (1) {
int n;
socklen_t len = sizeof(*sCliAddr);
char data[MAXSIZE];
n = recvfrom(iSockfd, data, MAXSIZE, 0,
reinterpret_cast<sockaddr *>(sCliAddr), &len);
if (n == -1) std::cout << "recvfrom error:" << errno << std::endl;
std::cout << "Recv[" << n << "] " << std::endl;
// cout << DataToHex(data, n) << endl;
char ackData[] = {0x01};
iRet = sendto(iSockfd, ackData, sizeof(ackData), 0,
reinterpret_cast<sockaddr *>(sCliAddr), len);
}
}
Data *handle(void *context, Data *const request) {
Data *response = new Data(1);
return response;
}
int main(int argc, char **argv) {
InitLogger(argv);
UDPServerChannel channel;
channel.Bind("0.0.0.0", 9877);
channel.Serve(nullptr, handle);
return 0;
}
| 1,938
|
C++
|
.cc
| 61
| 28.016393
| 79
| 0.599253
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,725
|
client_main.cc
|
RobertIndie_moss/example/client/client_main.cc
|
/**
* Copyright 2019 Aaron Robert
* */
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "common/common.h"
#include "util/util.h"
const size_t MAXSIZE = 4096;
int readable_timeo(int fd, int sec) {
fd_set rset;
timeval tv;
FD_ZERO(&rset);
FD_SET(fd, &rset);
tv.tv_sec = sec;
tv.tv_usec = 0;
return select(fd + 1, &rset, NULL, NULL, &tv);
}
int old_main() {
int totalPacket = 0, ackPacket = 0;
int iSockfd = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in *sSvrAddr = new sockaddr_in;
sSvrAddr->sin_family = AF_INET;
sSvrAddr->sin_addr.s_addr = htonl(1998009103);
sSvrAddr->sin_port = htons(9877);
int n;
char data[] = {0x01, 0x02};
char data2[50000];
for (int i = 0; i < 2; i++) {
std::cout << "ACK/TOTAL: " << ackPacket << "/" << totalPacket << " "
<< ackPacket * 1.0 / totalPacket << std::endl;
totalPacket++;
n = sendto(iSockfd, data2, sizeof(data2), 0,
reinterpret_cast<sockaddr *>(sSvrAddr), sizeof(*sSvrAddr));
if (n == -1) continue;
char ackData[1];
if (readable_timeo(iSockfd, 1) == 0) {
std::cout << "Timeout" << std::endl;
continue;
}
n = recvfrom(iSockfd, ackData, sizeof(ackData), 0, NULL, NULL);
if (n == -1) continue;
if (ackData[0] == 0x01) ackPacket++;
}
}
int main(int argc, char **argv) {
InitLogger(argv);
// protoc_test();
UDPClientChannel channel;
channel.Connect("119.23.51.15", 9877);
char send_buff[100];
char recv_buff[100];
Data send_data(send_buff, 100), recv_data(recv_buff, 100);
for (int i = 0; i < 100; i++) channel.Send(&send_data, &recv_data);
return 0;
}
| 1,729
|
C++
|
.cc
| 60
| 25.483333
| 74
| 0.629052
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,726
|
test.cc
|
RobertIndie_moss/test/test.cc
|
#include <cstdint>
#include <map>
#include "iostream"
template <typename FuncType>
int Call(FuncType i) {
std::cout << sizeof(static_cast<FuncType>(i)) << std::endl;
return 0;
}
int main() {
std::map<std::string, int (*)(int)> m;
m["test"] = &Call<long>;
m["test"](1);
}
| 283
|
C++
|
.cc
| 13
| 19.846154
| 61
| 0.645522
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,727
|
main.cc
|
RobertIndie_moss/test/test_server/main.cc
|
/**
* Copyright 2019 Aaron Robert
* */
#include "./test.pb.h"
#include "rpc/rpc.h"
Data *handle(void *context, Data *const request) {
Data *response = new Data(1);
return response;
}
int P2PTest(std::stringstream *in_data, std::stringstream *out_data) {
moss_test::SimpleMessage req, res;
ConvertStreamToProtoObj(&req, in_data);
res.set_header(req.header());
res.set_id(req.id());
res.set_body(req.body());
ConvertProtoObjToStream(&res, out_data);
return 0;
}
int main(int argc, char **argv) {
InitLogger(argv);
UDPServerChannel channel;
channel.Bind("0.0.0.0", 9877);
ServerProxy prx(&channel);
REG_FUNC(prx, P2PTest);
prx.Serve();
return 0;
}
| 682
|
C++
|
.cc
| 27
| 22.888889
| 70
| 0.70092
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,728
|
test_stream.cc
|
RobertIndie_moss/test/moss_test/test_stream.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#ifndef __MOSS_TEST
#define __MOSS_TEST
#endif
#include "./command.h"
#include "./interfaces.h"
#include "./stream.h"
#include "gtest/gtest.h"
class TestConnection : public moss::CommandExecutor {
public:
TestConnection() {
cmdQueue_ =
std::static_pointer_cast<moss::CommandQueue<moss::CmdConnection>>(
std::make_shared<moss::CoCmdQueue<moss::CmdConnection>>());
}
std::shared_ptr<moss::CommandQueue<moss::CmdConnection>> cmdQueue_;
void PushCommand(std::shared_ptr<moss::CommandBase> cmd) {
auto _cmd = std::static_pointer_cast<moss::CmdConnection>(cmd);
cmdQueue_->PushCmd(std::static_pointer_cast<moss::CmdConnection>(cmd));
}
};
TEST(Stream, SendSideSimpleSend) {
auto conn = std::make_shared<TestConnection>();
auto stream = std::make_shared<moss::Stream>(
conn.get(), 12345, moss::Initializer::kClient,
moss::Directional::kUnidirectional);
char data[] = "Hello world!";
// Set flow credit
stream->sendSide_.flow_credit_ = sizeof(data);
// Test write data
stream->WriteData(data, sizeof(data));
auto data_block_cmd =
std::dynamic_pointer_cast<moss::CmdSendGFL>(conn->cmdQueue_->PopCmd());
EXPECT_NE(data_block_cmd.get(), nullptr);
auto send_data_cmd =
std::dynamic_pointer_cast<moss::CmdSendData>(conn->cmdQueue_->PopCmd());
EXPECT_EQ(send_data_cmd->send_count_, sizeof(data));
// std::shared_ptr<char> result_data(new char[sizeof(data)]);
// send_data_cmd->buffer_->read(result_data.get(), sizeof(data));
std::shared_ptr<char> result_data(new char[send_data_cmd->send_count_]);
stream->sendSide_.reader_for_conn_->Read(send_data_cmd->send_count_,
result_data.get());
EXPECT_EQ(memcmp(data, result_data.get(), sizeof(data)), 0);
// Test stream flow control -- data block
stream->WriteData(data, sizeof(data));
// auto data_cmd =
// std::dynamic_pointer_cast<moss::CmdSendData>(conn->cmdQueue_->PopCmd());
// EXPECT_NE(data_cmd.get(), nullptr);
auto blocked_cmd =
std::dynamic_pointer_cast<moss::CmdSendGFL>(conn->cmdQueue_->PopCmd());
EXPECT_NE(blocked_cmd.get(), nullptr);
auto frame = std::make_shared<FrameStreamDataBlocked>();
FrameType frame_type;
ConvertGFLToFrame(blocked_cmd->gfl_.get(), frame.get(), &frame_type);
EXPECT_EQ(frame_type, FrameType::kStreamDataBlocked);
EXPECT_EQ(frame->stream_data_limit, sizeof(data));
EXPECT_EQ(frame->stream_id, stream->id_);
// Test final stream
stream->sendSide_.flow_credit_ += 2 * sizeof(data); // add flow credit
stream->WriteData(data, sizeof(data), true);
auto send_final_data_cmd =
std::dynamic_pointer_cast<moss::CmdSendData>(conn->cmdQueue_->PopCmd());
EXPECT_EQ(stream->send_buffer_->is_final_, true);
}
| 3,457
|
C++
|
.cc
| 78
| 40.858974
| 81
| 0.703583
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,729
|
test_databuffer.cc
|
RobertIndie_moss/test/moss_test/test_databuffer.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#ifndef __MOSS_TEST
#define __MOSS_TEST
#endif
#include "gtest/gtest.h"
#include "util/databuffer.h"
TEST(DataBuffer, DPTR) {
DataBuffer buffer;
auto a = buffer.NewReader();
auto b = buffer.NewReader();
buffer.writer_pos_ = 5;
// test Move
EXPECT_EQ(DPTR::Move(&buffer, a->ptr_, -1), 7);
EXPECT_EQ(DPTR::Move(&buffer, a->ptr_, 7), 7);
EXPECT_EQ(DPTR::Move(&buffer, a->ptr_, 8), 0);
*a += 1;
EXPECT_EQ(a->ptr_, 1);
EXPECT_EQ(*a > *b, true);
}
TEST(DataBuffer, Write) {
DataBuffer buffer(16, false);
auto reader = buffer.NewReader();
char write_data[5] = {1, 2, 3, 4, 5};
buffer.Write(5, write_data);
EXPECT_EQ(memcmp(buffer.block_->buffer_, write_data, sizeof(write_data)), 0);
buffer.Write(5, write_data);
EXPECT_EQ(buffer.cap_size_, 16);
buffer.Read(reader.get(), 5, nullptr);
buffer.Write(5, write_data);
buffer.Write(5, write_data);
char check_data[16] = {2, 3, 4, 5, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1};
EXPECT_EQ(buffer.cap_size_, 16);
EXPECT_EQ(memcmp(buffer.block_->buffer_, check_data, sizeof(check_data)), 0);
}
TEST(DataBuffer, Read) {
DataBuffer buffer(8, false);
auto reader = buffer.NewReader();
char check_data[16] = {2, 3, 4, 5, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1};
buffer.Write(sizeof(check_data), check_data);
char read_data[8];
EXPECT_EQ(reader->Read(8, read_data), 8);
EXPECT_EQ(buffer.cap_size_, 16);
EXPECT_EQ(memcmp(read_data, check_data, sizeof(8)), 0);
}
| 2,142
|
C++
|
.cc
| 58
| 34.775862
| 79
| 0.683325
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,731
|
test_frame.cc
|
RobertIndie_moss/test/moss_test/test_frame.cc
|
/**
* Copyright 2019 Linkworld Open Team
* */
#include <cstring>
#include "./frame.h"
#include "gtest/gtest.h"
TEST(Frame, StreamFrameConvert) {
FrameStream frame;
frame.bits = 0x07;
frame.id = 0;
frame.offset = 64;
frame.length = 5;
frame.stream_data = new char[5]{0x01, 0x02, 0x03, 0x04, 0x05};
GenericFrameLayout gfl;
EXPECT_EQ(ConvertFrameToGFL(&frame, FrameType::kStream, &gfl), 0);
EXPECT_EQ(gfl.frame_type_bits, 0x07 | 0x08);
char gfl_data[] = {
0x00, // Stream ID
0x40, 0x40, // Offset
0x05, // Length
0x01, 0x02, 0x03, 0x04, 0x05 // Stream Data
};
EXPECT_EQ(gfl.data_len, 9);
EXPECT_EQ(memcmp(gfl.data, gfl_data, 9), 0);
// test convert bin to frame;
FrameStream recv_frame;
FrameType TypeFrame;
ConvertGFLToFrame(&gfl, &recv_frame, &TypeFrame);
EXPECT_EQ(TypeFrame, FrameType::kStream);
EXPECT_EQ(recv_frame.bits, 0x07 | 0x08);
EXPECT_EQ(recv_frame.id, 0);
EXPECT_EQ(recv_frame.length, 5);
EXPECT_EQ(recv_frame.offset, 64);
}
TEST(Frame, StreamFrameConvertWithoutData) {
FrameStream frame;
frame.bits = 0x4;
frame.id = 1073741823; // 4 bytes
frame.offset = 4611686018427387903; // 8 bytes
frame.stream_data = new char[5]{0x01, 0x02, 0x03, 0x04,
0x05}; // test: do not contain data in gfl
GenericFrameLayout gfl;
EXPECT_EQ(ConvertFrameToGFL(&frame, FrameType::kStream, &gfl), 0);
EXPECT_EQ(gfl.frame_type_bits, 0x04 | 0x08);
char gfl_data[] = {
0xbf, 0xff, 0xff, 0xff, // Stream ID
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff // Offset
};
EXPECT_EQ(gfl.data_len, 12);
EXPECT_EQ(memcmp(gfl.data, gfl_data, 12), 0);
// test convert bin to frame;
FrameStream recv_frame;
FrameType TypeFrame;
ConvertGFLToFrame(&gfl, &recv_frame, &TypeFrame);
EXPECT_EQ(TypeFrame, FrameType::kStream);
EXPECT_EQ(recv_frame.bits, 0x04 | 0x08);
EXPECT_EQ(recv_frame.id, 1073741823);
EXPECT_EQ(recv_frame.offset, 4611686018427387903);
}
TEST(Frame, StreamDataBlockedFrameConvert) {
FrameStreamDataBlocked frame;
frame.stream_id = 12345;
frame.stream_data_limit = 0;
GenericFrameLayout gfl;
EXPECT_EQ(ConvertFrameToGFL(&frame, FrameType::kStreamDataBlocked, &gfl), 0);
EXPECT_EQ(gfl.frame_type_bits, 0x15);
char gfl_data[] = {
0x70, 0x39, // Stream ID
0x00 // Stream Data Limit
};
EXPECT_EQ(gfl.data_len, 3);
EXPECT_EQ(memcmp(gfl.data, gfl_data, 3), 0);
// test convert bin to frame;
FrameStreamDataBlocked recv_frame;
FrameType frame_type;
ConvertGFLToFrame(&gfl, &recv_frame, &frame_type);
EXPECT_EQ(frame_type, FrameType::kStreamDataBlocked);
EXPECT_EQ(recv_frame.stream_id, frame.stream_id);
EXPECT_EQ(recv_frame.stream_data_limit, frame.stream_data_limit);
}
TEST(Frame, ResetStreamFrameConvert) {
FrameResetStream frame;
frame.stream_id = 12345;
frame.error_code = 12345;
frame.final_size = 12345;
GenericFrameLayout gfl;
EXPECT_EQ(ConvertFrameToGFL(&frame, FrameType::kResetStream, &gfl), 0);
EXPECT_EQ(gfl.frame_type_bits,0x04);
char gfl_data[] = {
0x70, 0x39, // Stream ID
0x70, 0x39, // Application Error Code
0x70, 0x39 // Final Size
};
EXPECT_EQ(gfl.data_len, 6);
EXPECT_EQ(memcmp(gfl.data, gfl_data, 6), 0);
// test convert bin to frame;
FrameResetStream recv_frame;
FrameType frame_type;
ConvertGFLToFrame(&gfl, &recv_frame, &frame_type);
EXPECT_EQ(frame_type, FrameType::kResetStream);
EXPECT_EQ(recv_frame.stream_id, frame.stream_id);
EXPECT_EQ(recv_frame.error_code, frame.error_code);
EXPECT_EQ(recv_frame.final_size, frame.final_size);
}
| 3,732
|
C++
|
.cc
| 104
| 32.355769
| 79
| 0.678167
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,732
|
test_routine.cc
|
RobertIndie_moss/test/moss_test/test_routine.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#ifndef __MOSS_TEST
#define __MOSS_TEST
#endif
#include "./routine.h"
#include "gtest/gtest.h"
struct TestParam {
std::shared_ptr<moss::AsynRoutine> routine;
int times;
int result;
};
void *func(void *param) {
auto param_ = static_cast<TestParam *>(param);
while (true) {
param_->result++;
param_->routine->Suspend();
}
}
TEST(Routine, Coroutine) {
auto coroutine = std::make_shared<moss::Coroutine>();
TestParam param;
param.routine = coroutine;
param.times = 2;
param.result = 0;
coroutine->Init(func, ¶m);
for (int i = 0; i < param.times; i++) {
coroutine->Resume();
}
EXPECT_EQ(param.result, param.times);
}
| 1,358
|
C++
|
.cc
| 44
| 28.818182
| 74
| 0.719084
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,733
|
test_fsm.cc
|
RobertIndie_moss/test/moss_test/test_fsm.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#include "util/fsm.h"
#include "gtest/gtest.h"
TEST(FSM, FSMTest) {
FSM machine(1);
int status = 0;
machine.When(1, FSM::transition_t(1, 2));
machine.When(1, FSM::transition_t(2, 3));
machine.When(2, FSM::transition_t(3, 1));
machine.On(1, [&status, &machine]() -> int {
status = 1;
machine.Trigger(1);
});
machine.On(2, [&status, &machine]() -> int {
status = 2;
machine.Trigger(1);
});
machine.On(3, [&status, &machine]() -> int {
status = 3;
machine.Trigger(2);
});
EXPECT_EQ(machine.GetState(), 1);
machine.Run();
EXPECT_EQ(machine.GetState(), 2);
EXPECT_EQ(status, 1);
machine.Run();
EXPECT_EQ(status, 2);
EXPECT_EQ(machine.GetState(), 3);
machine.Run();
EXPECT_EQ(status, 3);
EXPECT_EQ(machine.GetState(), 1);
}
| 1,482
|
C++
|
.cc
| 46
| 29.73913
| 74
| 0.68689
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,734
|
test_connection.cc
|
RobertIndie_moss/test/moss_test/test_connection.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#ifndef __MOSS_TEST
#define __MOSS_TEST
#endif
#include "./connection.h"
#include "gtest/gtest.h"
TEST(Connection, NewID) {
std::shared_ptr<moss::Connection> conn(
new moss::Connection(moss::ConnectionType::kClient));
EXPECT_EQ(__Test_NewID(conn, moss::Initializer::kClient,
moss::Directional::kBidirectional),
0);
EXPECT_EQ(__Test_NewID(conn, moss::Initializer::kServer,
moss::Directional::kBidirectional),
5);
EXPECT_EQ(__Test_NewID(conn, moss::Initializer::kClient,
moss::Directional::kUnidirectional),
10);
EXPECT_EQ(__Test_NewID(conn, moss::Initializer::kServer,
moss::Directional::kUnidirectional),
15);
}
void TestCreateStream(std::shared_ptr<moss::Connection> conn,
const moss::ConnectionType& conn_type,
const moss::Directional& direct,
moss::streamID_t expectID) {
auto stream = conn->CreateStream(direct);
EXPECT_EQ(stream->id_, expectID);
EXPECT_EQ(stream->initer_, conn_type);
EXPECT_EQ(stream->direct_, direct);
}
TEST(Connection, CreateStream) {
std::shared_ptr<moss::Connection> cliConn(
new moss::Connection(moss::ConnectionType::kClient));
std::shared_ptr<moss::Connection> svrConn(
new moss::Connection(moss::ConnectionType::kServer));
TestCreateStream(cliConn, moss::ConnectionType::kClient,
moss::Directional::kBidirectional, 0);
TestCreateStream(cliConn, moss::ConnectionType::kClient,
moss::Directional::kUnidirectional, 6);
TestCreateStream(svrConn, moss::ConnectionType::kServer,
moss::Directional::kUnidirectional, 3);
TestCreateStream(svrConn, moss::ConnectionType::kServer,
moss::Directional::kBidirectional, 5);
}
| 2,580
|
C++
|
.cc
| 59
| 36.949153
| 74
| 0.675933
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,735
|
test_P2PConnection.cc
|
RobertIndie_moss/test/testcases/test_P2PConnection.cc
|
/**
* Copyright 2019 Aaron Robert
* */
#include "gtest/gtest.h"
#include "./test.pb.h"
#include "rpc/rpc.h"
TEST(ServerProxy, P2PConnection) {
UDPClientChannel channel;
channel.Connect("127.0.0.1", 9877);
ClientProxy prx(&channel);
moss_test::SimpleMessage req, res;
req.set_header("GET");
req.set_id(1);
req.set_body("Content");
prx.Call("P2PTest", &req, &res);
EXPECT_EQ(res.header(), "GET");
EXPECT_EQ(res.id(), 1);
EXPECT_EQ(res.body(), "Content");
}
| 480
|
C++
|
.cc
| 19
| 22.947368
| 37
| 0.673913
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,736
|
test_ServerProxy.cc
|
RobertIndie_moss/test/testcases/test_ServerProxy.cc
|
/**
* Copyright 2019 Aaron Robert
* */
#include "gtest/gtest.h"
#include "./test.pb.h"
#include "rpc/rpc.h"
class _Fack_ServerChannel : public ServerChannel {
public:
int Bind(std::string ip, unsigned short port) {}
int Serve(void* context, ServeFunc serve_func) {
moss_test::SimpleMessage req;
req.set_header("GET");
req.set_id(12138);
req.set_body("Login");
RequestHeader req_hdr{BKDRHash("TestFunction")};
char* hdr_mem = new char[REQUEST_HEADER_LEN];
memcpy(hdr_mem, &req_hdr, REQUEST_HEADER_LEN);
std::stringstream ss;
std::string req_str;
req.SerializeToString(&req_str);
ss << std::string(hdr_mem, REQUEST_HEADER_LEN) << req_str;
std::string req_str_data = ss.str();
Data* req_data = new Data(req_str_data.c_str(), req_str_data.size());
Data* res_data = serve_func(context, req_data);
std::stringstream r_ss;
r_ss << std::string(res_data->GetBuff(), res_data->len);
moss_test::SimpleMessage res;
res.ParseFromIstream(&r_ss);
EXPECT_EQ(res.header(), "PASS");
EXPECT_EQ(res.id(), 12138);
return 0;
}
};
int serve(std::stringstream* in_data, std::stringstream* out_data) {
moss_test::SimpleMessage req, res;
ConvertStreamToProtoObj(&req, in_data);
EXPECT_EQ(req.header(), "GET");
EXPECT_EQ(req.id(), 12138);
EXPECT_EQ(req.body(), "Login");
res.set_header("PASS");
res.set_id(12138);
ConvertProtoObjToStream(&res, out_data);
return 0;
}
TEST(ServerProxy, FunctionManagement) {
_Fack_ServerChannel fackChannel;
ServerProxy prx(&fackChannel);
prx.Register("TestFunction", serve);
prx.Serve();
}
| 1,618
|
C++
|
.cc
| 50
| 28.92
| 73
| 0.682428
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,737
|
server.cc
|
RobertIndie_moss/benchmark/server/server.cc
|
/**
* Copyright 2019 Aaron Robert
* */
#include "./login.pb.h"
#include "rpc/rpc.h"
Data *handle(void *context, Data *const request) {
Data *response = new Data(1);
return response;
}
int Login(std::stringstream *in_data, std::stringstream *out_data) {
benchmark_test::LoginMessage req;
benchmark_test::LoginResult res;
ConvertStreamToProtoObj(&req, in_data);
if (req.id() == 12138 && req.password() == "123456") {
res.set_code(0);
res.set_error("No Error");
} else {
res.set_code(-1);
res.set_error("Error");
}
ConvertProtoObjToStream(&res, out_data);
return 0;
}
int main(int argc, char **argv) {
google::InitGoogleLogging(argv[0]);
const char *ip = argv[1];
int port = atoi(argv[2]);
if (argc < 3) {
printf(
"Usage:\n"
"example_echosvr [IP] [PORT]\n");
return -1;
}
UDPServerChannel channel;
channel.Bind(ip, port);
ServerProxy prx(&channel);
REG_FUNC(prx, Login);
prx.Serve();
return 0;
}
| 980
|
C++
|
.cc
| 40
| 21.325
| 68
| 0.652081
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,738
|
client.cc
|
RobertIndie_moss/benchmark/client/client.cc
|
/**
* Copyright 2019 Aaron Robert
* */
#define NDEBUG
#include <stdio.h>
#include <vector>
#include "./login.pb.h"
#include "fstream"
#include "rpc/rpc.h"
void proc(int id, std::fstream &fs_err, std::fstream &fs_result, const char *ip,
int port) {
printf("Proc %d started.\n", id);
UDPClientChannel channel;
channel.Connect(ip, port);
ClientProxy prx(&channel);
while (1) {
benchmark_test::LoginMessage req;
benchmark_test::LoginResult res;
req.set_id(12138);
req.set_password("123456");
int ret = prx.Call("Login", &req, &res);
if (ret != -1 && res.code() == 0 && res.error() == "No Error") {
fs_result << id << ":Sent" << std::endl;
} else {
fs_err << id << ":ERROR" << std::endl;
}
}
}
int main(int argc, char *argv[]) {
google::InitGoogleLogging(argv[0]);
std::fstream fs_err("./error.txt");
std::fstream fs_result("./result.txt");
if (!fs_err.is_open()) {
printf("error.txt dose not exist!\n");
return -1;
}
if (!fs_result.is_open()) {
printf("result.txt does not exist!\n");
return -1;
}
const char *ip = argv[1];
int port = atoi(argv[2]);
int task = atoi(argv[3]);
int proccnt = atoi(argv[4]);
if (argc < 5) {
printf(
"Usage:\n"
"example_echosvr [IP] [PORT] [TASK] [PROCESS_COUNT]\n");
return -1;
}
pid_t *pids = new pid_t[proccnt];
bool isParent = false;
int _pcnt = 0;
for (int i = 0; i < proccnt; i++) {
pid_t pid = fork();
if (pid > 0) {
pids[i] = pid;
_pcnt++;
printf("Pushed %d\n", pid);
continue;
} else if (pid < 0) {
printf("Create proc error!\n");
break;
}
proc(i, fs_err, fs_result, ip, port);
}
sleep(10);
for (int i = 0; i < _pcnt; i++) {
int ret = kill(pids[i], SIGKILL);
if (ret == -1) PLOG(ERROR);
}
fs_err.close();
fs_result.close();
delete[] pids;
return 0;
}
| 1,910
|
C++
|
.cc
| 76
| 21.171053
| 80
| 0.573457
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,739
|
connection.cc
|
RobertIndie_moss/src/connection.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#include "./connection.h"
#include "util/util.h"
namespace moss {
void* CoConnection(void* arg) {
auto conn = reinterpret_cast<Connection*>(arg);
while (true) {
// TODO(Connection) : co func
}
}
Connection::Connection(const ConnectionType& type) : type_(type) {
routine_ = std::static_pointer_cast<AsynRoutine>(
std::make_shared<Coroutine>(CoConnection, this));
cmdQueue_ = std::static_pointer_cast<CommandQueue<CmdConnection>>(
std::make_shared<CoCmdQueue<CmdConnection>>(routine_));
}
streamID_t Connection::NewID(const Initializer& initer,
const Directional& direct) {
return ((nextIDPrefix_++) << 2) + (direct << 1) + initer;
}
std::shared_ptr<Stream> moss::Connection::CreateStream(Directional direct) {
auto id = NewID(type_, direct);
std::shared_ptr<Stream> stream =
std::make_shared<Stream>(this, id, type_, direct);
mapStreams_[id] = stream;
return stream;
}
void Connection::PushCommand(std::shared_ptr<CommandBase> cmd) {
auto _cmd = std::static_pointer_cast<CmdConnection>(cmd);
cmdQueue_->PushCmdAndResume(std::static_pointer_cast<CmdConnection>(cmd));
}
void Connection::SendGFL(streamID_t stream_id,
std::shared_ptr<GenericFrameLayout> gfl) {
mapStreamGFL_[stream_id].push(gfl);
}
void Connection::SendData(streamID_t stream_id, int send_count) {}
} // namespace moss
| 2,092
|
C++
|
.cc
| 51
| 37.823529
| 76
| 0.720335
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,740
|
stream.cc
|
RobertIndie_moss/src/stream.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#include "./stream.h"
#include "./util/util.h"
namespace moss {
void* CoSendSide(void* arg) {
auto sendside = reinterpret_cast<SendSide*>(arg);
while (true) {
sendside->ConsumeCmd();
if (sendside->fsm_.Run() == -1) break;
}
}
SendSide::SendSide(Stream* const stream) : stream_(stream) {
fsm_.When(TriggerType::kSendFIN,
FSM::transition_t(State::kSend, State::kDataSent));
fsm_.When(TriggerType::kResetStream,
FSM::transition_t(State::kSend, State::kResetSent));
fsm_.When(TriggerType::kResetStream,
FSM::transition_t(State::kDataSent, State::kResetSent));
fsm_.When(TriggerType::kRecvACKs,
FSM::transition_t(State::kDataSent, State::kDataRecvd));
fsm_.When(TriggerType::kRecvResetACK,
FSM::transition_t(State::kResetSent, State::kResetRecvd));
fsm_.On(State::kSend, std::bind(&SendSide::OnSend, this));
fsm_.On(State::kDataSent, std::bind(&SendSide::OnDataSent, this));
fsm_.On(State::kResetSent, std::bind(&SendSide::OnResetSent, this));
fsm_.On(State::kDataRecvd, std::bind(&SendSide::OnDataRecvd, this));
fsm_.On(State::kResetRecvd, std::bind(&SendSide::OnResetRecvd, this));
fsm_.SetState(State::kSend);
routine_ = std::shared_ptr<AsynRoutine>(
reinterpret_cast<AsynRoutine*>(new Coroutine(CoSendSide, this)));
cmdQueue_ = std::shared_ptr<CommandQueue<CmdSendSide>>(
reinterpret_cast<CommandQueue<CmdSendSide>*>(
new CoCmdQueue<CmdSendSide>(routine_)));
if (!stream->send_buffer_.get())
stream->send_buffer_ = std::make_shared<DataBuffer>();
buffer_reader_ = stream->send_buffer_->NewReader();
reader_for_conn_ = stream->send_buffer_->NewReader(buffer_reader_.get());
routine_->Resume(); // Init
}
void SendSide::SendData(int data_pos, bool final) { // TODO(Delete): 删除
// auto cmd = std::make_shared<CmdSendData>(stream_->id_, &send_buffer_,
// data_pos, final);
// stream_->conn_->PushCommand(std::static_pointer_cast<CommandBase>(cmd));
}
void SendSide::SendDataBlocked(std::streampos data_limit) {
auto gfl = std::make_shared<GenericFrameLayout>();
auto frame = std::make_shared<FrameStreamDataBlocked>();
frame->stream_data_limit = data_limit;
frame->stream_id = stream_->id_;
ConvertFrameToGFL(frame.get(), FrameType::kStreamDataBlocked, gfl.get());
std::shared_ptr<CmdSendGFL> cmd(new CmdSendGFL(stream_->id_, gfl));
stream_->conn_->PushCommand(std::static_pointer_cast<CommandBase>(cmd));
}
int SendSide::OnSend() {
auto read_max = flow_credit_ - used_credit_;
auto read_count = buffer_reader_->Read(read_max);
if (read_count == read_max) { //遇到数据阻塞
SendDataBlocked(flow_credit_);
}
used_credit_ += read_count;
std::shared_ptr<CmdSendData> cmd(new CmdSendData(stream_->id_, read_count));
stream_->conn_->PushCommand(std::static_pointer_cast<CommandBase>(cmd));
// 检查信号
if (CheckSignal(signal_, SignalMask::kBitEndStream)) {
ClearSignal(signal_, SignalMask::kBitEndStream);
fsm_.Trigger(TriggerType::kSendFIN);
}
if (CheckSignal(signal_, SignalMask::kBitResetStream)) {
ClearSignal(signal_, SignalMask::kBitResetStream);
fsm_.Trigger(TriggerType::kResetStream);
}
return 0;
}
int SendSide::OnDataSent() {
if (CheckSignal(signal_, SignalMask::kBitResetStream)) {
ClearSignal(signal_, SignalMask::kBitResetStream);
fsm_.Trigger(TriggerType::kResetStream);
}
return 0;
}
int SendSide::OnResetSent() { return 0; }
int SendSide::OnDataRecvd() { return 0; }
int SendSide::OnResetRecvd() { return 0; }
void SendSide::ConsumeCmd() { auto cmd = cmdQueue_->WaitAndExecuteCmds(this); }
void SendSide::WriteData() {}
void SendSide::EndStream() { AddSignal(signal_, SignalMask::kBitEndStream); }
void SendSide::ResetStream() {
AddSignal(signal_, SignalMask::kBitResetStream);
}
void Stream::WriteData(const char* data, int data_len, bool is_final) {
send_buffer_->Write(data_len, data); // TODO(IO): 将来是在用户线程中写入数据
send_buffer_->SetFinal(is_final);
sendSide_.PushCommand(std::dynamic_pointer_cast<CommandBase>(
std::make_shared<SendSide::CmdWriteData>())); // TODO(Delete): 现在没必要
}
void Stream::EndStream() {
sendSide_.PushCommand(std::dynamic_pointer_cast<CommandBase>(
std::make_shared<SendSide::CmdEndStream>()));
}
void Stream::ResetStream() {
sendSide_.PushCommand(std::dynamic_pointer_cast<CommandBase>(
std::make_shared<SendSide::CmdResetStream>()));
}
} // namespace moss
| 5,244
|
C++
|
.cc
| 118
| 40.694915
| 79
| 0.710266
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,741
|
command.cc
|
RobertIndie_moss/src/command.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#include "./command.h"
#include "./co_routine.h"
| 748
|
C++
|
.cc
| 17
| 42.823529
| 74
| 0.755495
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,742
|
frame.cc
|
RobertIndie_moss/src/frame.cc
|
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#include <arpa/inet.h>
#include "./frame.h"
using uint = unsigned int;
enum Type {
FRS = 0x04,
FSDB = 0x15,
FS = 0x00
};
// 长度信息标志
enum Flags { OEB = 0x00, TWB = 0x01, FOB = 0x02, EIB = 0x03, NON = 0xff };
// 将一个vint 类型写道相应一个数组中,第四个参数为从*location的位置开始写
// 第三个参数指明这一次写多长的数据
inline void WriteVintToBin(const vint &src_data, char *bin_data, int len,
int *location);
// 根据一个数据的长度返回标志,并且将标志位设置到相应的位置
inline uint GetLenAndSetFlag(vint *num);
void AppendStr(const char *const src_str, char *dir_str, int len, int begin);
// FrameStream 转换到 GenericFrameLayout
enum StreamFlags { OFF = 0x04, LEN = 0x02, FIN = 0x01, SAV = 0x08 };
int FSToGFL(const FrameStream *const fs, GenericFrameLayout *gfl) {
int id_len = 0, off_len = 0, len_len = 0, dat_len = 0, total_len = 0;
vint copy_id = fs->id, copy_offset = 0, copy_len = 0;
id_len = GetLenAndSetFlag(©_id);
if (fs->bits & StreamFlags::OFF) {
copy_offset = fs->offset;
off_len = GetLenAndSetFlag(©_offset);
}
if (fs->bits & StreamFlags::LEN) {
copy_len = dat_len = fs->length;
len_len = GetLenAndSetFlag(©_len);
}
// change
total_len = id_len + off_len + len_len + dat_len;
char *total_data = new char[total_len]{0};
if (total_data == nullptr) return -1;
// gfl->frame_type_bits = Type::FS;
gfl->frame_type_bits = fs->bits | 0x08;
gfl->data_len = total_len;
int pos = 0;
// WriteVintToBin(fs->bits, total_data, 1, &pos);
WriteVintToBin(copy_id, total_data, id_len, &pos);
if (off_len) WriteVintToBin(copy_offset, total_data, off_len, &pos);
if (len_len) {
WriteVintToBin(copy_len, total_data, len_len, &pos);
AppendStr(fs->stream_data, total_data, dat_len, pos);
}
gfl->data = total_data;
return 0;
}
// Convert FrameStreamDataBlocked to GenericFrmaeLayout
int FSDBToGFL(const FrameStreamDataBlocked *const fsdb,
GenericFrameLayout *gfl) {
vint copy_id = fsdb->stream_id;
vint copy_stream_data_limit = fsdb->stream_data_limit;
int id_len = GetLenAndSetFlag(©_id);
int sdl_len = GetLenAndSetFlag(©_stream_data_limit);
int total_len = id_len + sdl_len;
char *total_data = new char[total_len]{0};
if (total_data == nullptr) return -1;
gfl->data_len = total_len;
gfl->frame_type_bits = Type::FSDB;
int pos = 0;
WriteVintToBin(copy_id, total_data, id_len, &pos);
WriteVintToBin(copy_stream_data_limit, total_data, sdl_len, &pos);
gfl->data = total_data;
return 0;
}
int FRSToGFL(const FrameResetStream *const fs, GenericFrameLayout *gfl) {
vint copy_id = fs->stream_id;
vint copy_error_code = fs->error_code;
vint copy_final_size = fs->final_size;
int id_len = GetLenAndSetFlag(©_id);
int ec_len = GetLenAndSetFlag(©_error_code);
int fz_len = GetLenAndSetFlag(©_final_size);
int total_len = id_len + ec_len + fz_len;
char *total_data = new char[total_len]{0};
if (total_data == nullptr) return -1;
gfl->frame_type_bits = Type::FRS;
gfl->data_len = total_len;
int pos = 0;
WriteVintToBin(copy_id, total_data, id_len, &pos);
WriteVintToBin(copy_error_code, total_data, ec_len, &pos);
WriteVintToBin(copy_final_size, total_data, fz_len, &(pos));
gfl->data = total_data;
return 0;
}
// 成功转换返回0 失败返回-1
int ConvertFrameToGFL(const void *const frame, const FrameType Frame_type,
GenericFrameLayout *gfl) {
switch (Frame_type) {
case FrameType::kStream:
return FSToGFL(reinterpret_cast<const FrameStream *const>((frame)), gfl);
case FrameType::kStreamDataBlocked:
return FSDBToGFL(
reinterpret_cast<const FrameStreamDataBlocked *const>((frame)), gfl);
case FrameType::kResetStream:
return FRSToGFL(reinterpret_cast<const FrameResetStream *const>((frame)),
gfl);
default:
return -1;
}
return 0;
}
// 获取某一个类型的大小 并且为这个类型设置flag
// 如果传入一个负数,或者超出这个范围那么将返回0
inline uint GetLenAndSetFlag(vint *num) {
if ((*num >= 0 && *num <= 63)) {
*(num) |= Flags::OEB << 6;
return 1;
} else if (*num > 63 && *num <= 16383) {
*(num) |= Flags::TWB << 14;
return 2;
} else if ((*num > 16383 && *num <= 1073741823)) {
*(num) |= Flags::FOB << 30;
return 4;
} else if (*num > 1073741823 && *num <= 4611686018427387903) {
*(num) |= (vint)(Flags::EIB) << 62;
return 8;
}
return 0;
}
// 传入的这个值需要设置好flag 从数组头部开始写值
inline void WriteVintToBin(const vint &src_data, char *bin_data, int len,
int *location) {
for (int i = 0, j = len - 1; i < len; ++i, ++*(location), --j) {
*(bin_data + *(location)) |= (((src_data) >> ((j)*8)) & 0xff);
}
}
// Append string to dir_str in begin
inline void AppendStr(const char *const src_str, char *dir_str, int len,
int begin) {
for (int i = 0; i < len; ++i, ++begin) {
*(dir_str + begin) = *(src_str + i);
}
}
// 删除vint中的标志并且返回这个标志代表的长度
inline void RemoveFlags(vint *vint_data, const uint &flag) {
switch (flag) {
case Flags::OEB:
break;
case Flags::TWB:
*vint_data &= 0x3fff;
break;
case Flags::FOB:
*vint_data &= 0x3fffffff;
break;
case Flags::EIB:
*vint_data &= 0x3fffffffffffffff;
break;
}
}
inline int FlagToLen(const uint &flag) {
switch (flag) {
case Flags::OEB:
return 1;
case Flags::TWB:
return 2;
case Flags::FOB:
return 4;
case Flags::EIB:
return 8;
default:
return 0;
}
return 0;
}
// 从二进制数据中写入*vint数组中 这个函数针对FSDB FRS类型的对象
inline void WriteBinToVint(const char *const src_data, vint **dest_data,
uint num) {
// 一个参数为二进制数据对象,
// 第二参数个是目标数组,
// 第三个参数指明第二个参数拥有几个参数
int location = 0;
for (uint i = 0; i < num; ++i) {
uint8_t tmpFlag = (*(src_data + location) & 0xC0) >> 6;
int len = FlagToLen(tmpFlag);
int begin = location;
location += len; // 此时location指向下一个标志所在的空间
while (len-- > 0) {
*(*(dest_data + i)) |= ((*(src_data + begin) & 0xff) << (len * 8));
++begin;
}
RemoveFlags(*(dest_data + i), tmpFlag);
}
}
int GFLToFRS(const GenericFrameLayout *const gfl, FrameResetStream *frame) {
vint *vint_array[3] = {&(frame->stream_id = 0), &(frame->error_code = 0),
&(frame->final_size = 0)};
WriteBinToVint(gfl->data, vint_array, 3);
return 0;
}
int GFLToFSDB(const GenericFrameLayout *const gfl,
FrameStreamDataBlocked *frame) {
vint *vint_array[2] = {&(frame->stream_id = 0),
&(frame->stream_data_limit = 0)};
WriteBinToVint(gfl->data, vint_array, 2);
return 0;
}
int GFLToFS(const GenericFrameLayout *const gfl, FrameStream *frame) {
int location = 0; // 数据开始的位置 // change
frame->stream_data = nullptr;
// 若没有数据存放的时候不设置为Nullptr那在程序结束的时候会释放一个无效指针
auto readF = [&](vint *dest_data) mutable {
uint8_t tmpFlag = (*(gfl->data + location) & 0xC0) >> 6;
int len = FlagToLen(tmpFlag);
int begin = location;
location += len; // 此时location指向下一个标志所在的空间
while (len-- > 0) {
*(dest_data) |= ((*(gfl->data + begin) & 0xff) << len * 8);
++begin;
}
RemoveFlags(dest_data, tmpFlag);
};
readF(&(frame->id = 0));
// frame->bits = *(gfl->data + 0);
frame->bits = gfl->frame_type_bits;
if (frame->bits & StreamFlags::OFF) {
readF(&(frame->offset = 0));
}
if (frame->bits & StreamFlags::LEN) {
readF(&(frame->length = 0));
frame->stream_data = new char[frame->length]{0};
for (uint i = 0; i < frame->length; ++i) {
(frame->stream_data)[i] = *(gfl->data + location + i);
}
}
return 0;
}
int ConvertGFLToFrame(const GenericFrameLayout *const gfl, void *frame,
FrameType *frameType) {
const int frame_type = gfl->frame_type_bits;
switch (frame_type) {
case Type::FRS:
*frameType = FrameType::kResetStream;
return GFLToFRS(gfl, reinterpret_cast<FrameResetStream *>(frame));
case Type::FSDB:
*frameType = FrameType::kStreamDataBlocked;
return GFLToFSDB(gfl, reinterpret_cast<FrameStreamDataBlocked *>(frame));
default:
if (frame_type >= 0x08 && frame_type <= 0x0f) {
*frameType = FrameType::kStream;
return GFLToFS(gfl, reinterpret_cast<FrameStream *>(frame));
} else {
return -1;
}
}
}
| 9,596
|
C++
|
.cc
| 261
| 30.203065
| 79
| 0.643332
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,743
|
routine.cc
|
RobertIndie_moss/src/routine.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#include "./routine.h"
stShareStack_t *moss::Coroutine::share_stack;
| 767
|
C++
|
.cc
| 17
| 44
| 74
| 0.760695
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,744
|
util.cc
|
RobertIndie_moss/src/util/util.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#include "./util/util.h"
| 722
|
C++
|
.cc
| 16
| 44.0625
| 74
| 0.757447
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,745
|
databuffer.cc
|
RobertIndie_moss/src/util/databuffer.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#include "util/databuffer.h"
#include <math.h>
#include <algorithm>
#include "util/util.h"
#define READ_LOCK(lock) pthread_rwlock_rdlock(&lock);
#define WRITE_LOCK(lock) pthread_rwlock_wrlock(&lock);
#define DEFER_UNLOCK(lock) DEFER(pthread_rwlock_unlock(&lock);)
DPTR& DPTR::operator+=(Index_t offset) {
ptr_ = Move(buffer_, ptr_, offset);
return *this;
}
bool DPTR::operator<(const DPTR& rhs) const {
auto offset = buffer_->cap_size_ - buffer_->writer_pos_ - 1;
return Move(buffer_, ptr_, offset) < Move(buffer_, rhs.ptr_, offset);
}
bool DPTR::operator>(const DPTR& rhs) const { return rhs < *this; }
bool DPTR::operator<=(const DPTR& rhs) const { return !(rhs > *this); }
bool DPTR::operator>=(const DPTR& rhs) const { return !(rhs < *this); }
bool DPTR::operator==(const DPTR& rhs) const { return rhs.ptr_ == this->ptr_; }
bool DPTR::operator!=(const DPTR& rhs) const {
return !(rhs.ptr_ == this->ptr_);
}
Index_t DPTR::Move(const DataBuffer* const buffer, Index_t ptr,
Index_t offset) {
auto result = (static_cast<Index_t>(ptr) + offset) % buffer->cap_size_;
if (result < 0) {
result += buffer->cap_size_;
}
return result;
}
int DataReader::Read(const int count, char* data) {
return buffer_->Read(this, count, data);
}
int DataReader::GetRemainingDataSize() {
uint64_t end_ptr;
if (constraint_ != nullptr) {
end_ptr = constraint_->ptr_;
} else {
end_ptr = buffer_->writer_pos_;
}
auto offset = buffer_->cap_size_ - buffer_->writer_pos_ - 1;
auto maxCount =
DPTR::Move(buffer_, end_ptr, offset) - DPTR::Move(buffer_, ptr_, offset);
return maxCount;
}
DataBuffer::DataBuffer(size_t init_size, bool fixed_size)
: block_size(init_size), fixed_size_(fixed_size), cap_size_(init_size) {
pthread_rwlock_init(&lock_, nullptr);
block_ = std::make_shared<DataBlock>(init_size);
}
DataBuffer::~DataBuffer() {
// for (auto iter = blocks_.begin(); iter != blocks_.end(); ++iter) {
// auto p = *iter;
// if (p != nullptr) delete p;
// }
}
std::shared_ptr<DataReader> DataBuffer::NewReader(
const DataReader* const constraintReader) {
WRITE_LOCK(lock_);
DEFER_UNLOCK(lock_)
auto reader = std::make_shared<DataReader>(this, constraintReader);
readers_.push_back(reader);
return reader;
}
uint64_t DataBuffer::MovePtr(uint64_t ptr, int64_t offset) {
auto result = (static_cast<int64_t>(ptr) + offset) % cap_size_;
if (result < 0) {
result += cap_size_;
}
return result;
}
void DataBuffer::Resize(std::shared_ptr<DataReader> min, Index_t new_cap_size) {
// auto new_block = std::make_shared<DataBlock>(new_cap_size);
std::shared_ptr<DataBlock> new_block(new DataBlock(new_cap_size));
auto start_pos = min->ptr_;
if (writer_pos_ >= start_pos) {
memcpy(new_block->buffer_, block_->buffer_ + start_pos,
writer_pos_ - start_pos);
} else {
memcpy(new_block->buffer_, block_->buffer_ + start_pos,
cap_size_ - start_pos);
memcpy(new_block->buffer_, block_->buffer_, writer_pos_);
}
for (auto iter = readers_.begin(); iter != readers_.end(); iter++) {
DPTR::Move(this, (**iter).ptr_, -start_pos);
}
writer_pos_ = DPTR::Move(this, writer_pos_, -start_pos);
cap_size_ = new_cap_size;
block_ = new_block;
}
int DataBuffer::Read(DataReader* const reader, const int count, char* data) {
READ_LOCK(lock_);
DEFER_UNLOCK(lock_)
// check constraint, set end_ptr
uint64_t end_ptr;
if (reader->constraint_ != nullptr) {
end_ptr = reader->constraint_->ptr_;
} else {
end_ptr = writer_pos_;
}
auto offset = cap_size_ - writer_pos_ - 1;
auto maxCount = DPTR::Move(this, end_ptr, offset) -
DPTR::Move(this, reader->ptr_, offset);
if (count != -1 && maxCount > count) {
end_ptr = MovePtr(reader->ptr_, count);
}
// get data
Index_t read_count;
auto diff = end_ptr - reader->ptr_;
if (diff >= 0) {
// out_data = new char[diff];
if (data != nullptr) memcpy(data, block_->buffer_ + reader->ptr_, diff);
read_count = diff;
} else {
diff += cap_size_;
if (data != nullptr) {
// out_data = new char[diff];
memcpy(data, block_->buffer_ + reader->ptr_, cap_size_ - reader->ptr_);
memcpy(data + cap_size_ - reader->ptr_, block_->buffer_, end_ptr);
}
read_count = cap_size_ - reader->ptr_ + end_ptr;
}
reader->ptr_ = end_ptr;
auto min = *std::max_element(readers_.begin(), readers_.end());
data_size_ = DPTR::Move(this, writer_pos_, offset) -
DPTR::Move(this, min->ptr_, offset);
// resize
#define SCHMIDT_COEFFICIENT (3.0 / 8.0) // 范围为0-1
auto new_cap_size = cap_size_;
while (
data_size_ <
new_cap_size *
SCHMIDT_COEFFICIENT && // 需要使用小于号,当SCHMIDT_COEFFICIENT
// 为1时,则可预留空间
new_cap_size > block_size) { // 施密特触发降低resize灵敏度
new_cap_size /= 2;
}
if (new_cap_size != cap_size_) Resize(min, new_cap_size);
return read_count;
}
int DataBuffer::Write(const int count, const char* data) {
if (is_final_ == true) return 0;
WRITE_LOCK(lock_);
DEFER_UNLOCK(lock_)
auto new_data_size = data_size_ + count;
// resize
if (new_data_size >= cap_size_) {
auto offset = cap_size_ - writer_pos_ - 1;
if (readers_.size() == 0) {
DLOG(ERROR) << "No readers.";
throw "No readers.";
}
auto min = *std::max_element(readers_.begin(), readers_.end());
auto current_cap_size = cap_size_;
while (current_cap_size <= new_data_size) { // 需要预留一字节空间
current_cap_size *= 2;
}
Resize(min, current_cap_size);
}
auto end_ptr = DPTR::Move(this, writer_pos_, count);
auto diff = end_ptr - writer_pos_;
if (diff >= 0) {
memcpy(block_->buffer_ + writer_pos_, data, diff);
} else {
memcpy(block_->buffer_ + writer_pos_, data, cap_size_ - writer_pos_);
memcpy(block_->buffer_, data + cap_size_ - writer_pos_, end_ptr);
}
writer_pos_ = end_ptr;
data_size_ = new_data_size;
return count;
}
| 6,791
|
C++
|
.cc
| 186
| 32.376344
| 80
| 0.644636
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,746
|
fsm.cc
|
RobertIndie_moss/src/util/fsm.cc
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#include "util/fsm.h"
#include <sstream>
#include "util/util.h"
void FSM::When(const trigger_t& trigger, const transition_t& transition) {
auto trigger_map = triggers[trigger];
auto trans_ele = trigger_map.find(transition.first);
if (trans_ele != trigger_map.end()) {
PLOG(FATAL) << "[FSM]State transition conflict. ";
}
triggers[trigger].insert(transition);
}
void FSM::On(const state_t& state, const std::function<int()>& on_func) {
state_events[state] = on_func;
}
void FSM::Trigger(const trigger_t& trigger) {
auto trigger_ele = triggers.find(trigger);
if (trigger_ele == triggers.end()) {
PLOG(FATAL) << "[FSM]Cannot find trigger:" << trigger;
}
auto trigger_map = trigger_ele->second;
auto trans_ele = trigger_map.find(state_);
if (trans_ele == trigger_map.end()) {
PLOG(FATAL) << "[FSM]Cannot find transition. " << LOG_VALUE(state_)
<< LOG_VALUE(trigger);
}
state_ = trans_ele->second;
}
int FSM::Run() const {
auto ele = state_events.find(state_);
if (ele != state_events.end()) {
return ele->second();
}
}
| 1,782
|
C++
|
.cc
| 48
| 34.645833
| 74
| 0.702718
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,747
|
common.cc
|
RobertIndie_moss/src/common/common.cc
|
/**
* Copyright 2019 Aaron Robert
* */
#include "common/common.h"
#pragma region RTTInfo
void RTTInfo::Init() {
this->time_base = GetTimestamp();
this->rtt = 0;
this->srtt = 0;
this->rttvar = 50;
this->rto = this->GetRTO();
}
void RTTInfo::NewPack() { this->retransmitted_count = 0; }
float RTTInfo::GetRTO() {
float rto = this->srtt + (4.0 * this->rttvar);
if (rto < kRXTMin)
rto = kRXTMin;
else if (rto > kRXTMax)
rto = kRXTMax;
return rto;
}
template <typename TimeType>
TimeType RTTInfo::GetRelativeTs() {
int64_t ts = GetTimestamp();
return static_cast<TimeType>(ts - this->time_base);
}
template <typename TimeType>
TimeType RTTInfo::Start() {
return static_cast<TimeType>(
this->rto + 0.5); // if TimeType is integer, round float to integer
}
int RTTInfo::Timeout() {
this->rto *= 2;
if (++this->retransmitted_count > kRXTMaxTimes) {
return -1; // give up sending this packet
}
return 0;
}
template <typename TimeType>
void RTTInfo::Stop(TimeType rtt) {
this->rtt = rtt;
double delta = this->rtt - this->srtt;
this->srtt += delta / 8;
if (delta < 0.0) delta = -delta;
this->rttvar += (delta - this->rttvar) / 4;
this->rto = this->GetRTO();
}
#pragma endregion
#pragma region PacketBuilder
PacketBuilder::PacketBuilder(sockaddr_in *sa) {
this->result = new msghdr;
this->result->msg_control = NULL;
this->result->msg_controllen = 0;
this->result->msg_flags = 0;
if (sa != nullptr) {
this->result->msg_name = sa;
this->result->msg_namelen = sizeof(*sa);
} else {
sockaddr_in *new_sa = new sockaddr_in;
_new_sa = new_sa;
this->result->msg_name = new_sa;
this->result->msg_namelen = sizeof(*new_sa);
}
#define IOV_LEN 2
iovec *iov = new iovec[IOV_LEN];
_iov = iov; // for memory release
this->result->msg_iov = iov;
this->result->msg_iovlen = IOV_LEN;
}
Header *PacketBuilder::MakeHeader(uint32_t seq, uint32_t ts) {
Header *hdr = new Header;
_header = hdr;
hdr->seq = seq;
hdr->ts = ts;
result->msg_iov[0].iov_base = hdr;
result->msg_iov[0].iov_len = sizeof(*hdr);
return hdr;
}
Data *PacketBuilder::MakeData(char *buff, size_t buff_size) {
Data *data;
if (buff != nullptr)
data = new Data(buff, buff_size);
else
data = new Data(buff_size);
_data = data;
result->msg_iov[1].iov_base = data->buff;
result->msg_iov[1].iov_len = data->len;
return data;
}
Data *const PacketBuilder::MakeData(Data *const data) {
result->msg_iov[1].iov_base = const_cast<char *>(data->GetBuff());
result->msg_iov[1].iov_len = data->len;
return data;
}
msghdr *const PacketBuilder::GetResult() const { return result; }
Data *const PacketBuilder::GetData() const { return _data; }
PacketBuilder::~PacketBuilder() {
DELETE_PTR(_new_sa);
DELETE_PTR(_iov);
DELETE_PTR(_header);
DELETE_PTR(_data);
DELETE_PTR(result);
}
#pragma endregion
#pragma region UDPChannel
void UDPChannel::SocketConnect(std::string ip, unsigned short port) {
int ret = 0;
LOG(INFO) << "Socket Connect: IP:" << ip << "\tPort:" << port;
ret = socket(AF_INET, SOCK_DGRAM, 0);
if (ret == -1) PLOG(ERROR);
this->socket_fd_ = ret;
this->sa_->sin_family = AF_INET;
// store this IP address in sa:
inet_pton(AF_INET, ip.c_str(), &(this->sa_->sin_addr));
this->sa_->sin_port = htons(port);
}
void UDPChannel::SocketBind() {
int ret = 0;
ret = bind(this->socket_fd_, reinterpret_cast<sockaddr *>(this->sa_),
sizeof(*this->sa_));
if (ret < 0) PLOG(FATAL);
}
#pragma endregion
#pragma region UDPClientChannel
int UDPClientChannel::Connect(std::string ip, unsigned short port) {
this->SocketConnect(ip, port);
}
int UDPClientChannel::Send(Data *in_data, Data *out_data) {
timespec ts_start, ts_end;
clock_gettime(CLOCK_MONOTONIC, &ts_start);
int ret = 0;
if (this->reinit_rtt) {
this->rtt_info_.Init();
}
msghdr *msgsend, *msgrecv;
Header *sendhdr, *recvhdr;
PacketBuilder pbsend(this->sa_);
sendhdr = pbsend.MakeHeader();
pbsend.MakeData(in_data);
msgsend = pbsend.GetResult();
PacketBuilder pbrecv(nullptr);
recvhdr = pbrecv.MakeHeader();
pbrecv.MakeData(out_data);
msgrecv = pbrecv.GetResult();
this->rtt_info_.NewPack();
ssize_t recvSize = 0;
bool isSendAgain = true;
sendhdr->seq = this->seq_++;
do {
isSendAgain = false;
sendhdr->ts = this->rtt_info_.GetRelativeTs();
ret = sendmsg(this->socket_fd_, msgsend, 0);
if (ret == -1) PLOG(ERROR);
int waitTime = this->rtt_info_.Start();
DLOG(INFO) << "Client send:" << LOG_VALUE(sendhdr->seq)
<< LOG_VALUE(in_data->len) << LOG_VALUE(waitTime);
bool isContinueWait = false;
do {
isContinueWait = false;
if (ReadableTimeout(this->socket_fd_, waitTime) == 0) {
DLOG(INFO) << "Timeout:" << LOG_VALUE(sendhdr->seq)
<< LOG_VALUE(this->rtt_info_.retransmitted_count);
// timeout
if (this->rtt_info_.Timeout() < 0) {
DLOG(ERROR) << "Send error.";
this->reinit_rtt =
true; // reinit rtt_info in case we're called again
return -1; // send error
}
isSendAgain = true;
} else {
recvSize = recvmsg(this->socket_fd_, msgrecv, 0);
if (recvSize == -1) PLOG(ERROR);
if (recvSize < sizeof(Header) || recvhdr->seq != sendhdr->seq
/*|| memcmp(msgrecv->msg_name, msgsend->msg_name, 8) != 0*/) {
DLOG(ERROR) << "Receive packet error:" << LOG_VALUE(recvSize)
<< LOG_VALUE(sizeof(Header)) << LOG_VALUE(recvhdr->seq)
<< LOG_VALUE(sendhdr->seq)
<< LOG_NV("msgrecv->msgname",
inet_ntoa(reinterpret_cast<sockaddr_in *>(
msgrecv->msg_name)
->sin_addr))
<< LOG_NV("msgsend->msg_name",
inet_ntoa(reinterpret_cast<sockaddr_in *>(
msgsend->msg_name)
->sin_addr));
waitTime -= this->rtt_info_.GetRelativeTs();
if (waitTime < 0) break;
isContinueWait = true;
}
}
} while (isContinueWait);
} while (isSendAgain);
clock_gettime(CLOCK_MONOTONIC, &ts_end);
// Send and recv packet success
DLOG(INFO) << "Send success:" << LOG_VALUE(sendhdr->seq)
<< LOG_NV("delta_tv_msec",
(ts_end.tv_sec - ts_start.tv_sec) * 1000 +
(ts_end.tv_nsec - ts_start.tv_nsec) / 1000000);
this->rtt_info_.Stop(this->rtt_info_.GetRelativeTs() - recvhdr->ts);
out_data->len = recvSize - sizeof(Header);
return (recvSize - sizeof(Header));
}
#pragma endregion
#pragma region UDPServerChannel
int UDPServerChannel::Bind(std::string ip, unsigned short port) {
this->SocketConnect(ip, port);
this->SocketBind();
}
int UDPServerChannel::Serve(void *context, ServeFunc serve_func) {
if (serve_func == nullptr) LOG(FATAL) << "serve_func is null";
int ret = 0;
while (1) {
PacketBuilder pbrecv(nullptr);
Header *recvhdr = pbrecv.MakeHeader();
pbrecv.MakeData(nullptr, 1452);
msghdr *msgrecv = pbrecv.GetResult();
ssize_t recvSize = recvmsg(this->socket_fd_, msgrecv, 0);
if (recvSize == -1) PLOG(ERROR);
PacketBuilder pbsend(reinterpret_cast<sockaddr_in *>(msgrecv->msg_name));
pbsend.MakeHeader(recvhdr->seq, recvhdr->ts);
DLOG(INFO)
<< "Server recv:"
<< LOG_NV("origin_ip:",
inet_ntoa(reinterpret_cast<sockaddr_in *>(msgrecv->msg_name)
->sin_addr))
<< LOG_NV("origin_port",
ntohs(reinterpret_cast<sockaddr_in *>(msgrecv->msg_name)
->sin_port))
<< LOG_VALUE(recvSize) << LOG_NV("seq", recvhdr->seq);
Data *response = serve_func(context, pbrecv.GetData());
pbsend.MakeData(response);
msghdr *msgsend = pbsend.GetResult();
ret = sendmsg(this->socket_fd_, msgsend, 0);
DLOG(INFO) << "Sent";
if (ret == -1) PLOG(ERROR);
DELETE_PTR(response);
}
}
#pragma endregion
#pragma region Factories
ServerChannel *UDPChannelFactory::CreateServerChannel(std::string ip,
unsigned int port) {
ServerChannel *sc = new UDPServerChannel;
sc->Bind(ip, port);
return sc;
}
ClientChannel *UDPChannelFactory::CreateClientChannel(std::string ip,
unsigned int port) {
UDPClientChannel *cc = new UDPClientChannel;
cc->Connect(ip, port);
return cc;
}
#pragma endregion
| 8,736
|
C++
|
.cc
| 254
| 28.377953
| 78
| 0.611453
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,748
|
rpc.cc
|
RobertIndie_moss/src/rpc/rpc.cc
|
/**
* Copyright 2019 Aaron Robert
* */
#include "rpc/rpc.h"
#pragma region ClientProxy
#pragma endregion
#pragma region ServerProxy
Data* ServeHandle(void* context, Data* const request) {
ServerProxy* prx = reinterpret_cast<ServerProxy*>(context);
std::stringstream ss_req, ss_res;
const char* req_buff = request->GetBuff();
for (int i = 0; i < request->len; i++) {
ss_req << req_buff[i];
}
RequestHeader req_hdr;
char req_hdr_mem[REQUEST_HEADER_LEN];
ss_req.read(req_hdr_mem, REQUEST_HEADER_LEN);
memcpy(&req_hdr, req_hdr_mem, REQUEST_HEADER_LEN);
DLOG(INFO) << "Call Function" << LOG_VALUE(req_hdr.func_name);
auto func = prx->func_map.find(req_hdr.func_name);
if (func != prx->func_map.end()) {
func->second(&ss_req, &ss_res);
} else {
DLOG(ERROR) << "Could not find function:" << LOG_VALUE(req_hdr.func_name);
return new Data(0); // TODO(Exception): need throw expection
}
std::string response_str = ss_res.str();
DLOG(INFO) << "Call Function Result:" << LOG_VALUE(req_hdr.func_name)
<< LOG_VALUE(response_str.length());
Data* response_data = new Data(response_str.c_str(), response_str.length());
return response_data;
}
int ServerProxy::Register(std::string func_name, ServeFuncType serve_func) {
this->func_map[BKDRHash(func_name.c_str())] = serve_func;
return 0;
}
void ServerProxy::Serve() { this->channel_->Serve(this, ServeHandle); }
#pragma endregion
| 1,440
|
C++
|
.cc
| 38
| 34.894737
| 78
| 0.687187
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,749
|
Timer.h
|
RobertIndie_moss/example/Chat/timer/Timer.h
|
#pragma once
#include <pthread.h>
#include <sys/time.h>
#include <sys/select.h>
class Run {
public:
void start()
{
this->CorePro();
}
private:
virtual void CorePro() = 0;
};
class Timer
{
static void* TimerCore(void* obejct_self);
public:
Timer(Run * instance);
Timer(Run * insatance ,const long& second,const long& u_second=0);
virtual ~Timer();
public:
void SetTime(const long& second,const long& u_second=0);
void Start();
void Stop();
private:
void ProThread();
private:
long m_second;
long m_u_second;
private:
Run* exec;
private:
//Ïß³ÌID
pthread_t TimerThread;
};
| 634
|
C++
|
.h
| 35
| 15.314286
| 68
| 0.682968
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,750
|
Client.h
|
RobertIndie_moss/example/Chat/Client/Client.h
|
#pragma once
#include "moss/src/common/common.h"
#include <iostream>
#include <string>
enum CONST_ { RecvBuff = 1024, SEN = 5 };
class Client {
public:
Client(const std::string& name = "User00",
const std::string& ServerIP = "47.94.89.84",
const unsigned short& ServePort = 9421);
~Client();
public:
void run();
private:
void core();
void SelfControlSend(const std::string& DirID);
void autoRequest();
Data* Packag(const std::string& str);
private:
ssize_t SendAndRecv();
private:
UDPClientChannel channel;
//服务器的信息
private:
std::string ServerAddress;
unsigned short ServerPort;
private:
std::string UserID;
private:
Data* recv_data = nullptr;
Data* send_data = nullptr;
};
| 763
|
C++
|
.h
| 32
| 20.0625
| 49
| 0.708514
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,751
|
ProRequest.h
|
RobertIndie_moss/example/Chat/server/ProRequest.h
|
#pragma once
#include "Server.h"
class ProRequest {
friend Data* fun(Data* const);
public:
ProRequest() = default;
virtual ~ProRequest() {}
public:
//协助mHandle的一些函数
protected:
//解析请求
int Analysis(const std::string& request);
Data* MakeErrorData();
Data* MakeRespoData(const std::string& name);
Data* MakeSucData();
protected:
std::vector<std::string> ID_List;
std::vector<std::string> Context_List;
};
| 458
|
C++
|
.h
| 19
| 20.157895
| 47
| 0.716019
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,752
|
Str.h
|
RobertIndie_moss/example/Chat/server/Str.h
|
#pragma once
#include <iostream>
#include <vector>
#include <string>
std::vector<std::string*> SpiltStr(const std::string& TotalStr, const char& spiltChar);
bool MatchStr(const std::string& Match_Str, const std::string& Source_Str);
int SerchID(const std::vector<std::string> str, const std::string& ID);
| 317
|
C++
|
.h
| 7
| 42.714286
| 89
| 0.738562
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,753
|
Server.h
|
RobertIndie_moss/example/Chat/server/Server.h
|
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include "moss/src/common/common.h"
#include "Str.h"
using HandleFUN = Data* (*)(Data*const);
extern HandlFUN fun;
enum ERRORCODE { ErrData = -1, SucData, Respond };
class Server {
public:
explicit Server(const unsigned short& port);
virtual ~Server() {}
public:
void Run(HandleFUN fun);
//处理接受的请求的函数
private:
ProRequest* Handle = nullptr;
private:
UDPServerChannel Channel;
};
| 509
|
C++
|
.h
| 21
| 20.333333
| 51
| 0.72467
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,754
|
Client.h
|
RobertIndie_moss/example/HeartChat/Client/Client.h
|
#pragma once
#include "moss/src/common/common.h"
#include <iostream>
#include <string>
#include "timer/Timer.h"
#include "common/common.h"
enum CONST_ { RecvBuff = 1024, SEN = 5 };
class Client {
friend class TimerSend;
public:
Client(const std::string& name = "User00",
const std::string& ServerIP = "47.94.89.84",
const unsigned short& ServePort = 9421);
~Client();
public:
void run();
private:
void core();
void SelfControlSend(const std::string& DirID);
void autoRequest();
Data* Packag(const std::string& str);
private:
ssize_t SendAndRecv();
private:
UDPClientChannel channel;
//服务器的信息
private:
std::string ServerAddress;
unsigned short ServerPort;
private:
std::string UserID;
private:
Data* recv_data = nullptr;
Data* send_data = nullptr;
};
| 843
|
C++
|
.h
| 35
| 20.428571
| 49
| 0.712987
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,755
|
stream.h
|
RobertIndie_moss/src/stream.h
|
//
// Copyright (C) 2019 Linkworld Open Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https: //www.gnu.org/licenses/>.
#ifndef STREAM_H_
#define STREAM_H_
#include <memory>
#include <queue>
#include <sstream>
#include "./co_routine.h"
#include "./command.h"
#include "./frame.h"
#include "./interfaces.h"
#include "./util/databuffer.h"
#include "./util/fsm.h"
namespace moss {
class StreamSide {
public:
StreamSide() : fsm_(0) {}
protected:
FSM fsm_;
};
class Stream;
class SendSide;
class SendSide : public StreamSide, public CommandExecutor {
public:
struct CmdSendSide : public CommandBase {
int Execute(void* const arg) {
auto sendSide = static_cast<SendSide* const>(arg);
return Call(sendSide);
}
protected:
virtual int Call(SendSide* const sendSide) = 0;
};
struct CmdWriteData : public CmdSendSide {
public:
std::size_t GetHash() const { return typeid(this).hash_code(); }
explicit CmdWriteData() {}
private:
int Call(SendSide* const sendSide) { sendSide->WriteData(); }
};
struct CmdEndStream : public CmdSendSide {
public:
std::size_t GetHash() const { return typeid(this).hash_code(); }
CmdEndStream() {}
private:
int Call(SendSide* const sendSide) { sendSide->EndStream(); }
};
struct CmdResetStream : public CmdSendSide {
public:
std::size_t GetHash() const { return typeid(this).hash_code(); }
CmdResetStream() {}
private:
int Call(SendSide* const sendSide) { sendSide->ResetStream(); }
};
// O
// +
// | Create Stream
// |
// Send STREAM/ v
// STREAM_DATA_BLOCKED +-------+ Send RESET_STREAM
// +----------->+ Send +-----------------------+
// | | | |
// +------------+-------+ |
// | |
// | Send STREAM+FIN |
// v v
// +-------+ Send RESET_STREAM+-------+
// | Data +------------------>+ Reset |
// | Sent | | Sent |
// +-------+ +-------+
// | |
// | Recv All ACKs | Recv ACK
// v v
// +-------+ +-------+
// | Data | | Reset |
// | Recvd | | Recvd |
// +-------+ +-------+
enum State : state_t {
kSend,
kDataSent,
kResetSent,
kDataRecvd,
kResetRecvd,
};
enum TriggerType : trigger_t {
kResetStream, // Reset stream
kSendFIN, // Send Finish : Send -> Data Sent
kRecvACKs, // Recv All ACKs : Data Sent -> Data Recvd
kRecvResetACK, // Recv Reset ACK : Reset Sent -> Reset Recvd
};
explicit SendSide(Stream* const stream);
void PushCommand(std::shared_ptr<CommandBase> cmd) {
cmdQueue_->PushCmdAndResume(std::dynamic_pointer_cast<CmdSendSide>(cmd));
}
#ifdef __MOSS_TEST
public:
#else
private:
#endif
struct SignalMask {
enum Value { kBitEndStream, kBitResetStream };
};
Stream* const stream_;
std::shared_ptr<AsynRoutine> routine_;
std::shared_ptr<CommandQueue<CmdSendSide>> cmdQueue_;
// readers
std::shared_ptr<DataReader> buffer_reader_;
std::shared_ptr<DataReader> reader_for_conn_;
unsigned int flow_credit_ = 1500;
unsigned int used_credit_ = 0;
std::stringstream send_buffer_; // 将被替换为DataBuffer
std::shared_ptr<DataBuffer> buffer_;
unsigned char signal_;
inline std::streampos GetSendBufferLen() {
return send_buffer_.tellp() - send_buffer_.tellg();
}
void SendData(int data_pos, bool final = false);
void SendDataBlocked(std::streampos data_limit);
int OnSend();
int OnDataSent();
int OnResetSent();
int OnDataRecvd();
int OnResetRecvd();
void ConsumeCmd();
void WriteData();
void EndStream();
void ResetStream();
friend void* CoSendSide(void* arg);
};
class Stream {
public:
enum RecvSideState {
kRecv,
kSizeKnown,
kDataRecvd,
kResetRecvd,
kDataRead,
kResetRead
};
streamID_t id_;
CommandExecutor* const conn_;
std::shared_ptr<DataBuffer>
send_buffer_; // 使用方需自行判断是否初始化send_buffer_
SendSide sendSide_;
SendSide recvSide_;
Stream(CommandExecutor* const conn, streamID_t id, Initializer initer,
Directional direct)
: conn_(conn),
id_(id),
initer_(initer),
direct_(direct),
sendSide_(this),
recvSide_(this) {}
// TODO(Multi-thread): just for test
void WriteData(const char* data, int data_len, bool is_final = false);
void EndStream();
void ResetStream();
// ====
#ifdef __MOSS_TEST
public:
#else
private:
#endif
Initializer initer_;
Directional direct_;
};
} // namespace moss
#endif // STREAM_H_
| 6,115
|
C++
|
.h
| 180
| 29.35
| 78
| 0.541289
|
RobertIndie/moss
| 37
| 6
| 3
|
GPL-3.0
|
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.