Ejemplo n.º 1
0
def initData(filepath=None, texpath=None):
    global objs

    if not filepath:
        filepath=Path("files/sphere.obj")
    if not texpath:
        texpath=Path("texture/earth")

    
    obj_data = io.read_obj(filepath)
    sphere = io.read_obj("files/sphere.obj")
    # cube_data = io.read_obj("files/cube.obj")

    obj = Object(obj_data, [1.0, 1.0, 1.0])
    light = Object(sphere, [1.0, 1.0, 1.0])
    sky = Object(sphere, [0.8, 0.8, 0.8])

    if Path(texpath).is_dir():
        obj_tex = Cubemap()
    else:
        obj_tex = Texture()

    obj_tex.load(Path(texpath))
    
    stars = Texture()
    stars.load("texture/milky_way.jpg")

    moon = Texture()
    moon.load("texture/moon.jpg")


    # for key in earth.faces:
        # print(f'{key}: {earth.faces[key].filename}')

    sky.create(stars)
    obj.create(obj_tex)
    # obj.create()

    light.create(moon)

    objs = [obj, light, sky]
    # objs = [obj, light]


    # Place objects in center
    light.translate(-light.x, -light.y, -light.z)
    obj.translate(-obj.x, -obj.y, -obj.z)
    sky.translate(-sky.x, -sky.y, -sky.z-1)
    
    light.scale(0.1, 0.1, 0.1)
    sky.scale(10,10,10)
    
    sky.rotate('y', 145)

    
    gl.glEnable(gl.GL_DEPTH_TEST)
    gl.glDepthFunc(gl.GL_LESS)

    # Unbind Vertex Array Object.
    gl.glBindVertexArray(0)
Ejemplo n.º 2
0
    def __init__(self, main, ScreenManager, tileSizeX, tileSizeY, map="base"):
        self.main = main
        self.screenManager = ScreenManager
        self.display_surf = ScreenManager.display_surf
        self.middle = ScreenManager.size[0]/2
        self.tileSizeX = tileSizeX  # H
        self.tileSizeY = tileSizeY  # W

        self.IsoMathHelper = None
        self._IsoMathHelperInit()

        self.MapPos = self.MapPosX, self.MapPosY = 0, 0
        self.MapMovConst = 10
        self.RegisterMapMovement()

        self.RecalculateDisplayTiles = True 
        self.RDT_X_S = None
        self.RDT_X_E = None
        self.RDT_Y_S = None
        self.RDT_Y_E = None

        self.Map = Map(map)
        self.Map.loadMap()
        print(self.Map.sizeX)
        self.MapJSON = MapJSON(map)
        self.MapJSON.loadMap()
        print(self.MapJSON.sizeX)
        self.tiles = []
        self.loadTextures()
        self.screenManager.setBackgrounColor(self.screenManager.colors["Black"], 1.0)
        self.MouseSelectedTexture = Texture("resources/graphics/map/select_tile.png")
        self.test = Texture("resources/graphics/map/holzblock.png")
        self.MouseActive = True 
        self.InGameMenuActive = False
        self.button = Button(self.main,
                                        self.display_surf,
                                        self.screenManager.colors["Gray"],
                                        self.screenManager.colors["Blue"],
                                        self.screenManager.colors["Yellow"],
                                        self.screenManager.colors["White"],
                                        self.middle-200,
                                        (self.screenManager.size[1]/10)*2+140,
                                        400, 80,
                                        "Create Level", 60,
                                        self.place)

        self.main.EventHandler.registerKEYDOWNevent(K_ESCAPE, self.KEYDOWNesc)
        self.main.EventHandler.registerMOUSEBUTTONDOWNevent(1, self.place)
        self.button.draw()
Ejemplo n.º 3
0
 def __init__(self, texture_filename, position_x, position_y, width,
              height):
     self.texture = Texture(texture_filename)
     self.x = position_x
     self.y = position_y
     self.size['width'] = width
     self.size['height'] = height
Ejemplo n.º 4
0
    def _genTextures(self):
        self.BordSurf = pygame.Surface(self.size)
        self.HoverSurf = pygame.Surface(self.size)

        pygame.draw.rect(self.BordSurf, self.bord_color, self.Rect,
                         self.border)
        pygame.draw.rect(self.BordSurf, self.in_color, self.InRect, 0)
        self.BordSurf.blit(self.textSurf, self.textRect)

        pygame.draw.rect(self.HoverSurf, self.hover_color, self.Rect,
                         self.border)
        pygame.draw.rect(self.HoverSurf, self.in_color, self.InRect, 0)
        self.HoverSurf.blit(self.textSurf, self.textRect)

        self.HoverTexture = Texture(None, self.HoverSurf, self.Rect)
        self.BoardTexture = Texture(None, self.BordSurf, self.Rect)
Ejemplo n.º 5
0
    def generateTextureInfo(self):

        # Figure out texture size
        self.mTextureWidth, self.mTextureHeight = self.getTextureDimension(self.mTotalIndices)

        # Initialize an array of target textures based upon the chosen settings
        self.mTextures = [Texture(self.mTextureWidth, self.mTextureHeight, self.mView, view) for view in self.mView.getTextureViews()]
Ejemplo n.º 6
0
 def __init__(self):
     self.texture = Texture('resources/piste2.png')
     self.tracklist = {}
     self.trackelt = [{
         'type': 'straight',
         'L': 5.4
     }, {
         'type': 'turn',
         'L': 0.7,
         'sweep': math.radians(135)
     }, {
         'type': 'straight',
         'L': 2
     }, {
         'type': 'turn',
         'L': 0.5,
         'sweep': math.radians(78.65)
     }, {
         'type': 'turn',
         'L': 4.5,
         'sweep': -math.radians(90)
     }, {
         'type': 'turn',
         'L': 0.8,
         'sweep': math.radians(146.35)
     }, {
         'type': 'straight',
         'L': 1.7
     }, {
         'type': 'turn',
         'L': 1.4,
         'sweep': math.radians(90)
     }]
Ejemplo n.º 7
0
  def __init__(self, context, ImgData):
    self.ImgData = None
    self.texture = None
    self.context = context
    self.cache = None
    self.transform = SvgTransform()
    self.filename = ImgData
    self.triangVtx = np.zeros((4,2), dtype=float32)
    self.textriangVtx = np.zeros((4,2), dtype=float32)

    # Detect the type of data passed in
    if type(ImgData) == file:
      self.ImgData = ImgData.read()
    elif type(ImgData) == str:
      self.texture = Texture(ImgData)
#      bitmapFile = ImgData.replace(".svg", ".png")
#      # Load PNG files directly
#      if ImgData.endswith(".png"):
#        self.texture = Texture(ImgData)
#      elif ImgData.endswith(".jpg"):
#        self.texture = Texture(ImgData)
#      elif ImgData.endswith(".jpeg"):
#        self.texture = Texture(ImgData)
      # Check whether we have a prerendered bitmap version of the SVG file
#      elif ImgData.endswith(".svg") and os.path.exists(bitmapFile):
#        Log.debug("Loading cached bitmap '%s' instead of '%s'." % (bitmapFile, ImgData))
#        self.texture = Texture(bitmapFile)
#      else:
#        if not haveAmanith:
#          e = "PyAmanith support is deprecated and you are trying to load an SVG file."
#          Log.error(e)
#          raise RuntimeError(e)
#        Log.debug("Loading SVG file '%s'." % (ImgData))
#        self.ImgData = open(ImgData).read()
    elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in
      self.texture = Texture()
      self.texture.loadImage(ImgData)

    # Make sure we have a valid texture
    if not self.texture:
      if type(ImgData) == str:
        e = "Unable to load texture for %s." % ImgData
      else:
        e = "Unable to load texture for SVG file."
      Log.error(e)
      raise RuntimeError(e)
Ejemplo n.º 8
0
 def __init__(self, texture_filename, position_x, position_y, width, height,
              visible, speed):
     self.texture = Texture(texture_filename)
     self.x = position_x
     self.y = position_y
     self.size['width'] = width
     self.size['height'] = height
     self.visible = visible
     self.speed = speed
Ejemplo n.º 9
0
    def loadTextureFile(self):
        if not self.textureFile: return
        f = open(self.textureFile, 'r')
        self.textures = []

        for line in f:
            l = line.strip()
            if not l: continue
            self.textures.append(Texture(l))
Ejemplo n.º 10
0
    def AddTexture(self, Display, ID, Filename):
        if ID == "":
            return

        NewTexture = Texture()
        if not NewTexture.Load(Display, Filename):
            Log("Unable to Load Texture:", ID)
            return

        self.TexList[ID] = NewTexture
Ejemplo n.º 11
0
    def __init__(self, file_name):
        global active_camera
        self.models = None
        self.cameras = None
        self.lights = None
        self.active_camera = active_camera

        # shared resources
        self.textures = {}  # name -> tex lookup
        self.shaders = {}  # name -> tex lookup
        self.meshes = {}  # name -> tex lookup

        with open(file_name, "r") as fp:
            data = json.load(fp)

        # models
        self.models = {name: Model(m) for (name, m) in data["models"].items()}
        for model in self.models.values():
            vert_file = model.io['shader']['vert']
            frag_file = model.io['shader']['frag']
            shader_name = vert_file.split('.')[0]
            shader = ResourceManager.get_shader(shader_name)
            if not shader:
                shader = Shader(vert_file, frag_file)
                ResourceManager.add_shader(shader_name, shader)
            model.shader = shader

            mesh_name = model.io['mesh']  # contains relative path string
            mesh = ResourceManager.get_mesh(mesh_name)
            if not mesh:
                mesh = Mesh(mesh_name)
                ResourceManager.add_mesh(mesh_name, mesh)
            model.mesh = mesh

            tex_files = model.io['textures']
            for (layer, tex_file) in tex_files.items():
                tex = ResourceManager.get_texture(tex_file)
                if not tex:
                    tex = Texture(tex_file)
                    ResourceManager.add_texture(tex_file, tex)
                model.textures[layer] = tex

        # cameras, set first camera to active
        self.cameras = {
            name: Camera(c)
            for (name, c) in data["cameras"].items()
        }
        if len(self.cameras) > 0:
            # get first items value
            active_camera = next(iter(self.cameras.items()))[1]
        logging.warn('camera needs to set shader uniforms')

        # lights
        self.lights = {name: Light(l) for (name, l) in data["lights"].items()}
        logging.warn('light needs to set shader uniforms')
Ejemplo n.º 12
0
 def loadItemLabel(self, i):
   # Load the item label if it isn't yet loaded
   item = self.items[i]
   if self.itemLabels[i] is None:
     if isinstance(item, Song.SongInfo):
       label = self.engine.resource.fileName(self.library, item.songName,    "label.png")
     else:
       assert isinstance(item, Song.LibraryInfo)
       label = self.engine.resource.fileName(item.libraryName, "label.png")
     if os.path.exists(label):
       self.itemLabels[i] = Texture(label)
Ejemplo n.º 13
0
    def __init__(self, context, ImgData):
        self.ImgData = None
        self.texture = None
        self.context = context
        self.cache = None
        self.filename = ImgData

        # Detect the type of data passed in
        if isinstance(ImgData, file):
            self.ImgData = ImgData.read()
        elif isinstance(ImgData, basestring):
            self.texture = Texture(ImgData)
        elif isinstance(ImgData,
                        Image.Image):  #stump: let a PIL image be passed in
            self.texture = Texture()
            self.texture.loadImage(ImgData)

        # Make sure we have a valid texture
        if not self.texture:
            if isinstance(ImgData, basestring):
                e = "Unable to load texture for %s." % ImgData
            else:
                e = "Unable to load texture for SVG file."
            Log.error(e)
            raise RuntimeError(e)

        self.pixelSize = self.texture.pixelSize  #the size of the image in pixels (from texture)
        self.position = [0.0, 0.0]  #position of the image in the viewport
        self.scale = [1.0, 1.0]  #percentage scaling
        self.angle = 0  #angle of rotation (degrees)
        self.color = (1.0, 1.0, 1.0, 1.0)  #glColor rgba
        self.rect = (0, 1, 0, 1)  #texture mapping coordinates
        self.shift = -.5  #horizontal alignment
        self.vshift = -.5  #vertical alignment

        self.path = self.texture.name  #path of the image file

        self.texArray = np.zeros((4, 2), dtype=np.float32)

        self.createTex()
Ejemplo n.º 14
0
def tracker(i):
    boxes = Boxes(len(files))
    tex = Texture()
    ims = Slicer()
    th = Threshold()
    hog = Hog()
    cells = Cells(sizeh, sizew)

    names = list(listdir(path))
    names = names[i:i + batch_size]

    net = Network()
    net.load('data/net/dataset_184_nets_ann/', 'compile_config.txt',
             hog_block_size, hog_cell_size, hog_orientations)

    index = 0

    while (len(names) > 0):

        index = len(names) - 1
        name = names.pop()

        img = cv2.imread(path + name)
        img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        images, coords = ims.split(img_grey, sizeh, sizew, sizeh, sizew)
        signal = tex.analize(images, haralick_feature)
        indexes = th.threshold_mean(signal)
        #coords_f = []
        #for x in indexes:
        #	coords_f.append(coords[x])
        coords = coords[indexes]
        coords = cells.group(coords)
        coords = cells.reorganize_coords(coords)

        for c in coords:
            part_img = img_grey[c[2]:c[3], c[0]:c[1]]
            part_img = cv2.resize(part_img, resize_img)
            part = hog.runOne(part_img,
                              orient=hog_orientations,
                              pixels=hog_cell_size,
                              cells=hog_block_size)
            part = part.reshape((1, part.shape[0]))
            Y = net.predict(part)[0, 0]
            if (Y > thresh and c[0] != 0 and c[1] != 500
                    and abs(c[0] - c[1]) * abs(c[2] - c[3]) > 625):
                cells.box2(img, c)
                box = Box()
                box.box = [c[0], c[2], c[1], c[3]]
                boxes.add(index, box)
        cv2.imwrite(path_out + name, img)
    boxes.save('boxes_predicted_ann_25.b')
