Hi all,
I am using pyglet to develop a series of visual stimuli. I have some
problems with my code, could you help me understand what I am doing wrong?
I have attached a part of the code I am using, the main file is called
"150121_Plaid_v19", and "rlabs_libutils" is a library of some functions,
one of which I will explain next.
In lines 190 - 258 I have the stimulus loop (or game loop) and for each
iteration I need to retrieve the subject's input and save it in an array.
In order to do that, I use the function 'my_dispatch_events', which I call
in line 204 with the pyglet window and an instance of a class called
LastEvent() that I defined.
With this method, I lose some of the data. Could you help me understand
what would be a good method of retrieving input events and saving them for
each iteration of the game loop, while using as few global variables as
possible (I would like to keep the pyglet window instance as a local
variable)?.
Thank you very much for your attention,
jl
--
You received this message because you are subscribed to the Google Groups
"pyglet-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/pyglet-users.
For more options, visit https://groups.google.com/d/optout.
import os, sys
lib_path = os.path.abspath(os.path.join('..','_Libraries'))
sys.path.append(lib_path)
from rlabs_libtobii import EyetrackerBrowser, MyTobiiController #
this is OUR library for the tobii eyetracker
from rlabs_libutils import *
from pyglet.window import Window
from pyglet.gl import * #
to change the color of the background
from pyglet import clock
import time #
for the while loop
from numpy.random import permutation as np_permutation #
for random trials
def main(ExpName = 'Plaid_v19', subjectname = ''):
######################################################
## Load parameters
######################################################
if getattr(sys, 'frozen', False): #
path is different
application_path = os.path.dirname(sys.executable) #
if its an executable
elif __file__: #
or a Python script,
application_path = os.path.dirname(__file__) #
look for it
# config_name = "config_file" #
Name of the config file
# trials_name = "trials_file" #
Name of the trials file
# config_name_full = os.path.join(application_path, config_name) # Full
path name of the config file
# trials_name_full = os.path.join(application_path, trials_name) # Full
path name of the trials file
from config_file import (aperture_color,numTheta,apertureDiv,
# import config parameters
red_color, cyan_color, stereo1, stereo2, fixp_color, surrp_color,
time_fixp, framerate, FPsize, fg_color, aperture_switch,
forced,aperture_radius,
testing_with_eyetracker, randomize_trials, fixYN)
from trials_file import (numtrials,mylambda1, duty_cycle1, orientation1,
# import trials parameters
speed1, mylambda2, duty_cycle2, orientation2, speed2, timeCurrentTrial)
if forced:
# read forced transitions file
transfilename = 'datatestN_NR_5_trans.txt'
# transfilename_full = os.path.join(application_path, transfilename)
# Full path name of the transition file
# transTimeL, transTimeR = read_forced_transitions(transfilename)
transTimeL, transTimeR =
read_forced_transitions(transfilename=transfilename)
timeRamp = 0.5
else:
deltaX1 = 0
deltaX2 = 0
## randomize trials ?
if randomize_trials:
trials_array = np_permutation(numtrials) # goes from 0 to numtrials in
random order
else:
trials_array = range(numtrials) # no random
######################################################
## Create Pyglet Window
######################################################
screens = pyglet.window.get_platform().get_default_display().get_screens()
if aperture_switch:
allowstencil = pyglet.gl.Config(stencil_size = 8,double_buffer=True)
MyWin = Window(config=allowstencil,fullscreen=True,screen=screens[0],
visible = 0) # Create window (not visible for now)
else:
MyWin = Window(fullscreen=True,screen=screens[0], visible = 0)
xcenter = MyWin.width/2
ycenter = MyWin.height/2
clock.set_fps_limit(framerate) #
set limit for frames per second
frameMs = 1000.0/framerate #
manual frame rate control: frameMs is the time in ms a frame will be displayed
######################################################
## Initialize variables for data file
######################################################
# Name of the data files
filename_fordata = os.path.join('data',("Plaid_v19" + "-" +
time.strftime("%y.%m.%d_%H.%M", time.localtime()) + "_" + subjectname + "_" +
"data" + ".txt"))
filename_rawdata = os.path.join('data',("Plaid_v19" + "-" +
time.strftime("%y.%m.%d_%H.%M", time.localtime()) + "_" + subjectname + "_" +
"rawd" + ".txt"))
eyetrackeroutput = os.path.join('data',("Plaid_v19" + "-" +
time.strftime("%y.%m.%d_%H.%M", time.localtime()) + "_" + subjectname + "_" +
"eyet" + ".txt"))
eyetrackeroutput2 = os.path.join('data',("Plaid_v19" + "-" +
time.strftime("%y.%m.%d_%H.%M", time.localtime()) + "_" + subjectname + "_" +
"etvg" + ".txt"))
right_keys = [4, 109, 110, 106] # right click, M, N, J #
array with ascii codes for right keys
left_keys = [1, 122, 120, 115] # left click, Z, X, S #
array with ascii codes for left keys
lastevent = LastEvent() #
LastEvent() is defined in rlabs_libutils
data_struct = DataStruct() #
DataStruct() is defined in rlabs_libutils
# 3.4 - Initialize text to be shown at startup (not whown right now)
textInstruc = "Continually report the motion of the grating in
front.\nPress the left mouse button for left-ward motion.\nPress the right
mouse button for right-ward motion\n\nClick mouse-wheel to start"
# Use the mouse buttons to indicate the direction of the plaid in
front.\n\nClick mouse-wheel to start"
# textInstruc = "Use the mouse buttons to indicate the direction of the
plaid in front.\n\nClick mouse-wheel to start"
lbl_instr = pyglet.text.Label(text=textInstruc, font_name=None,
font_size=36, bold=False, italic=False,
color=(0, 0, 0, 255), x = 100, y = MyWin.height/1.5, width=1400,
height=None,
anchor_x='left', anchor_y='baseline', halign='left', multiline=True,
dpi=None, batch=None, group=None)
textInstruc2 = "Click mouse-wheel for next trial"
lbl_instr2 = pyglet.text.Label(text=textInstruc2, font_name=None,
font_size=24, bold=False, italic=False,
color=(0, 0, 0, 255), x = MyWin.width/2 - 200, y = MyWin.height/2.4,
width=1400, height=None,
anchor_x='left', anchor_y='baseline', halign='left', multiline=True,
dpi=None, batch=None, group=None)
if testing_with_eyetracker:
######################################################
## Create an EyetrackerBrowser and display it
######################################################
eb = EyetrackerBrowser()
eb.main()
######################################################
## Initialize controller (MyTobiiController)
######################################################
controller = MyTobiiController(datafilename=eyetrackeroutput, vergdfn =
eyetrackeroutput2) # create controller
controller.waitForFindEyeTracker() #
wait to find eyetracker
controller.activate(controller.eyetrackers.keys()[0]) #
activate eyetracker
######################################################
## Start trials
######################################################
if testing_with_eyetracker:
controller.startTracking()
# start the eye tracking recording
time.sleep(0.2)
# wait for the eytracker to warm up
controller.recordEvent("{0}\t{1}\t{2}".format('InfoEvent','ExpName',ExpName))
# write event to eyetracker data file: expname
controller.recordEvent("{0}\t{1}\t{2}".format('InfoEvent','SubjectName',subjectname))
# write event to eyetracker data file: subjectname
MyWin.set_visible(True) #
set window to visible
MyWin.set_mouse_visible(False) #
set mouse to not visible
timeStart_general = time.time() #
get general start time
for trial_counter in range(numtrials): #
for each trial
######################################################
## Prepare variables before stimulus loop
######################################################
trial = trials_array[trial_counter]
# read from trials
apertRad_pix = MyWin.height / apertureDiv
grating11 = Grating(MyWin, mycoords(0,0, MyWin).x + stereo1,
mycoords(0,0, MyWin).y, red_color, orientation1[trial], mylambda1[trial],
duty_cycle1, apertRad_pix, speed1)
grating12 = Grating(MyWin, mycoords(0,0, MyWin).x - stereo1,
mycoords(0,0, MyWin).y, cyan_color, orientation1[trial], mylambda1[trial],
duty_cycle1, apertRad_pix, speed1)
grating21 = Grating(MyWin, mycoords(0,0, MyWin).x + stereo2,
mycoords(0,0, MyWin).y, red_color, orientation2[trial], mylambda2[trial],
duty_cycle2, apertRad_pix, speed2)
grating22 = Grating(MyWin, mycoords(0,0, MyWin).x - stereo2,
mycoords(0,0, MyWin).y, cyan_color, orientation2[trial], mylambda2[trial],
duty_cycle2, apertRad_pix, speed2)
# grating11 = GratingHORIZONTAL(MyWin, mycoords(0,0, MyWin).x +
stereo1, mycoords(0,0, MyWin).y, red_color, orientation1[trial],
mylambda1[trial], duty_cycle1, apertRad_pix, speed1)
# grating12 = GratingHORIZONTAL(MyWin, mycoords(0,0, MyWin).x -
stereo1, mycoords(0,0, MyWin).y, cyan_color, orientation1[trial],
mylambda1[trial], duty_cycle1, apertRad_pix, speed1)
######################################################
## Wait for go Loop
######################################################
while not wait_for_go_function(MyWin,lastevent) and not MyWin.has_exit:
glClearColor(fg_color[0],fg_color[1],fg_color[2],1) #
set background color
MyWin.clear() #
clear window
if trial_counter == 0: #
if first trial,
lbl_instr.draw() #
show instructions
else: #
for the rest show fixation point
lbl_instr2.draw() #
show instructions
drawCircle(xcenter, ycenter, numTheta, FPsize * 4, surrp_color)
drawCircle(xcenter, ycenter, numTheta, FPsize, fixp_color)
MyWin.flip() #
flip window
######################################################
## Start stimulus loop
######################################################
# Initialize forced variables
if forced:
i_R = 0
i_L = 0
Ron = 0
Lon = 0
timeTransR = transTimeL[0]
timeTransL = transTimeR[0]
deltaXaux1 = 0
deltaXaux2 = 0
timeStart = time.time() #
get trial start time
if testing_with_eyetracker: #
write START trial to log file
controller.recordEvent("{0}\t{1}\t{2}".format('TrialEvent',trial,'START'))
# write event to eyetracker data file
while (time.time() - timeStart) < timeCurrentTrial and not
MyWin.has_exit:
timeNow = time.time() #
get current time
startMs = clock.tick() #
manual frame rate control: time point when frame starts. Also needed to show fps
glClearColor(fg_color[0],fg_color[1],fg_color[2],1) #
set background color
MyWin.clear() #
clear window
MyWin.dispatch_events() #
dispatch window events (very important call)
######################################################
## Retrieve subject input and save it to data arrays
######################################################
# MyWin.dispatch_events()
lastevent = my_dispatch_events(MyWin, lastevent) #
my_dispatch_events is defined in rlabs_libutils
#
last event subject has triggered, will remain the same until subject triggers
another event
# write last event to data arrays
if lastevent.type != []: #
if there's an event, save it
save_data_to_arrays(lastevent, data_struct, trial, timeNow) #
save_data_to_arrays is defined in rlabs_libutils
if testing_with_eyetracker:
controller.recordEvent("{0}\t{1}\t{2}".format('InputEvent',
lastevent.type, lastevent.id)) # write event to eyetracker data file
lastevent.reset_values() #
reset values of event
######################################################
## Update position of objects
######################################################
if forced:
stereo1, stereo2, i_R, i_L, Ron, Lon, timeTransR, timeTransL,
deltaXaux1, deltaXaux2 = compute_forced_values(i_R, i_L, Ron, Lon, timeTransR,
timeTransL, deltaXaux1, deltaXaux2, timeRamp, timeStart, timeNow, transTimeL,
transTimeR)
else:
stereo1 = stereo1
stereo2 = stereo2
grating11.update_position(timeStart, stereo1)
grating12.update_position(timeStart, stereo2)
grating21.update_position(timeStart, stereo2)
grating22.update_position(timeStart, stereo1)
######################################################
## Draw objects
######################################################
glEnable(GL_BLEND)
drawAperture(xcenter, ycenter, apertRad_pix, aperture_color,
numTheta)
grating11.draw()
grating12.draw()
grating21.draw()
grating22.draw()
glDisable(GL_BLEND)
if fixYN:
drawCircle(xcenter, ycenter, numTheta, FPsize * 4, surrp_color)
drawCircle(xcenter, ycenter, numTheta, FPsize, fixp_color)
fps.draw()
######################################################
## Flip the window
######################################################
MyWin.flip() #
flip window
endMs = clock.tick() # manual frame rate control: time point when
frame ends.
# delaytime = frameMs - (endMs-startMs) # manual frame rate
control: time time frame must be frozen.
if testing_with_eyetracker: #
write END trial to log file
controller.recordEvent("{0}\t{1}\t{2}".format('TrialEvent',trial,'END')) #
write event to eyetracker data file
if MyWin.has_exit: #
This breaks the For stimulus loop.
break #
Data is not lost, it has already been saved in the arrays.
###############################################################
## Stop eyetracker processes, save data and close pyglet window
###############################################################
if testing_with_eyetracker:
controller.stopTracking() #
stop eye tracking and write output file
controller.destroy() #
destroy controller
save_raw_data(filename_rawdata, data_struct) #
save raw data
save_data_formatted(filename_fordata,data_struct,right_keys,left_keys) #
save formatted data
MyWin.close() #
close pyglet window
######################################################
##
######################################################
if __name__ == '__main__':
print 'running 150121_Plaid_v19'
if len(sys.argv) > 1: # optional: add a subject
name
subjectname = sys.argv[1] # run as python Plaid_v19
subjectname
else:
subjectname = 'defaultsubjectname'
fps = pyglet.clock.ClockDisplay(color=(1,1,1,1)) # show frames per second
main(subjectname = subjectname)
import math # for the circle
from pyglet.gl import * # for the circle
import time # for the update method
of the gratings
import csv # for reading the forced
transition file
import os, stat # to create read-only file
########################################
## Data management functions and classes
########################################
class DataStruct(object):
def __init__(self):
self.eventsCounter = [0]
self.event_counter_array = []
self.time_array = []
self.event_type_array = []
self.ID_array = []
self.trial_index_array = []
class LastEvent():
def __init__(self):
self.type = []
self.id = []
self.counter = []
def reset_values(self):
self.type = []
self.id = []
self.counter = []
def save_data_to_arrays(lastevent, data_struct, trial, timeNow):
"""
Appends each new event of an instance of the class
LastEvent() to the correspondent array of an instance
of the the class LastEvent()
arguments
- lastevent: instance of LastEvent class
- data_struct: instance of DataStruct class
- trial: number of the current trial
- timeNow: call to time.time()
returns
Nothing -- data_struct will be updated
"""
# add event data to arrays
data_struct.eventsCounter[0] += 1
data_struct.event_counter_array.append(data_struct.eventsCounter[0])
data_struct.time_array.append(timeNow)
data_struct.event_type_array.append(lastevent.type)
data_struct.ID_array.append(lastevent.id)
data_struct.trial_index_array.append(trial)
def save_raw_data(rawdata_filename, data_struct):
# """
# Save contents of data_struct to output file
# arguments
# - rawdata_filename: name of output file
# - data_struct: instance of DataStruct class
# returns
# Nothing --
#"""
timeStampStart = 0#data_struct.time_array[0]
length = len(data_struct.event_counter_array)
with open(rawdata_filename, 'w' ) as txtfile:
for i in range(length):
txtfile.write(str(data_struct.event_counter_array[i]) +'\t'+
str(data_struct.trial_index_array[i]) +'\t'+
str((data_struct.time_array[i]-timeStampStart)) +'\t'+
str(data_struct.event_type_array[i]) +'\t'+str(data_struct.ID_array[i])+'\n')
# print("raw data saved")
os.chmod(rawdata_filename,stat.S_IREAD) # make file read only
pass
def save_data_formatted(data_namefile, data_struct, right_keys, left_keys):
# """
# Save contents of data_struct to output file in HARDCODED format.
# Format is:
# 1 - right key down (pressed)
# 2 - right key up (released)
# -1 - left key down (pressed)
# -2 - left key up (released)
# arguments
# - rawdata_filename: name of output file
# - data_struct: instance of DataStruct class
# - right_keys: array with ascii codes for
right keys
# - left_keys: array with ascii codes for left
keys
# returns
# Nothing --
# """
timeStampStart = 0#data_struct.time_array[0]
length = len(data_struct.event_counter_array)
with open(data_namefile, 'w' ) as txtfile:
for i in xrange(0,length,1): # equal to for(i = 1, i <length, < i++)
# this will look at the last two characters of the current
event_type_array and will determine if it is up or down
isdown =
(data_struct.event_type_array[i][len(data_struct.event_type_array[i])-2:len(data_struct.event_type_array[i])]
== "DW")
isup =
(data_struct.event_type_array[i][len(data_struct.event_type_array[i])-2:len(data_struct.event_type_array[i])]
== "UP")
if (data_struct.ID_array[i] in right_keys) and (isdown):
code = 1
pass
elif (data_struct.ID_array[i] in right_keys) and (isup):
code = 2
elif (data_struct.ID_array[i] in left_keys) and (isdown):
code = -1
pass
elif (data_struct.ID_array[i] in left_keys) and (isup):
code = -2
else: # key not in right and left arrays
code = 999
# data file
# ToDo: put a column for number of trials too
txtfile.write(str(data_struct.event_counter_array[i]) +'\t'+
str(data_struct.trial_index_array[i]) +'\t'+
str((data_struct.time_array[i]-timeStampStart)) +'\t'+ str(code) +'\n')
os.chmod(data_namefile,stat.S_IREAD) # make file read only
# print("formatted data saved")
pass
def write_data_file(data_namefile, data_struct):
# fields in header:
fields = ['Timestamp', 'EventType', 'EventID', 'EventValue']
timeStampStart = data_struct.time_array[0]
with open(data_namefile, 'w' ) as f: # open or create text file
'filename' to append
f.write('\t'.join(fields)+'\n') # write header. Separate
the fields into tabs
length = len(data_struct.event_counter_array)
for i in range(length):
f.write(''.format())
txtfile.write(str(data_struct.event_counter_array[i]) +'\t'+
str(data_struct.trial_index_array[i]) +'\t'+
str((data_struct.time_array[i]-timeStampStart)) +'\t'+
str(data_struct.event_type_array[i]) +'\t'+str(data_struct.ID_array[i])+'\n')
os.chmod(data_namefile,stat.S_IREAD) # make file read only
pass
def create_unique_name(subject_info):
## Create output data file name
# Get subject and time information
exp_name = 'pythonMigration'
time_string = time.strftime("%y.%m.%d_%H.%M.%S", time.localtime())
subject_name = subject_info["Name"]
textfilename = (exp_name + '_' + subject_name + '_' + time_string + '.txt')
# Save output file in the folder "data".
# following command will create the native file separator caracter. e.g.:
'\' for windows
out_file_name = os.path.join('data', textfilename)
return out_file_name
########################################
##
########################################
def my_dispatch_events(mywindow, event):
"""
Appends each new event of an instance of the class
LastEvent() to the correspondent array of an instance
of the the class LastEvent()
arguments
- mywindow: instance of a pyglet Window class
- event: instance of LastEvent class
returns
- event: event will be updated
"""
@mywindow.event
def on_key_press(symbol, modifiers):
event.type = "Key_DW"
event.id = symbol
# event.counter += 1
@mywindow.event
def on_key_release(symbol, modifiers):
event.type = "Key_UP"
event.id = symbol
# event.counter += 1
@mywindow.event
def on_mouse_press(x, y, button, modifiers):
event.type = "Mouse_DW"
event.id = button
# event.counter += 1
@mywindow.event
def on_mouse_release(x, y, button, modifiers):
event.type = "Mouse_UP"
event.id = button
# event.counter += 1
@mywindow.event
def on_close():
# The closing of the window is taken care in the while loop
pass
return event
def wait_for_go_function(mywindow, event, expected_type = 'Mouse_UP',
expected_id = 2):
wait_for_go = 0
mywindow.dispatch_events()
event = my_dispatch_events(mywindow,event)
# Calculate condition for "go", for example:
# -the mouse was clicked (any key), OR
# -SPACE key was pressed (ASCII 32 key)
# if (event.type == "Key_DW" and event.id == 32) or
(event.type=="Mouse_UP"):
# wait_for_go = 1
# Calculate condition for "go", for example:
# Default: when mouse-wheel is released
if (event.type == expected_type and event.id == expected_id):
wait_for_go = 1
event.reset_values()
return wait_for_go
pass
def my_on_close(mywindow):
# Save data +do whatever other pre-exit cleanup necessary
print("closed nicely")
mywindow.clear()
mywindow.close()
########################################
## Stimulus functions and classes
########################################
def drawCircle(x, y, numTheta = 90, radius = 100, circle_color = (0,0,0)):
deltaTheta = 2 * math.pi / numTheta
glColor3f( circle_color[0] , circle_color[1], circle_color[2])
for i in range (0, numTheta):
cx1 = x + radius * math.sin(deltaTheta * i)
cy1 = y + radius * math.cos(deltaTheta * i)
cx2 = x + radius * math.sin(deltaTheta * (i+1))
cy2 = y + radius * math.cos(deltaTheta * (i+1))
glBegin( GL_TRIANGLES )
glVertex2f(x, y )
glVertex2f(cx1 , cy1 )
glVertex2f(cx2 , cy2 )
glEnd()
def drawGrating(x, y, fill_color, orientation, mylambda, duty_cycle,
apertRad_pix):
bar_length = 1000
radio_aux = (2 * apertRad_pix) + mylambda #diameter
num_bars = int(1 + math.floor(radio_aux / mylambda))+3
glStencilFunc (GL_EQUAL, 0x1, 0x1)
glStencilOp (GL_KEEP, GL_KEEP, GL_KEEP)
glLoadIdentity() #replace current matrix with the identity matrix
glTranslatef(x, y, 0)
glRotatef(orientation,0,0,1)
glTranslatef(-x, -y, 0)
glColor3f(fill_color[0] , fill_color[1], fill_color[2] )
glBlendFunc(GL_ZERO, GL_SRC_COLOR)
for i in range(int(-num_bars/2),int(num_bars/2)):
x1 = mylambda * i + x
x2 = (duty_cycle * mylambda) + (mylambda * i + x)
glBegin(GL_QUADS)
glVertex2f(x1, y - bar_length)
glVertex2f(x1, y + bar_length)
glVertex2f(x2, y + bar_length)
glVertex2f(x2, y - bar_length)
glEnd()
# glRotatef(-orientation, 0, 0, 1)#Is it necessary?
glBlendFunc(GL_ONE, GL_ZERO)
glLoadIdentity()
pass
def drawAperture(x0_pix, y0_pix, radius_pix, color, numTheta):
# Enable stencil
glClearStencil(0x0)
glEnable(GL_STENCIL_TEST)
#define the region where the stencil is 1
glClear(GL_STENCIL_BUFFER_BIT)
glStencilFunc(GL_ALWAYS, 0x1, 0x1) #Always pass stencil functions test
glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE) #Replace stencil value with
reference value
drawCircle(x0_pix, y0_pix, numTheta, radius_pix, color)
pass
class Grating():
def __init__(self, MyWin, x, y, fill_color, orientation, mylambda,
duty_cycle, apertRad_pix, speed):
self.x = x
self.y = y
self.fill_color = fill_color
self.orientation = orientation
self.mylambda = mylambda
self.duty_cycle = duty_cycle
self.apertRad_pix = apertRad_pix
self.speed = speed
# decide if horizontal or vertical motion, depending on orientation:
# self.threshold_angle = 50
# if orientation < self.threshold_angle:
# self.motion_cycle = mylambda/(math.cos(math.radians(orientation)))
# self.initialpos = x
# elif orientation >= self.threshold_angle:
# self.motion_cycle = mylambda/(math.sin(math.radians(orientation)))
# self.initialpos = y
# # self.initialpos = MyWin.width/2 - apertRad_pix - mylambda/2
self.motion_cycle = mylambda/(math.cos(math.radians(orientation)))
self.initialpos = x
pass
def draw(self):
x = self.x
y = self.y
fill_color = self.fill_color
orientation = self.orientation
mylambda = self.mylambda
duty_cycle = self.duty_cycle
apertRad_pix = self.apertRad_pix
bar_length = 1000
radio_aux = (2 * apertRad_pix) + mylambda #diameter
num_bars = int(1 + math.floor(radio_aux / mylambda))+3
glStencilFunc (GL_EQUAL, 0x1, 0x1)
glStencilOp (GL_KEEP, GL_KEEP, GL_KEEP)
glLoadIdentity() #replace current matrix with the identity matrix
glTranslatef(x, y, 0)
glRotatef(orientation,0,0,1)
glTranslatef(-x, -y, 0)
glColor3f(fill_color[0] , fill_color[1], fill_color[2] )
glBlendFunc(GL_ZERO, GL_SRC_COLOR)
for i in range(int(-num_bars/2),int(num_bars/2)):
x1 = mylambda * i + x
x2 = (duty_cycle * mylambda) + (mylambda * i + x)
glBegin(GL_QUADS)
glVertex2f(x1, y - bar_length)
glVertex2f(x1, y + bar_length)
glVertex2f(x2, y + bar_length)
glVertex2f(x2, y - bar_length)
glEnd()
# glRotatef(-orientation, 0, 0, 1)#Is it necessary?
#glBlendFunc(GL_ONE, GL_ZERO) #150116 comment out NR
glLoadIdentity()
pass
def update_position(self, runningTime, stereo):
motion_cycle = self.motion_cycle
speed = self.speed
initialpos = self.initialpos
timeNow = time.time()
position = initialpos + stereo
self.x = position + math.fmod(speed*(timeNow-runningTime), motion_cycle)
# if self.orientation < self.threshold_angle:
# self.x = position + math.fmod(speed*(timeNow-runningTime),
motion_cycle)
# elif self.orientation >= self.threshold_angle:
# self.y = initialpos + math.fmod(speed*(timeNow-runningTime),
motion_cycle)
pass
pass
class mycoords():
# OpenGL coordinate system (0,0) is at the bottom left of the screen
# this funciton makes the cordinate system at the center of the scree
def __init__(self,x,y,window):
self.x = x + window.width/2
self.y = y + window.height/2
########################################
## Forced mode functions
########################################
def read_forced_transitions(transfilename='datatestN_NR_5_trans.txt'):
transfilename = 'datatestN_NR_5_trans.txt'
#forced = 1
deltaXaux1_ini = 0
deltaXaux2_ini = 0
deltaX1 = 0.01
deltaX2 = 0.01
# transfilename = 'datatestN_NR_5_trans.txt'
# transfilename_full = os.path.join(application_path, transfilename)
# Full path name of the transition file
# 5.1 - Read file with transition time stamps (for forced mode)
transTimeL = []
transTimeR = []
try: #
try/except is used here to handle errors such
with open(transfilename, 'r') as f: # as the
transition file name is wrong
#with open(transfilename) as f:
#with open('trans.txt') as f:
reader=csv.reader(f,delimiter='\t')
# reader is a csv class to parse data files
for L_item,R_item in reader:
#L_item and R_item are the time stamps
#for R_item,L_item in reader: #L_item
and R_item are the time stamps
#L_array.append(float(L_item)) #
Append time stamps to array
#R_array.append(float(R_item))
transTimeL.append(float(L_item))
# Append time stamps to array
transTimeR.append(float(R_item))
#L_array.append(timeTrialMax) # Append
total duration of trial at the end?
#R_array.append(timeTrialMax)
#timeTransL = L_array[0]
#timeTransR = R_array[0]
# timeRamp = 0.5
except EnvironmentError:
#print srt(transfilename)+' could not be opened'
print "transition file could not be opened"
sys.exit()
return transTimeL,transTimeR
def compute_forced_values(i_R, i_L, Ron, Lon, timeTransR, timeTransL,
deltaXaux1, deltaXaux2, timeRamp, timeStartTrial,timeNow, transTimeL,
transTimeR, deltaX1=0.01, deltaX2=0.01, deltaXaux1_ini=0, deltaXaux2_ini=0):
# Apply forced mode changes to the stereo
# Moving the Depth
scale = 500
if (timeNow - timeStartTrial > timeTransR) & (timeNow - timeStartTrial <
timeTransR + timeRamp):
deltaXaux1 = deltaX1 * (timeNow - timeStartTrial - timeTransR) /
timeRamp
Ron = 1
if deltaXaux2_ini > deltaX2/2:
deltaXaux2 = deltaX2 - deltaX2 * (timeNow - timeStartTrial -
timeTransR) / timeRamp
deltaXaux1_ini = deltaXaux1
if (timeNow - timeStartTrial > timeTransR + timeRamp) & (Ron == 1):
Ron = 0
i_R = i_R + 1
timeTransR = transTimeR[i_R]
# print timeTransR
if (timeNow - timeStartTrial > timeTransL) & (timeNow - timeStartTrial <
timeTransL + timeRamp):
deltaXaux2 = deltaX2 * (timeNow - timeStartTrial - timeTransL) /
timeRamp
Lon = 1
if (deltaXaux1_ini > deltaX1/2):
deltaXaux1 = deltaX1 - deltaX1 * (timeNow - timeStartTrial -
timeTransL) / timeRamp
deltaXaux2_ini = deltaXaux2
if (timeNow - timeStartTrial > timeTransL + timeRamp) & (Lon == 1):
Lon = 0
i_L = i_L + 1
timeTransL = transTimeL[i_L]
# update stereo value
stereo1 = (-deltaXaux1/2 + deltaXaux2/2) * scale
stereo2 = (deltaXaux1/2 - deltaXaux2/2) * scale
return stereo1, stereo2, i_R, i_L, Ron, Lon, timeTransR, timeTransL,
deltaXaux1, deltaXaux2
########################################
## Not used
########################################
class Aperture():
def __init__(self, color, numTheta, x0_pix, y0_pix, radius_pix):
self.color = color
self.numTheta = numTheta
self.x0 = x0_pix
self.y0 = y0_pix
self.radius = radius_pix
pass
def draw(self):
color = self.color
numTheta = self.numTheta
x0_pix = self.x0
y0_pix = self.y0
apertRad_pix = self.radius
# Enable stencil
glClearStencil(0x0)
glEnable(GL_STENCIL_TEST)
#define the region where the stencil is 1
glClear(GL_STENCIL_BUFFER_BIT)
glStencilFunc(GL_ALWAYS, 0x1, 0x1) #Always pass stencil functions test
glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE) #Replace stencil value
with reference value
drawCircle(x0_pix, y0_pix, numTheta, apertRad_pix, color)
pass
pass
# if __name__ == '__main__':
# lastevent = LastEvent()
# lastevent.reset_values()
# # main()