Exemplo n.º 1
0
 def __init__(self, surface, sky="fluffy_clouds.png", bed="seabed.png"):
     app.Canvas.__init__(self,
                         size=(600, 600),
                         title="Water surface simulator 2")
     self.surface = surface
     self.sky = io.read_png(sky)
     self.bed = io.read_png(bed)
     self.program = gloo.Program(VS, FS_triangle)
     self.program_point = gloo.Program(VS, FS_point)
     pos = self.surface.position()
     self.program["a_position"] = pos
     self.program_point["a_position"] = pos
     self.program['u_sky_texture'] = gloo.Texture2D(self.sky,
                                                    wrapping='repeat',
                                                    interpolation='linear')
     self.program['u_bed_texture'] = gloo.Texture2D(self.bed,
                                                    wrapping='repeat',
                                                    interpolation='linear')
     self.program_point["u_eye_height"] = self.program["u_eye_height"] = 3
     self.program["u_alpha"] = 0.9
     self.program["u_bed_depth"] = 1
     self.triangles = gloo.IndexBuffer(self.surface.triangulation())
     self.are_points_visible = False
     self._timer = app.Timer('auto', connect=self.on_timer, start=True)
     self.activate_zoom()
     self.show()
Exemplo n.º 2
0
    def __init__(self,
                 surface,
                 sky="textures/fluffy_clouds.png",
                 bed="textures/sand.png"):
        # self.method = RungeKutta()
        self.method = Euler()

        self.surface = surface
        self.sky = io.read_png(sky)
        self.bed = io.read_png(bed)
        app.Canvas.__init__(self, size=(400, 400), title="water")

        self.program = gloo.Program(vertex_shader, fragment_shader)
        self.program_point = gloo.Program(vertex_shader, point_fragment_shader)

        pos = self.surface.position()

        self.camera_height = 1.0
        self.program["a_position"] = pos
        self.program_point["a_position"] = pos
        self.program['u_sky_texture'] = gloo.Texture2D(self.sky,
                                                       wrapping='repeat',
                                                       interpolation='linear')
        self.program['u_bed_texture'] = gloo.Texture2D(self.bed,
                                                       wrapping='repeat',
                                                       interpolation='linear')
        self.program_point['u_camera_height'] = self.program[
            'u_camera_height'] = self.camera_height
        self.program_point["u_eye_height"] = self.program["u_eye_height"] = 1
        self.program["u_alpha"] = 0.9
        self.program["u_bed_depth"] = 2
        self.program["u_sun_direction"] = normalize([0, 1, 0.1])
        self.program["u_sun_diffused_color"] = [1, 0.8, 1]
        self.program["u_sun_reflected_color"] = [1, 0.8, 0.6]
        self.program["u_water_ambient_color"] = [0.1, 0.2, 0.2]
        self.program["u_water_depth_color"] = [0, 0.1, 0.1]
        self.triangles = gloo.IndexBuffer(self.surface.triangulation())

        self.h_description = None

        self.camera = np.array([0, 0, 1])
        self.up = np.array([0, 1, 0])
        self.set_camera()
        self.are_points_visible = False
        self.drag_start = None
        self.diffused_flag = True
        self.reflected_flag = True
        self.bed_flag = True
        self.stop_flag = False
        self.depth_flag = True
        self.sky_flag = True
        self.apply_flags()

        self._timer = app.Timer('auto', connect=self.on_timer, start=True)
        self.activate_zoom()
        self.show()
Exemplo n.º 3
0
    def __init__(self):
        app.Canvas.__init__(
                self,
                keys='interactive',
                size=(800,600),
                config=dict(samples=4)
                )

        self.V, self.F = create_sphere()
        self.program = gloo.Program(VSHADER, FSHADER)
        self.program.bind(self.V)
        self.program['u_sampler'] = gloo.Texture2D(
                io.read_png('earth.png'),
                interpolation='linear')

        self.th, self.ph = 0., 0.
        self.delta = 5.
        self.fov = 80.

        self.view = lookat(self.th, self.ph)
        self.model = rotate(180., (1,0,0))

        gloo.set_state(depth_test=True)
        self.set_viewport()
        self.show()
Exemplo n.º 4
0
def load_galaxy_star_image():

    fname = io.load_data_file('galaxy/star-particle.png')

    raw_image = io.read_png(fname)

    return raw_image
Exemplo n.º 5
0
 def __init__(self, surface, sky="fluffy_clouds.png", bed="seabed.png"):
     # store parameters
     self.surface = surface
     # read textures
     self.sky = io.read_png(sky)
     self.bed = io.read_png(bed)
     # create GL context
     app.Canvas.__init__(self,
                         size=(600, 600),
                         title="Water surface simulator 2")
     # Compile shaders and set constants
     self.program = gloo.Program(VS, FS_triangle)
     self.program_point = gloo.Program(VS, FS_point)
     pos = self.surface.position()
     self.program["a_position"] = pos
     self.program_point["a_position"] = pos
     self.program['u_sky_texture'] = gloo.Texture2D(self.sky,
                                                    wrapping='repeat',
                                                    interpolation='linear')
     self.program['u_bed_texture'] = gloo.Texture2D(self.bed,
                                                    wrapping='repeat',
                                                    interpolation='linear')
     self.program_point["u_eye_height"] = self.program["u_eye_height"] = 3
     self.program["u_alpha"] = 0.9
     self.program["u_bed_depth"] = 2
     self.sun_direction = [0, 0, 0.1]
     self.program["u_sun_direction"] = normalize(self.sun_direction)
     self.program["u_sun_diffused_color"] = [1, 0.8, 1]
     self.program["u_sun_reflected_color"] = [1, 0.8, 0.6]
     self.triangles = gloo.IndexBuffer(self.surface.triangulation())
     # Set up GUI
     self.camera = np.array([0, 0, 1])
     self.up = np.array([0, 1, 0])
     self.set_camera()
     self.are_points_visible = False
     self.drag_start = None
     self.diffused_flag = False
     self.reflected_flag = True
     self.bed_flag = True
     self.depth_flag = True
     self.sky_flag = True
     self.apply_flags()
     # Run everything
     self._timer = app.Timer('auto', connect=self.on_timer, start=True)
     self.activate_zoom()
     self.show()
