четверг, 13 декабря 2007 г.

3D-программирование с Vpython

Vpython позволяет создавать 3D объекты и размещать их на 3D сцене. Vpython запускается в отдельном процессе (thread) и контролирует 3D сцену, программисту остается только писать логику программы. Пользователь, работая с такой программой, может перемещаться по сцене и масштабировать, поворачивать и перемещать объекты, используя мыша.
Модуль можно скачать с официального сайта http://vpython.org. В зависимостях у модуля: Numpy, gtkglarea и boost. Для пользователей Debian и Ubuntu в репозиториях уже есть пакет python-visual, который ставится стандартными средствами, например:

sudo aptitude install python-visual

Можно также поставить и модуль gamepy для музыкального оформления программы

sudo aptitude install gamepy

Теперь, по традиции, напишем программу, выводящую 3D "Hellow World"

from visual.text import *

# At present, VPython supports only numbers and uppercase characters. Other characters will be displayed as *
# Specifying the Title of the window
scene.title = "Hello World"
# Here goes the hello world text
text(pos=(0,3,0), string='HELLO WORLD', color=color.orange, depth=0.3, justify='center')

Вот как это должно выглядеть.



Теперь нарисуем синусоиду, естественно объемную

from visual import *

"""
This will print the sin curve
"""
scene.title = "Sin Curve"
scene.center = vector(0,0,0)

# using a suitable 'box' as x- axis
xaxis = box(length= 20, height=0.2, width= 0.5, color=color.blue)

#creating the sine curve object
sinecurve = curve( color = color.red, radius=0.2)
dt = 0.1

for t in arange(0,10,dt):
dydt = vector( t,sin(t), 0 );
sinecurve.append( pos=dydt, color=(1,0,0) )
rate( 500 )

Смотрим что получилось


Ее можно двигать мышкой.

Ну и более "живой" пример - 3D часы.

from visual.text import *
import time

scene.title = "3D Clock"
while 1:
rate(100)
cur_time = time.localtime()
time_string = str(cur_time[3]) +": "+ str(cur_time[4]) + ": "+ str(cur_time[5])
timer = text(pos=(-3,0,-2), string=time_string, color= color.red, depth=0.5 )
time.sleep(1)
timer.makeinvisible()




С помощью Vpython можно создавать RedBlue стерео-объекты, которые нужно смотреть в красно-синих очках (прямо как в "Дети шпионов 3"). Для включения стерео режима служит команда:

scene.stero='redblue'

Для примера, выведем анимированную стерео 3D-строку

from visual.text import *
import time

#importing pygame to play the background music :)
#import pygame
#Uncomment it if you have the redblue goggles
scene.stereo='redblue'

scene.title = "Renaissance"
#scene.fullscreen = 1
scene.fov = 0.001
scene.range = 0
rate(100)

# Uncomment this if you need to play the background music
#pygame.mixer.init()
#intromusic=pygame.mixer.Sound("/usr/share/sounds/KDE_Startup.wav")
#pygame.mixer.Sound.play(intromusic)

def intro():
Title= text(pos=(0,3,0), string='MCA PROUDLY PRESENTS', color=color.red, depth=0.3, justify='center')
for i in range(20):
rate(10)
scene.range = i
Title.makeinvisible()
scene.range = 0
Header= text(pos=(0,3,0), string='RENAISSANCE 2005', color=color.yellow, depth=0.3, justify='center')
for i in range(20):
rate(10)
scene.fov = 3
scene.range = i
# Now play with colors
Header.reshape(color= color.cyan)
time.sleep(1)
Header.reshape(color= color.blue)
time.sleep(1)
Header.reshape(color= color.green)
time.sleep(1)
Header.reshape(color=color.orange)
time.sleep(1)
Header.reshape(color= color.red)
# Now let's delete the Header
Header.makeinvisible()
scene.range = 10
scene.fov = 0.2
Body= text(pos=(0,3,0), string='A CELEBRATION OF LINUX ', color=color.red, depth=0.3, justify='center')
Body.reshape(color=color.orange)
#Here I am not adding the rest of the code as it just shows the schedule of that days programs
# Invoking intro()
if __name__ == '__main__':
intro()




Удачного программирования.
При написании данного поста использовалась статья в Linux Gazette #144

Комментариев нет: