Exemplo n.º 1
0
def main():

    if not glfw.init():
        return

    monitors = glfw.get_monitors()
    print('Monitors')

    print(glfw.get_monitor_name(monitors[0]))
    print(glfw.get_monitor_name(monitors[1]))

    print(glfw.get_video_mode(monitors[0]))
    print(glfw.get_video_mode(monitors[1]))

    print(glfw.get_video_modes(monitors[0]))
    print(glfw.get_video_modes(monitors[1]))

    window = glfw.create_window(1024, 768, "Opengl GLFW Window", monitors[1],
                                None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        glfw.swap_buffers(window)

    glfw.terminate()
Exemplo n.º 2
0
    def glfwMonitorCallback(self):
        # TODO: Test the F**K out of this!
        newMonitors = glfw.get_monitors()
        newMonitornames = [bytes.decode(glfw.get_monitor_name(monitor)) for monitor in newMonitors]

        for monitorName in self.glfwWorkers:
            if monitorName not in newMonitornames:
                print("Monitor " + monitorName + " doesn't exist anymore, worker is now doing whatever.")

        self.monitors = newMonitors
        self.monitornames = newMonitornames

        for monitor in self.monitors:
            self.monitorDict[bytes.decode(glfw.get_monitor_name(monitor))] = monitor
Exemplo n.º 3
0
    def _select_monitor(self):
        self.monitor = None
        if SETTINGS.display in ["window", "windowed"]:
            return

        for monitor in glfw.get_monitors():
            logger.info("* {} : {}".format(glfw.get_monitor_name(monitor),
                                           glfw.get_video_modes(monitor)))

        for monitor in glfw.get_monitors():
            if glfw.get_monitor_name(
                    monitor
            ) == SETTINGS.display or SETTINGS.display == "fullscreen":
                self.monitor = monitor
                break
Exemplo n.º 4
0
    def __init__(self):
        self.tcpPort = 31337
        self.tcpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.tcpsocket.bind(("0.0.0.0", self.tcpPort))
        self.tcpsocket.listen(10)

        self.discoverysocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.discoverysocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
                                        1)
        self.discoverysocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,
                                        1)

        self.glfwWorkers = {}

        self.controllerConn = None
        self.controllerAddr = None
        self.outbuf = ""  # IO buffer for controller
        self.inbuf = ""

        self.monitors = glfw.get_monitors()

        for monitor in glfw.get_monitors():
            self.glfwWorkers[bytes.decode(
                glfw.get_monitor_name(monitor))] = glfwWorker(monitor)
Exemplo n.º 5
0
    def __init__(self, monitor):
        self.monitor = monitor
        self.window = None

        self.availableModules = {}
        self.sheetdata = {}
        self.sheetObjects = {}

        self.nodedataJar = {}

        self.currentSheet = None
        self.sheetInitId = None
        self.sheetLoopId = None

        # --- Runtime variables
        self.width = 1
        self.height = 1

        self.state = "stop"
        self.time = glfw.get_time()
        self.deltatime = 1

        self.fbo = None
        self.fbotexture = None
        self.monitorname = bytes.decode(glfw.get_monitor_name(self.monitor))
Exemplo n.º 6
0
    def parse(self,
              monitorptr: ctypes.POINTER(ctypes.POINTER(glfw._GLFWmonitor))):
        self.monitorptr: ctypes.POINTER(ctypes.POINTER(
            glfw._GLFWmonitor)) = monitorptr

        self.vidmodes = glfw.get_video_modes(self.monitorptr)
        self.name = glfw.get_monitor_name(self.monitorptr)
Exemplo n.º 7
0
    def _select_video_mode(self):
        """ Selects the monitor resolution whose width is the immediately higher than the stitcher resolution
        """
        resolutions = list(reversed(glfw.get_video_modes(self.monitor)))
        self.video_mode = None
        for refresh_rate in [30, 29, 60, 59]:
            for resolution in resolutions:
                if resolution[0][0] < self.width:
                    break
                if resolution[2] == refresh_rate:
                    self.video_mode = resolution
            if self.video_mode:
                break

        if not self.video_mode:
            logger.info(
                "No matching resolution found, using highest available")
            self.video_mode = resolutions[0]

        mode = str(self.video_mode[0][0]) + "x" + str(self.video_mode[0][1])
        rate = str(self.video_mode[2])
        subprocess.call([
            "xrandr", "--output",
            glfw.get_monitor_name(self.monitor), "--mode", mode, "--rate", rate
        ])
        time.sleep(1)
Exemplo n.º 8
0
 def _monitor_event(self, monitor, event):
     name = glfw.get_monitor_name(monitor)
     if event == glfw.DISCONNECTED:
         logger.info("Unplugged monitor {}".format(name))
     else:
         logger.info("Plugged monitor {}".format(name))
     self.pano_renderer.enableOutput(False)
     if self.output_window:
         glfw.hide_window(self.output_window)
     async .delay(SWITCH_DELAY, self.open_output_window)
