Initial commit

This commit is contained in:
2022-10-08 17:16:13 -04:00
commit 385638c5e1
1925 changed files with 872504 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,412 @@
/*
CGUITTFont FreeType class for Irrlicht
Copyright (c) 2009-2010 John Norman
Copyright (c) 2016 Nathanaëlle Courant
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
The original version of this class can be located at:
http://irrlicht.suckerfreegames.com/
John Norman
john@suckerfreegames.com
*/
#pragma once
#include <irrlicht.h>
#include <ft2build.h>
#include <vector>
#include <map>
#include <irrUString.h>
#include "util/enriched_string.h"
#include "util/basic_macros.h"
#include FT_FREETYPE_H
namespace irr
{
namespace gui
{
struct SGUITTFace;
class CGUITTFont;
//! Structure representing a single TrueType glyph.
struct SGUITTGlyph
{
//! Constructor.
SGUITTGlyph() :
isLoaded(false),
glyph_page(0),
source_rect(),
offset(),
advance(),
surface(0),
parent(0)
{}
DISABLE_CLASS_COPY(SGUITTGlyph);
//! This class would be trivially copyable except for the reference count on `surface`.
SGUITTGlyph(SGUITTGlyph &&other) :
isLoaded(other.isLoaded),
glyph_page(other.glyph_page),
source_rect(other.source_rect),
offset(other.offset),
advance(other.advance),
surface(other.surface),
parent(other.parent)
{
other.surface = 0;
}
//! Destructor.
~SGUITTGlyph() { unload(); }
//! Preload the glyph.
//! The preload process occurs when the program tries to cache the glyph from FT_Library.
//! However, it simply defines the SGUITTGlyph's properties and will only create the page
//! textures if necessary. The actual creation of the textures should only occur right
//! before the batch draw call.
void preload(u32 char_index, FT_Face face, video::IVideoDriver* driver, u32 font_size, const FT_Int32 loadFlags);
//! Unloads the glyph.
void unload();
//! Creates the IImage object from the FT_Bitmap.
video::IImage* createGlyphImage(const FT_Bitmap& bits, video::IVideoDriver* driver) const;
//! If true, the glyph has been loaded.
bool isLoaded;
//! The page the glyph is on.
u32 glyph_page;
//! The source rectangle for the glyph.
core::recti source_rect;
//! The offset of glyph when drawn.
core::vector2di offset;
//! Glyph advance information.
FT_Vector advance;
//! This is just the temporary image holder. After this glyph is paged,
//! it will be dropped.
mutable video::IImage* surface;
//! The pointer pointing to the parent (CGUITTFont)
CGUITTFont* parent;
};
//! Holds a sheet of glyphs.
class CGUITTGlyphPage
{
public:
CGUITTGlyphPage(video::IVideoDriver* Driver, const io::path& texture_name) :texture(0), available_slots(0), used_slots(0), dirty(false), driver(Driver), name(texture_name) {}
~CGUITTGlyphPage()
{
if (texture)
{
if (driver)
driver->removeTexture(texture);
else texture->drop();
}
}
//! Create the actual page texture,
bool createPageTexture(const u8& pixel_mode, const core::dimension2du& texture_size)
{
if( texture )
return false;
bool flgmip = driver->getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);
driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);
#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8
bool flgcpy = driver->getTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY);
driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, true);
#endif
// Set the texture color format.
switch (pixel_mode)
{
case FT_PIXEL_MODE_MONO:
texture = driver->addTexture(texture_size, name, video::ECF_A1R5G5B5);
break;
case FT_PIXEL_MODE_GRAY:
default:
texture = driver->addTexture(texture_size, name, video::ECF_A8R8G8B8);
break;
}
// Restore our texture creation flags.
driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, flgmip);
#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8
driver->setTextureCreationFlag(video::ETCF_ALLOW_MEMORY_COPY, flgcpy);
#endif
return texture ? true : false;
}
//! Add the glyph to a list of glyphs to be paged.
//! This collection will be cleared after updateTexture is called.
void pushGlyphToBePaged(const SGUITTGlyph* glyph)
{
glyph_to_be_paged.push_back(glyph);
}
//! Updates the texture atlas with new glyphs.
void updateTexture()
{
if (!dirty) return;
void* ptr = texture->lock();
video::ECOLOR_FORMAT format = texture->getColorFormat();
core::dimension2du size = texture->getOriginalSize();
video::IImage* pageholder = driver->createImageFromData(format, size, ptr, true, false);
for (u32 i = 0; i < glyph_to_be_paged.size(); ++i)
{
const SGUITTGlyph* glyph = glyph_to_be_paged[i];
if (glyph && glyph->isLoaded)
{
if (glyph->surface)
{
glyph->surface->copyTo(pageholder, glyph->source_rect.UpperLeftCorner);
glyph->surface->drop();
glyph->surface = 0;
}
else
{
; // TODO: add error message?
//currently, if we failed to create the image, just ignore this operation.
}
}
}
pageholder->drop();
texture->unlock();
glyph_to_be_paged.clear();
dirty = false;
}
video::ITexture* texture;
u32 available_slots;
u32 used_slots;
bool dirty;
core::array<core::vector2di> render_positions;
core::array<core::recti> render_source_rects;
core::array<video::SColor> render_colors;
private:
core::array<const SGUITTGlyph*> glyph_to_be_paged;
video::IVideoDriver* driver;
io::path name;
};
//! Class representing a TrueType font.
class CGUITTFont : public IGUIFont
{
public:
//! Creates a new TrueType font and returns a pointer to it. The pointer must be drop()'ed when finished.
//! \param env The IGUIEnvironment the font loads out of.
//! \param filename The filename of the font.
//! \param size The size of the font glyphs in pixels. Since this is the size of the individual glyphs, the true height of the font may change depending on the characters used.
//! \param antialias set the use_monochrome (opposite to antialias) flag
//! \param transparency set the use_transparency flag
//! \return Returns a pointer to a CGUITTFont. Will return 0 if the font failed to load.
static CGUITTFont* createTTFont(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true, const u32 shadow = 0, const u32 shadow_alpha = 255);
static CGUITTFont* createTTFont(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true);
static CGUITTFont* create(IGUIEnvironment *env, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true);
static CGUITTFont* create(IrrlichtDevice *device, const io::path& filename, const u32 size, const bool antialias = true, const bool transparency = true);
//! Destructor
virtual ~CGUITTFont();
//! Sets the amount of glyphs to batch load.
virtual void setBatchLoadSize(u32 batch_size) { batch_load_size = batch_size; }
//! Sets the maximum texture size for a page of glyphs.
virtual void setMaxPageTextureSize(const core::dimension2du& texture_size) { max_page_texture_size = texture_size; }
//! Get the font size.
virtual u32 getFontSize() const { return size; }
//! Check the font's transparency.
virtual bool isTransparent() const { return use_transparency; }
//! Check if the font auto-hinting is enabled.
//! Auto-hinting is FreeType's built-in font hinting engine.
virtual bool useAutoHinting() const { return use_auto_hinting; }
//! Check if the font hinting is enabled.
virtual bool useHinting() const { return use_hinting; }
//! Check if the font is being loaded as a monochrome font.
//! The font can either be a 256 color grayscale font, or a 2 color monochrome font.
virtual bool useMonochrome() const { return use_monochrome; }
//! Tells the font to allow transparency when rendering.
//! Default: true.
//! \param flag If true, the font draws using transparency.
virtual void setTransparency(const bool flag);
//! Tells the font to use monochrome rendering.
//! Default: false.
//! \param flag If true, the font draws using a monochrome image. If false, the font uses a grayscale image.
virtual void setMonochrome(const bool flag);
//! Enables or disables font hinting.
//! Default: Hinting and auto-hinting true.
//! \param enable If false, font hinting is turned off. If true, font hinting is turned on.
//! \param enable_auto_hinting If true, FreeType uses its own auto-hinting algorithm. If false, it tries to use the algorithm specified by the font.
virtual void setFontHinting(const bool enable, const bool enable_auto_hinting = true);
//! Draws some text and clips it to the specified rectangle if wanted.
virtual void draw(const core::stringw& text, const core::rect<s32>& position,
video::SColor color, bool hcenter=false, bool vcenter=false,
const core::rect<s32>* clip=0);
void draw(const EnrichedString& text, const core::rect<s32>& position,
bool hcenter=false, bool vcenter=false,
const core::rect<s32>* clip=0);
//! Returns the dimension of a character produced by this font.
virtual core::dimension2d<u32> getCharDimension(const wchar_t ch) const;
//! Returns the dimension of a text string.
virtual core::dimension2d<u32> getDimension(const wchar_t* text) const;
virtual core::dimension2d<u32> getDimension(const core::ustring& text) const;
//! Calculates the index of the character in the text which is on a specific position.
virtual s32 getCharacterFromPos(const wchar_t* text, s32 pixel_x) const;
virtual s32 getCharacterFromPos(const core::ustring& text, s32 pixel_x) const;
//! Sets global kerning width for the font.
virtual void setKerningWidth(s32 kerning);
//! Sets global kerning height for the font.
virtual void setKerningHeight(s32 kerning);
//! Gets kerning values (distance between letters) for the font. If no parameters are provided,
virtual s32 getKerningWidth(const wchar_t* thisLetter=0, const wchar_t* previousLetter=0) const;
virtual s32 getKerningWidth(const uchar32_t thisLetter=0, const uchar32_t previousLetter=0) const;
//! Returns the distance between letters
virtual s32 getKerningHeight() const;
//! Define which characters should not be drawn by the font.
virtual void setInvisibleCharacters(const wchar_t *s);
virtual void setInvisibleCharacters(const core::ustring& s);
//! Get the last glyph page if there's still available slots.
//! If not, it will return zero.
CGUITTGlyphPage* getLastGlyphPage() const;
//! Create a new glyph page texture.
//! \param pixel_mode the pixel mode defined by FT_Pixel_Mode
//should be better typed. fix later.
CGUITTGlyphPage* createGlyphPage(const u8& pixel_mode);
//! Get the last glyph page's index.
u32 getLastGlyphPageIndex() const { return Glyph_Pages.size() - 1; }
//! Set font that should be used for glyphs not present in ours
void setFallback(gui::IGUIFont* font) { fallback = font; }
//! Create corresponding character's software image copy from the font,
//! so you can use this data just like any ordinary video::IImage.
//! \param ch The character you need
virtual video::IImage* createTextureFromChar(const uchar32_t& ch);
//! This function is for debugging mostly. If the page doesn't exist it returns zero.
//! \param page_index Simply return the texture handle of a given page index.
virtual video::ITexture* getPageTextureByIndex(const u32& page_index) const;
//! Add a list of scene nodes generated by putting font textures on the 3D planes.
virtual core::array<scene::ISceneNode*> addTextSceneNode
(const wchar_t* text, scene::ISceneManager* smgr, scene::ISceneNode* parent = 0,
const video::SColor& color = video::SColor(255, 0, 0, 0), bool center = false );
inline s32 getAscender() const { return font_metrics.ascender; }
protected:
bool use_monochrome;
bool use_transparency;
bool use_hinting;
bool use_auto_hinting;
u32 size;
u32 batch_load_size;
core::dimension2du max_page_texture_size;
private:
// Manages the FreeType library.
static FT_Library c_library;
static std::map<io::path, SGUITTFace*> c_faces;
static bool c_libraryLoaded;
static scene::IMesh* shared_plane_ptr_;
static scene::SMesh shared_plane_;
CGUITTFont(IGUIEnvironment *env);
bool load(const io::path& filename, const u32 size, const bool antialias, const bool transparency);
void reset_images();
void update_glyph_pages() const;
void update_load_flags()
{
// Set up our loading flags.
load_flags = FT_LOAD_DEFAULT | FT_LOAD_RENDER;
if (!useHinting()) load_flags |= FT_LOAD_NO_HINTING;
if (!useAutoHinting()) load_flags |= FT_LOAD_NO_AUTOHINT;
if (useMonochrome()) load_flags |= FT_LOAD_MONOCHROME | FT_LOAD_TARGET_MONO;
else load_flags |= FT_LOAD_TARGET_NORMAL;
}
u32 getWidthFromCharacter(wchar_t c) const;
u32 getWidthFromCharacter(uchar32_t c) const;
u32 getHeightFromCharacter(wchar_t c) const;
u32 getHeightFromCharacter(uchar32_t c) const;
u32 getGlyphIndexByChar(wchar_t c) const;
u32 getGlyphIndexByChar(uchar32_t c) const;
core::vector2di getKerning(const wchar_t thisLetter, const wchar_t previousLetter) const;
core::vector2di getKerning(const uchar32_t thisLetter, const uchar32_t previousLetter) const;
core::dimension2d<u32> getDimensionUntilEndOfLine(const wchar_t* p) const;
void createSharedPlane();
irr::IrrlichtDevice* Device;
gui::IGUIEnvironment* Environment;
video::IVideoDriver* Driver;
io::path filename;
FT_Face tt_face;
FT_Size_Metrics font_metrics;
FT_Int32 load_flags;
mutable core::array<CGUITTGlyphPage*> Glyph_Pages;
mutable core::array<SGUITTGlyph> Glyphs;
s32 GlobalKerningWidth;
s32 GlobalKerningHeight;
core::ustring Invisible;
u32 shadow_offset;
u32 shadow_alpha;
gui::IGUIFont* fallback;
};
} // end namespace gui
} // end namespace irr