Exemplo n.º 6
0
    def draw_init(self, backgroundImg=False, fontsize=14, fontColor="white"):
        gloo.clear(color="#231e1f")
        # gloo.set_state("translucent", depth_test=False,blend=True)
        try:
            self.text.clear()
        except:
            pass
        self.selected_point = -1
        self.fontsize = fontsize
        panzoom = PanZoomTransform(self.canvas)

        if backgroundImg:
            self.im = read_png("timg.png")
            self.image = ImageVisual(self.im, method="subdivide")
            self.image.update = self.canvas.update
            self.image.transform = STTransform(
                scale=(2 / self.image.size[0], 2 / self.image.size[1]),
                translate=(-1, -1),
            )
        else:
            self.image = None

        self.markers = PointCollection(
            "agg",
            vertex=self.pvertex,
            fragment=self.pfragment,
            color="shared",
            size="local",
            transform=panzoom,
        )
        self.lines = PathCollection(
            mode="agg",
            vertex=self.lvertex,
            fragment=self.lfragment,
            color="shared",
            linewidth="global",
            transform=panzoom,
        )
        self.markers.update.connect(self.canvas.update)
        self.lines.update.connect(self.canvas.update)
        self.text = TextVisual(u"", color="white")

        self.text.font_size = self.fontsize
        self.text.visible = False
        self.textpos = None

        self.canvas.events.draw.connect(self.on_draw)
        self.canvas.events.resize.connect(self.on_resize)
        self.canvas.events.mouse_press.connect(self.on_mouse_press)
        self.canvas.show()
Exemplo n.º 7
0
 def __init__(self, **kwargs):
     self._textureRegionDict = {
         "100%": (0, 0, 1/3, 1/3),
         "75%": (1/3, 0, 1/3, 1/3),
         "50%": (2/3, 0, 1/3, 1/3),
         "25%": (0, 1/3, 1/3, 1/3),
         "15%": (1/3, 1/3, 1/3, 1/3),
         "5%": (2/3, 1/3, 1/3, 1/3),
         "charging": (0, 2/3, 1/3, 1/3)
     }
     self._percent = 100
     self.text = Text("100%", font_size=5, color='w', bold=True)
     Sprite.__init__(self, read_png("images/battery.png"), **kwargs)
     self.rect = self._textureRegionDict['100%']
     self.text.parent = self.parent
Exemplo n.º 8
0
def test_show_vispy():
    """Some basic tests of show_vispy"""
    if has_matplotlib():
        n = 200
        t = np.arange(n)
        noise = np.random.RandomState(0).randn(n)
        # Need, image, markers, line, axes, figure
        plt.figure()
        ax = plt.subplot(211)
        ax.imshow(read_png(load_data_file('pyplot/logo.png')))
        ax = plt.subplot(212)
        ax.plot(t, noise, 'ko-')
        plt.draw()
        canvases = plt.show()
        canvases[0].close()
    else:
        assert_raises(ImportError, plt.show)
Exemplo n.º 9
0
def test_make_png():
    """Test to ensure that make_png functions correctly."""
    # Save random RGBA and RGB arrays onto disk as PNGs using make_png.
    # Read them back with an image library and check whether the array
    # saved is equal to the array read.

    # Create random RGBA array as type ubyte
    rgba_save = np.random.randint(256, size=(100, 100, 4)).astype(np.ubyte)
    # Get rid of the alpha for RGB
    rgb_save = rgba_save[:, :, :3]
    # Output file should be in temp
    png_out = op.join(temp_dir, 'random.png')

    # write_png implicitly tests _make_png
    for rgb_a in (rgba_save, rgb_save):
        write_png(png_out, rgb_a)
        rgb_a_read = read_png(png_out)
        assert_array_equal(rgb_a, rgb_a_read)
Exemplo n.º 10
0
def test_make_png():
    """ Test to ensure that make_png functions correctly.
    """
    # Save random RGBA and RGB arrays onto disk as PNGs using make_png.
    # Read them back with an image library and check whether the array
    # saved is equal to the array read.

    # Create random RGBA array as type ubyte
    rgba_save = np.random.randint(256, size=(100, 100, 4)).astype(np.ubyte)
    # Get rid of the alpha for RGB
    rgb_save = rgba_save[:, :, :3]
    # Output file should be in temp
    png_out = op.join(temp_dir, 'random.png')

    # write_png implicitly tests _make_png
    for rgb_a in (rgba_save, rgb_save):
        write_png(png_out, rgb_a)
        rgb_a_read = read_png(png_out)
        assert_array_equal(rgb_a, rgb_a_read)
