Oolite
Loading...
Searching...
No Matches
GameController.m
Go to the documentation of this file.
1/*
2
3GameController.m
4
5Oolite
6Copyright (C) 2004-2013 Giles C Williams and contributors
7
8This program is free software; you can redistribute it and/or
9modify it under the terms of the GNU General Public License
10as published by the Free Software Foundation; either version 2
11of the License, or (at your option) any later version.
12
13This program is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with this program; if not, write to the Free Software
20Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21MA 02110-1301, USA.
22
23*/
24
25#import "GameController.h"
26#import "MyOpenGLView.h"
29#import "OODebugFlags.h"
30#import "OODebugSupport.h"
31#import "OOJSFrameCallbacks.h"
33#import "OOLoggingExtended.h"
34#import "OOOXPVerifier.h"
35#import "OOOXZManager.h"
37#import "OOOpenGL.h"
40#import "OOSound.h"
42#import "ResourceManager.h"
43#import "Universe.h"
44#import "legacy_random.h"
45#include <stdlib.h>
46#if OOJS_QUICKJS && !defined(NDEBUG)
47#import "OOJavaScriptEngine.h"
48#endif
49
50#if OOLITE_MAC_COCOA_UI
51#import "JAPersistentFileReference.h"
52#import "OOMacJoystickManager.h"
53#import "OoliteApp.h"
54#import <Sparkle/Sparkle.h>
55
56static void SetUpSparkle(void);
57#elif (OOLITE_SDL && defined(OO_DEBUG_MONITOR_ENABLED))
58#import "OODebugMonitor.h"
59#endif
60
62
63@interface GameController (OOPrivate)
64
65- (void)reportUnhandledStartupException:(NSException*)exception;
66
67- (void)doPerformGameTick;
68
69@end
70
71@implementation GameController
72
74{
75 if (sSharedController == nil) {
76 sSharedController = [[self alloc] init];
77 }
78 return sSharedController;
79}
80
81- (id)init
82{
83 if (sSharedController != nil) {
84 [self release];
85 [NSException raise:NSInternalInconsistencyException format:@"%s: expected only one GameController to exist at a time.", __PRETTY_FUNCTION__];
86 }
87
88 if ((self = [super init])) {
89 _finishedLaunching = NO;
90 last_timeInterval = [NSDate timeIntervalSinceReferenceDate];
91 delta_t = 0.01; // one hundredth of a second
92 _animationTimerInterval = [[NSUserDefaults standardUserDefaults] oo_doubleForKey:@"animation_timer_interval" defaultValue:MINIMUM_ANIMATION_TICK];
93
94 // rather than seeding this with the date repeatedly, seed it
95 // once here at startup
96 ranrot_srand((uint32_t)[[NSDate date] timeIntervalSince1970]); // reset randomiser with current time
97
98 _splashStart = [[NSDate alloc] init];
99 }
100
101 return self;
102}
103
104- (void)dealloc
105{
106#if OOLITE_MAC_COCOA_UI
107 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:UNIVERSE];
108#endif
109
110 [timer release];
111 [gameView release];
112 [UNIVERSE release];
113
114 [playerFileToLoad release];
115 [playerFileDirectory release];
116 [expansionPathsToInclude release];
117
118 [super dealloc];
119}
120
122{
123 return gameIsPaused;
124}
125
126- (void)setGamePaused:(BOOL)value
127{
128 if (value && !gameIsPaused) {
131 [self setEcoQoS:YES];
132 gameIsPaused = YES;
133 [PLAYER doScriptEvent:OOJSID("gamePaused")];
134 } else if (!value && gameIsPaused) {
135 [self setMouseInteractionMode:_resumeMode];
136 [self setEcoQoS:NO];
137 gameIsPaused = NO;
138 [PLAYER doScriptEvent:OOJSID("gameResumed")];
139 }
140}
141
142- (void)setEcoQoS:(BOOL)efficiencyModeRequested
143{
144#if OOLITE_WINDOWS
145 if ([[NSUserDefaults standardUserDefaults] oo_boolForKey:@"ecoqos" defaultValue:YES]) {
146 BOOL setEfficiencyMode = !!efficiencyModeRequested; // yes or no, not 42
147 HANDLE currentProcess = GetCurrentProcess();
148
149 if (EXPECT_NOT(!SetPriorityClass(currentProcess, setEfficiencyMode ? IDLE_PRIORITY_CLASS : NORMAL_PRIORITY_CLASS))) {
150 OOLog(@"gameController.setEcoQos", @"SetPriorityClass failed with error %lu", GetLastError());
151 }
152
153 PROCESS_POWER_THROTTLING_STATE powerThrottling;
154 RtlZeroMemory(&powerThrottling, sizeof(powerThrottling));
155 powerThrottling.Version = PROCESS_POWER_THROTTLING_CURRENT_VERSION;
156 powerThrottling.ControlMask = PROCESS_POWER_THROTTLING_EXECUTION_SPEED;
157 powerThrottling.StateMask = setEfficiencyMode ? PROCESS_POWER_THROTTLING_EXECUTION_SPEED : 0;
158 if (EXPECT_NOT(!SetProcessInformation(currentProcess, ProcessPowerThrottling, &powerThrottling, sizeof(powerThrottling)))) {
159 OOLog(@"gameController.setEcoQos", @"SetProcessInformation failed with error %lu", GetLastError());
160 }
161 }
162#endif
163}
164
169
170- (void)setMouseInteractionMode:(OOMouseInteractionMode)mode
171{
173 if (mode == oldMode)
174 return;
175
177 OOLog(@"input.mouseMode.changed", @"Mouse interaction mode changed from %@ to %@", OOStringFromMouseInteractionMode(oldMode), OOStringFromMouseInteractionMode(mode));
178
179#if OO_USE_FULLSCREEN_CONTROLLER
180 if ([self inFullScreenMode]) {
182 } else
183#endif
184 {
185 [[self gameView] noteMouseInteractionModeChangedFrom:oldMode to:mode];
186 }
187}
188
190{
191 [self setMouseInteractionMode:[PLAYER isMouseControlOn] ? MOUSE_MODE_FLIGHT_WITH_MOUSE_CONTROL : MOUSE_MODE_FLIGHT_NO_MOUSE_CONTROL];
192}
193
194- (void)setMouseInteractionModeForUIWithMouseInteraction:(BOOL)interaction
195{
196 [self setMouseInteractionMode:interaction ? MOUSE_MODE_UI_SCREEN_WITH_INTERACTION : MOUSE_MODE_UI_SCREEN_NO_INTERACTION];
197}
198
200{
201 return gameView;
202}
203
204- (void)setGameView:(MyOpenGLView*)view
205{
206 [gameView release];
207 gameView = [view retain];
209 [UNIVERSE setGameView:gameView];
210}
211
212- (void)applicationDidFinishLaunching:(NSNotification*)notification
213{
214 NSAutoreleasePool* pool = nil;
215 unsigned i;
216
217 pool = [[NSAutoreleasePool alloc] init];
218
219 @try {
220 // if not verifying oxps, ensure that gameView is drawn to using beginSplashScreen
221 // OpenGL is initialised and that allows textures to initialise too.
222
223#if OO_OXP_VERIFIER_ENABLED
224
225 if ([OOOXPVerifier runVerificationIfRequested]) {
226 [self exitAppWithContext:@"OXP verifier run"];
227 } else {
228 [self beginSplashScreen];
229 }
230
231#else
232 [self beginSplashScreen];
233#endif
234
235#if OOLITE_MAC_COCOA_UI
237 SetUpSparkle();
238#endif
239
240 [self setUpDisplayModes];
241
242 // moved to before the Universe is created
244 for (i = 0; i < [expansionPathsToInclude count]; i++) {
245 [ResourceManager addExternalPath:(NSString*)[expansionPathsToInclude objectAtIndex:i]];
246 }
247 }
248
249 // initialise OXZ manager
251
252 // moved here to try to avoid initialising this before having an Open GL context
253 //[self logProgress:DESC(@"Initialising universe")]; // DESC expansions only possible after Universe init
254 [[Universe alloc] initWithGameView:gameView];
255
257
258 [self logProgress:@""];
259
260 // get the run loop and add the call to performGameTick:
261 [self startAnimationTimer];
262
263 [self endSplashScreen];
264 }
265 @catch (NSException* exception) {
266 [self reportUnhandledStartupException:exception];
267 exit(EXIT_FAILURE);
268 }
269
270 OOLog(@"startup.complete", @"========== Loading complete in %.2f seconds. ==========", -[_splashStart timeIntervalSinceNow]);
271
272#if OO_USE_FULLSCREEN_CONTROLLER
273 [self setFullScreenMode:[[NSUserDefaults standardUserDefaults] boolForKey:@"fullscreen"]];
274#endif
275
276 _finishedLaunching = YES;
277
278 // Release anything allocated above that is not required.
279 [pool release];
280
281#if !OOLITE_MAC_COCOA_UI
282 [[NSRunLoop currentRunLoop] run];
283#endif
284}
285
287{
288 return _finishedLaunching;
289}
290
292{
293 if (playerFileToLoad != nil) {
294 [self logProgress:DESC(@"loading-player")];
295 // fix problem with non-shader lighting when starting skips
296 // the splash screen
297 [UNIVERSE useGUILightSource:YES];
298 [UNIVERSE useGUILightSource:NO];
299 [PLAYER loadPlayerFromFile:playerFileToLoad asNew:NO];
300 }
301}
302
304{
305#if !OOLITE_MAC_COCOA_UI
306 if (!gameView) {
307 gameView = [MyOpenGLView alloc];
308 [gameView init];
311 }
312#else
314#endif
315}
316
317#if OOLITE_MAC_COCOA_UI
318
319- (void)performGameTick:(id)sender
320{
322 [self doPerformGameTick];
323}
324
325#else
326
327- (void)performGameTick:(id)sender
328{
329 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
330
331 [gameView pollControls];
332 [self doPerformGameTick];
333
334 [pool release];
335}
336
337#endif
338
340{
341 @try {
342 if (gameIsPaused)
343 delta_t = 0.0; // no movement!
344 else {
345 delta_t = [NSDate timeIntervalSinceReferenceDate] - last_timeInterval;
346 last_timeInterval += delta_t;
347 if (delta_t > MINIMUM_GAME_TICK)
348 delta_t = MINIMUM_GAME_TICK; // peg the maximum pause (at 0.5->1.0 seconds) to protect against when the machine sleeps
349 }
350
351 [UNIVERSE update:delta_t];
352 if (EXPECT_NOT([PLAYER status] == STATUS_RESTART_GAME)) {
353 [UNIVERSE reinitAndShowDemo:YES];
354 }
355 [OOSound update];
356 if (!gameIsPaused) {
358 }
359 }
360 @catch (id exception) {
361 OOLog(@"exception.backtrace", @"%@", [exception callStackSymbols]);
362 }
363
364 @
365 try {
366 [gameView updateScreen];
367 }
368 @catch (id exception) {
369 }
370}
371
373{
374 if (timer == nil) {
375 NSTimeInterval ti = _animationTimerInterval; // default one two-hundredth of a second (should be a fair bit faster than expected frame rate ~60Hz to avoid problems with phase differences)
376
377 timer = [[NSTimer timerWithTimeInterval:ti target:self selector:@selector(performGameTick:) userInfo:nil repeats:YES] retain];
378
379 [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
380#if OOLITE_MAC_COCOA_UI
381 [[NSRunLoop currentRunLoop] addTimer:timer
382 forMode:NSEventTrackingRunLoopMode];
383#endif
384 }
385}
386
388{
389 if (timer != nil) {
390 [timer invalidate];
391 [timer release];
392 timer = nil;
393 }
394}
395
396#if OOLITE_MAC_COCOA_UI
397
399{
400 // FIXME: does this really need to be spread across GameController and MyOpenGLView? -- Ahruman 2011-01-22
401 my_mouse_x = my_mouse_y = 0; // center mouse
402 [gameView setVirtualJoystick:0.0:0.0];
403}
404
405- (IBAction)showLogAction:sender
406{
407 [[NSWorkspace sharedWorkspace] openFile:[OOLogHandlerGetLogBasePath() stringByAppendingPathComponent:@"Previous.log"]];
408}
409
410- (IBAction)showLogFolderAction:sender
411{
412 [[NSWorkspace sharedWorkspace] openFile:OOLogHandlerGetLogBasePath()];
413}
414
415// Helpers to allow -snapshotsURLCreatingIfNeeded: code to be identical here and in dock tile plug-in.
416static id GetPreference(NSString* key, Class expectedClass)
417{
418 id result = [[NSUserDefaults standardUserDefaults] objectForKey:key];
419 if (expectedClass != Nil && ![result isKindOfClass:expectedClass])
420 result = nil;
421
422 return result;
423}
424
425static void SetPreference(NSString* key, id value)
426{
427 [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
428}
429
430static void RemovePreference(NSString* key)
431{
432 [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
433}
434
435#define kSnapshotsDirRefKey @"snapshots-directory-reference"
436#define kSnapshotsDirNameKey @"snapshots-directory-name"
437
438- (NSURL*)snapshotsURLCreatingIfNeeded:(BOOL)create
439{
440 BOOL stale = NO;
441 NSDictionary* snapshotDirDict = GetPreference(kSnapshotsDirRefKey, [NSDictionary class]);
442 NSURL* url = nil;
443 NSString* name = DESC(@"snapshots-directory-name-mac");
444
445 if (snapshotDirDict != nil) {
446 url = JAURLFromPersistentFileReference(snapshotDirDict, kJAPersistentFileReferenceWithoutUI | kJAPersistentFileReferenceWithoutMounting, &stale);
447 if (url != nil) {
448 NSString* existingName = [[url path] lastPathComponent];
449 if ([existingName compare:name options:NSCaseInsensitiveSearch] != 0) {
450 // Check name from previous access, because we might have changed localizations.
451 NSString* originalOldName = GetPreference(kSnapshotsDirNameKey, [NSString class]);
452 if (originalOldName == nil || [existingName compare:originalOldName options:NSCaseInsensitiveSearch] != 0) {
453 url = nil;
454 }
455 }
456
457 // did we put the old directory in the trash?
458 Boolean inTrash = false;
459 const UInt8* utfPath = (const UInt8*)[[url path] UTF8String];
460
461 OSStatus err = DetermineIfPathIsEnclosedByFolder(kOnAppropriateDisk, kTrashFolderType, utfPath, false, &inTrash);
462 // if so, create a new directory.
463 if (err == noErr && inTrash == true)
464 url = nil;
465 }
466 }
467
468 if (url == nil) {
469 NSString* path = nil;
470 NSArray* searchPaths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
471 if ([searchPaths count] > 0) {
472 path = [[searchPaths objectAtIndex:0] stringByAppendingPathComponent:name];
473 }
474 url = [NSURL fileURLWithPath:path];
475
476 if (url != nil) {
477 stale = YES;
478 if (create) {
479 NSFileManager* fmgr = [NSFileManager defaultManager];
480 if (![fmgr fileExistsAtPath:path]) {
481 [fmgr oo_createDirectoryAtPath:path attributes:nil];
482 }
483 }
484 }
485 }
486
487 if (stale) {
488 snapshotDirDict = JAPersistentFileReferenceFromURL(url);
489 if (snapshotDirDict != nil) {
490 SetPreference(kSnapshotsDirRefKey, snapshotDirDict);
491 SetPreference(kSnapshotsDirNameKey, [[url path] lastPathComponent]);
492 } else {
494 }
495 }
496
497 return url;
498}
499
500- (IBAction)showSnapshotsAction:sender
501{
502 [[NSWorkspace sharedWorkspace] openURL:[self snapshotsURLCreatingIfNeeded:YES]];
503}
504
505- (IBAction)showAddOnsAction:sender
506{
507 NSArray* paths = ResourceManager.userRootPaths;
508
509 // Look for an AddOns directory that actually contains some AddOns.
510 for (NSString* path in paths) {
511 if ([self addOnsExistAtPath:path]) {
512 [self openPath:path];
513 return;
514 }
515 }
516
517 // If that failed, look for an AddOns directory that actually exists.
518 for (NSString* path in paths) {
519 if ([self isDirectoryAtPath:path]) {
520 [self openPath:path];
521 return;
522 }
523 }
524
525 // None found, create the default path.
526 [NSFileManager.defaultManager createDirectoryAtPath:[paths objectAtIndex:0]
527 withIntermediateDirectories:YES
528 attributes:nil
529 error:NULL];
530 [self openPath:[paths objectAtIndex:0]];
531}
532
533- (BOOL)isDirectoryAtPath:(NSString*)path
534{
535 BOOL isDirectory;
536 return [NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory;
537}
538
539- (BOOL)addOnsExistAtPath:(NSString*)path
540{
541 if (![self isDirectoryAtPath:path])
542 return NO;
543
544 NSWorkspace* workspace = NSWorkspace.sharedWorkspace;
545 for (NSString* subPath in [NSFileManager.defaultManager enumeratorAtPath:path]) {
546 subPath = [path stringByAppendingPathComponent:subPath];
547 NSString* type = [workspace typeOfFile:subPath error:NULL];
548 if ([workspace type:type conformsToType:@"org.aegidian.oolite.expansion"])
549 return YES;
550 }
551
552 return NO;
553}
554
555- (void)openPath:(NSString*)path
556{
557 [NSWorkspace.sharedWorkspace openURL:[NSURL fileURLWithPath:path]];
558}
559
560- (BOOL)validateMenuItem:(NSMenuItem*)menuItem
561{
562 SEL action = menuItem.action;
563
564 if (action == @selector(showLogAction:)) {
565 // the first path is always Resources
566 return ([[NSFileManager defaultManager] fileExistsAtPath:[OOLogHandlerGetLogBasePath() stringByAppendingPathComponent:@"Previous.log"]]);
567 }
568
569 if (action == @selector(showAddOnsAction:)) {
570 // Always enabled in unrestricted mode, to allow users to add OXPs more easily.
571 return [ResourceManager useAddOns] != nil;
572 }
573
574 if (action == @selector(showSnapshotsAction:)) {
575 BOOL pathIsDirectory;
576 if (![[NSFileManager defaultManager] fileExistsAtPath:[self snapshotsURLCreatingIfNeeded:NO].path isDirectory:&pathIsDirectory]) {
577 return NO;
578 }
579 return pathIsDirectory;
580 }
581
582 if (action == @selector(toggleFullScreenAction:)) {
583 if (_fullScreenController.fullScreenMode) {
584 // NOTE: not DESC, because menu titles are not generally localizable.
585 menuItem.title = NSLocalizedString(@"Exit Full Screen", NULL);
586 } else {
587 menuItem.title = NSLocalizedString(@"Enter Full Screen", NULL);
588 }
589 }
590
591 // default
592 return YES;
593}
594
595- (NSMenu*)applicationDockMenu:(NSApplication*)sender
596{
597 return dockMenu;
598}
599
600#elif OOLITE_SDL
601
602- (NSURL*)snapshotsURLCreatingIfNeeded:(BOOL)create
603{
604 NSURL* url = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:DESC(@"snapshots-directory-name")]];
605
606 if (create) {
607 NSString* path = [url path];
608 NSFileManager* fmgr = [NSFileManager defaultManager];
609 if (![fmgr fileExistsAtPath:path]) {
610 [fmgr oo_createDirectoryAtPath:path attributes:nil];
611 }
612 }
613 return url;
614}
615
616#else
617#error Unknown environment!
618#endif
619
620- (void)logProgress:(NSString*)message
621{
622 if (![UNIVERSE doingStartUp])
623 return;
624
625#if OOLITE_MAC_COCOA_UI
626 [splashProgressTextField setStringValue:message];
627 [splashProgressTextField display];
628#endif
629 if ([message length] > 0) {
630 OOLog(@"startup.progress", @"===== [%.2f s] %@", -[_splashStart timeIntervalSinceNow], message);
631 }
632}
633
634#if OO_DEBUG
635#if OOLITE_MAC_COCOA_UI
636- (BOOL)debugMessageTrackingIsOn
637{
638 return splashProgressTextField != nil;
639}
640
641- (NSString*)debugMessageCurrentString
642{
643 return [splashProgressTextField stringValue];
644}
645#else
646- (BOOL)debugMessageTrackingIsOn
647{
648 return OOLogWillDisplayMessagesInClass(@"startup.progress");
649}
650
651- (NSString*)debugMessageCurrentString
652{
653 return @"";
654}
655#endif
656
657- (void)debugLogProgress:(NSString*)format, ...
658{
659 va_list args;
660 va_start(args, format);
661 [self debugLogProgress:format arguments:args];
662 va_end(args);
663}
664
665- (void)debugLogProgress:(NSString*)format arguments:(va_list)arguments
666{
667 NSString* message = [[[NSString alloc] initWithFormat:format arguments:arguments] autorelease];
668 [self logProgress:message];
669}
670
671static NSMutableArray* sMessageStack;
672
673- (void)debugPushProgressMessage:(NSString*)format, ...
674{
675 if ([self debugMessageTrackingIsOn]) {
676 if (sMessageStack == nil)
677 sMessageStack = [[NSMutableArray alloc] init];
678 [sMessageStack addObject:[self debugMessageCurrentString]];
679
680 va_list args;
681 va_start(args, format);
682 [self debugLogProgress:format arguments:args];
683 va_end(args);
684 }
685
686 OOLogIndentIf(@"startup.progress");
687}
688
689- (void)debugPopProgressMessage
690{
691 OOLogOutdentIf(@"startup.progress");
692
693 if ([sMessageStack count] > 0) {
694 NSString* message = [sMessageStack lastObject];
695 if ([message length] > 0)
696 [self logProgress:message];
697 [sMessageStack removeLastObject];
698 }
699}
700
701#endif
702
704{
705 OOLogSetDisplayMessagesInClass(@"startup.progress", NO);
706
707#if OOLITE_MAC_COCOA_UI
708 // These views will be released when we replace the content view.
710 splashView = nil;
711
712 [gameWindow setAcceptsMouseMovedEvents:YES];
713 [gameWindow setContentView:gameView];
714 [gameWindow makeFirstResponder:gameView];
715#elif OOLITE_SDL
717#endif
718}
719
720#if OOLITE_MAC_COCOA_UI
721
722// NIB methods
724{
725 NSString* path = nil;
726
727 // Set contents of Help window
728 path = [[NSBundle mainBundle] pathForResource:@"OoliteReadMe" ofType:@"pdf"];
729 if (path != nil) {
730 PDFDocument* document = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:path]];
731 [helpView setDocument:document];
732 [document release];
733 }
734 [helpView setBackgroundColor:[NSColor whiteColor]];
735}
736
737// delegate methods
738- (BOOL)application:(NSApplication*)theApplication openFile:(NSString*)filename
739{
740 if ([[filename pathExtension] isEqual:@"oolite-save"]) {
741 [self setPlayerFileToLoad:filename];
742 [self setPlayerFileDirectory:filename];
743 return YES;
744 }
745 if ([[filename pathExtension] isEqualToString:@"oxp"]) {
746 BOOL dir_test;
747 [[NSFileManager defaultManager] fileExistsAtPath:filename isDirectory:&dir_test];
748 if (dir_test) {
751 }
752 [expansionPathsToInclude addObject:filename];
753 return YES;
754 }
755 }
756 return NO;
757}
758
759- (void)exitAppWithContext:(NSString*)context
760{
761 [gameView.window orderOut:nil];
762 [(OoliteApp*)NSApp setExitContext:context];
763 [NSApp terminate:self];
764}
765
766- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender
767{
770 return NSTerminateNow;
771}
772
773#elif OOLITE_SDL
774#include <SDL3/SDL_init.h>
775
776- (void)exitAppWithContext:(NSString*)context
777{
778 OOLog(@"exit.context", @"Exiting: %@.", context);
779#if (OOLITE_SDL && defined(OO_DEBUG_MONITOR_ENABLED))
780 [[OODebugMonitor sharedDebugMonitor] applicationWillTerminate];
781#endif
782#if OOLITE_WINDOWS
783 // This should not be required normally but we have to ensure that
784 // desktop resolution is restored also on some Intel cards on Win10
785 if (![gameView atDesktopResolution]) {
786 OOLog(@"gameController.exitApp", @"%@", @"Restoring desktop resolution.");
787 ChangeDisplaySettingsEx(NULL, NULL, NULL, 0, NULL);
788 }
789#endif
790 [[NSUserDefaults standardUserDefaults] synchronize];
791 OOLog(@"gameController.exitApp", @"%@", @".GNUstepDefaults synchronized.");
792#if OOJS_QUICKJS && !defined(NDEBUG)
793 // Leak check: tears down the JavaScript runtime and logs any objects still alive.
795#endif
797 SDL_Quit();
799 exit(0);
800}
801
802#else
803#error Unknown environment!
804#endif
805
807{
808 [self exitAppWithContext:@"Command-Q"];
809}
810
811- (void)windowDidResize:(NSNotification*)aNotification
812{
814}
815
817{
818 return playerFileToLoad;
819}
820
821- (void)setPlayerFileToLoad:(NSString*)filename
822{
824 [playerFileToLoad autorelease];
826 if ([[[filename pathExtension] lowercaseString] isEqual:@"oolite-save"])
827 playerFileToLoad = [filename copy];
828}
829
831{
832 if (playerFileDirectory == nil) {
833 playerFileDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"save-directory"];
834 if (playerFileDirectory != nil && ![[NSFileManager defaultManager] fileExistsAtPath:playerFileDirectory]) {
836 }
838 playerFileDirectory = [[NSFileManager defaultManager] defaultCommanderPath];
839
840 [playerFileDirectory retain];
841 }
842
843 return playerFileDirectory;
844}
845
846- (void)setPlayerFileDirectory:(NSString*)filename
847{
848 if (playerFileDirectory != nil) {
849 [playerFileDirectory autorelease];
851 }
852
853 if ([[[filename pathExtension] lowercaseString] isEqual:@"oolite-save"]) {
854 filename = [filename stringByDeletingLastPathComponent];
855 }
856
857 playerFileDirectory = [filename retain];
858 [[NSUserDefaults standardUserDefaults] setObject:filename forKey:@"save-directory"];
859}
860
861- (void)reportUnhandledStartupException:(NSException*)exception
862{
863 OOLog(@"startup.exception", @"***** Unhandled exception during startup: %@ (%@).", [exception name], [exception reason]);
864
865#if OOLITE_MAC_COCOA_UI
866 // Display an error alert.
867 // TODO: provide better information on reporting bugs in the manual, and refer to it here.
868 NSRunCriticalAlertPanel(@"Oolite failed to start up, because an unhandled exception occurred.", @"An exception of type %@ occurred. If this problem persists, please file a bug report.", @"OK", NULL, NULL, [exception name]);
869#endif
870}
871
872#ifndef NDEBUG
873/* This method exists purely to suppress Clang static analyzer warnings that
874 these ivars are unused (but may be used by categories, which they are).
875*/
877{
878 return pauseSelector && pauseTarget;
879}
880#endif
881
882@end
883
884#if OOLITE_MAC_COCOA_UI
885
886static void SetUpSparkle(void)
887{
888#define FEED_URL_BASE "http://www.oolite.org/updates/"
889#define TEST_RELEASE_FEED_NAME "oolite-mac-test-release-appcast.xml"
890#define DEPLOYMENT_FEED_NAME "oolite-mac-appcast.xml"
891
892#define TEST_RELEASE_FEED_URL (@FEED_URL_BASE TEST_RELEASE_FEED_NAME)
893#define DEPLOYMENT_FEED_URL (@FEED_URL_BASE DEPLOYMENT_FEED_NAME)
894
895// Default to test releases in test release or debug builds, and stable releases for deployment builds.
896#ifdef NDEBUG
897#define DEFAULT_TEST_RELEASE 0
898#else
899#define DEFAULT_TEST_RELEASE 1
900#endif
901
902 BOOL useTestReleases = [[NSUserDefaults standardUserDefaults] oo_boolForKey:@"use-test-release-updates"
903 defaultValue:DEFAULT_TEST_RELEASE];
904
905 SUUpdater* updater = [SUUpdater sharedUpdater];
906 [updater setFeedURL:[NSURL URLWithString:useTestReleases ? TEST_RELEASE_FEED_URL : DEPLOYMENT_FEED_URL]];
907}
908
909#endif
#define MINIMUM_GAME_TICK
static GameController * sSharedController
#define kSnapshotsDirNameKey
#define kSnapshotsDirRefKey
static void SetUpSparkle(void)
#define EXPECT_NOT(x)
void OOJSFrameCallbacksInvoke(OOTimeDelta delta)
NSString * OOLogHandlerGetLogBasePath(void)
BOOL OOLogWillDisplayMessagesInClass(NSString *inMessageClass)
Definition OOLogging.m:136
#define OOLogOutdentIf(class)
Definition OOLogging.h:112
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define OOLogIndentIf(class)
Definition OOLogging.h:107
void OOLoggingTerminate(void)
Definition OOLogging.m:562
void OOLogSetDisplayMessagesInClass(NSString *inClass, BOOL inFlag)
Definition OOLogging.m:172
OOMouseInteractionMode
NSString * OOStringFromMouseInteractionMode(OOMouseInteractionMode mode)
unsigned count
return nil
#define PLAYER
#define UNIVERSE
Definition Universe.h:827
#define DESC(key)
Definition Universe.h:832
void setMouseInteractionMode:(OOMouseInteractionMode mode)
void setMouseInteractionModeForUIWithMouseInteraction:(BOOL interaction)
IBOutlet NSTextField * splashProgressTextField
static id GetPreference(NSString *key, Class expectedClass)
OOMouseInteractionMode mouseInteractionMode()
void setUpDisplayModes()
NSString * playerFileToLoad
GameController * sharedController()
NSMutableArray * expansionPathsToInclude
OOMouseInteractionMode _resumeMode
NSTimeInterval last_timeInterval
void recenterVirtualJoystick()
NSString * playerFileDirectory
void reportUnhandledStartupException:(NSException *exception)
void openPath:(NSString *path)
void logProgress:(NSString *message)
NSDate * _splashStart
NSTimeInterval _animationTimerInterval
void exitAppWithContext:(NSString *context)
static void SetPreference(NSString *key, id value)
OOMouseInteractionMode _mouseMode
void setPlayerFileDirectory:(NSString *filename)
void setEcoQoS:(BOOL efficiencyModeRequested)
void setMouseInteractionModeForFlight()
NSObject * pauseTarget
void setFullScreenMode:(BOOL value)
NSURL * snapshotsURLCreatingIfNeeded:(BOOL create)
IBOutlet MyOpenGLView * gameView
static void RemovePreference(NSString *key)
void setPlayerFileToLoad:(NSString *filename)
IBOutlet NSView * splashView
OOFullScreenController * _fullScreenController
IBOutlet NSMenu * dockMenu
BOOL inFullScreenMode()
void endSplashScreen()
void noteMouseInteractionModeChangedFrom:to:(OOMouseInteractionMode oldMode,[to] OOMouseInteractionMode newMode)
void setGameController:(GameController *controller)
void initSplashScreen()
OOCacheManager * sharedCache()
OODebugMonitor * sharedDebugMonitor()
void noteMouseInteractionModeChangedFrom:to:(OOMouseInteractionMode oldMode,[to] OOMouseInteractionMode newMode)
OOJavaScriptEngine * sharedEngine()
BOOL setStickHandlerClass:(Class aClass)
OOOXZManager * sharedManager()
OOOpenALController * sharedController()
void update()
Definition OOALSound.m:136
void addExternalPath:(NSString *fileName)
NSString * useAddOns()
NSArray * userRootPaths()
const char * filename
Definition ioapi.h:125
const char int mode
Definition ioapi.h:125
void ranrot_srand(uint32_t seed)