File: kernel.cpp

package info (click to toggle)
scummvm 2.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 450,580 kB
  • sloc: cpp: 4,299,825; asm: 28,322; python: 12,901; sh: 11,302; java: 9,289; xml: 7,895; perl: 2,639; ansic: 2,465; yacc: 1,670; javascript: 1,020; makefile: 933; lex: 578; awk: 275; objc: 82; sed: 11; php: 1
file content (516 lines) | stat: -rw-r--r-- 14,105 bytes parent folder | download | duplicates (2)
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
/* 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 3 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, see <http://www.gnu.org/licenses/>.
 *
 */

#include "ultima/ultima8/misc/debugger.h"
#include "ultima/ultima8/kernel/kernel.h"
#include "ultima/ultima8/kernel/process.h"
#include "ultima/ultima8/misc/id_man.h"
#include "ultima/ultima8/ultima8.h"

namespace Ultima {
namespace Ultima8 {

Kernel *Kernel::_kernel = nullptr;

const uint32 Kernel::TICKS_PER_FRAME = 2;
const uint32 Kernel::TICKS_PER_SECOND = 60;
const uint32 Kernel::FRAMES_PER_SECOND = Kernel::TICKS_PER_SECOND / Kernel::TICKS_PER_FRAME;

// A special proc type which means "all"
const uint16 Kernel::PROC_TYPE_ALL = 6;

// The same as above, but for Crusader.
// Used in Usecode functions to translate.
static const uint16 CRU_PROC_TYPE_ALL = 0xc;

Kernel::Kernel() : _loading(false), _tickNum(0), _paused(0),
		_runningProcess(nullptr), _frameByFrame(false) {
	debug(1, "Creating Kernel...");

	_kernel = this;
	_pIDs = new idMan(1, 32766, 128);
	_currentProcess = _processes.end();
}

Kernel::~Kernel() {
	reset();
	debug(1, "Destroying Kernel...");

	_kernel = nullptr;

	delete _pIDs;
}

void Kernel::reset() {
	debug(1, "Resetting Kernel...");

	for (ProcessIterator it = _processes.begin(); it != _processes.end(); ++it) {
		Process *p = *it;
		if (p->_flags & Process::PROC_TERM_DISPOSE && p != _runningProcess) {
			delete p;
		} else {
			p->_flags |= Process::PROC_TERMINATED;
		}
	}
	_processes.clear();
	_currentProcess = _processes.end();

	_pIDs->clearAll();

	_paused = 0;
	_runningProcess = nullptr;

	// if we're in frame-by-frame mode, reset to a _paused state
	if (_frameByFrame) _paused = 1;
}

ProcId Kernel::assignPID(Process *proc) {
	// to prevent new processes from getting a PID while loading
	if (_loading) return 0xFFFF;

	// Get a pID
	proc->_pid = _pIDs->getNewID();

	return proc->_pid;
}

ProcId Kernel::addProcess(Process *proc, bool dispose) {
#if 0
	for (ProcessIterator it = processes.begin(); it != processes.end(); ++it) {
		if (*it == proc)
			return 0;
	}
#endif

	assert(proc->_pid != 0 && proc->_pid != 0xFFFF);

#if 0
	debug(1, "[Kernel] Adding process %p, pid = %u type %s",
		proc, proc->_pid, proc->GetClassType()._className);
#endif

	if (dispose) {
		proc->_flags |= Process::PROC_TERM_DISPOSE;
	}
	setNextProcess(proc);
	return proc->_pid;
}

ProcId Kernel::addProcessExec(Process *proc, bool dispose) {
#if 0
	for (ProcessIterator it = processes.begin(); it != processes.end(); ++it) {
		if (*it == proc)
			return 0;
	}
#endif

	assert(proc->_pid != 0 && proc->_pid != 0xFFFF);

#if 0
	debug(1, "[Kernel] Adding process %p, pid = %u type %s",
		proc, proc->_pid, proc->GetClassType()._className);
#endif

	if (dispose) {
		proc->_flags |= Process::PROC_TERM_DISPOSE;
	}
	_processes.push_back(proc);
	proc->_flags |= Process::PROC_ACTIVE;

	Process *oldrunning = _runningProcess;
	_runningProcess = proc;
	proc->run();
	_runningProcess = oldrunning;

	return proc->_pid;
}

void Kernel::runProcesses() {
	if (!_paused)
		_tickNum++;

	if (_processes.size() == 0) {
		warning("Process queue is empty?! Aborting.");
		return;
	}

	int num_run = 0;

	_currentProcess = _processes.begin();
	while (_currentProcess != _processes.end()) {
		Process *p = *_currentProcess;

		if (!_paused && ((p->_flags & (Process::PROC_TERMINATED |
		                             Process::PROC_TERM_DEFERRED))
		                == Process::PROC_TERM_DEFERRED)) {
			p->terminate();
		}
		if (!(p->is_terminated() || p->is_suspended()) &&
		        (!_paused || (p->_flags & Process::PROC_RUNPAUSED)) &&
				(_paused || _tickNum % p->getTicksPerRun() == 0)) {
			_runningProcess = p;
			p->run();
			_runningProcess = nullptr;

			num_run++;

			//
			// WORKAROUND:
			// In Crusader: No Remorse, the HOVER near the end of Mission 3
			// (Floor 1) gets stuck in a tight loop after moving to the
			// destination (path egg frame 0).
			//
			// Something is probably not right about the switch trigger, but until
			// we can work out what it is avoid the game totally hanging at this
			// point.
			//
			// If this threshold is set too low, it can cause issues with U8 map
			// transitions (eg, bug #12913).  If it's too high, Crusader locks up
			// for a really long time at this point.  Set it high enough that
			// a process going through all map items should still terminate.
			//
			if (((num_run > 8192 && GAME_IS_CRUSADER) || num_run > 65534)
					&& !p->is_terminated()) {
				warning("Seem to be stuck in process loop - killing current process");
				p->fail();
			}

			if (_currentProcess == _processes.end()) {
				// If this happens then the list was reset so delete the process and return.
				if (p->_flags & Process::PROC_TERM_DISPOSE) {
					delete p;
				}
				return;
			}
		}
		if (!_paused && (p->_flags & Process::PROC_TERMINATED)) {
			// process is killed, so remove it from the list
			_currentProcess = _processes.erase(_currentProcess);

			// Clear pid
			_pIDs->clearID(p->_pid);

			if (p->_flags & Process::PROC_TERM_DISPOSE) {
				delete p;
			}
		} else if (!_paused && (p->_flags & Process::PROC_TERM_DEFERRED) && GAME_IS_CRUSADER) {
			//
			// In Crusader, move term deferred processes to the end to clean up after
			// others have run.  This gets the right speed on ELEVAT (which should
			// execute one movement per tick)
			//
			// In U8, frame-count comparison for Devon turning at the start shows this
			// *shouldn't* be used, and the process should be cleaned up next tick.
			//
			_processes.push_back(p);
			_currentProcess = _processes.erase(_currentProcess);
		} else {
			++_currentProcess;
		}
	}

	if (!_paused && _frameByFrame) pause();
}

void Kernel::setNextProcess(Process *proc) {
	if (_currentProcess != _processes.end() && *_currentProcess == proc) return;

	if (proc->_flags & Process::PROC_ACTIVE) {
		for (ProcessIterator it = _processes.begin();
		        it != _processes.end(); ++it) {
			if (*it == proc) {
				_processes.erase(it);
				break;
			}
		}
	} else {
		proc->_flags |= Process::PROC_ACTIVE;
	}

	if (_currentProcess == _processes.end()) {
		// Not currently running processes, add to the start of the next run.
		_processes.push_front(proc);
	} else {
		ProcessIterator t = _currentProcess;
		++t;

		_processes.insert(t, proc);
	}
}

Process *Kernel::getProcess(ProcId pid) {
	for (ProcessIterator it = _processes.begin(); it != _processes.end(); ++it) {
		Process *p = *it;
		if (p->_pid == pid)
			return p;
	}
	return nullptr;
}

void Kernel::kernelStats() {
	g_debugger->debugPrintf("Kernel memory stats:\n");
	g_debugger->debugPrintf("Processes  : %u/32765\n", _processes.size());
}

void Kernel::processTypes() {
	g_debugger->debugPrintf("Current process types:\n");
	Common::HashMap<Common::String, unsigned int> processtypes;
	for (ProcessIterator it = _processes.begin(); it != _processes.end(); ++it) {
		Process *p = *it;
		processtypes[p->GetClassType()._className]++;
	}
	Common::HashMap<Common::String, unsigned int>::const_iterator iter;
	for (iter = processtypes.begin(); iter != processtypes.end(); ++iter) {
		g_debugger->debugPrintf("%s: %u\n", (*iter)._key.c_str(), (*iter)._value);
	}
}

uint32 Kernel::getNumProcesses(ObjId objid, uint16 processtype) {
	uint32 count = 0;

	for (ProcessIterator it = _processes.begin(); it != _processes.end(); ++it) {
		Process *p = *it;

		// Don't count us, we are not really here
		if (p->is_terminated()) continue;

		if ((objid == 0 || objid == p->_itemNum) &&
		        (processtype == PROC_TYPE_ALL || processtype == p->_type))
			count++;
	}

	return count;
}

Process *Kernel::findProcess(ObjId objid, uint16 processtype) {
	for (ProcessIterator it = _processes.begin(); it != _processes.end(); ++it) {
		Process *p = *it;

		// Don't count us, we are not really here
		if (p->is_terminated()) continue;

		if ((objid == 0 || objid == p->_itemNum) &&
		        (processtype == PROC_TYPE_ALL || processtype == p->_type)) {
			return p;
		}
	}

	return nullptr;
}


void Kernel::killProcesses(ObjId objid, uint16 processtype, bool fail) {
	for (ProcessIterator it = _processes.begin(); it != _processes.end(); ++it) {
		Process *p = *it;

		if (p->_itemNum != 0 && (objid == 0 || objid == p->_itemNum) &&
		        (processtype == PROC_TYPE_ALL || processtype == p->_type) &&
		        !(p->_flags & Process::PROC_TERMINATED) &&
		        !(p->_flags & Process::PROC_TERM_DEFERRED)) {
			if (fail)
				p->fail();
			else
				p->terminate();
		}
	}
}

void Kernel::killProcessesNotOfType(ObjId objid, uint16 processtype, bool fail) {
	for (ProcessIterator it = _processes.begin(); it != _processes.end(); ++it) {
		Process *p = *it;

		// * If objid is 0, terminate procs for all objects.
		// * Never terminate procs with objid 0
		if (p->_itemNum != 0 && (objid == 0 || objid == p->_itemNum) &&
		        (p->_type != processtype) &&
		        !(p->_flags & Process::PROC_TERMINATED) &&
		        !(p->_flags & Process::PROC_TERM_DEFERRED)) {
			if (fail)
				p->fail();
			else
				p->terminate();
		}
	}
}

void Kernel::killAllProcessesNotOfTypeExcludeCurrent(uint16 processtype, bool fail) {
	Common::HashMap<ProcId, bool> procsToSave;
	Common::Array<ProcId> queue;

	// Create a list of all the processes and their waiting parents that we can't kill.
	if (_runningProcess) {
		queue.push_back(_runningProcess->_pid);
		while (!queue.empty()) {
			ProcId procToSave = queue.back();
			queue.pop_back();
			if (!procsToSave.contains(procToSave)) {
				Process *p = getProcess(procToSave);
				if (p) {
					procsToSave[procToSave] = true;
					queue.push_back(p->_waiting);
				}
			}
		}
	}

	for (ProcessIterator it = _processes.begin(); it != _processes.end(); ++it) {
		Process *p = *it;

		// Don't kill the running process
		if (procsToSave.contains(p->_pid))
			continue;

		if ((p->_type != processtype) &&
				!(p->_flags & Process::PROC_TERMINATED) &&
				!(p->_flags & Process::PROC_TERM_DEFERRED)) {
			if (fail)
				p->fail();
			else
				p->terminate();
		}
	}
}

bool Kernel::canSave() {
	for (ProcessIterator it = _processes.begin(); it != _processes.end(); ++it) {
		Process *p = *it;

		if (!p->is_terminated() && p->_flags & Process::PROC_PREVENT_SAVE) {
			return false;
		}
	}

	return true;
}

void Kernel::save(Common::WriteStream *ws) {
	ws->writeUint32LE(_tickNum);
	_pIDs->save(ws);
	ws->writeUint32LE(_processes.size());
	for (ProcessIterator it = _processes.begin(); it != _processes.end(); ++it) {
		const Std::string & classname = (*it)->GetClassType()._className; // virtual
		assert(classname.size());

		Common::HashMap<Common::String, ProcessLoadFunc>::iterator iter;
		iter = _processLoaders.find(classname);

		if (iter == _processLoaders.end()) {
			error("Process class cannot save without registered loader: %s", classname.c_str());
		}

		ws->writeUint16LE(classname.size());
		ws->write(classname.c_str(), classname.size());
		(*it)->saveData(ws);
	}
}

bool Kernel::load(Common::ReadStream *rs, uint32 version) {
	_tickNum = rs->readUint32LE();

	if (!_pIDs->load(rs, version)) return false;

	const uint32 pcount = rs->readUint32LE();

	for (unsigned int i = 0; i < pcount; ++i) {
		Process *p = loadProcess(rs, version);
		if (!p) return false;
		_processes.push_back(p);
	}

	// Integrity check for processes
	Std::set<ProcId> procs;
	for (Std::list<Process *>::const_iterator iter = _processes.begin(); iter != _processes.end(); iter++) {
		const Process *p = *iter;
		if (!_pIDs->isIDUsed(p->getPid())) {
			warning("Process id %d exists but not marked used.  Corrupt save?", p->getPid());
			return false;
		}
		if (procs.find(p->getPid()) != procs.end()) {
			warning("Duplicate process id %d in processes.  Corrupt save?", p->getPid());
			return false;
		}
		procs.insert(p->getPid());
		if (!p->validateWaiters()) {
			return false;
		}
		if (p->getTicksPerRun() > 100) {
			warning("Improbable value for ticks per run %d in process id %d .  Corrupt save?", p->getTicksPerRun(), p->getPid());
			return false;
		}
		if (p->getType() > 0x1000) {
			warning("Improbable value for proctype %x in process id %d .  Corrupt save?", p->getType(), p->getPid());
			return false;
		}
	}

	return true;
}

Process *Kernel::loadProcess(Common::ReadStream *rs, uint32 version) {
	const uint16 classlen = rs->readUint16LE();
	assert(classlen > 0);
	char *buf = new char[classlen + 1];
	rs->read(buf, classlen);
	buf[classlen] = 0;

	Std::string classname = buf;
	delete[] buf;

	Common::HashMap<Common::String, ProcessLoadFunc>::iterator iter;
	iter = _processLoaders.find(classname);

	if (iter == _processLoaders.end()) {
		warning("Unknown Process class: %s", classname.c_str());
		return nullptr;
	}

	_loading = true;

	Process *p = (*(iter->_value))(rs, version);

	_loading = false;

	return p;
}

uint32 Kernel::I_getNumProcesses(const uint8 *args, unsigned int /*argsize*/) {
	ARG_OBJID(item);
	ARG_UINT16(type);

	if (GAME_IS_CRUSADER && type == CRU_PROC_TYPE_ALL)
		type = PROC_TYPE_ALL;

	return Kernel::get_instance()->getNumProcesses(item, type);
}

uint32 Kernel::I_resetRef(const uint8 *args, unsigned int /*argsize*/) {
	ARG_OBJID(item);
	ARG_UINT16(type);

	if (GAME_IS_CRUSADER && type == CRU_PROC_TYPE_ALL)
		type = PROC_TYPE_ALL;

	Kernel::get_instance()->killProcesses(item, type, true);
	return 0;
}

} // End of namespace Ultima8
} // End of namespace Ultima