View File

@@ -0,0 +1,11 @@
if (BUILD_CLIENT)
set(client_irrlicht_changes_SRCS
${CMAKE_CURRENT_SOURCE_DIR}/static_text.cpp
${CMAKE_CURRENT_SOURCE_DIR}/CGUITTFont.cpp
)
# CMake require us to set a local scope and then parent scope
# Else the last set win in parent scope
set(client_irrlicht_changes_SRCS ${client_irrlicht_changes_SRCS} PARENT_SCOPE)
endif()

View File

@@ -0,0 +1,589 @@
// Copyright (C) 2002-2012 Nikolaus Gebhardt
// Copyright (C) 2016 Nathanaëlle Courant:
// Modified the functions to use EnrichedText instead of string.
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "static_text.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include <IGUIFont.h>
#include <IVideoDriver.h>
#include <rect.h>
#include <SColor.h>
#include "CGUITTFont.h"
#include "util/string.h"
namespace irr
{
namespace gui
{
//! constructor
StaticText::StaticText(const EnrichedString &text, bool border,
IGUIEnvironment* environment, IGUIElement* parent,
s32 id, const core::rect<s32>& rectangle,
bool background)
: IGUIStaticText(environment, parent, id, rectangle),
HAlign(EGUIA_UPPERLEFT), VAlign(EGUIA_UPPERLEFT),
Border(border), WordWrap(false), Background(background),
RestrainTextInside(true), RightToLeft(false),
OverrideFont(0), LastBreakFont(0)
{
#ifdef _DEBUG
setDebugName("StaticText");
#endif
setText(text);
}
//! destructor
StaticText::~StaticText()
{
if (OverrideFont)
OverrideFont->drop();
}
//! draws the element and its children
void StaticText::draw()
{
if (!IsVisible)
return;
IGUISkin* skin = Environment->getSkin();
if (!skin)
return;
video::IVideoDriver* driver = Environment->getVideoDriver();
core::rect<s32> frameRect(AbsoluteRect);
// draw background
if (Background)
driver->draw2DRectangle(getBackgroundColor(), frameRect, &AbsoluteClippingRect);
// draw the border
if (Border)
{
skin->draw3DSunkenPane(this, 0, true, false, frameRect, &AbsoluteClippingRect);
frameRect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X);
}
// draw the text
IGUIFont *font = getActiveFont();
if (font && BrokenText.size()) {
if (font != LastBreakFont)
updateText();
core::rect<s32> r = frameRect;
s32 height_line = font->getDimension(L"A").Height + font->getKerningHeight();
s32 height_total = height_line * BrokenText.size();
if (VAlign == EGUIA_CENTER && WordWrap)
{
r.UpperLeftCorner.Y = r.getCenter().Y - (height_total / 2);
}
else if (VAlign == EGUIA_LOWERRIGHT)
{
r.UpperLeftCorner.Y = r.LowerRightCorner.Y - height_total;
}
if (HAlign == EGUIA_LOWERRIGHT)
{
r.UpperLeftCorner.X = r.LowerRightCorner.X -
getTextWidth();
}
irr::video::SColor previous_color(255, 255, 255, 255);
for (const EnrichedString &str : BrokenText) {
if (HAlign == EGUIA_LOWERRIGHT)
{
r.UpperLeftCorner.X = frameRect.LowerRightCorner.X -
font->getDimension(str.c_str()).Width;
}
if (font->getType() == irr::gui::EGFT_CUSTOM) {
CGUITTFont *tmp = static_cast<CGUITTFont*>(font);
tmp->draw(str,
r, HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER,
(RestrainTextInside ? &AbsoluteClippingRect : NULL));
} else
{
// Draw non-colored text
font->draw(str.c_str(),
r, str.getDefaultColor(), // TODO: Implement colorization
HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER,
(RestrainTextInside ? &AbsoluteClippingRect : NULL));
}
r.LowerRightCorner.Y += height_line;
r.UpperLeftCorner.Y += height_line;
}
}
IGUIElement::draw();
}
//! Sets another skin independent font.
void StaticText::setOverrideFont(IGUIFont* font)
{
if (OverrideFont == font)
return;
if (OverrideFont)
OverrideFont->drop();
OverrideFont = font;
if (OverrideFont)
OverrideFont->grab();
updateText();
}
//! Gets the override font (if any)
IGUIFont * StaticText::getOverrideFont() const
{
return OverrideFont;
}
//! Get the font which is used right now for drawing
IGUIFont* StaticText::getActiveFont() const
{
if ( OverrideFont )
return OverrideFont;
IGUISkin* skin = Environment->getSkin();
if (skin)
return skin->getFont();
return 0;
}
//! Sets another color for the text.
void StaticText::setOverrideColor(video::SColor color)
{
ColoredText.setDefaultColor(color);
updateText();
}
//! Sets another color for the text.
void StaticText::setBackgroundColor(video::SColor color)
{
ColoredText.setBackground(color);
Background = true;
}
//! Sets whether to draw the background
void StaticText::setDrawBackground(bool draw)
{
Background = draw;
}
//! Gets the background color
video::SColor StaticText::getBackgroundColor() const
{
IGUISkin *skin = Environment->getSkin();
return (ColoredText.hasBackground() || !skin) ?
ColoredText.getBackground() : skin->getColor(gui::EGDC_3D_FACE);
}
//! Checks if background drawing is enabled
bool StaticText::isDrawBackgroundEnabled() const
{
return Background;
}
//! Sets whether to draw the border
void StaticText::setDrawBorder(bool draw)
{
Border = draw;
}
//! Checks if border drawing is enabled
bool StaticText::isDrawBorderEnabled() const
{
return Border;
}
void StaticText::setTextRestrainedInside(bool restrainTextInside)
{
RestrainTextInside = restrainTextInside;
}
bool StaticText::isTextRestrainedInside() const
{
return RestrainTextInside;
}
void StaticText::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical)
{
HAlign = horizontal;
VAlign = vertical;
}
video::SColor StaticText::getOverrideColor() const
{
return ColoredText.getDefaultColor();
}
#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8
video::SColor StaticText::getActiveColor() const
{
return getOverrideColor();
}
#endif
//! Sets if the static text should use the overide color or the
//! color in the gui skin.
void StaticText::enableOverrideColor(bool enable)
{
// TODO
}
bool StaticText::isOverrideColorEnabled() const
{
return true;
}
//! Enables or disables word wrap for using the static text as
//! multiline text control.
void StaticText::setWordWrap(bool enable)
{
WordWrap = enable;
updateText();
}
bool StaticText::isWordWrapEnabled() const
{
return WordWrap;
}
void StaticText::setRightToLeft(bool rtl)
{
if (RightToLeft != rtl)
{
RightToLeft = rtl;
updateText();
}
}
bool StaticText::isRightToLeft() const
{
return RightToLeft;
}
//! Breaks the single text line.
// Updates the font colors
void StaticText::updateText()
{
const EnrichedString &cText = ColoredText;
BrokenText.clear();
if (cText.hasBackground())
setBackgroundColor(cText.getBackground());
else
setDrawBackground(false);
if (!WordWrap) {
BrokenText.push_back(cText);
return;
}
// Update word wrap
IGUISkin* skin = Environment->getSkin();
IGUIFont* font = getActiveFont();
if (!font)
return;
LastBreakFont = font;
EnrichedString line;
EnrichedString word;
EnrichedString whitespace;
s32 size = cText.size();
s32 length = 0;
s32 elWidth = RelativeRect.getWidth();
if (Border)
elWidth -= 2*skin->getSize(EGDS_TEXT_DISTANCE_X);
wchar_t c;
//std::vector<irr::video::SColor> colors;
// We have to deal with right-to-left and left-to-right differently
// However, most parts of the following code is the same, it's just
// some order and boundaries which change.
if (!RightToLeft)
{
// regular (left-to-right)
for (s32 i=0; i<size; ++i)
{
c = cText.getString()[i];
bool lineBreak = false;
if (c == L'\r') // Mac or Windows breaks
{
lineBreak = true;
//if (Text[i+1] == L'\n') // Windows breaks
//{
// Text.erase(i+1);
// --size;
//}
c = '\0';
}
else if (c == L'\n') // Unix breaks
{
lineBreak = true;
c = '\0';
}
bool isWhitespace = (c == L' ' || c == 0);
if ( !isWhitespace )
{
// part of a word
//word += c;
word.addChar(cText, i);
}
if ( isWhitespace || i == (size-1))
{
if (word.size())
{
// here comes the next whitespace, look if
// we must break the last word to the next line.
const s32 whitelgth = font->getDimension(whitespace.c_str()).Width;
//const std::wstring sanitized = removeEscapes(word.c_str());
const s32 wordlgth = font->getDimension(word.c_str()).Width;
if (wordlgth > elWidth)
{
// This word is too long to fit in the available space, look for
// the Unicode Soft HYphen (SHY / 00AD) character for a place to
// break the word at
int where = core::stringw(word.c_str()).findFirst( wchar_t(0x00AD) );
if (where != -1)
{
EnrichedString first = word.substr(0, where);
EnrichedString second = word.substr(where, word.size() - where);
first.addCharNoColor(L'-');
BrokenText.push_back(line + first);
const s32 secondLength = font->getDimension(second.c_str()).Width;
length = secondLength;
line = second;
}
else
{
// No soft hyphen found, so there's nothing more we can do
// break to next line
if (length)
BrokenText.push_back(line);
length = wordlgth;
line = word;
}
}
else if (length && (length + wordlgth + whitelgth > elWidth))
{
// break to next line
BrokenText.push_back(line);
length = wordlgth;
line = word;
}
else
{
// add word to line
line += whitespace;
line += word;
length += whitelgth + wordlgth;
}
word.clear();
whitespace.clear();
}
if ( isWhitespace && c != 0)
{
whitespace.addChar(cText, i);
}
// compute line break
if (lineBreak)
{
line += whitespace;
line += word;
BrokenText.push_back(line);
line.clear();
word.clear();
whitespace.clear();
length = 0;
}
}
}
line += whitespace;
line += word;
BrokenText.push_back(line);
}
else
{
// right-to-left
for (s32 i=size; i>=0; --i)
{
c = cText.getString()[i];
bool lineBreak = false;
if (c == L'\r') // Mac or Windows breaks
{
lineBreak = true;
//if ((i>0) && Text[i-1] == L'\n') // Windows breaks
//{
// Text.erase(i-1);
// --size;
//}
c = '\0';
}
else if (c == L'\n') // Unix breaks
{
lineBreak = true;
c = '\0';
}
if (c==L' ' || c==0 || i==0)
{
if (word.size())
{
// here comes the next whitespace, look if
// we must break the last word to the next line.
const s32 whitelgth = font->getDimension(whitespace.c_str()).Width;
const s32 wordlgth = font->getDimension(word.c_str()).Width;
if (length && (length + wordlgth + whitelgth > elWidth))
{
// break to next line
BrokenText.push_back(line);
length = wordlgth;
line = word;
}
else
{
// add word to line
line = whitespace + line;
line = word + line;
length += whitelgth + wordlgth;
}
word.clear();
whitespace.clear();
}
if (c != 0)
// whitespace = core::stringw(&c, 1) + whitespace;
whitespace = cText.substr(i, 1) + whitespace;
// compute line break
if (lineBreak)
{
line = whitespace + line;
line = word + line;
BrokenText.push_back(line);
line.clear();
word.clear();
whitespace.clear();
length = 0;
}
}
else
{
// yippee this is a word..
//word = core::stringw(&c, 1) + word;
word = cText.substr(i, 1) + word;
}
}
line = whitespace + line;
line = word + line;
BrokenText.push_back(line);
}
}
//! Sets the new caption of this element.
void StaticText::setText(const wchar_t* text)
{
setText(EnrichedString(text, getOverrideColor()));
}
void StaticText::setText(const EnrichedString &text)
{
ColoredText = text;
IGUIElement::setText(ColoredText.c_str());
updateText();
}
void StaticText::updateAbsolutePosition()
{
IGUIElement::updateAbsolutePosition();
updateText();
}
//! Returns the height of the text in pixels when it is drawn.
s32 StaticText::getTextHeight() const
{
IGUIFont* font = getActiveFont();
if (!font)
return 0;
if (WordWrap) {
s32 height = font->getDimension(L"A").Height + font->getKerningHeight();
return height * BrokenText.size();
}
// There may be intentional new lines without WordWrap
return font->getDimension(BrokenText[0].c_str()).Height;
}
s32 StaticText::getTextWidth() const
{
IGUIFont *font = getActiveFont();
if (!font)
return 0;
s32 widest = 0;
for (const EnrichedString &line : BrokenText) {
s32 width = font->getDimension(line.c_str()).Width;
if (width > widest)
widest = width;
}
return widest;
}
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_

