aboutsummaryrefslogtreecommitdiff
path: root/engines/draci/animation.cpp
blob: 2528383f4f34f3069e27e60df7daf6da2251b5c4 (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
/* 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 "draci/draci.h"
#include "draci/animation.h"
#include "draci/barchive.h"
#include "draci/game.h"
#include "draci/screen.h"
#include "draci/sound.h"
#include "draci/surface.h"

#include "common/memstream.h"
#include "common/system.h"

namespace Draci {

Animation::Animation(DraciEngine *vm, int id, uint z, bool playing) : _vm(vm) {
	_id = id;
	_index = kIgnoreIndex;
	_z = z;
	clearShift();
	_displacement = kNoDisplacement;
	_playing = playing;
	_looping = false;
	_paused = false;
	_canBeQuick = false;
	_tick = _vm->_system->getMillis();
	_currentFrame = 0;
	_hasChangedFrame = true;
	_callback = &Animation::doNothing;
	_isRelative = false;
}

Animation::~Animation() {
	deleteFrames();
}

void Animation::setRelative(int relx, int rely) {
	// Delete the previous frame if there is one
	if (_frames.size() > 0)
		markDirtyRect(_vm->_screen->getSurface());

	_displacement.relX = relx;
	_displacement.relY = rely;
}

Displacement Animation::getCurrentFrameDisplacement() const {
	Displacement dis = _displacement;
	dis.relX += scummvm_lround(dis.extraScaleX * _shift.x);
	dis.relY += scummvm_lround(dis.extraScaleY * _shift.y);
	return dis;
}

Common::Point Animation::getCurrentFramePosition() const {
	Displacement dis = getCurrentFrameDisplacement();
	return Common::Point(dis.relX, dis.relY);
}

void Animation::setLooping(bool looping) {
	_looping = looping;
	debugC(7, kDraciAnimationDebugLevel, "Setting looping to %d on animation %d",
		looping, _id);
}

void Animation::markDirtyRect(Surface *surface) const {
	if (getFrameCount() == 0)
		return;

	// Fetch the current frame's rectangle
	const Drawable *frame = getConstCurrentFrame();
	Common::Rect frameRect = frame->getRect(getCurrentFrameDisplacement());

	// Mark the rectangle dirty on the surface
	surface->markDirtyRect(frameRect);
}

void Animation::nextFrame(bool force) {
	// If there are no frames or if the animation is not playing, return
	if (getFrameCount() == 0 || !_playing)
		return;

	const Drawable *frame = getConstCurrentFrame();
	Surface *surface = _vm->_screen->getSurface();

	if (force || (_tick + frame->getDelay() <= _vm->_system->getMillis()) ||
	    (_canBeQuick && _vm->_game->getEnableQuickHero() && _vm->_game->getWantQuickHero())) {
		// If we are at the last frame and not looping, stop the animation
		// The animation is also restarted to frame zero
		if ((_currentFrame == getFrameCount() - 1) && !_looping) {
			// When the animation reaches its end, call the preset callback
			(this->*_callback)();
		} else {
			// Mark old frame dirty so it gets deleted
			markDirtyRect(surface);

			_shift.x += _relativeShifts[_currentFrame].x;
			_shift.y += _relativeShifts[_currentFrame].y;
			_currentFrame = nextFrameNum();
			_tick = _vm->_system->getMillis();

			// Fetch new frame and mark it dirty
			markDirtyRect(surface);

			// If the animation is paused, then nextFrameNum()
			// returns the same frame number even though the time
			// has elapsed to switch to another frame.  We must not
			// flip _hasChangedFrame to true, otherwise the sample
			// assigned to this frame will be re-started over and
			// over until all sound handles are exhausted (happens,
			// e.g., when switching to the inventory which pauses
			// all animations).
			_hasChangedFrame = !_paused;
		}
	}

	debugC(6, kDraciAnimationDebugLevel,
	"anim=%d tick=%d delay=%d tick+delay=%d currenttime=%d frame=%d framenum=%d x=%d y=%d z=%d",
	_id, _tick, frame->getDelay(), _tick + frame->getDelay(), _vm->_system->getMillis(),
	_currentFrame, _frames.size(), frame->getX() + getRelativeX(), frame->getY() + getRelativeY(), _z);
}

uint Animation::nextFrameNum() const {
	if (_paused)
		return _currentFrame;

	if ((_currentFrame == getFrameCount() - 1) && _looping)
		return 0;
	else
		return _currentFrame + 1;
}

void Animation::drawFrame(Surface *surface) {
	// If there are no frames or the animation is not playing, return
	if (_frames.size() == 0 || !_playing)
		return;

	const Drawable *frame = getConstCurrentFrame();

	if (_id == kOverlayImage) {
		// No displacement or relative animations is supported.
		frame->draw(surface, false, 0, 0);
	} else {
		// Draw frame: first shifted by the relative shift and then
		// scaled/shifted by the given displacement.
		frame->drawReScaled(surface, false, getCurrentFrameDisplacement());
	}

	const SoundSample *sample = _samples[_currentFrame];
	if (_hasChangedFrame && sample) {
		uint duration = _vm->_sound->playSound(sample, Audio::Mixer::kMaxChannelVolume, false);
		debugC(3, kDraciSoundDebugLevel,
			"Playing sample on animation %d, frame %d: %d+%d at %dHz: %dms",
			_id, _currentFrame, sample->_offset, sample->_length, sample->_frequency, duration);
	}
	_hasChangedFrame = false;
}

void Animation::setPlaying(bool playing) {
	_tick = _vm->_system->getMillis();
	_playing = playing;

	// When restarting an animation, allow playing sounds.
	_hasChangedFrame |= playing;
}

void Animation::setScaleFactors(double scaleX, double scaleY) {
	debugC(5, kDraciAnimationDebugLevel,
		"Setting scaling factors on anim %d (scaleX: %.3f scaleY: %.3f)",
		_id, scaleX, scaleY);

	markDirtyRect(_vm->_screen->getSurface());

	_displacement.extraScaleX = scaleX;
	_displacement.extraScaleY = scaleY;
}

void Animation::addFrame(Drawable *frame, const SoundSample *sample) {
	_frames.push_back(frame);
	_samples.push_back(sample);
	_relativeShifts.push_back(Common::Point(0, 0));
}

void Animation::makeLastFrameRelative(int x, int y) {
	_relativeShifts.back() = Common::Point(x, y);
}

void Animation::clearShift() {
	_shift = Common::Point(0, 0);
}

void Animation::replaceFrame(int i, Drawable *frame, const SoundSample *sample) {
	_frames[i] = frame;
	_samples[i] = sample;
}

const Drawable *Animation::getConstCurrentFrame() const {
	// If there are no frames stored, return NULL
	return _frames.size() > 0 ? _frames[_currentFrame] : NULL;
}

Drawable *Animation::getCurrentFrame() {
	// If there are no frames stored, return NULL
	return _frames.size() > 0 ? _frames[_currentFrame] : NULL;
}

Drawable *Animation::getFrame(int frameNum) {
	// If there are no frames stored, return NULL
	return _frames.size() > 0 ? _frames[frameNum] : NULL;
}

void Animation::setCurrentFrame(uint frame) {
	// Check whether the value is sane
	if (frame >= _frames.size()) {
		return;
	}

	_currentFrame = frame;
}

void Animation::deleteFrames() {
	// If there are no frames to delete, return
	if (_frames.size() == 0) {
		return;
	}

	markDirtyRect(_vm->_screen->getSurface());

	for (int i = getFrameCount() - 1; i >= 0; --i) {
		delete _frames[i];
		_frames.pop_back();
	}
	_relativeShifts.clear();
	_samples.clear();
}

void Animation::exitGameLoop() {
	_vm->_game->setExitLoop(true);
}

void Animation::tellWalkingState() {
	_vm->_game->heroAnimationFinished();
}

void Animation::play() {
	if (isPlaying()) {
		return;
	}

	// Mark the first frame dirty so it gets displayed
	markDirtyRect(_vm->_screen->getSurface());

	setPlaying(true);

	debugC(3, kDraciAnimationDebugLevel, "Playing animation %d...", getID());
}

void Animation::stop() {
	if (!isPlaying()) {
		return;
	}

	// Clean up the last frame that was drawn before stopping
	markDirtyRect(_vm->_screen->getSurface());

	setPlaying(false);

	// Reset the animation to the beginning
	setCurrentFrame(0);
	clearShift();

	debugC(3, kDraciAnimationDebugLevel, "Stopping animation %d...", getID());
}

void Animation::del() {
	_vm->_anims->deleteAnimation(this);
}

void AnimationManager::pauseAnimations() {
	if (_animationPauseCounter++) {
		// Already paused
		return;
	}

	Common::List<Animation *>::iterator it;

	for (it = _animations.begin(); it != _animations.end(); ++it) {
		if ((*it)->getID() > 0 || (*it)->getID() == kTitleText) {
			// Clean up the last frame that was drawn before stopping
			(*it)->markDirtyRect(_vm->_screen->getSurface());

			(*it)->setPaused(true);
		}
	}
}

void AnimationManager::unpauseAnimations() {
	if (--_animationPauseCounter) {
		// Still paused
		return;
	}

	Common::List<Animation *>::iterator it;

	for (it = _animations.begin(); it != _animations.end(); ++it) {
		if ((*it)->isPaused()) {
			// Clean up the last frame that was drawn before stopping
			(*it)->markDirtyRect(_vm->_screen->getSurface());

			(*it)->setPaused(false);
		}
	}
}

Animation *AnimationManager::getAnimation(int id) {
	Common::List<Animation *>::iterator it;

	for (it = _animations.begin(); it != _animations.end(); ++it) {
		if ((*it)->getID() == id) {
			return *it;
		}
	}

	return NULL;
}

void AnimationManager::insert(Animation *anim, bool allocateIndex) {
	if (allocateIndex)
		anim->setIndex(++_lastIndex);

	Common::List<Animation *>::iterator it;

	for (it = _animations.begin(); it != _animations.end(); ++it) {
		if (anim->getZ() < (*it)->getZ())
			break;
	}

	_animations.insert(it, anim);
}

void AnimationManager::drawScene(Surface *surf) {
	// Fill the screen with color zero since some rooms may rely on the screen being black
	_vm->_screen->getSurface()->fill(0);

	sortAnimations();

	Common::List<Animation *>::iterator it;

	for (it = _animations.begin(); it != _animations.end(); ++it) {
		if (! ((*it)->isPlaying()) ) {
			continue;
		}

		(*it)->nextFrame(false);
		(*it)->drawFrame(surf);
	}
}

void AnimationManager::sortAnimations() {
	Common::List<Animation *>::iterator cur;
	Common::List<Animation *>::iterator next;

	cur = _animations.begin();

	// If the list is empty, we're done
	if (cur == _animations.end())
		return;

	bool hasChanged;

	do {
		hasChanged = false;
		cur = _animations.begin();
		next = cur;

		while (true) {
			next++;

			// If we are at the last element, we're done
			if (next == _animations.end())
				break;

			// If we find an animation out of order, reinsert it
			if ((*next)->getZ() < (*cur)->getZ()) {

				Animation *anim = *next;
				next = _animations.reverse_erase(next);

				insert(anim, false);
				hasChanged = true;
			}

			// Advance to next animation
			cur = next;
		}
	} while (hasChanged);
}

void AnimationManager::deleteAnimation(Animation *anim) {
	if (!anim) {
		return;
	}
	Common::List<Animation *>::iterator it;

	int index = -1;

	// Iterate for the first time to delete the animation
	for (it = _animations.begin(); it != _animations.end(); ++it) {
		if (*it == anim) {
			// Remember index of the deleted animation
			index = (*it)->getIndex();

			debugC(3, kDraciAnimationDebugLevel, "Deleting animation %d...", anim->getID());

			delete *it;
			_animations.erase(it);

			break;
		}
	}

	// Iterate the second time to decrease indexes greater than the deleted animation index
	for (it = _animations.begin(); it != _animations.end(); ++it) {
		if ((*it)->getIndex() > index && (*it)->getIndex() != kIgnoreIndex) {
			(*it)->setIndex((*it)->getIndex() - 1);
		}
	}

	// Decrement index of last animation
	_lastIndex -= 1;
}

void AnimationManager::deleteOverlays() {
	debugC(3, kDraciAnimationDebugLevel, "Deleting overlays...");

	Common::List<Animation *>::iterator it;

	for (it = _animations.begin(); it != _animations.end(); ++it) {
		if ((*it)->getID() == kOverlayImage) {
			delete *it;
			it = _animations.reverse_erase(it);
		}
	}
}

void AnimationManager::deleteAll() {
	debugC(3, kDraciAnimationDebugLevel, "Deleting all animations...");

	Common::List<Animation *>::iterator it;

	for (it = _animations.begin(); it != _animations.end(); ++it) {
		delete *it;
	}

	_animations.clear();

	_lastIndex = -1;
}

void AnimationManager::deleteAfterIndex(int index) {
	Common::List<Animation *>::iterator it;

	for (it = _animations.begin(); it != _animations.end(); ++it) {
		if ((*it)->getIndex() > index) {

			debugC(3, kDraciAnimationDebugLevel, "Deleting animation %d...", (*it)->getID());

			delete *it;
			it = _animations.reverse_erase(it);
		}
	}

	_lastIndex = index;
}

const Animation *AnimationManager::getTopAnimation(int x, int y) const {
	Common::List<Animation *>::const_iterator it;

	Animation *retval = NULL;

	// Get transparent color for the current screen
	const int transparent = _vm->_screen->getSurface()->getTransparentColor();

	for (it = _animations.reverse_begin(); it != _animations.end(); --it) {

		Animation *anim = *it;

		// If the animation is not playing, ignore it
		if (!anim->isPlaying() || anim->isPaused()) {
			continue;
		}

		const Drawable *frame = anim->getConstCurrentFrame();

		if (frame == NULL) {
			continue;
		}

		bool matches = false;
		if (frame->getRect(anim->getCurrentFrameDisplacement()).contains(x, y)) {
			if (frame->getType() == kDrawableText) {

				matches = true;

			} else if (frame->getType() == kDrawableSprite &&
					   reinterpret_cast<const Sprite *>(frame)->getPixel(x, y, anim->getCurrentFrameDisplacement()) != transparent) {

				matches = true;
			}
		}

		// Return the top-most animation object, unless it is a
		// non-clickable sprite (overlay, debugging sprites for
		// walking, or title/speech text) and there is an actual object
		// underneath it.
		if (matches) {
			if (anim->getID() > kOverlayImage || anim->getID() < kSpeechText) {
				return anim;
			} else if (retval == NULL) {
				retval = anim;
			}
		}
	}

	// The default return value if no animations were found on these coordinates (not even overlays)
	return retval;
}

Animation *AnimationManager::load(uint animNum) {
	// Make double-sure that an animation isn't loaded more than twice,
	// otherwise horrible things happen in the AnimationManager, because
	// they use a simple link-list without duplicate checking.  This should
	// never happen unless there is a bug in the game, because all GPL2
	// commands are guarded.
	assert(!getAnimation(animNum));

	const BAFile *animFile = _vm->_animationsArchive->getFile(animNum);
	Common::MemoryReadStream animationReader(animFile->_data, animFile->_length);

	uint numFrames = animationReader.readByte();

	// The following two flags are ignored by the played.  Memory logic was
	// a hint to the old player whether it should cache the sprites or load
	// them on demand.  We have 1 memory manager and ignore these hints.
	animationReader.readByte();
	// The disable erasing field is just a (poor) optimization flag that
	// turns of drawing the background underneath the sprite.  By reading
	// the source code of the old player, I'm not sure if that would ever
	// have worked.  There are only 6 animations in the game with this flag
	// true.  All of them have just 1 animation phase and they are used to
	// patch a part of the original background by a new sprite.  This
	// should work with the default logic as well---just play this
	// animation on top of the background.  Since the only meaning of the
	// flag was optimization, ignoring should be OK even without dipping
	// into details.
	animationReader.readByte();
	const bool cyclic = animationReader.readByte();
	const bool relative = animationReader.readByte();

	Animation *anim = new Animation(_vm, animNum, 0, false);
	insert(anim, true);

	anim->setLooping(cyclic);
	anim->setIsRelative(relative);

	for (uint i = 0; i < numFrames; ++i) {
		uint spriteNum = animationReader.readUint16LE() - 1;
		int x = animationReader.readSint16LE();
		int y = animationReader.readSint16LE();
		uint scaledWidth = animationReader.readUint16LE();
		uint scaledHeight = animationReader.readUint16LE();
		byte mirror = animationReader.readByte();
		int sample = animationReader.readUint16LE() - 1;
		uint freq = animationReader.readUint16LE();
		uint delay = animationReader.readUint16LE();

		// _spritesArchive is flushed when entering a room.  All
		// scripts in a room are responsible for loading their animations.
		const BAFile *spriteFile = _vm->_spritesArchive->getFile(spriteNum);
		Sprite *sp = new Sprite(spriteFile->_data, spriteFile->_length,
			relative ? 0 : x, relative ? 0 : y, true);

		// Some frames set the scaled dimensions to 0 even though other frames
		// from the same animations have them set to normal values
		// We work around this by assuming it means no scaling is necessary
		if (scaledWidth == 0) {
			scaledWidth = sp->getWidth();
		}

		if (scaledHeight == 0) {
			scaledHeight = sp->getHeight();
		}

		sp->setScaled(scaledWidth, scaledHeight);

		if (mirror)
			sp->setMirrorOn();

		sp->setDelay(delay * 10);

		anim->addFrame(sp, _vm->_soundsArchive->getSample(sample, freq));
		if (relative) {
			anim->makeLastFrameRelative(x, y);
		}
	}

	return anim;
}

} // End of namespace Draci