Exemplo n.º 11
0
def get_test_image():
    """Load an image from the demo-data repository if possible. Otherwise,
    just return a randomly generated image.
    """
    from vispy.io import load_data_file, read_png

    try:
        return read_png(load_data_file('mona_lisa/mona_lisa_sm.png'))
    except Exception as exc:
        # fall back to random image
        print("Error loading demo image data: %r" % exc)

    # generate random image
    image = np.random.normal(size=(100, 100, 3))
    image[20:80, 20:80] += 3.
    image[50] += 3.
    image[:, 50] += 3.
    image = ((image - image.min()) *
             (253. / (image.max() - image.min()))).astype(np.ubyte)
    return image
Exemplo n.º 12
0
def get_image():
    """Load an image from the demo-data repository if possible. Otherwise,
    just return a randomly generated image.
    """
    from vispy.io import load_data_file, read_png
    
    try:
        return read_png(load_data_file('mona_lisa/mona_lisa_sm.png'))
    except Exception as exc:
        # fall back to random image
        print("Error loading demo image data: %r" % exc)

    # generate random image
    image = np.random.normal(size=(100, 100, 3))
    image[20:80, 20:80] += 3.
    image[50] += 3.
    image[:, 50] += 3.
    image = ((image - image.min()) *
             (253. / (image.max() - image.min()))).astype(np.ubyte)
    
    return image
Exemplo n.º 13
0
n = 200
freq = 10
fs = 100.
t = np.arange(n) / fs
tone = np.sin(2*np.pi*freq*t)
noise = np.random.RandomState(0).randn(n)
signal = tone + noise
magnitude = np.abs(np.fft.fft(signal))
freqs = np.fft.fftfreq(n, 1. / fs)
flim = n // 2

# Signal
fig = plt.figure()
ax = plt.subplot(311)
ax.imshow(read_png(load_data_file('pyplot/logo.png')))

ax = plt.subplot(312)
ax.plot(t, signal, 'k-')

# Frequency content
ax = plt.subplot(313)
idx = np.argmax(magnitude[:flim])
ax.text(freqs[idx], magnitude[idx], 'Max: %s Hz' % freqs[idx],
        verticalalignment='top')
ax.plot(freqs[:flim], magnitude[:flim], 'r-o')

plt.draw()

# NOTE: show() has currently been overwritten to convert to vispy format, so:
# 1. It must be called to show the results, and
Exemplo n.º 14
0
n = 200
freq = 10
fs = 100.
t = np.arange(n) / fs
tone = np.sin(2 * np.pi * freq * t)
noise = np.random.RandomState(0).randn(n)
signal = tone + noise
magnitude = np.abs(np.fft.fft(signal))
freqs = np.fft.fftfreq(n, 1. / fs)
flim = n // 2

# Signal
fig = plt.figure()
ax = plt.subplot(311)
ax.imshow(read_png(load_data_file('pyplot/logo.png')))

ax = plt.subplot(312)
ax.plot(t, signal, 'k-')

# Frequency content
ax = plt.subplot(313)
idx = np.argmax(magnitude[:flim])
ax.text(freqs[idx],
        magnitude[idx],
        'Max: %s Hz' % freqs[idx],
        verticalalignment='top')
ax.plot(freqs[:flim], magnitude[:flim], 'k-o')

plt.draw()
Exemplo n.º 15
0
    def __init__(self, surface, bed="img\seabed.png", size=(600, 600)):
        # app window dimensions
        self.width = size[0]
        self.height = size[1]

        # set method - delta is 1. Parametrize just v and sigma
        self.resolver = RungeKutta(method="vertical", is_shallow=False)

        # initial time to count heights of points
        self.time = 0

        app.Canvas.__init__(self, size=(self.width, self.height), title='Waves Surface Simulator')

        self.surface = surface
        self.h_description = None
        self.bed = io.read_png(bed)
        self.triangles = gloo.IndexBuffer(self.surface.triangulation())
        self.sun = Sun(np.asarray([0, 1, 0.1], dtype=np.float32))

        skybox = Skybox(front="../img/skybox/sky-front.png", back="../img/skybox/sky-back.png",
                        left="../img/skybox/sky-left.png", right="../img/skybox/sky-right.png",
                        up="../img/skybox/sky-up.png", down="../img/skybox/sky-down.png")

        position = self.surface.position()

        self.program = gloo.Program(shaders.vert_shader, shaders.frag_shader)
        self.programSkybox = gloo.Program(shaders.vert_shader_skybox, shaders.frag_shader_skybox)

        self.program['a_position'] = position
        self.programSkybox['a_position'] = position

        self.program['u_bed_texture'] = gloo.Texture2D(self.bed, wrapping='repeat', interpolation='linear')

        self.program['u_skybox'] = gloo.TextureCubeMap(data=skybox.texture, interpolation='linear', wrapping='clamp_to_edge', internalformat='rgb32f')
        self.programSkybox['u_skybox'] = gloo.TextureCubeMap(data=skybox.texture, interpolation='linear', wrapping='clamp_to_edge', internalformat='rgb32f')

        self.program['u_eye_height'] = 3
        self.program['u_alpha'] = 0.5
        self.program['u_bed_depth'] = 0.8

        self.program['u_sun_direction'] = self.sun.normalized_direction()
        self.program['u_sun_diffused_color'] = self.sun.diffused_color()
        self.program['u_sun_reflected_color'] = self.sun.reflected_color()

        # GUI set up
        self.camera = np.array([0, 0, 1], dtype=np.float32)
        self.up = np.array([0, 1, 0], dtype=np.float32)
        self.set_camera()

        self.drag_start = None
        self.diffused_flag = True
        self.reflected_flag = True
        self.bed_flag = True
        self.depth_flag = True
        self.sky_flag = True
        self.bed_type = "normal"
        self.stop_flag = False
        self.apply_flags()

        self.timer = app.Timer('auto', connect=self.on_timer, start=True)
        self.activate_zoom()
        self.show()
