Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: colored text #580

Merged
merged 3 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,13 @@
- Discord RPC by [@SkullzOTS](https://github.com/SkullzOTS)
- To enable just go to [config.h](https://github.com/mehah/otclient/blob/main/src/client/config.h), set 1 in ENABLE_DISCORD_RPC and configure the others definitions
- You can see the step by step in [YouTube](https://www.youtube.com/watch?v=zCHYtRlD58g)

- Client Updater by [@conde2](https://github.com/conde2)
- Paste the API folder in your www folder (https://github.com/mehah/otclient/tree/main/tools/api)
- Create a folder called "files" in your www folder and paste init.lua, modules, data, and exe files
- Uncomment and change this line (https://github.com/mehah/otclient/blob/main/init.lua#L6)
- Colored text [@conde2](https://github.com/conde2)
- ex: widget:setColoredText("{Colored text, #ff00ff} normal text")

##### [OTClient V8](https://github.com/OTCv8) (Features)
- Lighting System
- Floor Fading
Expand Down
125 changes: 123 additions & 2 deletions src/framework/graphics/bitmapfont.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,111 @@ void BitmapFont::fillTextCoords(const CoordsBufferPtr& coords, const std::string
}
}

void BitmapFont::fillTextColorCoords(std::vector<std::pair<Color, CoordsBufferPtr>>& colorCoords, const std::string_view text,
const std::vector<std::pair<int, Color>> textColors,
const Size& textBoxSize, Fw::AlignmentFlag align,
const Rect& screenCoords, const std::vector<Point>& glyphsPositions) const
{
colorCoords.clear();

// prevent glitches from invalid rects
if (!screenCoords.isValid() || !m_texture)
return;

const int textLenght = text.length();
const int textColorsSize = textColors.size();

std::map<uint32_t, CoordsBufferPtr> colorCoordsMap;
uint32_t curColorRgba;
int32_t nextColorIndex = 0;
int32_t colorIndex = -1;
CoordsBufferPtr coords;
for (int i = 0; i < textLenght; ++i) {
if (i >= nextColorIndex) {
colorIndex = colorIndex + 1;
if (colorIndex < textColorsSize) {
curColorRgba = textColors[colorIndex].second.rgba();
}
if (colorIndex + 1 < textColorsSize) {
nextColorIndex = textColors[colorIndex + 1].first;
} else {
nextColorIndex = textLenght;
}

if (colorCoordsMap.find(curColorRgba) == colorCoordsMap.end()) {
colorCoordsMap.insert(std::make_pair(curColorRgba, std::make_shared<CoordsBuffer>()));
}

coords = colorCoordsMap[curColorRgba];
}

const int glyph = static_cast<uint8_t>(text[i]);

// skip invalid glyphs
if (glyph < 32)
continue;

// calculate initial glyph rect and texture coords
Rect glyphScreenCoords(glyphsPositions[i], m_glyphsSize[glyph]);
Rect glyphTextureCoords = m_glyphsTextureCoords[glyph];

// first translate to align position
if (align & Fw::AlignBottom) {
glyphScreenCoords.translate(0, screenCoords.height() - textBoxSize.height());
} else if (align & Fw::AlignVerticalCenter) {
glyphScreenCoords.translate(0, (screenCoords.height() - textBoxSize.height()) / 2);
} else { // AlignTop
// nothing to do
}

if (align & Fw::AlignRight) {
glyphScreenCoords.translate(screenCoords.width() - textBoxSize.width(), 0);
} else if (align & Fw::AlignHorizontalCenter) {
glyphScreenCoords.translate((screenCoords.width() - textBoxSize.width()) / 2, 0);
} else { // AlignLeft
// nothing to do
}

// only render glyphs that are after 0, 0
if (glyphScreenCoords.bottom() < 0 || glyphScreenCoords.right() < 0)
continue;

// bound glyph topLeft to 0,0 if needed
if (glyphScreenCoords.top() < 0) {
glyphTextureCoords.setTop(glyphTextureCoords.top() - glyphScreenCoords.top());
glyphScreenCoords.setTop(0);
}
if (glyphScreenCoords.left() < 0) {
glyphTextureCoords.setLeft(glyphTextureCoords.left() - glyphScreenCoords.left());
glyphScreenCoords.setLeft(0);
}

// translate rect to screen coords
glyphScreenCoords.translate(screenCoords.topLeft());

// only render if glyph rect is visible on screenCoords
if (!screenCoords.intersects(glyphScreenCoords))
continue;

// bound glyph bottomRight to screenCoords bottomRight
if (glyphScreenCoords.bottom() > screenCoords.bottom()) {
glyphTextureCoords.setBottom(glyphTextureCoords.bottom() + (screenCoords.bottom() - glyphScreenCoords.bottom()));
glyphScreenCoords.setBottom(screenCoords.bottom());
}
if (glyphScreenCoords.right() > screenCoords.right()) {
glyphTextureCoords.setRight(glyphTextureCoords.right() + (screenCoords.right() - glyphScreenCoords.right()));
glyphScreenCoords.setRight(screenCoords.right());
}

// add glyph to color
coords->addRect(glyphScreenCoords, glyphTextureCoords);
}

for (auto& [rgba, coords] : colorCoordsMap) {
colorCoords.emplace_back(Color(rgba), coords);
}
}

const std::vector<Point>& BitmapFont::calculateGlyphsPositions(const std::string_view text, Fw::AlignmentFlag align, Size* textBoxSize) const
{
const int textLength = text.length();
Expand Down Expand Up @@ -371,7 +476,7 @@ void BitmapFont::calculateGlyphsWidthsAutomatically(const ImagePtr& image, const
}
}

std::string BitmapFont::wrapText(const std::string_view text, int maxWidth)
std::string BitmapFont::wrapText(const std::string_view text, int maxWidth, std::vector<std::pair<int, Color>>* colors)
{
if (text.empty())
return "";
Expand All @@ -380,6 +485,7 @@ std::string BitmapFont::wrapText(const std::string_view text, int maxWidth)
std::vector<std::string> words;
const std::vector<std::string> wordsSplit = stdext::split(text);

auto currentSize = 0;
// break huge words into small ones
for (const auto& word : wordsSplit) {
const int wordWidth = calculateTextRectSize(word).width();
Expand All @@ -394,15 +500,20 @@ std::string BitmapFont::wrapText(const std::string_view text, int maxWidth)
if (candidateWidth > maxWidth) {
newWord += '-';
words.push_back(newWord);
currentSize += newWord.size() + 2; // each word break adds 2 characters: '-' and '\n'
newWord.clear();

updateColors(colors, currentSize - 2, 2);
}

newWord += word[j];
}

words.push_back(newWord);
currentSize += newWord.size() + 1;
} else {
words.push_back(word);
currentSize += word.size() + 1;
}
}

Expand All @@ -425,4 +536,14 @@ std::string BitmapFont::wrapText(const std::string_view text, int maxWidth)
outText.append(line);

return outText;
}
}

void BitmapFont::updateColors(std::vector<std::pair<int, Color>>* colors, int pos, int newTextLen)
{
if (!colors) return;
for (auto& it : *colors) {
if (it.first > pos) {
it.first += newTextLen;
}
}
}
9 changes: 8 additions & 1 deletion src/framework/graphics/bitmapfont.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ class BitmapFont
const Size& textBoxSize, Fw::AlignmentFlag align,
const Rect& screenCoords, const std::vector<Point>& glyphsPositions) const;

void fillTextColorCoords(std::vector<std::pair<Color, CoordsBufferPtr>>& colorCoords, const std::string_view text,
const std::vector<std::pair<int, Color>> textColors,
const Size& textBoxSize, Fw::AlignmentFlag align,
const Rect& screenCoords, const std::vector<Point>& glyphsPositions) const;


/// Calculate glyphs positions to use on render, also calculates textBoxSize if wanted
const std::vector<Point>& calculateGlyphsPositions(const std::string_view text,
Fw::AlignmentFlag align,
Expand All @@ -60,7 +66,7 @@ class BitmapFont
/// Simulate render and calculate text size
Size calculateTextRectSize(const std::string_view text);

std::string wrapText(const std::string_view text, int maxWidth);
std::string wrapText(const std::string_view text, int maxWidth, std::vector<std::pair<int, Color>>* colors = nullptr);

const std::string& getName() { return m_name; }
int getGlyphHeight() const { return m_glyphHeight; }
Expand All @@ -73,6 +79,7 @@ class BitmapFont
private:
/// Calculates each font character by inspecting font bitmap
void calculateGlyphsWidthsAutomatically(const ImagePtr& image, const Size& glyphSize);
void updateColors(std::vector<std::pair<int, Color>>* colors, int pos, int newTextLen);

std::string m_name;
int m_glyphHeight{ 0 };
Expand Down
1 change: 1 addition & 0 deletions src/framework/luafunctions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,7 @@ void Application::registerLuaFunctions()
g_lua.bindClassMemberFunction<UIWidget>("resizeToText", &UIWidget::resizeToText);
g_lua.bindClassMemberFunction<UIWidget>("clearText", &UIWidget::clearText);
g_lua.bindClassMemberFunction<UIWidget>("setText", &UIWidget::setText);
g_lua.bindClassMemberFunction<UIWidget>("setColoredText", &UIWidget::setColoredText);
g_lua.bindClassMemberFunction<UIWidget>("setTextAlign", &UIWidget::setTextAlign);
g_lua.bindClassMemberFunction<UIWidget>("setTextOffset", &UIWidget::setTextOffset);
g_lua.bindClassMemberFunction<UIWidget>("setTextWrap", &UIWidget::setTextWrap);
Expand Down
4 changes: 4 additions & 0 deletions src/framework/ui/uiwidget.h
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,7 @@ class UIWidget : public LuaObject
std::vector<Point> m_glyphsPositionsCache;
Size m_textSize;
CoordsBufferPtr m_coordsBuffer;
std::vector<std::pair<Color, CoordsBufferPtr>> m_colorCoordsBuffer;

protected:
virtual void updateText();
Expand All @@ -539,6 +540,8 @@ class UIWidget : public LuaObject
Point m_textOffset;

BitmapFontPtr m_font;
std::vector<std::pair<int, Color>> m_textColors;
std::vector<std::pair<int, Color>> m_drawTextColors;

float m_fontScale{ 1.f };

Expand All @@ -547,6 +550,7 @@ class UIWidget : public LuaObject
void clearText() { setText(""); }

void setText(const std::string_view text, bool dontFireLuaCall = false);
void setColoredText(const std::string_view coloredText, bool dontFireLuaCall = false);
void setTextAlign(Fw::AlignmentFlag align) { m_textAlign = align; updateText(); }
void setTextOffset(const Point& offset) { m_textOffset = offset; updateText(); }
void setTextWrap(bool textWrap) { setProp(PropTextWrap, textWrap); updateText(); }
Expand Down
75 changes: 70 additions & 5 deletions src/framework/ui/uiwidgettext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <framework/graphics/drawpoolmanager.h>
#include <framework/graphics/fontmanager.h>
#include <client/gameconfig.h>
#include <regex>
#include "uitranslator.h"
#include "uiwidget.h"

Expand All @@ -36,10 +37,14 @@ void UIWidget::initText()

void UIWidget::updateText()
{
if (isTextWrap() && m_rect.isValid())
if (isTextWrap() && m_rect.isValid()) {
m_drawTextColors = m_textColors;
m_drawText = m_font->wrapText(m_text, getWidth() - m_textOffset.x);
else
}
else {
m_drawText = m_text;
m_drawTextColors = m_textColors;
}

if (m_font)
m_glyphsPositionsCache = m_font->calculateGlyphsPositions(m_drawText, m_textAlign, &m_textSize);
Expand Down Expand Up @@ -111,11 +116,22 @@ void UIWidget::drawText(const Rect& screenCoords)
auto coords = Rect(screenCoords.topLeft().scale(m_fontScale), screenCoords.bottomRight().scale(m_fontScale));
coords.translate(textOffset);

m_font->fillTextCoords(m_coordsBuffer, m_text, m_textSize, m_textAlign, coords, m_glyphsPositionsCache);
if (m_drawTextColors.empty())
m_font->fillTextCoords(m_coordsBuffer, m_drawText, m_textSize, m_textAlign, coords, m_glyphsPositionsCache);
else
m_font->fillTextColorCoords(m_colorCoordsBuffer, m_drawText, m_drawTextColors, m_textSize, m_textAlign, coords, m_glyphsPositionsCache);
}

g_drawPool.scale(m_fontScale);
g_drawPool.addTexturedCoordsBuffer(m_font->getTexture(), m_coordsBuffer, m_color);
if (m_drawTextColors.empty() || m_colorCoordsBuffer.empty()) {
g_drawPool.addTexturedCoordsBuffer(m_font->getTexture(), m_coordsBuffer, m_color);
}
else {
auto texture = m_font->getTexture();
for (const auto& [color, coordsBuffer] : m_colorCoordsBuffer) {
g_drawPool.addTexturedCoordsBuffer(texture, coordsBuffer, color);
}
}
g_drawPool.scale(1.f); // reset scale
}

Expand All @@ -132,8 +148,12 @@ void UIWidget::setText(const std::string_view text, bool dontFireLuaCall)
if (hasProp(PropTextOnlyUpperCase))
stdext::toupper(_text);

if (m_text == _text)
if (m_text == _text && m_textColors.empty())
return;

m_textColors.clear();
m_drawTextColors.clear();
m_colorCoordsBuffer.clear();

const std::string oldText = m_text;
m_text = _text;
Expand All @@ -144,6 +164,51 @@ void UIWidget::setText(const std::string_view text, bool dontFireLuaCall)
}
}


