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.

shadowtex.c 29KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. /*
  2. * Shadow demo using the GL_ARB_depth_texture, GL_ARB_shadow and
  3. * GL_ARB_shadow_ambient extensions.
  4. *
  5. * Brian Paul
  6. * 19 Feb 2001
  7. *
  8. * Added GL_EXT_shadow_funcs support on 23 March 2002
  9. * Added GL_EXT_packed_depth_stencil support on 15 March 2006.
  10. * Added GL_EXT_framebuffer_object support on 27 March 2006.
  11. * Removed old SGIX extension support on 5 April 2006.
  12. * Added vertex / fragment program support on 7 June 2007 (Ian Romanick).
  13. *
  14. * Copyright (C) 1999-2006 Brian Paul All Rights Reserved.
  15. *
  16. * Permission is hereby granted, free of charge, to any person obtaining a
  17. * copy of this software and associated documentation files (the "Software"),
  18. * to deal in the Software without restriction, including without limitation
  19. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  20. * and/or sell copies of the Software, and to permit persons to whom the
  21. * Software is furnished to do so, subject to the following conditions:
  22. *
  23. * The above copyright notice and this permission notice shall be included
  24. * in all copies or substantial portions of the Software.
  25. *
  26. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  27. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  28. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  29. * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
  30. * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  31. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. */
  33. #include <assert.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <math.h>
  38. #include <GL/glew.h>
  39. #include <GL/glut.h>
  40. #include "showbuffer.h"
  41. #define DEG_TO_RAD (3.14159 / 180.0)
  42. static GLint WindowWidth = 450, WindowHeight = 300;
  43. static GLfloat Xrot = 15, Yrot = 0, Zrot = 0;
  44. static GLfloat Red[4] = {1, 0, 0, 1};
  45. static GLfloat Green[4] = {0, 1, 0, 1};
  46. static GLfloat Blue[4] = {0, 0, 1, 1};
  47. static GLfloat Yellow[4] = {1, 1, 0, 1};
  48. static GLfloat LightDist = 10;
  49. static GLfloat LightLatitude = 45.0;
  50. static GLfloat LightLongitude = 45.0;
  51. static GLfloat LightPos[4];
  52. static GLfloat SpotDir[3];
  53. static GLfloat SpotAngle = 40.0 * DEG_TO_RAD;
  54. static GLfloat ShadowNear = 4.0, ShadowFar = 24.0;
  55. static GLint ShadowTexWidth = 256, ShadowTexHeight = 256;
  56. static GLboolean LinearFilter = GL_FALSE;
  57. static GLfloat Bias = -0.06;
  58. static GLboolean Anim = GL_TRUE;
  59. static GLboolean NeedNewShadowMap = GL_FALSE;
  60. static GLuint ShadowTexture, GrayTexture;
  61. static GLuint ShadowFBO;
  62. static GLfloat lightModelview[16];
  63. static GLfloat lightProjection[16];
  64. static GLuint vert_prog;
  65. static GLuint frag_progs[3];
  66. static GLuint curr_frag = 0;
  67. static GLuint max_frag = 1;
  68. #define NUM_FRAG_MODES 3
  69. static const char *FragProgNames[] = {
  70. "fixed-function",
  71. "program without \"OPTION ARB_fragment_program_shadow\"",
  72. "program with \"OPTION ARB_fragment_program_shadow\"",
  73. };
  74. static GLboolean HaveShadow = GL_FALSE;
  75. static GLboolean HaveFBO = GL_FALSE;
  76. static GLboolean UseFBO = GL_FALSE;
  77. static GLboolean HaveVP = GL_FALSE;
  78. static GLboolean HaveFP = GL_FALSE;
  79. static GLboolean HaveFP_Shadow = GL_FALSE;
  80. static GLboolean UseVP = GL_FALSE;
  81. static GLboolean HavePackedDepthStencil = GL_FALSE;
  82. static GLboolean UsePackedDepthStencil = GL_FALSE;
  83. static GLboolean HaveEXTshadowFuncs = GL_FALSE;
  84. static GLboolean HaveShadowAmbient = GL_FALSE;
  85. static GLint Operator = 0;
  86. static const GLenum OperatorFunc[8] = {
  87. GL_LEQUAL, GL_LESS, GL_GEQUAL, GL_GREATER,
  88. GL_EQUAL, GL_NOTEQUAL, GL_ALWAYS, GL_NEVER };
  89. static const char *OperatorName[8] = {
  90. "GL_LEQUAL", "GL_LESS", "GL_GEQUAL", "GL_GREATER",
  91. "GL_EQUAL", "GL_NOTEQUAL", "GL_ALWAYS", "GL_NEVER" };
  92. static GLuint DisplayMode;
  93. #define SHOW_SHADOWS 0
  94. #define SHOW_DEPTH_IMAGE 1
  95. #define SHOW_DEPTH_MAPPING 2
  96. #define SHOW_DISTANCE 3
  97. #define MAT4_MUL(dest_vec, src_mat, src_vec) \
  98. "DP4 " dest_vec ".x, " src_mat "[0], " src_vec ";\n" \
  99. "DP4 " dest_vec ".y, " src_mat "[1], " src_vec ";\n" \
  100. "DP4 " dest_vec ".z, " src_mat "[2], " src_vec ";\n" \
  101. "DP4 " dest_vec ".w, " src_mat "[3], " src_vec ";\n"
  102. #define MAT3_MUL(dest_vec, src_mat, src_vec) \
  103. "DP3 " dest_vec ".x, " src_mat "[0], " src_vec ";\n" \
  104. "DP3 " dest_vec ".y, " src_mat "[1], " src_vec ";\n" \
  105. "DP3 " dest_vec ".z, " src_mat "[2], " src_vec ";\n"
  106. #define NORMALIZE(dest, src) \
  107. "DP3 " dest ".w, " src ", " src ";\n" \
  108. "RSQ " dest ".w, " dest ".w;\n" \
  109. "MUL " dest ", " src ", " dest ".w;\n"
  110. /**
  111. * Vertex program for shadow mapping.
  112. */
  113. static const char vert_code[] =
  114. "!!ARBvp1.0\n"
  115. "ATTRIB iPos = vertex.position;\n"
  116. "ATTRIB iNorm = vertex.normal;\n"
  117. "PARAM mvinv[4] = { state.matrix.modelview.invtrans };\n"
  118. "PARAM mvp[4] = { state.matrix.mvp };\n"
  119. "PARAM mv[4] = { state.matrix.modelview };\n"
  120. "PARAM texmat[4] = { state.matrix.texture[0] };\n"
  121. "PARAM lightPos = state.light[0].position;\n"
  122. "PARAM ambientCol = state.lightprod[0].ambient;\n"
  123. "PARAM diffuseCol = state.lightprod[0].diffuse;\n"
  124. "TEMP n, lightVec;\n"
  125. "ALIAS V = lightVec;\n"
  126. "ALIAS NdotL = n;\n"
  127. "OUTPUT oPos = result.position;\n"
  128. "OUTPUT oColor = result.color;\n"
  129. "OUTPUT oTex = result.texcoord[0];\n"
  130. /* Transform the vertex to clip coordinates. */
  131. MAT4_MUL("oPos", "mvp", "iPos")
  132. /* Transform the vertex to eye coordinates. */
  133. MAT4_MUL("V", "mv", "iPos")
  134. /* Transform the vertex to projected light coordinates. */
  135. MAT4_MUL("oTex", "texmat", "iPos")
  136. /* Transform the normal to eye coordinates. */
  137. MAT3_MUL("n", "mvinv", "iNorm")
  138. /* Calculate the vector from the vertex to the light in eye
  139. * coordinates.
  140. */
  141. "SUB lightVec, lightPos, V;\n"
  142. NORMALIZE("lightVec", "lightVec")
  143. /* Compute diffuse lighting coefficient.
  144. */
  145. "DP3 NdotL.x, n, lightVec;\n"
  146. "MAX NdotL.x, NdotL.x, {0.0};\n"
  147. "MIN NdotL.x, NdotL.x, {1.0};\n"
  148. /* Accumulate color contributions.
  149. */
  150. "MOV oColor, diffuseCol;\n"
  151. "MAD oColor.xyz, NdotL.x, diffuseCol, ambientCol;\n"
  152. "END\n"
  153. ;
  154. static const char frag_code[] =
  155. "!!ARBfp1.0\n"
  156. "TEMP shadow, temp;\n"
  157. "TXP shadow, fragment.texcoord[0], texture[0], 2D;\n"
  158. "RCP temp.x, fragment.texcoord[0].w;\n"
  159. "MUL temp.x, temp.x, fragment.texcoord[0].z;\n"
  160. "SGE shadow, shadow.x, temp.x;\n"
  161. "MUL result.color.rgb, fragment.color, shadow.x;\n"
  162. "MOV result.color.a, fragment.color;\n"
  163. "END\n"
  164. ;
  165. static const char frag_shadow_code[] =
  166. "!!ARBfp1.0\n"
  167. "OPTION ARB_fragment_program_shadow;\n"
  168. "TEMP shadow;\n"
  169. "TXP shadow, fragment.texcoord[0], texture[0], SHADOW2D;\n"
  170. "MUL result.color.rgb, fragment.color, shadow.x;\n"
  171. "MOV result.color.a, fragment.color.a;\n"
  172. "END\n"
  173. ;
  174. static void
  175. DrawScene(void)
  176. {
  177. GLfloat k = 6;
  178. /* sphere */
  179. glPushMatrix();
  180. glTranslatef(1.6, 2.2, 2.7);
  181. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Green);
  182. glColor4fv(Green);
  183. glutSolidSphere(1.5, 15, 15);
  184. glPopMatrix();
  185. /* dodecahedron */
  186. glPushMatrix();
  187. glTranslatef(-2.0, 1.2, 2.1);
  188. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Red);
  189. glColor4fv(Red);
  190. glutSolidDodecahedron();
  191. glPopMatrix();
  192. /* icosahedron */
  193. glPushMatrix();
  194. glTranslatef(-0.6, 1.3, -0.5);
  195. glScalef(1.5, 1.5, 1.5);
  196. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Yellow);
  197. glColor4fv(Red);
  198. glutSolidIcosahedron();
  199. glPopMatrix();
  200. /* a plane */
  201. glPushMatrix();
  202. glTranslatef(0, -1.1, 0);
  203. glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, Blue);
  204. glColor4fv(Blue);
  205. glNormal3f(0, 1, 0);
  206. glBegin(GL_POLYGON);
  207. glVertex3f(-k, 0, -k);
  208. glVertex3f( k, 0, -k);
  209. glVertex3f( k, 0, k);
  210. glVertex3f(-k, 0, k);
  211. glEnd();
  212. glPopMatrix();
  213. }
  214. /**
  215. * Calculate modelview and project matrices for the light
  216. *
  217. * Stores the results in \c lightProjection (projection matrix) and
  218. * \c lightModelview (modelview matrix).
  219. */
  220. static void
  221. MakeShadowMatrix(const GLfloat lightPos[4], const GLfloat spotDir[3],
  222. GLfloat spotAngle, GLfloat shadowNear, GLfloat shadowFar)
  223. {
  224. /* compute frustum to enclose spot light cone */
  225. const GLfloat d = shadowNear * tan(spotAngle);
  226. glMatrixMode(GL_PROJECTION);
  227. glPushMatrix();
  228. glLoadIdentity();
  229. glFrustum(-d, d, -d, d, shadowNear, shadowFar);
  230. glGetFloatv(GL_PROJECTION_MATRIX, lightProjection);
  231. glPopMatrix();
  232. glMatrixMode(GL_MODELVIEW);
  233. glPushMatrix();
  234. glLoadIdentity();
  235. gluLookAt(lightPos[0], lightPos[1], lightPos[2],
  236. lightPos[0] + spotDir[0],
  237. lightPos[1] + spotDir[1],
  238. lightPos[2] + spotDir[2],
  239. 0.0, 1.0, 0.0);
  240. glGetFloatv(GL_MODELVIEW_MATRIX, lightModelview);
  241. glPopMatrix();
  242. }
  243. /**
  244. * Load \c GL_TEXTURE matrix with light's MVP matrix.
  245. */
  246. static void SetShadowTextureMatrix(void)
  247. {
  248. static const GLfloat biasMatrix[16] = {
  249. 0.5, 0.0, 0.0, 0.0,
  250. 0.0, 0.5, 0.0, 0.0,
  251. 0.0, 0.0, 0.5, 0.0,
  252. 0.5, 0.5, 0.5, 1.0,
  253. };
  254. glMatrixMode(GL_TEXTURE);
  255. glLoadMatrixf(biasMatrix);
  256. glTranslatef(0.0, 0.0, Bias);
  257. glMultMatrixf(lightProjection);
  258. glMultMatrixf(lightModelview);
  259. glMatrixMode(GL_MODELVIEW);
  260. }
  261. static void
  262. EnableIdentityTexgen(void)
  263. {
  264. /* texgen so that texcoord = vertex coord */
  265. static GLfloat sPlane[4] = { 1, 0, 0, 0 };
  266. static GLfloat tPlane[4] = { 0, 1, 0, 0 };
  267. static GLfloat rPlane[4] = { 0, 0, 1, 0 };
  268. static GLfloat qPlane[4] = { 0, 0, 0, 1 };
  269. glTexGenfv(GL_S, GL_EYE_PLANE, sPlane);
  270. glTexGenfv(GL_T, GL_EYE_PLANE, tPlane);
  271. glTexGenfv(GL_R, GL_EYE_PLANE, rPlane);
  272. glTexGenfv(GL_Q, GL_EYE_PLANE, qPlane);
  273. glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  274. glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  275. glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  276. glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  277. glEnable(GL_TEXTURE_GEN_S);
  278. glEnable(GL_TEXTURE_GEN_T);
  279. glEnable(GL_TEXTURE_GEN_R);
  280. glEnable(GL_TEXTURE_GEN_Q);
  281. }
  282. /*
  283. * Setup 1-D texgen so that the distance from the light source, between
  284. * the near and far planes maps to s=0 and s=1. When we draw the scene,
  285. * the grayness will indicate the fragment's distance from the light
  286. * source.
  287. */
  288. static void
  289. EnableDistanceTexgen(const GLfloat lightPos[4], const GLfloat lightDir[3],
  290. GLfloat lightNear, GLfloat lightFar)
  291. {
  292. GLfloat m, d;
  293. GLfloat sPlane[4];
  294. GLfloat nearPoint[3];
  295. m = sqrt(lightDir[0] * lightDir[0] +
  296. lightDir[1] * lightDir[1] +
  297. lightDir[2] * lightDir[2]);
  298. d = lightFar - lightNear;
  299. /* nearPoint = point on light direction vector which intersects the
  300. * near plane of the light frustum.
  301. */
  302. nearPoint[0] = lightPos[0] + lightDir[0] / m * lightNear;
  303. nearPoint[1] = lightPos[1] + lightDir[1] / m * lightNear;
  304. nearPoint[2] = lightPos[2] + lightDir[2] / m * lightNear;
  305. sPlane[0] = lightDir[0] / d / m;
  306. sPlane[1] = lightDir[1] / d / m;
  307. sPlane[2] = lightDir[2] / d / m;
  308. sPlane[3] = -(sPlane[0] * nearPoint[0]
  309. + sPlane[1] * nearPoint[1]
  310. + sPlane[2] * nearPoint[2]);
  311. glTexGenfv(GL_S, GL_EYE_PLANE, sPlane);
  312. glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
  313. glEnable(GL_TEXTURE_GEN_S);
  314. }
  315. static void
  316. DisableTexgen(void)
  317. {
  318. glDisable(GL_TEXTURE_GEN_S);
  319. glDisable(GL_TEXTURE_GEN_T);
  320. glDisable(GL_TEXTURE_GEN_R);
  321. glDisable(GL_TEXTURE_GEN_Q);
  322. }
  323. static void
  324. ComputeLightPos(GLfloat dist, GLfloat latitude, GLfloat longitude,
  325. GLfloat pos[4], GLfloat dir[3])
  326. {
  327. pos[0] = dist * sin(longitude * DEG_TO_RAD);
  328. pos[1] = dist * sin(latitude * DEG_TO_RAD);
  329. pos[2] = dist * cos(latitude * DEG_TO_RAD) * cos(longitude * DEG_TO_RAD);
  330. pos[3] = 1;
  331. dir[0] = -pos[0];
  332. dir[1] = -pos[1];
  333. dir[2] = -pos[2];
  334. }
  335. /**
  336. * Render the shadow map / depth texture.
  337. * The result will be in the texture object named ShadowTexture.
  338. */
  339. static void
  340. RenderShadowMap(void)
  341. {
  342. GLenum depthFormat; /* GL_DEPTH_COMPONENT or GL_DEPTH_STENCIL_EXT */
  343. GLenum depthType; /* GL_UNSIGNED_INT_24_8_EXT or GL_UNSIGNED_INT */
  344. if (WindowWidth >= 1024 && WindowHeight >= 1024) {
  345. ShadowTexWidth = ShadowTexHeight = 1024;
  346. }
  347. else if (WindowWidth >= 512 && WindowHeight >= 512) {
  348. ShadowTexWidth = ShadowTexHeight = 512;
  349. }
  350. else if (WindowWidth >= 256 && WindowHeight >= 256) {
  351. ShadowTexWidth = ShadowTexHeight = 256;
  352. }
  353. else {
  354. ShadowTexWidth = ShadowTexHeight = 128;
  355. }
  356. printf("Rendering %d x %d depth texture\n", ShadowTexWidth, ShadowTexHeight);
  357. if (UsePackedDepthStencil) {
  358. depthFormat = GL_DEPTH_STENCIL_EXT;
  359. depthType = GL_UNSIGNED_INT_24_8_EXT;
  360. }
  361. else {
  362. depthFormat = GL_DEPTH_COMPONENT;
  363. depthType = GL_UNSIGNED_INT;
  364. }
  365. glMatrixMode(GL_PROJECTION);
  366. glLoadMatrixf(lightProjection);
  367. glMatrixMode(GL_MODELVIEW);
  368. glLoadMatrixf(lightModelview);
  369. if (UseFBO) {
  370. GLenum fbo_status;
  371. glTexImage2D(GL_TEXTURE_2D, 0, depthFormat,
  372. ShadowTexWidth, ShadowTexHeight, 0,
  373. depthFormat, depthType, NULL);
  374. /* Set the filter mode so that the texture is texture-complete.
  375. * Otherwise it will cause the framebuffer to fail the framebuffer
  376. * completeness test.
  377. */
  378. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  379. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ShadowFBO);
  380. glDrawBuffer(GL_NONE);
  381. glReadBuffer(GL_NONE);
  382. fbo_status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
  383. if (fbo_status != GL_FRAMEBUFFER_COMPLETE_EXT) {
  384. fprintf(stderr, "FBO not complete! status = 0x%04x\n", fbo_status);
  385. assert(fbo_status == GL_FRAMEBUFFER_COMPLETE_EXT);
  386. }
  387. }
  388. assert(!glIsEnabled(GL_TEXTURE_1D));
  389. assert(!glIsEnabled(GL_TEXTURE_2D));
  390. glViewport(0, 0, ShadowTexWidth, ShadowTexHeight);
  391. glClear(GL_DEPTH_BUFFER_BIT);
  392. glEnable(GL_DEPTH_TEST);
  393. DrawScene();
  394. if (UseFBO) {
  395. /* all done! */
  396. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  397. }
  398. else {
  399. /*
  400. * copy depth buffer into the texture map
  401. */
  402. if (DisplayMode == SHOW_DEPTH_MAPPING) {
  403. /* load depth image as gray-scale luminance texture */
  404. GLuint *depth = (GLuint *)
  405. malloc(ShadowTexWidth * ShadowTexHeight * sizeof(GLuint));
  406. assert(depth);
  407. glReadPixels(0, 0, ShadowTexWidth, ShadowTexHeight,
  408. depthFormat, depthType, depth);
  409. glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE,
  410. ShadowTexWidth, ShadowTexHeight, 0,
  411. GL_LUMINANCE, GL_UNSIGNED_INT, depth);
  412. free(depth);
  413. }
  414. else {
  415. /* The normal shadow case - a real depth texture */
  416. glCopyTexImage2D(GL_TEXTURE_2D, 0, depthFormat,
  417. 0, 0, ShadowTexWidth, ShadowTexHeight, 0);
  418. if (UsePackedDepthStencil) {
  419. /* debug check */
  420. GLint intFormat;
  421. glGetTexLevelParameteriv(GL_TEXTURE_2D, 0,
  422. GL_TEXTURE_INTERNAL_FORMAT, &intFormat);
  423. assert(intFormat == GL_DEPTH_STENCIL_EXT);
  424. }
  425. }
  426. }
  427. }
  428. /**
  429. * Show the shadow map as a grayscale image.
  430. */
  431. static void
  432. ShowShadowMap(void)
  433. {
  434. glClear(GL_COLOR_BUFFER_BIT);
  435. glMatrixMode(GL_TEXTURE);
  436. glLoadIdentity();
  437. glMatrixMode(GL_PROJECTION);
  438. glLoadIdentity();
  439. glOrtho(0, WindowWidth, 0, WindowHeight, -1, 1);
  440. glMatrixMode(GL_MODELVIEW);
  441. glLoadIdentity();
  442. glDisable(GL_DEPTH_TEST);
  443. glDisable(GL_LIGHTING);
  444. glEnable(GL_TEXTURE_2D);
  445. DisableTexgen();
  446. /* interpret texture's depth values as luminance values */
  447. if (HaveShadow) {
  448. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE);
  449. }
  450. glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
  451. glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  452. glBegin(GL_POLYGON);
  453. glTexCoord2f(0, 0); glVertex2f(0, 0);
  454. glTexCoord2f(1, 0); glVertex2f(ShadowTexWidth, 0);
  455. glTexCoord2f(1, 1); glVertex2f(ShadowTexWidth, ShadowTexHeight);
  456. glTexCoord2f(0, 1); glVertex2f(0, ShadowTexHeight);
  457. glEnd();
  458. glDisable(GL_TEXTURE_2D);
  459. glEnable(GL_DEPTH_TEST);
  460. glEnable(GL_LIGHTING);
  461. }
  462. /**
  463. * Redraw window image
  464. */
  465. static void
  466. Display(void)
  467. {
  468. GLenum error;
  469. ComputeLightPos(LightDist, LightLatitude, LightLongitude,
  470. LightPos, SpotDir);
  471. if (NeedNewShadowMap) {
  472. MakeShadowMatrix(LightPos, SpotDir, SpotAngle, ShadowNear, ShadowFar);
  473. RenderShadowMap();
  474. NeedNewShadowMap = GL_FALSE;
  475. }
  476. glViewport(0, 0, WindowWidth, WindowHeight);
  477. if (DisplayMode == SHOW_DEPTH_IMAGE) {
  478. ShowShadowMap();
  479. }
  480. else {
  481. /* prepare to draw scene from camera's view */
  482. const GLfloat ar = (GLfloat) WindowWidth / (GLfloat) WindowHeight;
  483. glMatrixMode(GL_PROJECTION);
  484. glLoadIdentity();
  485. glFrustum(-ar, ar, -1.0, 1.0, 4.0, 50.0);
  486. glMatrixMode(GL_MODELVIEW);
  487. glLoadIdentity();
  488. glTranslatef(0.0, 0.0, -22.0);
  489. glRotatef(Xrot, 1, 0, 0);
  490. glRotatef(Yrot, 0, 1, 0);
  491. glRotatef(Zrot, 0, 0, 1);
  492. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  493. glLightfv(GL_LIGHT0, GL_POSITION, LightPos);
  494. if (LinearFilter) {
  495. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  496. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  497. }
  498. else {
  499. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  500. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  501. }
  502. if (DisplayMode == SHOW_DEPTH_MAPPING) {
  503. if (HaveShadow) {
  504. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE);
  505. }
  506. glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  507. glEnable(GL_TEXTURE_2D);
  508. SetShadowTextureMatrix();
  509. EnableIdentityTexgen();
  510. }
  511. else if (DisplayMode == SHOW_DISTANCE) {
  512. glMatrixMode(GL_TEXTURE);
  513. glLoadIdentity();
  514. glMatrixMode(GL_MODELVIEW);
  515. EnableDistanceTexgen(LightPos, SpotDir, ShadowNear+Bias, ShadowFar);
  516. glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  517. glEnable(GL_TEXTURE_1D);
  518. assert(!glIsEnabled(GL_TEXTURE_2D));
  519. }
  520. else {
  521. assert(DisplayMode == SHOW_SHADOWS);
  522. if (HaveShadow) {
  523. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB,
  524. GL_COMPARE_R_TO_TEXTURE_ARB);
  525. }
  526. if (curr_frag > 0) {
  527. glEnable(GL_FRAGMENT_PROGRAM_ARB);
  528. }
  529. else {
  530. glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  531. }
  532. glEnable(GL_TEXTURE_2D);
  533. SetShadowTextureMatrix();
  534. if (UseVP) {
  535. glEnable(GL_VERTEX_PROGRAM_ARB);
  536. }
  537. else {
  538. glEnable(GL_LIGHTING);
  539. EnableIdentityTexgen();
  540. }
  541. }
  542. DrawScene();
  543. if (UseVP) {
  544. glDisable(GL_VERTEX_PROGRAM_ARB);
  545. }
  546. else {
  547. DisableTexgen();
  548. glDisable(GL_LIGHTING);
  549. }
  550. if (curr_frag > 0) {
  551. glDisable(GL_FRAGMENT_PROGRAM_ARB);
  552. }
  553. glDisable(GL_TEXTURE_1D);
  554. glDisable(GL_TEXTURE_2D);
  555. }
  556. glutSwapBuffers();
  557. error = glGetError();
  558. if (error) {
  559. printf("GL Error: %s\n", (char *) gluErrorString(error));
  560. }
  561. }
  562. static void
  563. Reshape(int width, int height)
  564. {
  565. WindowWidth = width;
  566. WindowHeight = height;
  567. NeedNewShadowMap = GL_TRUE;
  568. }
  569. static void
  570. Idle(void)
  571. {
  572. static double t0 = -1.;
  573. double dt, t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
  574. if (t0 < 0.0)
  575. t0 = t;
  576. dt = t - t0;
  577. t0 = t;
  578. Yrot += 75.0 * dt;
  579. /*LightLongitude -= 5.0;*/
  580. glutPostRedisplay();
  581. }
  582. static void
  583. Key(unsigned char key, int x, int y)
  584. {
  585. const GLfloat step = 3.0;
  586. (void) x;
  587. (void) y;
  588. switch (key) {
  589. case 'a':
  590. Anim = !Anim;
  591. if (Anim)
  592. glutIdleFunc(Idle);
  593. else
  594. glutIdleFunc(NULL);
  595. break;
  596. case 'b':
  597. Bias -= 0.01;
  598. printf("Bias %g\n", Bias);
  599. break;
  600. case 'B':
  601. Bias += 0.01;
  602. printf("Bias %g\n", Bias);
  603. break;
  604. case 'd':
  605. DisplayMode = SHOW_DISTANCE;
  606. break;
  607. case 'f':
  608. LinearFilter = !LinearFilter;
  609. printf("%s filtering\n", LinearFilter ? "Bilinear" : "Nearest");
  610. break;
  611. case 'i':
  612. DisplayMode = SHOW_DEPTH_IMAGE;
  613. break;
  614. case 'm':
  615. DisplayMode = SHOW_DEPTH_MAPPING;
  616. break;
  617. case 'M':
  618. curr_frag = (1 + curr_frag) % max_frag;
  619. if (!HaveShadow && (curr_frag == 0)) {
  620. curr_frag = 1;
  621. }
  622. printf("Using fragment %s\n", FragProgNames[curr_frag]);
  623. if (HaveFP) {
  624. glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, frag_progs[curr_frag]);
  625. }
  626. break;
  627. case 'n':
  628. case 's':
  629. case ' ':
  630. DisplayMode = SHOW_SHADOWS;
  631. break;
  632. case 'o':
  633. if (HaveEXTshadowFuncs) {
  634. Operator++;
  635. if (Operator >= 8)
  636. Operator = 0;
  637. printf("Operator: %s\n", OperatorName[Operator]);
  638. if (HaveShadow) {
  639. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC_ARB,
  640. OperatorFunc[Operator]);
  641. }
  642. }
  643. break;
  644. case 'p':
  645. UsePackedDepthStencil = !UsePackedDepthStencil;
  646. if (UsePackedDepthStencil && !HavePackedDepthStencil) {
  647. printf("Sorry, GL_EXT_packed_depth_stencil not supported\n");
  648. UsePackedDepthStencil = GL_FALSE;
  649. }
  650. else {
  651. printf("Use GL_DEPTH_STENCIL_EXT: %d\n", UsePackedDepthStencil);
  652. /* Don't really need to regenerate shadow map texture, but do so
  653. * to exercise more code more often.
  654. */
  655. NeedNewShadowMap = GL_TRUE;
  656. }
  657. break;
  658. case 'v':
  659. UseVP = !UseVP && HaveVP;
  660. printf("Using vertex %s mode.\n",
  661. UseVP ? "program" : "fixed-function");
  662. break;
  663. case 'z':
  664. Zrot -= step;
  665. break;
  666. case 'Z':
  667. Zrot += step;
  668. break;
  669. case 27:
  670. exit(0);
  671. break;
  672. }
  673. glutPostRedisplay();
  674. }
  675. static void
  676. SpecialKey(int key, int x, int y)
  677. {
  678. const GLfloat step = 3.0;
  679. const int mod = glutGetModifiers();
  680. (void) x;
  681. (void) y;
  682. switch (key) {
  683. case GLUT_KEY_UP:
  684. if (mod)
  685. LightLatitude += step;
  686. else
  687. Xrot += step;
  688. break;
  689. case GLUT_KEY_DOWN:
  690. if (mod)
  691. LightLatitude -= step;
  692. else
  693. Xrot -= step;
  694. break;
  695. case GLUT_KEY_LEFT:
  696. if (mod)
  697. LightLongitude += step;
  698. else
  699. Yrot += step;
  700. break;
  701. case GLUT_KEY_RIGHT:
  702. if (mod)
  703. LightLongitude -= step;
  704. else
  705. Yrot -= step;
  706. break;
  707. }
  708. if (mod)
  709. NeedNewShadowMap = GL_TRUE;
  710. glutPostRedisplay();
  711. }
  712. /* A helper for finding errors in program strings */
  713. static int FindLine( const char *program, int position )
  714. {
  715. int i, line = 1;
  716. for (i = 0; i < position; i++) {
  717. if (program[i] == '\n')
  718. line++;
  719. }
  720. return line;
  721. }
  722. static GLuint
  723. compile_program(GLenum target, const char *code)
  724. {
  725. GLuint p;
  726. GLint errorPos;
  727. glGenProgramsARB(1, & p);
  728. glBindProgramARB(target, p);
  729. glProgramStringARB(target, GL_PROGRAM_FORMAT_ASCII_ARB,
  730. strlen(code), code);
  731. glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errorPos);
  732. if (glGetError() != GL_NO_ERROR || errorPos != -1) {
  733. int l = FindLine(code, errorPos);
  734. printf("Fragment Program Error (pos=%d line=%d): %s\n", errorPos, l,
  735. (char *) glGetString(GL_PROGRAM_ERROR_STRING_ARB));
  736. exit(0);
  737. }
  738. glBindProgramARB(target, 0);
  739. return p;
  740. }
  741. static void
  742. Init(void)
  743. {
  744. static const GLfloat borderColor[4] = {1.0, 0.0, 0.0, 0.0};
  745. if (!glutExtensionSupported("GL_ARB_depth_texture")) {
  746. printf("Sorry, this demo requires the GL_ARB_depth_texture extension\n");
  747. exit(1);
  748. }
  749. HaveShadow = glutExtensionSupported("GL_ARB_shadow");
  750. HaveVP = glutExtensionSupported("GL_ARB_vertex_program");
  751. HaveFP = glutExtensionSupported("GL_ARB_fragment_program");
  752. HaveFP_Shadow = glutExtensionSupported("GL_ARB_fragment_program_shadow");
  753. if (!HaveShadow && !HaveFP) {
  754. printf("Sorry, this demo requires either the GL_ARB_shadow extension "
  755. "or the GL_ARB_fragment_program extension\n");
  756. exit(1);
  757. }
  758. printf("Using GL_ARB_depth_texture\n");
  759. if (HaveShadow) {
  760. printf("and GL_ARB_shadow\n");
  761. }
  762. if (HaveFP) {
  763. printf("and GL_ARB_fragment_program\n");
  764. }
  765. HaveShadowAmbient = glutExtensionSupported("GL_ARB_shadow_ambient");
  766. if (HaveShadowAmbient) {
  767. printf("and GL_ARB_shadow_ambient\n");
  768. }
  769. HaveEXTshadowFuncs = glutExtensionSupported("GL_EXT_shadow_funcs");
  770. HavePackedDepthStencil = glutExtensionSupported("GL_EXT_packed_depth_stencil");
  771. UsePackedDepthStencil = HavePackedDepthStencil;
  772. #if defined(GL_EXT_framebuffer_object)
  773. HaveFBO = glutExtensionSupported("GL_EXT_framebuffer_object");
  774. UseFBO = HaveFBO;
  775. if (UseFBO) {
  776. printf("Using GL_EXT_framebuffer_object\n");
  777. }
  778. #endif
  779. /*
  780. * Set up the 2D shadow map texture
  781. */
  782. glGenTextures(1, &ShadowTexture);
  783. glBindTexture(GL_TEXTURE_2D, ShadowTexture);
  784. glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
  785. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  786. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  787. if (HaveShadow) {
  788. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB,
  789. GL_COMPARE_R_TO_TEXTURE_ARB);
  790. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL);
  791. }
  792. if (HaveShadowAmbient) {
  793. glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FAIL_VALUE_ARB, 0.3);
  794. }
  795. #if defined(GL_EXT_framebuffer_object)
  796. if (UseFBO) {
  797. glGenFramebuffersEXT(1, &ShadowFBO);
  798. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ShadowFBO);
  799. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
  800. GL_COLOR_ATTACHMENT0_EXT,
  801. GL_RENDERBUFFER_EXT, 0);
  802. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
  803. GL_TEXTURE_2D, ShadowTexture, 0);
  804. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  805. }
  806. #endif
  807. /*
  808. * Setup 1-D grayscale texture image for SHOW_DISTANCE mode
  809. */
  810. glGenTextures(1, &GrayTexture);
  811. glBindTexture(GL_TEXTURE_1D, GrayTexture);
  812. glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  813. glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  814. glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  815. {
  816. GLuint i;
  817. GLubyte image[256];
  818. for (i = 0; i < 256; i++)
  819. image[i] = i;
  820. glTexImage1D(GL_TEXTURE_1D, 0, GL_LUMINANCE,
  821. 256, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, image);
  822. }
  823. if (HaveVP) {
  824. vert_prog = compile_program(GL_VERTEX_PROGRAM_ARB, vert_code);
  825. glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vert_prog);
  826. }
  827. max_frag = 1;
  828. frag_progs[0] = 0;
  829. if (HaveFP) {
  830. frag_progs[1] = compile_program(GL_FRAGMENT_PROGRAM_ARB, frag_code);
  831. max_frag = 2;
  832. }
  833. if (HaveFP && HaveFP_Shadow) {
  834. frag_progs[2] = compile_program(GL_FRAGMENT_PROGRAM_ARB,
  835. frag_shadow_code);
  836. max_frag = 3;
  837. }
  838. if (!HaveShadow) {
  839. curr_frag = 1;
  840. glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, frag_progs[curr_frag]);
  841. }
  842. glEnable(GL_DEPTH_TEST);
  843. glEnable(GL_LIGHTING);
  844. glEnable(GL_LIGHT0);
  845. }
  846. static void
  847. PrintHelp(void)
  848. {
  849. printf("Keys:\n");
  850. printf(" a = toggle animation\n");
  851. printf(" i = show depth texture image\n");
  852. printf(" m = show depth texture mapping\n");
  853. printf(" d = show fragment distance from light source\n");
  854. printf(" n = show normal, shadowed image\n");
  855. printf(" f = toggle nearest/bilinear texture filtering\n");
  856. printf(" b/B = decrease/increase shadow map Z bias\n");
  857. printf(" p = toggle use of packed depth/stencil\n");
  858. printf(" M = cycle through fragment program modes\n");
  859. printf(" v = toggle vertex program modes\n");
  860. printf(" cursor keys = rotate scene\n");
  861. printf(" <shift> + cursor keys = rotate light source\n");
  862. if (HaveEXTshadowFuncs)
  863. printf(" o = cycle through comparison modes\n");
  864. }
  865. int
  866. main(int argc, char *argv[])
  867. {
  868. glutInit(&argc, argv);
  869. glutInitWindowPosition(0, 0);
  870. glutInitWindowSize(WindowWidth, WindowHeight);
  871. glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);
  872. glutCreateWindow(argv[0]);
  873. glewInit();
  874. glutReshapeFunc(Reshape);
  875. glutKeyboardFunc(Key);
  876. glutSpecialFunc(SpecialKey);
  877. glutDisplayFunc(Display);
  878. if (Anim)
  879. glutIdleFunc(Idle);
  880. Init();
  881. PrintHelp();
  882. glutMainLoop();
  883. return 0;
  884. }