Exemplo n.º 16
0
    gl_FragColor = textureCube(a_texture, v_texcoord);
}
"""

vertices = np.array([[+1, +1, +1], [-1, +1, +1], [-1, -1, +1], [+1, -1, +1],
                     [+1, -1, -1], [+1, +1, -1], [-1, +1, -1],
                     [-1, -1, -1]]).astype(np.float32)
faces = np.array([
    vertices[i] for i in
    [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 6, 7, 2, 1, 7, 4, 3, 2, 4, 7, 6, 5]
])
indices = np.resize(np.array([0, 1, 2, 0, 2, 3], dtype=np.uint32), 36)
indices += np.repeat(4 * np.arange(6, dtype=np.uint32), 6)

texture = np.zeros((6, 1024, 1024, 3), dtype=np.float32)
texture[2] = read_png(load_data_file("skybox/sky-left.png")) / 255.
texture[3] = read_png(load_data_file("skybox/sky-right.png")) / 255.
texture[0] = read_png(load_data_file("skybox/sky-front.png")) / 255.
texture[1] = read_png(load_data_file("skybox/sky-back.png")) / 255.
texture[4] = read_png(load_data_file("skybox/sky-up.png")) / 255.
texture[5] = read_png(load_data_file("skybox/sky-down.png")) / 255.


class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(1024, 1024),
                            title='Skybox example',
                            keys='interactive')

        self.cubeSize = 10
Exemplo n.º 17
0
def load_star_image():
    #fname = io.load_data_file('galaxy/star-particle.png')
    raw_image = io.read_png('helper_files/star-particle.png')
    return raw_image
Exemplo n.º 18
0
    def __init__(self, keys='interactive', size=(400, 550), **kwargs):
        self._canvas = scene.SceneCanvas(keys=keys, size=size, **kwargs)
        self._view = self._canvas.central_widget.add_view()

        self._gloveImage = scene.visuals.Image(
            read_png("../plotting/img/glove.png"),
            interpolation='nearest',
            parent=self._view.scene,
            method='subdivide')

        self._thumb = Text("flex:\n0",
                           pos=(104, 261),
                           color='k',
                           font_size=10,
                           bold=True,
                           parent=self._gloveImage)
        self._index = Text("flex:\n0",
                           pos=(166, 171),
                           color='k',
                           font_size=10,
                           bold=True,
                           parent=self._gloveImage)
        self._middle = Text("flex:\n0",
                            pos=(225, 171),
                            color='k',
                            font_size=10,
                            bold=True,
                            parent=self._gloveImage)
        self._ring = Text("flex:\n0",
                          pos=(283, 171),
                          color='k',
                          font_size=10,
                          bold=True,
                          parent=self._gloveImage)
        self._little = Text("flex:\n0",
                            pos=(342, 171),
                            color='k',
                            font_size=10,
                            bold=True,
                            parent=self._gloveImage)

        Text("yaw:  ",
             pos=(40, 400),
             color='b',
             font_size=10,
             bold=True,
             parent=self._gloveImage)
        Text("pitch:",
             pos=(40, 425),
             color='#00d200',
             font_size=10,
             bold=True,
             parent=self._gloveImage)
        Text("roll:   ",
             pos=(40, 450),
             color='r',
             font_size=10,
             bold=True,
             parent=self._gloveImage)

        self._yaw = Text("0",
                         pos=(100, 400),
                         color='b',
                         font_size=10,
                         bold=True,
                         parent=self._gloveImage)
        self._pitch = Text("0",
                           pos=(100, 425),
                           color='#00d200',
                           font_size=10,
                           bold=True,
                           parent=self._gloveImage)
        self._roll = Text("0",
                          pos=(100, 450),
                          color='r',
                          font_size=10,
                          bold=True,
                          parent=self._gloveImage)

        self._canvas.show()
Exemplo n.º 19
0
void main()
{
    gl_FragColor = textureCube(a_texture, v_texcoord);
}
"""

vertices = np.array([[+1, +1, +1], [-1, +1, +1], [-1, -1, +1], [+1, -1, +1],
                     [+1, -1, -1], [+1, +1, -1], [-1, +1, -1], [-1, -1, -1]]).astype(np.float32)
faces = np.array([vertices[i] for i in [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1,
                                        6, 7, 2, 1, 7, 4, 3, 2, 4, 7, 6, 5]])
indices = np.resize(np.array([0, 1, 2, 0, 2, 3], dtype=np.uint32), 36)
indices += np.repeat(4 * np.arange(6, dtype=np.uint32), 6)

texture = np.zeros((6, 1024, 1024, 3), dtype=np.float32)
texture[2] = read_png(load_data_file("skybox/sky-left.png"))/255.
texture[3] = read_png(load_data_file("skybox/sky-right.png"))/255.
texture[0] = read_png(load_data_file("skybox/sky-front.png"))/255.
texture[1] = read_png(load_data_file("skybox/sky-back.png"))/255.
texture[4] = read_png(load_data_file("skybox/sky-up.png"))/255.
texture[5] = read_png(load_data_file("skybox/sky-down.png"))/255.


class Canvas(app.Canvas):

    def __init__(self):
        app.Canvas.__init__(self, size=(1024, 1024), title='Skybox example',
                            keys='interactive')

        self.cubeSize = 10
        self.pressed = False