void UIWidget::setColoredText(const std::string_view coloredText, bool dontFireLuaCall)
{
m_textColors.clear();
m_drawTextColors.clear();
m_colorCoordsBuffer.clear();
m_coordsBuffer->clear();

std::regex exp("\\{([^\\}]+),[ ]*([^\\}]+)\\}");

std::string _text{ coloredText.data() };

Color baseColor = Color::white;
std::smatch res;
std::string text = "";
while (std::regex_search(_text, res, exp))
{
std::string prefix = res.prefix().str();
if (prefix.size() > 0) {
m_textColors.push_back(std::make_pair(text.size(), baseColor));
text = text + prefix;
}
auto color = Color(res[2].str());
m_textColors.push_back(std::make_pair(text.size(), color));
text = text + res[1].str();
_text = res.suffix();
}

if (_text.size() > 0) {
m_textColors.push_back(std::make_pair(text.size(), baseColor));
text = text + _text;
}

if (hasProp(PropTextOnlyUpperCase))
stdext::toupper(text);

std::string oldText = m_text;
m_text = text;
updateText();

if (!dontFireLuaCall) {
onTextChange(text, oldText);
}
}

void UIWidget::setFont(const std::string_view fontName)
{
m_font = g_fonts.getFont(fontName);
Expand Down
2 changes: 1 addition & 1 deletion src/framework/util/color.h
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class Color
float gF() const { return m_g; }
float rF() const { return m_r; }

uint32_t rgba() const { return static_cast<uint32_t>(a() | b() << 8 | g() << 16 | r() << 24); }
uint32_t rgba() const { return static_cast<uint32_t>(a() << 24 | b() << 16 | g() << 8 | r()); }
size_t hash() const { return m_hash; }

void setRed(const int r) { m_r = static_cast<uint8_t>(r) / 255.f; update(); }
Expand Down