Ejemplo n.º 15
0
    def __init__(self, context, svgData):
        self.svgData = None
        self.texture = None
        self.context = context
        self.cache = None
        self.transform = SvgTransform()

        # Detect the type of data passed in
        if type(svgData) == file:
            self.svgData = svgData.read()
        elif type(svgData) == str:
            bitmapFile = svgData.replace(".svg", ".png")
            # Load PNG files directly
            if svgData.endswith(".png"):
                self.texture = Texture(svgData)
            # Check whether we have a prerendered bitmap version of the SVG file
            elif svgData.endswith(".svg") and os.path.exists(bitmapFile):
                Log.debug("Loading cached bitmap '%s' instead of '%s'." %
                          (bitmapFile, svgData))
                self.texture = Texture(bitmapFile)
            else:
                if not haveAmanith:
                    e = "PyAmanith support is deprecated and you are trying to load an SVG file."
                    Log.error(e)
                    raise RuntimeError(e)
                Log.debug("Loading SVG file '%s'." % (svgData))
                self.svgData = open(svgData).read()

        # Make sure we have a valid texture
        if not self.texture:
            if type(svgData) == str:
                e = "Unable to load texture for %s." % svgData
            else:
                e = "Unable to load texture for SVG file."
            Log.error(e)
            raise RuntimeError(e)
Ejemplo n.º 16
0
    def testRenderToTexture(self):
        scale = 4
        fullwidth, fullheight = 512, 512
        width, height = int(fullwidth / scale), int(fullheight / scale)
        t = Texture()
        self.e.svg.setProjection((0, 0, fullwidth, fullheight))

        t.prepareRenderTarget(width, height)
        t.setAsRenderTarget()
        glViewport(0, 0, width, height)
        glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT
                | GL_DEPTH_BUFFER_BIT)
        self.svg.transform.translate(width * scale / 2, height * scale / 2)
        self.svg.transform.rotate(3.141592)
        self.svg.draw()
        t.resetDefaultRenderTarget()

        glViewport(0, 0, fullwidth, fullheight)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluOrtho2D(0.0, 1.0, 0.0, 1.0)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        t.bind()
        glEnable(GL_TEXTURE_2D)
        if not t.framebuffer.emulated:
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
                            GL_LINEAR_MIPMAP_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

        glClear(GL_COLOR_BUFFER_BIT)
        glColor3f(1.0, 1.0, 1.0)
        glBegin(GL_TRIANGLE_STRIP)
        glTexCoord2f(0.0, 0.0)
        glVertex2f(0.0, 0.0)
        glTexCoord2f(1.0, 0.0)
        glVertex2f(1.0, 0.0)
        glTexCoord2f(0.0, 1.0)
        glVertex2f(0.0, 1.0)
        glTexCoord2f(1.0, 1.0)
        glVertex2f(1.0, 1.0)
        glEnd()

        self.e.video.flip()
        import time
        time.sleep(2)
