1. Leonard Ritter
  2. craftlike

Source

craftlike / src / sdlutils.cpp

  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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
#include <cassert>
#include "sdlutils.hpp"
#include <SDL_image.h>

namespace sdl {

////////////////////////////////////////////////////////////////////////////////

SDL_Surface *create_surface(const Vector2i &size) {
	return SDL_CreateRGBSurface(SDL_SWSURFACE, size.x, size.y, 32,
			0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
}

SDL_Surface *load_surface(const std::string &path)
{
    SDL_Surface *surface = IMG_Load(path.c_str());
    if (!surface) {
    	printf("IMG_Load: %s\n",IMG_GetError());
    }
    return surface;
}

SDL_Surface *copy_surface(SDL_Surface *surface)
{
	return SDL_ConvertSurface(surface, surface->format, SDL_SWSURFACE);
}

SDL_Surface *convert_surface(SDL_Surface *surface)
{
	switch(surface->format->BytesPerPixel)
	{
	case 4: {
		if (surface->format->Rmask == 0x000000ff)
			return NULL;
	} // fall-through
	case 3: {
		SDL_Surface *surface_old = surface;

		surface = SDL_CreateRGBSurface(SDL_SWSURFACE, surface_old->w,
				surface_old->h, 32, 0x000000ff, 0x0000ff00,
				0x00ff0000, 0xff000000);

		SDL_BlitSurface(surface_old, NULL, surface, NULL);
		return surface;
	} break;
	case 1: { // 8-bit texture
		SDL_Surface *surface8 = surface;

		surface = SDL_CreateRGBSurface(SDL_SWSURFACE, surface8->w,
				surface8->h, 32, 0x000000ff, 0x0000ff00,
				0x00ff0000, 0xff000000);

		SDL_SetColorKey(surface8, SDL_SRCCOLORKEY, 255);
		SDL_BlitSurface(surface8, NULL, surface, NULL);
		return surface;
	} break;
	default: assert(0); break;
	}
	return NULL;
}

SDL_Surface *convert_replace_surface(SDL_Surface *surface)
{
	SDL_Surface *new_surface = convert_surface(surface);
	if (new_surface) {
		SDL_FreeSurface(surface);
		return new_surface;
	}
	return surface;
}

////////////////////////////////////////////////////////////////////////////////

inline Uint32 add_div2_colors(Uint32 p, Uint32 c) {
	return (((p & 0xff)+(c & 0xff))>>1)
		| ((((p & 0xff00)+(c & 0xff00))>>1) & 0xff00)
		| ((((p & 0xff0000)+(c & 0xff0000))>>1) & 0xff0000)
		| (((p & 0xff000000)>>1)+((c & 0xff000000)>>1) & 0xff000000);
}

bool div2_surface_y(SDL_Surface *surface)
{
	// if this assertion fails, use convert_surface() to convert the surface
	// before passing it to this function.
	assert((surface->format->BytesPerPixel == 4)
		&& (surface->format->Rmask == 0x000000ff));

	int w = surface->w;
	int h = surface->h;
	int h2 = h>>1;
	if (!h2)
		return false;

	Uint32 *dst_pixels = (Uint32 *)surface->pixels;
	Uint32 *src_pixels = dst_pixels;
	int size = w*h2;
	for (int i = 0; i < size; ++i) {
		if (i && !(i % w)) {
			src_pixels += w;
		}
		*dst_pixels++ = add_div2_colors(*src_pixels, *(src_pixels+w));
		src_pixels++;
	}

	surface->h = h2;

	return true;
}

bool div2_surface_x(SDL_Surface *surface)
{
	// if this assertion fails, use convert_surface() to convert the surface
	// before passing it to this function.
	assert((surface->format->BytesPerPixel == 4)
		&& (surface->format->Rmask == 0x000000ff));

	int w = surface->w;
	int h = surface->h;
	int w2 = w>>1;
	if (!w2)
		return false;

	Uint32 *src_pixels = (Uint32 *)surface->pixels;
	Uint32 *dst_pixels = src_pixels;
	int size = w*h;
	Uint32 c;
	while (size--) {
		if (size%2) {
			c = *src_pixels++;
		} else {
			*dst_pixels++ = add_div2_colors(*src_pixels++,c);
		}
	}

	surface->w = w2;

	return true;
}


////////////////////////////////////////////////////////////////////////////////

bool div2_surface(SDL_Surface *surface)
{
	if (!div2_surface_y(surface))
		return false;
	return div2_surface_x(surface);
}

////////////////////////////////////////////////////////////////////////////////

void flipxy_surface(SDL_Surface *surface)
{
	int w = surface->w;
	int h = surface->h;
	int size = w*h;
	// need a temporary buffer for flipping - wish we didn't have to
	Uint32 *src_pixels = new Uint32[size];
	Uint32 *dst_pixels = (Uint32 *)surface->pixels;
	// make an original copy because we're going to modify the destination
	memcpy(src_pixels, dst_pixels, sizeof(Uint32) * size);
	for (int y = 0; y < h; ++y) {
		for (int x = 0; x < w; ++x) {
			Uint32 p = src_pixels[y*w + x];
			printf("w=%i h=%i x=%i y=%i p=%08x\n", w, h, x, y, p);
			dst_pixels[x*h + y] = p;
		}
	}
	// delete the temporary buffer
	delete[] src_pixels;
	surface->w = h;
	surface->h = w;
}

////////////////////////////////////////////////////////////////////////////////

uimath::Vector2i texture2d_image(gl::Texture2D &texture,
		const std::string &path, bool mipmapped/* = false*/)
{
    SDL_Surface *surface = load_surface(path);
    if (!surface) return uimath::Vector2i(0,0);
	surface = convert_replace_surface(surface);
	uimath::Vector2i size(surface->w, surface->h);
	if (mipmapped)
		texture2d_mipmap_image(texture, surface);
	else
		texture2d_image(texture, surface, 0);
    SDL_FreeSurface(surface);
    return size;
}

void texture2d_mipmap_image(gl::Texture2D &texture,
							SDL_Surface *surface)
{
	assert(surface);
	int level = 0;
	texture2d_image(texture, surface, level++);
	surface = copy_surface(surface);
	while (div2_surface(surface)) {
		texture2d_image(texture, surface, level);
		level++;
	}
	SDL_FreeSurface(surface);
}

void texture2d_image(gl::Texture2D &texture,
		SDL_Surface *surface, GLint level/* = 0*/)
{
	// if this assertion fails, use convert_surface() to convert the surface
	// before passing it to this function.
	assert((surface->format->BytesPerPixel == 4)
		&& (surface->format->Rmask == 0x000000ff));
	texture.image(level, 4,
		surface->w,
		surface->h,
		0, GL_RGBA,
		GL_UNSIGNED_BYTE, surface->pixels);
}

////////////////////////////////////////////////////////////////////////////////

FontMap::FontMap()
	: vertical_run(0), max_glyph_width(0)
{
}

void FontMap::load(const std::string &path, int glyph_height)
{
	glyphs.clear();
    SDL_Surface *surface = load_surface(path);
    if (!surface) return;
    assert(surface->format->BytesPerPixel == 1);
    if (vertical_run <= 0)
    	vertical_run = glyph_height;
    uv_scalar = Vector2f(1.0f/surface->w, 1.0f/surface->h);
	max_glyph_width = 0;

    Recti rc_glyph(0,0,0,glyph_height);
    unsigned char *pixels = (unsigned char *)surface->pixels;
    while (rc_glyph.p1.y < surface->h) {
    	rc_glyph.p1.x = rc_glyph.p2.x = 0;
		for (int x = 0; x < surface->w; ++x) {
			unsigned char idx = pixels[rc_glyph.p1.y*surface->pitch + x];
			rc_glyph.p2.x = x;
			if (idx == ColorCmdNextGlyph) {
				max_glyph_width = std::max(max_glyph_width, rc_glyph.width());
				glyphs.push_back(rc_glyph);
				rc_glyph.p1.x = x+1;
			}
			else if (idx == ColorCmdNextRow) {
				max_glyph_width = std::max(max_glyph_width, rc_glyph.width());
				glyphs.push_back(rc_glyph);
				break;
			}
			if (glyphs.size() == GlyphCount)
				break;
		}
		if (glyphs.size() == GlyphCount)
			break;
		rc_glyph.set_y(rc_glyph.p1.y+glyph_height);
    }

    assert(glyphs.size() == GlyphCount);

	surface = convert_replace_surface(surface);
	texture2d_image(texture, surface, 0);
	texture.filter_min(false);
	texture.filter_mag(false);
	texture.wrap_clamp_st();
    SDL_FreeSurface(surface);
}

TextLayout::TextLayout()
{
	valid = false;
	font = NULL;
	color = Color4c(255,255,255,255);
	flags = 0;
}

static const Color4c shadow_colors[] = {
	Color4c(0,0,0,0xa0),
	Color4c(0,0,0,0xa0),
	Color4c(0,0,0,0xa0),
	Color4c(0,0,0,0xa0),
};

void TextLayout::update()
{
	if (valid)
		return;
	lines.clear();
	assert(font);
	cursor = origin;
	Line line;
	for (int i = 0; i < text.size(); ++i) {
		char c = text[i];
		if (c == '\n') {
			cursor.x = origin.x;
			cursor.y += font->vertical_run;
			if (lines.empty()) {
				bounds = line.bounds;
			} else {
				bounds.add(line.bounds);
			}
			lines.push_back(line);
			line.glyphs.clear();
		}
		int index = (int)c - FontMap::GlyphBaseIndex;
		if ((index < 0)||(index > FontMap::GlyphCount))
			continue;
		Recti rc = font->glyphs[index];
		int w = rc.width(); int h = rc.height();
		int ofsx = 0;
		if (flags & FlagFixedWidth) {
			ofsx = (font->max_glyph_width - w) / 2;
		}
		Glyph glyph;
		glyph.rect = rc;
		glyph.origin = Vector2i(ofsx+cursor.x, cursor.y);

		Recti glyph_bounds(glyph.origin.x, glyph.origin.y, glyph.rect.width(),
				glyph.rect.height());
		if (!i) {
			line.bounds = glyph_bounds;
		} else {
			line.bounds.add(glyph_bounds);
		}
		line.glyphs.push_back(glyph);

		if (flags & FlagFixedWidth) {
			cursor.x += font->max_glyph_width;
		} else {
			cursor.x += w + 1;
		}
	}

	if (lines.empty()) {
		bounds = line.bounds;
	} else {
		bounds.add(line.bounds);
	}
	lines.push_back(line);
	valid = true;
}

void TextLayout::bind()
{
	font->texture.bind();
}

void TextLayout::draw(gl::TriBuffer<true,true> &tb)
{
	update();
	assert(font);
	for (int i = 0; i < get_line_count(); ++i) {
		draw_line(tb, i);
	}
}

void TextLayout::draw_line(gl::TriBuffer<true,true> &tb, int index)
{
	update();
	assert(font);
	float fx = font->uv_scalar.x;
	float fy = font->uv_scalar.y;
	Line &line = lines[index];
	for (GlyphArray::iterator glyph = line.glyphs.begin();
			glyph != line.glyphs.end(); ++glyph) {

		Recti rc = glyph->rect;
		int w = rc.width(); int h = rc.height();
		int ofsx = 0;
		if (flags & FlagFixedWidth) {
			ofsx = (font->max_glyph_width - w) / 2;
		}
		Vector2i pos = glyph->origin;
		const Vector3f vertices[] = {
			Vector3f(pos.x, pos.y, 0),
			Vector3f(pos.x+w, pos.y, 0),
			Vector3f(pos.x+w, pos.y+h, 0),
			Vector3f(pos.x, pos.y+h, 0),
		};
		const Vector2f texcoords[] = {
			Vector2f(rc.p1.x * fx, rc.p1.y * fy),
			Vector2f(rc.p2.x * fx, rc.p1.y * fy),
			Vector2f(rc.p2.x * fx, rc.p2.y * fy),
			Vector2f(rc.p1.x * fx, rc.p2.y * fy),
		};
		const Color4c colors[] = {
			color, color, color, color,
		};
		if (flags & FlagShadowed) {
			const Vector3f shadow_vertices[] = {
				Vector3f(1+pos.x, 1+pos.y, 0),
				Vector3f(1+pos.x+w, 1+pos.y, 0),
				Vector3f(1+pos.x+w, 1+pos.y+h, 0),
				Vector3f(1+pos.x, 1+pos.y+h, 0),
			};
			tb.add_quad(shadow_vertices, texcoords, shadow_colors);
		}
		tb.add_quad(vertices, texcoords, colors);
	}
}

int TextLayout::get_line_count()
{
	update();
	return (int)lines.size();
}

void TextLayout::set_font(FontMap *font)
{
	this->font = font;
	valid = false;
}

void TextLayout::set_color(const Color4c &color)
{
	this->color = color;
	valid = false;
}

void TextLayout::set_flags(unsigned int flags)
{
	this->flags = flags;
	valid = false;
}

void TextLayout::add_flags(unsigned int flags)
{
	this->flags |= flags;
	valid = false;
}

Recti TextLayout::get_line_bounds(int index)
{
	update();
	return lines[index].bounds;
}

Recti TextLayout::get_bounds()
{
	update();
	return bounds;
}

Vector2i TextLayout::get_cursor()
{
	update();
	return cursor;
}

void TextLayout::set_origin(const Vector2i &origin)
{
	this->origin = origin;
	valid = false;
}

void TextLayout::set_text(const std::string &text)
{
	this->text = text;
	valid = false;
}

std::string TextLayout::get_text() const
{
	return this->text;
}

FontMap *TextLayout::get_font() const
{
	return this->font;
}

////////////////////////////////////////////////////////////////////////////////

void NinePatch::load(const std::string &path)
{
    SDL_Surface *surface = load_surface(path);
    if (!surface) return;
    assert(surface->format->BytesPerPixel == 1);
    SDL_SetColorKey(surface, SDL_SRCCOLORKEY, 255);

    unsigned char *pixels = (unsigned char *)surface->pixels;
    grid.clear();
    int i = 0;
    // look for grid markers
    for (int x = 0; x < surface->w; ++x) {
        unsigned char idx = pixels[x];
        if ((i == 0) && (idx == ColorCmdCenter)) {
            grid[i++].x = x-1;
        } else if ((i == 1) && (idx == ColorCmdCorner)) {
            grid[i].x = x-1;
            break;
        }
    }
    
    i = 0;
    for (int y = 0; y < surface->h; ++y) {
        unsigned char idx = pixels[y * surface->pitch];
        if ((i == 0) && (idx == ColorCmdCenter)) {
            grid[i++].y = y-1;
        } else if ((i == 1) && (idx == ColorCmdCorner)) {
            grid[i].y = y-1;
            break;
        }
    }
    
    SDL_Surface *cropped = create_surface(Vector2i(surface->w-1, surface->h-1));
    SDL_FillRect(cropped, NULL, 0x00000000);
    
    size = Vector2i(cropped->w, cropped->h);
    Vector2f uv = Vector2f(1.0f/size.x, 1.0f/size.y);

    grid_uv.p1 = Vector2f(uv.x * grid.p1.x, uv.y * grid.p1.y);
    grid_uv.p2 = Vector2f(uv.x * grid.p2.x, uv.y * grid.p2.y);

    SDL_Rect src_rc;
    src_rc.x = src_rc.y = 1;
    src_rc.w = cropped->w; 
    src_rc.h = cropped->h;;
    SDL_Rect dst_rc = src_rc;
    dst_rc.x = dst_rc.y = 0;
    SDL_BlitSurface(surface, &src_rc, cropped, &dst_rc);
    SDL_FreeSurface(surface);
    
	texture2d_image(texture, cropped, 0);
	texture.filter_min(false);
	texture.filter_mag(false);
	texture.wrap_clamp_st();
}

Recti NinePatch::get_grid() const
{
    return grid;
}

Recti NinePatch::get_margin() const
{
	Recti result;
	result.p1 = grid.p1;
	result.p2 = size - grid.p2;
	return result;
}

void NinePatch::draw(const Recti &target)
{
    gl::TriBuffer<true,false> tb;

    Vector2f vgrid[4] = {
    		target.p1, target.p1 + grid.p1, target.p2 - (size - grid.p2), target.p2
    };
    Vector2f uvgrid[4] = {
    		Vector2f(0,0), grid_uv.p1, grid_uv.p2, Vector2f(1,1)
    };

    for (int y = 0; y < 3; ++y) {
    	for (int x = 0; x < 3; ++x) {
    		const Vector3f vertices[] = {
    			Vector3f(vgrid[x].x, vgrid[y].y, 0),
				Vector3f(vgrid[x+1].x, vgrid[y].y, 0),
				Vector3f(vgrid[x+1].x, vgrid[y+1].y, 0),
				Vector3f(vgrid[x].x, vgrid[y+1].y, 0),
    		};
    		const Vector2f texcoords[] = {
    			Vector2f(uvgrid[x].x, uvgrid[y].y),
    			Vector2f(uvgrid[x+1].x, uvgrid[y].y),
    			Vector2f(uvgrid[x+1].x, uvgrid[y+1].y),
    			Vector2f(uvgrid[x].x, uvgrid[y+1].y),
    		};
    		tb.add_quad(vertices, texcoords);
    	}
    }

    gl::Texture2D::enable();
    texture.bind();
    tb.draw();
}

////////////////////////////////////////////////////////////////////////////////

} // namespace sdl