Exemplo n.º 20
0
    def __init__(self, surface, sky="fluffy_clouds.png", bed="seabed.png"):
        # store parameters
        self.surface = surface
        # read textures
        self.sky = io.read_png(sky)
        self.bed = io.read_png(bed)
        self.fish = io.read_png("fish2.png")
        self.fish2 = io.read_png("fish2.png")
        # create GL context
        app.Canvas.__init__(self,
                            size=(600, 600),
                            title="Water surface simulator")
        # Compile shaders and set constants
        self.program = gloo.Program(VS, FS_triangle)
        self.program_point = gloo.Program(VS, FS_point)
        pos = self.surface.position()
        self.program["a_position"] = pos
        self.program_point["a_position"] = pos
        self.program['u_sky_texture'] = gloo.Texture2D(self.sky,
                                                       wrapping='repeat',
                                                       interpolation='linear')
        self.program['u_bed_texture'] = gloo.Texture2D(self.bed,
                                                       wrapping='repeat',
                                                       interpolation='linear')
        self.program['u_fish_texture'] = gloo.Texture2D(self.fish)
        self.program['u_fish_texture2'] = gloo.Texture2D(self.fish2)
        self.program_point["u_eye_height"] = self.program["u_eye_height"] = 10
        self.program["u_alpha"] = 0.9
        self.program["u_bed_depth"] = 1
        self.program["u_fish_depth"] = 0.6
        self.program["u_fish_depth2"] = 0.4
        self.program["u_sun_direction"] = normalize([0, 0.9, 0.5])
        self.program["u_sun_direction2"] = normalize([0.5, 0.5, 0.0001])
        self.sun_direction2 = np.array([[1, 0, 0.5]], dtype=np.float32)
        self.program["u_sun_diffused_color"] = [1, 0.8, 1]
        self.program["u_sun_diffused_color2"] = [0, 0, 1]
        self.program["u_sun_reflected_color"] = [1, 0.8, 0.6]
        self.program["u_sun_reflected_color2"] = [1, 1, 0]
        self.program["fish_coord"] = [4, np.random.rand()]
        self.program["fish_speed"] = ((np.random.rand() + 1) / 100)
        self.program["fish_coord2"] = [7, np.random.rand()]
        self.program["fish_speed2"] = ((np.random.rand() + 1) / 100)
        self.triangles = gloo.IndexBuffer(self.surface.triangulation())
        # Set up GUI
        self.camera = np.array([0, 0, 1])
        self.up = np.array([0, 1, 0])
        self.set_camera()
        self.are_points_visible = False
        self.drag_start = None
        self.diffused_flag = True
        self.diffused_flag2 = False
        self.reflected_flag1 = True
        self.reflected_flag2 = False
        self.bed_flag = True
        self.fish_flag = True
        self.depth_flag = True
        self.sky_flag = True
        self.movement_state = False
        self.apply_flags()
        # Run everything
        self._timer = app.Timer('auto', connect=self.on_timer, start=True)
        self.activate_zoom()
        self.show()

        self.shift = False
        self.z = False
        self.x = False

        self.timerCounter = 0
Exemplo n.º 21
0
    def __init__(self,
                 surface,
                 sky="fluffy_clouds.png",
                 bed="seabed.png",
                 shademap_name="shademap.png"):
        app.Canvas.__init__(self, size=(600, 600), title="Water surface")
        gloo.set_state(clear_color=(0, 0, 0, 1), depth_test=True, blend=True)
        self.program = gloo.Program(VS, FS_triangle)
        self.program["a_position"] = surface.position()
        self.program["u_surf_size"] = self.size

        height_texture = surface.get_heights_in_norm_coords()
        self.program["u_height"] = gloo.Texture2D(height_texture,
                                                  wrapping='repeat',
                                                  interpolation='linear')

        depth_texture = surface.get_bed_depth()
        self.program["u_bed_depth"] = gloo.Texture2D(depth_texture,
                                                     wrapping='repeat',
                                                     interpolation='linear')

        self.program["a_dot"] = surface.dot_types

        sun = np.array([0., 0.5, 1], dtype=np.float32)
        self.sun = sun / np.linalg.norm(sun)
        self.program["u_sun_direction"] = self.sun
        self.program["u_sun_color"] = np.array([1, 0.8, 0.6], dtype=np.float32)
        ambient = [0.4, 0.4, 0.4]
        self.program["u_ambient_color"] = np.array(ambient, dtype=np.float32)

        self.sky = io.read_png(sky)
        self.program['u_sky_texture'] = gloo.Texture2D(
            self.sky, wrapping='mirrored_repeat', interpolation='linear')
        self.bed = io.read_png(bed)
        self.program['u_bed_texture'] = gloo.Texture2D(self.bed,
                                                       wrapping='repeat',
                                                       interpolation='linear')

        self.eye_height = 4.5
        self.eye_position = np.array([0., 0.])
        self.program["u_eye_height"] = self.eye_height
        self.program["u_eye_position"] = self.eye_position
        self.program["u_alpha"] = 0.4

        self.angle_x, self.angle_y, self.angle_z = 0, 0, 0
        self.program["u_angle"] = np.array(
            [self.angle_x, self.angle_y, self.angle_z])

        self.show_bed = 0
        self.program["u_show_bed"] = self.show_bed
        self.show_sky = 0
        self.program["u_show_sky"] = self.show_sky

        self.program["test"] = 0.

        self.triangles = gloo.IndexBuffer(surface.triangulation())
        # self.normal = surface.normal()
        # self.program["u_normal"] = gloo.Texture2D(self.normal, interpolation='linear')

        self.camera = np.array([0, 0, 1])
        self.up = np.array([0, 1, 0])

        self.t = 0
        self._timer = app.Timer('auto', connect=self.on_timer, start=True)

        self.activate_zoom()
        self.show()