Ejemplo n.º 17
0
def tracker(i):
	boxes = Boxes(len(files))
	tex = Texture()
	ims = Slicer()
	th = Threshold()
	hog = Hog()
	cells = Cells(sizeh,sizew)

	names = list(listdir(path))
	names = names[i:i+batch_size]
	
	
	f = open('data/net/dataset_184_nets_svm/svm_c_2_p_8_o_2.svm','rb')
	clf = pickle.load(f)
	f.close()

	while(len(names)>0):
		index = len(names)-1
		name = names.pop()

		img = cv2.imread(path+name)
		img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

		images,coords = ims.split(img_grey,sizeh,sizew,sizeh,sizew)
		signal_p = tex.analize(images,haralick_feature)
		indexes = th.threshold_mean(signal_p)
		coords_f = []
		for x in indexes:
			coords_f.append(coords[x])

		coords = cells.group(coords_f)
		coords = cells.reorganize_coords(coords)
		for c in coords:
			part_img = img_grey[c[2]:c[3],c[0]:c[1]]
			part_img = cv2.resize(part_img,resize_img)
			part = hog.runOne(part_img,orient=hog_orientations,pixels=hog_cell_size,cells=hog_block_size)
			part = part.reshape((1,part.shape[0]))
			Y = clf.predict(part)
			if(Y>thresh and c[0]!=0 and c[1]!=500 and abs(c[0]-c[1])*abs(c[2]-c[3])>625 ):
				cells.box2(img,c)
				box = Box()
				box.box = [c[0],c[2],c[1],c[3]]
				boxes.add(index,box)
		cv2.imwrite(path_out+name,img)
	boxes.save('boxes_predicted_svm_25.b')
Ejemplo n.º 18
0
    def cacheGlyph(self, ch):
        """
    Add character and size to glyph caches

    @param ch: Character
    @return:   Glyph instance
    """
        # Font size
        self.glyphSizeCache[ch] = self.font.size(ch)
        # Font texture
        s = self.font.render(ch, True, (255, 255, 255))
        t = Texture()
        t.setFilter(GL_LINEAR, GL_LINEAR)
        t.setRepeat(GL_CLAMP, GL_CLAMP)
        t.loadSurface(s, alphaChannel=True)
        del s
        self.glyphCache[ch] = t
        return t
Ejemplo n.º 19
0
def tracker(i):
	boxes = Boxes(len(files))
	tex = Texture()
	ims = Slicer()
	th = Threshold()
	cells = Cells(sizeh,sizew)

	names = list(listdir(path))
	names = names[i:i+batch_size]
	
	
	f = open('svmsemhog.svm','rb')
	clf = pickle.load(f)
	f.close()

	while(len(names)>0):
		index = len(names)-1
		name = names.pop()

		img = cv2.imread(path+name)
		img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

		images,coords = ims.split(img_grey,sizeh,sizew,sizeh,sizew)
		signal_p = tex.analize(images,haralick_feature)
		indexes = th.threshold_mean(signal_p)
		coords_f = []
		for x in indexes:
			coords_f.append(coords[x])

		coords = cells.group(coords_f)
		coords = cells.reorganize_coords(coords)
		for c in coords:
			part_img = img_grey[c[2]:c[3],c[0]:c[1]]
			part_img = cv2.resize(part_img,resize_img).flatten()
			print(part_img)
			input()
			Y = clf.predict(part_img)
			if(Y>thresh and c[0]!=0 and c[1]!=500 and abs(c[0]-c[1])*abs(c[2]-c[3])>625 ):
				cells.box2(img,c)
				box = Box()
				box.box = [c[0],c[2],c[1],c[3]]
				boxes.add(index,box)
		cv2.imwrite(path_out+name,img)
	boxes.save('boxes_predicted_svm.b')
Ejemplo n.º 20
0
    def __init__(self, texture_path):
        self.texture_path = texture_path

        self.texture_size = 16  # 16*16 texture size

        self.textures = {}

        for texture in json.load(open(TEXTURE_CONFIG_FILE)).items():
            name = texture[0]
            settings = texture[1]
            texture_coords = settings["texture_coords"]
            mining_level = settings["mining_level"]
            damage = settings["damage"]
            top, bottom, side = texture_coords
            self.textures[name] = Texture(
                name, self.get_texture_coordinates(top, bottom, side),
                mining_level, damage)

        self.indestructible_resources = [
            resource for resource in self.textures.values()
            if resource.indestructible
        ]

        self.world_resources = [
            texture for texture in list(self.textures.values())
            if texture not in self.indestructible_resources
        ]

        self.resource_levels = [
            self.textures["dirt"], self.textures["stone"],
            self.textures["bedrock"]
        ]

        self.wall_resource = self.textures["bedrock"]

        self.faces = [
            (0, 1, 0),
            (0, -1, 0),
            (-1, 0, 0),
            (1, 0, 0),
            (0, 0, 1),
            (0, 0, -1),
        ]