View File

@@ -0,0 +1,237 @@
// Copyright (C) 2002-2012 Nikolaus Gebhardt
// Copyright (C) 2016 Nathanaëlle Courant
// Modified this class to work with EnrichedStrings too
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#pragma once
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IGUIStaticText.h"
#include "irrArray.h"
#include "log.h"
#include <vector>
#include "util/enriched_string.h"
#include "config.h"
#include <IGUIEnvironment.h>
namespace irr
{
namespace gui
{
const EGUI_ELEMENT_TYPE EGUIET_ENRICHED_STATIC_TEXT = (EGUI_ELEMENT_TYPE)(0x1000);
class StaticText : public IGUIStaticText
{
public:
// StaticText is translated by EnrichedString.
// No need to use translate_string()
StaticText(const EnrichedString &text, bool border, IGUIEnvironment* environment,
IGUIElement* parent, s32 id, const core::rect<s32>& rectangle,
bool background = false);
//! destructor
virtual ~StaticText();
static irr::gui::IGUIStaticText *add(
irr::gui::IGUIEnvironment *guienv,
const EnrichedString &text,
const core::rect< s32 > &rectangle,
bool border = false,
bool wordWrap = true,
irr::gui::IGUIElement *parent = NULL,
s32 id = -1,
bool fillBackground = false)
{
if (parent == NULL) {
// parent is NULL, so we must find one, or we need not to drop
// result, but then there will be a memory leak.
//
// What Irrlicht does is to use guienv as a parent, but the problem
// is that guienv is here only an IGUIEnvironment, while it is a
// CGUIEnvironment in Irrlicht, which inherits from both IGUIElement
// and IGUIEnvironment.
//
// A solution would be to dynamic_cast guienv to a
// IGUIElement*, but Irrlicht is shipped without rtti support
// in some distributions, causing the dymanic_cast to segfault.
//
// Thus, to find the parent, we create a dummy StaticText and ask
// for its parent, and then remove it.
irr::gui::IGUIStaticText *dummy_text =
guienv->addStaticText(L"", rectangle, border, wordWrap,
parent, id, fillBackground);
parent = dummy_text->getParent();
dummy_text->remove();
}
irr::gui::IGUIStaticText *result = new irr::gui::StaticText(
text, border, guienv, parent,
id, rectangle, fillBackground);
result->setWordWrap(wordWrap);
result->drop();
return result;
}
static irr::gui::IGUIStaticText *add(
irr::gui::IGUIEnvironment *guienv,
const wchar_t *text,
const core::rect< s32 > &rectangle,
bool border = false,
bool wordWrap = true,
irr::gui::IGUIElement *parent = NULL,
s32 id = -1,
bool fillBackground = false)
{
return add(guienv, EnrichedString(text), rectangle, border, wordWrap, parent,
id, fillBackground);
}
//! draws the element and its children
virtual void draw();
//! Sets another skin independent font.
virtual void setOverrideFont(IGUIFont* font=0);
//! Gets the override font (if any)
virtual IGUIFont* getOverrideFont() const;
//! Get the font which is used right now for drawing
virtual IGUIFont* getActiveFont() const;
//! Sets another color for the text.
virtual void setOverrideColor(video::SColor color);
//! Sets another color for the background.
virtual void setBackgroundColor(video::SColor color);
//! Sets whether to draw the background
virtual void setDrawBackground(bool draw);
//! Gets the background color
virtual video::SColor getBackgroundColor() const;
//! Checks if background drawing is enabled
virtual bool isDrawBackgroundEnabled() const;
//! Sets whether to draw the border
virtual void setDrawBorder(bool draw);
//! Checks if border drawing is enabled
virtual bool isDrawBorderEnabled() const;
//! Sets alignment mode for text
virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical);
//! Gets the override color
virtual video::SColor getOverrideColor() const;
#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8
//! Gets the currently used text color
virtual video::SColor getActiveColor() const;
#endif
//! Sets if the static text should use the overide color or the
//! color in the gui skin.
virtual void enableOverrideColor(bool enable);
//! Checks if an override color is enabled
virtual bool isOverrideColorEnabled() const;
//! Set whether the text in this label should be clipped if it goes outside bounds
virtual void setTextRestrainedInside(bool restrainedInside);
//! Checks if the text in this label should be clipped if it goes outside bounds
virtual bool isTextRestrainedInside() const;
//! Enables or disables word wrap for using the static text as
//! multiline text control.
virtual void setWordWrap(bool enable);
//! Checks if word wrap is enabled
virtual bool isWordWrapEnabled() const;
//! Sets the new caption of this element.
virtual void setText(const wchar_t* text);
//! Returns the height of the text in pixels when it is drawn.
virtual s32 getTextHeight() const;
//! Returns the width of the current text, in the current font
virtual s32 getTextWidth() const;
//! Updates the absolute position, splits text if word wrap is enabled
virtual void updateAbsolutePosition();
//! Set whether the string should be interpreted as right-to-left (RTL) text
/** \note This component does not implement the Unicode bidi standard, the
text of the component should be already RTL if you call this. The
main difference when RTL is enabled is that the linebreaks for multiline
elements are performed starting from the end.
*/
virtual void setRightToLeft(bool rtl);
//! Checks if the text should be interpreted as right-to-left text
virtual bool isRightToLeft() const;
virtual bool hasType(EGUI_ELEMENT_TYPE t) const {
return (t == EGUIET_ENRICHED_STATIC_TEXT) || (t == EGUIET_STATIC_TEXT);
};
virtual bool hasType(EGUI_ELEMENT_TYPE t) {
return (t == EGUIET_ENRICHED_STATIC_TEXT) || (t == EGUIET_STATIC_TEXT);
};
void setText(const EnrichedString &text);
private:
//! Breaks the single text line.
void updateText();
EGUI_ALIGNMENT HAlign, VAlign;
bool Border;
bool WordWrap;
bool Background;
bool RestrainTextInside;
bool RightToLeft;
gui::IGUIFont* OverrideFont;
gui::IGUIFont* LastBreakFont; // stored because: if skin changes, line break must be recalculated.
EnrichedString ColoredText;
std::vector<EnrichedString> BrokenText;
};
} // end namespace gui
} // end namespace irr
inline void setStaticText(irr::gui::IGUIStaticText *static_text, const EnrichedString &text)
{
// dynamic_cast not possible due to some distributions shipped
// without rtti support in irrlicht
if (static_text->hasType(irr::gui::EGUIET_ENRICHED_STATIC_TEXT)) {
irr::gui::StaticText* stext = static_cast<irr::gui::StaticText*>(static_text);
stext->setText(text);
} else {
static_text->setText(text.c_str());
}
}
inline void setStaticText(irr::gui::IGUIStaticText *static_text, const wchar_t *text)
{
setStaticText(static_text, EnrichedString(text, static_text->getOverrideColor()));
}
#endif // _IRR_COMPILE_WITH_GUI_