Exemplo n.º 22
0
    def __init__(self, surface, bed, new_waves_class=None, size=(600, 600), 
            sky_img_path="D:\Documents\water-surface\water-surface/fluffy_clouds.png", 
            bed_img_path="D:\Documents\water-surface\water-surface/seabed.png",
            depth_img_path="D:\Documents\water-surface\water-surface/depth.png"):
        app.Canvas.__init__(self, size=size,
                            title="Water surface simulator")
        # запрещаем текст глубины depth_test (все точки будут отрисовываться),
        # запрещает смещивание цветов blend - цвет пикселя на экране равен gl_fragColor.
        gloo.set_state(clear_color=(0, 0, 0, 1), depth_test=True, blend=True)
        self.program = gloo.Program(vertex, fragment_triangle)
        self.program_point = gloo.Program(vertex, fragment_point)

        self.surface = surface
        self.surface_class = new_waves_class
        self.surface_wave_list = []
        self.add_wave_center((self.size[0] / 2, self.size[1] / 2))

        self.bed = bed
        self.sky_img = io.read_png(sky_img_path)
        self.bed_img = io.read_png(bed_img_path)
        io.write_png(depth_img_path, self.bed.depth())
        self.depth_img = io.read_png(depth_img_path)
        
        # xy координаты точек сразу передаем шейдеру, они не будут изменятся со временем
        self.program["a_position"] = self.surface.position()
        self.program_point["a_position"] = self.surface.position()

        self.program['u_sky_texture'] = gloo.Texture2D(
            self.sky_img, wrapping='repeat', interpolation='linear')
        self.program['u_bed_texture'] = gloo.Texture2D(
            self.bed_img, wrapping='repeat', interpolation='linear')
        
        self.program['u_bed_depth_texture'] = gloo.Texture2D(
            self.depth_img, wrapping='repeat', interpolation='linear')
            
        self.program_point["u_eye_height"] = self.program["u_eye_height"] = 3
        self.program["u_alpha"] = 0.3
        self.program["u_bed_depth"] = -0.5

        self.program["u_sun_direction"] = self.normalize([0, 1, 0.1])
        self.program["u_sun_diffused_color"] = [1, 0.8, 1]
        self.program["u_sun_reflected_color"] = [1, 0.8, 0.6]

        self.triangles = gloo.IndexBuffer(self.surface.triangulation())

        # Set up GUI
        self.camera = np.array([0, 0, 1])
        self.up = np.array([0, 1, 0])
        self.set_camera()
        self.are_points_visible = False
        self.drag_start = None
        self.diffused_flag = True
        self.reflected_flag = True
        self.bed_flag = True
        self.depth_flag = True
        self.sky_flag = True
        self.apply_flags()

        # Run
        self._timer = app.Timer('auto', connect=self.on_timer, start=True)
        self.activate_zoom()
        self.show()
Exemplo n.º 23
0
    def __init__(self,
                 surface,
                 sky="img/clouds.png",
                 bed="img/seabed.png",
                 size=(600, 600)):
        # app window dimensions
        self.width = size[0]
        self.height = size[1]

        # set method - delta is 1. Parametrize just v and sigma
        self.resolver = RungeKutta(method="vertical",
                                   is_shallow=True,
                                   borders=False)

        # initial time to count heights of points
        self.time = 0

        app.Canvas.__init__(self,
                            size=(self.width, self.height),
                            title='Circular Waves Surface Simulator')

        self.surface = surface
        self.h_description = None
        self.sky = io.read_png(sky)
        self.bed = io.read_png(bed)
        self.triangles = gloo.IndexBuffer(self.surface.triangulation())
        self.sun = Sun(np.asarray([0, 1, 0.1], dtype=np.float32))
        self.bed_resolver = Bed()

        position = self.surface.position()

        self.program = gloo.Program(shaders.vert_shader,
                                    shaders.frag_shader_triangle)
        self.program['a_position'] = position
        self.program['u_sky_texture'] = gloo.Texture2D(self.sky,
                                                       wrapping='repeat',
                                                       interpolation='linear')
        self.program['u_bed_texture'] = gloo.Texture2D(self.bed,
                                                       wrapping='repeat',
                                                       interpolation='linear')
        self.program['u_eye_height'] = 1
        self.program['u_alpha'] = 0.9
        #    self.program['u_bed_depth'] = 1
        self.program["a_bed_depth"] = self.bed_resolver.bed_depths("beach")
        self.program['u_sun_direction'] = self.sun.normalized_direction()
        self.program['u_sun_diffused_color'] = self.sun.diffused_color()
        self.program['u_sun_reflected_color'] = self.sun.reflected_color()

        self.program_point = gloo.Program(shaders.vert_shader,
                                          shaders.frag_shader_point)
        self.program_point['a_position'] = position
        self.program_point['u_eye_height'] = 1

        # GUI set up
        self.camera = np.array([0, 0, 1])
        self.up = np.array([0, 1, 0])
        self.set_camera()

        self.are_points_visible = False
        self.drag_start = None
        self.diffused_flag = True
        self.reflected_flag = True
        self.bed_flag = True
        self.depth_flag = True
        self.sky_flag = True
        self.bed_type = "normal"
        self.stop_flag = False
        self.apply_flags()

        self.timer = app.Timer('auto', connect=self.on_timer, start=True)
        self.activate_zoom()
        self.show()
