Clone of mesa.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dinoshade.c 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. /* Copyright (c) Mark J. Kilgard, 1994, 1997. */
  2. /* This program is freely distributable without licensing fees
  3. and is provided without guarantee or warrantee expressed or
  4. implied. This program is -not- in the public domain. */
  5. /* Example for PC game developers to show how to *combine* texturing,
  6. reflections, and projected shadows all in real-time with OpenGL.
  7. Robust reflections use stenciling. Robust projected shadows
  8. use both stenciling and polygon offset. PC game programmers
  9. should realize that neither stenciling nor polygon offset are
  10. supported by Direct3D, so these real-time rendering algorithms
  11. are only really viable with OpenGL.
  12. The program has modes for disabling the stenciling and polygon
  13. offset uses. It is worth running this example with these features
  14. toggled off so you can see the sort of artifacts that result.
  15. Notice that the floor texturing, reflections, and shadowing
  16. all co-exist properly. */
  17. /* When you run this program: Left mouse button controls the
  18. view. Middle mouse button controls light position (left &
  19. right rotates light around dino; up & down moves light
  20. position up and down). Right mouse button pops up menu. */
  21. /* Check out the comments in the "redraw" routine to see how the
  22. reflection blending and surface stenciling is done. You can
  23. also see in "redraw" how the projected shadows are rendered,
  24. including the use of stenciling and polygon offset. */
  25. /* This program is derived from glutdino.c */
  26. /* Compile: cc -o dinoshade dinoshade.c -lglut -lGLU -lGL -lXmu -lXext -lX11 -lm */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <math.h> /* for cos(), sin(), and sqrt() */
  31. #include <stddef.h> /* for ptrdiff_t, referenced by GL.h when GL_GLEXT_LEGACY defined */
  32. #ifdef _WIN32
  33. #include <windows.h>
  34. #endif
  35. #define GL_GLEXT_LEGACY
  36. #include <GL/glew.h> /* OpenGL Utility Toolkit header */
  37. #include <GL/glut.h> /* OpenGL Utility Toolkit header */
  38. /* Some <math.h> files do not define M_PI... */
  39. #ifndef M_PI
  40. #define M_PI 3.14159265358979323846
  41. #endif
  42. /* Variable controlling various rendering modes. */
  43. static int stencilReflection = 1, stencilShadow = 1, offsetShadow = 1;
  44. static int renderShadow = 1, renderDinosaur = 1, renderReflection = 1;
  45. static int linearFiltering = 0, useMipmaps = 0, useTexture = 1;
  46. static int reportSpeed = 0;
  47. static int animation = 1;
  48. static GLboolean lightSwitch = GL_TRUE;
  49. static int directionalLight = 1;
  50. static int forceExtension = 0;
  51. /* Time varying or user-controled variables. */
  52. static float jump = 0.0;
  53. static float lightAngle = 0.0, lightHeight = 20;
  54. GLfloat angle = -150; /* in degrees */
  55. GLfloat angle2 = 30; /* in degrees */
  56. int moving, startx, starty;
  57. int lightMoving = 0, lightStartX, lightStartY;
  58. enum {
  59. MISSING, EXTENSION, ONE_DOT_ONE
  60. };
  61. int polygonOffsetVersion;
  62. static GLdouble bodyWidth = 3.0;
  63. /* *INDENT-OFF* */
  64. static GLfloat body[][2] = { {0, 3}, {1, 1}, {5, 1}, {8, 4}, {10, 4}, {11, 5},
  65. {11, 11.5}, {13, 12}, {13, 13}, {10, 13.5}, {13, 14}, {13, 15}, {11, 16},
  66. {8, 16}, {7, 15}, {7, 13}, {8, 12}, {7, 11}, {6, 6}, {4, 3}, {3, 2},
  67. {1, 2} };
  68. static GLfloat arm[][2] = { {8, 10}, {9, 9}, {10, 9}, {13, 8}, {14, 9}, {16, 9},
  69. {15, 9.5}, {16, 10}, {15, 10}, {15.5, 11}, {14.5, 10}, {14, 11}, {14, 10},
  70. {13, 9}, {11, 11}, {9, 11} };
  71. static GLfloat leg[][2] = { {8, 6}, {8, 4}, {9, 3}, {9, 2}, {8, 1}, {8, 0.5}, {9, 0},
  72. {12, 0}, {10, 1}, {10, 2}, {12, 4}, {11, 6}, {10, 7}, {9, 7} };
  73. static GLfloat eye[][2] = { {8.75, 15}, {9, 14.7}, {9.6, 14.7}, {10.1, 15},
  74. {9.6, 15.25}, {9, 15.25} };
  75. static GLfloat lightPosition[4];
  76. static GLfloat lightColor[] = {0.8, 1.0, 0.8, 1.0}; /* green-tinted */
  77. static GLfloat skinColor[] = {0.1, 1.0, 0.1, 1.0}, eyeColor[] = {1.0, 0.2, 0.2, 1.0};
  78. /* *INDENT-ON* */
  79. /* Nice floor texture tiling pattern. */
  80. static char *circles[] = {
  81. "....xxxx........",
  82. "..xxxxxxxx......",
  83. ".xxxxxxxxxx.....",
  84. ".xxx....xxx.....",
  85. "xxx......xxx....",
  86. "xxx......xxx....",
  87. "xxx......xxx....",
  88. "xxx......xxx....",
  89. ".xxx....xxx.....",
  90. ".xxxxxxxxxx.....",
  91. "..xxxxxxxx......",
  92. "....xxxx........",
  93. "................",
  94. "................",
  95. "................",
  96. "................",
  97. };
  98. static void
  99. makeFloorTexture(void)
  100. {
  101. GLubyte floorTexture[16][16][3];
  102. GLubyte *loc;
  103. int s, t;
  104. /* Setup RGB image for the texture. */
  105. loc = (GLubyte*) floorTexture;
  106. for (t = 0; t < 16; t++) {
  107. for (s = 0; s < 16; s++) {
  108. if (circles[t][s] == 'x') {
  109. /* Nice green. */
  110. loc[0] = 0x1f;
  111. loc[1] = 0x8f;
  112. loc[2] = 0x1f;
  113. } else {
  114. /* Light gray. */
  115. loc[0] = 0xaa;
  116. loc[1] = 0xaa;
  117. loc[2] = 0xaa;
  118. }
  119. loc += 3;
  120. }
  121. }
  122. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  123. if (useMipmaps) {
  124. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
  125. GL_LINEAR_MIPMAP_LINEAR);
  126. gluBuild2DMipmaps(GL_TEXTURE_2D, 3, 16, 16,
  127. GL_RGB, GL_UNSIGNED_BYTE, floorTexture);
  128. } else {
  129. if (linearFiltering) {
  130. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  131. } else {
  132. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  133. }
  134. glTexImage2D(GL_TEXTURE_2D, 0, 3, 16, 16, 0,
  135. GL_RGB, GL_UNSIGNED_BYTE, floorTexture);
  136. }
  137. }
  138. enum {
  139. X, Y, Z, W
  140. };
  141. enum {
  142. A, B, C, D
  143. };
  144. /* Create a matrix that will project the desired shadow. */
  145. static void
  146. shadowMatrix(GLfloat shadowMat[4][4],
  147. GLfloat groundplane[4],
  148. GLfloat lightpos[4])
  149. {
  150. GLfloat dot;
  151. /* Find dot product between light position vector and ground plane normal. */
  152. dot = groundplane[X] * lightpos[X] +
  153. groundplane[Y] * lightpos[Y] +
  154. groundplane[Z] * lightpos[Z] +
  155. groundplane[W] * lightpos[W];
  156. shadowMat[0][0] = dot - lightpos[X] * groundplane[X];
  157. shadowMat[1][0] = 0.f - lightpos[X] * groundplane[Y];
  158. shadowMat[2][0] = 0.f - lightpos[X] * groundplane[Z];
  159. shadowMat[3][0] = 0.f - lightpos[X] * groundplane[W];
  160. shadowMat[X][1] = 0.f - lightpos[Y] * groundplane[X];
  161. shadowMat[1][1] = dot - lightpos[Y] * groundplane[Y];
  162. shadowMat[2][1] = 0.f - lightpos[Y] * groundplane[Z];
  163. shadowMat[3][1] = 0.f - lightpos[Y] * groundplane[W];
  164. shadowMat[X][2] = 0.f - lightpos[Z] * groundplane[X];
  165. shadowMat[1][2] = 0.f - lightpos[Z] * groundplane[Y];
  166. shadowMat[2][2] = dot - lightpos[Z] * groundplane[Z];
  167. shadowMat[3][2] = 0.f - lightpos[Z] * groundplane[W];
  168. shadowMat[X][3] = 0.f - lightpos[W] * groundplane[X];
  169. shadowMat[1][3] = 0.f - lightpos[W] * groundplane[Y];
  170. shadowMat[2][3] = 0.f - lightpos[W] * groundplane[Z];
  171. shadowMat[3][3] = dot - lightpos[W] * groundplane[W];
  172. }
  173. /* Find the plane equation given 3 points. */
  174. static void
  175. findPlane(GLfloat plane[4],
  176. GLfloat v0[3], GLfloat v1[3], GLfloat v2[3])
  177. {
  178. GLfloat vec0[3], vec1[3];
  179. /* Need 2 vectors to find cross product. */
  180. vec0[X] = v1[X] - v0[X];
  181. vec0[Y] = v1[Y] - v0[Y];
  182. vec0[Z] = v1[Z] - v0[Z];
  183. vec1[X] = v2[X] - v0[X];
  184. vec1[Y] = v2[Y] - v0[Y];
  185. vec1[Z] = v2[Z] - v0[Z];
  186. /* find cross product to get A, B, and C of plane equation */
  187. plane[A] = vec0[Y] * vec1[Z] - vec0[Z] * vec1[Y];
  188. plane[B] = -(vec0[X] * vec1[Z] - vec0[Z] * vec1[X]);
  189. plane[C] = vec0[X] * vec1[Y] - vec0[Y] * vec1[X];
  190. plane[D] = -(plane[A] * v0[X] + plane[B] * v0[Y] + plane[C] * v0[Z]);
  191. }
  192. static void
  193. extrudeSolidFromPolygon(GLfloat data[][2], unsigned int dataSize,
  194. GLdouble thickness, GLuint side, GLuint edge, GLuint whole)
  195. {
  196. static GLUtriangulatorObj *tobj = NULL;
  197. GLdouble vertex[3], dx, dy, len;
  198. int i;
  199. int count = (int) (dataSize / (2 * sizeof(GLfloat)));
  200. if (tobj == NULL) {
  201. tobj = gluNewTess(); /* create and initialize a GLU
  202. polygon tesselation object */
  203. gluTessCallback(tobj, GLU_BEGIN, glBegin);
  204. gluTessCallback(tobj, GLU_VERTEX, glVertex2fv); /* semi-tricky */
  205. gluTessCallback(tobj, GLU_END, glEnd);
  206. }
  207. glNewList(side, GL_COMPILE);
  208. glShadeModel(GL_SMOOTH); /* smooth minimizes seeing
  209. tessellation */
  210. gluBeginPolygon(tobj);
  211. for (i = 0; i < count; i++) {
  212. vertex[0] = data[i][0];
  213. vertex[1] = data[i][1];
  214. vertex[2] = 0;
  215. gluTessVertex(tobj, vertex, data[i]);
  216. }
  217. gluEndPolygon(tobj);
  218. glEndList();
  219. glNewList(edge, GL_COMPILE);
  220. glShadeModel(GL_FLAT); /* flat shade keeps angular hands
  221. from being "smoothed" */
  222. glBegin(GL_QUAD_STRIP);
  223. for (i = 0; i <= count; i++) {
  224. #if 1 /* weird, but seems to be legal */
  225. /* mod function handles closing the edge */
  226. glVertex3f(data[i % count][0], data[i % count][1], 0.0);
  227. glVertex3f(data[i % count][0], data[i % count][1], thickness);
  228. /* Calculate a unit normal by dividing by Euclidean
  229. distance. We * could be lazy and use
  230. glEnable(GL_NORMALIZE) so we could pass in * arbitrary
  231. normals for a very slight performance hit. */
  232. dx = data[(i + 1) % count][1] - data[i % count][1];
  233. dy = data[i % count][0] - data[(i + 1) % count][0];
  234. len = sqrt(dx * dx + dy * dy);
  235. glNormal3f(dx / len, dy / len, 0.0);
  236. #else /* the nice way of doing it */
  237. /* Calculate a unit normal by dividing by Euclidean
  238. distance. We * could be lazy and use
  239. glEnable(GL_NORMALIZE) so we could pass in * arbitrary
  240. normals for a very slight performance hit. */
  241. dx = data[i % count][1] - data[(i - 1 + count) % count][1];
  242. dy = data[(i - 1 + count) % count][0] - data[i % count][0];
  243. len = sqrt(dx * dx + dy * dy);
  244. glNormal3f(dx / len, dy / len, 0.0);
  245. /* mod function handles closing the edge */
  246. glVertex3f(data[i % count][0], data[i % count][1], 0.0);
  247. glVertex3f(data[i % count][0], data[i % count][1], thickness);
  248. #endif
  249. }
  250. glEnd();
  251. glEndList();
  252. glNewList(whole, GL_COMPILE);
  253. glFrontFace(GL_CW);
  254. glCallList(edge);
  255. glNormal3f(0.0, 0.0, -1.0); /* constant normal for side */
  256. glCallList(side);
  257. glPushMatrix();
  258. glTranslatef(0.0, 0.0, thickness);
  259. glFrontFace(GL_CCW);
  260. glNormal3f(0.0, 0.0, 1.0); /* opposite normal for other side */
  261. glCallList(side);
  262. glPopMatrix();
  263. glEndList();
  264. }
  265. /* Enumerants for refering to display lists. */
  266. typedef enum {
  267. RESERVED, BODY_SIDE, BODY_EDGE, BODY_WHOLE, ARM_SIDE, ARM_EDGE, ARM_WHOLE,
  268. LEG_SIDE, LEG_EDGE, LEG_WHOLE, EYE_SIDE, EYE_EDGE, EYE_WHOLE
  269. } displayLists;
  270. static void
  271. makeDinosaur(void)
  272. {
  273. extrudeSolidFromPolygon(body, sizeof(body), bodyWidth,
  274. BODY_SIDE, BODY_EDGE, BODY_WHOLE);
  275. extrudeSolidFromPolygon(arm, sizeof(arm), bodyWidth / 4,
  276. ARM_SIDE, ARM_EDGE, ARM_WHOLE);
  277. extrudeSolidFromPolygon(leg, sizeof(leg), bodyWidth / 2,
  278. LEG_SIDE, LEG_EDGE, LEG_WHOLE);
  279. extrudeSolidFromPolygon(eye, sizeof(eye), bodyWidth + 0.2,
  280. EYE_SIDE, EYE_EDGE, EYE_WHOLE);
  281. }
  282. static void
  283. drawDinosaur(void)
  284. {
  285. glPushMatrix();
  286. /* Translate the dinosaur to be at (0,8,0). */
  287. glTranslatef(-8, 0, -bodyWidth / 2);
  288. glTranslatef(0.0, jump, 0.0);
  289. glMaterialfv(GL_FRONT, GL_DIFFUSE, skinColor);
  290. glCallList(BODY_WHOLE);
  291. glTranslatef(0.0, 0.0, bodyWidth);
  292. glCallList(ARM_WHOLE);
  293. glCallList(LEG_WHOLE);
  294. glTranslatef(0.0, 0.0, -bodyWidth - bodyWidth / 4);
  295. glCallList(ARM_WHOLE);
  296. glTranslatef(0.0, 0.0, -bodyWidth / 4);
  297. glCallList(LEG_WHOLE);
  298. glTranslatef(0.0, 0.0, bodyWidth / 2 - 0.1);
  299. glMaterialfv(GL_FRONT, GL_DIFFUSE, eyeColor);
  300. glCallList(EYE_WHOLE);
  301. glPopMatrix();
  302. }
  303. static GLfloat floorVertices[4][3] = {
  304. { -20.0, 0.0, 20.0 },
  305. { 20.0, 0.0, 20.0 },
  306. { 20.0, 0.0, -20.0 },
  307. { -20.0, 0.0, -20.0 },
  308. };
  309. /* Draw a floor (possibly textured). */
  310. static void
  311. drawFloor(void)
  312. {
  313. glDisable(GL_LIGHTING);
  314. if (useTexture) {
  315. glEnable(GL_TEXTURE_2D);
  316. }
  317. glBegin(GL_QUADS);
  318. glTexCoord2f(0.0, 0.0);
  319. glVertex3fv(floorVertices[0]);
  320. glTexCoord2f(0.0, 16.0);
  321. glVertex3fv(floorVertices[1]);
  322. glTexCoord2f(16.0, 16.0);
  323. glVertex3fv(floorVertices[2]);
  324. glTexCoord2f(16.0, 0.0);
  325. glVertex3fv(floorVertices[3]);
  326. glEnd();
  327. if (useTexture) {
  328. glDisable(GL_TEXTURE_2D);
  329. }
  330. glEnable(GL_LIGHTING);
  331. }
  332. static GLfloat floorPlane[4];
  333. static GLfloat floorShadow[4][4];
  334. static void
  335. redraw(void)
  336. {
  337. int start = 0, end = 0;
  338. if (reportSpeed) {
  339. start = glutGet(GLUT_ELAPSED_TIME);
  340. }
  341. /* Clear; default stencil clears to zero. */
  342. if ((stencilReflection && renderReflection) || (stencilShadow && renderShadow)) {
  343. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  344. } else {
  345. /* Avoid clearing stencil when not using it. */
  346. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  347. }
  348. /* Reposition the light source. */
  349. lightPosition[0] = 12*cos(lightAngle);
  350. lightPosition[1] = lightHeight;
  351. lightPosition[2] = 12*sin(lightAngle);
  352. if (directionalLight) {
  353. lightPosition[3] = 0.0;
  354. } else {
  355. lightPosition[3] = 1.0;
  356. }
  357. shadowMatrix(floorShadow, floorPlane, lightPosition);
  358. glPushMatrix();
  359. /* Perform scene rotations based on user mouse input. */
  360. glRotatef(angle2, 1.0, 0.0, 0.0);
  361. glRotatef(angle, 0.0, 1.0, 0.0);
  362. /* Tell GL new light source position. */
  363. glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
  364. if (renderReflection) {
  365. if (stencilReflection) {
  366. /* We can eliminate the visual "artifact" of seeing the "flipped"
  367. dinosaur underneath the floor by using stencil. The idea is
  368. draw the floor without color or depth update but so that
  369. a stencil value of one is where the floor will be. Later when
  370. rendering the dinosaur reflection, we will only update pixels
  371. with a stencil value of 1 to make sure the reflection only
  372. lives on the floor, not below the floor. */
  373. /* Don't update color or depth. */
  374. glDisable(GL_DEPTH_TEST);
  375. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  376. /* Draw 1 into the stencil buffer. */
  377. glEnable(GL_STENCIL_TEST);
  378. glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
  379. glStencilFunc(GL_ALWAYS, 1, 0xffffffff);
  380. /* Now render floor; floor pixels just get their stencil set to 1. */
  381. drawFloor();
  382. /* Re-enable update of color and depth. */
  383. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  384. glEnable(GL_DEPTH_TEST);
  385. /* Now, only render where stencil is set to 1. */
  386. glStencilFunc(GL_EQUAL, 1, 0xffffffff); /* draw if ==1 */
  387. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  388. }
  389. glPushMatrix();
  390. /* The critical reflection step: Reflect dinosaur through the floor
  391. (the Y=0 plane) to make a relection. */
  392. glScalef(1.0, -1.0, 1.0);
  393. /* Reflect the light position. */
  394. glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
  395. /* To avoid our normals getting reversed and hence botched lighting
  396. on the reflection, turn on normalize. */
  397. glEnable(GL_NORMALIZE);
  398. glCullFace(GL_FRONT);
  399. /* Draw the reflected dinosaur. */
  400. drawDinosaur();
  401. /* Disable noramlize again and re-enable back face culling. */
  402. glDisable(GL_NORMALIZE);
  403. glCullFace(GL_BACK);
  404. glPopMatrix();
  405. /* Switch back to the unreflected light position. */
  406. glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
  407. if (stencilReflection) {
  408. glDisable(GL_STENCIL_TEST);
  409. }
  410. }
  411. /* Back face culling will get used to only draw either the top or the
  412. bottom floor. This let's us get a floor with two distinct
  413. appearances. The top floor surface is reflective and kind of red.
  414. The bottom floor surface is not reflective and blue. */
  415. /* Draw "bottom" of floor in blue. */
  416. glFrontFace(GL_CW); /* Switch face orientation. */
  417. glColor4f(0.1, 0.1, 0.7, 1.0);
  418. drawFloor();
  419. glFrontFace(GL_CCW);
  420. if (renderShadow) {
  421. if (stencilShadow) {
  422. /* Draw the floor with stencil value 3. This helps us only
  423. draw the shadow once per floor pixel (and only on the
  424. floor pixels). */
  425. glEnable(GL_STENCIL_TEST);
  426. glStencilFunc(GL_ALWAYS, 3, 0xffffffff);
  427. glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  428. }
  429. }
  430. /* Draw "top" of floor. Use blending to blend in reflection. */
  431. glEnable(GL_BLEND);
  432. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  433. glColor4f(0.7, 0.0, 0.0, 0.3);
  434. glColor4f(1.0, 1.0, 1.0, 0.3);
  435. drawFloor();
  436. glDisable(GL_BLEND);
  437. if (renderDinosaur) {
  438. /* Draw "actual" dinosaur, not its reflection. */
  439. drawDinosaur();
  440. }
  441. if (renderShadow) {
  442. /* Render the projected shadow. */
  443. if (stencilShadow) {
  444. /* Now, only render where stencil is set above 2 (ie, 3 where
  445. the top floor is). Update stencil with 2 where the shadow
  446. gets drawn so we don't redraw (and accidently reblend) the
  447. shadow). */
  448. glStencilFunc(GL_LESS, 2, 0xffffffff); /* draw if ==1 */
  449. glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
  450. }
  451. /* To eliminate depth buffer artifacts, we use polygon offset
  452. to raise the depth of the projected shadow slightly so
  453. that it does not depth buffer alias with the floor. */
  454. if (offsetShadow) {
  455. switch (polygonOffsetVersion) {
  456. case EXTENSION:
  457. #ifdef GL_EXT_polygon_offset
  458. glEnable(GL_POLYGON_OFFSET_EXT);
  459. break;
  460. #endif
  461. #ifdef GL_VERSION_1_1
  462. case ONE_DOT_ONE:
  463. glEnable(GL_POLYGON_OFFSET_FILL);
  464. break;
  465. #endif
  466. case MISSING:
  467. /* Oh well. */
  468. break;
  469. }
  470. }
  471. /* Render 50% black shadow color on top of whatever the
  472. floor appareance is. */
  473. glEnable(GL_BLEND);
  474. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  475. glDisable(GL_LIGHTING); /* Force the 50% black. */
  476. glColor4f(0.0, 0.0, 0.0, 0.5);
  477. glPushMatrix();
  478. /* Project the shadow. */
  479. glMultMatrixf((GLfloat *) floorShadow);
  480. drawDinosaur();
  481. glPopMatrix();
  482. glDisable(GL_BLEND);
  483. glEnable(GL_LIGHTING);
  484. if (offsetShadow) {
  485. switch (polygonOffsetVersion) {
  486. #ifdef GL_EXT_polygon_offset
  487. case EXTENSION:
  488. glDisable(GL_POLYGON_OFFSET_EXT);
  489. break;
  490. #endif
  491. #ifdef GL_VERSION_1_1
  492. case ONE_DOT_ONE:
  493. glDisable(GL_POLYGON_OFFSET_FILL);
  494. break;
  495. #endif
  496. case MISSING:
  497. /* Oh well. */
  498. break;
  499. }
  500. }
  501. if (stencilShadow) {
  502. glDisable(GL_STENCIL_TEST);
  503. }
  504. }
  505. glPushMatrix();
  506. glDisable(GL_LIGHTING);
  507. glColor3f(1.0, 1.0, 0.0);
  508. if (directionalLight) {
  509. /* Draw an arrowhead. */
  510. glDisable(GL_CULL_FACE);
  511. glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]);
  512. glRotatef(lightAngle * -180.0 / M_PI, 0, 1, 0);
  513. glRotatef(atan(lightHeight/12) * 180.0 / M_PI, 0, 0, 1);
  514. glBegin(GL_TRIANGLE_FAN);
  515. glVertex3f(0, 0, 0);
  516. glVertex3f(2, 1, 1);
  517. glVertex3f(2, -1, 1);
  518. glVertex3f(2, -1, -1);
  519. glVertex3f(2, 1, -1);
  520. glVertex3f(2, 1, 1);
  521. glEnd();
  522. /* Draw a white line from light direction. */
  523. glColor3f(1.0, 1.0, 1.0);
  524. glBegin(GL_LINES);
  525. glVertex3f(0, 0, 0);
  526. glVertex3f(5, 0, 0);
  527. glEnd();
  528. glEnable(GL_CULL_FACE);
  529. } else {
  530. /* Draw a yellow ball at the light source. */
  531. glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]);
  532. glutSolidSphere(1.0, 5, 5);
  533. }
  534. glEnable(GL_LIGHTING);
  535. glPopMatrix();
  536. glPopMatrix();
  537. if (reportSpeed) {
  538. glFinish();
  539. end = glutGet(GLUT_ELAPSED_TIME);
  540. printf("Speed %.3g frames/sec (%d ms)\n", 1000.0/(end-start), end-start);
  541. fflush(stdout);
  542. }
  543. glutSwapBuffers();
  544. }
  545. /* ARGSUSED2 */
  546. static void
  547. mouse(int button, int state, int x, int y)
  548. {
  549. if (button == GLUT_LEFT_BUTTON) {
  550. if (state == GLUT_DOWN) {
  551. moving = 1;
  552. startx = x;
  553. starty = y;
  554. }
  555. if (state == GLUT_UP) {
  556. moving = 0;
  557. }
  558. }
  559. if (button == GLUT_MIDDLE_BUTTON) {
  560. if (state == GLUT_DOWN) {
  561. lightMoving = 1;
  562. lightStartX = x;
  563. lightStartY = y;
  564. }
  565. if (state == GLUT_UP) {
  566. lightMoving = 0;
  567. }
  568. }
  569. }
  570. /* ARGSUSED1 */
  571. static void
  572. motion(int x, int y)
  573. {
  574. if (moving) {
  575. angle = angle + (x - startx);
  576. angle2 = angle2 + (y - starty);
  577. startx = x;
  578. starty = y;
  579. glutPostRedisplay();
  580. }
  581. if (lightMoving) {
  582. lightAngle += (x - lightStartX)/40.0;
  583. lightHeight += (lightStartY - y)/20.0;
  584. lightStartX = x;
  585. lightStartY = y;
  586. glutPostRedisplay();
  587. }
  588. }
  589. /* Advance time varying state when idle callback registered. */
  590. static void
  591. idle(void)
  592. {
  593. static float time = 0.0;
  594. time = glutGet(GLUT_ELAPSED_TIME) / 500.0;
  595. jump = 4.0 * fabs(sin(time)*0.5);
  596. if (!lightMoving) {
  597. lightAngle += 0.03;
  598. }
  599. glutPostRedisplay();
  600. }
  601. enum {
  602. M_NONE, M_MOTION, M_LIGHT, M_TEXTURE, M_SHADOWS, M_REFLECTION, M_DINOSAUR,
  603. M_STENCIL_REFLECTION, M_STENCIL_SHADOW, M_OFFSET_SHADOW,
  604. M_POSITIONAL, M_DIRECTIONAL, M_PERFORMANCE
  605. };
  606. static void
  607. controlLights(int value)
  608. {
  609. switch (value) {
  610. case M_NONE:
  611. return;
  612. case M_MOTION:
  613. animation = 1 - animation;
  614. if (animation) {
  615. glutIdleFunc(idle);
  616. } else {
  617. glutIdleFunc(NULL);
  618. }
  619. break;
  620. case M_LIGHT:
  621. lightSwitch = !lightSwitch;
  622. if (lightSwitch) {
  623. glEnable(GL_LIGHT0);
  624. } else {
  625. glDisable(GL_LIGHT0);
  626. }
  627. break;
  628. case M_TEXTURE:
  629. useTexture = !useTexture;
  630. break;
  631. case M_SHADOWS:
  632. renderShadow = 1 - renderShadow;
  633. break;
  634. case M_REFLECTION:
  635. renderReflection = 1 - renderReflection;
  636. break;
  637. case M_DINOSAUR:
  638. renderDinosaur = 1 - renderDinosaur;
  639. break;
  640. case M_STENCIL_REFLECTION:
  641. stencilReflection = 1 - stencilReflection;
  642. break;
  643. case M_STENCIL_SHADOW:
  644. stencilShadow = 1 - stencilShadow;
  645. break;
  646. case M_OFFSET_SHADOW:
  647. offsetShadow = 1 - offsetShadow;
  648. break;
  649. case M_POSITIONAL:
  650. directionalLight = 0;
  651. break;
  652. case M_DIRECTIONAL:
  653. directionalLight = 1;
  654. break;
  655. case M_PERFORMANCE:
  656. reportSpeed = 1 - reportSpeed;
  657. break;
  658. }
  659. glutPostRedisplay();
  660. }
  661. /* When not visible, stop animating. Restart when visible again. */
  662. static void
  663. visible(int vis)
  664. {
  665. if (vis == GLUT_VISIBLE) {
  666. if (animation)
  667. glutIdleFunc(idle);
  668. } else {
  669. if (!animation)
  670. glutIdleFunc(NULL);
  671. }
  672. }
  673. /* Press any key to redraw; good when motion stopped and
  674. performance reporting on. */
  675. /* ARGSUSED */
  676. static void
  677. key(unsigned char c, int x, int y)
  678. {
  679. if (c == 27) {
  680. exit(0); /* IRIS GLism, Escape quits. */
  681. }
  682. glutPostRedisplay();
  683. }
  684. /* Press any key to redraw; good when motion stopped and
  685. performance reporting on. */
  686. /* ARGSUSED */
  687. static void
  688. special(int k, int x, int y)
  689. {
  690. glutPostRedisplay();
  691. }
  692. static int
  693. supportsOneDotOne(void)
  694. {
  695. const char *version;
  696. int major, minor;
  697. version = (char *) glGetString(GL_VERSION);
  698. if (sscanf(version, "%d.%d", &major, &minor) == 2)
  699. return major * 10 + minor >= 11;
  700. return 0; /* OpenGL version string malformed! */
  701. }
  702. int
  703. main(int argc, char **argv)
  704. {
  705. int i;
  706. glutInit(&argc, argv);
  707. for (i=1; i<argc; i++) {
  708. if (!strcmp("-linear", argv[i])) {
  709. linearFiltering = 1;
  710. } else if (!strcmp("-mipmap", argv[i])) {
  711. useMipmaps = 1;
  712. } else if (!strcmp("-ext", argv[i])) {
  713. forceExtension = 1;
  714. }
  715. }
  716. glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);
  717. #if 0
  718. /* In GLUT 4.0, you'll be able to do this an be sure to
  719. get 2 bits of stencil if the machine has it for you. */
  720. glutInitDisplayString("samples stencil>=2 rgb double depth");
  721. #endif
  722. glutCreateWindow("Shadowy Leapin' Lizards");
  723. glewInit();
  724. if (glutGet(GLUT_WINDOW_STENCIL_SIZE) <= 1) {
  725. printf("dinoshade: Sorry, I need at least 2 bits of stencil.\n");
  726. exit(1);
  727. }
  728. /* Register GLUT callbacks. */
  729. glutDisplayFunc(redraw);
  730. glutMouseFunc(mouse);
  731. glutMotionFunc(motion);
  732. glutVisibilityFunc(visible);
  733. glutKeyboardFunc(key);
  734. glutSpecialFunc(special);
  735. glutCreateMenu(controlLights);
  736. glutAddMenuEntry("Toggle motion", M_MOTION);
  737. glutAddMenuEntry("-----------------------", M_NONE);
  738. glutAddMenuEntry("Toggle light", M_LIGHT);
  739. glutAddMenuEntry("Toggle texture", M_TEXTURE);
  740. glutAddMenuEntry("Toggle shadows", M_SHADOWS);
  741. glutAddMenuEntry("Toggle reflection", M_REFLECTION);
  742. glutAddMenuEntry("Toggle dinosaur", M_DINOSAUR);
  743. glutAddMenuEntry("-----------------------", M_NONE);
  744. glutAddMenuEntry("Toggle reflection stenciling", M_STENCIL_REFLECTION);
  745. glutAddMenuEntry("Toggle shadow stenciling", M_STENCIL_SHADOW);
  746. glutAddMenuEntry("Toggle shadow offset", M_OFFSET_SHADOW);
  747. glutAddMenuEntry("----------------------", M_NONE);
  748. glutAddMenuEntry("Positional light", M_POSITIONAL);
  749. glutAddMenuEntry("Directional light", M_DIRECTIONAL);
  750. glutAddMenuEntry("-----------------------", M_NONE);
  751. glutAddMenuEntry("Toggle performance", M_PERFORMANCE);
  752. glutAttachMenu(GLUT_RIGHT_BUTTON);
  753. makeDinosaur();
  754. #ifdef GL_VERSION_1_1
  755. if (supportsOneDotOne() && !forceExtension) {
  756. polygonOffsetVersion = ONE_DOT_ONE;
  757. glPolygonOffset(-2.0, -9.0);
  758. } else
  759. #endif
  760. {
  761. #ifdef GL_EXT_polygon_offset
  762. /* check for the polygon offset extension */
  763. if (glutExtensionSupported("GL_EXT_polygon_offset")) {
  764. polygonOffsetVersion = EXTENSION;
  765. glPolygonOffsetEXT(-2.0, -0.002);
  766. } else
  767. #endif
  768. {
  769. polygonOffsetVersion = MISSING;
  770. printf("\ndinoshine: Missing polygon offset.\n");
  771. printf(" Expect shadow depth aliasing artifacts.\n\n");
  772. fflush(stdout);
  773. }
  774. }
  775. glEnable(GL_CULL_FACE);
  776. glEnable(GL_DEPTH_TEST);
  777. glEnable(GL_TEXTURE_2D);
  778. glLineWidth(3.0);
  779. glMatrixMode(GL_PROJECTION);
  780. gluPerspective( /* field of view in degree */ 40.0,
  781. /* aspect ratio */ 1.0,
  782. /* Z near */ 20.0, /* Z far */ 100.0);
  783. glMatrixMode(GL_MODELVIEW);
  784. gluLookAt(0.0, 8.0, 60.0, /* eye is at (0,8,60) */
  785. 0.0, 8.0, 0.0, /* center is at (0,8,0) */
  786. 0.0, 1.0, 0.); /* up is in postivie Y direction */
  787. glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  788. glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor);
  789. glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1);
  790. glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05);
  791. glEnable(GL_LIGHT0);
  792. glEnable(GL_LIGHTING);
  793. makeFloorTexture();
  794. /* Setup floor plane for projected shadow calculations. */
  795. findPlane(floorPlane, floorVertices[1], floorVertices[2], floorVertices[3]);
  796. glutMainLoop();
  797. return 0; /* ANSI C requires main to return int. */
  798. }