osxOpenGLDevice.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #import "platformOSX/platformOSX.h"
  23. #import "platformOSX/osxOpenGLDevice.h"
  24. #import "platformOSX/platformGL.h"
  25. #include "console/console.h"
  26. #include "game/gameInterface.h"
  27. #include "graphics/dgl.h"
  28. //-----------------------------------------------------------------------------
  29. osxOpenGLDevice::osxOpenGLDevice()
  30. {
  31. mDeviceName = "OpenGL";
  32. mFullScreenOnly = false;
  33. // pick a monitor to run on
  34. enumMonitors();
  35. platState = [osxPlatState sharedPlatState];
  36. CGDirectDisplayID display = chooseMonitor();
  37. [platState setCgDisplay:display];
  38. enumDisplayModes(display);
  39. }
  40. //------------------------------------------------------------------------------
  41. bool osxOpenGLDevice::enumDisplayModes( CGDirectDisplayID display )
  42. {
  43. // Clear the resolution list.
  44. mResolutionList.clear();
  45. // Fetch a list of all available modes for the specified display.
  46. CFArrayRef modeArray = CGDisplayCopyAllDisplayModes(display, NULL);
  47. // Fetch the mode count.
  48. const S32 modeCount = (const S32)CFArrayGetCount(modeArray);
  49. // Iterate the modes.
  50. for( S32 modeIndex = 0; modeIndex < modeCount; modeIndex++ )
  51. {
  52. // Fetch the display mode.
  53. CGDisplayModeRef mode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modeArray, modeIndex);
  54. // Get the mode width.
  55. const S32 width = (const S32)CGDisplayModeGetWidth(mode);
  56. // Get the mode height.
  57. const S32 height = (const S32)CGDisplayModeGetHeight(mode);
  58. // Get the pixel encoding.
  59. CFStringRef pixelEncoding = CGDisplayModeCopyPixelEncoding(mode);
  60. // Is it a 32 bpp?
  61. S32 bitDepth;
  62. if ( CFStringCompare( pixelEncoding, CFSTR(IO32BitDirectPixels), 0 ) == kCFCompareEqualTo )
  63. {
  64. bitDepth = 32;
  65. }
  66. else if ( CFStringCompare( pixelEncoding, CFSTR(IO16BitDirectPixels), 0 ) == kCFCompareEqualTo )
  67. {
  68. bitDepth = 16;
  69. }
  70. else
  71. {
  72. // Skip the mode.
  73. continue;
  74. }
  75. // Prepare the resolution.
  76. Resolution foundResolution( width, height, bitDepth );
  77. // Ensure this isn't already in the list.
  78. bool alreadyPresent = false;
  79. for( Vector<Resolution>::iterator itr = mResolutionList.begin(); itr != mResolutionList.end(); ++itr )
  80. {
  81. if ( *itr == foundResolution )
  82. {
  83. alreadyPresent = true;
  84. break;
  85. }
  86. }
  87. // Skip if already present.
  88. if ( alreadyPresent )
  89. continue;
  90. // Store the resolution.
  91. mResolutionList.push_back( Resolution( width, height, bitDepth ) );
  92. }
  93. return true;
  94. }
  95. //-----------------------------------------------------------------------------
  96. // Unused for new OS X platform. The constructor handles initialization now
  97. void osxOpenGLDevice::initDevice()
  98. {
  99. }
  100. //-----------------------------------------------------------------------------
  101. // This will fully clear the OpenGL context
  102. bool osxOpenGLDevice::cleanUpContext()
  103. {
  104. bool needResurrect = false;
  105. platState = [osxPlatState sharedPlatState];
  106. if ([[platState torqueView] contextInitialized])
  107. {
  108. if (!Video::smNeedResurrect)
  109. {
  110. Con::printf( "Killing the texture manager..." );
  111. Game->textureKill();
  112. needResurrect = true;
  113. }
  114. [[platState torqueView] clearContext];
  115. }
  116. // clear the Resolution state, so setScreenMode() will know not to early-out.
  117. smCurrentRes = Resolution(0, 0, 0);
  118. return needResurrect;
  119. }
  120. //-----------------------------------------------------------------------------
  121. //
  122. bool osxOpenGLDevice::activate( U32 width, U32 height, U32 bpp, bool fullScreen )
  123. {
  124. Con::printf( " OpenGLDevice activating..." );
  125. // gets opengl rendering capabilities of the screen pointed to by platState.hDisplay
  126. // sets up dgl with the capabilities info, & reports opengl status.
  127. getGLCapabilities();
  128. // Create the window or capture fullscreen
  129. if(!setScreenMode(width, height, bpp, fullScreen, true, false))
  130. return false;
  131. // set the displayDevice pref to "OpenGL"
  132. Con::setVariable( "$pref::Video::displayDevice", mDeviceName );
  133. // set vertical sync now because it doesnt need setting every time we setScreenMode()
  134. setVerticalSync( !Con::getBoolVariable( "$pref::Video::disableVerticalSync" ));
  135. return true;
  136. }
  137. //-----------------------------------------------------------------------------
  138. void osxOpenGLDevice::shutdown()
  139. {
  140. Con::printf( "Shutting down the OpenGL display device..." );
  141. cleanUpContext();
  142. }
  143. //-----------------------------------------------------------------------------
  144. NSOpenGLPixelFormat* osxOpenGLDevice::generateValidPixelFormat(bool fullscreen, U32 bpp, U32 samples)
  145. {
  146. AssertWarn(samples <= 6, "An unusual multisample depth was requested in findValidPixelFormat(). clamping to 0...6");
  147. samples = samples > 6 ? 6 : samples;
  148. int i = 0;
  149. NSOpenGLPixelFormatAttribute attr[64];
  150. attr[i++] = NSOpenGLPFADoubleBuffer;
  151. attr[i++] = NSOpenGLPFANoRecovery;
  152. attr[i++] = NSOpenGLPFAAccelerated;
  153. if(bpp != 0)
  154. {
  155. // native pixel formats are argb 1555 & argb 8888.
  156. U32 colorbits = 0;
  157. U32 alphabits = 0;
  158. if(bpp == 16)
  159. {
  160. colorbits = 5; // ARGB 1555
  161. alphabits = 1;
  162. }
  163. else if(bpp == 32)
  164. colorbits = alphabits = 8; // ARGB 8888
  165. attr[i++] = NSOpenGLPFADepthSize;
  166. attr[i++] = (NSOpenGLPixelFormatAttribute)bpp;
  167. attr[i++] = NSOpenGLPFAColorSize;
  168. attr[i++] = (NSOpenGLPixelFormatAttribute)colorbits;
  169. attr[i++] = NSOpenGLPFAAlphaSize;
  170. attr[i++] = (NSOpenGLPixelFormatAttribute)alphabits;
  171. }
  172. if (samples != 0)
  173. {
  174. attr[i++] = NSOpenGLPFAMultisample;
  175. attr[i++] = (NSOpenGLPixelFormatAttribute)1;
  176. attr[i++] = NSOpenGLPFASamples;
  177. attr[i++] = (NSOpenGLPixelFormatAttribute)samples;
  178. }
  179. attr[i++] = 0;
  180. NSOpenGLPixelFormat* format = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attr] autorelease];
  181. return format;
  182. }
  183. //-----------------------------------------------------------------------------
  184. bool osxOpenGLDevice::setScreenMode( U32 width, U32 height, U32 bpp, bool fullScreen, bool forceIt, bool repaint )
  185. {
  186. // Print to the console that we are setting the screen mode
  187. Con::printf(" set screen mode %i x %i x %i, %s, %s, %s",width, height, bpp,
  188. fullScreen ? "fullscreen" : "windowed",
  189. forceIt ? "force it" : "dont force it",
  190. repaint ? "repaint" : "dont repaint");
  191. bool needResurrect = cleanUpContext();
  192. // Get the global OSX platform state
  193. osxPlatState * platState = [osxPlatState sharedPlatState];
  194. // Validation, early outs
  195. // Sanity check. Some scripts are liable to pass in bad values.
  196. if (!bpp)
  197. bpp = [platState desktopBitsPixel];
  198. if (bpp)
  199. bpp = bpp > 16 ? 32 : 16;
  200. Resolution newRes = Resolution(width, height, bpp);
  201. // If no values changing and we're not forcing a change, kick out. prevents thrashing.
  202. if (!forceIt && smIsFullScreen == fullScreen && smCurrentRes == newRes)
  203. return true;
  204. // Create a pixel format to be used with the context
  205. NSOpenGLPixelFormat* pixelFormat = generateValidPixelFormat(fullScreen, bpp, 0);
  206. if (!pixelFormat)
  207. {
  208. Con::printf("osxOpenGLDevice::setScreenMode error: No OpenGL pixel format");
  209. return false;
  210. }
  211. [platState setFullScreen:fullScreen];
  212. if (fullScreen)
  213. {
  214. NSRect mainDisplayRect = [[NSScreen mainScreen] frame];
  215. newRes.w = mainDisplayRect.size.width;
  216. newRes.h = mainDisplayRect.size.height;
  217. [[platState window] setStyleMask:NSBorderlessWindowMask];
  218. [[platState window] setFrame:mainDisplayRect display:YES];
  219. [[platState window] setLevel:NSMainMenuWindowLevel+1];
  220. }
  221. else
  222. {
  223. #if __MAC_OS_X_VERSION_MAX_ALLOWED < 1070
  224. [[platState window] setStyleMask:NSTitledWindowMask | NSClosableWindowMask] ;
  225. // Calculate the actual center
  226. CGFloat x = ([[NSScreen mainScreen] frame].size.width - width) / 2;
  227. CGFloat y = ([[NSScreen mainScreen] frame].size.height - height) / 2;
  228. // Create a rect to send to the window
  229. NSRect newFrame = NSMakeRect(x, y, width, height);
  230. // Send message to the window to resize/relocate
  231. [[platState window] setFrame:newFrame display:YES animate:NO];
  232. #else
  233. [[platState window] setStyleMask:NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask];
  234. #endif
  235. }
  236. [[platState torqueView] createContextWithPixelFormat:pixelFormat];
  237. [platState setWindowSize:newRes.w height:newRes.h];
  238. // clear out garbage from the gl window.
  239. glClearColor(0,0,0,1);
  240. glClear(GL_COLOR_BUFFER_BIT );
  241. // set opengl options & other options ---------------------------------------
  242. // ensure data is packed tightly in memory. this defaults to 4.
  243. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  244. // TODO: set gl arb multisample enable & hint
  245. //dglSetFSAASamples(gFSAASamples);
  246. // update smIsFullScreen and pref
  247. smIsFullScreen = fullScreen;
  248. Con::setBoolVariable( "$pref::Video::fullScreen", smIsFullScreen );
  249. // save resolution
  250. smCurrentRes = newRes;
  251. // save resolution to prefs
  252. char buf[32];
  253. if (fullScreen)
  254. {
  255. dSprintf( buf, sizeof(buf), "%d %d %d", newRes.w, newRes.h, newRes.bpp);
  256. Con::setVariable("$pref::Video::resolution", buf);
  257. }
  258. else
  259. {
  260. dSprintf( buf, sizeof(buf), "%d %d", newRes.w, newRes.h);
  261. Con::setVariable("$pref::Video::windowedRes", buf);
  262. }
  263. if (needResurrect)
  264. {
  265. // Reload the textures gl names
  266. Con::printf( "Resurrecting the texture manager..." );
  267. Game->textureResurrect();
  268. }
  269. if( repaint )
  270. Video::resetCanvas();
  271. return true;
  272. }
  273. //-----------------------------------------------------------------------------
  274. void osxOpenGLDevice::swapBuffers()
  275. {
  276. if ([[platState torqueView] contextInitialized])
  277. [[platState torqueView] flushBuffer];
  278. #if defined(TORQUE_DEBUG)
  279. if (gOutlineEnabled)
  280. glClear(GL_COLOR_BUFFER_BIT);
  281. #endif
  282. }
  283. //-----------------------------------------------------------------------------
  284. const char* osxOpenGLDevice::getDriverInfo()
  285. {
  286. // Prepare some driver info for the console:
  287. const char* vendorString = (const char*) glGetString( GL_VENDOR );
  288. const char* rendererString = (const char*) glGetString( GL_RENDERER );
  289. const char* versionString = (const char*) glGetString( GL_VERSION );
  290. const char* extensionsString = (const char*) glGetString( GL_EXTENSIONS );
  291. U32 bufferLen = ( vendorString ? dStrlen( vendorString ) : 0 )
  292. + ( rendererString ? dStrlen( rendererString ) : 0 )
  293. + ( versionString ? dStrlen( versionString ) : 0 )
  294. + ( extensionsString ? dStrlen( extensionsString ) : 0 )
  295. + 4;
  296. char* returnString = Con::getReturnBuffer( bufferLen );
  297. dSprintf( returnString, bufferLen, "%s\t%s\t%s\t%s",
  298. ( vendorString ? vendorString : "" ),
  299. ( rendererString ? rendererString : "" ),
  300. ( versionString ? versionString : "" ),
  301. ( extensionsString ? extensionsString : "" ) );
  302. return( returnString );
  303. }
  304. //-----------------------------------------------------------------------------
  305. // Not yet implemented. Will resolve in the next video update
  306. bool osxOpenGLDevice::getGammaCorrection(F32 &g)
  307. {
  308. return false;
  309. }
  310. //-----------------------------------------------------------------------------
  311. // Not yet implemented. Will resolve in the next video update
  312. bool osxOpenGLDevice::setGammaCorrection(F32 g)
  313. {
  314. return false;
  315. }
  316. //-----------------------------------------------------------------------------
  317. bool osxOpenGLDevice::getVerticalSync()
  318. {
  319. if (!gGLState.suppSwapInterval)
  320. {
  321. return false;
  322. }
  323. //Note that this returns the number of frames between Swaps.
  324. //The function returns 0 / false if SwapInterval has not been specified.
  325. return false;//getVerticalSync();
  326. }
  327. //-----------------------------------------------------------------------------
  328. bool osxOpenGLDevice::setVerticalSync( bool sync )
  329. {
  330. if ([[platState torqueView] contextInitialized])
  331. {
  332. [[platState torqueView] setVerticalSync:sync];
  333. return true;
  334. }
  335. else
  336. {
  337. return false;
  338. }
  339. }
  340. //------------------------------------------------------------------------------
  341. // Fill mMonitorList with list of supported modes
  342. // Guaranteed to include at least the main device.
  343. //------------------------------------------------------------------------------
  344. bool osxOpenGLDevice::enumMonitors()
  345. {
  346. mMonitorList.clear();
  347. nAllDevs = 0;
  348. CGDirectDisplayID _displayIDs[32];
  349. uint32_t _displayCount;
  350. CGGetActiveDisplayList (32, _displayIDs, &_displayCount);
  351. for (int ii = 0 ; ii < _displayCount ; ii++)
  352. {
  353. mMonitorList.push_back(_displayIDs[ii]);
  354. allDevs[nAllDevs++] = _displayIDs[ii];
  355. }
  356. return true;
  357. }
  358. //------------------------------------------------------------------------------
  359. // Chooses a monitor based on $pref, on the results of tors(), & on the
  360. // current window's screen.
  361. //------------------------------------------------------------------------------
  362. CGDirectDisplayID osxOpenGLDevice::chooseMonitor()
  363. {
  364. // TODO: choose monitor based on which one contains most of the window.
  365. // NOTE: do not call cleanup before calling choose, or we won't have a window to consider.
  366. AssertFatal(!mMonitorList.empty(), "Cannot choose a monitor if the list is empty!");
  367. U32 monNum = Con::getIntVariable("$pref::Video::monitorNum", 0);
  368. if (monNum >= mMonitorList.size())
  369. {
  370. Con::errorf("invalid monitor number %i", monNum);
  371. monNum = 0;
  372. Con::setIntVariable("$pref::Video::monitorNum", 0);
  373. }
  374. Con::printf("using display 0x%x", mMonitorList[monNum]);
  375. return mMonitorList[monNum];
  376. }