-
Notifications
You must be signed in to change notification settings - Fork 3
/
listing19.html
executable file
·1858 lines (1662 loc) · 77.2 KB
/
listing19.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<!-- BEGIN META TAG INFO -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="home" href="http://developer.apple.com/">
<link rel="find" href="http://developer.apple.com/search/">
<link rel="stylesheet" type="text/css" href="../../documentation/css/adcstyle.css" title="fonts">
<script language="JavaScript" src="../../documentation/js/adc.js" type="text/javascript"></script>
<!-- END META TAG INFO -->
<!-- BEGIN TITLE -->
<title>GLCarbon1ContextPbuffer - /main.c</title>
<!-- END TITLE -->
<script language="JavaScript">
function JumpToNewPage() {
window.location=document.scpopupmenu.gotop.value;
return true;
}
</script>
</head>
<!-- BEGIN BODY OPEN -->
<body>
<!--END BODY OPEN -->
<!-- START CENTER OPEN -->
<center>
<!-- END CENTER OPEN -->
<!-- BEGIN LOGO AND SEARCH -->
<!--#include virtual="/includes/adcnavbar"-->
<!-- END LOGO AND SEARCH -->
<!-- START BREADCRUMB -->
<div id="breadcrumb">
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td scope="row"><img width="340" height="10" src="images/1dot.gif" alt=""></td>
<td><img width="340" height="10" src="images/1dot.gif" alt=""></td>
</tr>
<tr valign="middle">
<td align="left" colspan="2">
<a href="http://developer.apple.com/">ADC Home</a> > <a href="../../referencelibrary/index.html">Reference Library</a> > <a href="../../samplecode/index.html">Sample Code</a> > <a href="../../samplecode/GraphicsImaging/index.html">Graphics & Imaging</a> > <a href="../../samplecode/GraphicsImaging/idxOpenGL-date.html">OpenGL</a> > <A HREF="javascript:location.replace('index.html');">GLCarbon1ContextPbuffer</A> >
</td>
</tr>
<tr>
<td colspan="2" scope="row"><img width="680" height="35" src="images/1dot.gif" alt=""></td>
</tr>
</table>
</div>
<!-- END BREADCRUMB -->
<!-- START MAIN CONTENT -->
<!-- START TITLE GRAPHIC AND INTRO-->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td><h1><div id="pagehead">GLCarbon1ContextPbuffer</div></h1></td>
</tr>
</table>
<!-- END TITLE GRAPHIC AND INTRO -->
<!-- START WIDE COLUMN -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td id="scdetails">
<h2>/main.c</h2>
<form name="scpopupmenu" onSubmit="return false;" method=post>
<p><strong>View Source Code:</strong>
<select name="gotop" onChange="JumpToNewPage();" style="width:340px"><option selected value="ingnore">Select File</option>
<option value="listing1.html">/camera.h</option>
<option value="listing2.html">/drawInfo.h</option>
<option value="listing3.html">/glCheck.c</option>
<option value="listing4.html">/glCheck.h</option>
<option value="listing5.html">/HID Support/HID_Config_Utilities.c</option>
<option value="listing6.html">/HID Support/HID_Config_Utilities.h</option>
<option value="listing7.html">/HID Support/HID_Error_Handler.c</option>
<option value="listing8.html">/HID Support/HID_Error_Handler.h</option>
<option value="listing9.html">/HID Support/HID_Name_Lookup.c</option>
<option value="listing10.html">/HID Support/HID_Name_Lookup.h</option>
<option value="listing11.html">/HID Support/HID_Queue_Utilities.c</option>
<option value="listing12.html">/HID Support/HID_Queue_Utilities.h</option>
<option value="listing13.html">/HID Support/HID_Utilities.c</option>
<option value="listing14.html">/HID Support/HID_Utilities.h</option>
<option value="listing15.html">/HID Support/HID_Utilities_External.h</option>
<option value="listing16.html">/HID Support/HID_Utilities_Internal.h</option>
<option value="listing17.html">/HID Support/HIDSupport.c</option>
<option value="listing18.html">/HID Support/HIDSupport.h</option>
<option value="listing19.html">/main.c</option>
<option value="listing20.html">/main.h</option>
<option value="listing21.html">/pbuffer.c</option>
<option value="listing22.html">/pbuffer.h</option>
<option value="listing23.html">/SurfaceGeometry.c</option>
<option value="listing24.html">/SurfaceGeometry.h</option>
<option value="listing25.html">/trackball.c</option>
<option value="listing26.html">/trackball.h</option></select>
</p>
</form>
<p><strong><a href="GLCarbon1ContextPbuffer.zip">Download Sample</a></strong> (“GLCarbon1ContextPbuffer.zip”, 220.4K)<BR>
<strong><a href="GLCarbon1ContextPbuffer.dmg">Download Sample</a></strong> (“GLCarbon1ContextPbuffer.dmg”, 270.0K)</p>
<!--
<p><strong><a href="#">Download Sample</a></strong> (“filename.sit”, 500K)</p>
-->
</td>
</tr>
<tr>
<td scope="row"><img width="680" height="10" src="images/1dot.gif" alt=""><br>
<img height="1" width="680" src="images/1dot_919699.gif" alt=""><br>
<img width="680" height="20" src="images/1dot.gif" alt=""></td>
</tr>
<tr>
<td scope="row">
<!--googleon: index -->
<pre class="sourcecodebox">/*
* main.c
* Carbon OpenGL
*
* Created by ggs on 13 Nov 2002
Copyright: Copyright © 2002-2004 Apple Computer, Inc., All Rights Reserved
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under Apple's
copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks or logos of
Apple Computer, Inc. may be used to endorse or promote products derived from the
Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple
Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <OpenGL/glu.h>
#include <OpenGL/glext.h>
#include "HIDSupport.h"
#include "glCheck.h"
#include "trackball.h"
#include "SurfaceGeometry.h"
#include "pbuffer.h"
#include "main.h"
// ==================================
recVec gOrigin = {0.0, 0.0, 0.0};
// single set of interaction flags and states
GLint gDollyPanStartPoint[2] = {0, 0};
GLfloat gTrackBallRotation [4] = {0.0f, 0.0f, 0.0f, 0.0f};
GLboolean gDolly = GL_FALSE;
GLboolean gPan = GL_FALSE;
GLboolean gTrackball = GL_FALSE;
AGLContext gTrackingContextInfo = NULL;
EventHandlerUPP gEvtHandler; // main event handler
EventHandlerUPP gWinEvtHandler; // window event handler
IBNibRef nibRef = NULL;
AbsoluteTime gStartTime;
char gErrorMessage[256] = ""; // buffer for error message output
float gErrorTime = 0.0;
GLint gCurrentBufferName = 1; // name assigned to next window draw buffer created
#pragma mark ---- OpenGL Capabilities ----
// GL configuration info globals
// see glcheck.h for more info
GLCaps * gDisplayCaps = NULL; // array of GLCaps
CGDisplayCount gNumDisplays = 0;
// related DM change notification:
DMExtendedNotificationUPP gConfigEDMUPP = NULL;
static void getCurrentCaps (void)
{
// Check for existing opengl caps here
// This can be called again with same display caps array when display configurations are changed and
// your info needs to be updated. Note, if you are doing dynmaic allocation, the number of displays
// may change and thus you should always reallocate your display caps array.
if (gDisplayCaps && HaveOpenGLCapsChanged (gDisplayCaps, gNumDisplays)) { // see if caps have changed
free (gDisplayCaps);
gDisplayCaps = NULL;
}
if (!gDisplayCaps) { // if we do not have caps
CheckOpenGLCaps (0, NULL, &gNumDisplays); // will just update number of displays
gDisplayCaps = (GLCaps*) malloc (sizeof (GLCaps) * gNumDisplays);
CheckOpenGLCaps (gNumDisplays, gDisplayCaps, &gNumDisplays);
}
}
#pragma mark ---- Utilities ----
// return float elpased time in seconds since app start
static float getElapsedTime (void)
{
float deltaTime = (float) AbsoluteDeltaToDuration (UpTime(), gStartTime);
if (0 > deltaTime) // if negative microseconds
deltaTime /= -1000000.0;
else // else milliseconds
deltaTime /= 1000.0;
return deltaTime;
}
#pragma mark ---- Error Reporting ----
// C string to Pascal string
static void cstr2pstr (StringPtr outString, const char *inString)
{
unsigned short x = 0;
do {
outString [x + 1] = (unsigned char) inString [x];
x++;
} while ((inString [x] != 0) && (x < 256));
outString [0] = x;
}
// ---------------------------------
// error reporting as both window message and debugger string
void reportError (char * strError)
{
Str255 strErr = "\p";
gErrorTime = getElapsedTime ();
sprintf (gErrorMessage, "Error: %s (at time: %0.1f secs)", strError, gErrorTime);
// out as debug string
cstr2pstr (strErr, gErrorMessage);
DebugStr (strErr);
fflush (stderr);
}
// ---------------------------------
// if error dump agl errors to debugger string, return error
OSStatus aglReportError (void)
{
GLenum err = aglGetError();
if (AGL_NO_ERROR != err) {
char errStr[256];
sprintf (errStr, "AGL: %s",(char *) aglErrorString(err));
reportError (errStr);
}
// ensure we are returning an OSStatus noErr if no error condition
if (err == AGL_NO_ERROR)
return noErr;
else
return (OSStatus) err;
}
// ---------------------------------
// if error dump gl errors to debugger string, return error
OSStatus glReportError (void)
{
GLenum err = glGetError();
if (GL_NO_ERROR != err) {
char errStr[256];
sprintf (errStr, "GL: %s",(char *) gluErrorString(err));
reportError (errStr);
}
// ensure we are returning an OSStatus noErr if no error condition
if (err == GL_NO_ERROR)
return noErr;
else
return (OSStatus) err;
}
#pragma mark ---- OpenGL Utilities ----
// C string drawing function
void drawCStringGL (char * cstrOut, GLuint fontList)
{
GLint i = 0;
while (cstrOut [i])
glCallList (fontList + cstrOut[i++]);
}
// ---------------------------------
// AGL bitmpp font setup
GLuint buildFontGL (AGLContext ctx, GLint fontID, Style face, GLint size)
{
GLuint listBase = glGenLists (256);
if (aglUseFont (ctx, fontID , face, size, 0, 256, (long) listBase)) {
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glReportError ();
return listBase;
} else {
reportError ("aglUseFont failed\n" );
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glDeleteLists (listBase, 256);
return 0;
}
}
// ---------------------------------
// delete font list passed in
void deleteFontGL (GLuint fontList)
{
if (fontList)
glDeleteLists (fontList, 256);
}
// ---------------------------------
// given a delta time in seconds and current roatation accel, velocity and position, update overall object rotation
void updateRotation (double deltaTime, GLfloat * fRot, GLfloat * fVel, GLfloat * fAccel, GLfloat * objectRotation )
{
// update rotation based on vel and accel
float rotation[4] = {0.0f, 0.0f, 0.0f, 0.0f};
GLfloat fVMax = 2.0f;
short i;
// do velocities
for (i = 0; i < 3; i++) {
fVel[i] += fAccel[i] * deltaTime * 30.0f;
if (fVel[i] > fVMax) {
fAccel[i] *= -1.0f;
fVel[i] = fVMax;
} else if (fVel[i] < -fVMax) {
fAccel[i] *= -1.0f;
fVel[i] = -fVMax;
}
fRot[i] += fVel[i] * deltaTime * 30.0f;
while (fRot[i] > 360.0f)
fRot[i] -= 360.0f;
while (fRot[i] < -360.0f)
fRot[i] += 360.0f;
}
rotation[0] = fRot[0];
rotation[1] = 1.0f;
addToRotationTrackball (rotation, objectRotation);
rotation[0] = fRot[1];
rotation[1] = 0.0f; rotation[2] = 1.0f;
addToRotationTrackball (rotation, objectRotation);
rotation[0] = fRot[2];
rotation[2] = 0.0f; rotation[3] = 1.0f;
addToRotationTrackball (rotation, objectRotation);
}
// ---------------------------------
#ifndef DTOR
#define DTOR 0.0174532925
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
// update the projection matrix based on camera and view info
// should be called when viewport size, eye z position, or camera aperture changes
// also call if far or near changes which is determined by shape size in this case
// current context should be set before calling
void updateProjection (GLdouble width, GLdouble height, GLdouble zPos, GLdouble aperture, GLdouble shapeSize)
{
GLdouble xmin, xmax, ymin, ymax;
// far frustum plane
GLdouble zFar = -zPos + shapeSize * 0.5;
// near frustum plane (clamped at 1.0)
GLdouble zNear = MIN (-zPos - shapeSize * 0.5, 1.0);
// view aspect ratio
GLdouble aspect = width / height;
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
if (aspect > 1.0) {
ymax = zNear * tan (aperture * 0.5 * DTOR);
ymin = -ymax;
xmin = ymin * aspect;
xmax = ymax * aspect;
} else {
xmax = zNear * tan (aperture * 0.5 * DTOR);
xmin = -xmax;
ymin = xmin / aspect;
ymax = xmax / aspect;
}
glFrustum(xmin, xmax, ymin, ymax, zNear, zFar);
}
// ---------------------------------
// updates the contexts model view matrix for object and camera moves
// we will call this every draw loop for simplicity
// current context should be set before calling
void updateModelView (AGLContext aglContext, recCamera * pCamera, GLfloat * pSpinRot, GLfloat * pObjectRot, GLfloat * pWorldRot)
{
// move view
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
gluLookAt (pCamera->viewPos.x, pCamera->viewPos.y, pCamera->viewPos.z,
pCamera->viewPos.x + pCamera->viewDir.x,
pCamera->viewPos.y + pCamera->viewDir.y,
pCamera->viewPos.z + pCamera->viewDir.z,
pCamera->viewUp.x, pCamera->viewUp.y ,pCamera->viewUp.z);
if (pWorldRot) { // if we have a world rotation eval the track ball
// if we have trackball rotation to map (this IS the test I want as it can be explicitly 0.0f)
if ((gTrackingContextInfo == aglContext) && gTrackBallRotation[0] != 0.0f)
glRotatef (gTrackBallRotation[0], gTrackBallRotation[1], gTrackBallRotation[2], gTrackBallRotation[3]);
else {
}
// accumlated world rotation via trackball
glRotatef (pWorldRot[0], pWorldRot[1], pWorldRot[2], pWorldRot[3]);
}
if (pObjectRot && pSpinRot) {
// object itself rotating applied after camera rotation
glRotatef (pObjectRot[0], pObjectRot[1], pObjectRot[2], pObjectRot[3]);
pSpinRot[0] = 0.0f; // reset animation rotations (do in all cases to prevent rotating while moving with trackball)
pSpinRot[1] = 0.0f;
pSpinRot[2] = 0.0f;
}
}
// ---------------------------------
// handles resizing of GL need context update and if the window dimensions change, a
// a window dimension update, reseting of viewport and an update of the projection matrix
// this is a windowing system level routine so it handles setting context, etc.
// returns error if resize fails
OSStatus resizeGL (AGLContext aglContext, recCamera * pCamera, GLfloat shapeSize, CGRect viewRect)
{
OSStatus err = noErr;
if (!aglContext)
return paramErr;
// re-attach drawable to ensure context is updated
if (!aglSetCurrentContext (aglContext))
err = aglReportError ();
if ((noErr == err) && !aglUpdateContext (aglContext))
err = aglReportError ();
// Must go directly to the stored value to proper check for differences with window size
// Note, it is likely a toss up as to whether blinding setting the viewport is faster than doing the
// to test for changes
if (noErr == err) {
GLint aViewportDims[4];
glGetIntegerv (GL_VIEWPORT, aViewportDims);
if ((viewRect.size.width != aViewportDims[2]) ||
(viewRect.size.height != aViewportDims[3])) {
pCamera->viewOriginX = viewRect.origin.x;
pCamera->viewOriginY = viewRect.origin.y;
pCamera->viewWidth = viewRect.size.width;
pCamera->viewHeight = viewRect.size.height;
glViewport (0, 0, pCamera->viewWidth, pCamera->viewHeight);
}
}
return err;
}
// ---------------------------------
// sets the camera data to initial conditions
void resetCamera (recCamera * pCamera)
{
pCamera->aperture = 40;
pCamera->rotPoint = gOrigin;
pCamera->viewPos.x = 0.0;
pCamera->viewPos.y = 0.0;
pCamera->viewPos.z = -9.0;
pCamera->viewDir.x = -pCamera->viewPos.x;
pCamera->viewDir.y = -pCamera->viewPos.y;
pCamera->viewDir.z = -pCamera->viewPos.z;
pCamera->viewUp.x = 0;
pCamera->viewUp.y = 1;
pCamera->viewUp.z = 0;
// will be set in resize once the target view size and position is known
pCamera->viewOriginY = 0;
pCamera->viewOriginX = 0;
pCamera->viewHeight = 0;
pCamera->viewWidth = 0;
}
// ---------------------------------
void SetLighting (unsigned int mode)
{
GLfloat mat_specular[] = {1.0, 1.0, 1.0, 1.0};
GLfloat mat_shininess[] = {90.0};
GLfloat position[4] = {7.0,-7.0,12.0,0.0};
GLfloat ambient[4] = {0.2,0.2,0.2,1.0};
GLfloat diffuse[4] = {1.0,1.0,1.0,1.0};
GLfloat specular[4] = {1.0,1.0,1.0,1.0};
glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
glMaterialfv (GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
switch (mode) {
case 0:
break;
case 1:
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_FALSE);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_FALSE);
break;
case 2:
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_FALSE);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_TRUE);
break;
case 3:
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_FALSE);
break;
case 4:
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_TRUE);
break;
}
glLightfv(GL_LIGHT0,GL_POSITION,position);
glLightfv(GL_LIGHT0,GL_AMBIENT,ambient);
glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuse);
glLightfv(GL_LIGHT0,GL_SPECULAR,specular);
glEnable(GL_LIGHT0);
}
#pragma mark ---- OpenGL Minimize Handler (thanks to Dan Herman) ----
void InvertGLImage( char *imageData, size_t imageSize, size_t rowBytes )
{
long i, j;
char *tBuffer = (char*) malloc (rowBytes);
if (NULL == tBuffer) return;
// Copy by rows through temp buffer
for (i = 0, j = imageSize - rowBytes; i < imageSize >> 1; i += rowBytes, j -= rowBytes) {
memcpy( tBuffer, &imageData[i], rowBytes );
memcpy( &imageData[i], &imageData[j], rowBytes );
memcpy( &imageData[j], tBuffer, rowBytes );
}
free(tBuffer);
}
// ---------------------------------
void CompositeGLBufferIntoWindow (AGLContext ctx, Rect *bufferRect, WindowRef win)
{
GWorldPtr pGWorld;
QDErr err;
// blit OpenGL content into window backing store
// allocate buffer to hold pane image
long width = (bufferRect->right - bufferRect->left);
long height = (bufferRect->bottom - bufferRect->top);
Rect src_rect = {0, 0, height, width};
long rowBytes = width * 4;
long imageSize = rowBytes * height;
char *image = (char *) NewPtr (imageSize);
if (!image) {
printf("Out of memory in CompositeGLBufferIntoWindow()!");
return; // no harm in continuing
}
// pull GL content down to our image buffer
aglSetCurrentContext( ctx );
glReadPixels (0, 0, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, image);
// GL buffers are upside-down relative to QD buffers, so we need to flip it
InvertGLImage( image, imageSize, rowBytes );
// create a GWorld containing our image
err = NewGWorldFromPtr (&pGWorld, k32ARGBPixelFormat, &src_rect, 0, 0, 0, image, rowBytes);
if (err != noErr) {
printf("WARNING: error in NewGWorldFromPtr, called from CompositeGLBufferIntoWindow()");
free( image );
return;
}
SetPort( GetWindowPort (win));
CopyBits( GetPortBitMapForCopyBits (pGWorld), GetPortBitMapForCopyBits (GetWindowPort (win)), &src_rect, bufferRect, srcCopy, 0 );
DisposeGWorld( pGWorld );
DisposePtr ( image );
}
#pragma mark ---- Display Manager Event Handling ----
// update our GL configuration info based on display change notification
void handleConfigDMEvent (void *userData, short theMessage, void *notifyData)
{
if (kDMNotifyEvent == theMessage) { // post change notifications only
getCurrentCaps ();
}
}
// ---------------------------------
// handle display config changes meaing we need to update the GL context via the resize function and check for windwo dimension changes
// also note we redraw the content here as it could be lost in a display config change
void handleWindowDMEvent (void *userData, short theMessage, void *notifyData)
{
if (kDMNotifyEvent == theMessage) { // post change notifications only
pRecContext pContextInfo = NULL;
WindowRef window = (WindowRef) userData;
if (window)
pContextInfo = GetCurrentContextInfo (window);
if (pContextInfo) { // have a valid OpenGl window
Rect rectPort;
CGRect viewRect = {{0.0f, 0.0f}, {0.0f, 0.0f}};
#if DEBUG
sprintf (pContextInfo->message, "Event: Display Change at %0.1f secs", getElapsedTime ());
pContextInfo->msgTime = getElapsedTime ();
#endif
GetWindowPortBounds (window, &rectPort);
viewRect.size.width = (float) (rectPort.right - rectPort.left);
viewRect.size.height = (float) (rectPort.bottom - rectPort.top);
resizeGL (pContextInfo->aglContext, &pContextInfo->camera, pContextInfo->shapeSize, viewRect);
InvalWindowRect (window, &rectPort); // force redrow
}
}
}
#pragma mark ---- OpenGL Window ----
// intializes context conditions
static void initialConditions (pRecContext pContextInfo)
{
BlockZero (pContextInfo, sizeof (recContext));
resetCamera (&pContextInfo->camera);
pContextInfo->info = kInfoState;
pContextInfo->drawHelp = 1;
pContextInfo->timer = NULL;
// set up structure for this context's pbuffer
#pragma mark *** allocate and initialize pbuffer structure ***
pRecPbuffer pPbufferInfo = (pRecPbuffer) NewPtr (sizeof (recPbuffer));
initialConditionsPbuffer (pPbufferInfo);
pContextInfo->pPbuffer = pPbufferInfo;
}
// ---------------------------------
OSStatus buildGL (WindowRef window)
{
OSStatus err = noErr;
/*
#if kUseMultiSample
GLint attrib[] = { AGL_RGBA, AGL_DOUBLEBUFFER, AGL_DEPTH_SIZE, 16, AGL_NO_RECOVERY,
AGL_SAMPLE_BUFFERS_ARB, 1, AGL_SAMPLES_ARB, kSamples, AGL_NONE };
#else
GLint attrib[] = { AGL_RGBA, AGL_DOUBLEBUFFER, AGL_DEPTH_SIZE, 16, AGL_NONE };
#endif
*/
#if kUseMultiSample
GLint attrib[] = { AGL_RGBA, AGL_DOUBLEBUFFER, AGL_RED_SIZE, 8, AGL_ALPHA_SIZE, 8, AGL_DEPTH_SIZE, 24, AGL_CLOSEST_POLICY, AGL_NO_RECOVERY, AGL_SAMPLE_BUFFERS_ARB, 1, AGL_SAMPLES_ARB, kSamples, AGL_NONE };
#else
GLint attrib[] = { AGL_RGBA, AGL_DOUBLEBUFFER, AGL_RED_SIZE, 8, AGL_ALPHA_SIZE, 8, AGL_DEPTH_SIZE, 24, AGL_CLOSEST_POLICY, AGL_NO_RECOVERY, AGL_NONE };
#endif
ProcessSerialNumber psn = { 0, kCurrentProcess };
pRecContext pContextInfo = GetCurrentContextInfo(window);
if (NULL == pContextInfo)
return paramErr;
if (pContextInfo->aglContext)
return noErr; // already built
// build context
pContextInfo->aglContext = NULL;
pContextInfo->aglPixFmt = aglChoosePixelFormat (NULL, 0, attrib);
err = aglReportError ();
if (pContextInfo->aglPixFmt) {
// Note: when using a single context with AGL one must ensure that there is always a context attached to a window to ensure
// the accelerated surface is not destroyed. We use buffer naming and use a dummy context to hold accelerated surface in place.
// The following code points both contexts to the same buffer name (thus buffer) and then leaves the dummy context attached to the
// window.
pContextInfo->windowBufferName = gCurrentBufferName++;
pContextInfo->aglWindowDummyContext = aglCreateContext (pContextInfo->aglPixFmt, 0); // create a context to hold buffers for the window
err = aglReportError ();
aglSetInteger (pContextInfo->aglWindowDummyContext, AGL_BUFFER_NAME, &pContextInfo->windowBufferName); // set buffer name for this window context
if ((noErr == err) && (NULL != pContextInfo->aglWindowDummyContext)) {
pContextInfo->aglContext = aglCreateContext (pContextInfo->aglPixFmt, 0);
err = aglReportError ();
aglSetInteger (pContextInfo->aglContext, AGL_BUFFER_NAME, &pContextInfo->windowBufferName); // set same buffer name to share hardware buffers
}
}
#if kUseMultiSample
// if multi-sample pixel format or context fails allocate a non-multi-sample one
if ((noErr != err) || (NULL == pContextInfo->aglContext)) { // try non-multisample
attrib[10] = attrib[11] = attrib[12] = attrib[13] = 0; // remove multi-sample attribs
if (pContextInfo->aglPixFmt)
aglDestroyPixelFormat (pContextInfo->aglPixFmt);
pContextInfo->aglPixFmt = aglChoosePixelFormat (NULL, 0, attrib);
err = aglReportError ();
if (pContextInfo->aglPixFmt) {
pContextInfo->windowBufferName = gCurrentBufferName++;
pContextInfo->aglWindowDummyContext = aglCreateContext (pContextInfo->aglPixFmt, 0); // create a context to hold buffers for the window
err = aglReportError ();
aglSetInteger (pContextInfo->aglWindowDummyContext, AGL_BUFFER_NAME, &pContextInfo->windowBufferName); // set buffer name for this window context
if ((noErr == err) && (NULL != pContextInfo->aglWindowDummyContext)) {
pContextInfo->aglContext = aglCreateContext (pContextInfo->aglPixFmt, 0);
err = aglReportError ();
aglSetInteger (pContextInfo->aglContext, AGL_BUFFER_NAME, &pContextInfo->windowBufferName); // set same buffer name to share hardware buffers
}
}
}
#endif
if (pContextInfo->aglContext) {
Rect rectPort;
short fNum;
GLint swap = 1;
CGRect viewRect = {{0.0f, 0.0f}, {0.0f, 0.0f}};
GrafPtr portSave = NULL;
GetPort (&portSave);
SetPort ((GrafPtr) GetWindowPort (window));
if(!aglSetDrawable(pContextInfo->aglWindowDummyContext, GetWindowPort (window))) // force creation of buffers for window
err = aglReportError ();
// now set real context in use for rest of app (window context just ensures we maintain the buffers on detach and attach to pbuffer)
if(!aglSetDrawable(pContextInfo->aglContext, GetWindowPort (window)))
err = aglReportError ();
if (!aglSetCurrentContext(pContextInfo->aglContext))
err = aglReportError ();
pContextInfo->currentVS = aglGetVirtualScreen (pContextInfo->aglContext);
// ensure we know when display configs are changed
pContextInfo->windowEDMUPP = NewDMExtendedNotificationUPP (handleWindowDMEvent); // for display change notification
DMRegisterExtendedNotifyProc (pContextInfo->windowEDMUPP, (void *) window, NULL, &psn);
// VBL SYNC
if (!aglSetInteger (pContextInfo->aglContext, AGL_SWAP_INTERVAL, &swap))
aglReportError ();
// init GL stuff here
#if kUseMultiSample
switch (pContextInfo->modeFSAA) {
case kFSAAOff:
glDisable (GL_MULTISAMPLE_ARB);
break;
case kFSAAFast:
glEnable (GL_MULTISAMPLE_ARB);
glHint (GL_MULTISAMPLE_FILTER_HINT_NV, GL_FASTEST);
break;
case kFSAANice:
glEnable (GL_MULTISAMPLE_ARB);
glHint (GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
break;
}
#endif
// context state (applies to pbuffer and window since context is shared)
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glFrontFace(GL_CCW);
glPolygonOffset (1.0, 1.0);
glEnable (GL_ALPHA_TEST);
glAlphaFunc (GL_GREATER, 0.5);
glEnable (GL_BLEND); // for text fading
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // ditto
glClearColor(0.0,0.0,0.0,0.0);
SetLighting (4); // lighting for pbuffer only but set context wide
pContextInfo->shapeSize = 9.0f; // max radius of of objects
GetFNum ("\pGeneva", &fNum); // build font
pContextInfo->boldFontList = buildFontGL (pContextInfo->aglContext, fNum, bold, 9);
pContextInfo->regFontList = buildFontGL (pContextInfo->aglContext, fNum, normal, 9);
// setup viewport and prespective
GetWindowPortBounds (window, &rectPort);
viewRect.size.width = (float) (rectPort.right - rectPort.left);
viewRect.size.height = (float) (rectPort.bottom - rectPort.top);
pContextInfo->camera.viewOriginX = viewRect.origin.x;
pContextInfo->camera.viewOriginY = viewRect.origin.y;
pContextInfo->camera.viewWidth = viewRect.size.width;
pContextInfo->camera.viewHeight = viewRect.size.height;
glViewport (0, 0, pContextInfo->camera.viewWidth, pContextInfo->camera.viewHeight);
// window geometry
#if kUseNonPowerOf2
BuildGeometry (kCube, 0, 0, 0, &pContextInfo->polyList, &pContextInfo->lineList, &pContextInfo->pointList, kPbufferWidth, kPbufferHeight);
#else
BuildGeometry (kCube, 0, 0, 0, &pContextInfo->polyList, &pContextInfo->lineList, &pContextInfo->pointList, 0, 0);
#endif
// build pbuffer, set display lists (memory already allocated and initialized)
#pragma mark *** build pbuffer and add geometry for it to display ***
pContextInfo->pPbuffer->aglPixFmt = pContextInfo->aglPixFmt;
pContextInfo->pPbuffer->aglContext = pContextInfo->aglContext;
BuildGeometry (pContextInfo->pPbuffer->surface, pContextInfo->pPbuffer->colorScheme, // builds lists in current context (not pbuffer specific)
pContextInfo->pPbuffer->subdivisions, pContextInfo->pPbuffer->xyRatio,
&(pContextInfo->pPbuffer->polyList), &(pContextInfo->pPbuffer->lineList), &(pContextInfo->pPbuffer->pointList),
0, 0);
if (noErr != buildPbuffer (pContextInfo->pPbuffer)) // creates pbuffer drawable (but does not do anything with it yet)
reportError ("buildPbuffer failed.");
SetPort (portSave);
}
return err;
}
// ---------------------------------
// dump window data structures and OpenGL context and related data structures
OSStatus disposeGL (pRecContext pContextInfo)
{
// release our data
if ( pContextInfo != NULL )
{
if (pContextInfo->windowEDMUPP) { // dispose UPP for DM notifications
DisposeDMExtendedNotificationUPP (pContextInfo->windowEDMUPP);
pContextInfo->windowEDMUPP = NULL;
}
// dump context pbuffer
#pragma mark *** dispose pbuffer ***
if (pContextInfo->pPbuffer) {
aglSetCurrentContext (pContextInfo->aglContext);
disposePbuffer (pContextInfo->pPbuffer);
free (pContextInfo->pPbuffer);
pContextInfo->pPbuffer = NULL;
}
aglSetDrawable (pContextInfo->aglWindowDummyContext, NULL);
aglSetDrawable (pContextInfo->aglContext, NULL);
aglSetCurrentContext (NULL);
if (pContextInfo->aglWindowDummyContext) {
aglDestroyContext (pContextInfo->aglWindowDummyContext);
pContextInfo->aglWindowDummyContext = NULL;
}
if (pContextInfo->aglContext) {
aglDestroyContext (pContextInfo->aglContext);
pContextInfo->aglContext = NULL;
}
if (pContextInfo->aglPixFmt) {
aglDestroyPixelFormat (pContextInfo->aglPixFmt);
pContextInfo->aglPixFmt = NULL;
}
if (pContextInfo->timer) {
RemoveEventLoopTimer(pContextInfo->timer);
pContextInfo->timer = NULL;
}
// dump font display list
if (pContextInfo->boldFontList) {
deleteFontGL (pContextInfo->boldFontList);
pContextInfo->boldFontList = 0;
}
if (pContextInfo->regFontList) {
deleteFontGL (pContextInfo->regFontList);
pContextInfo->regFontList = 0;
}
}
return noErr;
}
// ---------------------------------
#include "drawInfo.h" // source info for info output
// ---------------------------------
// draw text info
// note: this bitmap technique is not the speediest and one should use textures for font in performance critical code
static void drawInfo (pRecContext pContextInfo)
{
static float msgPresistance = 10.0f;
char cstr [256];
GLint matrixMode, line = 1;
GLboolean depthTest = glIsEnabled (GL_DEPTH_TEST);
GLfloat height, width;
if (!pContextInfo)
return;
height = pContextInfo->camera.viewHeight;
width = pContextInfo->camera.viewWidth;
glDisable (GL_DEPTH_TEST); // ensure text is not remove by deoth buffer test.
glEnable (GL_BLEND); // for text fading
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // ditto
// set orthograhic 1:1 pixel transform in local view coords
glGetIntegerv (GL_MATRIX_MODE, &matrixMode);
glMatrixMode (GL_PROJECTION);
glPushMatrix();
glLoadIdentity ();
glMatrixMode (GL_MODELVIEW);
glPushMatrix();
glLoadIdentity ();
glScalef (2.0 / width, -2.0 / height, 1.0);
glTranslatef (-width / 2.0, -height / 2.0, 0.0);
// output strings
glColor3f (1.0, 1.0, 1.0);
sprintf (cstr, "Camera at (%0.1f, %0.1f, %0.1f) looking at (%0.1f, %0.1f, %0.1f) with %0.1f aperture",
pContextInfo->camera.viewPos.x, pContextInfo->camera.viewPos.y, pContextInfo->camera.viewPos.z,
pContextInfo->camera.viewDir.x, pContextInfo->camera.viewDir.y, pContextInfo->camera.viewDir.z,
pContextInfo->camera.aperture);
glRasterPos3d (10, line++ * 12, 0);
drawCStringGL (cstr, pContextInfo->boldFontList);
sprintf (cstr, "World Rotation: (%0.1f, %0.2f, %0.2f, %0.2f)",
pContextInfo->worldRotation[0], pContextInfo->worldRotation[1], pContextInfo->worldRotation[2], pContextInfo->worldRotation[3]);
glRasterPos3d (10, line++ * 12, 0);
drawCStringGL (cstr, pContextInfo->regFontList);
sprintf (cstr, "Vertices: %ld, Color Scheme: %ld",
pContextInfo->pPbuffer->subdivisions * pContextInfo->pPbuffer->xyRatio * pContextInfo->pPbuffer->subdivisions,
pContextInfo->pPbuffer->colorScheme);
glRasterPos3d (10, line++ * 12, 0);
drawCStringGL (cstr, pContextInfo->regFontList);
{
GLboolean twoSidedLighting, localViewer;
glGetBooleanv (GL_LIGHT_MODEL_LOCAL_VIEWER, &localViewer);
glGetBooleanv (GL_LIGHT_MODEL_TWO_SIDE, &twoSidedLighting);
if (!pContextInfo->pPbuffer->lighting) {
sprintf (cstr, "-- Lighting off");
} else {
if (!twoSidedLighting)
sprintf (cstr, "-- Single Sided Lighting");
else
sprintf (cstr, "-- Two Sided Lighting");
if (localViewer)
sprintf (cstr, "%s: Local Viewer", cstr);
}
glRasterPos3d (10, line++ * 12, 0);
drawCStringGL (cstr, pContextInfo->regFontList);
}
glRasterPos3d (10, line++ * 12, 0);
#if kUseMultiSample
switch (pContextInfo->modeFSAA) {
case kFSAAOff:
sprintf (cstr, "-- %d x FSAA: Disabled", kSamples);
break;
case kFSAAFast:
sprintf (cstr, "-- %d x FSAA: Fastest hint", kSamples);
break;
case kFSAANice:
sprintf (cstr, "-- %d x FSAA: Nicest hint", kSamples);
break;
}
#else
sprintf (cstr, "-- FSAA: Not Used");
#endif
drawCStringGL (cstr, pContextInfo->regFontList);
// message string
if (pContextInfo->message[0]) {
float currDelta = getElapsedTime () - pContextInfo->msgTime;
glColor4f (1.0, 1.0, 1.0, (msgPresistance - currDelta) * 0.1);
glRasterPos3d (10, line++ * 12, 0);
drawCStringGL (pContextInfo->message, pContextInfo->boldFontList);
if (currDelta > msgPresistance)
pContextInfo->message[0] = 0;
}
// global error message
if (gErrorMessage[0]) {
float currDelta = getElapsedTime () - gErrorTime;
glColor4f (1.0, 0.2, 0.2, (msgPresistance - currDelta) * 0.1);
glRasterPos3d (10, line++ * 12, 0);
drawCStringGL (gErrorMessage, pContextInfo->boldFontList);
if (currDelta > msgPresistance)
gErrorMessage[0] = 0;
}