1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322

#include "fsCNativeTextSprite.h"

#include <rlgl.h>

#include <fsCore/fsStr.h>
#include <fsCore/fsSColour.h>
#include <fsCore/fsRect.h>

#include "../fsCFont.h"
#include "fsAppCore/fsIDisplay.h"

namespace
{
	// raylib has no rich-text rendering yet. fsStr::removeXmlTags() deliberately preserves
	// <b>/<i>/<font ...> tags now (axmol/cocos2d-x render them), so without this they'd show
	// up as literal control codes here. Strip them, keeping the enclosed text, so raylib falls
	// back to plain readable text instead.
	fsStr richTextTagsStrip(const fsStr& pText)
	{
		fsStr result = pText;
		fsStr::sizeT start = result.find('<');
		while (start != fsStr::npos)
		{
			const fsStr::sizeT end = result.find('>', start);
			if (end == fsStr::npos)
			{
				break;
			}
			result.erase(start, end - start + 1);
			start = result.find('<');
		}
		return result;
	}
}

void fsCNativeTextSprite::outlineSet(const fsSColour4B& pOutline, fsF32 pSize) const<--- The member function 'fsCNativeTextSprite::outlineSet' can be static.
{
    // no impl
}

void fsCNativeTextSprite::glowSet(const fsSColour4B& pGlow) const<--- The member function 'fsCNativeTextSprite::glowSet' can be static.
{
    // no impl	
}

void fsCNativeTextSprite::shadowSet(const fsSColour4B& pShadow, fsVec2d pOffset, fsF32 pBlurRadius) const<--- The member function 'fsCNativeTextSprite::shadowSet' can be static.
{
    // no impl
}

fsF32 fsCNativeTextSprite::lineStart(fsF32 lineWidth) const
{
    if (mHorizontalAlignment == fsITextSpriteComponent::eHORIZONTAL_ALIGNMENT::eHALIGN_CENTRE)
        return (mRect.width - lineWidth) / 2;
    if (mHorizontalAlignment == fsITextSpriteComponent::eHORIZONTAL_ALIGNMENT::eHALIGN_RIGHT)
	    return mRect.width - lineWidth;
    // if (mHorizontalAlignment == fsITextSpriteComponent::eHORIZONTAL_ALIGNMENT::eHALIGN_LEFT)
	return 0;
}

fsS32 fsCNativeTextSprite::lineCountGet(Font font, const char *text, Rectangle rec, float fontSize, float spacing) const<--- The member function 'fsCNativeTextSprite::lineCountGet' can be static.
{
    const int length = TextLength(text);
    float textOffsetX = 0.0f;
    const float scaleFactor = fontSize/(float)font.baseSize;

    int lineCount = 0;
    
    for (int i = 0, k = 0; i < length; i++, k++)
    {
        int codepointByteCount = 0;
        int codepoint = GetCodepoint(&text[i], &codepointByteCount);
        int index = GetGlyphIndex(font, codepoint);
        
        // NOTE: Normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
        // but we need to draw all of the bad bytes using the '?' symbol moving one byte
        if (codepoint == 0x3f) codepointByteCount = 1;
        i += (codepointByteCount - 1);
        
        float glyphWidth = 0;
        if (codepoint != '\n')
        {
            glyphWidth = (font.glyphs[index].advanceX == 0) ? font.recs[index].width*scaleFactor : font.glyphs[index].advanceX*scaleFactor;
            if (i + 1 < length) glyphWidth = glyphWidth + spacing;
        }
        
        if ((textOffsetX + glyphWidth) > rec.width)
        {
            textOffsetX = 0;
            ++lineCount;
        }
        else if (codepoint == '\n')
        {
            textOffsetX = 0;
            ++lineCount;
        }
        else{
            if ((textOffsetX != 0) || (codepoint != ' ')) textOffsetX += glyphWidth;  // avoid leading spaces
        }
        
    }
    return lineCount;
}

