summaryrefslogtreecommitdiff
path: root/gShaderEdit/previewarea.py
blob: 2880e389de57d05bfd706a7d8da47ee029950107 (plain)
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
# coding=utf-8

'''
previewArea class
Author : Guillaume "iXce" Seguin
Email  : guillaume@segu.in

 # Fragment program preview GTK widget #

Copyright (C) 2007 Guillaume Seguin

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
'''

import gtk.gtkgl
import gobject
import cairo
import array

from OpenGL.GL import *
from OpenGL.GL.ARB.texture_rectangle import *

from gl_program import *
from gl_program_bindings import *

GL_BGRA = 0x80E1

def check_gl_extensions ():
    '''Check the availability required GL extensions'''
    extensions = glGetString (GL_EXTENSIONS).split ()
    if not "GL_ARB_fragment_program" in extensions:
        print _("GL_ARB_fragment_program extension missing, aborting")
        raise SystemExit
    elif not glInitTextureRectangleARB ():
        print _("GL_ARB_texture_rectangle extension missing, aborting")
        raise SystemExit


# create_texture_from_pixels mostly comes from "NeHe6Multi.py" from pygtkglext1
def create_texture_from_pixels (pixels, width, height, format):
    '''Create a GL texture from raw pixels data'''
    id = glGenTextures (1)
    glBindTexture (GL_TEXTURE_RECTANGLE_ARB, id)
    glPixelStorei (GL_UNPACK_ALIGNMENT, 1)
    glTexImage2D (GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA, width, height, 0,
                  format, GL_UNSIGNED_BYTE, pixels)
    glTexParameterf (GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP)
    glTexParameterf (GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP)
    glTexParameterf (GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER,
                     GL_NEAREST)
    glTexParameterf (GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER,
                     GL_NEAREST)
    glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
    return id, width, height

def create_texture_from_file (file):
    '''Create a GL texture from a file'''
    # Load the image from a file as a gdk.Pixbuf
    image = gtk.gdk.pixbuf_new_from_file (file)
    pixels = image.get_pixels ()
    width = image.get_width ()
    height = image.get_height ()

    if image.get_has_alpha ():
        format = GL_RGBA
    else:
        format = GL_RGB

    return create_texture_from_pixels (pixels, width, height, format)

def create_texture_from_surface (surface):
    '''Create a GL texture from a Cairo surface'''
    pixels = surface.get_data ()
    width = surface.get_width ()
    height = surface.get_height ()

    if surface.get_format () == cairo.FORMAT_ARGB32:
        format = GL_RGBA
    else:
        format = GL_RGB

    return create_texture_from_pixels (pixels, width, height, format)

