OSDN Git Service

remove blender25
[meshio/pymeshio.git] / examples / opengl / texture.py
1 #!/usr/bin/python
2 # coding: utf-8
3
4 from PIL import Image
5 from OpenGL.GL import *
6
7
8 class Texture(object):
9
10     def __init__(self, path):
11         self.path=path
12         self.image=None
13         self.id=0
14         self.isInitialized=False
15
16     def onInitialize(self):
17         self.isInitialized=False
18
19     def createTexture(self):
20         self.id=glGenTextures(1)
21         if self.id==0:
22             print("fail to glGenTextures")
23             return False
24         print("createTexture: %d" % self.id)
25
26         channels=len(self.image.getbands())
27         w, h=self.image.size
28         glBindTexture(GL_TEXTURE_2D, self.id)
29         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
30         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
31         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
32         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
33         if channels==4:
34             print("RGBA")
35             glPixelStorei(GL_UNPACK_ALIGNMENT, 4)
36             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 
37                     0, GL_RGBA, GL_UNSIGNED_BYTE, self.image.tostring())
38         elif channels==3:
39             print("RGB")
40             glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
41             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 
42                     0, GL_RGB, GL_UNSIGNED_BYTE, self.image.tostring())
43
44     def begin(self):
45         if not self.isInitialized:
46             try:
47                 # load image
48                 if not self.image:
49                     self.image=Image.open(self.path)
50                     if self.image:
51                         print("load image:", self.path)
52                     else:
53                         print("failt to load image:", self.path)
54                         return
55                 # createTexture
56                 if self.image:
57                     self.createTexture()
58             except Exception as e:
59                 print(e)
60                 return
61             finally:
62                 self.isInitialized=True
63         if self.id!=0:
64             glEnable(GL_TEXTURE_2D)
65             glBindTexture(GL_TEXTURE_2D, self.id)
66
67     def end(self):
68         glDisable(GL_TEXTURE_2D)
69