Exemplo n.º 24
0
"""
import sys

from vispy import scene, app
from vispy.visuals.filters import IsolineFilter
from vispy.io import load_data_file, read_png

canvas = scene.SceneCanvas(keys='interactive')
canvas.size = 600, 800
canvas.show()

# Set up a viewbox to display the image with interactive pan/zoom
view = canvas.central_widget.add_view()

interpolation = 'bicubic'
img_data = read_png(load_data_file('mona_lisa/mona_lisa_sm.png'))
image = scene.visuals.Image(img_data, interpolation=interpolation,
                            parent=view.scene, method='impostor')
level = 10
iso = IsolineFilter(level=level, width=1., color='white')

# Set 2D camera (the camera will scale to the contents in the scene)
view.camera = scene.PanZoomCamera(aspect=1)
# flip y-axis to have correct aligment
view.camera.flip = (0, 1, 0)
# select face part
view.camera.rect = (160, 130, 240, 200)

canvas.title = ('Spatial Filtering using %s Filter - Isoline %d level'
                % (image.interpolation, iso.level))
Exemplo n.º 25
0
"""
import sys

from vispy import scene, app
from vispy.visuals.filters import IsolineFilter
from vispy.io import load_data_file, read_png

canvas = scene.SceneCanvas(keys='interactive')
canvas.size = 600, 800
canvas.show()

# Set up a viewbox to display the image with interactive pan/zoom
view = canvas.central_widget.add_view()

interpolation = 'bicubic'
img_data = read_png(load_data_file('mona_lisa/mona_lisa_sm.png'))
image = scene.visuals.Image(img_data,
                            interpolation=interpolation,
                            parent=view.scene,
                            method='impostor')
level = 10
iso = IsolineFilter(level=level, width=1., color='white')

# Set 2D camera (the camera will scale to the contents in the scene)
view.camera = scene.PanZoomCamera(aspect=1)
# flip y-axis to have correct aligment
view.camera.flip = (0, 1, 0)
# select face part
view.camera.rect = (160, 130, 240, 200)

canvas.title = ('Spatial Filtering using %s Filter - Isoline %d level' %
    def __init__(
        self,
        glsl,
        filename,
        interactive=True,
        output_size=None,
        render_size=None,
        position=None,
        start_time=0.,
        interval='auto',
        duration=None,
        always_on_top=False,
        paused=False,
        output=None,
        progress_file=None,
        ffmpeg_pipe=None,
        ):

        app.Canvas.__init__(
            self,
            keys=('interactive' if interactive else None),
            size=(render_size if render_size else output_size),
            position=None,
            title=filename,
            always_on_top=always_on_top,
            show=False,
            resizable=ffmpeg_pipe is None,
            )

        self._filename = filename
        self._interactive = interactive
        self._output_size = output_size
        self._render_size = \
            (render_size if render_size else output_size)
        self._output = output
        self._profile = False
        self._doubleFbo = True
        self._doubleFboid = 0
        self._paused = paused
        self._timer = None
        self._start_time = start_time
        self._interval = interval
        self._ffmpeg_pipe = ffmpeg_pipe

        # Determine number of frames to render

        if duration:
            assert interval != 'auto'
            self._render_frame_count = math.ceil(duration / interval) \
                + 1
        elif not interactive:
            self._render_frame_count = 1
        else:
            self._render_frame_count = None

        self._render_frame_index = 0

        clock = time.clock()
        self._clock_time_zero = clock - start_time
        self._clock_time_start = clock

        if position is not None:
            self.position = position
            
        self.set_BufX()
        self.init_BufX()
        self.set_Buf_channel_input()
        # Initialize with a "known good" shader program, so that we can set all
        # the inputs once against it.

        self.program = gloo.Program(vertex, fragment_template
                                    % error_shader)
        self.program['position'] = [
            (-1, -1),
            (-1, 1),
            (1, 1),
            (-1, -1),
            (1, 1),
            (1, -1),
            ]
        self.program['iMouse'] = (0., 0., 0., 0.)
        self.program['iSampleRate'] = 44100.0
        self.program['iTimeDelta'] = self._interval
        self.program['iGlobalTime'] = start_time
        self.program['iFrame'] = self._render_frame_index
        self.program['iOffset'] = (0., 0.)

        self.activate_zoom()

        self.set_Buf_uniform('position' , [
            (-1, -1),
            (-1, 1),
            (1, 1),
            (-1, -1),
            (1, 1),
            (1, -1),
            ])
        self.set_Buf_uniform('iMouse' , (0., 0., 0., 0.))
        self.set_Buf_uniform('iSampleRate' , 44100.0)
        self.set_Buf_uniform('iFrame' , self._render_frame_index)
        self.set_Buf_uniform('iGlobalTime' , start_time)
        self.set_Buf_uniform('iOffset' , (0., 0.))
        self.set_Buf_uniform('iResolution' , (self.physical_size[0],
                    self.physical_size[1], 0.))
        self.set_Buf_uniform('iTimeDelta' , self._interval)

        try:
            self.set_texture_input(read_png('0.png'), i=0)
            self.set_Buf_texture_input(read_png('0.png'), i=0)
        except FileNotFoundError:
            self.set_texture_input(noise(resolution=256, nchannels=3), i=0)
            self.set_Buf_texture_input(noise(resolution=256, nchannels=3), i=0)
        try:
            self.set_texture_input(read_png('1.png'), i=1)
            self.set_Buf_texture_input(read_png('1.png'), i=1)
        except FileNotFoundError:
            self.set_texture_input(noise(resolution=256, nchannels=3), i=1)
            self.set_Buf_texture_input(noise(resolution=256, nchannels=3), i=1)
        try:
            self.set_texture_input(read_png('2.png'), i=2)
            self.set_Buf_texture_input(read_png('2.png'), i=2)
        except FileNotFoundError:
            self.set_texture_input(noise(resolution=256, nchannels=3), i=2)
            self.set_Buf_texture_input(noise(resolution=256, nchannels=3), i=2)
        try:
            self.set_texture_input(read_png('3.png'), i=3)
            self.set_Buf_texture_input(read_png('3.png'), i=3)
        except FileNotFoundError:
            self.set_texture_input(noise(resolution=256, nchannels=3), i=3)
            self.set_Buf_texture_input(noise(resolution=256, nchannels=3), i=3)
            
        self.set_channel_input()
        self.set_shader(glsl)

        if interactive:
            if not paused:
                self.ensure_timer()
            self.show()
        else:
            self._tile_index = 0
            self._tile_count = (output_size[0] + render_size[0] - 1) \
                // render_size[0] * ((output_size[1] + render_size[1]
                    - 1) // render_size[1])
            self._tile_coord = [0, 0]
            self._progress_file = progress_file

            # Note that gloo.Texture2D and gloo.RenderBuffer use the numpy convention for dimensions ('shape'),
            # i.e., HxW

            self._rendertex = gloo.Texture2D(shape=render_size[::-1]
                    + (4, ))
            self._fbo = gloo.FrameBuffer(self._rendertex,
                    gloo.RenderBuffer(shape=render_size[::-1]))

            # Allocate buffer to hold final image

            self._img = numpy.zeros(shape=self._output_size[::-1] + (4,
                                    ), dtype=numpy.uint8)

            # Write progress file now so we'll know right away if there are any problems writing to it

            if self._progress_file:
                self.write_img(self._img, self._progress_file)

            self.program['iResolution'] = self._output_size + (0., )
            self.ensure_timer()