class previewArea (gtk.gtkgl.DrawingArea):
    '''Fragment program preview GTK widget'''

    parent          = None
    file            = None

    tex_width       = 0
    tex_height      = 0
    tex_id          = None
    
    viewport_width  = 400
    viewport_height = 400

    program         = None

    surface         = None

    def __init__ (self, parent = None, file = None, width = 400, height = 400):
        '''Initialize drawing area'''
        try:
            # Double-buffered
            glconfig = gtk.gdkgl.Config (mode = (gtk.gdkgl.MODE_RGBA   |
                                                 gtk.gdkgl.MODE_DOUBLE))
        except gtk.gdkgl.NoMatches:
            # Single-buffered
            glconfig = gtk.gdkgl.Config (mode = (gtk.gdkgl.MODE_RGBA))
        gtk.gtkgl.DrawingArea.__init__ (self, glconfig)
        self.parent = parent
        self.file = file
        self.viewport_width = width
        self.viewport_height = height
        self.set_size_request (width, height)
        self.connect_after ("realize", self.on_realize)
        self.connect ("expose_event", self.on_expose_event)
        self.connect ("configure_event", self.on_configure_event)

    def drawable_begin (self):
        '''Call gl_begin on current GL Drawable'''
        gldrawable = self.get_gl_drawable ()
        glcontext = self.get_gl_context ()
        if not gldrawable.gl_begin (glcontext):
            return False
        else:
            return gldrawable

    def drawable_end (self):
        '''Call gl_end on current GL Drawable'''
        gldrawable = self.get_gl_drawable ()
        return gldrawable.gl_end ()

    def delete_texture (self):
        '''Delete current texture'''
        if self.tex_id:
            self.drawable_begin ()
            glDeleteTextures (self.tex_id)
            self.tex_id = None
            self.drawable_end ()

    def load_texture (self, file = None, surface = None):
        '''Load a texture from a file'''
        self.delete_texture ()
        self.drawable_begin ()
        if file:
            tex = create_texture_from_file (file)
        elif surface:
            tex = create_texture_from_surface (surface)
        else:
            raise RuntimeError, _("File and surface can't both be None")
        self.drawable_end ()
        self.tex_id, self.tex_width, self.tex_height = tex

    def get_tex_coord (self):
        '''Get texture coordinates'''
        alloc = self.get_allocation ()
        width, height = alloc.width, alloc.height
        tex_x = max (0, int (float (width) / 2 - float (self.tex_width) / 2))
        tex_y = max (0, int (float (height) / 2 - float (self.tex_height) / 2))
        return tex_x, tex_y

    def redraw (self, redo = True):
        self.surface = None
        self.queue_draw ()

    def draw (self):
        gldrawable = self.drawable_begin ()
        glClear (GL_COLOR_BUFFER_BIT)
        if self.program and self.program.id.value != 0:
            glEnable (self.program.type)
        glMatrixMode (GL_MODELVIEW)
        glLoadIdentity ()
        glTexEnvfv (GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, (1, 1, 1, 1))
        glColor (1.0, 1.0, 1.0, 1.0)
        glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
        self.draw_texture ()
        if gldrawable.is_double_buffered ():
            gldrawable.swap_buffers ()
        else:
            glFlush ()
        if self.program and self.program.id.value != 0:
            glDisable (self.program.type)
        self.drawable_end ()

    def draw_texture (self):
        '''Draw the texture'''
        glBegin (GL_QUADS)
        hratio = float (self.tex_width) / self.viewport_width
        vratio = float (self.tex_height) / self.viewport_height
        glNormal3f (1.0, 1.0, 1.0)
        # Bottom Left
        glTexCoord2f (0.0, self.tex_height)
        glVertex3f (-hratio, -vratio, 1.0)
        # Bottom Right
        glTexCoord2f (self.tex_width, self.tex_height)
        glVertex3f ( hratio, -vratio, 1.0)
        # Top Right
        glTexCoord2f (self.tex_width, 0.0)
        glVertex3f ( hratio,  vratio, 1.0)
        # Top Left
        glTexCoord2f (0.0, 0.0)
        glVertex3f (-hratio,  vratio, 1.0)
        glEnd ()

    def on_configure_event (self, *args):
        '''Configure event callback, set current GL viewport'''
        self.drawable_begin ()
        glViewport (0, 0, self.viewport_width, self.viewport_height)
        self.drawable_end ()
            
    def on_realize (self, *args):
        '''Initialize GL context'''
        if not self.drawable_begin ():
            return

        check_gl_extensions ()
        glEnable (GL_TEXTURE_RECTANGLE_ARB)

        if self.file:
            self.load_texture (file = self.file)
        
        glClearColor (1.0, 1.0, 1.0, 1.0)
        glShadeModel(GL_SMOOTH)

        light_diffuse = [1.0, 1.0, 1.0, 1.0]
        light_position = [1.0, 1.0, 1.0, 0.0]
        glLightfv (GL_LIGHT0, GL_DIFFUSE, light_diffuse)
        glLightfv (GL_LIGHT0, GL_POSITION, light_position)
        glEnable (GL_LIGHTING)
        glEnable (GL_LIGHT0)

        glMatrixMode (GL_PROJECTION)
        glLoadIdentity ()

        self.drawable_end ()

        self.queue_draw ()

    def on_expose_event (self, widget, event):
        '''Draw using OpenGL or Cairo surface'''
        if not self.surface:
            self.draw ()
            self.dump ()
        cr = self.window.cairo_create ()
        cr.rectangle (event.area.x, event.area.y,
                      event.area.width, event.area.height)
        cr.clip ()
        cr.set_operator (cairo.OPERATOR_SOURCE)
        cr.set_source_rgb (1, 1, 1)
        cr.paint ()
        cr.set_operator (cairo.OPERATOR_OVER)
        tex_x, tex_y = self.get_tex_coord ()
        cr.set_source_surface (self.surface, tex_x, tex_y)
        cr.paint ()

    def dump (self):
        '''Dump current GL context pixels into a cairo surface'''
        self.drawable_begin ()
        glPixelStorei (GL_PACK_ALIGNMENT, 1)
        tex_x, tex_y = self.get_tex_coord ()
        # Dump pixels to a string
        pixels = glReadPixels (tex_x, tex_y, self.tex_width, self.tex_height,
                               GL_BGRA, GL_UNSIGNED_BYTE)
        # Create a python array from pixels data
        data = array.array ("c", pixels)
        s = cairo.ImageSurface.create_for_data (data, cairo.FORMAT_RGB24,
                                                self.tex_width,
                                                self.tex_height,
                                                4 * self.tex_width)
        # Flip surface vertically
        self.surface = cairo.ImageSurface (cairo.FORMAT_ARGB32,
                                           self.tex_width,
                                           self.tex_height)
        cr = cairo.Context (self.surface)
        matrix = cairo.Matrix (yy = -1, y0 = self.tex_height)
        cr.transform (matrix)
        cr.set_source_surface (s)
        cr.paint ()
        self.drawable_end ()

    # Useful user functions
    def create_program (self, source):
        '''Create a fragment program for the given source'''
        if self.program and self.program.source == source:
            return
        self.drawable_begin ()
        self.delete_program (redraw = False)
        self.program = FragmentProgram (self.parent, source)
        self.drawable_end ()
        self.redraw ()

    def delete_program (self, redraw = True):
        '''Clean current program if required'''
        if self.program:
            self.drawable_begin ()
            del self.program
            self.drawable_end ()
            if redraw:
                self.redraw ()