Oolite
Loading...
Searching...
No Matches
MyOpenGLView.m
Go to the documentation of this file.
1/*
2
3MyOpenGLView.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 "MyOpenGLView.h"
26#import "GameController.h"
27#import "GuiDisplayGen.h"
29#import "NSFileManagerOOExtensions.h" // to find savedir
30#import "OOCollectionExtractors.h" // for splash screen settings
31#import "OOConstToString.h"
35#import "OOSound.h"
36#import "PlanetEntity.h"
37#import "PlayerEntity.h"
38#import "ResourceManager.h"
39#import "Universe.h"
40#import "png.h"
41#include <SDL3/SDL_clipboard.h>
42#include <SDL3/SDL_init.h>
43
44#define STB_IMAGE_WRITE_IMPLEMENTATION
45#import "stb_image_write.h"
46
47#define kOOLogUnconvertedNSLog @"unclassified.MyOpenGLView"
48
49extern int SaveEXRSnapshot(const char* outfilename, int width, int height, const float* rgb);
50
51#include <ctype.h>
52
53@interface MyOpenGLView (OOPrivate)
54
55@end
56
57@implementation MyOpenGLView
58
59- (SDL_DisplayID)getDisplayId
60{
61 SDL_DisplayID displayId = 0;
62 if (window) {
63 displayId = SDL_GetDisplayForWindow(window);
64 } else {
65 int displayCount;
66 SDL_DisplayID* displayIds = SDL_GetDisplays(&displayCount);
67 if (displayIds) {
68 displayId = displayIds[0];
69 } else {
70 OOLog(@"sdl.display_id", @"Could not get list of displays. Error was: %s", SDL_GetError());
71 }
72 SDL_free(displayIds);
73 }
74 return displayId;
75}
76
77- (NSMutableDictionary*)getNativeSize
78{
79 NSMutableDictionary* mode = [[NSMutableDictionary alloc] init];
80 int nativeDisplayWidth = 1024;
81 int nativeDisplayHeight = 768;
82
83 SDL_DisplayID displayId = [self getDisplayId];
84 SDL_Rect boundsRect;
85 if (displayId && SDL_GetDisplayUsableBounds(displayId, &boundsRect)) {
86 nativeDisplayWidth = boundsRect.w;
87 nativeDisplayHeight = boundsRect.h;
88 OOLog(@"display.mode.list.native", @"Native display resolution detected: %d x %d", nativeDisplayWidth, nativeDisplayHeight);
89 } else {
90 OOLog(@"display.mode.list.native.failed", @"%@", @"SDL_GetWMInfo failed, defaulting to 1024x768 for native size");
91 }
92
93 [mode setValue:[NSNumber numberWithInt:nativeDisplayWidth] forKey:kOODisplayWidth];
94 [mode setValue:[NSNumber numberWithInt:nativeDisplayHeight] forKey:kOODisplayHeight];
95 [mode setValue:[NSNumber numberWithInt:0] forKey:kOODisplayRefreshRate];
96
97 return [mode autorelease];
98}
99
101{
102 NSString* caption = [NSString stringWithFormat:@"Oolite v%@ by %@ - %@", @OO_VERSION_FULL, @OO_BUILDER, @OO_BUILD_DATE];
103 return [[caption retain] autorelease];
104}
105
106- (void)createWindowWithSize:(NSSize)size
107{
108 NSUserDefaults* prefs = [NSUserDefaults standardUserDefaults];
109
110 OOLog(@"display.initGL", @"Trying %d-bpcc, 24-bit depth buffer", bitsPerColorComponent);
111 if (bitsPerColorComponent > 8) {
112 SDL_GL_SetAttribute(SDL_GL_FLOATBUFFERS, 1);
113 _hdrOutput = YES;
114 } else {
115 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, bitsPerColorComponent);
116 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, bitsPerColorComponent);
117 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, bitsPerColorComponent);
118 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, bitsPerColorComponent);
119 _hdrOutput = NO;
120 }
121 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
122 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
123
124 /* Multisampling significantly improves graphics quality with
125 * basically no extra programming effort on our part, especially
126 * for curved surfaces like the planet, but is also expensive - in
127 * the worst case the entire scene must be rendered four
128 * times. For now it can be a hidden setting. If early testing
129 * doesn't give any problems (other than speed on low-end graphics
130 * cards) a game options entry might be useful. - CIM, 24 Aug 2013*/
131
132 if ([prefs oo_boolForKey:@"anti-aliasing" defaultValue:NO]) {
133 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
134 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
135 }
136
137 NSString* windowCaption = [self getWindowCaption];
138 Uint32 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS | SDL_WINDOW_HIGH_PIXEL_DENSITY;
139 if (glContext) {
140 // Game window replacing the splash window: create it hidden with its final
141 // decorations so it is mapped only once (see endSplashScreen).
142 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY;
143 }
144
145 // Define modern SDL3 properties for window configuration
146 SDL_PropertiesID props = SDL_CreateProperties();
147 SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, [windowCaption UTF8String]);
148 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, size.width);
149 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, size.height);
150 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_FLAGS_NUMBER, windowFlags);
151
152 // Explicit centering properties setup for SDL3
153 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_CENTERED);
154 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_CENTERED);
155
156 window = SDL_CreateWindowWithProperties(props);
157 if (!window) {
158 OOLog(@"display.initGL", @"%@", @"Trying 8-bpcc, 24-bit depth buffer");
159 SDL_GL_SetAttribute(SDL_GL_FLOATBUFFERS, 0);
160 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
161 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
162 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
163 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
164 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
165 window = SDL_CreateWindowWithProperties(props);
166 _hdrOutput = NO;
167 }
168
169 if (!window) {
170 OOLog(@"display.initGL", @"%@", @"Trying 5-bpcc, 16-bit depth buffer");
171 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
172 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
173 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
174 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
175 // and if it's this bad, forget even trying to multisample!
176 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
177 SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
178 window = SDL_CreateWindowWithProperties(props);
179 }
180
181 // Clean up properties block
182 SDL_DestroyProperties(props);
183
184 if (!window) {
185 const char* errStr = SDL_GetError();
186 OOLogERR(@"display.mode.error", @"Could not create window: %s", errStr);
187 exit(1);
188 }
189 if (glContext) {
190 // Keep the splash screen's context (and its textures); the GL attributes are unchanged,
191 // so the new window's pixel format matches.
192 if (!SDL_GL_MakeCurrent(window, glContext)) {
193 OOLog(@"sdl.create_context", @"Could not make OpenGL context current: %s", SDL_GetError());
194 exit(1);
195 }
196 } else {
197 glContext = SDL_GL_CreateContext(window);
198 }
199 if (!glContext) {
200 OOLog(@"sdl.create_context", @"%@", @"Could not create OpenGL context");
201 exit(1);
202 }
203#if !OOLITE_MAC_OS_X
204 // On macOS a window surface replaces the OpenGL drawable, so it must not be created there.
205 SDL_Surface* surface = SDL_GetWindowSurface(window);
206 if (!SDL_SetSurfaceColorspace(surface, SDL_COLORSPACE_SRGB_LINEAR)) {
207 OOLogWARN(@"sdl.use_edr_surface", @"%@ %s", @"Failed to set SDR linear surface - falling back to SDR. Error was:", SDL_GetError());
208 SDL_SetSurfaceColorspace(surface, SDL_COLORSPACE_SRGB);
209 }
210#endif
211 // Every window shares the single glContext, which owns Universe's GL objects (VAOs, FBOs,
212 // shaders). SDL_GetWindowSurface() may create an internal GL renderer context for the window
213 // and leave it current, so make glContext current again before any GL call.
214 if (!SDL_GL_MakeCurrent(window, glContext)) {
215 OOLog(@"sdl.create_context", @"Could not make OpenGL context current: %s", SDL_GetError());
216 exit(1);
217 }
218
219#if OOLITE_WINDOWS
220 // capture the window handle for later (only needed for ugly hack later when transitioning between
221 // full screen and window). Don't use anywhere else.
222 SDL_PropertiesID windowPropertiesId = SDL_GetWindowProperties(window);
223 windowHandle = SDL_GetPointerProperty(windowPropertiesId, SDL_PROP_WINDOW_WIN32_HWND_POINTER, NULL);
224 if (!windowHandle) {
225 OOLog(@"sdl.window_handle", @"%@", @"Failed to retrieve window handle");
226 exit(1);
227 }
228
229 atDesktopResolution = YES;
230
231#endif // OOLITE_WINDOWS
232
233#if !OOLITE_MAC_OS_X
234 // On macOS SDL would set this 32x32 image as the Dock icon, replacing the bundle's
235 // high-resolution oolite-icon.icns.
236 NSString* imagesDir = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Images"];
237 SDL_Surface* icon = SDL_LoadBMP([[imagesDir stringByAppendingPathComponent:@"WMicon.bmp"] UTF8String]);
238
239 if (icon != NULL) {
240 const SDL_PixelFormatDetails* pixelFormat = SDL_GetPixelFormatDetails(icon->format);
241 const SDL_Palette* palette = SDL_GetSurfacePalette(icon);
242 Uint32 colorkey = SDL_MapRGB(pixelFormat, palette, 128, 0, 128);
243 SDL_SetSurfaceColorKey(icon, YES, colorkey);
244 SDL_SetWindowIcon(window, icon);
245 }
246 SDL_DestroySurface(icon);
247#endif
248
249 _colorSaturation = 1.0f;
250
251#if OOLITE_WINDOWS
252 _hdrMaxBrightness = [prefs oo_floatForKey:@"hdr-max-brightness" defaultValue:1000.0f];
253 _hdrPaperWhiteBrightness = [prefs oo_floatForKey:@"hdr-paperwhite-brightness" defaultValue:200.0f];
254 _hdrToneMapper = OOHDRToneMapperFromString([prefs oo_stringForKey:@"hdr-tone-mapper" defaultValue:@"OOHDR_TONEMAPPER_ACES_APPROX"]);
255#endif
256
257 _sdrToneMapper = OOSDRToneMapperFromString([prefs oo_stringForKey:@"sdr-tone-mapper" defaultValue:@"OOSDR_TONEMAPPER_ACES"]);
258
259#if OOLITE_MAC_OS_X
260 SDL_GL_SetSwapInterval(vSyncPreference ? 1 : 0);
261#else
262 SDL_SetWindowSurfaceVSync(window, vSyncPreference);
263#endif
264 OOLog(@"display.initGL", @"V-Sync %@requested.", vSyncPreference ? @"" : @"not ");
265
266 int testAttrib = -1;
267 OOLog(@"display.initGL", @"%@", @"Achieved color / depth buffer sizes (bits):");
268 SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &testAttrib);
269 OOLog(@"display.initGL", @"Red: %d", testAttrib);
270 SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &testAttrib);
271 OOLog(@"display.initGL", @"Green: %d", testAttrib);
272 SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &testAttrib);
273 OOLog(@"display.initGL", @"Blue: %d", testAttrib);
274 SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &testAttrib);
275 OOLog(@"display.initGL", @"Alpha: %d", testAttrib);
276 SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &testAttrib);
277 OOLog(@"display.initGL", @"Depth Buffer: %d", testAttrib);
278
279 SDL_GL_GetAttribute(SDL_GL_FLOATBUFFERS, &testAttrib);
280 OOLog(@"display.initGL", @"Pixel type is float : %d", testAttrib);
281
282 SDL_PixelFormat format = SDL_GetWindowPixelFormat(window);
283 OOLog(@"display.initGL", @"Window Pixel Format: %s", SDL_GetPixelFormatName(format));
284
285 // Verify V-sync successfully set - report it if not
286
287 int hasVsync;
288#if OOLITE_MAC_OS_X
289 if (vSyncPreference && (!SDL_GL_GetSwapInterval(&hasVsync) || !hasVsync)) {
290#else
291 if (vSyncPreference && (!SDL_GetWindowSurfaceVSync(window, &hasVsync) || !hasVsync)) {
292#endif
293 OOLogWARN(@"display.initGL", @"Could not enable V-Sync. Please check that your graphics driver supports the %@_swap_control extension.",
294 OOLITE_WINDOWS ? @"WGL_EXT" : @"[GLX_SGI/GLX_MESA]");
295 } else {
296 OOLog(@"display.initGL", @"%@", @"V-Sync set");
297 }
298
299 int width, height;
300 SDL_GetWindowSizeInPixels(window, &width, &height);
301 bounds.size.width = width;
302 bounds.size.height = height;
303
304 return;
305}
306
307- (id)init
308{
309 self = [super init];
310
311 NSString* cmdLineArgsStr = @"Startup command: ";
312
313 // SDL splash screen settings
314
315 NSUserDefaults* prefs = [NSUserDefaults standardUserDefaults];
316 showSplashScreen = [prefs oo_boolForKey:@"splash-screen" defaultValue:YES];
317 vSyncPreference = [prefs oo_boolForKey:@"v-sync" defaultValue:YES];
318 bitsPerColorComponent = [prefs oo_boolForKey:@"hdr" defaultValue:NO] ? 16 : 8;
319
320 NSArray* arguments = nil;
321 NSEnumerator* argEnum = nil;
322 NSString* arg = nil;
323 BOOL noSplashArgFound = NO;
324
325 [self initKeyMappingData];
326
327 // preload the printscreen key into our translation array because SDLK_PRINTSCREEN isn't available
329
330 arguments = [[NSProcessInfo processInfo] arguments];
331
332 // scan for splash screen overrides: -nosplash || --nosplash , -splash || --splash
333 // scan for V-sync disabling overrides: -novsync || --novsync
334 for (argEnum = [arguments objectEnumerator]; (arg = [argEnum nextObject]);) {
335 if ([arg isEqual:@"-nosplash"] || [arg isEqual:@"--nosplash"]) {
336 showSplashScreen = NO;
337 noSplashArgFound = YES; // -nosplash always trumps -splash
338 } else if (([arg isEqual:@"-splash"] || [arg isEqual:@"--splash"]) && !noSplashArgFound) {
339 showSplashScreen = YES;
340 }
341
342 // if V-sync is disabled at the command line, override the defaults file
343 if ([arg isEqual:@"-novsync"] || [arg isEqual:@"--novsync"])
344 vSyncPreference = NO;
345
346 if ([arg isEqual:@"-hdr"])
348
349 // build the startup command string so that we can log it
350 cmdLineArgsStr = [cmdLineArgsStr stringByAppendingFormat:@"%@ ", arg];
351 }
352
353 OOLog(@"process.args", @"%@", cmdLineArgsStr);
354
355#if OOLITE_SPEECH_SYNTH
356#if OOLITE_ESPEAK
357 if (!SDL_getenv("ESPEAK_DATA_PATH")) {
358 espeak_Initialize(AUDIO_OUTPUT_PLAYBACK, 100, [[ResourceManager builtInPath] UTF8String], 0);
359 } else {
360 espeak_Initialize(AUDIO_OUTPUT_PLAYBACK, 100, NULL, 0);
361 }
362#endif
363#endif
364
365 matrixManager = [[OOOpenGLMatrixManager alloc] init];
366
367 // TODO: This code up to and including stickHandler really ought
368 // not to be in this class.
369 OOLog(@"sdl.init", @"%@", @"initialising SDL");
370 if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_GAMEPAD)) {
371 OOLog(@"sdl.init.failed", @"Unable to init SDL: %s\n", SDL_GetError());
372 [self dealloc];
373 return nil;
374 }
375
377
378 // Find what the full screen and windowed settings are.
379 fullScreen = NO;
380 currentSize = 0;
381 [self loadWindowSize];
383
384 // Set up the drawing surface's dimensions.
385 firstScreen = (fullScreen) ? [self modeAsSize:currentSize] : currentWindowSize;
386 viewSize = firstScreen; // viewSize must be set prior to splash screen initialization
387
389 // end TODO
390
391 [OOSound setUp];
392 if (![OOSound isSoundOK])
393 OOLog(@"sound.init", @"%@", @"Sound system disabled.");
394
395 grabMouseStatus = NO;
396
397 OOLog(@"display.mode.list", @"%@", @"CREATING MODE LIST");
398
399 if (!showSplashScreen) {
400 // blank the surface / go to fullscreen
401 [self initialiseGLWithSize:firstScreen];
402 }
403
404 [self autoShowMouse];
405
406 virtualJoystickPosition = NSMakePoint(0.0, 0.0);
407 mouseWarped = NO;
408
409 _mouseVirtualStickSensitivityFactor = OOClamp_0_1_f([prefs oo_floatForKey:@"mouse-flight-sensitivity" defaultValue:0.95f]);
410 // ensure no chance of a divide by zero later on
413
414 typedString = [[NSMutableString alloc] initWithString:@""];
417
418 timeIntervalAtLastClick = timeSinceLastMouseWheel = [NSDate timeIntervalSinceReferenceDate];
419
420 _mouseWheelDelta = 0.0f;
421
422 return self;
423}
424
426{
427#if OOLITE_WINDOWS
428 // we need to get through here even if splash screen has not
429 // been shown - this method also prepares the main game window
430 if ([self hdrOutput] && ![self isOutputDisplayHDREnabled]) {
431 if (MessageBox(NULL, "No primary display in HDR mode was detected.\n\n"
432 "If you continue, graphics will not be rendered as intended.\n"
433 "Click OK to launch anyway, or Cancel to exit.",
434 "oolite.exe - HDR requested",
435 MB_OKCANCEL | MB_ICONWARNING)
436 == IDCANCEL) {
437 [gameController exitAppWithContext:@"Cancel selected on no-HDR confirmation dialog"];
438 }
439 }
440
441#endif
442 BOOL replaceSplashWindow = showSplashScreen && !fullScreen && window && glContext;
443 if (!replaceSplashWindow) {
444 SDL_SetWindowResizable(window, true);
445 SDL_SetWindowBordered(window, true);
446 }
447 if (!showSplashScreen)
448 return;
449
450 if (fullScreen) {
451 SDL_SetWindowFullscreen(window, true);
452 } else {
453 // Some window managers (e.g. Marco) leave the borderless splash window unframed
454 // after it gains a border, and some (e.g. Mutter under XWayland) drop its focus.
455 // Replace it with a new window that has its final size, border and centred
456 // position before it is mapped. The splash window is destroyed before the new one
457 // is shown, so no other Oolite window holds focus when the new one is mapped.
458 SDL_Window* previousWindow = window; // the window in use so far, which showed the splash
459 window = NULL;
460 [self createWindowWithSize:firstScreen];
461 SDL_DestroyWindow(previousWindow);
462 // createWindowWithSize: left glContext current, and SDL_DestroyWindow does not destroy
463 // it. But destroying the old window frees the GL context of its SDL framebuffer renderer,
464 // which SDL makes current and then releases, so no context is current afterwards.
465 // Rebind glContext before anything draws.
466 if (!SDL_GL_MakeCurrent(window, glContext)) {
467 OOLog(@"sdl.create_context", @"Could not make OpenGL context current: %s", SDL_GetError());
468 exit(1);
469 }
470 SDL_ShowWindow(window);
471 }
472
473 /* MKW 2011.11.11
474 * Eat all SDL events to gobble up any resize events while the
475 * splash-screen was visible. They affected the main window after 1.74.
476 * TODO: should really process SDL events while showing the splash-screen
477
478 int numEvents = 0;
479 */
480 SDL_Event dummyEvent;
481 while (SDL_PollEvent(&dummyEvent)) {
482 /* Do nothing; the below is for development info
483 numEvents++;
484 OOLog(@"display.splash", @"Suppressed splash-screen event %d: %d ", numEvents, dummyEvent.type);
485 */
486 }
487
488 [self initialiseGLWithSize:firstScreen];
489 [self updateScreen];
490 [self autoShowMouse];
491}
492
493- (void)updateGLSize:(NSSize)size
494{
495 bounds.size = size;
496 viewSize = size;
497
498 if (bounds.size.width / bounds.size.height > 4.0 / 3.0) {
499 display_z = 480.0 * bounds.size.width / bounds.size.height;
500 x_offset = 240.0 * bounds.size.width / bounds.size.height;
501 y_offset = 240.0;
502 } else {
503 display_z = 640.0;
504 x_offset = 320.0;
505 y_offset = 320.0 * bounds.size.height / bounds.size.width;
506 }
507
508 float ratio = 0.5;
509 float aspect = bounds.size.height / bounds.size.width;
510
511 OOGL(glViewport(0, 0, bounds.size.width, bounds.size.height));
513 OOGLFrustum(-ratio, ratio, -aspect * ratio, aspect * ratio, 1.0, MAX_CLEAR_DEPTH);
514}
515
517{
519
520 OOGL(glClearColor(0.0, 0.0, 0.0, 0.0));
521 OOGL(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
522 OOGL(glClearDepth(1.0));
523 OOGL(glDepthFunc(GL_LESS)); // depth buffer
524
525 if (UNIVERSE) {
526 [UNIVERSE setLighting];
527 } else {
528 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
529 GLfloat white[] = { 1.0, 1.0, 1.0, 1.0 };
530 GLfloat stars_ambient[] = { 0.25, 0.2, 0.25, 1.0 };
531
532 OOGL(glLightfv(GL_LIGHT1, GL_AMBIENT, black));
533 OOGL(glLightfv(GL_LIGHT1, GL_SPECULAR, white));
534 OOGL(glLightfv(GL_LIGHT1, GL_DIFFUSE, white));
535 OOGL(glLightfv(GL_LIGHT1, GL_POSITION, black));
536 OOGL(glLightModelfv(GL_LIGHT_MODEL_AMBIENT, stars_ambient));
537 }
538
539 if ([extMgr usePointSmoothing]) {
540 OOGL(glEnable(GL_POINT_SMOOTH));
541 }
542
543 if ([extMgr useLineSmoothing]) {
544 OOGL(glEnable(GL_LINE_SMOOTH));
545 }
546
547 OOGL(glDisable(GL_NORMALIZE));
548 OOGL(glDisable(GL_RESCALE_NORMAL));
549
550 OOGL(glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR));
551}
552
553- (void)initialiseGLWithSize:(NSSize)v_size
554{
555 if (!window) {
556 [self createWindowWithSize:v_size];
557 }
558
559 viewSize = v_size;
560
561 OOLog(@"display.initGL", @"Requested a new surface of %d x %d, %@.", (int)viewSize.width, (int)viewSize.height,
562 (fullScreen ? @"fullscreen" : @"windowed"));
563
564 SDL_GL_SwapWindow(window); // clear the buffer before resize
565
566 SDL_SetWindowFullscreen(window, fullScreen);
567
568 if (!fullScreen) {
569 SDL_SetWindowSize(window, viewSize.width, viewSize.height);
570 SDL_SetWindowBordered(window, YES);
571 }
572#if OOLITE_WINDOWS
573 else // Hack for Windows SDL3 pause issue: https://github.com/libsdl-org/SDL/issues/12791
574 { // Occurs on some systems eg. when going fullscreen -> window or vice versa
575 LONG currentWindowStyle = GetWindowLong(windowHandle, GWL_STYLE);
576 currentWindowStyle &= ~WS_POPUP;
577 SetWindowLong(windowHandle, GWL_STYLE, currentWindowStyle);
578 }
579#endif
580
581 int pixelWidth, pixelHeight;
582 SDL_GetWindowSizeInPixels(window, &pixelWidth, &pixelHeight);
583
584 [self updateGLSize:NSMakeSize(pixelWidth, pixelHeight)];
585
586 OOLog(@"display.initGL",
587 @"Created a new surface of %d x %d, %@.",
588 (int)viewSize.width,
589 (int)viewSize.height,
590 (fullScreen ? @"fullscreen" : @"windowed"));
591
592 [self autoShowMouse];
593
595
596 SDL_GL_SwapWindow(window);
597
598 squareX = 0.0f;
599}
600
601- (void)dealloc
602{
603 if (typedString)
604 [typedString release];
605
606 if (screenSizes)
607 [screenSizes release];
608
609 if (window) {
610 SDL_DestroyWindow(window);
611 }
612
613 if (glContext) {
614 SDL_GL_DestroyContext(glContext);
615 }
616
618 [keyMappings_normal release];
619
621 [keyMappings_shifted release];
622
623 SDL_Quit();
624
625 if (matrixManager) {
626 [matrixManager release];
627 }
628
629 [super dealloc];
630}
631
632- (NSRect)bounds
633{
634 return bounds;
635}
636
637- (NSSize)viewSize
638{
639 return viewSize;
640}
641
643{
644 return bounds.size;
645}
646
647- (GLfloat)display_z
648{
649 return display_z;
650}
651
652- (GLfloat)x_offset
653{
654 return x_offset;
655}
656
657- (GLfloat)y_offset
658{
659 return y_offset;
660}
661
666
667- (void)setGameController:(GameController*)controller
668{
669 gameController = controller;
670}
671
673{
674 return fullScreen;
675}
676
677#if OOLITE_SDL
678- (void)setFullScreenMode:(BOOL)fsm
679{
680 fullScreen = fsm;
681
682 // Save the settings for later.
683 [[NSUserDefaults standardUserDefaults]
684 setBool:fullScreen
685 forKey:@"fullscreen"];
686 [[NSUserDefaults standardUserDefaults] synchronize];
687}
688
689- (void)toggleScreenMode
690{
691 [self setFullScreenMode:!fullScreen];
692 if (fullScreen) {
693 [self initialiseGLWithSize:[self modeAsSize:currentSize]];
694 } else {
695 [self initialiseGLWithSize:currentWindowSize];
696#if OOLITE_LINUX
697 SDL_HideWindow(window);
698 SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
699 SDL_ShowWindow(window);
700#endif
701 }
702}
703
704- (void)setDisplayMode:(int)mode fullScreen:(BOOL)fsm
705{
706 [self setFullScreenMode:fsm];
707 currentSize = mode;
708 if (fullScreen)
709 [self initialiseGLWithSize:[self modeAsSize:mode]];
710}
711
712- (void)setScreenSize:(int)sizeIndex
713{
714 currentSize = sizeIndex;
715 if (fullScreen)
716 [self initialiseGLWithSize:[self modeAsSize:currentSize]];
717}
718
719- (NSMutableArray*)getScreenSizeArray
720{
721 return screenSizes;
722}
723
724- (NSSize)modeAsSize:(int)sizeIndex
725{
726 NSDictionary* mode = [screenSizes objectAtIndex:sizeIndex];
727 return NSMakeSize([[mode objectForKey:kOODisplayWidth] intValue],
728 [[mode objectForKey:kOODisplayHeight] intValue]);
729}
730
731#endif
732
734{
735 if (UNIVERSE) {
736 [UNIVERSE drawUniverse]; // do all the drawing!
737 } else {
738 glClearColor(0.0, 0.0, 0.0, 0.0); // not set up yet, draw a black screen
739 glClear(GL_COLOR_BUFFER_BIT);
740 }
741
742 SDL_GL_SwapWindow(window);
743}
744
746{
747 if (!showSplashScreen)
748 return;
749
750 // too early for OOTexture!
751 SDL_Surface* image = NULL;
752 SDL_Rect dest;
753
754 NSString* imagesDir = [[ResourceManager builtInPath] stringByAppendingPathComponent:@"Images"];
755
756 image = SDL_LoadBMP([[imagesDir stringByAppendingPathComponent:@"splash.bmp"] UTF8String]);
757
758 if (image == NULL) {
759 SDL_DestroySurface(image);
760 OOLogWARN(@"sdl.gameStart", @"%@", @"image 'splash.bmp' not found!");
761 [self endSplashScreen];
762 return;
763 }
764
765 dest.x = 0;
766 dest.y = 0;
767 dest.w = image->w;
768 dest.h = image->h;
769
770 [self createWindowWithSize:NSMakeSize(image->w, image->h)];
772 float pixelDensity = SDL_GetWindowPixelDensity(window);
773 if (pixelDensity == 0.0f) {
774 pixelDensity = 1.0f;
775 }
776
777 glViewport(0, 0, dest.w * pixelDensity, dest.h * pixelDensity);
778
779 glEnable(GL_TEXTURE_2D);
780 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
781 glClear(GL_COLOR_BUFFER_BIT);
782
784 [matrixManager orthoLeft:0.0f right:1.0f bottom:1.0f top:0.0f near:-1.0f far:1.0f];
786
789
790 GLuint texture;
791 GLenum texture_format;
792 GLint nOfColors;
793
794 // get the number of channels in the SDL image
795 const SDL_PixelFormatDetails* pixelFormat = SDL_GetPixelFormatDetails(image->format);
796 nOfColors = pixelFormat->bytes_per_pixel;
797 if (nOfColors == 4) // contains an alpha channel
798 {
799 if (pixelFormat->Rmask == 0x000000ff)
800 texture_format = GL_RGBA;
801 else
802 texture_format = GL_BGRA;
803 } else if (nOfColors == 3) // no alpha channel
804 {
805 if (pixelFormat->Rmask == 0x000000ff)
806 texture_format = GL_RGB;
807 else
808 texture_format = GL_BGR;
809 } else {
810 SDL_DestroySurface(image);
811 OOLog(@"Sdl.GameStart", @"%@", @"----- Encoding error within image 'splash.bmp'");
812 [self endSplashScreen];
813 return;
814 }
815
816 glGenTextures(1, &texture);
817 glBindTexture(GL_TEXTURE_2D, texture);
818
819 // Set the texture's stretching properties
820 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
821 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
822
823 // Set the texture image data with the information from SDL_Surface
824 glTexImage2D(GL_TEXTURE_2D, 0, nOfColors, image->w, image->h, 0,
825 texture_format, GL_UNSIGNED_BYTE, image->pixels);
826
827 glBindTexture(GL_TEXTURE_2D, texture);
828 glBegin(GL_QUADS);
829
830 glTexCoord2i(0, 0);
831 glVertex2i(0, 0);
832 glTexCoord2i(1, 0);
833 glVertex2i(1, 0);
834 glTexCoord2i(1, 1);
835 glVertex2i(1, 1);
836 glTexCoord2i(0, 1);
837 glVertex2i(0, 1);
838
839 glEnd();
840 glFinish();
841
842 SDL_GL_SwapWindow(window);
845
846 if (image) {
847 SDL_DestroySurface(image);
848 }
849 glDeleteTextures(1, &texture);
850
851 glDisable(GL_TEXTURE_2D);
853
854 SDL_DestroySurface(image);
855 return;
856}
857
858- (void)getDisplayDimensions:(unsigned*)width height:(unsigned*)height
859{
860 SDL_DisplayID displayID = SDL_GetDisplayForWindow(window);
861
862 SDL_Rect displaybounds;
863 if (SDL_GetDisplayBounds(displayID, &displaybounds)) {
864 if (width)
865 *width = (unsigned)displaybounds.w;
866 if (height)
867 *height = (unsigned)displaybounds.h;
868 }
869}
870
872{
873 if (!window) {
874 return NO;
875 }
876
877 SDL_DisplayID windowDisplayID = SDL_GetDisplayForWindow(window);
878 SDL_DisplayID primaryDisplayID = SDL_GetPrimaryDisplay();
879
880 return (windowDisplayID != 0 && windowDisplayID == primaryDisplayID);
881}
882
883- (void)grabMouseInsideGameWindow:(BOOL)value
884{
885 SDL_SetWindowMouseGrab(window, value);
886 grabMouseStatus = value;
887}
888
889- (void)stringToClipboard:(NSString*)stringToCopy
890{
891 if (stringToCopy) {
892 const char* clipboardText = [stringToCopy UTF8String];
893 if (!SDL_SetClipboardText(clipboardText)) {
894 OOLog(@"stringToClipboard.failed", @"Failed to copy string %@ to clipboard: %s", stringToCopy, SDL_GetError());
895 }
896 }
897}
898
899#if OOLITE_WINDOWS
900
901- (BOOL)atDesktopResolution
902{
903 return atDesktopResolution;
904}
905
906- (BOOL)hdrOutput
907{
908 return _hdrOutput;
909}
910
911- (BOOL)isOutputDisplayHDREnabled
912{
913 BOOL result = NO;
914 SDL_DisplayID displayID = SDL_GetPrimaryDisplay(); // Get the primary display ID
915 if (displayID == 0) {
916 OOLog(@"gameView.isOutputDisplayHDREnabled", @"Error! Failed to retrieve primary display ID: %s", SDL_GetError());
917 return NO;
918 }
919 SDL_PropertiesID props = SDL_GetDisplayProperties(displayID); // Retrieve properties for the target display
920 if (props == 0) {
921 OOLog(@"gameView.isOutputDisplayHDREnabled", @"Error! Failed to get display properties: %s", SDL_GetError());
922 return NO;
923 }
924 result = SDL_GetBooleanProperty(props, SDL_PROP_DISPLAY_HDR_ENABLED_BOOLEAN, false); // Query for HDR enabling
925 OOLog(@"gameView.isOutputDisplayHDREnabled", @"HDR display output requested - checking availability: %@", result ? @"YES" : @"NO");
926 return result;
927}
928
929- (float)hdrMaxBrightness
930{
931 return _hdrMaxBrightness;
932}
933
934- (void)setHDRMaxBrightness:(float)newMaxBrightness
935{
936 if (newMaxBrightness < MIN_HDR_MAXBRIGHTNESS)
937 newMaxBrightness = MIN_HDR_MAXBRIGHTNESS;
938 if (newMaxBrightness > MAX_HDR_MAXBRIGHTNESS)
939 newMaxBrightness = MAX_HDR_MAXBRIGHTNESS;
940 _hdrMaxBrightness = newMaxBrightness;
941
942 [[NSUserDefaults standardUserDefaults] setFloat:_hdrMaxBrightness forKey:@"hdr-max-brightness"];
943}
944
945- (float)hdrPaperWhiteBrightness
946{
947 return _hdrPaperWhiteBrightness;
948}
949
950- (void)setHDRPaperWhiteBrightness:(float)newPaperWhiteBrightness
951{
952 if (newPaperWhiteBrightness < MIN_HDR_PAPERWHITE)
953 newPaperWhiteBrightness = MIN_HDR_PAPERWHITE;
954 if (newPaperWhiteBrightness > MAX_HDR_PAPERWHITE)
955 newPaperWhiteBrightness = MAX_HDR_PAPERWHITE;
956 _hdrPaperWhiteBrightness = newPaperWhiteBrightness;
957
958 [[NSUserDefaults standardUserDefaults] setFloat:_hdrPaperWhiteBrightness forKey:@"hdr-paperwhite-brightness"];
959}
960
961- (OOHDRToneMapper)hdrToneMapper
962{
963 return _hdrToneMapper;
964}
965
966- (void)setHDRToneMapper:(OOHDRToneMapper)newToneMapper
967{
968 if (newToneMapper > OOHDR_TONEMAPPER_REINHARD)
969 newToneMapper = OOHDR_TONEMAPPER_REINHARD;
970 if (newToneMapper < OOHDR_TONEMAPPER_NONE)
971 newToneMapper = OOHDR_TONEMAPPER_NONE;
972 _hdrToneMapper = newToneMapper;
973}
974
975#else // Linus stub methods
976
978{
979 return NO;
980}
981
983{
984 return NO;
985}
986
987#endif // OOLITE_WINDOWS
988
993
994- (void)setSDRToneMapper:(OOSDRToneMapper)newToneMapper
995{
996 if (newToneMapper > OOSDR_TONEMAPPER_REINHARD)
997 newToneMapper = OOSDR_TONEMAPPER_REINHARD;
998 if (newToneMapper < OOSDR_TONEMAPPER_NONE)
999 newToneMapper = OOSDR_TONEMAPPER_NONE;
1000 _sdrToneMapper = newToneMapper;
1001}
1002
1004{
1005 return _colorSaturation;
1006}
1007
1008- (void)adjustColorSaturation:(float)colorSaturationAdjustment;
1009{
1010 _colorSaturation += colorSaturationAdjustment;
1012}
1013
1014- (BOOL)snapShot:(NSString*)filename
1015{
1016 BOOL snapShotOK = YES;
1017 SDL_Surface* tmpSurface;
1018
1019#if OOLITE_MAC_OS_X
1020 // The back buffer is undefined after a swap on macOS, so read the frame currently on screen.
1021 OOGL(glReadBuffer(GL_FRONT));
1022#endif
1023
1024 // backup the previous directory
1025 NSString* originalDirectory = [[NSFileManager defaultManager] currentDirectoryPath];
1026 // use the snapshots directory
1027 [[NSFileManager defaultManager] chdirToSnapshotPath];
1028
1029 BOOL withFilename = (filename != nil);
1030 static unsigned imageNo = 0;
1031 unsigned tmpImageNo = 0;
1032 NSString* pathToPic = nil;
1033 NSString* baseName = @"oolite";
1034
1035#if SNAPSHOTS_PNG_FORMAT
1036 NSString* extension = @".png";
1037#else
1038 NSString* extension = @".bmp";
1039#endif
1040
1041 if (withFilename) {
1042 baseName = filename;
1043 pathToPic = [filename stringByAppendingString:extension];
1044 } else {
1045 tmpImageNo = imageNo;
1046 }
1047
1048 if (withFilename && [[NSFileManager defaultManager] fileExistsAtPath:pathToPic]) {
1049 OOLog(@"screenshot.filenameExists", @"Snapshot \"%@%@\" already exists - adding numerical sequence.", pathToPic, extension);
1050 pathToPic = nil;
1051 }
1052
1053 if (pathToPic == nil) {
1054 do {
1055 tmpImageNo++;
1056 pathToPic = [NSString stringWithFormat:@"%@-%03d%@", baseName, tmpImageNo, extension];
1057 } while ([[NSFileManager defaultManager] fileExistsAtPath:pathToPic]);
1058 }
1059
1060 if (!withFilename) {
1061 imageNo = tmpImageNo;
1062 }
1063
1064#if OOLITE_MAC_OS_X
1065 // No window surface on macOS (see createWindowWithSize:); describe the GL drawable instead.
1066 SDL_Surface* surface = NULL;
1067 {
1068 int pixelWidth, pixelHeight;
1069 SDL_GetWindowSizeInPixels(window, &pixelWidth, &pixelHeight);
1070 surface = SDL_CreateSurface(pixelWidth, pixelHeight, SDL_PIXELFORMAT_ARGB8888);
1071 }
1072#else
1073 SDL_Surface* surface = SDL_GetWindowSurface(window);
1074#endif
1075 OOLog(@"screenshot", @"Saving screen shot \"%@\" (%u x %u pixels).", pathToPic, surface->w, surface->h);
1076
1077 int pitch = surface->pitch;
1078 unsigned char* pixls = malloc(pitch * surface->h);
1079 int y;
1080 int off;
1081
1082 if (surface->w % 4)
1083 glPixelStorei(GL_PACK_ALIGNMENT, 1);
1084 else
1085 glPixelStorei(GL_PACK_ALIGNMENT, 4);
1086 for (y = surface->h - 1, off = 0; y >= 0; y--, off += pitch) {
1087 glReadPixels(0, y, surface->w, 1, GL_BGRA, GL_UNSIGNED_BYTE, pixls + off);
1088 }
1089
1090 tmpSurface = SDL_CreateSurfaceFrom(surface->w, surface->h, surface->format, pixls, surface->pitch);
1091#if SNAPSHOTS_PNG_FORMAT
1092 if (!SDL_SavePNG(tmpSurface, [pathToPic UTF8String])) {
1093 OOLog(@"screenshotPNG", @"Failed to save %@", pathToPic);
1094 snapShotOK = NO;
1095 }
1096#else
1097 if (!SDL_SaveBMP(tmpSurface, [pathToPic UTF8String])) {
1098 OOLog(@"screenshotBMP", @"Failed to save %@", pathToPic);
1099 snapShotOK = NO;
1100 }
1101#endif
1102 SDL_DestroySurface(tmpSurface);
1103 free(pixls);
1104
1105 // if outputting HDR signal, save also either an .exr or a Radiance .hdr snapshot
1106 if ([self hdrOutput]) {
1107 NSString* fileExtension = [[NSUserDefaults standardUserDefaults] oo_stringForKey:@"hdr-snapshot-format" defaultValue:SNAPSHOTHDR_EXTENSION_DEFAULT];
1108
1109 // we accept file extension with or without a leading dot; if it is without, insert it at the beginning now
1110 if (![[fileExtension substringToIndex:1] isEqual:@"."])
1111 fileExtension = [@"." stringByAppendingString:fileExtension];
1112
1113 if (![fileExtension isEqual:SNAPSHOTHDR_EXTENSION_EXR] && ![fileExtension isEqual:SNAPSHOTHDR_EXTENSION_HDR]) {
1114 OOLog(@"screenshotHDR", @"Unrecognized HDR file format requested, defaulting to %@", SNAPSHOTHDR_EXTENSION_DEFAULT);
1115 fileExtension = SNAPSHOTHDR_EXTENSION_DEFAULT;
1116 }
1117
1118 NSString* pathToPicHDR = [pathToPic stringByReplacingOccurrencesOfString:@".png" withString:fileExtension];
1119 OOLog(@"screenshot", @"Saving screen shot \"%@\" (%u x %u pixels).", pathToPicHDR, surface->w, surface->h);
1120 GLfloat* pixlsf = (GLfloat*)malloc(pitch * surface->h * sizeof(GLfloat));
1121 for (y = surface->h - 1, off = 0; y >= 0; y--, off += pitch) {
1122 glReadPixels(0, y, surface->w, 1, GL_RGB, GL_FLOAT, pixlsf + off);
1123 }
1124
1125 if (([fileExtension isEqual:SNAPSHOTHDR_EXTENSION_EXR] && SaveEXRSnapshot([pathToPicHDR cStringUsingEncoding:NSUTF8StringEncoding], surface -> w, surface -> h, pixlsf) != 0) // TINYEXR_SUCCESS
1126 || ([fileExtension isEqual:SNAPSHOTHDR_EXTENSION_HDR] && !stbi_write_hdr([pathToPicHDR cStringUsingEncoding:NSUTF8StringEncoding], surface -> w, surface -> h, 3, pixlsf))) {
1127 OOLog(@"screenshotHDR", @"Failed to save %@", pathToPicHDR);
1128 snapShotOK = NO;
1129 }
1130
1131 free(pixlsf);
1132 }
1133
1134#if OOLITE_MAC_OS_X
1135 SDL_DestroySurface(surface);
1136 OOGL(glReadBuffer(GL_BACK));
1137#endif
1138
1139 // return to the previous directory
1140 [[NSFileManager defaultManager] changeCurrentDirectoryPath:originalDirectory];
1141 return snapShotOK;
1142}
1143
1144// Full screen mode enumerator.
1146{
1147 int i;
1148 SDL_DisplayMode** modes;
1149 NSMutableDictionary* mode;
1150 SDL_DisplayID displayId = [self getDisplayId];
1151
1152 screenSizes = [[NSMutableArray alloc] init];
1153
1154 // The default resolution (slot 0) is the resolution we are
1155 // already in since this is guaranteed to work.
1156 mode = [self getNativeSize];
1157 [screenSizes addObject:mode];
1158
1159 int displayModeCount;
1160 modes = SDL_GetFullscreenDisplayModes(displayId, &displayModeCount);
1161 if (!displayModeCount) {
1162 OOLog(@"display.mode.list.none", @"%@", @"SDL didn't return any screen modes");
1163 return;
1164 }
1165
1166 for (i = 0; i < displayModeCount; i++) {
1167 mode = [NSMutableDictionary dictionary];
1168 [mode setValue:[NSNumber numberWithInt:(int)modes[i]->w]
1169 forKey:kOODisplayWidth];
1170 [mode setValue:[NSNumber numberWithInt:(int)modes[i]->h]
1171 forKey:kOODisplayHeight];
1172 [mode setValue:[NSNumber numberWithFloat:(int)modes[i]->refresh_rate]
1173 forKey:kOODisplayRefreshRate];
1174 if (![screenSizes containsObject:mode]) {
1175 [screenSizes addObject:mode];
1176 OOLog(@"display.mode.list", @"Added res %d x %d", modes[i]->w, modes[i]->h);
1177 }
1178 }
1179 SDL_free(modes);
1180}
1181
1182// Save and restore window sizes to/from defaults.
1183- (void)saveWindowSize:(NSSize)windowSize
1184{
1185 NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
1186 [defaults setInteger:(int)windowSize.width forKey:@"window_width"];
1187 [defaults setInteger:(int)windowSize.height forKey:@"window_height"];
1188 currentWindowSize = windowSize;
1189}
1190
1192{
1193 NSSize windowSize;
1194 NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
1195 if ([defaults objectForKey:@"window_width"] && [defaults objectForKey:@"window_height"]) {
1196 windowSize = NSMakeSize([defaults integerForKey:@"window_width"],
1197 [defaults integerForKey:@"window_height"]);
1198 } else {
1199 windowSize = NSMakeSize(WINDOW_SIZE_DEFAULT_WIDTH, WINDOW_SIZE_DEFAULT_HEIGHT);
1200 }
1201 currentWindowSize = windowSize;
1202 return windowSize;
1203}
1204
1206{
1207 currentSize = 0;
1208 int width = 0, height = 0, refresh = 0;
1209 unsigned i;
1210
1211 NSArray* cmdline_arguments = [[NSProcessInfo processInfo] arguments];
1212
1213 NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
1214 if ([userDefaults objectForKey:@"display_width"])
1215 width = [userDefaults integerForKey:@"display_width"];
1216 if ([userDefaults objectForKey:@"display_height"])
1217 height = [userDefaults integerForKey:@"display_height"];
1218 if ([userDefaults objectForKey:@"display_refresh"])
1219 refresh = [userDefaults integerForKey:@"display_refresh"];
1220 if ([userDefaults objectForKey:@"fullscreen"])
1221 fullScreen = [userDefaults boolForKey:@"fullscreen"];
1222
1223 // Check if -fullscreen or -windowed has been passed on the command line. If yes,
1224 // set it regardless of what is set by .GNUstepDefaults. If both are found in the
1225 // arguments list, the one that comes last wins.
1226 for (i = 0; i < [cmdline_arguments count]; i++) {
1227 if ([[cmdline_arguments objectAtIndex:i] isEqual:@"-fullscreen"])
1228 fullScreen = YES;
1229 if ([[cmdline_arguments objectAtIndex:i] isEqual:@"-windowed"])
1230 fullScreen = NO;
1231 }
1232
1233 if (width && height) {
1234 currentSize = [self findDisplayModeForWidth:width Height:height Refresh:refresh];
1235 return currentSize;
1236 }
1237 return currentSize;
1238}
1239
1240- (int)findDisplayModeForWidth:(unsigned int)d_width Height:(unsigned int)d_height Refresh:(unsigned int)d_refresh
1241{
1242 int i, modeCount;
1243 NSDictionary* mode;
1244 unsigned int modeWidth, modeHeight, modeRefresh;
1245
1246 modeCount = [screenSizes count];
1247
1248 for (i = 0; i < modeCount; i++) {
1249 mode = [screenSizes objectAtIndex:i];
1250 modeWidth = [[mode objectForKey:kOODisplayWidth] intValue];
1251 modeHeight = [[mode objectForKey:kOODisplayHeight] intValue];
1252 modeRefresh = [[mode objectForKey:kOODisplayRefreshRate] intValue];
1253 if ((modeWidth == d_width) && (modeHeight == d_height) && (modeRefresh == d_refresh)) {
1254 OOLog(@"display.mode.found", @"Found mode %@", mode);
1255 return i;
1256 }
1257 }
1258
1259 OOLog(@"display.mode.found.failed", @"Failed to find mode: width=%d height=%d refresh=%d", d_width, d_height, d_refresh);
1260 OOLog(@"display.mode.found.failed.list", @"Contents of list: %@", screenSizes);
1261 return 0;
1262}
1263
1265{
1266 NSDictionary* mode = [screenSizes objectAtIndex:currentSize];
1267
1268 if (mode) {
1269 return NSMakeSize([[mode objectForKey:kOODisplayWidth] intValue],
1270 [[mode objectForKey:kOODisplayHeight] intValue]);
1271 }
1272 OOLog(@"display.mode.unknown", @"%@", @"Screen size unknown!");
1274}
1275
1276- (NSDictionary*)currentScreenMode
1277{
1278 NSDictionary* mode = [screenSizes objectAtIndex:currentSize];
1279 return [[mode retain] autorelease];
1280}
1281
1282- (void)setFov:(float)value fromFraction:(BOOL)fromFraction
1283{
1284 _fov = fromFraction ? value : tan((value / 2) * M_PI / 180);
1285}
1286
1287- (float)fov:(BOOL)inFraction
1288{
1289 return inFraction ? _fov : 2 * atan(_fov) * 180 / M_PI;
1290}
1291
1292- (BOOL)msaa
1293{
1294 return _msaa;
1295}
1296
1297- (void)setMsaa:(BOOL)newMsaa
1298{
1299 _msaa = !!newMsaa;
1300}
1301
1306
1308{
1309#if !OOLITE_WINDOWS
1310 return 0 != (SDL_GetModState() & (SDL_KMOD_LSHIFT | SDL_KMOD_RSHIFT));
1311#else
1312 // SDL_GetModState() does not seem to do exactly what is intended under Windows. For this reason,
1313 // the GetKeyState Windows API call is used to detect the Shift keypress. -- Nikos.
1314 return 0 != (GetKeyState(VK_SHIFT) & 0x100);
1315#endif
1316}
1317
1318#ifndef NDEBUG
1319- (void)dumpRGBAToFileNamed:(NSString*)name
1320 bytes:(uint8_t*)bytes
1321 width:(NSUInteger)width
1322 height:(NSUInteger)height
1323 rowBytes:(NSUInteger)rowBytes
1324{
1325 if (name == nil || bytes == NULL || width == 0 || height == 0 || rowBytes < width * 4)
1326 return;
1327
1328 // use the snapshots directory
1329 NSString* dumpFile = [[NSHomeDirectory() stringByAppendingPathComponent:@SAVEDIR] stringByAppendingPathComponent:@SNAPSHOTDIR];
1330 dumpFile = [dumpFile stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", name]];
1331
1332 SDL_Surface* tmpSurface = SDL_CreateSurfaceFrom(width, height, SDL_PIXELFORMAT_RGBA32, bytes, rowBytes);
1333 SDL_SavePNG(tmpSurface, [dumpFile UTF8String]);
1334 SDL_DestroySurface(tmpSurface);
1335}
1336
1337- (void)dumpRGBToFileNamed:(NSString*)name
1338 bytes:(uint8_t*)bytes
1339 width:(NSUInteger)width
1340 height:(NSUInteger)height
1341 rowBytes:(NSUInteger)rowBytes
1342{
1343 if (name == nil || bytes == NULL || width == 0 || height == 0 || rowBytes < width * 3)
1344 return;
1345
1346 // use the snapshots directory
1347 NSString* dumpFile = [[NSHomeDirectory() stringByAppendingPathComponent:@SAVEDIR] stringByAppendingPathComponent:@SNAPSHOTDIR];
1348 dumpFile = [dumpFile stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", name]];
1349
1350 SDL_Surface* tmpSurface = SDL_CreateSurfaceFrom(width, height, SDL_PIXELFORMAT_RGB24, bytes, rowBytes);
1351 SDL_SavePNG(tmpSurface, [dumpFile UTF8String]);
1352 SDL_DestroySurface(tmpSurface);
1353}
1354
1355- (void)dumpGrayToFileNamed:(NSString*)name
1356 bytes:(uint8_t*)bytes
1357 width:(NSUInteger)width
1358 height:(NSUInteger)height
1359 rowBytes:(NSUInteger)rowBytes
1360{
1361 if (name == nil || bytes == NULL || width == 0 || height == 0 || rowBytes < width)
1362 return;
1363
1364 // use the snapshots directory
1365 NSString* dumpFile = [[NSHomeDirectory() stringByAppendingPathComponent:@SAVEDIR] stringByAppendingPathComponent:@SNAPSHOTDIR];
1366 dumpFile = [dumpFile stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", name]];
1367
1368 SDL_Surface* tmpSurface = SDL_CreateSurface(width, height, SDL_PIXELFORMAT_RGBA32);
1369 for (int y = 0; y < height; y++) {
1370 uint8_t* srcRow = bytes + rowBytes * y;
1371 uint8_t* dstRow = (uint8_t*)tmpSurface->pixels + y * tmpSurface->pitch;
1372 for (int x = 0; x < width; x++) {
1373 dstRow[4 * x + 0] = srcRow[x];
1374 dstRow[4 * x + 1] = srcRow[x];
1375 dstRow[4 * x + 2] = srcRow[x];
1376 dstRow[4 * x + 3] = '\xff';
1377 }
1378 }
1379 SDL_SavePNG(tmpSurface, [dumpFile UTF8String]);
1380 SDL_DestroySurface(tmpSurface);
1381}
1382
1383- (void)dumpGrayAlphaToFileNamed:(NSString*)name
1384 bytes:(uint8_t*)bytes
1385 width:(NSUInteger)width
1386 height:(NSUInteger)height
1387 rowBytes:(NSUInteger)rowBytes
1388{
1389 if (name == nil || bytes == NULL || width == 0 || height == 0 || rowBytes < width * 2)
1390 return;
1391
1392 // use the snapshots directory
1393 NSString* dumpFile = [[NSHomeDirectory() stringByAppendingPathComponent:@SAVEDIR] stringByAppendingPathComponent:@SNAPSHOTDIR];
1394 dumpFile = [dumpFile stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", name]];
1395
1396 SDL_Surface* tmpSurface = SDL_CreateSurfaceFrom(width, height, SDL_PIXELFORMAT_RGBA32, bytes, rowBytes);
1397 for (int y = 0; y < height; y++) {
1398 uint8_t* srcRow = bytes + rowBytes * y;
1399 uint8_t* dstRow = (uint8_t*)tmpSurface->pixels + y * tmpSurface->pitch;
1400 for (int x = 0; x < width; x++) {
1401 dstRow[4 * x + 0] = srcRow[2 * x];
1402 dstRow[4 * x + 1] = srcRow[2 * x];
1403 dstRow[4 * x + 2] = srcRow[2 * x];
1404 dstRow[4 * x + 3] = srcRow[2 * x + 1];
1405 }
1406 }
1407 SDL_SavePNG(tmpSurface, [dumpFile UTF8String]);
1408 SDL_DestroySurface(tmpSurface);
1409}
1410
1411- (void)dumpRGBAToRGBFileNamed:(NSString*)rgbName
1412 andGrayFileNamed:(NSString*)grayName
1413 bytes:(uint8_t*)bytes
1414 width:(NSUInteger)width
1415 height:(NSUInteger)height
1416 rowBytes:(NSUInteger)rowBytes
1417{
1418 if ((rgbName == nil && grayName == nil) || bytes == NULL || width == 0 || height == 0 || rowBytes < width * 4)
1419 return;
1420
1421 uint8_t *rgbBytes, *rgbPx, *grayBytes, *grayPx, *srcPx;
1422 NSUInteger x, y;
1423 BOOL trivalAlpha = YES;
1424
1425 rgbPx = rgbBytes = malloc(width * height * 3);
1426 if (rgbBytes == NULL)
1427 return;
1428
1429 grayPx = grayBytes = malloc(width * height);
1430 if (grayBytes == NULL) {
1431 free(rgbBytes);
1432 return;
1433 }
1434
1435 for (y = 0; y < height; y++) {
1436 srcPx = bytes + rowBytes * y;
1437
1438 for (x = 0; x < width; x++) {
1439 *rgbPx++ = *srcPx++;
1440 *rgbPx++ = *srcPx++;
1441 *rgbPx++ = *srcPx++;
1442 trivalAlpha = trivalAlpha && ((*srcPx == 0xFF) || (*srcPx == 0x00)); // Look for any "interesting" pixels in alpha.
1443 *grayPx++ = *srcPx++;
1444 }
1445 }
1446
1447 [self dumpRGBToFileNamed:rgbName
1448 bytes:rgbBytes
1449 width:width
1450 height:height
1451 rowBytes:width * 3];
1452 free(rgbBytes);
1453
1454 if (!trivalAlpha) {
1455 [self dumpGrayToFileNamed:grayName
1456 bytes:grayBytes
1457 width:width
1458 height:height
1459 rowBytes:width];
1460 }
1461 free(grayBytes);
1462}
1463#endif
1464
1465@end
@ gvPrintScreenKey
#define SNAPSHOTHDR_EXTENSION_HDR
OOHDRToneMapper
@ OOHDR_TONEMAPPER_REINHARD
@ OOHDR_TONEMAPPER_NONE
#define MAX_COLOR_SATURATION
OOSDRToneMapper
@ OOSDR_TONEMAPPER_REINHARD
@ OOSDR_TONEMAPPER_NONE
#define MAX_CLEAR_DEPTH
#define SNAPSHOTHDR_EXTENSION_DEFAULT
#define WINDOW_SIZE_DEFAULT_HEIGHT
#define MIN_HDR_MAXBRIGHTNESS
#define MIN_HDR_PAPERWHITE
#define WINDOW_SIZE_DEFAULT_WIDTH
#define SNAPSHOTHDR_EXTENSION_EXR
#define MAX_HDR_MAXBRIGHTNESS
#define MAX_HDR_PAPERWHITE
@ gvStringInputNo
int SaveEXRSnapshot(const char *outfilename, int width, int height, const float *rgb)
OOSDRToneMapper OOSDRToneMapperFromString(NSString *string)
OOHDRToneMapper OOHDRToneMapperFromString(NSString *string)
OOINLINE float OOClamp_0_max_f(float value, float max) INLINE_CONST_FUNC
OOINLINE float OOClamp_0_1_f(float value) INLINE_CONST_FUNC
#define OOLITE_WINDOWS
#define kOODisplayHeight
#define kOODisplayWidth
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define M_PI
Definition OOMaths.h:54
void OOGLFrustum(double left, double right, double bottom, double top, double near, double far)
void OOGLResetProjection(void)
@ OPENGL_STATE_OVERLAY
Definition OOOpenGL.h:124
#define OOVerifyOpenGLState()
Definition OOOpenGL.h:133
#define OOSetOpenGLState(STATE)
Definition OOOpenGL.h:132
#define OOGL(statement)
Definition OOOpenGL.h:262
return nil
float y
float x
int SaveEXRSnapshot(const char *outfilename, int width, int height, const float *rgb)
#define UNIVERSE
Definition Universe.h:827
void exitAppWithContext:(NSString *context)
BOOL showSplashScreen
void initialiseGLWithSize:(NSSize v_size)
void createWindowWithSize:(NSSize size)
int bitsPerColorComponent
NSDictionary * keyMappings_shifted
void endSplashScreen()
BOOL isAlphabetKeyDown
BOOL isOutputDisplayHDREnabled()
NSDictionary * currentScreenMode()
GLfloat display_z
int scancode2Unicode[NUM_KEYS]
NSSize backingViewSize()
enum StringInput allowingStringInput
int loadFullscreenSettings()
NSMutableString * typedString
NSMutableDictionary * getNativeSize()
SDL_Window * window
float _mouseVirtualStickSensitivityFactor
float _mouseWheelDelta
NSSize currentWindowSize
void populateFullScreenModelist()
int findDisplayModeForWidth:Height:Refresh:(unsigned int d_width,[Height] unsigned int d_height,[Refresh] unsigned int d_refresh)
BOOL inFullScreenMode()
NSMutableArray * screenSizes
void updateGLSize:(NSSize size)
float _colorSaturation
OOOpenGLMatrixManager * matrixManager
NSString * getWindowCaption()
NSPoint virtualJoystickPosition
BOOL isRunningOnPrimaryDisplayDevice()
NSDictionary * keyMappings_normal
OOOpenGLMatrixManager * getOpenGLMatrixManager()
GLfloat x_offset
float colorSaturation()
NSTimeInterval timeSinceLastMouseWheel
NSSize firstScreen
NSTimeInterval timeIntervalAtLastClick
NSSize currentScreenSize()
void dumpGrayToFileNamed:bytes:width:height:rowBytes:(NSString *name,[bytes] uint8_t *bytes,[width] NSUInteger width,[height] NSUInteger height,[rowBytes] NSUInteger rowBytes)
void initSplashScreen()
OOSDRToneMapper sdrToneMapper()
SDL_DisplayID getDisplayId()
void dumpRGBToFileNamed:bytes:width:height:rowBytes:(NSString *name,[bytes] uint8_t *bytes,[width] NSUInteger width,[height] NSUInteger height,[rowBytes] NSUInteger rowBytes)
SDL_GLContext glContext
GameController * gameController
void setUpBasicOpenGLStateWithSize()
NSSize loadWindowSize()
GLfloat y_offset
BOOL setStickHandlerClass:(Class aClass)
OOOpenGLExtensionManager * sharedManager()
void orthoLeft:right:bottom:top:near:far:(double l,[right] double r,[bottom] double b,[top] double t,[near] double n,[far] double f)
BOOL setUp()
Definition OOALSound.m:46
NSString * builtInPath()
voidpf void uLong size
Definition ioapi.h:126
const char * filename
Definition ioapi.h:125
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
const char int mode
Definition ioapi.h:125
STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data)