aboutsummaryrefslogtreecommitdiff
path: root/engines/startrek/graphics.cpp
blob: 5c6a1441b6e17a9d5993b47b0de03f97b7ac8e59 (plain)
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "startrek/common.h"
#include "startrek/graphics.h"

#include "common/algorithm.h"
#include "common/config-manager.h"
#include "common/events.h"
#include "common/rendermode.h"
#include "graphics/cursorman.h"
#include "graphics/palette.h"
#include "graphics/surface.h"

namespace StarTrek {

Graphics::Graphics(StarTrekEngine *vm) : _vm(vm), _egaMode(false) {
	_font = nullptr;
	_egaData = nullptr;
	_lutData = nullptr;

	for (int i = 0; i < 32; ++i) {
		_sprites[i] = nullptr;
		_pushedSprites[i] = nullptr;
	}

	_screenRect = Common::Rect(SCREEN_WIDTH, SCREEN_HEIGHT);

	if (ConfMan.hasKey("render_mode"))
		_egaMode = (Common::parseRenderMode(ConfMan.get("render_mode").c_str()) == Common::kRenderEGA) && (_vm->getGameType() != GType_STJR) && !(_vm->getFeatures() & GF_DEMO);

	if (_vm->getGameType() == GType_ST25 && _vm->getPlatform() == Common::kPlatformDOS)
		_font = new Font(_vm);

	_numSprites = 0;
	_pushedNumSprites = -1;

	_palData = new byte[256 * 3];
	_lutData = new byte[256 * 3];

	memset(_palData, 0, 256 * 3);
	memset(_lutData, 0, 256 * 3);

	_paletteFadeLevel = 0;
	_mouseLocked = false;
	_mouseToBeShown = false;
	_mouseToBeHidden = false;
	_mouseWarpX = -1;
	_mouseWarpY = -1;

	setMouseBitmap(loadBitmap("pushbtn"));
	CursorMan.showMouse(true);
}

Graphics::~Graphics() {
	delete[] _egaData;
	delete[] _palData;
	delete[] _lutData;

	delete _font;
}


void Graphics::setBackgroundImage(SharedPtr<Bitmap> bitmap) {
	_backgroundImage = SharedPtr<Bitmap>(new Bitmap(*bitmap));
}

void Graphics::drawBitmapToBackground(const Common::Rect &origRect, const Common::Rect &drawRect, SharedPtr<Bitmap> bitmap) {
	byte *dest = _backgroundImage->pixels + drawRect.top * SCREEN_WIDTH + drawRect.left;
	byte *src = bitmap->pixels + (drawRect.left - origRect.left)
	            + (drawRect.top - origRect.top) * bitmap->width;

	for (int y = drawRect.top; y < drawRect.bottom; y++) {
		for (int x = drawRect.left; x < drawRect.right; x++) {
			byte b = *src;

			if (b != 0)
				*dest = b;

			src++;
			dest++;
		}

		src += bitmap->width - drawRect.width();
		dest += SCREEN_WIDTH - drawRect.width();
	}
}

void Graphics::fillBackgroundRect(const Common::Rect &rect, byte color) {
	byte *dest = _backgroundImage->pixels + rect.top * SCREEN_WIDTH + rect.left;
	for (int y = rect.top; y < rect.bottom; y++) {
		memset(dest, color, rect.width());
		dest += SCREEN_WIDTH;
	}
}

byte *Graphics::getBackgroundPixels() {
	return _backgroundImage->pixels;
}

byte *Graphics::lockScreenPixels() {
	return (byte *)_vm->_system->lockScreen()->getPixels();
}

void Graphics::unlockScreenPixels() {
	_vm->_system->unlockScreen();
}

void Graphics::clearScreenAndPriBuffer() {
	Common::fill(_priData, _priData + sizeof(_priData), 0);

	::Graphics::Surface *surface = _vm->_system->lockScreen();
	surface->fillRect(_screenRect, 0);
	_vm->_system->unlockScreen();
	_vm->_system->updateScreen();
	_vm->_system->delayMillis(10);
}

void Graphics::loadPalette(const Common::String &paletteName) {
	// Set the palette from a PAL file
	Common::String palFile = paletteName + ".PAL";
	Common::String lutFile = paletteName + ".LUT";

	SharedPtr<FileStream> palStream = _vm->loadFile(palFile.c_str());
	palStream->read(_palData, 256 * 3);

	// Load LUT file
	SharedPtr<FileStream> lutStream = _vm->loadFile(lutFile.c_str());

	lutStream->read(_lutData, 256);
}

void Graphics::copyRectBetweenBitmaps(Bitmap *destBitmap, int destX, int destY, Bitmap *srcBitmap, int srcX, int srcY, int width, int height) {
	byte *src = srcBitmap->pixels + srcX + srcY * srcBitmap->width;
	byte *dest = destBitmap->pixels + destX + destY * destBitmap->width;

	for (int y = 0; y < height; y++) {
		memcpy(dest, src, width);
		src += srcBitmap->width;
		dest += destBitmap->width;
	}
}

void Graphics::fadeinScreen() {
	while (_paletteFadeLevel <= 100) {
		TrekEvent event;
		_vm->waitForNextTick();

		setPaletteFadeLevel(_palData, _paletteFadeLevel);
		_paletteFadeLevel += 10;
	}

	_paletteFadeLevel = 100;
}

void Graphics::fadeoutScreen() {
	while (_paletteFadeLevel >= 0) {
		TrekEvent event;
		_vm->waitForNextTick();

		setPaletteFadeLevel(_palData, _paletteFadeLevel);
		_paletteFadeLevel -= 10;
	}

	_paletteFadeLevel = 0;
}

void Graphics::setPaletteFadeLevel(byte *palData, int fadeLevel) {
	byte palBuffer[256 * 3];

	int multiplier = (fadeLevel << 8) / 100;

	for (uint16 i = 0; i < 256 * 3; i++) {
		palBuffer[i] = (palData[i] * multiplier) >> 8;

		// Expand color components
		if (_vm->getPlatform() == Common::kPlatformDOS || _vm->getPlatform() == Common::kPlatformMacintosh)
			palBuffer[i] <<= 2;
	}

	_vm->_system->getPaletteManager()->setPalette(palBuffer, 0, 256);

	// FIXME: this isn't supposed to flush changes to graphics, only palettes.
	// Might not matter...
	_vm->_system->updateScreen();
	_vm->_system->delayMillis(10);
}

void Graphics::incPaletteFadeLevel() {
	if (_paletteFadeLevel < 100) {
		_paletteFadeLevel += 10;
		setPaletteFadeLevel(_palData, _paletteFadeLevel);
	}
}

void Graphics::decPaletteFadeLevel() {
	if (_paletteFadeLevel > 0) {
		_paletteFadeLevel -= 10;
		setPaletteFadeLevel(_palData, _paletteFadeLevel);
	}
}


void Graphics::loadPri(const Common::String &priFile) {
	SharedPtr<FileStream> priStream = _vm->loadFile(priFile + ".pri");
	priStream->read(_priData, SCREEN_WIDTH * SCREEN_HEIGHT / 2);
}

void Graphics::clearPri() {
	memset(_priData, 0, sizeof(_priData));
}

void Graphics::setPri(byte val) {
	memset(_priData, val, sizeof(_priData));
}

byte Graphics::getPriValue(int x, int y) {
	assert(_screenRect.contains(x, y));

	int priOffset = y * SCREEN_WIDTH + x;
	byte b = _priData[priOffset / 2];
	if ((priOffset % 2) == 1)
		return b & 0xf;
	else
		return b >> 4;
}

SharedPtr<Bitmap> Graphics::loadBitmap(Common::String basename) {
	return SharedPtr<Bitmap>(new Bitmap(_vm->loadFile(basename + ".BMP")));
}

Common::Point Graphics::getMousePos() {
	if (_mouseWarpX != -1)
		return Common::Point(_mouseWarpX, _mouseWarpY);

	return _vm->_system->getEventManager()->getMousePos();
}

void Graphics::setMouseBitmap(SharedPtr<Bitmap> bitmap) {
	_mouseBitmap = bitmap;

	if (_mouseLocked)
		_lockedMouseSprite.setBitmap(_mouseBitmap);
}

void Graphics::lockMousePosition(int16 x, int16 y) {
	if (_mouseLocked) {
		if (x != _lockedMouseSprite.pos.x || y != _lockedMouseSprite.pos.y) {
			_lockedMouseSprite.pos.x = x;
			_lockedMouseSprite.pos.y = y;
			_lockedMouseSprite.bitmapChanged = true;
		}
		return;
	}

	_mouseLocked = true;
	_mouseToBeHidden = true;
	_mouseToBeShown = false;

	_lockedMouseSprite = Sprite();
	_lockedMouseSprite.setBitmap(_mouseBitmap);
	_lockedMouseSprite.drawPriority = 15;
	_lockedMouseSprite.drawPriority2 = 16;
	_lockedMouseSprite.pos.x = x;
	_lockedMouseSprite.pos.y = y;

	addSprite(&_lockedMouseSprite);
}

void Graphics::unlockMousePosition() {
	if (!_mouseLocked)
		return;

	_mouseLocked = false;
	_mouseToBeShown = true;
	_mouseToBeHidden = false;

	_lockedMouseSprite.dontDrawNextFrame();
	drawAllSprites(false);
	delSprite(&_lockedMouseSprite);
}

SharedPtr<Bitmap> Graphics::getMouseBitmap() {
	return _mouseBitmap;
}

void Graphics::warpMouse(int16 x, int16 y) {
	_mouseWarpX = x;
	_mouseWarpY = y;
}

void Graphics::drawSprite(const Sprite &sprite, ::Graphics::Surface *surface) {
	int left = sprite.drawX;
	int top = sprite.drawY;
	int right = left + sprite.bitmap->width;
	int bottom = top + sprite.bitmap->height;
	drawSprite(sprite, surface, Common::Rect(left, top, right, bottom));
}

// rect is the portion of the sprite to update. It must be entirely contained within the
// sprite's actual, full rectangle.
void Graphics::drawSprite(const Sprite &sprite, ::Graphics::Surface *surface, const Common::Rect &rect, int rectLeft, int rectTop) {
	Common::Rect spriteRect = Common::Rect(sprite.drawX, sprite.drawY,
	        sprite.drawX + sprite.bitmap->width, sprite.drawY + sprite.bitmap->height);

	assert(_screenRect.contains(rect));
	assert(spriteRect.contains(rect));

	byte *dest = (byte *)surface->getPixels() + (rect.top - rectTop) * SCREEN_WIDTH + (rect.left - rectLeft);

	switch (sprite.drawMode) {
	case 0: { // Normal sprite
		byte *src = sprite.bitmap->pixels + (rect.left - sprite.drawX)
		            + (rect.top - sprite.drawY) * sprite.bitmap->width;

		int priOffset = rect.top * SCREEN_WIDTH + rect.left;

		for (int y = rect.top; y < rect.bottom; y++) {
			for (int x = rect.left; x < rect.right; x++) {
				byte priByte = _priData[priOffset / 2];
				byte bgPriority;
				if ((priOffset % 2) == 1)
					bgPriority = priByte & 0xf;
				else
					bgPriority = priByte >> 4;
				priOffset++;

				byte b = *src++;
				if (b == 0 || sprite.drawPriority < bgPriority) {
					dest++;
					continue;
				}
				*dest++ = b;
			}

			src       += sprite.bitmap->width - rect.width();
			dest      += SCREEN_WIDTH - rect.width();
			priOffset += SCREEN_WIDTH - rect.width();
		}
		break;
	}

	case 1: // Invisible
		break;

	case 2: { // Normal sprite with darkened background for "transparent" pixels (and no priority)
		byte *src = sprite.bitmap->pixels + (rect.left - sprite.drawX)
		            + (rect.top - sprite.drawY) * sprite.bitmap->width;

		for (int y = rect.top; y < rect.bottom; y++) {
			for (int x = rect.left; x < rect.right; x++) {
				byte b = *src;

				if (b == 0) // Transparent (darken the pixel)
					*dest = _lutData[*dest];
				else // Solid color
					*dest = b;

				src++;
				dest++;
			}

			src += sprite.bitmap->width - rect.width();
			dest += SCREEN_WIDTH - rect.width();
		}

		break;
	}

	case 3: { // Text
		// The sprite's "bitmap" is not actually a bitmap, but instead the list of
		// characters to display.

		// Units of this rect are "characters" instead of pixels. This contains all
		// characters to be drawn.
		Common::Rect rectangle1;

		rectangle1.left   = (rect.left   - sprite.drawX) / 8;
		rectangle1.top    = (rect.top    - sprite.drawY) / 8;
		rectangle1.right  = (rect.right  - sprite.drawX + 7) / 8;
		rectangle1.bottom = (rect.bottom - sprite.drawY + 7) / 8;

		int drawWidth = rectangle1.width();
		int drawHeight = rectangle1.height();

		dest = (byte *)surface->getPixels() + sprite.drawY * SCREEN_WIDTH + sprite.drawX
		       + rectangle1.top * 8 * SCREEN_WIDTH + rectangle1.left * 8;

		byte *src = sprite.bitmap->pixels + rectangle1.top * sprite.bitmap->width / 8 + rectangle1.left;

		for (int y = 0; y < drawHeight; y++) {
			for (int x = 0; x < drawWidth; x++) {
				byte c = *src;

				int textColor;
				if (c >= 0x10 && c <= 0x1A) // Border characters
					textColor = 0xb3;
				else
					textColor = sprite.textColor;

				byte *fontData = _font->getCharData(c);

				for (int i = 0; i < 8; i++) {
					for (int j = 0; j < 8; j++) {
						byte b = *fontData;

						if (b == 0) // Transparent: use lookup table to darken this pixel
							*dest = _lutData[*dest];
						else if (b == 0x78) // Inner part of character
							*dest = textColor;
						else // Outline of character
							*dest = b;

						fontData++;
						dest++;
					}
					dest += SCREEN_WIDTH - 8;
				}

				dest -= (SCREEN_WIDTH * 8 - 8);
				src++;
			}

			src += (sprite.bitmap->width / 8) - drawWidth;
			dest += (SCREEN_WIDTH * 8) - drawWidth * 8;

		}

		break;
	}

	default:
		error("drawSprite: draw mode %d invalid", sprite.drawMode);
		break;
	}
}

/**
 * Compare 2 sprites for the purpose of sorting them by layer before drawing.
 * FIXME: Original returned an int, not a bool. This may affect the stability of the sort...
 */
bool compareSpritesByLayer(Sprite *s1, Sprite *s2) {
	if (s1->drawPriority != s2->drawPriority)
		return s1->drawPriority < s2->drawPriority;
	if (s1->drawPriority2 != s2->drawPriority2)
		return s1->drawPriority2 < s2->drawPriority2;
	if (s1->pos.y != s2->pos.y)
		return s1->pos.y < s2->pos.y;
	return s1->pos.x < s2->pos.x;
}

void Graphics::drawAllSprites(bool updateScreenFlag) {
	// TODO: different video modes?

	if (_numSprites != 0) {
		// Sort sprites by layer
		Common::sort(_sprites, _sprites + _numSprites, &compareSpritesByLayer);

		// Update sprite rectangles
		for (int i = 0; i < _numSprites; i++) {
			Sprite *spr = _sprites[i];
			Common::Rect rect;

			rect.left   = spr->pos.x - spr->bitmap->xoffset;
			rect.top    = spr->pos.y - spr->bitmap->yoffset;
			rect.right  = rect.left + spr->bitmap->width;
			rect.bottom = rect.top + spr->bitmap->height;

			spr->drawX = rect.left;
			spr->drawY = rect.top;

			spr->drawRect = rect.findIntersectingRect(_screenRect);

			if (!spr->drawRect.isEmpty()) { // At least partly on-screen
				if (spr->lastDrawRect.left < spr->lastDrawRect.right) {
					// If the sprite's position is close to where it was last time it was
					// drawn, combine the two rectangles and redraw that whole section.
					// Otherwise, redraw the old position and current position separately.
					rect = spr->drawRect.findIntersectingRect(spr->lastDrawRect);

					if (rect.isEmpty())
						spr->rect2Valid = 0;
					else {
						spr->rectangle2 = spr->drawRect;
						spr->rectangle2.extend(spr->lastDrawRect);
						spr->rect2Valid = 1;
					}
				} else {
					spr->rectangle2 = spr->drawRect;
					spr->rect2Valid = 1;
				}

				spr->isOnScreen = 1;
			} else { // Off-screen
				spr->rect2Valid = 0;
				spr->isOnScreen = 0;
			}
		}

		// Determine what portions of the screen need to be updated
		Common::Rect dirtyRects[MAX_SPRITES * 2];
		int numDirtyRects = 0;

		for (int i = 0; i < _numSprites; i++) {
			Sprite *spr = _sprites[i];

			if (spr->bitmapChanged) {
				if (spr->isOnScreen) {
					if (spr->rect2Valid) {
						dirtyRects[numDirtyRects++] = spr->rectangle2;
					} else {
						dirtyRects[numDirtyRects++] = spr->drawRect;
						dirtyRects[numDirtyRects++] = spr->lastDrawRect;
					}
				} else {
					dirtyRects[numDirtyRects++] = spr->lastDrawRect;
				}
			}
		}

		// Redraw the background on every dirty rectangle
		const ::Graphics::PixelFormat format = ::Graphics::PixelFormat::createFormatCLUT8();
		::Graphics::Surface surface;
		surface.create(SCREEN_WIDTH, SCREEN_HEIGHT, format);

		for (int i = 0; i < numDirtyRects; i++) {
			Common::Rect &r = dirtyRects[i];
			if (r.width() == 0 || r.height() == 0)
				continue;

			int offset = r.top * SCREEN_WIDTH + r.left;
			surface.copyRectToSurface(_backgroundImage->pixels + offset, SCREEN_WIDTH, r.left, r.top, r.width(), r.height());
		}

		// For each sprite, merge the rectangles that overlap with it and redraw the sprite.
		for (int i = 0; i < _numSprites; i++) {
			Sprite *spr = _sprites[i];

			if (!spr->field16 && spr->isOnScreen) {
				bool mustRedrawSprite = false;
				Common::Rect rect2;

				for (int j = 0; j < numDirtyRects; j++) {
					Common::Rect rect1 = spr->drawRect.findIntersectingRect(dirtyRects[j]);

					if (rect1.width() != 0 && rect1.height() != 0) {
						if (mustRedrawSprite)
							rect2.extend(rect1);
						else
							rect2 = rect1;
						mustRedrawSprite = true;
					}
				}

				if (mustRedrawSprite)
					drawSprite(*spr, &surface, rect2);
			}

			spr->field16 = false;
			spr->bitmapChanged = false;
			spr->lastDrawRect = spr->drawRect;
		}

		// Copy dirty rects to screen
		for (int j = 0; j < numDirtyRects; j++) {
			Common::Rect &r = dirtyRects[j];
			if (r.width() == 0 || r.height() == 0)
				continue;

			int offset = r.left + r.top * SCREEN_WIDTH;
			_vm->_system->copyRectToScreen((byte *)surface.getPixels() + offset, SCREEN_WIDTH, r.left, r.top, r.width(), r.height());
		}

		surface.free();
	}

	if (updateScreenFlag)
		this->updateScreen();
}

void Graphics::drawAllSpritesInRectToSurface(const Common::Rect &rect, ::Graphics::Surface *surface) {
	surface->copyFrom(*_vm->_system->lockScreen());
	_vm->_system->unlockScreen();

	for (int i = 0; i < _numSprites; i++) {
		Sprite *sprite = _sprites[i];
		if (!sprite->isOnScreen)
			continue;

		Common::Rect intersect = rect.findIntersectingRect(sprite->drawRect);
		if (!intersect.isEmpty())
			drawSprite(*sprite, surface, intersect);
	}
}

void Graphics::forceDrawAllSprites(bool updateScreenFlag) {
	for (int i = 0; i < _numSprites; i++)
		_sprites[i]->bitmapChanged = true;
	drawAllSprites(updateScreenFlag);
}

void Graphics::updateScreen() {
	// Check if there are any pending updates to the mouse.
	if (_mouseBitmap != _mouseBitmapLastFrame) {
		_mouseBitmapLastFrame = _mouseBitmap;
		_vm->_system->setMouseCursor(_mouseBitmap->pixels, _mouseBitmap->width, _mouseBitmap->height, _mouseBitmap->xoffset, _mouseBitmap->yoffset, 0);
	}
	if (_mouseToBeShown) {
		CursorMan.showMouse(true);
		_mouseToBeShown = false;
	} else if (_mouseToBeHidden) {
		CursorMan.showMouse(false);
		_mouseToBeHidden = false;
	}

	if (_mouseWarpX != -1) {
		_vm->_system->warpMouse(_mouseWarpX, _mouseWarpY);
		_mouseWarpX = -1;
		_mouseWarpY = -1;
	}

	_vm->_system->updateScreen();
	_vm->_system->delayMillis(10);
}

Sprite *Graphics::getSpriteAt(int16 x, int16 y) {
	for (int i = _numSprites - 1; i >= 0; i--) {
		Sprite *sprite = _sprites[i];

		if (sprite == &_lockedMouseSprite)
			continue;
		if (sprite->drawMode == 1) // Invisible
			continue;

		if (sprite->drawRect.contains(Common::Point(x, y))) {
			if (sprite->drawMode == 2 || sprite->drawMode == 3) // Button or text
				return sprite;

			// For draw mode 0 only, check that we're not clicking on a transparent part.
			int16 relX = x - sprite->drawX;
			int16 relY = y - sprite->drawY;
			byte pixel = sprite->bitmap->pixels[relY * sprite->bitmap->width + relX];
			if (pixel != 0)
				return sprite;
		}
	}

	return nullptr;
}

void Graphics::addSprite(Sprite *sprite) {
	if (_numSprites >= MAX_SPRITES)
		error("addSprite: too many sprites");

	// Initialize some fields
	sprite->drawMode = 0;
	sprite->field8 = "";
	sprite->field16 = false;
	sprite->bitmapChanged = true; // FIXME (delete this later?)

	sprite->lastDrawRect.top = -1;
	sprite->lastDrawRect.left = -1;
	sprite->lastDrawRect.bottom = -2;
	sprite->lastDrawRect.right = -2;

	_sprites[_numSprites++] = sprite;
}

void Graphics::delSprite(Sprite *sprite) {
	for (int i = 0; i < _numSprites; i++) {
		if (sprite != _sprites[i])
			continue;

		_numSprites--;
		_sprites[i] = _sprites[_numSprites];
		return;
	}

	error("delSprite: sprite not in list");
}

void Graphics::pushSprites() {
	if (_pushedNumSprites != -1)
		error("Tried to push sprites more than once");
	_pushedNumSprites = _numSprites;
	memcpy(_pushedSprites, _sprites, sizeof(_sprites));

	_numSprites = 0;
}

void Graphics::popSprites() {
	if (_pushedNumSprites == -1)
		error("Tried to pop sprites without a prior push");
	_numSprites = _pushedNumSprites;
	memcpy(_sprites, _pushedSprites, sizeof(_sprites));

	_pushedNumSprites = -1;
}

byte *Graphics::getFontGfx(char c) {
	return _font->getCharData(c & 0xff);
}


void Graphics::copyBackgroundScreen() {
	drawDirectToScreen(_backgroundImage);
}

void Graphics::drawDirectToScreen(SharedPtr<Bitmap> bitmap) {
	_vm->_system->copyRectToScreen(bitmap->pixels, bitmap->width, bitmap->xoffset, bitmap->yoffset, bitmap->width, bitmap->height);
}


void Graphics::loadEGAData(const char *filename) {
	// Load EGA palette data
	if (!_egaMode)
		return;

	if (!_egaData)
		_egaData = new byte[256];

	SharedPtr<FileStream> egaStream = _vm->loadFile(filename);
	egaStream->read(_egaData, 256);
}

void Graphics::drawBackgroundImage(const char *filename) {
	// Draw an stjr BGD image (palette built-in)

	SharedPtr<FileStream> imageStream = _vm->loadFile(filename);
	byte *palette = new byte[256 * 3];
	imageStream->read(palette, 256 * 3);

	// Expand color components
	for (uint16 i = 0; i < 256 * 3; i++)
		palette[i] <<= 2;

	uint16 xoffset = imageStream->readUint16();
	uint16 yoffset = imageStream->readUint16();
	uint16 width = imageStream->readUint16();
	uint16 height = imageStream->readUint16();

	byte *pixels = new byte[width * height];
	imageStream->read(pixels, width * height);

	_vm->_system->getPaletteManager()->setPalette(palette, 0, 256);
	_vm->_system->copyRectToScreen(pixels, width, xoffset, yoffset, width, height);
	//_vm->_system->updateScreen();
	//_vm->_system->delayMillis(10);

	delete[] pixels;
	delete[] palette;
}

} // End of namespace StarTrek