Exemplo n.º 9
0
def move_window_to_monitor(window, monitor_name):
    monitors = glfw.get_monitors()
    monitor = None
    for m in monitors:
        if glfw.get_monitor_name(m) == monitor_name:
            monitor = m

    if monitor is not None:
        glfw.set_window_pos(window, *glfw.get_monitor_pos(monitor))
        return True
    else:
        return False
Exemplo n.º 10
0
    def sendMonitorsReply(self, msgid):
        self.monitors = glfw.get_monitors()
        msg = {
            "msgid":
            uuid.uuid4().int,
            "msgtype":
            "reply",
            "refid":
            msgid,
            "replydata": [
                bytes.decode(glfw.get_monitor_name(monitor))
                for monitor in self.monitors
            ]
        }

        self.sendMessage(msg)
Exemplo n.º 11
0
    def open_output_window(self):
        self._pause_event_loop()

        # Select monitor
        self._select_monitor()

        # Open window
        if self.monitor:
            # Fullscreen
            self._select_video_mode()
            x, y = glfw.get_monitor_pos(self.monitor)
            logger.info("Output selected : {} on {} at {},{}".format(
                str(self.video_mode), glfw.get_monitor_name(self.monitor), x,
                y))
            w, h = self.video_mode[0]
            self.pano_renderer.setViewport(w, h)
            self.pano_renderer.setRefreshRate(
                self._convert_rate(30), self._convert_rate(self.video_mode[2]))
            if self.output_window:
                glfw.set_window_monitor(self.output_window, self.monitor, x, y,
                                        w, h, self.video_mode[2])
                glfw.show_window(self.output_window)
                self.pano_renderer.enableOutput(True)
            else:
                self._open_output_window(w, h, self.monitor, self.video_mode)
        else:
            # No monitor available or windowed
            w = self.width / 4
            h = self.height / 4
            self.pano_renderer.setViewport(w, h)

            monitor = glfw.get_primary_monitor()
            if monitor:
                rate = glfw.get_video_mode(monitor)[2]
                self.pano_renderer.setRefreshRate(self._convert_rate(30),
                                                  self._convert_rate(rate))

            if self.output_window:
                self.pano_renderer.enableOutput(True)
                glfw.show_window(self.output_window)
            else:
                self._open_output_window(w, h)
                if not SETTINGS.display in ["window", "windowed"]:
                    # No monitor available
                    glfw.hide_window(self.output_window)

        self._unpause_event_loop()
Exemplo n.º 12
0
 def __init__(self, index, gl_handle):
     self.__gl_handle = gl_handle
     self.__name = glfw.get_monitor_name(gl_handle).decode("utf-8")
     self.__index = index
Exemplo n.º 13
0
def main():
    if not glfw.init():
        raise RuntimeError('Failed to initialize GLFW')

    version = glfw.get_version_string().decode('ASCII')
    print('GLFW', version)

    monitors = glfw.get_monitors()
    for i, monitor in enumerate(monitors):
        name = glfw.get_monitor_name(monitor)
        primary = (glfw.get_monitor_pos(monitor) ==
                   glfw.get_monitor_pos(glfw.get_primary_monitor()))
        print('Monitor #{}: {}{}'.format(i, name.decode('utf8'),
              ' (primary)' if primary else ''))
        width_mm, height_mm = glfw.get_monitor_physical_size(monitor)
        diag_mm = math.sqrt(width_mm*width_mm + height_mm*height_mm)
        print('Diagonal: {:.1f}"'.format(diag_mm / 25.4))
        mode = glfw.get_video_mode(monitor)
        print('Video mode: {}x{} {}Hz {}'.format(mode.size.width, mode.size.height,
              mode.refresh_rate, mode.bits))
        xscale, yscale = glfw.get_monitor_content_scale(monitor)
        print('Scale: {}|{}'.format(xscale, yscale))
        print('Virtual position:', glfw.get_monitor_pos(monitor))
        print('Work ares:', glfw.get_monitor_workarea(monitor))
        for mode in glfw.get_video_modes(monitor):
            print('Supported: {}x{} {}Hz {}'.format(mode.size.width, mode.size.height,
                mode.refresh_rate, mode.bits))
            print(mode)

        print()

    glfw.window_hint(glfw.RESIZABLE, True)
    glfw.window_hint(glfw.STENCIL_BITS, 8)
    glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    monitor = glfw.get_primary_monitor()
    mode = glfw.get_video_mode(monitor)

    window = glfw.create_window(640, 480, 'Title', None, None)
    # window = glfw.create_window(mode.size.width, mode.size.height, 'Title', monitor, None)
    if window is None:
        glfw.terminate()
        raise RuntimeError('Failed to create a window')

    # glfw.set_window_monitor(window, monitor, 0, 0, mode.size.width, mode.size.height, mode.refresh_rate)

    width, height = glfw.get_window_size(window)
    print('Window size: {}x{}'.format(width, height))
    print('Frame size:', glfw.get_window_frame_size(window))
    width, height = glfw.get_framebuffer_size(window)
    print('Framebuffer size: {}x{}'.format(width, height))
    print('Client API:', glfw.get_window_attrib(window, glfw.CLIENT_API))
    version_major = glfw.get_window_attrib(window, glfw.CONTEXT_VERSION_MAJOR)
    version_minor = glfw.get_window_attrib(window, glfw.CONTEXT_VERSION_MINOR)
    revision = glfw.get_window_attrib(window, glfw.CONTEXT_REVISION)
    print('Version: {}.{} rev{}'.format(version_major, version_minor, revision))

    glfw.make_context_current(window)
    renderer = Renderer(window)

    while not glfw.window_should_close(window):
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        renderer.render()
        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
 def get_monitors_idx_list():
     monitors = [glfw.get_monitor_name(m) for m in glfw.get_monitors()]
     return range(len(monitors)), monitors
