• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Vincent_M

Wrapping My Head Around Word Wrapping Code...

1 post in this topic

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.

0

Share this post


Link to post
Share on other sites

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!

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0