Ejemplo n.º 21
0
    def initializeGL(self):
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClearDepth(1.0)

        domeStr = "CanvasModel.Dome"
        self.shaders[domeStr + "_proj"] = Shader("shaders/dome_proj.vert",
                                                 "shaders/dome_4proj.frag")
        self.shaders[domeStr + "_edgeblend"] = Shader(
            "shaders/dome_edgeblend.vert", "shaders/dome_edgeblend_4proj.frag")
        self.shaders[domeStr + "_inv_proj"] = Shader(
            "shaders/dome_inv_proj.vert", "shaders/dome_inv_proj.frag")
        #     cycloramaStr = "CanvasModel.Cyclorama"
        #     self.shaders[cycloramaStr+"_proj"] = Shader("shaders/cyclorama_proj.vert","shaders/dome_proj.frag")
        #    self.shaders[cycloramaStr+"_edgeblend"] = Shader("shaders/cyclorama_edgeblend.vert","shaders/cyclorama_edgeblend.frag")
        #   self.shaders[cycloramaStr+"_inv_proj"] = Shader("shaders/dome_inv_proj.vert","shaders/dome_inv_proj.frag")

        for textureFile in self.textureFiles:
            texFile = os.path.join(TEXTURE_PATH, textureFile)
            self.textures[textureFile[:-4]] = Texture(texFile)
Ejemplo n.º 22
0
print aruco.drawDetectedMarkers
#cv2.aruco.drawMarker()
#dic = cv2.aruco.getPredefinedDictionary(cv2.acuro.DICT_6X6_250)
#print cv2.aruco
print help(cv2)

bridge = CvBridge()
with open('camera_calib.pickle', 'r') as f:
    ret, mtx, dist, rvecs, tvecs, objpoints, imgpoints = pickle.load(f)

window = Window(640, 480, 16, 'OpenCV+OpenGL')

webcam_image = np.zeros((480, 640, 3), dtype=np.uint8)

tex = Texture(webcam_image.shape[:2])
fbo = Framebuffer(*webcam_image.shape[:2])
Texture.handlesToUBO([tex.handle, fbo.color_handle])


def callback(data):
    webcam_image[:] = bridge.imgmsg_to_cv2(data, "passthrough")


rospy.init_node('listener', anonymous=True, disable_signals=True)
rospy.Subscriber("/rgb/image", Image, callback, queue_size=1)
thread.start_new_thread(rospy.spin, ())

screen_shader = Shader('shader/screen_shader.vs', 'shader/screen_shader.frag')
color_shader = Shader('shader/color_shader.vs', 'shader/color_shader.frag')
quad_shader = Shader('shader/quad_shader.vs', 'shader/quad_shader.frag')
Ejemplo n.º 23
0
    
    glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, tex[0], 0)
    glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, tex[1], 0)
    
    color_handle = glGetTextureHandleNV(tex[0])
    glMakeTextureHandleResidentNV(color_handle)
    depth_handle = glGetTextureHandleNV(tex[1])
    glMakeTextureHandleResidentNV(depth_handle)

    assert glCheckNamedFramebufferStatus(fbo, GL_FRAMEBUFFER)\
                    == GL_FRAMEBUFFER_COMPLETE, 'Framebuffer not complete'
    return fbo, color_handle

fbo, color_handle  = createFramebuffer(640, 480, 1)

tex = Texture(raw_im.shape[:2])

handles = np.empty(2, dtype=np.uint64)
handles[0] = tex.getHandle()
handles[1] = color_handle

ubo = np.empty(1, dtype=np.uint32)
glCreateBuffers(len(ubo), ubo)
glNamedBufferStorage( ubo[0], handles.nbytes, handles, 0)
glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 2, ubo[0], 0, handles.nbytes)

def callback(data):
    try:
        #lock.acquire()
        dat = bridge.imgmsg_to_cv2(data, "passthrough")
        raw_im[:] = dat
Ejemplo n.º 24
0
    iA, iB, iC = [dot(n, render.light) for n in (nA, nB, nC)]
    intensity = w * iA + v * iB + u * iC
    intensity = intensity / 4
    if (tcolor):
        return color(
            int(tcolor[2] * intensity) if tcolor[0] * intensity > 0 else 0,
            int(tcolor[1] * intensity) if tcolor[1] * intensity > 0 else 0,
            int(tcolor[0] * intensity) if tcolor[2] * intensity > 0 else 0)
    else:
        return color(0, 0, 0)


def table(render, **kwargs):
    tx, ty = kwargs['texture_coords']
    return color(255, 255, 255)


r = Render(800, 800)
t = Texture('./models/model.bmp')
r.light = V3(0, 1, 1)

r.active_texture = t
r.active_shader = fragment

r.lookAt(V3(1, 0, 5), V3(0, 0, 0), V3(0, 1, 0))
r.load('./models/model.obj',
       translate=(0, 0, 0),
       scale=(1, 1, 1),
       rotate=(0, 0, 0))