Exemplo n.º 15
0
    def run(self):
        # See if there are any incoming connections
        rlist, wlist, elist = select([self.tcpsocket, self.udpsock], [], [], 0)
        if rlist:
            for sock in rlist:
                if sock == self.tcpsocket:
                    conn, addr = self.tcpsocket.accept()
                    if self.controllerConn is not None:
                        rlist, wlist, elist = select([], [conn], [], 0)
                        if wlist:
                            conn.send(b'{"status": ["error", 1], "message": "Already got controller."}\n')
                        print("Rejecting connection from " + str(self.controllerAddr) + ".")
                        conn.close()
                    else:
                        print("Accepting connection from " + str(self.controllerAddr) + ".")
                        self.controllerConn = conn
                        self.controllerAddr = addr
                        conn.send(b'{"status": ["ok", 1], "message": "Connection accepted."}\n')
                elif sock == self.udpsock:
                    data, addr = sock.recvfrom(4096)

                    try:
                        msg = bytes.decode(data)
                        msgdecoded = json.loads(msg)

                        if "bpm" in msgdecoded:
                            for worker in self.glfwWorkers:
                                self.glfwWorkers[worker].beatlow = True
                                self.glfwWorkers[worker].beatmid = False
                                self.glfwWorkers[worker].beathigh = False
                                self.glfwWorkers[worker].bpm = msgdecoded["bpm"]

                        if "cmd" in msgdecoded and "data" in msgdecoded:
                            pass


                    except:
                        raise

        # See if anything is to be sent to controller
        if self.outBuf:
            wlist = [self.controllerConn]
        else:
            wlist = []

        if self.controllerConn is not None:
            rlist = [self.controllerConn]
        else:
            rlist = []

        rlist, wlist, elist = select(rlist, wlist, [], 0)
        if rlist:
            incomingData = self.controllerConn.recv(1024)
            if not incomingData:    # AKA connection is dead
                print("Connection from " + str(self.controllerAddr) + " died.")
                self.controllerConn.close()
                self.controllerConn = None
                self.controllerAddr = None
            else:   # Append incoming message to the commandbuf to be parsed later
                try:
                    self.messageBuf += bytes.decode(incomingData)
                except UnicodeDecodeError:
                    self.sendError("""Error: Failed decoding message from controller as unicode:
----- MESSAGE: -----
""" + str(incomingData) + """
-- MESSAGE END --""", None)

        if wlist:
            self.controllerConn.send(str.encode(self.outBuf))

        self.parseMessageBuf()

        for key in self.glfwWorkers:
            try:
                with Timeout(1):
                    self.glfwWorkers[key].run()
            except Timeout.Timeout:
                print("Error: run() for worker '" + bytes.decode(glfw.get_monitor_name(self.glfwWorkers[key].monitor)) + "' timed out after 1 second.")   # TODO: send error message to controller
Exemplo n.º 16
0
def main():
    glfw.init()

    glfw.window_hint(glfw.RESIZABLE, False)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    w = glfw.create_window(800, 600, 'Window Title', None, None)

    glfw.make_context_current(w)

    ###############

    face = freetype.Face("/usr/share/fonts/TTF/IBMPlexSans-Regular.ttf")

    # Figure out DPI's of different monitors
    # Perhaps take these into account if you care, as well as window scale.
    # But what if your window is split across screens?
    for monitor in glfw.get_monitors():
        name = glfw.get_monitor_name(monitor).decode('utf8')
        pw, ph = glfw.get_monitor_physical_size(monitor)
        videomode = glfw.get_video_mode(monitor)  # in mm
        vw, vh = videomode.size.width, videomode.size.height
        # print(name, 25.4*vw/pw, 25.4*vh/ph) # convert to pixels per inch
        print(name, (1 / 72) * 25.4 * vw / pw,
              (1 / 72) * 25.4 * vh / ph)  # pixels per point

    # Set char size via physical size calculation
    # width, height in 1/64 of points
    # A point is one 1/72 of an inch. My monitors have 1.35 to 1.84 pixels per point.
    # Device resolution in dots per inch.
    # pixel_size = point_size * resolution / 72
    # face.set_char_size(width=16*64) #,height=0,hres=72,vres=72

    # Set size of EM square via pixels directly
    face.set_pixel_sizes(20, 0)
    baseline_height = 20 * face.height / face.units_per_EM
    print(baseline_height)

    ###############

    # disable byte-alignment restriction
    # normally, textures need to occupy a multiple of 4 in memory
    # but glyphs are single-color so they don't satisfy this
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)

    glyphs = {}
    for i in range(face.num_glyphs):
        face.load_glyph(i)  #flags=FT_LOAD_RENDER - renders glyph after loading

        texture = glGenTextures(1)

        # all of these numbers are pixels*64 by default
        # so divide by 64 to make these just pixels
        glyphs[i] = {
            "texture": texture,
            "w": face.glyph.metrics.width / 64,
            "h": face.glyph.metrics.height / 64,
            "hori": {
                "advance": face.glyph.metrics.horiAdvance / 64,
                "bearingX": face.glyph.metrics.horiBearingX / 64,
                "bearingY": face.glyph.metrics.horiBearingY / 64,
            },
            "vert": {
                "advance": face.glyph.metrics.vertAdvance / 64,
                "bearingX": face.glyph.metrics.vertBearingX / 64,
                "bearingY": face.glyph.metrics.vertBearingY / 64,
            }
        }

        bitmap = face.glyph.bitmap

        glBindTexture(GL_TEXTURE_2D, texture)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, bitmap.width, bitmap.rows, 0,
                     GL_RED, GL_UNSIGNED_BYTE, bitmap.buffer)
        # target, level, internalformat, width, height, border=0, format, type,data

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
                        GL_CLAMP_TO_EDGE)  # these two seem
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
                        GL_CLAMP_TO_EDGE)  # to be optional
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

    ##################

    shaderProgram = make_shader_program()
    glUseProgram(shaderProgram)

    posParamsUniform = glGetUniformLocation(shaderProgram, "posParams")

    def set_pos(x, y, dx, dy):
        s = 1
        glUniform4f(posParamsUniform, s * x, s * y, s * dx, s * dy)
        # location, count, transpose, value

    vao = glGenVertexArrays(1)
    glBindVertexArray(vao)

    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    # two triangles to make a rectangle
    # coordinates are in screen space
    # to get texture coordinates to x->x and y->1-y
    vertices = [0.0, 1.0] + [0.0,0.0] + [1.0,0.0] +\
                [0.0, 1.0] + [1.0,0.0] + [1.0,1.0]
    glBufferData(GL_ARRAY_BUFFER, len(vertices)*ctypes.sizeof(ctypes.c_float), \
            (ctypes.c_float*len(vertices))(*vertices), GL_STATIC_DRAW)

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    glEnable(GL_BLEND)  # need this because the shader uses alphas
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    fbsize = {}
    fbsize["w"], fbsize["h"] = glfw.get_framebuffer_size(w)

    while not glfw.window_should_close(w):
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

        x, y = -1.0, 1.0
        y -= baseline_height * 2 / fbsize["h"]

        for i in range(face.num_glyphs):
            bx = glyphs[i]["hori"]["bearingX"] * 2 / fbsize["w"]
            by = glyphs[i]["hori"]["bearingY"] * 2 / fbsize["h"]
            width = glyphs[i]["w"] * 2 / fbsize["w"]
            height = glyphs[i]["h"] * 2 / fbsize["h"]

            set_pos(x + bx, y + by - height, width, height)

            x += glyphs[i]["hori"]["advance"] * 2 / fbsize["w"]

            glBindTexture(GL_TEXTURE_2D, glyphs[i]["texture"])
            glDrawArrays(GL_TRIANGLES, 0, 6)

            if i + 1 < face.num_glyphs:
                x += face.get_kerning(i, i + 1).x

                if x + glyphs[i +
                              1]["hori"]["advance"] * 2 / fbsize["w"] >= 1.0:
                    x = -1.0
                    y -= baseline_height * 2 / fbsize["h"]

            if y <= -1.0:
                break

        glfw.swap_buffers(w)
        glfw.poll_events()

    glDeleteBuffers(1, vbo)
    glDeleteVertexArrays(1, vao)

    glDeleteProgram(shaderProgram)

    glfw.terminate()