Exemplo n.º 27
0
    def __init__(self, surface, sky, bed):
        self.surface = surface
        self.sky = io.read_png(sky)
        self.bed = io.read_png(bed)
        app.Canvas.__init__(self,
                            size=(800, 800),
                            position=(500, 100),
                            title="Waving Water")
        gloo.set_state(clear_color=(1, 1, 1, 1))

        # Create shaders
        self.program_main = gloo.Program(Shaders.MAIN_VERTEX_SHADER,
                                         Shaders.MAIN_FRAGMENT_SHADER)
        self.program_point = gloo.Program(Shaders.MAIN_VERTEX_SHADER,
                                          Shaders.POINT_FRAGMENT_SHADER)
        self.program_background = gloo.Program(
            Shaders.BACKGROUND_VERTEX_SHADER,
            Shaders.BACKGROUND_FRAGMENT_SHADER)
        self.program_caustics = gloo.Program(Shaders.CAUSTICS_VERTEX_SHADER,
                                             Shaders.CAUSTICS_FRAGMENT_SHADER)

        # Set values
        positions = self.surface.position()
        self.program_main["a_position"] = positions
        self.program_point["a_position"] = positions
        self.program_caustics["a_position"] = positions
        self.program_background['a_position'] = np.array(
            [[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]],
            dtype=np.float32)
        self.program_main['u_sky_texture'] = self.program_background['u_sky_texture'] = \
            gloo.Texture2D(self.sky, wrapping='repeat', interpolation='linear')
        self.program_main['u_bed_texture'] = self.program_background['u_bed_texture'] = \
            gloo.Texture2D(self.bed, wrapping='repeat', interpolation='linear')
        self.program_point["u_eye_height"] = self.program_main["u_eye_height"] = \
            self.program_background['u_eye_height'] = self.program_caustics["u_eye_height"] = 0.4
        self.program_main["u_alpha"] = \
            self.program_caustics["u_alpha"] = 0.7
        self.program_main["u_bed_depth"] = self.program_background['u_bed_depth'] = \
            self.program_caustics["u_bed_depth"] = 0.5
        self.program_main["u_sun_direction"] = self.program_background['u_sun_direction'] = \
            self.program_caustics["u_sun_direction"] = Canvas.normalize([0, 0, 1])
        self.program_main["u_sun_diffused_color"] = [1, 1, 0.5]
        self.program_main["u_sun_reflected_color"] = self.program_background[
            'u_sun_reflected_color'] = [1, 1, 0.5]
        self.program_main["u_water_ambient_color"] = \
            self.program_background['u_water_ambient_color'] = [0.5, 0.75, 0.9]
        self.triangles = gloo.IndexBuffer(self.surface.triangulation())
        self.triangles_background = gloo.IndexBuffer(
            np.array([[0], [1], [2], [2], [3], [0]], dtype=np.uint16))

        # GUI
        self.camera = np.array([0, 0, 1])
        self.up = np.array([0, 1, 0])
        self.set_camera()
        self.are_points_visible = False
        self.drag_start = None
        self.diffused_flag = True
        self.reflected_flag = True
        self.bed_flag = True
        self.depth_flag = True
        self.sky_flag = True
        self.caustics_flag = False
        self.apply_flags()

        # Run everything
        self._timer = app.Timer(connect=self.on_timer, start=True)
        self.activate_zoom()
        self.show()
Exemplo n.º 28
0
def load_galaxy_star_image():
    fname = io.load_data_file('galaxy/star-particle.png')
    raw_image = io.read_png(fname)

    return raw_image