/
busymode.cpp
519 lines (420 loc) · 12.9 KB
/
busymode.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
/** @file busymode.cpp Busy Mode
* @ingroup base
*
* @authors Copyright © 2007-2013 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2007-2013 Daniel Swanson <danij@dengine.net>
* @authors Copyright © 2007 Jamie Jones <jamie_jones_au@yahoo.com.au>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>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 St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#define DENG_NO_API_MACROS_BUSY
#include "de_base.h"
#include "de_platform.h"
#include "de_console.h"
#include "de_graphics.h"
#include "de_network.h"
#include "audio/s_main.h"
#include "ui/busyvisual.h"
#include <de/c_wrapper.h>
#include <de/Log>
#include <QEventLoop>
#ifdef __CLIENT__
static void BusyMode_Loop(void);
static void BusyMode_Exit(void);
static QEventLoop* eventLoop;
static volatile boolean busyDoneCopy;
static timespan_t busyTime;
static boolean busyWillAnimateTransition;
static boolean busyWasIgnoringInput;
#endif // __CLIENT__
static boolean busyInited;
static volatile boolean busyDone;
static mutex_t busy_Mutex; // To prevent Data races in the busy thread.
static BusyTask* busyTask; // Current task.
static thread_t busyThread;
static timespan_t accumulatedBusyTime; // Never cleared.
static boolean busyTaskEndedWithError;
static char busyError[256];
#ifdef __CLIENT__
static boolean animatedTransitionActive(int busyMode)
{
return (!novideo && !isDedicated && !netGame && !(busyMode & BUSYF_STARTUP) &&
rTransitionTics > 0 && (busyMode & BUSYF_TRANSITION));
}
#endif
boolean BusyMode_Active(void)
{
return busyInited;
}
timespan_t BusyMode_ElapsedTime(void)
{
if(!BusyMode_Active()) return 0;
return accumulatedBusyTime;
}
boolean BusyMode_IsWorkerThread(uint threadId)
{
boolean result;
if(!BusyMode_Active() || !busyThread) return false;
/// @todo Is locking necessary?
Sys_Lock(busy_Mutex);
result = (Sys_ThreadId(busyThread) == threadId);
Sys_Unlock(busy_Mutex);
return result;
}
boolean BusyMode_InWorkerThread(void)
{
return BusyMode_IsWorkerThread(Sys_CurrentThreadId());
}
BusyTask* BusyMode_CurrentTask(void)
{
if(!BusyMode_Active()) return NULL;
return busyTask;
}
#ifdef __CLIENT__
/**
* Callback that is called from the busy worker thread when it exists.
* @param status Exit status.
*/
static void busyWorkerTerminated(systhreadexitstatus_t status)
{
DENG_ASSERT(BusyMode_Active());
if(status == DENG_THREAD_STOPPED_WITH_EXCEPTION)
{
_api_Busy.WorkerError("Uncaught exception from busy thread.");
}
}
/**
* Sets up module state for running a busy task. After this the busy mode event
* loop is started. The loop will run until the worker thread exits.
*/
static void beginTask(BusyTask* task)
{
DENG_ASSERT(task);
if(!busyInited)
{
busy_Mutex = Sys_CreateMutex("BUSY_MUTEX");
}
if(busyInited)
{
Con_Error("Con_Busy: Already busy.\n");
}
Sys_Lock(busy_Mutex);
busyDone = false;
busyTaskEndedWithError = false;
// This is now the current task.
busyTask = task;
Sys_Unlock(busy_Mutex);
busyInited = true;
// Load any resources needed to visual this task's progress.
BusyVisual_PrepareResources();
// Start the busy worker thread, which will process the task in the
// background while we keep the user occupied with nice animations.
busyThread = Sys_StartThread(busyTask->worker, busyTask->workerData);
Thread_SetCallback(busyThread, busyWorkerTerminated);
// Switch the engine loop and window to the busy mode.
LegacyCore_SetLoopFunc(BusyMode_Loop);
Window_SetDrawFunc(Window_Main(), BusyVisual_Render);
busyTask->_startTime = Timer_RealSeconds();
}
/**
* Called after the busy mode worker thread and the event (sub-)loop has been stopped.
*/
static void endTask(BusyTask* task)
{
DENG_ASSERT(task);
LIBDENG_ASSERT_IN_MAIN_THREAD();
if(verbose)
{
Con_Message("Con_Busy: Was busy for %.2lf seconds.", busyTime);
}
// The window drawer will be restored later to the appropriate function.
Window_SetDrawFunc(Window_Main(), 0);
if(busyTaskEndedWithError)
{
Con_AbnormalShutdown(busyError);
}
if(busyWillAnimateTransition)
{
Con_TransitionBegin();
}
// Make sure that any remaining deferred content gets uploaded.
if(!(task->mode & BUSYF_NO_UPLOADS))
{
GL_ProcessDeferredTasks(0);
}
Sys_DestroyMutex(busy_Mutex);
busyInited = false;
}
#endif // __CLIENT__
/**
* Runs the busy mode event loop. Execution blocks here until the worker thread exits.
*/
static int runTask(BusyTask* task)
{
DENG_ASSERT(task);
if(novideo)
{
// Don't bother to start a thread -- non-GUI mode.
return task->worker(task->workerData);
}
#ifdef __CLIENT__
// Let's get busy!
beginTask(task);
DENG_ASSERT(eventLoop == 0);
// Run a local event loop since the primary event loop is blocked while
// we're busy. This event loop is able to handle window and input events
// just like the primary loop.
eventLoop = new QEventLoop;
int result = eventLoop->exec();
delete eventLoop;
eventLoop = 0;
// Teardown.
endTask(task);
return result;
#else
return 0;
#endif
}
static void preBusySetup(int initialMode)
{
#ifdef __CLIENT__
// Are we doing a transition effect?
busyWillAnimateTransition = animatedTransitionActive(initialMode);
if(busyWillAnimateTransition)
{
Con_TransitionConfigure();
}
busyWasIgnoringInput = DD_IgnoreInput(true);
// Save the present loop.
LegacyCore_PushLoop();
// Set up loop for busy mode.
LegacyCore_SetLoopRate(60);
LegacyCore_SetLoopFunc(NULL); // don't call main loop's func while busy
BusyVisual_PrepareFont();
BusyVisual_LoadTextures();
Window_SetDrawFunc(Window_Main(), 0);
#else
DENG_UNUSED(initialMode);
#endif
}
static void postBusyCleanup(void)
{
#ifdef __CLIENT__
// Discard input events so that any and all accumulated input events are ignored.
DD_IgnoreInput(busyWasIgnoringInput);
DD_ResetTimer();
BusyVisual_ReleaseTextures();
// Restore old loop.
LegacyCore_PopLoop();
// Resume drawing with the game loop drawer.
Window_SetDrawFunc(Window_Main(), !Sys_IsShuttingDown()? DD_GameLoopDrawer : 0);
#endif
}
/**
* @param mode Busy mode flags @ref busyModeFlags
* @param worker Worker thread that does processing while in busy mode.
* @param workerData Data context for the worker thread.
* @param taskName Optional task name (drawn with the progress bar).
*/
static BusyTask* newTask(int mode, busyworkerfunc_t worker, void* workerData,
const char* taskName)
{
// Initialize the task.
BusyTask* task = (BusyTask*) calloc(1, sizeof(*task));
task->mode = mode;
task->worker = worker;
task->workerData = workerData;
// Take a copy of the task name.
if(taskName && taskName[0])
{
task->name = strdup(taskName);
}
return task;
}
static void deleteTask(BusyTask* task)
{
DENG_ASSERT(task);
if(task->name) free((void*)task->name);
free(task);
}
int BusyMode_RunTasks(BusyTask* tasks, int numTasks)
{
const char* currentTaskName = NULL;
BusyTask* task;
int i, mode;
int result = 0;
if(BusyMode_Active())
{
Con_Error("BusyMode: Internal error, already busy...");
exit(1); // Unreachable.
}
if(!tasks || numTasks <= 0) return result; // Hmm, no work?
// Pick the first task.
task = tasks;
int initialMode = task->mode;
preBusySetup(initialMode);
// Process tasks.
for(i = 0; i < numTasks; ++i, task++)
{
// If no new task name is specified, continue using the name of the previous task.
if(task->name)
{
if(task->name[0])
currentTaskName = task->name;
else // Clear the name.
currentTaskName = NULL;
}
mode = task->mode;
/// @todo Kludge: Force BUSYF_STARTUP here so that the animation of one task
/// is not drawn on top of the last frame of the previous.
if(numTasks > 1)
{
mode |= BUSYF_STARTUP;
}
// kludge end
// Null tasks are not processed (implicit success).
if(!task->worker) continue;
/**
* Process the work.
*/
// Is the worker updating its progress?
if(task->maxProgress > 0)
Con_InitProgress2(task->maxProgress, task->progressStart, task->progressEnd);
// Invoke the worker in a new thread.
/// @todo Kludge: Presently a temporary local task is needed so that we can modify
/// the task name and mode flags.
{ BusyTask* tmp = newTask(mode, task->worker, task->workerData, currentTaskName);
result = runTask(tmp);
// We are now done with this task.
deleteTask(tmp);
if(result) break;
}
// kludge end.
}
postBusyCleanup();
return result;
}
int BusyMode_RunTask(BusyTask* task)
{
return BusyMode_RunTasks(task, 1);
}
int BusyMode_RunNewTaskWithName(int mode, busyworkerfunc_t worker, void* workerData, const char* taskName)
{
BusyTask* task = newTask(mode, worker, workerData, taskName);
int result = BusyMode_RunTask(task);
deleteTask(task);
return result;
}
int BusyMode_RunNewTask(int mode, busyworkerfunc_t worker, void* workerData)
{
return BusyMode_RunNewTaskWithName(mode, worker, workerData, NULL/*no task name*/);
}
#ifdef __CLIENT__
/**
* Ends the busy event loop and sets its return value. The loop callback, which
* during busy mode points to the busy loop callback, is reset to NULL.
*/
static void stopEventLoopWithValue(int result)
{
// After the event loop is gone, we don't want any loop callbacks until the
// busy state has been properly torn down.
LegacyCore_SetLoopFunc(0);
DENG_ASSERT(eventLoop != 0);
eventLoop->exit(result);
}
/**
* Exits the busy mode event loop. Called in the main thread, does not return
* until the worker thread is stopped.
*/
static void BusyMode_Exit(void)
{
int result;
systhreadexitstatus_t status;
LIBDENG_ASSERT_IN_MAIN_THREAD();
busyDone = true;
// Make sure the worker finishes before we continue.
result = Sys_WaitThread(busyThread, busyTaskEndedWithError? 100 : 5000, &status);
busyThread = NULL;
busyTask = NULL;
stopEventLoopWithValue(result);
}
/**
* The busy loop callback function. Called periodically in the main (UI) thread
* while the busy worker is running.
*/
static void BusyMode_Loop(void)
{
boolean canUpload = !(busyTask->mode & BUSYF_NO_UPLOADS);
timespan_t oldTime;
Garbage_Recycle();
// Make sure the audio system gets regularly updated.
S_StartFrame();
// Post and discard all input events.
DD_ProcessEvents(0);
DD_ProcessSharpEvents(0);
if(canUpload)
{
Window_GLActivate(Window_Main());
// Any deferred content needs to get uploaded.
GL_ProcessDeferredTasks(15);
}
S_EndFrame();
// We accumulate time in the busy loop so that the animation of a task
// sequence doesn't jump around but remains continuous.
oldTime = busyTime;
busyTime = Timer_RealSeconds() - busyTask->_startTime;
if(busyTime > oldTime)
{
accumulatedBusyTime += busyTime - oldTime;
}
Sys_Lock(busy_Mutex);
busyDoneCopy = busyDone;
Sys_Unlock(busy_Mutex);
if(!busyDoneCopy || (canUpload && GL_DeferredTaskCount() > 0) ||
!Con_IsProgressAnimationCompleted())
{
// Let's keep running the busy loop.
Window_Draw(Window_Main());
return;
}
// Stop the loop.
BusyMode_Exit();
}
#endif // __CLIENT__
void BusyMode_WorkerError(const char* message)
{
busyTaskEndedWithError = true;
strncpy(busyError, message, sizeof(busyError) - 1);
_api_Busy.WorkerEnd();
}
void BusyMode_WorkerEnd(void)
{
if(!busyInited) return;
Sys_Lock(busy_Mutex);
busyDone = true;
Sys_Unlock(busy_Mutex);
}
DENG_DECLARE_API(Busy) =
{
{ DE_API_BUSY },
BusyMode_Active,
BusyMode_ElapsedTime,
BusyMode_RunTask,
BusyMode_RunTasks,
BusyMode_RunNewTask,
BusyMode_RunNewTaskWithName,
BusyMode_WorkerEnd,
BusyMode_WorkerError
};