Jump to content

  • Log In with Google      Sign In   
  • Create Account


Wrapping My Head Around Word Wrapping Code...


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 Vincent_M   Members   -  Reputation: 596

Like
0Likes
Like

Posted 28 February 2013 - 03:12 AM

I'm trying to get my FontString class to print word-wrapped text within a certain height, but I'm not sure the best way of going about this. Here's my latest attempt (I have another version that does this character-by-character):

int startIndex = 0;
int startSpriteIndex = 0;
int numWordsOnLine = 0;
Vector2 offset;
Sprite *sprite = NULL;
		
int specialCharIndex = 0;
int startLineIndex = 0;
float spacing = 0.0f;
float glyphWidth = 0.0f;
bool stopUpdating = false;
		
// remove sprites
batch->RemoveAllSprites();
sprites.clear();
if(!fontPtr) return;
numLines = 1;

// print the text word-by-word
for(int i=0;i<numWords;i++)
{
	int specialCharacter = 0;
	int index = startIndex;
	float wordWidth = 0.0f;
			
	// stop updating the text if deprecated
	if(stopUpdating) break;
			
	// get the number of characters in the word
	while(index < (int)text.size())
	{
		// stop counting if a special character was found
		if(text[index] == ' ' || text[index] == '\t' || text[index] == '\n' || text[index] == '\0')
		{
			specialCharacter = (int)text[index];
			break;
		}
		index++; // increment the index
	}
			
	// get the word's length
	for(int e=startIndex;e<index;e++)
	{
		FontGlyph *glyph = fontPtr->GetGlyph(text[e], false);
		if(!glyph) continue;
		wordWidth += glyph->xAdvance;
	}
			
	// wrap the word down to the next line
	if(offset.x + wordWidth >= dimensions.x && dimensions.x > 0.0f)
	{
		// process alignment
		if(horizontalAlign != FONT_ALIGN_LEFT)
		{
			// modify the xExtent based on alignment
			float xExtent = dimensions.x - offset.x;
			if(horizontalAlign == FONT_ALIGN_CENTER)
				xExtent *= 0.5f;
			//printf("xExtent: %f - %f = %f\n", dimensions.x, offset.x, xExtent);
					
			// space the sprites accordingly
			for(int e=startSpriteIndex;e<(int)sprites.size();e++)
			{
				sprite = (Sprite*)sprites[e];
				sprite->Translate(Vector3(xExtent, 0.0f, 0.0f));
			}
			startSpriteIndex = (int)sprites.size();
		}
	
		// go to the next line
		if(deprecated) stopUpdating = true;
		offset.x = 0.0f;
		offset.y += (float)fontPtr->GetCommonData().lineHeight;
		numWordsOnLine = 0;
		numLines++;
	} else numWordsOnLine++;
			
	// set the sprites
	for(int e=startIndex;e<index;e++)
	{
		FontGlyph *glyph = fontPtr->GetGlyph(text[e], false);
		if(!glyph) continue;
				
		// add the sprite to the list and set its parameters
		//sprite = batch->AddSprite();
		sprite = new Sprite("");
		batch->AddSprite(sprite);
		TexCoords glyphDims((short)glyph->width, (short)glyph->height);
		TexCoords glyphPos((short)glyph->x, (short)glyph->y);
		sprite->Blit(glyphDims, glyphPos);
		sprite->SetColor(color);
				
		// translate and push the sprite into the batch
		Vector3 spritePosition(position.x + (float)glyph->xOffset + ((float)sprite->GetDimensions().x / 2.0f) + offset.x, position.y + (float)glyph->yOffset + ((float)sprite->GetDimensions().y / 2.0f) + offset.y, 0.0f);
		sprite->Translate(spritePosition);
		sprites.push_back(sprite);
		offset.x += (float)glyph->width;
	}
			
	// add spacing to the offset based on the special character
	switch(specialCharacter)
	{
		case (int)' ':
			offset.x += fontPtr->fixed.x;
			break;
					
		case (int)'\t':
			offset.x += fontPtr->fixed.x * fontPtr->numTabSpaces;
			break;
					
		case (int)'\n':
			// process alignment
			if(horizontalAlign != FONT_ALIGN_LEFT)
			{
				// modify the xExtent based on alignment
				float xExtent = dimensions.x - offset.x;
				if(horizontalAlign == FONT_ALIGN_CENTER)
					xExtent *= 0.5f;
				//printf("xExtent: %f - %f = %f\n", dimensions.x, offset.x, xExtent);
						
				// space the sprites accordingly
				for(int e=startSpriteIndex;e<(int)sprites.size();e++)
				{
					sprite = (Sprite*)sprites[e];
					sprite->Translate(Vector3(xExtent, 0.0f, 0.0f));
				}
				startSpriteIndex = (int)sprites.size();
			}
					
			startSpriteIndex = (int)sprites.size();
			if(deprecated) stopUpdating = true;
			offset.x = 0.0f;
			offset.y += fontPtr->GetCommonData().lineHeight;
			numWordsOnLine = 0;
			numLines++;
			break;
	}
	startIndex = index+1;
}

 

I'm pretty lost at this point... This algorithm nearly works, except if there's only 1 word in the line, then that word becomes right-aligned. Same happens when a newline character is found, and there's some issues with tabbing.



Sponsor:

#2 Vincent_M   Members   -  Reputation: 596

Like
0Likes
Like

Posted 01 March 2013 - 07:19 PM

I rewrote my code for a 3rd or 4th time, but eventually, I think I've got it! For those of you looking at how to implement word-wrap in C-like languages, here's my C++ implementation on how I did it:

void FontString::UpdateText()
	{
		if(!fontPtr) return;
		
		bool nextLine = false;
		bool endLineFound = false;
		float lineWidth = 0.0f;
		int startIndex = 0;
		int endIndex = 0;
		Vector2 offset;
		
		// handle zero width
		if(!GetDimensions().x)
		{
			// process each character
			for(int i=0;i<(int)text.size();i++)
			{
				// handle spacing characters
				switch(text[i])
				{
					case ' ':
					case '\t':
						offset.x += GetGlyphWidth(i);
						continue;
						
					case '\n':
					case '\r':
						return;
				}
				
				// add character and offset
				AddCharacterSprite(i, offset);
				offset.x += GetGlyphWidth(i);
			}
			
			// set dimensions and vertex buffer
			dimensions.x = offset.x;
			dimensions.y = fontPtr->GetCommonData().lineHeight;
			if(vertexBuffer)
			{
				vertexBuffer->GetVertex(0)->position = Vector2(position.x, position.y);
				vertexBuffer->GetVertex(1)->position = Vector2(position.x, position.y) + Vector2(dimensions.x, 0.0f);
				vertexBuffer->GetVertex(2)->position = Vector2(position.x, position.y) + dimensions;
				vertexBuffer->GetVertex(3)->position = Vector2(position.x, position.y) + Vector2(0.0f, dimensions.y);
			}
			return;
		}
		
		// handle text areas with fixed width
		for(int i=0;i<(int)text.size();i++)
		{
			// handle spacing characters
			switch(text[i])
			{
				case '\r':
				case '\n':
					endIndex = i;
					nextLine = true;
					break;
				
				case '\0':
					break;
					
				default:
					lineWidth += GetGlyphWidth(i);
					break;
			}
			
			// check if the end of the line is reached
			if(lineWidth >= GetDimensions().x || i == (text.size()-1))
			{
				// check if at the end of the line
				if(i == text.size()-1)
					endIndex = (int)text.size()-1;
				else {
					// find end index
					switch(i)
					{
						case ' ':
						case '\t':
						case '\n':
						case '\r':
							endIndex = i;
							break;
							
						// roll back to the beginning of the word
						default:
							// look backwards for a spacing character from current spot
							for(int e=i;e>=0;e--)
							{
								// check for spacing characters
								switch(text[e])
								{
									case ' ':
									case '\t':
									case '\n':
									case '\r':
										endIndex = e;
										endLineFound = true;
										break;
								}
								
								// stop searching if end of line character found
								lineWidth -= GetGlyphWidth(e);
								if(endLineFound) break;
							}
							break;
					}
				}
				nextLine = true;
			}
			
			// check if spacing has gone beyond line width
			if(nextLine)
			{
				// set offset based on alignment
				switch((int)horizontalAlign)
				{
					case FONT_ALIGN_LEFT:
						offset.x = 0.0f;
						break;
						
					case FONT_ALIGN_CENTER:
						offset.x = (GetDimensions().x - lineWidth) / 2.0f;
						break;
						
					case FONT_ALIGN_RIGHT:
						offset.x = GetDimensions().x - lineWidth;
						break;
						
					default:
						offset.x = 0.0f;
						break;
				}
				
				// add character sprites
				for(int e=startIndex;e<endIndex;e++)
				{
					AddCharacterSprite(e, offset);
					offset.x += GetGlyphWidth(e);
				}
				
				// reset variables
				lineWidth = 0.0f;
				offset.y += fontPtr->GetCommonData().lineHeight;
				startIndex = endIndex + 1; // skip newline character
				i = startIndex - 1; // set i to startIndex but subtract 1 due to incrementation
				endLineFound = false;
				nextLine = false;
				if(deprecated) break; // stop processing the loop after the line
			}
		}
		
		// calculate the height
		if(sprites.size())
		{
			if(!batch) return;
			SpriteVertices *topVertices = batch->GetVertexListElement(0);
			SpriteVertices *bottomVertices = batch->GetVertexListElement((int)sprites.size()-1);
			
			// find the difference
			if(!topVertices || !bottomVertices) return;
			dimensions.y = bottomVertices->vertex[5].position.y - topVertices->vertex[0].position.y;
		} else
			dimensions.y = 0.0f;
}

 

 

I hope the comments are clear enough on how this works. What I do is loop through each character in an std::string (I'm assuming it's 1 character per element, and not that weird two elements can equal a 16-bit UNICODE-ish character). I assume that you've already loaded a bitmapped font, and GetGlyphWidth(int index) will return the width of that character in pixels. Keep in mind that GetGlyphWidth's "index" parameter refers to the current element index in the string, and not the value of that element.

 

With each character iteration, I add that character's width to the current line's length called lineWidth. Once it's equal or exceeded the margin, I know it's time to find the starting and ending indexes in my string for that line, add and blit sprites between those indices, etc. The issue is, a line break will be found in the middle of the string, most of the time. So, what I do is see if the line break occurred in a whitespace such as newline, tab, space, etc, which means that I'm not in the middle of a word, and I can just set to ending index for that line at line breaking character. If not, I'm in the middle of a word, and I need to use a second loop to roll backward into the string to find the previous whitespace.

 

Once startIndex and endIndex are set, I flag that a new line was found with nextLine, and I proceed to setup the sprites, and reset variables for the next line. After the text is complete, I compute a bounding box for frustum checks, and create a vertex buffer for drawing the box if needed (vertex buffer setup isn't in the code).

 

I really hope this helps some one out!






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS