コード例 #1
0
TURN_LEFT = {NORTH: WEST, WEST: SOUTH, SOUTH: EAST, EAST: NORTH}
TURN_RIGHT = {NORTH: EAST, EAST: SOUTH, SOUTH: WEST, WEST: NORTH}

SIZE = 100.0
BLOCK_SIZE = 4.0

# Setup display and initialise pi3d
DISPLAY = pi3d.Display.create(x=100, y=100, frames_per_second=10)
DISPLAY.set_background(0.4, 0.8, 0.8, 1)  # r,g,b,alpha
#========================================
CAMERA = pi3d.Camera()
LIGHT = pi3d.Light(lightamb=(0.6, 0.6, 0.8))
# load shader
shader = pi3d.Shader("uv_light")
flatsh = pi3d.Shader("uv_flat")
foodTex = pi3d.Texture("textures/Raspi256x256.png")
partTex = pi3d.Texture("textures/world_map256x256.jpg")

ectex = pi3d.loadECfiles("textures/ecubes", "skybox_hall")
myecube = pi3d.EnvironmentCube(size=2.0 * SIZE, maptype="FACES", name="cube")
myecube.set_draw_details(shader, ectex)


class Food:
    def __init__(self, snake):
        self.snake = snake
        plane = pi3d.Plane(w=BLOCK_SIZE * 2.0, h=BLOCK_SIZE * 2.0)
        self.shape = pi3d.MergeShape()
        self.shape.add(plane, 0, 0, 0)
        self.shape.add(plane, 0, 0, 0, 0, 90, 0)
        self.shape.set_draw_details(shader, [foodTex])
コード例 #2
0
values 0 to 3. in nobottom is set to True then that image can be absent, the
drawing will use the previous image which is top
"""
import demo
import pi3d

# Setup display and initialise pi3d
DISPLAY = pi3d.Display.create(x=50, y=50)

shader = pi3d.Shader('shaders/uv_flat')
#========================================

#select the environment cube with 'box'...
box = 3
if box == 0:
    ectex = [pi3d.Texture('textures/ecubes/skybox_interstellar.jpg')]
    myecube = pi3d.EnvironmentCube(size=900.0, maptype='CROSS')
elif box == 1:
    ectex = [pi3d.Texture('textures/ecubes/SkyBox.jpg')]
    myecube = pi3d.EnvironmentCube(size=900.0, maptype='HALFCROSS')
elif box == 2:
    ectex = pi3d.loadECfiles('textures/ecubes',
                             'sbox_interstellar',
                             nobottom=True)
    myecube = pi3d.EnvironmentCube(size=900.0, maptype='FACES', nobottom=True)
else:
    ectex = pi3d.loadECfiles('textures/ecubes', 'skybox_hall')
    myecube = pi3d.EnvironmentCube(size=900.0, maptype='FACES')

myecube.set_draw_details(shader, ectex)
コード例 #3
0
args = parser.parse_args()
if args.radius:
    eyeRadius = args.radius

# A 2D camera is used, mostly to allow for pixel-accurate eye placement,
# but also because perspective isn't really helpful or needed here, and
# also this allows eyelids to be handled somewhat easily as 2D planes.
# Line of sight is down Z axis, allowing conventional X/Y cartesion
# coords for 2D positions.
cam = pi3d.Camera(is_3d=False, at=(0, 0, 0), eye=(0, 0, -1000))
shader = pi3d.Shader("uv_light")
light = pi3d.Light(lightpos=(0, -500, -500), lightamb=(.2, .2, .2))

# Load texture maps --------------------------------------------------------
irisMap = pi3d.Texture("graphics/iris.jpg",
                       mipmap=False,
                       filter=pi3d.GL_LINEAR)
scleraMap = pi3d.Texture("graphics/sclera.png",
                         mipmap=False,
                         filter=pi3d.GL_LINEAR,
                         blend=True)
scleraMapBackOfEye = pi3d.Texture("graphics/sclera_back.png",
                                  mipmap=False,
                                  filter=pi3d.GL_LINEAR,
                                  blend=True)

# U/V map may be useful for debugging texture placement; not normally used
#uvMap     = pi3d.Texture("graphics/uv.png"    , mipmap=False,
#              filter=pi3d.GL_LINEAR, blend=False, m_repeat=True)

# Initialize static geometry -----------------------------------------------
コード例 #4
0
ファイル: eyes.py プロジェクト: trodery/Pi_Eyes
	eyeRadius   = DISPLAY.height * 2 / 5
	eyePosition = DISPLAY.height / 2

# A 2D camera is used, mostly to allow for pixel-accurate eye placement,
# but also because perspective isn't really helpful or needed here, and
# also this allows eyelids to be handled somewhat easily as 2D planes.
# Line of sight is down Z axis, allowing conventional X/Y cartesion
# coords for 2D positions.
cam    = pi3d.Camera(is_3d=False, at=(0,0,0), eye=(0,0,-1000))
shader = pi3d.Shader("uv_light")
light  = pi3d.Light(lightpos=(0, -500, -500), lightamb=(0.2, 0.2, 0.2))


# Load texture maps --------------------------------------------------------

irisMap   = pi3d.Texture("graphics/iris.jpg"  , mipmap=False,
              filter=pi3d.GL_LINEAR)
scleraMap = pi3d.Texture("graphics/sclera.png", mipmap=False,
              filter=pi3d.GL_LINEAR, blend=True)
lidMap    = pi3d.Texture("graphics/lid.png"   , mipmap=False,
              filter=pi3d.GL_LINEAR, blend=True)
# U/V map may be useful for debugging texture placement; not normally used
#uvMap     = pi3d.Texture("graphics/uv.png"    , mipmap=False,
#              filter=pi3d.GL_LINEAR, blend=False, m_repeat=True)


# Initialize static geometry -----------------------------------------------

# Transform point lists to eye dimensions
scalePoints(pupilMinPts      , vb, eyeRadius)
scalePoints(pupilMaxPts      , vb, eyeRadius)
scalePoints(irisPts          , vb, eyeRadius)
コード例 #5
0
LOGGER = pi3d.Log.logger(__name__)

BACKGROUND_COLOR = (1.0, 1.0, 1.0, 0.0)
DISPLAY = pi3d.Display.create(background=BACKGROUND_COLOR)
WIDTH, HEIGHT = DISPLAY.width, DISPLAY.height
ZPLANE = 1000
fov = 2.0 * math.degrees(math.atan(HEIGHT / 2.0 / ZPLANE))

CAMERA = pi3d.Camera((0, 0, 0), (0, 0, -1.0),
                     (1, 1100, fov, WIDTH / float(HEIGHT)))
SHADER = pi3d.Shader('shaders/uv_flat')

TEXTURE_NAMES = [
    'textures/red_ball.png', 'textures/grn_ball.png', 'textures/blu_ball.png'
]
TEXTURES = [pi3d.Texture(t) for t in TEXTURE_NAMES]


def random_ball():
    """Return a ball with a random color, position and velocity."""
    return pi3d.Ball(shader=SHADER,
                     texture=random.choice(TEXTURES),
                     radius=random.uniform(MIN_BALL_SIZE, MAX_BALL_SIZE),
                     x=random.uniform(-WIDTH / 2.0, WIDTH / 2.0),
                     y=random.uniform(-HEIGHT / 2.0, HEIGHT / 2.0),
                     z=ZPLANE,
                     vx=random.uniform(-MAX_BALL_VELOCITY, MAX_BALL_VELOCITY),
                     vy=random.uniform(-MAX_BALL_VELOCITY, MAX_BALL_VELOCITY))


SPRITES = [random_ball() for b in range(MAX_BALLS)]
コード例 #6
0
 def __init__(self):
     wd = DISPLAY.width
     ht = DISPLAY.height
     asi_tex = pi3d.Texture("textures/airspeed_indicator.png")
     alt_tex = pi3d.Texture("textures/altimeter.png")
     rad_tex = pi3d.Texture("textures/radar.png")
     dot_tex = pi3d.Texture("textures/radar_dot.png")
     ndl_tex = pi3d.Texture("textures/instrument_needle.png")
     self.asi = pi3d.ImageSprite(asi_tex,
                                 FLATSH,
                                 camera=CAMERA2D,
                                 w=128,
                                 h=128,
                                 x=-128,
                                 y=-ht / 2 + 64,
                                 z=2)
     self.alt = pi3d.ImageSprite(alt_tex,
                                 FLATSH,
                                 camera=CAMERA2D,
                                 w=128,
                                 h=128,
                                 x=0,
                                 y=-ht / 2 + 64,
                                 z=2)
     self.rad = pi3d.ImageSprite(rad_tex,
                                 FLATSH,
                                 camera=CAMERA2D,
                                 w=128,
                                 h=128,
                                 x=128,
                                 y=-ht / 2 + 64,
                                 z=2)
     self.dot = pi3d.ImageSprite(dot_tex,
                                 FLATSH,
                                 camera=CAMERA2D,
                                 w=16,
                                 h=16,
                                 z=1)
     self.ndl1 = pi3d.ImageSprite(ndl_tex,
                                  FLATSH,
                                  camera=CAMERA2D,
                                  w=128,
                                  h=128,
                                  x=-128,
                                  y=-ht / 2 + 64,
                                  z=1)
     self.ndl2 = pi3d.ImageSprite(ndl_tex,
                                  FLATSH,
                                  camera=CAMERA2D,
                                  w=128,
                                  h=128,
                                  x=0,
                                  y=-ht / 2 + 64,
                                  z=1)
     self.ndl3 = pi3d.ImageSprite(ndl_tex,
                                  FLATSH,
                                  camera=CAMERA2D,
                                  w=128,
                                  h=128,
                                  x=128,
                                  y=-ht / 2 + 64,
                                  z=1)
     self.dot_list = []
     self.update_time = 0.0
コード例 #7
0
ファイル: Blur.py プロジェクト: rootkit/pi3d_demos
# Setup display and initialise pi3d
DISPLAY = pi3d.Display.create(x=10, y=10, w=900, h=600, frames_per_second=25)
DISPLAY.set_background(0.4, 0.6, 0.8, 1.0)  # r,g,b,alpha

persp_cam = pi3d.Camera.instance()  # default instance camera perspecive view
ortho_cam = pi3d.Camera(is_3d=False)  # 2d orthographic view camera

#setup textures, light position and initial model position
pi3d.Light((0, 5, 0))
#create shaders
shader = pi3d.Shader("uv_reflect")
flatsh = pi3d.Shader("uv_flat")
defocus = pi3d.Defocus()

#Create textures
shapeimg = pi3d.Texture("textures/straw1.jpg")
shapebump = pi3d.Texture("textures/floor_nm.jpg")
shapeshine = pi3d.Texture("textures/pong3.png")

#Create shape
myshape = pi3d.MergeShape(camera=persp_cam)  #specify perspective view
asphere = pi3d.Sphere(sides=16, slices=16)
myshape.radialCopy(asphere, step=72)
myshape.position(0.0, 0.0, 5.0)
myshape.set_draw_details(shader, [shapeimg, shapebump, shapeshine], 8.0, 0.1)

mysprite = pi3d.Sprite(w=10.0, h=10.0, camera=persp_cam)
mysprite.position(0.0, 0.0, 15.0)
mysprite.set_draw_details(flatsh, [shapebump])

tick = 0
コード例 #8
0
wv_height = lcm(weft_rpt, pick_rpt)

# extend each of the plans to the size of the sample
warp_plan = np.tile(warp_plan, (wv_width // warp_rpt))
weft_plan = weft_plan.reshape((weft_rpt, 1))  # make into vertical array
weft_plan = np.tile(weft_plan, (wv_height // weft_rpt, 1))
draft_plan = np.tile(draft_plan, (wv_width // draft_rpt))
peg_plan = np.tile(peg_plan, (wv_height // pick_rpt, 1))

lifts = peg_plan[:, draft_plan]  # generate an up/down map for the plan
# then fill it with the yarn for warp if it's up or weft if it's down
yarn_plan = lifts * warp_plan + (lifts * -1 + 1) * weft_plan
wv = yarn_colours[yarn_plan].astype(
    np.uint8)  # wv takes the [R,G,B] from yarn colours

clothimg = pi3d.Texture(wv)
########################################################################

# Setup display and initialise pi3d
DISPLAY = pi3d.Display.create(x=100, y=100, frames_per_second=30)
DISPLAY.set_background(0.4, 0.8, 0.8, 1.0)  # r,g,b,alpha
# yellowish directional light blueish ambient light
pi3d.Light(lightpos=(1, -1, -3),
           lightcol=(1.0, 1.0, 0.8),
           lightamb=(0.45, 0.5, 0.6))

#========================================

# load shader
shader = pi3d.Shader("uv_bump")
shinesh = pi3d.Shader("uv_reflect")
コード例 #9
0
    def __init__(self, parent, name, texture, *args, **kwargs):

        self.video = False
        self.audio = False
        self.video_speed = 1.0
        self.video_time = 0
        self.video_loop = 0

        if isinstance(texture, str):
            match = videos_formats.match(texture.lower())
            if match and match.string:

                try:
                    global cv2, video_support
                    import cv2
                    video_support = True
                except:
                    LOGGER.error('python-opencv is required to play videos')

                if parent.audio:
                    try:
                        global Player, audio_support
                        from mplayer import Player, CmdPrefix
                        Player.cmd_prefix = CmdPrefix.PAUSING_KEEP
                        audio_support = True
                    except:
                        LOGGER.warning(
                            'mplayer.py not found, video will play without audio'
                        )

                if audio_support:

                    self.audio = True

                    audiopath = texture + '.wav'
                    if not os.path.isfile(audiopath):
                        print('extracting audio stream to ' + audiopath)
                        subprocess.run([
                            'ffmpeg', '-i', texture, '-acodec', 'pcm_s16le',
                            '-ac', '2', audiopath
                        ])

                    mplayer_args = ['-vo', 'null']

                    if parent.audio == 'jack':
                        jackname = parent.name + '/' + name
                        if len(jackname) > 63:
                            jackname = jackname[0:62]
                        mplayer_args.append('-ao')
                        mplayer_args.append('jack:name=%s' % jackname)

                    self.audio_reader = Player(args=mplayer_args)
                    self.audio_reader.loadfile(texture + '.wav')
                    self.audio_bypass = 0
                    self.set_audio_bypass(1)

                if video_support:

                    self.video = True

                    self.video_reader = cv2.VideoCapture(texture)
                    self.video_shape = (int(
                        self.video_reader.get(cv2.CAP_PROP_FRAME_HEIGHT)),
                                        int(
                                            self.video_reader.get(
                                                cv2.CAP_PROP_FRAME_WIDTH)), 3)
                    self.video_blank_frame = numpy.zeros(self.video_shape,
                                                         dtype='uint8')
                    self.video_texture = pi3d.Texture(self.video_blank_frame,
                                                      mipmap=True)
                    self.frame_format = self.video_texture._get_format_from_array(
                        self.video_texture.image, self.video_texture.i_format)

                    self.video_frame_duration = 1. / min(
                        self.video_reader.get(cv2.CAP_PROP_FPS), 60)
                    self.video_duration = self.video_frame_duration * self.video_reader.get(
                        cv2.CAP_PROP_FRAME_COUNT)

                    self.video_elapsed_time = 0

                    texture = self.video_texture

        super(Video, self).__init__(parent=parent,
                                    name=name,
                                    texture=texture,
                                    *args,
                                    **kwargs)

        if self.video:
            self.active_effects.append('VIDEO')
コード例 #10
0
min_size = float(MIN_BUG_SIZE) / MAX_BUG_SIZE
max_size = 1.0

KEYBOARD = pi3d.Keyboard()
LOGGER = pi3d.Log.logger(__name__)

BACKGROUND_COLOR = (0.3, 0.3, 0.3, 0.0)
DISPLAY = pi3d.Display.create(background=BACKGROUND_COLOR,
                              frames_per_second=20)
HWIDTH, HHEIGHT = DISPLAY.width / 2.0, DISPLAY.height / 2.0

CAMERA = pi3d.Camera(is_3d=False)
shader = pi3d.Shader("uv_pointsprite")

img = pi3d.Texture("textures/atlas01.png",
                   mipmap=False,
                   i_format=pi3d.GL_RGBA,
                   filter=pi3d.GL_NEAREST)
# i_format=pi3d.GL_LUMINANCE_ALPHA ## see what happens with a converted texture type
loc = np.zeros((MAX_BUGS, 3))
loc[:, 0] = np.random.uniform(-HWIDTH, HWIDTH, MAX_BUGS)
loc[:, 1] = np.random.uniform(-HHEIGHT, HHEIGHT, MAX_BUGS)
loc[:, 2] = np.random.normal(
    (min_size + max_size) / 2.0,
    (max_size - min_size) / 5.0, MAX_BUGS) + np.random.randint(1, 8, MAX_BUGS)
vel = np.random.uniform(-MAX_BUG_VELOCITY, MAX_BUG_VELOCITY, (MAX_BUGS, 2))

dia = np.remainder(loc[:, 2], 1.0) * MAX_BUG_SIZE
mass = dia * dia
radii = np.add.outer(
    dia, dia) / 7.0  # should be / 2.0 this will make bugs 'touch' when nearer
コード例 #11
0
import demo
import pi3d
from math import cos, sin, radians

# Setup display and initialise pi3d
DISPLAY = pi3d.Display.create(x=100, y=100, background=(0.2, 0.4, 0.6, 1))
shader = pi3d.Shader("uv_reflect")
flatsh = pi3d.Shader('uv_flat')
#========================================
# this is a bit of a one off because the texture has transparent parts
# comment out and google to see why it's included here.
from pi3d import opengles, GL_CULL_FACE
opengles.glDisable(GL_CULL_FACE)
#========================================
# load bump and reflection textures
bumptex = pi3d.Texture("textures/floor_nm.jpg")
shinetex = pi3d.Texture("textures/photosphere.jpg")
# load model_loadmodel
mymodel = pi3d.Model(file_string='models/teapot.obj', name='teapot')
mymodel.set_shader(shader)
mymodel.set_normal_shine(bumptex, 0.0, shinetex, 0.4)

mysphere = pi3d.Sphere(radius=400.0, rx=180, ry=180, invert=True)
mysphere.set_draw_details(flatsh, [shinetex])

# Fetch key presses
mykeys = pi3d.Keyboard()
mymouse = pi3d.Mouse(restrict=False)
mymouse.start()

omx, omy = mymouse.position()
コード例 #12
0
sla = np.zeros((SLW, SLH, 4), dtype=np.uint8)
sla[:,:,3] = 255

# Setup display and initialise pi3d
DISPLAY = pi3d.Display.create(#x=100, y=100,
                         background=(0.2, 0.4, 0.6, 1))
shader = pi3d.Shader("uv_reflect")
flatsh = pi3d.Shader('uv_flat')
#========================================
# this is a bit of a one off because the texture has transparent parts
# comment out and google to see why it's included here.
from pi3d import opengles, GL_CULL_FACE
opengles.glDisable(GL_CULL_FACE)
#========================================
# load bump and reflection textures
bumptex = pi3d.Texture("/home/pi/Develop/pi3d/pi3d_demos/textures/floor_nm.jpg")
shinetex = pi3d.Texture(npa)

# load model_loadmodel
mymodel = pi3d.Model(file_string='/home/pi/Develop/pi3d/pi3d_demos/models/teapot.obj', name='teapot')
mymodel.set_shader(shader)
mymodel.set_normal_shine(bumptex, 0.0, shinetex, 0.7)

mysphere = pi3d.Sphere(radius=400.0, rx=180, ry=180, invert=True)
mysphere.set_draw_details(flatsh, [shinetex], vmult=3.0, umult=3.0)

# Fetch key presses
mykeys = pi3d.Keyboard()
mymouse = pi3d.Mouse(restrict=False)
mymouse.start()
コード例 #13
0
ファイル: slide.py プロジェクト: PlagiatBros/pytaVSL
    def __init__(self,
                 parent,
                 name,
                 texture,
                 width=None,
                 height=None,
                 init_z=0.0,
                 mesh_size=[1, 1]):

        if type(texture) is str:

            texture = pi3d.Texture(texture, flip=True)

        super(SlideBase,
              self).__init__(w=width if width is not None else texture.ix,
                             h=height if height is not None else texture.iy,
                             mesh_size=mesh_size)

        self.name = name
        self.parent = parent
        self.server = parent.server
        self.parent_slide = None

        self.is_clone = False
        self.clone_target = None

        if texture:
            self.set_textures([texture])

        self.visible = 0

        # Color
        self.color = [0.5, 0.5, 0.5]
        self.color_strobe = 0
        self.color_alpha = 1.0

        # Position
        self.pos_x = 0.0
        self.pos_y = 0.0
        self.pos_z = init_z
        self.init_z = init_z

        # Alignment
        self.h_align = 'center'
        self.v_align = 'center'

        # Scale
        self.init_scale = min(self.parent.width / self.width,
                              self.parent.height / self.height)
        self.sx = 1.0
        self.sy = 1.0

        # Rotate
        self.rx = 0.0
        self.ry = 0.0
        self.rz = 0.0

        # texture tiling
        self.tiles = [1.0, 1.0]
        self.offset = [0.0, 0.0]

        self.loaded = False
        self.grouped = False

        # init
        self.set_zoom(1.0)
        self.set_position_z(self.pos_z)
コード例 #14
0
''' Polygon class creates a mesh of triangles to fill a line, joining the last point
back to the first. Escape to quit, 'w' enlarge, 's' shrink.

In this demo the edges are children of the polygon so their z distance is
negative to bring them nearer the camera.
'''
import demo
import pi3d
import numpy as np  # only needed for the demo of random colours after pressing space

display = pi3d.Display.create(frames_per_second=60,
                              background=(0.3, 0.3, 0.2,
                                          0.2))  # try using samples=4
shader = pi3d.Shader('uv_flat')
lineshader = pi3d.Shader('mat_flat')
tex = pi3d.Texture('textures/Raspi256x256.png')
camera = pi3d.Camera(is_3d=False)
''' using inkscape path tracing and a few lines of python '''
path = [[-11.2, -128.0], [-26.8, -119.4], [-40.7, -110.8], [-71.3, -90.9],
        [-78.9, -81.6], [-83.3, -70.6], [-88.6, -53.6], [-93.5, -43.0],
        [-98.4, -32.9], [-99.8, -20.6], [-97.9, -8.2], [-86.3, 8.8],
        [-82.8, 12.9], [-80.4, 22.6], [-76.3, 36.6], [-67.0, 48.5],
        [-60.2, 55.1], [-65.6, 59.4], [-73.0, 65.9], [-83.6, 81.0],
        [-89.4, 95.0], [-90.4, 106.6], [-89.1, 116.9], [-84.7, 119.5],
        [-79.7, 121.3], [-49.7, 128.0], [-28.0, 126.0], [-20.0, 123.0],
        [-15.1, 120.8], [-8.9, 115.9], [-2.2, 106.6], [1.5,
                                                       101.5], [4.4, 105.6],
        [11.1, 115.1], [18.0, 120.8], [22.9, 123.0], [41.8, 127.6],
        [64.7, 126.6], [74.9, 124.1], [82.7, 121.2], [87.6, 119.5],
        [91.5, 118.0], [90.4, 91.2], [89.3, 87.7], [86.9, 81.9], [84.5, 77.1],
        [75.2, 66.0], [63.0, 55.6], [59.9, 54.4], [65.5, 49.4], [75.6, 36.8],
コード例 #15
0
MIN_BALL_SIZE = 15 # z value is used to determine point size
MAX_BALL_SIZE = 75
MAX_BALL_VELOCITY = 3.0

min_dist = 1.001
max_dist = 0.001 + float(MAX_BALL_SIZE) / MIN_BALL_SIZE

BACKGROUND_COLOR = (0.0, 0.0, 0.0, 0.0)
DISPLAY = pi3d.Display.create(background=BACKGROUND_COLOR)
HWIDTH, HHEIGHT = DISPLAY.width / 2.0, DISPLAY.height / 2.0
KEYBOARD = pi3d.Keyboard()

CAMERA = pi3d.Camera(is_3d=False)
shader = pi3d.Shader("shaders/uv_sprite")

ballimg = [pi3d.Texture("textures/red_ball.png"),
           pi3d.Texture("textures/blu_ball.png"),
           pi3d.Texture("textures/grn_ball.png")]

loc = np.zeros((MAX_BALLS, 3))
loc[:,0] = np.random.uniform(-HWIDTH, HWIDTH, MAX_BALLS)
loc[:,1] = np.random.uniform(-HHEIGHT, HHEIGHT, MAX_BALLS)
loc[:,2] = np.random.uniform(min_dist, max_dist, MAX_BALLS)
vel = np.random.uniform(-MAX_BALL_VELOCITY, MAX_BALL_VELOCITY, (MAX_BALLS, 2))
dia = (MIN_BALL_SIZE + (max_dist - loc[:,2]) /
                (max_dist - min_dist) * (MAX_BALL_SIZE - MIN_BALL_SIZE))
mass = dia * dia
radii = np.add.outer(dia, dia) / 3.0 # should be / 2.0 this will make balls 'touch' when nearer

color = np.floor(np.random.uniform(0.0, 2.99999, (MAX_BALLS, 3))) 
コード例 #16
0
This demonstration also shows in a fairly rough way how lighting can be changed
as the view point moves (from inside to outside in this instance).
"""
import math

import demo
import pi3d

# Setup display and initialise pi3d
DISPLAY = pi3d.Display.create(x=150, y=150, background=(0.4, 0.8, 0.8, 1))
shader = pi3d.Shader("shaders/uv_reflect")
flatsh = pi3d.Shader("shaders/uv_flat")
#############################

# Load textures
blockimg = pi3d.Texture("textures/squareblocks4.png")
roofedgeimg = pi3d.Texture("textures/roofedging.png")
roofimg = pi3d.Texture("textures/Roof.png")
greenimg = pi3d.Texture("textures/squareblocks4green.png")
ectex = pi3d.loadECfiles("textures/ecubes", "sbox", "jpg")
myecube = pi3d.EnvironmentCube(size=900.0, maptype="FACES")
myecube.set_draw_details(flatsh, ectex)

# Create elevation map
mapwidth = 1000.0
mapdepth = 1000.0
mapheight = 60.0
floorimg = pi3d.Texture("textures/dunes3_512.jpg")
bumpimg = pi3d.Texture("textures/mudnormal.jpg")
mymap = pi3d.ElevationMap(mapfile="textures/mountainsHgt2.png",
                          width=mapwidth,
コード例 #17
0
================================""")

SHADER = pi3d.Shader("shaders/uv_reflect")  #for objects to look 3D
FLATSH = pi3d.Shader(
    "shaders/uv_flat")  #for 'unlit' objects like the background

GRAVITY = 9.8  #m/s**2
LD = 10  #lift/drag ratio
DAMPING = 0.95  #reduce roll and pitch rate each update_variables
BOOSTER = 1.5  #extra manoevreability boost to defy 1st Low of Thermodynamics.
#load bullet images
BULLET_TEX = []  #list to hold Texture refs
iFiles = glob.glob("textures/biplane/bullet??.png")
iFiles.sort()  # order is vital to animation!
for f in iFiles:
    BULLET_TEX.append(pi3d.Texture(f))
DAMAGE_FACTOR = 50  #dived by distance of shoot()
NR_TM = 1.0  #check much less frequently until something comes back
FA_TM = 5.0
NR_DIST = 250
FA_DIST = 1500
P_FACTOR = 0.001
I_FACTOR = 0.00001


#define Aeroplane class
class Aeroplane(object):
    def __init__(self, model, recalc_time, refid):
        self.refid = refid
        self.recalc_time = recalc_time  #in theory use different values for enemy
        self.x, self.y, self.z = 0.0, 0.0, 0.0
コード例 #18
0
ファイル: DogFight.py プロジェクト: celesteh/pi3d_demos
CAMERA = pi3d.Camera(lens=(1.0, 10000.0, 55.0, 1.6))
CAMERA2D = pi3d.Camera(is_3d=False)

print("""===================================
== W increase power, S reduce power
== V view mode, C control mode
== B brakes
== mouse movement joystick
== Left button fire!
== X jumps to location of 1st enemy in list
================================""")

SHADER = pi3d.Shader("uv_bump")  #for objects to look 3D
FLATSH = pi3d.Shader("uv_flat")  #for 'unlit' objects like the background

flatwhite = pi3d.Texture("textures/white.png")
xoffset = 0  #-13.799986457824705
yoffset = 0  #-189.01106018066403
zoffset = 0  #-22.439974822998053

GRAVITY = 9.8  #m/s**2
LD = 10  #lift/drag ratio
DAMPING = 0.95  #reduce roll and pitch rate each update_variables
BOOSTER = 1.5  #extra manoevreability boost to defy 1st Low of Thermodynamics.
#load bullet images
BULLET_TEX = []  #list to hold Texture refs
iFiles = glob.glob(sys.path[0] + "/textures/biplane/bullet??.png")
iFiles.sort()  # order is vital to animation!
for f in iFiles:
    BULLET_TEX.append(pi3d.Texture(f))
DAMAGE_FACTOR = 50  #dived by distance of shoot()
コード例 #19
0
                              background=BACKGROUND_COLOR,
                              display_config=pi3d.DISPLAY_CONFIG_HIDE_CURSOR
                              | pi3d.DISPLAY_CONFIG_MAXIMIZED,
                              use_glx=True)

cam = pi3d.Camera(is_3d=False)

#========================================

# load shaders
flatsh = pi3d.Shader("uv_flat")
postsh = pi3d.Shader('post_pixelize')
post = pi3d.PostProcess(camera=cam, shader=postsh, scale=SCALE)

# Create texture for video
tex = pi3d.Texture(
    image)  # can pass numpy array or PIL.Image rather than path as string

# Create 2D flat sprite for the video texture
sprite = pi3d.Sprite(camera=cam, w=display.width, h=display.height)
sprite.set_shader(flatsh)
sprite.set_draw_details(flatsh, [tex])

## interactive inputs ##
kbd = pi3d.Keyboard()
mouse = pi3d.Mouse()  # pi3d.Mouse(restrict = True) # changes input coordinates
mouse.start()
MX, MY = mouse.position()
MXC, MYC = mouse.position()
MC = mouse.button_status(
)  # 8 = hover, 9 = right Click down, 10 = left C, 12 = middle C
MouseClicked = False
コード例 #20
0
import pi3d
from vrzero import engine

# VR Zero init, must be done *before* Pi3D setup.
engine.init()

# Pi3D scene setup...

shader = pi3d.Shader("uv_light")
shinesh = pi3d.Shader("uv_reflect")
flatsh = pi3d.Shader("uv_flat")
matsh = pi3d.Shader("mat_reflect")
##########################################
# Load textures
patimg = pi3d.Texture("textures/PATRN.PNG")
coffimg = pi3d.Texture("textures/COFFEE.PNG")
shapebump = pi3d.Texture("textures/floor_nm.jpg")
shapeshine = pi3d.Texture("textures/stars.jpg")
light = pi3d.Light(lightpos=(-1.0, 0.0, 10.0),
                   lightcol=(3.0, 3.0, 2.0),
                   lightamb=(0.02, 0.01, 0.03),
                   is_point=True)

#Create inbuilt shapes
mysphere = pi3d.Sphere(radius=1,
                       sides=24,
                       slices=24,
                       name="sphere",
                       x=-4,
                       y=2,
コード例 #21
0
if args.radius:
    eyeRadius = args.radius

# A 2D camera is used, mostly to allow for pixel-accurate eye placement,
# but also because perspective isn't really helpful or needed here, and
# also this allows eyelids to be handled somewhat easily as 2D planes.
# Line of sight is down Z axis, allowing conventional X/Y cartesion
# coords for 2D positions.
cam = pi3d.Camera(is_3d=False, at=(0, 0, 0), eye=(0, 0, -1000))
shader = pi3d.Shader("uv_light")
light = pi3d.Light(lightpos=(0, -500, -500), lightamb=(0.2, 0.2, 0.2))

# Load texture maps --------------------------------------------------------

scleraMap = pi3d.Texture("graphics/sclera.png",
                         mipmap=False,
                         filter=pi3d.GL_LINEAR,
                         blend=True)

# U/V map may be useful for debugging texture placement; not normally used
#uvMap     = pi3d.Texture("graphics/uv.png"    , mipmap=False,
#              filter=pi3d.GL_LINEAR, blend=False, m_repeat=True)

# Initialize static geometry -----------------------------------------------

# Transform point lists to eye dimensions
scalePoints(scleraFrontPts, vb, eyeRadius)
scalePoints(scleraBackPts, vb, eyeRadius)
scalePoints(scleraFrontPtsBackOfEye, vbBackOfEye, eyeRadius)
scalePoints(scleraBackPtsBackOfEye, vbBackOfEye, eyeRadius)

# Generate scleras for each eye...start with a 2D shape for lathing...
コード例 #22
0
"""


FOG = ((0.3, 0.3, 0.4, 0.8), 650.0)
TFOG = ((0.2, 0.24, 0.22, 1.0), 150.0)


#myecube = pi3d.EnvironmentCube(900.0,"HALFCROSS")
ectex=pi3d.loadECfiles("textures/ecubes","sbox")
myecube = pi3d.EnvironmentCube(size=900.0, maptype="FACES", name="cube")
myecube.set_draw_details(flatsh, ectex)

# Create elevation map
mapsize = 1000.0
mapheight = 60.0
mountimg1 = pi3d.Texture("textures/mountains3_512.jpg")
mymap = pi3d.ElevationMap("textures/mountainsHgt.png", name="map",
                     width=mapsize, depth=mapsize, height=mapheight,
                     divx=32, divy=32) 
mymap.set_draw_details(shader, [mountimg1, bumpimg, reflimg], 128.0, 0.0)
mymap.set_fog(*FOG)

"""
#Create tree models
treeplane = pi3d.Plane(w=4.0, h=5.0)

treemodel1 = pi3d.MergeShape(name="baretree")
treemodel1.add(treeplane.buf[0], 0,0,0)
treemodel1.add(treeplane.buf[0], 0,0,0, 0,90,0)

treemodel2 = pi3d.MergeShape(name="bushytree")
コード例 #23
0
""" GPU doing conways game of life. ESC to quit
this shows how it is possible to recycle images from the renderbuffer
and use the very fast processing speed of the GPU to do certain tasks.
"""
import ctypes
import demo
import pi3d

WIDTH = 800
HEIGHT = 800
DISPLAY = pi3d.Display.create(w=WIDTH, h=HEIGHT)
CAMERA = pi3d.Camera(is_3d=False)
shader = pi3d.Shader("conway")

tex = []
tex.append(pi3d.Texture("textures/Roof.png", mipmap=False))
tex.append(pi3d.Texture("textures/Roof.png", mipmap=False))
sprite = pi3d.Sprite(camera=CAMERA, w=WIDTH, h=HEIGHT, x=0.0, y=0.0, z=1.0)
sprite.set_draw_details(shader, [tex[0]])
sprite.set_2d_size(WIDTH, HEIGHT, 0.0,
                   0.0)  # used to get pixel scale by shader

ti = 0  # variable to toggle between two textures
mykeys = pi3d.Keyboard()

while DISPLAY.loop_running():
    sprite.draw()

    ti = (ti + 1) % 2
    pi3d.opengles.glBindTexture(pi3d.GL_TEXTURE_2D, tex[ti]._tex)
    pi3d.opengles.glCopyTexImage2D(pi3d.GL_TEXTURE_2D, 0, pi3d.GL_RGB, 0, 0,
コード例 #24
0
    def __init__(self, texture_path, width, height, pixel_size, camera):
        self.width = width
        self.height = height

        texture = Image.open(texture_path)
        texture_width = texture.size[0]
        texture_height = texture.size[1]

        if texture_width != texture_height:
            raise ValueError('The texture must be square.')

        if width > texture_width or height > texture_height:
            raise ValueError(
                'The texture must be larger than the display area.')

        self.num_pixels_w = int(width / pixel_size)
        self.num_pixels_h = int(height / pixel_size)

        point_size = 1.0 * float(pixel_size / texture_width)

        shader = pi3d.Shader("uv_pointsprite")
        img = pi3d.Texture(texture_path,
                           mipmap=False,
                           i_format=pi3d.GL_RGBA,
                           filter=pi3d.GL_NEAREST)

        self.loc = np.zeros((self.num_pixels_w * self.num_pixels_h, 3))
        uv = np.zeros((self.num_pixels_w * self.num_pixels_h, 2))

        # Constant arrays for efficiency
        sorted_row = np.arange(self.num_pixels_w)
        self.sorted_x_positions = np.arange(
            pixel_size / 2, pixel_size / 2 + (pixel_size * self.num_pixels_w),
            pixel_size)
        self.sorted_y_positions = np.arange(
            -pixel_size / 2,
            -pixel_size / 2 - (pixel_size * self.num_pixels_h), -pixel_size)
        texture_positions_x = np.linspace(0, point_size * self.num_pixels_w,
                                          self.num_pixels_w, False)
        texture_positions_y = np.linspace(0, point_size * self.num_pixels_h,
                                          self.num_pixels_h, False)
        self.initial_positions = np.random.rand(self.num_pixels_h,
                                                self.num_pixels_w).argsort()

        # Set starting positions
        for j in range(0, self.num_pixels_h):
            for i in range(0, self.num_pixels_w):
                index = self.initial_positions[j, i]
                self.loc[index + j * self.num_pixels_w,
                         0] = self.sorted_x_positions[i]
                self.loc[index + j * self.num_pixels_w,
                         1] = self.sorted_y_positions[j]
                self.loc[index + j * self.num_pixels_w,
                         2] = 0.999  # no scaling

                # Set textures
                uv[index + j * self.num_pixels_w,
                   0] = texture_positions_x[index]
                uv[index + j * self.num_pixels_w, 1] = texture_positions_y[j]

        # Rotation is not required.
        rot = np.zeros(
            (self.num_pixels_w * self.num_pixels_h, 3))  # :,0 for rotation
        rot[:, 1] = 999.999  # :,1 R, G
        rot[:, 2] = 999.999  # :,2 B, A

        super(ImageRandomiser, self).__init__(camera=camera,
                                              vertices=self.loc,
                                              normals=rot,
                                              tex_coords=uv,
                                              point_size=pixel_size)

        self.set_draw_details(shader, [img])
        self.unif[48] = point_size
コード例 #25
0
print("move this terminal window to top of screen to see FPS")
print("=====================================================")

# Setup display and initialise pi3d
DISPLAY = pi3d.Display.create(x=200, y=150, frames_per_second=25.0)
DISPLAY.set_background(0.4, 0.6, 0.8, 0.5)  # r,g,b,alpha

#setup textures, light position and initial model position
pi3d.Light((5, -5, 8))
#create shaders
shader = pi3d.Shader("uv_reflect")
matsh = pi3d.Shader("mat_reflect")
flatsh = pi3d.Shader("uv_flat")

#Create textures
shapeimg = pi3d.Texture("textures/straw1.jpg")
shapebump = pi3d.Texture("textures/straw1.jpg", normal_map=-6.0)
waterbump = []
iFiles = glob.glob("textures/water/n_norm???.png")
iFiles.sort()  # order is vital to animation!
for f in iFiles:
    waterbump.append(pi3d.Texture(f))
num_n = len(waterbump)
shapeshine = pi3d.Texture("textures/stars.jpg")

#Create shape
myshape = pi3d.MergeShape()
num = (2, 2)
asphere = pi3d.Sphere(sides=32)
for i in range(num[0]):
    for j in range(num[1]):
コード例 #26
0
ファイル: Post.py プロジェクト: wezzynl/pi3d_demos
                              h=800,
                              frames_per_second=40,
                              mouse=True)
DISPLAY.set_background(0.4, 0.6, 0.8, 1.0)  # r,g,b,alpha

persp_cam = pi3d.Camera(scale=0.5)  # default instance camera perspecive view

#setup textures, light position and initial model position
pi3d.Light((0, 5, 0))
#create shaders
shader = pi3d.Shader("star")
flatsh = pi3d.Shader("uv_flat")
post = pi3d.PostProcess(camera=persp_cam, scale=0.5)

#Create textures
shapeimg = pi3d.Texture("textures/straw1.jpg")
shapebump = pi3d.Texture("textures/floor_nm.jpg", True)

#Create shape
myshape = pi3d.MergeShape(camera=persp_cam)  #specify perspective view
asphere = pi3d.Sphere(sides=32, slices=32)
myshape.radialCopy(asphere, step=72)
myshape.position(0.0, 0.0, 5.0)
myshape.set_draw_details(shader, [shapeimg], 8.0, 0.1)

mysprite = pi3d.Sprite(w=10.0, h=10.0, camera=persp_cam)
mysprite.position(0.0, 0.0, 15.0)
mysprite.set_draw_details(flatsh, [shapebump])

# Fetch key presses.
mykeys = pi3d.Keyboard()
コード例 #27
0
ファイル: LoadModelObj.py プロジェクト: jmalm/pi3d
#!/usr/bin/python
from __future__ import absolute_import, division, print_function, unicode_literals
""" Wavefront obj model loading. Material properties set in mtl file.
Uses the import pi3d method to load *everything*
"""
import demo
import pi3d
# Setup display and initialise pi3d
DISPLAY = pi3d.Display.create(x=100, y=100,
                         background=(0.2, 0.4, 0.6, 1))
shader = pi3d.Shader("shaders/uv_reflect")
#========================================
# load bump and reflection textures
bumptex = pi3d.Texture("textures/floor_nm.jpg")
shinetex = pi3d.Texture("textures/stars.jpg")
# load model_loadmodel
mymodel = pi3d.Model(file_string='models/teapot.obj', name='teapot', z=4)
mymodel.set_shader(shader)
mymodel.set_normal_shine(bumptex, 16.0, shinetex, 0.5)
# Fetch key presses
mykeys = pi3d.Keyboard()

while DISPLAY.loop_running():
  mymodel.draw()
  mymodel.rotateIncY(2.0)
  mymodel.rotateIncZ(0.1)
  mymodel.rotateIncX(0.3)

  k = mykeys.read()
  if k >-1:
    if k==112:
コード例 #28
0
#!/usr/bin/python
from __future__ import absolute_import, division, print_function, unicode_literals
""" Peter Hess' converted shader for pi3d dynamic texturing """
import demo
import pi3d

DISPLAY = pi3d.Display.create(x=100, y=100, frames_per_second=30)
shader = pi3d.Shader("star")
tex = pi3d.Texture("textures/PATRN.PNG")
#box = pi3d.Cuboid(x=0, y=0, z=2.2)
box = pi3d.Cuboid(w=100, h=100, d=100, x=0, y=0, z=100.0)
box.set_draw_details(shader, [tex])
tm = 0.0
dt = 0.01
sc = 0.0
ds = 0.001

mykeys = pi3d.Keyboard()
ASPECT = DISPLAY.width / DISPLAY.height
camera1 = pi3d.Camera((0, 0, 0), (0, 0, -0.1), (1, 1000, 45, ASPECT),
                      is_3d=True)
camera2 = pi3d.Camera(is_3d=False)
while DISPLAY.loop_running():
    box.set_custom_data(48, [tm, sc, -0.5 * sc])
    """Three custom unif values used by star shader to animate image
  """
    tm += dt
    sc = (sc + ds) % 10.0
    box.rotateIncX(0.1)
    box.rotateIncY(0.71)
    box.position(-50.0, 50.0, 400.0)
コード例 #29
0
# Setup display and initialise pi3d
DISPLAY = pi3d.Display.create(x=100, y=100)
DISPLAY.set_background(0.4, 0.8, 0.8, 1)  # r,g,b,alpha
# yellowish directional light blueish ambient light
pi3d.Light(lightpos=(1, -1, -3),
           lightcol=(1.0, 1.0, 0.7),
           lightamb=(0.15, 0.1, 0.3))

#========================================

# load shader
shader = pi3d.Shader("shaders/uv_reflect")
flatsh = pi3d.Shader("shaders/uv_flat")

tree2img = pi3d.Texture("textures/tree2.png")
tree1img = pi3d.Texture("textures/tree1.png")
hb2img = pi3d.Texture("textures/hornbeam2.png")
bumpimg = pi3d.Texture("textures/grasstile_n.jpg")
reflimg = pi3d.Texture("textures/stars.jpg")
rockimg = pi3d.Texture("textures/rock1.jpg")

clash = pi3d.Clashtest()

FOG = ((0.3, 0.3, 0.4, 0.5), 650.0)
TFOG = ((0.1, 0.14, 0.12, 0.3), 150.0)

#myecube = pi3d.EnvironmentCube(900.0,"HALFCROSS")
ectex = pi3d.loadECfiles("textures/ecubes", "sbox")
myecube = pi3d.EnvironmentCube(size=900.0, maptype="FACES", name="cube")
myecube.set_draw_details(flatsh, ectex)
コード例 #30
0
from __future__ import absolute_import, division, print_function, unicode_literals
""" Example showing use of FixedString. ESC to quit

FixedString should be faster for rendering large quantities of text as
it only requires two triangles for the whole text rather than two triangles
for each letter"""
import demo
import pi3d

DISPLAY = pi3d.Display.create(x=150, y=150)
flatsh = pi3d.Shader("uv_flat")
shader = pi3d.Shader("uv_bump")
CAMERA = pi3d.Camera()
CAMERA2D = pi3d.Camera(is_3d=False)
pi3d.Light(lightpos=(10, -10, 2))
tex = pi3d.Texture('textures/rock1.jpg')
mytext = '''Pi3D is a Python module that
aims to greatly simplify
writing 3D in Python whilst
giving access to the power
of the Raspberry Pi GPU.
It enables both 3D and 2D
rendering and aims to provide
a host of exciting commands.'''

str1 = pi3d.FixedString('fonts/NotoSans-Regular.ttf',
                        mytext,
                        font_size=32,
                        background_color=(200, 140, 20, 235),
                        camera=CAMERA2D,
                        shader=flatsh,