// Draw text using font inside rectangle limits with support for text selection
void fsCNativeTextSprite::drawTextBoxed(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint)
{
    const int length = TextLength(text);
    const float scaleFactor = fontSize/(float)font.baseSize;

    enum { MEASURE_STATE = 0, DRAW_STATE = 1 };
    int state = wordWrap? MEASURE_STATE : DRAW_STATE;

    int startLine = -1;         // Index where to begin drawing (where a line begins)
    int endLine = -1;           // Index where to stop drawing (where a line ends)
    int lastk = -1;             // Holds last value of the character position

    float glyghHeight = (fontSize + fontSize / 2) * scaleFactor;
    float textOffsetX = 0.0f;
    float textOffsetY = -lineCountGet(font, text, rec, fontSize, spacing) * glyghHeight / 2;          // Offset between lines (on line break '\n')

    for (int i = 0, k = 0; i < length; i++, k++)
    {
        // Get next codepoint from byte string and glyph index in font
        int codepointByteCount = 0;
        int codepoint = GetCodepoint(&text[i], &codepointByteCount);
        int index = GetGlyphIndex(font, codepoint);

        // NOTE: Normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
        // but we need to draw all of the bad bytes using the '?' symbol moving one byte
        if (codepoint == 0x3f) codepointByteCount = 1;
        i += (codepointByteCount - 1);

        float glyphWidth = 0;
        if (codepoint != '\n')
        {
            glyphWidth = (font.glyphs[index].advanceX == 0) ? font.recs[index].width*scaleFactor : font.glyphs[index].advanceX*scaleFactor;

            if (i + 1 < length) glyphWidth = glyphWidth + spacing;
        }

        // NOTE: When wordWrap is ON we first measure how much of the text we can draw before going outside of the rec container
        // We store this info in startLine and endLine, then we change states, draw the text between those two variables
        // and change states again and again recursively until the end of the text (or until we get outside of the container).
        // When wordWrap is OFF we don't need the measure state so we go to the drawing state immediately
        // and begin drawing on the next line before we can get outside the container.
        if (state == MEASURE_STATE)
        {
            // TODO: There are multiple types of spaces in UNICODE, maybe it's a good idea to add support for more
            // Ref: http://jkorpela.fi/chars/spaces.html
            if ((codepoint == ' ') || (codepoint == '\t') || (codepoint == '\n')) endLine = i;

            if ((textOffsetX + glyphWidth) > rec.width)
            {
                endLine = (endLine < 1)? i : endLine;
                if (i == endLine) endLine -= codepointByteCount;
                if ((startLine + codepointByteCount) == endLine) endLine = (i - codepointByteCount);

                state = !state;
            }
            else if ((i + 1) == length)
            {
                textOffsetX += glyphWidth;
                endLine = i;
                state = !state;
            }
            else if (codepoint == '\n') 
            {
                textOffsetX += glyphWidth;
                state = !state;
            }

            if (state == DRAW_STATE)
            {
                textOffsetX = lineStart(textOffsetX);
                i = startLine;

                // Save character position when we switch states
                int tmp = lastk;
                lastk = k - 1;
                k = tmp;
            }
        }
        else
        {
            if (codepoint == '\n')
            {
                if (!wordWrap)
                {
                    textOffsetY += glyghHeight;
                    textOffsetX = 0;
                }
            }
            else
            {
                if (!wordWrap && ((textOffsetX + glyphWidth) > rec.width))
                {
                    textOffsetY += glyghHeight;
                    textOffsetX = 0;
                }

                // When text overflows rectangle height limit, just stop drawing
                if ((textOffsetY + font.baseSize*scaleFactor) > rec.height) break;

                // Draw current character glyph
                if ((codepoint != ' ') && (codepoint != '\t'))
                {
                    DrawTextCodepoint(font, codepoint, Vector2{ rec.x + textOffsetX, rec.y + textOffsetY }, fontSize, tint);
                }
            }

            if (wordWrap && (i == endLine))
            {
                textOffsetY += glyghHeight;
                textOffsetX = 0;
                startLine = endLine;
                endLine = -1;
                k = lastk;

                state = !state;
            }
        }

        if ((textOffsetX != 0) || (codepoint != ' ')) textOffsetX += glyphWidth;  // avoid leading spaces
    }
}

void fsCNativeTextSprite::renderDo()
{
	rlPushMatrix();
	rlMultMatrixf(&mRenderMatrix[0]);

	auto fnt = static_cast<fsCFont*>(mFont);
	drawTextBoxed(fnt->mFont, mText.utf8Get(), mRect, fnt->mPointSize, 0, true, mTint);

	rlPopMatrix();
}

void fsCNativeTextSprite::colourSetDo(const fsSColour4B& pColour)
{
	mTint = reinterpret_cast<::Color&>(const_cast<fsSColour4B&>(pColour));
}

void fsCNativeTextSprite::alignmentSet(fsS32 pAlignH, fsS32 pAlignV)
{
	mHorizontalAlignment = static_cast<fsTHorizontalAlign>(pAlignH);
	mVerticalAlignment = static_cast<fsTVerticalAlign>(pAlignV);
}

void fsCNativeTextSprite::initialise(const fsStr& pText, fsIFont* pFont)
{
	mFont = pFont;
	textSet(pText);
}

fsS32 fsCNativeTextSprite::stringWidthInPixelsGet() const
{
	auto fnt = static_cast<fsCFont*>(mFont);
	return ::MeasureTextEx(fnt->mFont, mText.utf8Get(), fnt->mPointSize, 0 ).x;
}

fsS32 fsCNativeTextSprite::stringHeightInPixelsGet() const
{
	auto fnt = static_cast<fsCFont*>(mFont);
	return ::MeasureTextEx(fnt->mFont, mText.utf8Get(), fnt->mPointSize, 0 ).y;
}

void fsCNativeTextSprite::formattingRectSizeSet(const fsRect& pFormattingRect)
{
	mBoundingBox = pFormattingRect;
	mRect.width = mBoundingBox.widthGet();
	mRect.height = mBoundingBox.heightGet();
	positionRecompute();
}

fsStr fsCNativeTextSprite::textGet() const
{
	return mText;
}

void fsCNativeTextSprite::textSet(const fsStr& pText)
{
	// Can be called every frame by callers reapplying unchanged text - skip the (otherwise
	// duplicated) MeasureTextEx work below when nothing actually changed.
	const fsStr strippedText = richTextTagsStrip(pText);
	if (strippedText == mText)
	{
		return;
	}

	mText = strippedText;
	positionRecompute();
}

void fsCNativeTextSprite::positionRecompute()
{
	// textSet() and formattingRectSizeSet() can each run before the other has ever been
	// called (the real construction order is text-then-size, but this must stay correct
	// regardless), so this is the single place that (re)computes position from whichever
	// values are current for both, rather than each function reading the other's
	// possibly-not-yet-set state.
	if (!mFont)
	{
		return;
	}

	const fsS32 currentHeight = stringHeightInPixelsGet();
	mRect.x = mBoundingBox.xCoordGet() - mRect.width / 2 - (currentHeight / 2.0);
	mRect.y = mBoundingBox.yCoordGet() - (currentHeight / 2.0);
}

fsCNativeTextSprite::fsCNativeTextSprite():
fsINative(),
mFont(nullptr),
mRect{0, 0, 0, 0}
{
}

fsCNativeTextSprite::~fsCNativeTextSprite()
{
}