r.draw_arrays('TRIANGLES')
r.display('out.bmp')
Ejemplo n.º 25
0
 def loadTexture(self, filename):
     self.texture = Texture(self.renderer, filename).filename
Ejemplo n.º 26
0
  def render(self, text, pos = (0, 0), direction = (1, 0), scale = DEFAULT_SCALE, shadowoffset = (.0022, .0005)):
    """
    Draw some text.

    @param text:      Text to draw
    @param pos:       Text coordinate tuple (x, y)
    @param direction: Text direction vector (x, y, z)
    @param scale:     Scale factor
    """
    # deufeufeu : new drawing relaying only on pygame.font.render
    #           : I know me miss special unicodes characters, but the gain
    #           : is really important.
    # evilynux : Use arrays to increase performance
    def drawSquare(w,h,tw,th):
        self.square_prim[1,0] = self.square_prim[3,0] = w
        self.square_prim[2,1] = self.square_prim[3,1] = h
        self.square_tex[0,1] = self.square_tex[1,1] = th
        self.square_tex[1,0] = self.square_tex[3,0] = tw
        glEnableClientState(GL_VERTEX_ARRAY)
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glVertexPointerf(self.square_prim)
        glTexCoordPointerf(self.square_tex)
        glDrawArrays(GL_TRIANGLE_STRIP, 0, self.square_prim.shape[0])
        glDisableClientState(GL_VERTEX_ARRAY)
        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
 
    if not text:
        return

    try:
        t,w,h = self.stringsCache.get(text)
    except KeyError:
        s = self.font.render(text, True, (255,255,255))
        t = Texture()
        t.setFilter(GL_LINEAR, GL_LINEAR)
        t.setRepeat(GL_CLAMP, GL_CLAMP)
        t.loadSurface(s, alphaChannel = True)
        del s
        w, h = self.font.size(text)
        self.stringsCache.add(text,(t,w,h))
     
    x, y = pos
    scale *= self.scale
    w, h = w*scale, h*scale
    tw,th = t.size
    glEnable(GL_TEXTURE_2D)
    glPushMatrix()
    glTranslatef(x,y,0)
    t.bind()
    if self.outline:
        glPushAttrib(GL_CURRENT_BIT)
        glColor4f(0, 0, 0, .25 * glGetDoublev(GL_CURRENT_COLOR)[3])

        blur = 2 * DEFAULT_SCALE
        for offset in [(-.7, -.7), (0, -1), (.7, -.7), (-1, 0), 
                       (1, 0), (-.7, .7), (0, 1), (.7, .7)]:
            glTranslatef(blur * offset[0], blur * offset[1], 0)
            drawSquare(w,h,tw,th)
            glTranslatef(-blur * offset[0], -blur * offset[1], 0)
        glPopAttrib()

    if self.shadow:
        glPushAttrib(GL_CURRENT_BIT)
        glColor4f(0, 0, 0, 1)
        glTranslatef(shadowoffset[0], shadowoffset[1], 0)
        drawSquare(w,h,tw,th)
        glTranslatef(-shadowoffset[0], -shadowoffset[1], 0)
        glPopAttrib()

    drawSquare(w,h,tw,th)
    glPopMatrix()

    glDisable(GL_TEXTURE_2D)
    return
