-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlisting10.html
executable file
·992 lines (834 loc) · 34.4 KB
/
listing10.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
<!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>OpenGL Screensaver - /Source/BasicOpenGLView.m</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');">OpenGL Screensaver</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">OpenGL Screensaver</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>/Source/BasicOpenGLView.m</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">/Headers/BasicOpenGLView.h</option>
<option value="listing2.html">/Headers/drawInfo.h</option>
<option value="listing3.html">/Headers/glCheck.h</option>
<option value="listing4.html">/Headers/OpenGLScreensaverView.h</option>
<option value="listing5.html">/Headers/StringTexture.h</option>
<option value="listing6.html">/Headers/trackball.h</option>
<option value="listing7.html">/main.m</option>
<option value="listing8.html">/OpenGL Screensaver.saver/Contents/Resources/ReadMe.txt</option>
<option value="listing9.html">/ReadMe.txt</option>
<option value="listing10.html">/Source/BasicOpenGLView.m</option>
<option value="listing11.html">/Source/drawInfo.m</option>
<option value="listing12.html">/Source/glCheck.c</option>
<option value="listing13.html">/Source/OpenGLScreensaverView.m</option>
<option value="listing14.html">/Source/StringTexture.m</option>
<option value="listing15.html">/Source/trackball.c</option></select>
</p>
</form>
<p><strong><a href="OpenGL_Screensaver.zip">Download Sample</a></strong> (“OpenGL_Screensaver.zip”, 143.0K)<BR>
<strong><a href="OpenGL_Screensaver.dmg">Download Sample</a></strong> (“OpenGL_Screensaver.dmg”, 206.4K)</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">/*
* BasicOpenGLView.m
*
* Created by ggs on April 1 2003.
* Copyright (c) 2003 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.
*
*/
#import "BasicOpenGLView.h"
#import "glcheck.h"
#import "trackball.h"
#import "drawinfo.h"
// ==================================
// simple cube data
GLint cube_num_vertices = 8;
GLfloat cube_vertices [8][3] = {
{1.0, 1.0, 1.0}, {1.0, -1.0, 1.0}, {-1.0, -1.0, 1.0}, {-1.0, 1.0, 1.0},
{1.0, 1.0, -1.0}, {1.0, -1.0, -1.0}, {-1.0, -1.0, -1.0}, {-1.0, 1.0, -1.0} };
GLfloat cube_vertex_colors [8][3] = {
{1.0, 1.0, 1.0}, {1.0, 1.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 1.0, 1.0},
{1.0, 0.0, 1.0}, {1.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 1.0} };
GLint num_faces = 6;
short cube_faces [6][4] = {
{3, 2, 1, 0}, {2, 3, 7, 6}, {0, 1, 5, 4}, {3, 0, 4, 7}, {1, 2, 6, 5}, {4, 5, 6, 7} };
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;
BasicOpenGLView * gTrackingViewInfo = NULL;
// time and message info
CFAbsoluteTime gMsgPresistance = 10.0f;
// error output
StringTexture * gErrStringTex;
float gErrorTime;
// ==================================
#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);
initCapsTexture (gDisplayCaps, gNumDisplays); // (re)init the texture for printing caps
}
}
#pragma mark ---- Utilities ----
static CFAbsoluteTime gStartTime = 0.0f;
// set app start time
static void setStartTime (void)
{
gStartTime = CFAbsoluteTimeGetCurrent ();
}
// ---------------------------------
// return float elpased time in seconds since app start
static CFAbsoluteTime getElapsedTime (void)
{
return CFAbsoluteTimeGetCurrent () - gStartTime;
}
#pragma mark ---- Error Reporting ----
// error reporting as both window message and debugger string
void reportError (char * strError)
{
NSMutableDictionary *attribs = [NSMutableDictionary dictionary];
[attribs setObject: [NSFont fontWithName: @"Monaco" size: 9.0f] forKey: NSFontAttributeName];
[attribs setObject: [NSColor whiteColor] forKey: NSForegroundColorAttributeName];
gErrorTime = getElapsedTime ();
NSString * errString = [NSString stringWithFormat:@"Error: %s (at time: %0.1f secs).", strError, gErrorTime];
NSLog (@"%@\n", errString);
if (gErrStringTex)
[gErrStringTex setString:errString withAttributes:attribs];
else {
gErrStringTex = [[StringTexture alloc] initWithString:errString withAttributes:attribs withTextColor:[NSColor colorWithDeviceRed:1.0f green:1.0f blue:1.0f alpha:1.0f] withBoxColor:[NSColor colorWithDeviceRed:1.0f green:0.0f blue:0.0f alpha:0.3f] withBorderColor:[NSColor colorWithDeviceRed:1.0f green:0.0f blue:0.0f alpha:0.8f]];
}
}
// ---------------------------------
// if error dump gl errors to debugger string, return error
GLenum glReportError (void)
{
GLenum err = glGetError();
if (GL_NO_ERROR != err)
reportError ((char *) gluErrorString (err));
return err;
}
#pragma mark ---- OpenGL Utils ----
// ---------------------------------
// draw our simple cube based on current modelview and projection matrices
static void drawCube (GLfloat fSize)
{
long f, i;
if (1) {
glColor3f (1.0, 0.5, 0.0);
glBegin (GL_QUADS);
for (f = 0; f < num_faces; f++)
for (i = 0; i < 4; i++) {
glColor3f (cube_vertex_colors[cube_faces[f][i]][0], cube_vertex_colors[cube_faces[f][i]][1], cube_vertex_colors[cube_faces[f][i]][2]);
glVertex3f(cube_vertices[cube_faces[f][i]][0] * fSize, cube_vertices[cube_faces[f][i]][1] * fSize, cube_vertices[cube_faces[f][i]][2] * fSize);
}
glEnd ();
}
if (1) {
glColor3f (0.0, 0.0, 0.0);
for (f = 0; f < num_faces; f++) {
glBegin (GL_LINE_LOOP);
for (i = 0; i < 4; i++)
glVertex3f(cube_vertices[cube_faces[f][i]][0] * fSize, cube_vertices[cube_faces[f][i]][1] * fSize, cube_vertices[cube_faces[f][i]][2] * fSize);
glEnd ();
}
}
}
// ===================================
@implementation BasicOpenGLView
// pixel format definition
+ (NSOpenGLPixelFormat*) basicPixelFormat
{
NSOpenGLPixelFormatAttribute attributes [] = {
NSOpenGLPFAWindow,
NSOpenGLPFAAllRenderers,
NSOpenGLPFAAccelerated,
NSOpenGLPFADoubleBuffer, // double buffered
NSOpenGLPFAColorSize, (NSOpenGLPixelFormatAttribute)32, // 32 bit color buffer
NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute)16, // 32 bit depth buffer
(NSOpenGLPixelFormatAttribute)nil
};
return [[[NSOpenGLPixelFormat alloc] initWithAttributes:attributes] autorelease];
}
// ---------------------------------
// update the projection matrix based on camera and view info
- (void) updateProjection
{
GLdouble ratio, radians, wd2;
GLdouble left, right, top, bottom, near, far;
[[self openGLContext] makeCurrentContext];
// set projection
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
near = -camera.viewPos.z - shapeSize * 0.5;
if (near < 0.00001)
near = 0.00001;
far = -camera.viewPos.z + shapeSize * 0.5;
if (near < 1.0)
near = 1.0;
radians = 0.0174532925 * camera.aperture / 2; // half aperture degrees to radians
wd2 = near * tan(radians);
ratio = camera.viewWidth / (float) camera.viewHeight;
if (ratio >= 1.0) {
left = -ratio * wd2;
right = ratio * wd2;
top = wd2;
bottom = -wd2;
} else {
left = -wd2;
right = wd2;
top = wd2 / ratio;
bottom = -wd2 / ratio;
}
glFrustum (left, right, bottom, top, near, far);
[self updateCameraString];
}
// ---------------------------------
// updates the contexts model view matrix for object and camera moves
- (void) updateModelView
{
[[self openGLContext] makeCurrentContext];
// move view
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
gluLookAt (camera.viewPos.x, camera.viewPos.y, camera.viewPos.z,
camera.viewPos.x + camera.viewDir.x,
camera.viewPos.y + camera.viewDir.y,
camera.viewPos.z + camera.viewDir.z,
camera.viewUp.x, camera.viewUp.y ,camera.viewUp.z);
// if we have trackball rotation to map (this IS the test I want as it can be explicitly 0.0f)
if ((gTrackingViewInfo == self) && gTrackBallRotation[0] != 0.0f)
glRotatef (gTrackBallRotation[0], gTrackBallRotation[1], gTrackBallRotation[2], gTrackBallRotation[3]);
else {
}
// accumlated world rotation via trackball
glRotatef (worldRotation[0], worldRotation[1], worldRotation[2], worldRotation[3]);
// object itself rotating applied after camera rotation
glRotatef (objectRotation[0], objectRotation[1], objectRotation[2], objectRotation[3]);
rRot[0] = 0.0f; // reset animation rotations (do in all cases to prevent rotating while moving with trackball)
rRot[1] = 0.0f;
rRot[2] = 0.0f;
[self updateCameraString];
}
// ---------------------------------
// 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
- (void) resizeGL
{
NSRect rectView = [self bounds];
// ensure camera knows size changed
if ((camera.viewHeight != rectView.size.height) ||
(camera.viewWidth != rectView.size.width)) {
camera.viewHeight = rectView.size.height;
camera.viewWidth = rectView.size.width;
glViewport (0, 0, camera.viewWidth, camera.viewHeight);
[self updateProjection]; // update projection matrix
[self updateInfoString];
}
}
- (void)reshape
{
NSRect bounds = [self bounds];
NSRect visRect = [self visibleRect];
[[self openGLContext] makeCurrentContext];
glViewport(-floor(visRect.origin.x), -floor(visRect.origin.y), floor(bounds.size.width), floor(bounds.size.height));
glScissor(0, 0, floor(visRect.size.width), floor(visRect.size.height));
}
// ---------------------------------
// move camera in z axis
-(void)mouseDolly: (NSPoint) location
{
GLfloat dolly = (gDollyPanStartPoint[1] -location.y) * -camera.viewPos.z / 300.0f;
camera.viewPos.z += dolly;
if (camera.viewPos.z == 0.0) // do not let z = 0.0
camera.viewPos.z = 0.0001;
gDollyPanStartPoint[0] = location.x;
gDollyPanStartPoint[1] = location.y;
}
// ---------------------------------
// move camera in x/y plane
- (void)mousePan: (NSPoint) location
{
GLfloat panX = (gDollyPanStartPoint[0] - location.x) / (900.0f / -camera.viewPos.z);
GLfloat panY = (gDollyPanStartPoint[1] - location.y) / (900.0f / -camera.viewPos.z);
camera.viewPos.x -= panX;
camera.viewPos.y -= panY;
gDollyPanStartPoint[0] = location.x;
gDollyPanStartPoint[1] = location.y;
}
// ---------------------------------
// sets the camera data to initial conditions
- (void) resetCamera
{
camera.aperture = 40;
camera.rotPoint = gOrigin;
camera.viewPos.x = 0.0;
camera.viewPos.y = 0.0;
camera.viewPos.z = -10.0;
camera.viewDir.x = -camera.viewPos.x;
camera.viewDir.y = -camera.viewPos.y;
camera.viewDir.z = -camera.viewPos.z;
camera.viewUp.x = 0;
camera.viewUp.y = 1;
camera.viewUp.z = 0;
}
// ---------------------------------
// given a delta time in seconds and current rotation accel, velocity and position, update overall object rotation
- (void) updateObjectRotationForTimeDelta:(CFAbsoluteTime)deltaTime
{
// update rotation based on vel and accel
float rotation[4] = {0.0f, 0.0f, 0.0f, 0.0f};
GLfloat fVMax = 2.0;
short i;
// do velocities
for (i = 0; i < 3; i++) {
rVel[i] += rAccel[i] * deltaTime * 30.0;
if (rVel[i] > fVMax) {
rAccel[i] *= -1.0;
rVel[i] = fVMax;
} else if (rVel[i] < -fVMax) {
rAccel[i] *= -1.0;
rVel[i] = -fVMax;
}
rRot[i] += rVel[i] * deltaTime * 30.0;
while (rRot[i] > 360.0)
rRot[i] -= 360.0;
while (rRot[i] < -360.0)
rRot[i] += 360.0;
}
rotation[0] = rRot[0];
rotation[1] = 1.0f;
addToRotationTrackball (rotation, objectRotation);
rotation[0] = rRot[1];
rotation[1] = 0.0f; rotation[2] = 1.0f;
addToRotationTrackball (rotation, objectRotation);
rotation[0] = rRot[2];
rotation[2] = 0.0f; rotation[3] = 1.0f;
addToRotationTrackball (rotation, objectRotation);
}
// ---------------------------------
// per-window timer function, basic time based animation preformed here
- (void)animationTimer:(NSTimer *)timer
{
BOOL shouldDraw = NO;
if (fAnimate) {
CFTimeInterval deltaTime = CFAbsoluteTimeGetCurrent () - time;
if (deltaTime > 10.0) // skip pauses
return;
else {
// if we are not rotating with trackball in this window
if (!gTrackball || (gTrackingViewInfo != self)) {
[self updateObjectRotationForTimeDelta: deltaTime]; // update object rotation
}
shouldDraw = YES; // force redraw
}
}
time = CFAbsoluteTimeGetCurrent (); //reset time in all cases
// if we have current messages
if (((getElapsedTime () - msgTime) < gMsgPresistance) || ((getElapsedTime () - gErrorTime) < gMsgPresistance))
shouldDraw = YES; // force redraw
if (YES == shouldDraw)
[self drawRect:[self bounds]]; // redraw now instead dirty to enable updates during live resize
}
#pragma mark ---- Text Drawing ----
// these functions create or update StringTextures one should expect to have to regenerate the image, bitmap and texture when the string changes thus these functions are not particularly light weight
- (void) updateInfoString
{ // update info string texture
NSString * string = [NSString stringWithFormat:@"(%0.0f x %0.0f) \n%s \n%s", [self bounds].size.width, [self bounds].size.height, glGetString (GL_RENDERER), glGetString (GL_VERSION)];
if (infoStringTex)
[infoStringTex setString:string withAttributes:stanStringAttrib];
else {
infoStringTex = [[StringTexture alloc] initWithString:string withAttributes:stanStringAttrib withTextColor:[NSColor colorWithDeviceRed:1.0f green:1.0f blue:1.0f alpha:1.0f] withBoxColor:[NSColor colorWithDeviceRed:0.5f green:0.5f blue:0.5f alpha:0.5f] withBorderColor:[NSColor colorWithDeviceRed:0.8f green:0.8f blue:0.8f alpha:0.8f]];
}
}
// ---------------------------------
- (void) createHelpString
{
NSString * string = [NSString stringWithFormat:@"Cmd-A: animate Cmd-I: show info \n'h': toggle help 'c': toggle OpenGL caps"];
helpStringTex = [[StringTexture alloc] initWithString:string withAttributes:stanStringAttrib withTextColor:[NSColor colorWithDeviceRed:1.0f green:1.0f blue:1.0f alpha:1.0f] withBoxColor:[NSColor colorWithDeviceRed:0.0f green:0.5f blue:0.0f alpha:0.5f] withBorderColor:[NSColor colorWithDeviceRed:0.3f green:0.8f blue:0.3f alpha:0.8f]];
}
// ---------------------------------
- (void) createMessageString
{
NSString * string = [NSString stringWithFormat:@"No messages..."];
msgStringTex = [[StringTexture alloc] initWithString:string withAttributes:stanStringAttrib withTextColor:[NSColor colorWithDeviceRed:1.0f green:1.0f blue:1.0f alpha:1.0f] withBoxColor:[NSColor colorWithDeviceRed:0.5f green:0.5f blue:0.5f alpha:0.5f] withBorderColor:[NSColor colorWithDeviceRed:0.8f green:0.8f blue:0.8f alpha:0.8f]];
}
// ---------------------------------
- (void) updateCameraString
{ // update info string texture
NSString * string = [NSString stringWithFormat:@"Camera at (%0.1f, %0.1f, %0.1f) looking at (%0.1f, %0.1f, %0.1f) with %0.1f aperture", camera.viewPos.x, camera.viewPos.y, camera.viewPos.z, camera.viewDir.x, camera.viewDir.y, camera.viewDir.z, camera.aperture];
if (camStringTex)
[camStringTex setString:string withAttributes:stanStringAttrib];
else {
camStringTex = [[StringTexture alloc] initWithString:string withAttributes:stanStringAttrib withTextColor:[NSColor colorWithDeviceRed:1.0f green:1.0f blue:1.0f alpha:1.0f] withBoxColor:[NSColor colorWithDeviceRed:0.5f green:0.5f blue:0.5f alpha:0.5f] withBorderColor:[NSColor colorWithDeviceRed:0.8f green:0.8f blue:0.8f alpha:0.8f]];
}
}
// ---------------------------------
// draw text info using our StringTexture class for much more optimized text drawing
- (void) drawInfo
{
GLint matrixMode;
GLboolean depthTest = glIsEnabled (GL_DEPTH_TEST);
GLfloat height, width, messageTop = 10.0f;
height = camera.viewHeight;
width = camera.viewWidth;
glDisable (GL_DEPTH_TEST); // ensure text is not remove by deoth buffer test.
glEnable (GL_BLEND); // for text fading
glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // ditto
glEnable (GL_TEXTURE_RECTANGLE_EXT);
// 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.0f / width, -2.0f / height, 1.0f);
glTranslatef (-width / 2.0f, -height / 2.0f, 0.0f);
glColor4f (1.0f, 1.0f, 1.0f, 1.0f);
[infoStringTex drawAtPoint:NSMakePoint (10.0f, height - [infoStringTex frameSize].height - 10.0f)];
[camStringTex drawAtPoint:NSMakePoint (10.0f, messageTop)];
messageTop += [camStringTex frameSize].height + 3.0f;
if (fDrawHelp)
[helpStringTex drawAtPoint:NSMakePoint (floor ((width - [helpStringTex frameSize].width) / 2.0f), floor ((height - [helpStringTex frameSize].height) / 3.0f))];
if (fDrawCaps) {
long renderer;
[[self pixelFormat] getValues:&renderer forAttribute:NSOpenGLPFARendererID forVirtualScreen:[[self openGLContext] currentVirtualScreen]];
drawCaps (gDisplayCaps, gNumDisplays, renderer, width);
}
// message string
float currTime = getElapsedTime ();
if ((currTime - msgTime) < gMsgPresistance) {
GLfloat comp = (gMsgPresistance - getElapsedTime () + msgTime) * 0.1; // premultiplied fade
glColor4f (comp, comp, comp, comp);
[msgStringTex drawAtPoint:NSMakePoint (10.0f, messageTop)];
messageTop += [msgStringTex frameSize].height + 3.0f;
}
// global error message
if ((currTime - gErrorTime) < gMsgPresistance) {
GLfloat comp = (gMsgPresistance - getElapsedTime () + gErrorTime) * 0.1; // premultiplied fade
glColor4f (comp, comp, comp, comp);
[gErrStringTex drawAtPoint:NSMakePoint (10.0f, messageTop)];
}
// reset orginal martices
glPopMatrix(); // GL_MODELVIEW
glMatrixMode (GL_PROJECTION);
glPopMatrix();
glMatrixMode (matrixMode);
glDisable (GL_TEXTURE_RECTANGLE_EXT);
glDisable (GL_BLEND);
if (depthTest)
glEnable (GL_DEPTH_TEST);
glReportError ();
}
#pragma mark ---- IB Actions ----
-(IBAction) animate: (id) sender
{
fAnimate = 1 - fAnimate;
if (fAnimate)
[animateMenuItem setState: NSOnState];
else
[animateMenuItem setState: NSOffState];
}
// ---------------------------------
-(IBAction) info: (id) sender
{
fInfo = 1 - fInfo;
if (fInfo)
[infoMenuItem setState: NSOnState];
else
[infoMenuItem setState: NSOffState];
[self setNeedsDisplay: YES];
}
#pragma mark ---- Method Overrides ----
-(void)keyDown:(NSEvent *)theEvent
{
NSString *characters = [theEvent characters];
if ([characters length]) {
unichar character = [characters characterAtIndex:0];
switch (character) {
case 'h':
// toggle help
fDrawHelp = 1 - fDrawHelp;
[self setNeedsDisplay: YES];
break;
case 'c':
// toggle caps
fDrawCaps = 1 - fDrawCaps;
[self setNeedsDisplay: YES];
break;
}
}
}
// ---------------------------------
- (void)mouseDown:(NSEvent *)theEvent // trackball
{
if ([theEvent modifierFlags] & NSControlKeyMask) // send to pan
[self rightMouseDown:theEvent];
else if ([theEvent modifierFlags] & NSAlternateKeyMask) // send to dolly
[self otherMouseDown:theEvent];
else {
NSPoint location = [self convertPoint:[theEvent locationInWindow] fromView:nil];
location.y = camera.viewHeight - location.y;
gDolly = GL_FALSE; // no dolly
gPan = GL_FALSE; // no pan
gTrackball = GL_TRUE;
startTrackball (location.x, location.y, 0, 0, camera.viewWidth, camera.viewHeight);
gTrackingViewInfo = self;
}
}
// ---------------------------------
- (void)rightMouseDown:(NSEvent *)theEvent // pan
{
NSPoint location = [self convertPoint:[theEvent locationInWindow] fromView:nil];
location.y = camera.viewHeight - location.y;
if (gTrackball) { // if we are currently tracking, end trackball
if (gTrackBallRotation[0] != 0.0)
addToRotationTrackball (gTrackBallRotation, worldRotation);
gTrackBallRotation [0] = gTrackBallRotation [1] = gTrackBallRotation [2] = gTrackBallRotation [3] = 0.0f;
}
gDolly = GL_FALSE; // no dolly
gPan = GL_TRUE;
gTrackball = GL_FALSE; // no trackball
gDollyPanStartPoint[0] = location.x;
gDollyPanStartPoint[1] = location.y;
gTrackingViewInfo = self;
}
// ---------------------------------
- (void)otherMouseDown:(NSEvent *)theEvent //dolly
{
NSPoint location = [self convertPoint:[theEvent locationInWindow] fromView:nil];
location.y = camera.viewHeight - location.y;
if (gTrackball) { // if we are currently tracking, end trackball
if (gTrackBallRotation[0] != 0.0)
addToRotationTrackball (gTrackBallRotation, worldRotation);
gTrackBallRotation [0] = gTrackBallRotation [1] = gTrackBallRotation [2] = gTrackBallRotation [3] = 0.0f;
}
gDolly = GL_TRUE;
gPan = GL_FALSE; // no pan
gTrackball = GL_FALSE; // no trackball
gDollyPanStartPoint[0] = location.x;
gDollyPanStartPoint[1] = location.y;
gTrackingViewInfo = self;
}
// ---------------------------------
- (void)mouseUp:(NSEvent *)theEvent
{
if (gDolly) { // end dolly
gDolly = GL_FALSE;
} else if (gPan) { // end pan
gPan = GL_FALSE;
} else if (gTrackball) { // end trackball
gTrackball = GL_FALSE;
if (gTrackBallRotation[0] != 0.0)
addToRotationTrackball (gTrackBallRotation, worldRotation);
gTrackBallRotation [0] = gTrackBallRotation [1] = gTrackBallRotation [2] = gTrackBallRotation [3] = 0.0f;
}
gTrackingViewInfo = NULL;
}
// ---------------------------------
- (void)rightMouseUp:(NSEvent *)theEvent
{
[self mouseUp:theEvent];
}
// ---------------------------------
- (void)otherMouseUp:(NSEvent *)theEvent
{
[self mouseUp:theEvent];
}
// ---------------------------------
- (void)mouseDragged:(NSEvent *)theEvent
{
NSPoint location = [self convertPoint:[theEvent locationInWindow] fromView:nil];
location.y = camera.viewHeight - location.y;
if (gTrackball) {
rollToTrackball (location.x, location.y, gTrackBallRotation);
[self setNeedsDisplay: YES];
} else if (gDolly) {
[self mouseDolly: location];
[self updateProjection]; // update projection matrix (not normally done on draw)
[self setNeedsDisplay: YES];
} else if (gPan) {
[self mousePan: location];
[self setNeedsDisplay: YES];
}
}
// ---------------------------------
- (void)scrollWheel:(NSEvent *)theEvent
{
float wheelDelta = [theEvent deltaX] +[theEvent deltaY] + [theEvent deltaZ];
if (wheelDelta)
{
GLfloat deltaAperture = wheelDelta * -camera.aperture / 200.0f;
camera.aperture += deltaAperture;
if (camera.aperture < 0.1) // do not let aperture <= 0.1
camera.aperture = 0.1;
if (camera.aperture > 179.9) // do not let aperture >= 180
camera.aperture = 179.9;
[self updateProjection]; // update projection matrix
[self setNeedsDisplay: YES];
}
}
// ---------------------------------
- (void)rightMouseDragged:(NSEvent *)theEvent
{
[self mouseDragged: theEvent];
}
// ---------------------------------
- (void)otherMouseDragged:(NSEvent *)theEvent
{
[self mouseDragged: theEvent];
}
// ---------------------------------
- (void) drawRect:(NSRect)rect
{
if (NO == fGLInit)
[self prepareOpenGL];
fGLInit = YES;
// setup viewport and prespective
[self resizeGL]; // forces projection matrix update (does test for size changes)
[self updateModelView]; // update model view matrix for object
// clear our drawable
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// model view and projection matricies already set
drawCube (1.5f); // draw scene
if (fInfo)
[self drawInfo];
if ([self inLiveResize] && !fAnimate)
glFlush ();
else
[[self openGLContext] flushBuffer];
glReportError ();
}
// ---------------------------------
// set initial OpenGL state (current context is set)
// called after context is created
- (void) prepareOpenGL
{
long swapInt = 1;
[[self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; // set to vbl sync
// init GL stuff here
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glPolygonOffset (1.0f, 1.0f);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
[self resetCamera];
shapeSize = 7.0f; // max radius of of objects
// init fonts for use with strings
NSFont * font =[NSFont fontWithName:@"Helvetica" size:12.0];
stanStringAttrib = [[NSMutableDictionary dictionary] retain];
[stanStringAttrib setObject:font forKey:NSFontAttributeName];
[stanStringAttrib setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
[font release];
// ensure strings are created
[self createHelpString];
[self createMessageString];
}
// ---------------------------------
// this can be a troublesome call to do anything heavyweight, as it is called on window moves, resizes, and display config changes. So be
// careful of doing too much here.
- (void) update // window resizes, moves and display changes (resize, depth and display config change)
{
msgTime = getElapsedTime ();
[msgStringTex setString:[NSString stringWithFormat:@"update at %0.1f secs", msgTime] withAttributes:stanStringAttrib];
[super update];
if (![self inLiveResize]) {// if not doing live resize
[self updateInfoString]; // to get change in renderers will rebuld string every time (could test for early out)
getCurrentCaps (); // this call checks to see if the current config changed in a reasonably lightweight way to prevent expensive re-allocations
}
}
// ---------------------------------
-(id) initWithFrame: (NSRect) frameRect
{
NSOpenGLPixelFormat * pf = [BasicOpenGLView basicPixelFormat];
self = [super initWithFrame: frameRect pixelFormat: pf];
return self;
}
// ---------------------------------
- (BOOL)acceptsFirstResponder
{
return YES;
}
// ---------------------------------
- (BOOL)becomeFirstResponder
{
return YES;
}
// ---------------------------------
- (BOOL)resignFirstResponder
{
return YES;
}
// ---------------------------------
- (void) awakeFromNib
{
setStartTime (); // get app start time
getCurrentCaps (); // get current GL capabilites for all displays
// set start values...
rVel[0] = 0.3; rVel[1] = 0.1; rVel[2] = 0.2;
rAccel[0] = 0.003; rAccel[1] = -0.005; rAccel[2] = 0.004;
fInfo = 1;
fAnimate = 1;
time = CFAbsoluteTimeGetCurrent (); // set animation time start time
fDrawHelp = 1;
// start animation timer
timer = [NSTimer timerWithTimeInterval:(1.0f/60.0f) target:self selector:@selector(animationTimer:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSEventTrackingRunLoopMode]; // ensure timer fires during resize
}
@end
</pre>
<!--googleoff: index -->
</td>
</tr>
</table>
<!-- END WIDE COLUMN -->
<!-- END MAIN CONTENT -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><div style="width: 100%; height: 1px; background-color: #919699; margin-top: 5px; margin-bottom: 15px"></div></td>
</tr>
<tr>
<td align="center"><br/>
<table border="0" cellpadding="0" cellspacing="0" class="graybox">
<tr>
<th>Did this document help you?</th>
</tr>
<tr>
<td>
<div style="margin-bottom: 8px"><a href="http://developer.apple.com/feedback/?v=1&url=/samplecode/OpenGL_Screensaver/listing10.html%3Fid%3DDTS10003169-1.0&media=dvd" target=_new>Yes</a>: Tell us what works for you.</div>
<div style="margin-bottom: 8px"><a href="http://developer.apple.com/feedback/?v=2&url=/samplecode/OpenGL_Screensaver/listing10.html%3Fid%3DDTS10003169-1.0&media=dvd" target=_new>It’s good, but:</a> Report typos, inaccuracies, and so forth.</div>
<div><a href="http://developer.apple.com/feedback/?v=3&url=/samplecode/OpenGL_Screensaver/listing10.html%3Fid%3DDTS10003169-1.0&media=dvd" target=_new>It wasn’t helpful</a>: Tell us what would have helped.</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- START BOTTOM APPLE NAVIGATION -->
<!--#include virtual="/includes/footer"-->
<!-- END BOTTOM APPLE NAVIGATION -->
<!-- START CENTER CLOSE -->
</center>
<!-- END CENTER CLOSE -->
</body>
</html>