Add support for the final 'implicit pass'.
[bsnes:xml-shaders.git] / reference / shaderview.py
1 #!/usr/bin/python
2 import sys, time
3 import os
4 import os.path
5 import OpenGL
6 from OpenGL.GL import *
7 from OpenGL.GLUT import *
8 from OpenGL.GL import framebufferobjects
9 import texreader
10 import shaderreader
11
12
13 BASEDIR = os.path.abspath(os.path.dirname(__file__))
14
15
16 def load_textures(texturePath):
17         res = []
18
19         for name in os.listdir(texturePath):
20                 if not name.endswith(".ppm"):
21                         continue
22
23                 fullpath = os.path.join(texturePath, name)
24                 res.append(
25                                 (name, texreader.textureFromFile(fullpath))
26                         )
27
28         return res
29
30
31 def scale_integer(windowW, windowH, inputW, inputH):
32         """
33         Calculates the image as the largest integer multiple of raw frame size.
34         """
35         scaleX = windowW / inputW
36         scaleY = windowH / inputH
37
38         if scaleX > 0 and scaleY > 0:
39                 scale = min(scaleX, scaleY)
40                 finalW = scale * inputW
41                 finalH = scale * inputH
42         else:
43                 if scaleX == 0:
44                         finalW = windowW
45                 else:
46                         finalW = inputW
47
48                 if scaleY == 0:
49                         finalH = windowH
50                 else:
51                         finalH = inputH
52
53         return finalW, finalH
54
55
56 def scale_aspect(windowW, windowH, inputW, inputH):
57         """
58         Calculates the image as the largest multiple of the raw frame size.
59         """
60         scale = min(
61                         float(windowW) / float(inputW),
62                         float(windowH) / float(inputH),
63                 )
64
65         return inputW * scale, inputH * scale
66
67
68 def scale_max(windowW, windowH, inputW, inputH):
69         """
70         Stretch the image to the largest possible size, regardless of aspect.
71         """
72         return windowW, windowH
73
74
75 SCALE_METHODS = [
76                 ("Integer", scale_integer),
77                 ("Aspect-correct", scale_aspect),
78                 ("Maximized", scale_max),
79         ]
80
81
82 class GLUTDemo(object):
83
84         def __init__(self, shaderFile, texturePath):
85                 self.start = time.clock()
86                 self.framecount = 0
87
88                 glutInitDisplayMode(GLUT_RGBA)
89
90                 glutInitWindowSize(640, 480)
91                 self.window = glutCreateWindow("XML Shader Demo - Esc to exit")
92                 self.windowW = None
93                 self.windowH = None
94
95                 glutDisplayFunc(self._draw_scene)
96                 glutIdleFunc(self._handle_idle)
97                 glutReshapeFunc(self._handle_resize)
98                 glutKeyboardFunc(self._handle_key)
99
100                 glClearColor(0.0, 0.0, 0.0, 0.0)
101                 glEnable(GL_TEXTURE_2D)
102
103                 with open(shaderFile, "r") as handle:
104                         self.shaderPasses = shaderreader.parse_shader(handle.read())
105
106                 self.textures = load_textures(texturePath)
107                 textureMenu = glutCreateMenu(self._set_texture)
108                 for index, (filename, _) in enumerate(self.textures):
109                         glutAddMenuEntry(filename, index)
110
111                 self.inputTexture = None
112                 self._set_texture(0)
113
114                 self.framebufferID = framebufferobjects.glGenFramebuffers(1)
115                 self.framebufferTexture1, self.framebufferTexture2 = \
116                                 glGenTextures(2)
117
118                 scaleMenu = glutCreateMenu(self._set_scale_method)
119                 for index, (desc, _) in enumerate(SCALE_METHODS):
120                         glutAddMenuEntry(desc, index)
121
122                 self._set_scale_method(0)
123
124                 self.masterMenu = glutCreateMenu(lambda _: 0)
125                 glutAddSubMenu("Test pattern", textureMenu)
126                 glutAddSubMenu("Scale method", scaleMenu)
127                 glutAttachMenu(GLUT_RIGHT_BUTTON)
128
129         def _set_texture(self, textureIndex):
130
131                 _, self.inputTexture = self.textures[textureIndex]
132
133                 # According to the OpenGL docs, a glutCreateMenu callback doesn't need
134                 # to return anything. PyOpenGL seems to think differently.
135                 return 0
136
137         def _set_scale_method(self, index):
138                 self.scaleMethod = SCALE_METHODS[index][1]
139
140                 # According to the OpenGL docs, a glutCreateMenu callback doesn't need
141                 # to return anything. PyOpenGL seems to think differently.
142                 return 0
143
144         def _setUniform(self, program, name, x, y):
145                 loc = glGetUniformLocation(program, name)
146
147                 if loc < 0:
148                         return
149
150                 glUniform2f(loc, x, y)
151
152         def _draw_texture(self, shaderPass, texture, x, y, width, height):
153                 if shaderPass is not None:
154                         glUseProgram(shaderPass.programID)
155
156                         self._setUniform(shaderPass.programID, 'rubyInputSize',
157                                         texture.width, texture.height)
158                         self._setUniform(shaderPass.programID, 'rubyOutputSize',
159                                         width, height)
160                         self._setUniform(shaderPass.programID, 'rubyTextureSize',
161                                         texture.width, texture.height)
162                         loc = glGetUniformLocation(shaderPass.programID, 'rubyFrameCount')
163                         if loc >= 0:
164                                 glUniform1i(loc, self.framecount)
165
166                         if shaderPass.filterMethod == shaderreader.ATTR_FILTER_LINEAR:
167                                 filterID = GL_LINEAR
168                         else:
169                                 filterID = GL_NEAREST
170
171                 else:
172                         # There's no shader pass to tell us what to do, so go with a safe
173                         # default.
174                         filterID = GL_LINEAR
175
176                 glBindTexture(GL_TEXTURE_2D, texture.textureID)
177
178                 glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filterID)
179                 glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filterID)
180
181                 glClear(GL_COLOR_BUFFER_BIT)
182
183                 glBegin(GL_QUADS)                   # Start drawing a 4 sided polygon
184
185                 glTexCoord2f(0,   0  ); glVertex(x,       y,      )
186                 glTexCoord2f(1.0, 0  ); glVertex(x+width, y,      )
187                 glTexCoord2f(1.0, 1.0); glVertex(x+width, y+height)
188                 glTexCoord2f(0,   1.0); glVertex(x,       y+height)
189
190                 glEnd()                             # We are done with the polygon
191
192                 if shaderPass is not None:
193                         glUseProgram(0)
194
195         def _draw_texture_to_fbo(self, shaderPass, fromTexture, finalW, finalH):
196
197                 # How big should the output of this pass be?
198                 outputW, outputH = shaderPass.calculateFramebufferSize(
199                                 fromTexture.width, fromTexture.height, finalW, finalH,
200                         )
201
202                 # If this pass doesn't specify a size, default to the input.
203                 if outputW is None: outputW = fromTexture.width
204                 if outputH is None: outputH = fromTexture.height
205
206                 # Make a texture exactly that big.
207                 toTexture = texreader.Texture(outputW, outputH)
208
209                 # Configure OpenGL to render to the texture.
210                 framebufferobjects.glBindFramebuffer(
211                                 framebufferobjects.GL_FRAMEBUFFER,
212                                 self.framebufferID,
213                         )
214                 framebufferobjects.glFramebufferTexture2D(
215                                 framebufferobjects.GL_FRAMEBUFFER,
216                                 framebufferobjects.GL_COLOR_ATTACHMENT0,
217                                 GL_TEXTURE_2D,
218                                 toTexture.textureID,
219                                 0,
220                         )
221
222                 # Are we all set?
223                 framebufferobjects.checkFramebufferStatus()
224
225                 glViewport(0, 0, int(outputW), int(outputH))
226                 glMatrixMode(GL_PROJECTION)
227                 glLoadIdentity()
228                 # A framebufferobject will always have the underlying texture's (0,0)
229                 # at the lower-left, so align our coordinate system to match.
230                 glOrtho(0, outputW, 0, outputH, -1, 1)
231
232                 self._draw_texture(shaderPass, fromTexture, 0, 0, outputW, outputH)
233
234                 # Detach all the things we set up.
235                 framebufferobjects.glBindFramebuffer(
236                                 framebufferobjects.GL_FRAMEBUFFER,
237                                 0,
238                         )
239
240                 return toTexture
241
242         def _draw_scene(self):
243                 if None in (self.inputTexture, self.windowW, self.windowH):
244                         return
245
246                 finalW, finalH = self.scaleMethod(
247                                 self.windowW, self.windowH,
248                                 self.inputTexture.width, self.inputTexture.height,
249                         )
250
251                 finalX = (self.windowW - finalW) / 2
252                 finalY = (self.windowH - finalH) / 2
253
254                 # Will we need an implicit pass at the end of this?
255                 requiresImplicitPass = self.shaderPasses[-1].requiresImplicitPass()
256
257                 # Render all but the last pass
258                 fromTexture = self.inputTexture
259                 for shaderPass in self.shaderPasses[:-1]:
260                         fromTexture = self._draw_texture_to_fbo(
261                                         shaderPass, fromTexture, finalW, finalH)
262
263                 # If the last pass expects to be rendered at some specific scale, we'd
264                 # better respect its wishes.
265                 if requiresImplicitPass:
266                         fromTexture = self._draw_texture_to_fbo(
267                                         self.shaderPasses[-1], fromTexture, finalW, finalH)
268                         lastPass = None
269                 else:
270                         lastPass = self.shaderPasses[-1]
271
272                 glViewport(0, 0, self.windowW, self.windowH)
273                 glMatrixMode(GL_PROJECTION)
274                 glLoadIdentity()
275                 # After all the shader passes, the (0,0) corner of the resulting
276                 # texture is supposed to appear at the top-left, so let's set our
277                 # coordinate system appropriately.
278                 glOrtho(0, self.windowW, self.windowH, 0, -1, 1)
279
280                 self._draw_texture(lastPass, fromTexture,
281                                 finalX, finalY, finalW, finalH,
282                         )
283
284                 glFlush()
285
286         def _handle_key(self, key, x, y):
287                 if key == '\x1b': # Escape
288                         self._shutdown()
289
290         def _handle_resize(self, width, height):
291                 self.windowW = max(width, 1)
292                 self.windowH = max(height, 1)
293
294         def _handle_idle(self):
295                 now = time.clock()
296                 if now > self.start + 1:
297                         fps = self.framecount / (now - self.start)
298                         sys.stdout.write("FPS: %0.1f\r" % fps)
299                         sys.stdout.flush()
300                         self.framecount = 0
301                         self.start = now
302
303                 glutPostWindowRedisplay(self.window)
304                 self.framecount += 1
305
306         def _shutdown(self):
307                 # clean up textures we've allocated.
308                 for _, texture in self.textures:
309                         texture.destroy()
310
311                 # There's no clean way to kill GLUT.
312                 sys.exit(0)
313
314 if __name__ == "__main__":
315         argv = glutInit(sys.argv)
316
317         if len(argv) != 2:
318                 print >> sys.stderr, "Usage: %s /path/to/shaderfile" % (argv[0],)
319                 sys.exit(1)
320
321         shaderFile = argv[1]
322         texturePath = os.path.join(BASEDIR, "test-patterns")
323         demo = GLUTDemo(shaderFile, texturePath)
324
325         glutMainLoop()