Ejemplo n.º 27
0
    def render(self,
               text,
               pos=(0, 0),
               rotate=0,
               scale=DEFAULT_SCALE,
               shadowoffset=(.0022, .0005),
               align=LEFT,
               new=False,
               shadow=False,
               outline=False,
               shadowOpacity=1.0):
        """
        Draw some text.

        @param text:      Text to draw
        @param pos:       Text coordinate tuple (x, y)
        @param rotate:    Angle to rotate text, in degrees
        @param scale:     Scale factor
        """

        # deufeufeu : new drawing relaying only on pygame.font.render
        #           : I know me miss special unicodes characters, but the gain
        #           : is really important.
        # evilynux : Use arrays to increase performance
        def drawSquare(w, h, tw, th):
            self.square_prim[1, 0] = self.square_prim[3, 0] = w
            self.square_prim[2, 1] = self.square_prim[3, 1] = h
            self.square_tex[0, 1] = self.square_tex[1, 1] = th
            self.square_tex[1, 0] = self.square_tex[3, 0] = tw
            cmgl.drawArrays(GL_TRIANGLE_STRIP,
                            vertices=self.square_prim,
                            texcoords=self.square_tex)

        if not text:
            return

        try:
            t, w, h = self.stringsCache.get(text)
        except KeyError:
            s = self.font.render(text, True, (255, 255, 255))
            t = Texture()
            t.setFilter(GL_LINEAR, GL_LINEAR)
            t.setRepeat(GL_CLAMP, GL_CLAMP)
            t.loadSurface(s, alphaChannel=True)
            del s
            w, h = self.font.size(text)
            self.stringsCache.add(text, (t, w, h))

        x, y = pos
        scale *= self.scale
        w, h = w * scale * self.aspectRatioFactor, h * scale
        if align == CENTER:  #we have already done all the calculating. Why not add this? - akedrou
            x -= (w / 2)
        elif align == RIGHT:
            x -= w
        y -= (h / 2)
        tw, th = t.size
        glEnable(GL_TEXTURE_2D)
        with cmgl.PushedMatrix():
            if rotate:
                if not isinstance(rotate, tuple):
                    glRotatef(rotate, 0, 0, 1.0)
                else:
                    glRotatef(0, *rotate)
            glTranslatef(x, y, 0)
            t.bind()
            if self.outline or outline:
                with cmgl.PushedAttrib(GL_CURRENT_BIT):
                    glColor4f(0, 0, 0, .25 * glGetDoublev(GL_CURRENT_COLOR)[3])

                    blur = 2 * DEFAULT_SCALE
                    for offset in [(-.7, -.7), (0, -1), (.7, -.7), (-1, 0),
                                   (1, 0), (-.7, .7), (0, 1), (.7, .7)]:
                        with cmgl.PushedMatrix():
                            glTranslatef(blur * offset[0], blur * offset[1], 0)
                            drawSquare(w, h, tw, th)

            if self.shadow or shadow:
                with cmgl.PushedAttrib(GL_CURRENT_BIT):
                    glColor4f(
                        0, 0, 0,
                        glGetDoublev(GL_CURRENT_COLOR)[3] * shadowOpacity)
                    with cmgl.PushedMatrix():
                        glTranslatef(shadowoffset[0], shadowoffset[1], 0)
                        drawSquare(w, h, tw, th)

            drawSquare(w, h, tw, th)

        glDisable(GL_TEXTURE_2D)
Ejemplo n.º 28
0
mesh2 = Mesh("resources/meshes/plane2_p_n_uv1.ply")
mesh2.load()
mesh2.create()
mesh2_mat = pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 0, 0]))

# mesh3 = Mesh("resources/meshes/Dragon.ply")
# mesh3.load()
# mesh3.create()
# mesh3_mat = pyrr.matrix44.create_from_translation(pyrr.Vector3([2, 1, .5]))

shader1 = Shader("resources/shaders/shader1.vs", "resources/shaders/shader1.fs")
shader1.load()
shader1.create()
# shader1.use() # needed

tex1 = Texture("resources/images/marble.jpg")
tex1.load()
tex1.create()

tex2 = Texture("resources/images/brickwall.jpg")
tex2.load()
tex2.create()

tex3 = Texture("resources/images/StoneMarbleCalacatta004_COL_2K.jpg")
tex3.load()
tex3.create()

light_pos = [0.0, 1.0, 3.0]

# set global render states
glClearColor(0, 0.1, 0.1, 1)
Ejemplo n.º 29
0
Then we Draw the stars in the sky, using a shader that use a random generator of
white points, and that random has lower probability when y is greater. 

"""
stars(r)
"""

We draw to moons, using an sphere model, each one has different texture
and differnt shader to produce the effect of an celestial body. This models
were made using bump mapping. 


"""

#Draw the moon Iscaco
t = Texture('./models/iscalo.bmp')
r.active_texture = t
r.active_light = norm(V3(0, 20, 0))
r.load('./models/sphere.obj', [-0.55, 0.70, 0], [0.22, 0.22, 0.22],
       [0, 0.2, 0])
r.active_shader = moon
r.draw_arrays('TRIANGLES')

#Draw the moon Urica
t = Texture('./models/urica.bmp')
r.active_texture = t
r.load('./models/sphere.obj', [0.57, 0.80, 0], [0.20, 0.20, 0.20], [0, 0.2, 0])
r.active_shader = planet
r.draw_arrays('TRIANGLES')
"""
Ejemplo n.º 30
0
	def __init__(self,half_width,half_height,filename):
		self.compiler=Compiler()
		self.background_t = Texture(TEXDIR+filename)
		self.background_geom=self.compiler.quad(half_width,half_height)