Debian Codegraph @

src/Graphics/UI/GLUT/Initialization.hs

raw
1 --------------------------------------------------------------------------------
2 -- |
3 -- Module : Graphics.UI.GLUT.Initialization
4 -- Copyright : (c) Sven Panne 2002-2018
5 -- License : BSD3
6 --
7 -- Maintainer : Sven Panne <[email protected]>
8 -- Stability : stable
9 -- Portability : portable
10 --
11 -- Actions and state variables in this module are used to initialize GLUT state.
12 -- The primary initialization routine is 'initialize', which should only be
13 -- called exactly once in a GLUT program. No other GLUT or OpenGL actions should
14 -- be called before 'initialize', apart from getting or setting the state
15 -- variables in this module.
16 --
17 -- The reason is that these state variables can be used to set default window
18 -- initialization state that might be modified by the command processing done in
19 -- 'initialize'. For example, 'initialWindowSize' can be set to @('Size'
20 -- 400 400)@ before 'initialize' is called to indicate 400 by 400 is the
21 -- program\'s default window size. Setting the initial window size or position
22 -- before 'initialize' allows the GLUT program user to specify the initial size
23 -- or position using command line arguments.
24 --
25 --------------------------------------------------------------------------------
26
27 module Graphics.UI.GLUT.Initialization (
28 -- * Primary initialization
29 initialize, getArgsAndInitialize, exit,
30
31 -- * Initial window geometry
32 initialWindowPosition, initialWindowSize,
33
34 -- * Setting the initial display mode (I)
35 DisplayMode(..), initialDisplayMode, displayModePossible,
36
37 -- * Setting the initial display mode (II)
38 DisplayCapability(..), Relation(..), DisplayCapabilityDescription(..),
39 initialDisplayCapabilities,
40
41 -- * Controlling the creation of rendering contexts
42 RenderingContext(..), renderingContext,
43
44 -- * Direct\/indirect rendering
45 DirectRendering(..), directRendering,
46
47 -- * OpenGL 3.x context support
48 initialContextVersion, ContextFlag(..), initialContextFlags,
49 ContextProfile(..), initialContextProfile
50 ) where
51
52 import Control.Monad ( when )
53 import Control.Monad.IO.Class ( MonadIO(..) )
54 import Data.Bits ( Bits(..) )
55 import Data.List ( genericLength, intersperse, mapAccumR )
56 import Data.StateVar ( get, ($=), GettableStateVar, makeGettableStateVar
57 , SettableStateVar, makeSettableStateVar, StateVar, makeStateVar )
58 import Foreign.C.String ( peekCString, withCString )
59 import Foreign.C.Types ( CInt, CUInt )
60 import Foreign.Marshal.Array ( peekArray, withArray0 )
61 import Foreign.Marshal.Utils ( with, withMany )
62 import Foreign.Ptr ( nullPtr )
63 import Foreign.Storable ( peek )
64 import Graphics.Rendering.OpenGL ( Position(..), Size(..) )
65 import System.Environment ( getArgs, getProgName )
66
67 import Graphics.UI.GLUT.QueryUtils
68 import Graphics.UI.GLUT.Raw
69 import Graphics.UI.GLUT.Types
70
71 --------------------------------------------------------------------------------
72
73 -- | Given the program name and command line arguments, initialize the GLUT
74 -- library and negotiate a session with the window system. During this
75 -- process, 'initialize' may cause the termination of the GLUT program with an
76 -- error message to the user if GLUT cannot be properly initialized.
77 -- Examples of this situation include the failure to connect to the window
78 -- system, the lack of window system support for OpenGL, and invalid command
79 -- line options.
80 --
81 -- 'initialize' also processes command line options, but the specific options
82 -- parsed are window system dependent. Any command line arguments which are
83 -- not GLUT-specific are returned.
84 --
85 -- /X Implementation Notes:/ The X Window System specific options parsed by
86 -- 'initialize' are as follows:
87 --
88 -- * @-display /DISPLAY/@: Specify the X server to connect to. If not specified,
89 -- the value of the @DISPLAY@ environment variable is used.
90 --
91 -- * @-geometry /WxH+X+Y/@: Determines where windows should be created on the
92 -- screen. The parameter following @-geometry@ should be formatted as a
93 -- standard X geometry specification. The effect of using this option is to
94 -- change the GLUT initial size and initial position the same as if
95 -- 'initialWindowSize' or 'initialWindowPosition' were modified directly.
96 --
97 -- * @-iconic@: Requests all top-level windows be created in an iconic state.
98 --
99 -- * @-indirect@: Force the use of indirect OpenGL rendering contexts.
100 --
101 -- * @-direct@: Force the use of direct OpenGL rendering contexts (not all GLX
102 -- implementations support direct rendering contexts). A fatal error is
103 -- generated if direct rendering is not supported by the OpenGL
104 -- implementation. If neither @-indirect@ or @-direct@ are used to force a
105 -- particular behavior, GLUT will attempt to use direct rendering if
106 -- possible and otherwise fallback to indirect rendering.
107 --
108 -- * @-gldebug@: After processing callbacks and\/or events, call
109 -- 'Graphics.UI.GLUT.Debugging.reportErrors' to check if there are any pending
110 -- OpenGL errors. Using this option is helpful in detecting OpenGL run-time
111 -- errors.
112 --
113 -- * @-sync@: Enable synchronous X protocol transactions. This option makes
114 -- it easier to track down potential X protocol errors.
115
116 initialize :: MonadIO m
117 => String -- ^ The program name.
118 -> [String] -- ^ The command line arguments
119 -> m [String] -- ^ Non-GLUT command line arguments
120 initialize prog args = liftIO $
121 with (1 + genericLength args) $ \argcBuf ->
122 withMany withCString (prog : args) $ \argvPtrs ->
123 withArray0 nullPtr argvPtrs $ \argvBuf -> do
124 glutInit argcBuf argvBuf
125 newArgc <- peek argcBuf
126 newArgvPtrs <- peekArray (fromIntegral newArgc) argvBuf
127 newArgv <- mapM peekCString newArgvPtrs
128 return $ tail newArgv
129
130 -- | Convenience action: Initialize GLUT, returning the program name and any
131 -- non-GLUT command line arguments.
132
133 getArgsAndInitialize :: MonadIO m => m (String, [String])
134 getArgsAndInitialize = liftIO $ do
135 prog <- getProgName
136 args <- getArgs
137 nonGLUTArgs <- initialize prog args
138 return (prog, nonGLUTArgs)
139
140 -----------------------------------------------------------------------------
141
142 -- | (/freeglut only/) De-initialize GLUT. After this, one has to use
143 -- 'initialize' or 'getArgsAndInitialize' to initialize GLUT again.
144
145 exit :: MonadIO m => m ()
146 exit = glutExit
147
148 --------------------------------------------------------------------------------
149
150 -- | Controls the /initial window position/. Windows created by
151 -- 'Graphics.UI.GLUT.Window.createWindow' will be requested to be created with
152 -- the current /initial window position/. The initial value of the /initial
153 -- window position/ GLUT state is @'Position' (-1) (-1)@. If either the X or Y
154 -- component of the /initial window position/ is negative, the actual window
155 -- position is left to the window system to determine.
156 --
157 -- The intent of the /initial window position/ is to provide a suggestion to
158 -- the window system for a window\'s initial position. The window system is
159 -- not obligated to use this information. Therefore, GLUT programs should not
160 -- assume the window was created at the specified position.
161
162 initialWindowPosition :: StateVar Position
163 initialWindowPosition =
164 makeStateVar getInitialWindowPosition setInitialWindowPosition
165
166 getInitialWindowPosition :: IO Position
167 getInitialWindowPosition = do
168 x <- simpleGet fromIntegral glut_INIT_WINDOW_X
169 y <- simpleGet fromIntegral glut_INIT_WINDOW_Y
170 return $ Position x y
171
172 setInitialWindowPosition :: Position -> IO ()
173 setInitialWindowPosition (Position x y) =
174 glutInitWindowPosition (fromIntegral x) (fromIntegral y)
175
176 --------------------------------------------------------------------------------
177
178 -- | Controls the /initial window size/. Windows created by
179 -- 'Graphics.UI.GLUT.Window.createWindow' will be requested to be created with
180 -- the current /initial window size/. The initial value of the /initial window
181 -- size/ GLUT state is @'Size' 300 300@. If either the width or the height
182 -- component of the /initial window size/ is non-positive, the actual window
183 -- size is left to the window system to determine.
184 --
185 -- The intent of the /initial window size/ is to provide a suggestion to the
186 -- window system for a window\'s initial size. The window system is not
187 -- obligated to use this information. Therefore, GLUT programs should not
188 -- assume the window was created at the specified size. A GLUT program should
189 -- use the window\'s reshape callback to determine the true size of the
190 -- window.
191
192 initialWindowSize :: StateVar Size
193 initialWindowSize = makeStateVar getInitialWindowSize setInitialWindowSize
194
195 getInitialWindowSize :: IO Size
196 getInitialWindowSize = do
197 w <- simpleGet fromIntegral glut_INIT_WINDOW_WIDTH
198 h <- simpleGet fromIntegral glut_INIT_WINDOW_HEIGHT
199 return $ Size w h
200
201 setInitialWindowSize :: Size -> IO ()
202 setInitialWindowSize (Size w h) =
203 glutInitWindowSize (fromIntegral w) (fromIntegral h)
204
205 --------------------------------------------------------------------------------
206
207 -- | A single aspect of a window which is to be created, used in conjunction
208 -- with 'initialDisplayMode'.
209
210 data DisplayMode
211 = RGBAMode
212 -- ^ Select an RGBA mode window. This is the default if neither 'RGBAMode'
213 -- nor 'IndexMode' are specified.
214 | RGBMode
215 -- ^ An alias for 'RGBAMode'.
216 | IndexMode
217 -- ^ Select a color index mode window. This overrides 'RGBAMode' if it is
218 -- also specified.
219 | LuminanceMode
220 -- ^ Select a window with a \"luminance\" color model. This model provides
221 -- the functionality of OpenGL\'s RGBA color model, but the green and blue
222 -- components are not maintained in the frame buffer. Instead each pixel\'s
223 -- red component is converted to an index between zero and
224 -- 'Graphics.UI.GLUT.Colormap.numColorMapEntries' and looked up in a
225 -- per-window color map to determine the color of pixels within the window.
226 -- The initial colormap of 'LuminanceMode' windows is initialized to be a
227 -- linear gray ramp, but can be modified with GLUT\'s colormap actions.
228 -- /Implementation Notes:/ 'LuminanceMode' is not supported on most OpenGL
229 -- platforms.
230 | WithAlphaComponent
231 -- ^ Select a window with an alpha component to the color buffer(s).
232 | WithAccumBuffer
233 -- ^ Select a window with an accumulation buffer.
234 | WithDepthBuffer
235 -- ^ Select a window with a depth buffer.
236 | WithStencilBuffer
237 -- ^ Select a window with a stencil buffer.
238 | WithAuxBuffers Int
239 -- ^ (/freeglut only/) Select a window with /n/ (1 .. 4) auxiliary buffers.
240 -- Any /n/ outside the range 1 .. 4 is a fatal error.
241 | SingleBuffered
242 -- ^ Select a single buffered window. This is the default if neither
243 -- 'DoubleBuffered' nor 'SingleBuffered' are specified.
244 | DoubleBuffered
245 -- ^ Select a double buffered window. This overrides 'SingleBuffered' if it
246 -- is also specified.
247 | Multisampling
248 -- ^ Select a window with multisampling support. If multisampling is not
249 -- available, a non-multisampling window will automatically be chosen.
250 -- Note: both the OpenGL client-side and server-side implementations must
251 -- support the @GLX_SAMPLE_SGIS@ extension for multisampling to be
252 -- available. Deprecated, use 'WithSamplesPerPixel'.
253 | WithSamplesPerPixel Int
254 -- ^ Select a window with multisampling, using the given samples per pixel.
255 | Stereoscopic
256 -- ^ Select a stereo window.
257 | Captionless
258 -- ^ Select a window without a caption (/freeglut only/).
259 | Borderless
260 -- ^ Select a window without any borders (/freeglut only/).
261 | SRGBMode
262 -- ^ Select an sRGB mode window (/freeglut only/).
263 deriving ( Eq, Ord, Show )
264
265 marshalDisplayMode :: DisplayMode -> CUInt
266 marshalDisplayMode m = case m of
267 RGBAMode -> glut_RGBA
268 RGBMode -> glut_RGB
269 IndexMode -> glut_INDEX
270 LuminanceMode -> glut_LUMINANCE
271 WithAlphaComponent -> glut_ALPHA
272 WithAccumBuffer -> glut_ACCUM
273 WithDepthBuffer -> glut_DEPTH
274 WithStencilBuffer -> glut_STENCIL
275 WithAuxBuffers 1 -> glut_AUX1
276 WithAuxBuffers 2 -> glut_AUX2
277 WithAuxBuffers 3 -> glut_AUX3
278 WithAuxBuffers 4 -> glut_AUX4
279 WithAuxBuffers n ->
280 error ("marshalDisplayMode: illegal number of auxiliary buffers: " ++ show n)
281 SingleBuffered -> glut_SINGLE
282 DoubleBuffered -> glut_DOUBLE
283 Multisampling -> glut_MULTISAMPLE
284 WithSamplesPerPixel _ -> error ("marshalDisplayMode: this should not happen")
285 Stereoscopic -> glut_STEREO
286 Captionless -> glut_CAPTIONLESS
287 Borderless -> glut_BORDERLESS
288 SRGBMode -> glut_SRGB
289
290 --------------------------------------------------------------------------------
291
292 -- | Controls the /initial display mode/ used when creating top-level windows,
293 -- subwindows, and overlays to determine the OpenGL display mode for the
294 -- to-be-created window or overlay.
295 --
296 -- Note that 'RGBAMode' selects the RGBA color model, but it does not request any
297 -- bits of alpha (sometimes called an /alpha buffer/ or /destination alpha/)
298 -- be allocated. To request alpha, specify 'WithAlphaComponent'. The same
299 -- applies to 'LuminanceMode'.
300
301 initialDisplayMode :: StateVar [DisplayMode]
302 initialDisplayMode = makeStateVar getInitialDisplayMode setInitialDisplayMode
303
304 getInitialDisplayMode :: IO [DisplayMode]
305 getInitialDisplayMode = do
306 mode <- simpleGet fromIntegral glut_INIT_DISPLAY_MODE
307 let displayModes = i2dms (mode .&. complement glut_MULTISAMPLE)
308 if mode .&. glut_MULTISAMPLE == 0
309 then return displayModes
310 else do
311 n <- get samplesPerPixel
312 return $ WithSamplesPerPixel n : displayModes
313
314 i2dms :: CUInt -> [DisplayMode]
315 i2dms bitfield | IndexMode `elem` modes || LuminanceMode `elem` modes = modes
316 | otherwise = RGBAMode : modes
317 where modes = i2dmsWithoutRGBA bitfield
318
319 i2dmsWithoutRGBA :: CUInt -> [DisplayMode]
320 i2dmsWithoutRGBA bitfield =
321 [ c | c <- [ IndexMode, LuminanceMode, WithAlphaComponent,
322 WithAccumBuffer, WithDepthBuffer, WithStencilBuffer,
323 WithAuxBuffers 1, WithAuxBuffers 2, WithAuxBuffers 3,
324 WithAuxBuffers 4, SingleBuffered, DoubleBuffered, Multisampling,
325 Stereoscopic, Captionless, Borderless, SRGBMode ]
326 , (bitfield .&. marshalDisplayMode c) /= 0 ]
327
328 setInitialDisplayMode :: [DisplayMode] -> IO ()
329 setInitialDisplayMode modes = do
330 let (spps, transformedModes) = mapAccumR handleMultisampling [] modes
331 mapM_ (samplesPerPixel $=) spps
332 glutInitDisplayMode (toBitfield marshalDisplayMode transformedModes)
333
334 handleMultisampling :: [Int] -> DisplayMode -> ([Int], DisplayMode)
335 handleMultisampling spps (WithSamplesPerPixel spp) = (spp : spps, Multisampling)
336 handleMultisampling spps mode = (spps, mode)
337
338 toBitfield :: (Num b, Bits b) => (a -> b) -> [a] -> b
339 toBitfield marshal = foldl (.|.) 0 . map marshal
340
341 -- | Contains 'True' if the /current display mode/ is supported, 'False'
342 -- otherwise.
343
344 displayModePossible :: GettableStateVar Bool
345 displayModePossible =
346 makeGettableStateVar $ simpleGet (/= 0) glut_DISPLAY_MODE_POSSIBLE
347
348 --------------------------------------------------------------------------------
349
350 samplesPerPixel :: StateVar Int
351 samplesPerPixel = makeStateVar getSamplesPerPixel setSamplesPerPixel
352
353 getSamplesPerPixel :: IO Int
354 getSamplesPerPixel = do
355 m <- multisamplingSupported
356 if m
357 then simpleGet fromIntegral (fromIntegral glut_MULTISAMPLE)
358 else return defaultSamplesPerPixels
359
360 defaultSamplesPerPixels :: Int
361 defaultSamplesPerPixels = 4
362
363 setSamplesPerPixel :: Int -> IO ()
364 setSamplesPerPixel spp = do
365 m <- multisamplingSupported
366 when m $
367 glutSetOption (fromIntegral glut_MULTISAMPLE) (fromIntegral spp)
368
369 multisamplingSupported :: IO Bool
370 multisamplingSupported = isKnown "glutGetModeValues"
371
372 --------------------------------------------------------------------------------
373
374 -- | Capabilities for 'initialDisplayCapabilities', most of them are extensions
375 -- of the constructors of 'DisplayMode'.
376
377 data DisplayCapability
378 = DisplayRGBA -- ^ Number of bits of red, green, blue, and alpha in the RGBA
379 -- color buffer. Default is \"'IsAtLeast' @1@\" for red,
380 -- green, blue, and alpha capabilities, and \"'IsEqualTo'
381 -- @1@\" for the RGBA color model capability.
382 | DisplayRGB -- ^ Number of bits of red, green, and blue in the RGBA color
383 -- buffer and zero bits of alpha color buffer precision.
384 -- Default is \"'IsAtLeast' @1@\" for the red, green, and
385 -- blue capabilities, and \"'IsNotLessThan' @0@\" for alpha
386 -- capability, and \"'IsEqualTo' @1@\" for the RGBA color
387 -- model capability.
388 | DisplayRed -- ^ Red color buffer precision in bits. Default is
389 -- \"'IsAtLeast' @1@\".
390 | DisplayGreen -- ^ Green color buffer precision in bits. Default is
391 -- \"'IsAtLeast' @1@\".
392 | DisplayBlue -- ^ Blue color buffer precision in bits. Default is
393 -- \"'IsAtLeast' @1@\".
394 | DisplayIndex -- ^ Boolean if the color model is color index or not. True is
395 -- color index. Default is \"'IsAtLeast' @1@\".
396 | DisplayBuffer -- ^ Number of bits in the color index color buffer. Default
397 -- is \"'IsAtLeast' @1@\".
398 | DisplaySingle -- ^ Boolean indicate the color buffer is single buffered.
399 -- Default is \"'IsEqualTo' @1@\".
400 | DisplayDouble -- ^ Boolean indicating if the color buffer is double
401 -- buffered. Default is \"'IsEqualTo' @1@\".
402 | DisplayAccA -- ^ Red, green, blue, and alpha accumulation buffer precision
403 -- in bits. Default is \"'IsAtLeast' @1@\" for red, green,
404 -- blue, and alpha capabilities.
405 | DisplayAcc -- ^ Red, green, and green accumulation buffer precision in
406 -- bits and zero bits of alpha accumulation buffer precision.
407 -- Default is \"'IsAtLeast' @1@\" for red, green, and blue
408 -- capabilities, and \"'IsNotLessThan' @0@\" for the alpha
409 -- capability.
410 | DisplayAlpha -- ^ Alpha color buffer precision in bits. Default is
411 -- \"'IsAtLeast' @1@\".
412 | DisplayDepth -- ^ Number of bits of precsion in the depth buffer. Default
413 -- is \"'IsAtLeast' @12@\".
414 | DisplayStencil -- ^ Number of bits in the stencil buffer. Default is
415 -- \"'IsNotLessThan' @1@\".
416 | DisplaySamples -- ^ Indicates the number of multisamples to use based on
417 -- GLX\'s @SGIS_multisample@ extension (for antialiasing).
418 -- Default is \"'IsNotGreaterThan' @4@\". This default means
419 -- that a GLUT application can request multisampling if
420 -- available by simply specifying \"'With' 'DisplaySamples'\".
421 | DisplayStereo -- ^ Boolean indicating the color buffer is supports
422 -- OpenGL-style stereo. Default is \"'IsEqualTo' @1@\".
423 | DisplayLuminance -- ^ Number of bits of red in the RGBA and zero bits of green,
424 -- blue (alpha not specified) of color buffer precision.
425 -- Default is \"'IsAtLeast' @1@\" for the red capabilitis,
426 -- and \"'IsEqualTo' @0@\" for the green and blue
427 -- capabilities, and \"'IsEqualTo' @1@\" for the RGBA color
428 -- model capability, and, for X11, \"'IsEqualTo' @1@\" for
429 -- the 'DisplayXStaticGray' capability. SGI InfiniteReality (and
430 -- other future machines) support a 16-bit luminance (single
431 -- channel) display mode (an additional 16-bit alpha channel
432 -- can also be requested). The red channel maps to gray
433 -- scale and green and blue channels are not available. A
434 -- 16-bit precision luminance display mode is often
435 -- appropriate for medical imaging applications. Do not
436 -- expect many machines to support extended precision
437 -- luminance display modes.
438 | DisplayAux -- ^ (/freeglut only/) Number of auxiliary buffers. Default is
439 -- \"'IsEqualTo' @1@\".
440 | DisplayNum -- ^ A special capability name indicating where the value
441 -- represents the Nth frame buffer configuration matching
442 -- the description string. When not specified,
443 -- 'initialDisplayCapabilities' also uses the first
444 -- (best matching) configuration. 'Num' requires a relation
445 -- and numeric value.
446 | DisplayConformant -- ^ Boolean indicating if the frame buffer configuration is
447 -- conformant or not. Conformance information is based on
448 -- GLX\'s @EXT_visual_rating@ extension if supported. If the
449 -- extension is not supported, all visuals are assumed
450 -- conformant. Default is \"'IsEqualTo' @1@\".
451 | DisplaySlow -- ^ Boolean indicating if the frame buffer configuration is
452 -- slow or not. Slowness information is based on GLX\'s
453 -- @EXT_visual_rating@ extension if supported. If the
454 -- extension is not supported, all visuals are assumed fast.
455 -- Note that slowness is a relative designation relative to
456 -- other frame buffer configurations available. The intent
457 -- of the slow capability is to help programs avoid frame
458 -- buffer configurations that are slower (but perhaps higher
459 -- precision) for the current machine. Default is
460 -- \"'IsAtLeast' @0@\". This default means that slow visuals
461 -- are used in preference to fast visuals, but fast visuals
462 -- will still be allowed.
463 | DisplayWin32PFD -- ^ Only recognized on GLUT implementations for Win32, this
464 -- capability name matches the Win32 Pixel Format Descriptor
465 -- by number. 'DisplayWin32PFD' can only be used with 'Where'.
466 | DisplayXVisual -- ^ Only recongized on GLUT implementations for the X Window
467 -- System, this capability name matches the X visual ID by
468 -- number. 'DisplayXVisual' requires a relation and numeric value.
469 | DisplayXStaticGray -- ^ Only recongized on GLUT implementations for the X Window
470 -- System, boolean indicating if the frame buffer
471 -- configuration\'s X visual is of type @StaticGray@.
472 -- Default is \"'IsEqualTo' @1@\".
473 | DisplayXGrayScale -- ^ Only recongized on GLUT implementations for the X Window
474 -- System, boolean indicating if the frame buffer
475 -- configuration\'s X visual is of type @GrayScale@. Default
476 -- is \"'IsEqualTo' @1@\".
477 | DisplayXStaticColor -- ^ Only recongized on GLUT implementations for the X Window
478 -- System, boolean indicating if the frame buffer
479 -- configuration\'s X visual is of type @StaticColor@.
480 -- Default is \"'IsEqualTo' @1@\".
481 | DisplayXPseudoColor -- ^ Only recongized on GLUT implementations for the X Window
482 -- System, boolean indicating if the frame buffer
483 -- configuration\'s X visual is of type @PsuedoColor@.
484 -- Default is \"'IsEqualTo' @1@\".
485 | DisplayXTrueColor -- ^ Only recongized on GLUT implementations for the X Window
486 -- System, boolean indicating if the frame buffer
487 -- configuration\'s X visual is of type @TrueColor@. Default
488 -- is \"'IsEqualTo' @1@\".
489 | DisplayXDirectColor -- ^ Only recongized on GLUT implementations for the X Window
490 -- System, boolean indicating if the frame buffer
491 -- configuration\'s X visual is of type @DirectColor@.
492 -- Default is \"'IsEqualTo' @1@\".
493 deriving ( Eq, Ord, Show )
494
495 displayCapabilityToString :: DisplayCapability -> String
496 displayCapabilityToString x = case x of
497 DisplayRGBA -> "rgba"
498 DisplayRGB -> "rgb"
499 DisplayRed -> "red"
500 DisplayGreen -> "green"
501 DisplayBlue -> "blue"
502 DisplayIndex -> "index"
503 DisplayBuffer -> "buffer"
504 DisplaySingle -> "single"
505 DisplayDouble -> "double"
506 DisplayAccA -> "acca"
507 DisplayAcc -> "acc"
508 DisplayAlpha -> "alpha"
509 DisplayDepth -> "depth"
510 DisplayStencil -> "stencil"
511 DisplaySamples -> "samples"
512 DisplayStereo -> "stereo"
513 DisplayLuminance -> "luminance"
514 DisplayAux -> "aux"
515 DisplayNum -> "num"
516 DisplayConformant -> "conformant"
517 DisplaySlow -> "slow"
518 DisplayWin32PFD -> "win32pfd"
519 DisplayXVisual -> "xvisual"
520 DisplayXStaticGray -> "xstaticgray"
521 DisplayXGrayScale -> "xgrayscale"
522 DisplayXStaticColor -> "xstaticcolor"
523 DisplayXPseudoColor -> "xpseudocolor"
524 DisplayXTrueColor -> "xtruecolor"
525 DisplayXDirectColor -> "xdirectcolor"
526
527 -- | A single capability description for 'initialDisplayCapabilities'.
528
529 data DisplayCapabilityDescription
530 = Where DisplayCapability Relation Int
531 -- ^ A description of a capability with a specific relation to a numeric
532 -- value.
533 | With DisplayCapability
534 -- ^ When the relation and numeric value are not specified, each capability
535 -- has a different default, see the different constructors of
536 -- 'DisplayCapability'.
537 deriving ( Eq, Ord, Show )
538
539 displayCapabilityDescriptionToString :: DisplayCapabilityDescription -> String
540 displayCapabilityDescriptionToString (Where c r i) =
541 displayCapabilityToString c ++ relationToString r ++ show i
542 displayCapabilityDescriptionToString (With c) = displayCapabilityToString c
543
544 -- | Controls the /initial display mode/ used when creating top-level windows,
545 -- subwindows, and overlays to determine the OpenGL display mode for the
546 -- to-be-created window or overlay. It is described by a list of zero or more
547 -- capability descriptions, which are translated into a set of criteria used to
548 -- select the appropriate frame buffer configuration. The criteria are matched
549 -- in strict left to right order of precdence. That is, the first specified
550 -- criterion (leftmost) takes precedence over the later criteria for non-exact
551 -- criteria ('IsGreaterThan', 'IsLessThan', etc.). Exact criteria ('IsEqualTo',
552 -- 'IsNotEqualTo') must match exactly so precedence is not relevant.
553 --
554 -- Unspecified capability descriptions will result in unspecified criteria being
555 -- generated. These unspecified criteria help 'initialDisplayCapabilities'
556 -- behave sensibly with terse display mode descriptions.
557 --
558 -- Here is an example using 'initialDisplayCapabilities':
559 --
560 -- @
561 -- initialDisplayCapabilities $= [ With DisplayRGB,
562 -- Where DisplayDepth IsAtLeast 16,
563 -- With DisplaySamples,
564 -- Where DisplayStencil IsNotLessThan 2,
565 -- With DisplayDouble ]
566 -- @
567 --
568 -- The above call requests a window with an RGBA color model (but requesting
569 -- no bits of alpha), a depth buffer with at least 16 bits of precision but
570 -- preferring more, multisampling if available, at least 2 bits of stencil
571 -- (favoring less stencil to more as long as 2 bits are available), and double
572 -- buffering.
573
574 initialDisplayCapabilities :: SettableStateVar [DisplayCapabilityDescription]
575 initialDisplayCapabilities =
576 makeSettableStateVar $ \caps ->
577 withCString
578 (concat . intersperse " " . map displayCapabilityDescriptionToString $
579 caps)
580 glutInitDisplayString
581
582 -----------------------------------------------------------------------------
583
584 -- | How rendering context for new windows are created.
585
586 data RenderingContext
587 = -- | Create a new context via @glXCreateContext@ or @wglCreateContext@
588 -- (default).
589 CreateNewContext
590 | -- | Re-use the current rendering context.
591 UseCurrentContext
592 deriving ( Eq, Ord, Show )
593
594 marshalRenderingContext :: RenderingContext -> CInt
595 marshalRenderingContext CreateNewContext = glut_CREATE_NEW_CONTEXT
596 marshalRenderingContext UseCurrentContext = glut_USE_CURRENT_CONTEXT
597
598 unmarshalRenderingContext :: CInt -> RenderingContext
599 unmarshalRenderingContext r
600 | r == glut_CREATE_NEW_CONTEXT = CreateNewContext
601 | r == glut_USE_CURRENT_CONTEXT = UseCurrentContext
602 | otherwise = error "unmarshalRenderingContext"
603
604 -----------------------------------------------------------------------------
605
606 -- | (/freeglut only/) Controls the creation of rendering contexts for new
607 -- windows.
608
609 renderingContext :: StateVar RenderingContext
610 renderingContext =
611 makeStateVar
612 (simpleGet unmarshalRenderingContext glut_RENDERING_CONTEXT)
613 (glutSetOption glut_RENDERING_CONTEXT . marshalRenderingContext)
614
615 -----------------------------------------------------------------------------
616
617 -- | The kind of GLX rendering context used. Direct rendering provides a
618 -- performance advantage in some implementations. However, direct rendering
619 -- contexts cannot be shared outside a single process, and they may be unable
620 -- to render to GLX pixmaps.
621
622 data DirectRendering
623 = -- | Rendering is always done through the X server. This corresponds to
624 -- the command line argument @-indirect@, see 'initialize'.
625 ForceIndirectContext
626 | -- | Try to use direct rendering, silently using indirect rendering if this
627 -- is not possible.
628 AllowDirectContext
629 | -- | Try to use direct rendering, issue a warning and use indirect
630 -- rendering if this is not possible.
631 TryDirectContext
632 | -- | Try to use direct rendering, issue an error and terminate the program
633 -- if this is not possible.This corresponds to the command line argument
634 -- @-direct@, see 'initialize'.
635 ForceDirectContext
636 deriving ( Eq, Ord, Show )
637
638 marshalDirectRendering :: DirectRendering -> CInt
639 marshalDirectRendering x = case x of
640 ForceIndirectContext -> glut_FORCE_INDIRECT_CONTEXT
641 AllowDirectContext -> glut_ALLOW_DIRECT_CONTEXT
642 TryDirectContext -> glut_TRY_DIRECT_CONTEXT
643 ForceDirectContext -> glut_FORCE_DIRECT_CONTEXT
644
645 unmarshalDirectRendering :: CInt -> DirectRendering
646 unmarshalDirectRendering x
647 | x == glut_FORCE_INDIRECT_CONTEXT = ForceIndirectContext
648 | x == glut_ALLOW_DIRECT_CONTEXT = AllowDirectContext
649 | x == glut_TRY_DIRECT_CONTEXT = TryDirectContext
650 | x == glut_FORCE_DIRECT_CONTEXT = ForceDirectContext
651 | otherwise = error ("unmarshalDirectRendering: illegal value " ++ show x)
652
653 -----------------------------------------------------------------------------
654
655 -- | (/freeglut on X11 only/) Controls which kind of rendering context is
656 -- created when a new one is required.
657
658 directRendering :: StateVar DirectRendering
659 directRendering =
660 makeStateVar
661 (simpleGet unmarshalDirectRendering glut_DIRECT_RENDERING)
662 (glutSetOption glut_DIRECT_RENDERING . marshalDirectRendering)
663
664 -----------------------------------------------------------------------------
665
666 -- | (/freeglut only/) Controls the API major\/minor version of the OpenGL
667 -- context. If a version less than or equal to 2.1 is requested, the context
668 -- returned may implement any version no less than that requested and no
669 -- greater than 2.1. If version 3.0 is requested, the context returned must
670 -- implement exactly version 3.0. Versioning behavior once GL versions beyond
671 -- 3.0 are defined will be defined by an amendment to the OpenGL specification
672 -- to define dependencies on such GL versions.
673 --
674 -- 'Graphics.Rendering.OpenGL.GL.StringQueries.glVersion' and
675 -- 'Graphics.Rendering.OpenGL.GL.StringQueries.majorMinor' will return the
676 -- actual version supported by a context.
677 --
678 -- The default context version is (1, 0), which will typically return an
679 -- OpenGL 2.1 context, if one is available.
680
681 initialContextVersion :: StateVar (Int, Int)
682 initialContextVersion = makeStateVar getContextVersion setContextVersion
683
684 getContextVersion :: IO (Int, Int)
685 getContextVersion = do
686 major <- simpleGet fromIntegral glut_INIT_MAJOR_VERSION
687 minor <- simpleGet fromIntegral glut_INIT_MINOR_VERSION
688 return (major, minor)
689
690 setContextVersion :: (Int, Int) -> IO ()
691 setContextVersion (major, minor) =
692 glutInitContextVersion (fromIntegral major) (fromIntegral minor)
693
694 -----------------------------------------------------------------------------
695
696 -- | A flag affecting the rendering context to create, used in conjunction
697 -- with 'initialContextFlags'.
698
699 data ContextFlag
700 = -- | Debug contexts are intended for use during application development,
701 -- and provide additional runtime checking, validation, and logging
702 -- functionality while possibly incurring performance penalties. The
703 -- additional functionality provided by debug contexts may vary according
704 -- to the implementation. In some cases a debug context may be identical
705 -- to a non-debug context.
706 DebugContext
707 | -- | Forward-compatible contexts are defined only for OpenGL versions 3.0
708 -- and later. They must not support functionality marked as /deprecated/
709 -- by that version of the API, while a non-forward-compatible context must
710 -- support all functionality in that version, deprecated or not.
711 ForwardCompatibleContext
712 deriving ( Eq, Ord, Show )
713
714 marshalContextFlag :: ContextFlag -> CInt
715 marshalContextFlag x = case x of
716 DebugContext -> glut_DEBUG
717 ForwardCompatibleContext -> glut_FORWARD_COMPATIBLE
718
719 -----------------------------------------------------------------------------
720
721 -- | (/freeglut only/) Controls the set of flags for the rendering context.
722
723 initialContextFlags :: StateVar [ContextFlag]
724 initialContextFlags = makeStateVar getContextFlags setContextFlags
725
726 getContextFlags :: IO [ContextFlag]
727 getContextFlags = simpleGet i2cfs glut_INIT_FLAGS
728
729 i2cfs :: CInt -> [ContextFlag]
730 i2cfs bitfield =
731 [ c | c <- [ DebugContext, ForwardCompatibleContext ]
732 , (fromIntegral bitfield .&. marshalContextFlag c) /= 0 ]
733
734 setContextFlags :: [ContextFlag] -> IO ()
735 setContextFlags = glutInitContextFlags . toBitfield marshalContextFlag
736
737
738 -----------------------------------------------------------------------------
739
740 -- | An OpenGL API profile, affecting the rendering context to create, used
741 -- in conjunction with 'initialContextProfile'.
742
743 data ContextProfile
744 = -- | The OpenGL /core/ profile, which all OpenGL 3.2 implementations
745 -- are required to support.
746 CoreProfile
747 | -- | The OpenGL /compatibility/ profile, which is optional for OpenGL
748 -- 3.2 implementations.
749 CompatibilityProfile
750 deriving ( Eq, Ord, Show )
751
752 marshalContextProfile :: ContextProfile -> CInt
753 marshalContextProfile x = case x of
754 CoreProfile -> glut_CORE_PROFILE
755 CompatibilityProfile -> glut_COMPATIBILITY_PROFILE
756
757 -----------------------------------------------------------------------------
758
759 -- | (/freeglut only/) Controls the set of profiles for the rendering context.
760
761 initialContextProfile :: StateVar [ContextProfile]
762 initialContextProfile = makeStateVar getContextProfiles setContextProfiles
763
764 getContextProfiles :: IO [ContextProfile]
765 getContextProfiles = simpleGet i2cps glut_INIT_PROFILE
766
767 i2cps :: CInt -> [ContextProfile]
768 i2cps bitfield =
769 [ c | c <- [ CoreProfile, CompatibilityProfile ]
770 , (fromIntegral bitfield .&. marshalContextProfile c) /= 0 ]
771
772 setContextProfiles :: [ContextProfile] -> IO ()
773 setContextProfiles = glutInitContextProfile . toBitfield marshalContextProfile