PageRenderTime 27ms CodeModel.GetById 14ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/cookbook/openglapp.pl

http://github.com/PerlGameDev/SDL
Perl | 115 lines | 95 code | 20 blank | 0 comment | 14 complexity | 80d02e2538b383ba615041cd35b2a138 MD5 | raw file
  1use strict;
  2use warnings;
  3use SDL;
  4use SDLx::App;
  5use SDL::Mouse;
  6use SDL::Video;
  7use SDL::Events;
  8use SDL::Event;
  9use OpenGL qw(:all);
 10
 11my ( $SDLAPP, $WIDTH, $HEIGHT, $SDLEVENT );
 12
 13$|      = 1;
 14$WIDTH  = 1024;
 15$HEIGHT = 768;
 16$SDLAPP = SDLx::App->new(
 17	title  => "Opengl App",
 18	width  => $WIDTH,
 19	height => $HEIGHT,
 20	gl     => 1
 21);
 22$SDLEVENT = SDL::Event->new;
 23
 24glEnable(GL_DEPTH_TEST);
 25glMatrixMode(GL_PROJECTION);
 26glLoadIdentity;
 27gluPerspective( 60, $WIDTH / $HEIGHT, 1, 1000 );
 28glTranslatef( 0, 0, -20 );
 29
 30while (1) {
 31	&handlepolls;
 32	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
 33	glRotatef( .1, 1, 1, 1 );
 34	&drawscene;
 35	$SDLAPP->sync;
 36}
 37
 38sub drawscene {
 39	my ( $color, $x, $y, $z );
 40
 41	for ( -2 .. 2 ) {
 42		glPushMatrix;
 43		glTranslatef( $_ * 3, 0, 0 );
 44		glColor3d( 1, 0, 0 );
 45		&draw_cube;
 46		glPopMatrix;
 47	}
 48
 49	return "";
 50}
 51
 52sub draw_cube {
 53	my ( @indices, @vertices, $face, $vertex, $index, $coords );
 54
 55	@indices = qw(4 5 6 7   1 2 6 5   0 1 5 4
 56		0 3 2 1   0 4 7 3   2 3 7 6);
 57	@vertices = (
 58		[ -1, -1, -1 ],
 59		[ 1,  -1, -1 ],
 60		[ 1,  1,  -1 ],
 61		[ -1, 1,  -1 ],
 62		[ -1, -1, 1 ],
 63		[ 1,  -1, 1 ],
 64		[ 1,  1,  1 ],
 65		[ -1, 1,  1 ]
 66	);
 67
 68	glBegin(GL_QUADS);
 69
 70	foreach my $face ( 0 .. 5 ) {
 71		foreach my $vertex ( 0 .. 3 ) {
 72			$index  = $indices[ 4 * $face + $vertex ];
 73			$coords = $vertices[$index];
 74
 75			glVertex3d(@$coords);
 76		}
 77	}
 78
 79	glEnd;
 80
 81	return "";
 82}
 83
 84sub handlepolls {
 85	my ( $type, $key );
 86
 87	SDL::Events::pump_events();
 88
 89	while ( SDL::Events::poll_event($SDLEVENT) ) {
 90		$type = $SDLEVENT->type();
 91		$key = ( $type == 2 or $type == 3 ) ? $SDLEVENT->key_sym : "";
 92
 93		if ( $type == 4 ) {
 94			printf(
 95				"You moved the mouse! x=%s y=%s xrel=%s yrel=%s\n",
 96				$SDLEVENT->motion_x,    $SDLEVENT->motion_y,
 97				$SDLEVENT->motion_xrel, $SDLEVENT->motion_yrel
 98			);
 99		} elsif ( $type == 2 ) {
100			print "You are pressing $key\n";
101		} elsif ( $type == 3 ) {
102			print "You released $key\n";
103		} elsif ( $type == 12 ) {
104			exit;
105		} else {
106			print "TYPE $type UNKNOWN!\n";
107		}
108
109		if ( $type == 2 ) {
110			if ( $key eq "q" or $key eq "escape" ) {exit}
111		}
112	}
113
114	return "";
115}