Lesson 1: Hello World!

In this script we'll learn how to open a 'screen' using the psychtoolbox, put up some text, pause, and close the window. Once you get this working, you're well off the ground for puting up stimuli wit hteh psychtoolbox.

Contents

Opening the screen

Most commands using the psychtoolbox are called using a single matlab function, SCREEN. The first argument for SCREEN is the name of the command, and the rest are arguments specific to that command. Getting help for the Screen command is a bit unconventional. Rather than typing 'help Screen', to get a list of commands, type:

Screen
Usage:

% Activate compatibility mode: Try to behave like the old MacOS-9 Psychtoolbox:
oldEnableFlag=Screen('Preference', 'EmulateOldPTB', [enableFlag]);

% Open or close a window or texture:
[windowPtr,rect]=Screen('OpenWindow',windowPtrOrScreenNumber [,color] [,rect] [,pixelSize] [,numberOfBuffers] [,stereomode] [,multisample][,imagingmode]);
[windowPtr,rect]=Screen('OpenOffscreenWindow',windowPtrOrScreenNumber [,color] [,rect] [,pixelSize] [,specialFlags] [,multiSample]);
textureIndex=Screen('MakeTexture', WindowIndex, imageMatrix [, optimizeForDrawAngle=0] [, specialFlags=0] [, floatprecision=0] [, textureOrientation=0] [, textureShader=0]);
Screen('Close', [windowOrTextureIndex or list of textureIndices/offscreenWindowIndices]);
Screen('CloseAll');

%  Draw lines and solids like QuickDraw and DirectX (OS 9 and Windows):
currentbuffer = Screen('SelectStereoDrawBuffer', windowPtr [, bufferid] [, param1]);
Screen('DrawLine', windowPtr [,color], fromH, fromV, toH, toV [,penWidth]);
Screen('DrawArc',windowPtr,[color],[rect],startAngle,arcAngle)
Screen('FrameArc',windowPtr,[color],[rect],startAngle,arcAngle[,penWidth] [,penHeight] [,penMode])
Screen('FillArc',windowPtr,[color],[rect],startAngle,arcAngle)
Screen('FillRect', windowPtr [,color] [,rect] );
Screen('FrameRect', windowPtr [,color] [,rect] [,penWidth]);
Screen('FillOval', windowPtr [,color] [,rect] [,perfectUpToMaxDiameter]);
Screen('FrameOval', windowPtr [,color] [,rect] [,penWidth] [,penHeight] [,penMode]);
Screen('FramePoly', windowPtr [,color], pointList [,penWidth]);
Screen('FillPoly', windowPtr [,color], pointList [, isConvex]);

% New OpenGL functions for OS X:
Screen('glPoint', windowPtr, color, x, y [,size]);
Screen('gluDisk', windowPtr, color, x, y [,size]);
Screen('DrawDots', windowPtr, xy [,size] [,color] [,center] [,dot_type]);
Screen('DrawLines', windowPtr, xy [,width] [,colors] [,center] [,smooth]);
[sourceFactorOld, destinationFactorOld, colorMaskOld]=('BlendFunction', windowIndex, [sourceFactorNew], [destinationFactorNew], [colorMaskNew]);

% Draw Text in windows
textModes = Screen('TextModes');
oldCopyMode=Screen('TextMode', windowPtr [,textMode]);
oldTextSize=Screen('TextSize', windowPtr [,textSize]);
oldStyle=Screen('TextStyle', windowPtr [,style]);
[oldFontName,oldFontNumber]=Screen(windowPtr,'TextFont' [,fontNameOrNumber]);
[normBoundsRect, offsetBoundsRect]=Screen('TextBounds', windowPtr, text);
[newX,newY]=Screen('DrawText', windowPtr, text [,x] [,y] [,color] [,backgroundColor] [,yPositionIsBaseline]);
oldTextColor=Screen('TextColor', windowPtr [,colorVector]);
oldTextBackgroundColor=Screen('TextBackgroundColor', windowPtr [,colorVector]);

% Copy an image, very quickly, between textures, offscreen windows and onscreen windows.
[resident [texidresident]] = Screen('PreloadTextures', windowPtr [, texids]);
Screen('DrawTexture', windowPointer, texturePointer [,sourceRect] [,destinationRect] [,rotationAngle] [, filterMode] [, globalAlpha] [, modulateColor] [, textureShader] [, specialFlags] [, auxParameters]);
Screen('DrawTextures', windowPointer, texturePointer(s) [, sourceRect(s)] [, destinationRect(s)] [, rotationAngle(s)] [, filterMode(s)] [, globalAlpha(s)] [, modulateColor(s)] [, textureShader] [, specialFlags] [, auxParameters]);
Screen('CopyWindow', srcWindowPtr, dstWindowPtr, [srcRect], [dstRect], [copyMode])

% Copy an image, slowly, between matrices and windows :
imageArray=Screen('GetImage', windowPtr [,rect] [,bufferName] [,floatprecision=0] [,nrchannels=3])
Screen('PutImage', windowPtr, imageArray [,rect]);

% Synchronize with the window's screen (on-screen only):
[VBLTimestamp StimulusOnsetTime FlipTimestamp Missed Beampos] = Screen('Flip', windowPtr [, when] [, dontclear] [, dontsync] [, multiflip]);
Screen('AsyncFlipBegin', windowPtr [, when] [, dontclear] [, dontsync] [, multiflip]);
[VBLTimestamp StimulusOnsetTime FlipTimestamp Missed Beampos] = Screen('AsyncFlipEnd', windowPtr);
[VBLTimestamp StimulusOnsetTime FlipTimestamp Missed Beampos] = Screen('AsyncFlipCheckEnd', windowPtr);
[VBLTimestamp StimulusOnsetTime swapCertainTime] = Screen('WaitUntilAsyncFlipCertain', windowPtr);
[telapsed] = Screen('DrawingFinished', windowPtr [, dontclear] [, sync]);
framesSinceLastWait = Screen('WaitBlanking', windowPtr [, waitFrames]);

% Load color lookup table of the window's screen (on-screen only):
[gammatable, dacbits, reallutsize] = Screen('ReadNormalizedGammaTable', windowPtrOrScreenNumber);
Screen('LoadNormalizedGammaTable', windowPtrOrScreenNumber, table [, loadOnNextFlip] [, physicalDisplay]);
oldclut = Screen('LoadCLUT', windowPtrOrScreenNumber [, clut] [, startEntry=0] [, bits=8]);

% Get (and set) information about a window or screen:
screenNumbers=Screen('Screens' [, physicalDisplays]);
windowPtrs=Screen('Windows');
kind=Screen(windowPtr, 'WindowKind');
isOffscreen=Screen(windowPtr,'IsOffscreen');
hz=Screen('FrameRate', windowPtrOrScreenNumber [, mode] [, reqFrameRate]);
...

The first Screen command will be 'OpenWindow', the first in the list. To see more about how to use that command, use the Screen command like this.

Screen('OpenWindow?')
Usage:

[windowPtr,rect]=Screen('OpenWindow',windowPtrOrScreenNumber [,color] [,rect][,pixelSize][,numberOfBuffers][,stereomode][,multisample][,imagingmode]);

Open an onscreen window. Specify a screen by a windowPtr or a screenNumber (0 is
the main screen, with menu bar). "color" is the clut index (scalar or [r g b]
triplet) that you want to poke into each pixel; default is white. If supplied,
"rect" must contain at least one pixel. If a windowPtr is supplied then "rect"
is in the window's coordinates (origin at upper left), and defaults to the whole
window. If a screenNumber is supplied then "rect" is in screen coordinates
(origin at upper left), and defaults to the whole screen. (In all cases,
subsequent references to this new window will use its coordinates: origin at its
upper left.). Please note that while providing a "rect" parameter to open a
normal window instead of a fullscreen window is convenient for debugging, but
drawing performance, stimulus onset timing and onset timestamping may be
impaired, so be careful.
"pixelSize" sets the depth (in bits) of each pixel; default is to leave depth
unchanged. "numberOfBuffers" is the number of buffers to use. Setting anything
else than 2 will be useful for development/debugging of PTB itself but will mess
up any real experiment. "stereomode" Type of stereo display algorithm to use: 0
(default) means: Monoscopic viewing. 1 means: Stereo output via OpenGL on any
stereo hardware that is supported by MacOS-X, e.g., the shutter glasses from
CrystalView. 2 means: Left view compressed into top half, right view into bottom
half. 3 means left view compressed into bottom half, right view compressed into
top half. 4 and 5 allow split screen display where left view is shown in left
half, right view is shown in right half or the display. A value of 5 does the
opposite (cross-fusion). Values of 6,7,8 and 9 enable Anaglyph stereo rendering
of types left=Red, right=Green, vice versa and left=Red, right=Blue and vice
versa. A value of 10 enables multi-window stereo: Open one window for left eye
view, one for right eye view, treat both of them as one single stereo window.
See StereoDemo.m for examples of usage of the different stereo modes. See
ImagingStereoDemo.m for more advanced usage on modern hardware.
"multisample" This parameter, if provided and set to a value greater than zero,
enables automatic hardware anti-aliasing of the display: For each pixel,
'multisample' color samples are computed and combined into a single output pixel
color. Higher numbers provide better quality but consume more video memory and
lead to a reduction in framerate due to the higher computational demand. The
maximum number of samples is hardware dependent. Psychtoolbox will silently
clamp the number to the maximum supported by your hardware if you ask for too
much. On very old hardware, the value will be ignored. Read 'help AntiAliasing'
for more in-depth information about multi-sampling. "imagingmode" This optional
parameter enables PTB's internal image processing pipeline. The pipeline is off
by default. Read 'help PsychGLImageprocessing' for information about this
feature.
Opening or closing a window takes about one to three seconds, depending on type
of connected display. COMPATIBILITY TO OS-9 PTB: If you absolutely need to run
old code for the old MacOS-9 or Windows Psychtoolbox, you can switch into a
compatibility mode by adding the command Screen('Preference', 'EmulateOldPTB',
1) at the very top of your script. This will restore Offscreen windows and
WaitBlanking functionality, but at the same time disable most of the new
features of the OpenGL Psychtoolbox. Please do not write new experiment code in
the old style! Emulation mode is pretty new and may contain significant bugs, so
use with great caution!

Yes, that's a lot of verbage! The most important part of this verbage is the first line which describes how to use the command:

[windowPtr,rect]=Screen('OpenWindow',windowPtrOrScreenNumber [,color]
[,rect][,pixelSize][,numberOfBuffers][,stereomode][,multisample][,imagin
gm ode]);

Arguments in [brackets] are optional.

The second Screen command is 'CloseAll'. We'll use 'OpenWindow' and 'Close' together because if we just use 'OpenWindow' alone it'll leave the computer in a state where we can't see the Matlab command window.

Here's a simple set of commands that opens the screen and then closes it. Be sure to run these two lines together:

windowPtr=Screen('OpenWindow',0);
Screen('CloseAll');
PTB-WARNING: Startup test of beamposition queries for high precision timestamping detected problems on your graphics card + driver combo.
PTB-WARNING: Seems beamposition queries malfunction whenever the display is in a vertical retrace state!
PTB-WARNING: I will enable a work-around which should satisfy the timing needs of most applications, ie.
PTB-WARNING: robust and jitter-free deterministic timestamps. However, all reported timestamps may have a
PTB-WARNING: constant offset of up to the duration of the vertical blanking interval (max 1 msec worst case)
PTB-WARNING: of your display. Read 'help BeampositionQueries' on how you can remove that bias by some manual
PTB-WARNING: intervention, should you need that last bit of accuracy. A second drawback is increased cpu load,
PTB-WARNING: which may cause louder air-fan noise due to heat production and lower battery runtime of laptops.
PTB-WARNING: Check your vendors website for driver updates regularly, so you can get rid of this workaround asap.



PTB-INFO: This is the OpenGL-Psychtoolbox for Microsoft Windows, version 3.0.8. (Build date: Feb  3 2009)
PTB-INFO: Type 'PsychtoolboxVersion' for more detailed version information.
PTB-INFO: Psychtoolbox is licensed to you under terms of the GNU General Public License (GPL). See file 'License.txt' in the
PTB-INFO: Psychtoolbox root folder for a copy of the GPL license.



OpenGL-Extensions are: GL_ARB_color_buffer_float GL_ARB_depth_texture GL_ARB_draw_buffers GL_ARB_fragment_program GL_ARB_fragment_program_shadow GL_ARB_fragment_shader GL_ARB_half_float_pixel GL_ARB_imaging GL_ARB_multisample GL_ARB_multitexture GL_ARB_occlusion_query GL_ARB_pixel_buffer_object GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB_shadow GL_ARB_shader_objects GL_ARB_shading_language_100 GL_ARB_texture_border_clamp GL_ARB_texture_compression GL_ARB_texture_cube_map GL_ARB_texture_env_add GL_ARB_texture_env_combine GL_ARB_texture_env_dot3 GL_ARB_texture_float GL_ARB_texture_mirrored_repeat GL_ARB_texture_non_power_of_two GL_ARB_texture_rectangle GL_ARB_transpose_matrix GL_ARB_vertex_buffer_object GL_ARB_vertex_program GL_ARB_vertex_shader GL_ARB_window_pos GL_ATI_draw_buffers GL_ATI_texture_float GL_ATI_texture_mirror_once GL_S3_s3tc GL_EXT_texture_env_add GL_EXT_abgr GL_EXT_bgra GL_EXT_blend_color GL_EXT_blend_equation_separate GL_EXT_blend_func_separate GL_EXT_blend_minmax GL_EXT_blend_subtract GL_EXT_compiled_vertex_array GL_EXT_Cg_shader GL_EXT_bindable_uniform GL_EXT_depth_bounds_test GL_EXT_draw_buffers2 GL_EXT_draw_instanced GL_EXT_draw_range_elements GL_EXT_fog_coord GL_EXT_framebuffer_blit GL_EXT_framebuffer_multisample GL_EXT_framebuffer_object GL_EXTX_framebuffer_mixed_formats GL_EXT_framebuffer_sRGB GL_EXT_geometry_shader4 GL_EXT_gpu_program_parameters GL_EXT_gpu_shader4 GL_EXT_multi_draw_arrays GL_EXT_packed_depth_stencil GL_EXT_packed_float GL_EXT_packed_pixels GL_EXT_pixel_buffer_object GL_EXT_point_parameters GL_EXT_rescale_normal GL_EXT_secondary_color GL_EXT_separate_specular_color GL_EXT_shadow_funcs GL_EXT_stencil_two_side GL_EXT_stencil_wrap GL_EXT_texture3D GL_EXT_texture_array GL_EXT_texture_buffer_object GL_EXT_texture_compression_latc GL_EXT_texture_compression_rgtc GL_EXT_texture_compression_s3tc GL_EXT_texture_cube_map GL_EXT_texture_edge_clamp GL_EXT_texture_env_combine GL_EXT_texture_env_dot3 GL_EXT_texture_filter_anisotropic GL_EXT_texture_integer GL_EXT_texture_lod GL_EXT_texture_lod_bias GL_EXT_texture_mirror_clamp GL_EXT_texture_object GL_EXT_texture_sRGB GL_EXT_texture_shared_exponent GL_EXT_timer_query GL_EXT_vertex_array GL_IBM_rasterpos_clip GL_IBM_texture_mirrored_repeat GL_KTX_buffer_region GL_NV_blend_square GL_NV_copy_depth_to_color GL_NV_depth_buffer_float GL_NV_depth_clamp GL_NV_fence GL_NV_float_buffer GL_NV_fog_distance GL_NV_fragment_program GL_NV_fragment_program_option GL_NV_fragment_program2 GL_NV_framebuffer_multisample_coverage GL_NV_geometry_shader4 GL_NV_gpu_program4 GL_NV_half_float GL_NV_light_max_exponent GL_NV_multisample_filter_hint GL_NV_occlusion_query GL_NV_packed_depth_stencil GL_NV_parameter_buffer_object GL_NV_pixel_data_range GL_NV_point_sprite GL_NV_primitive_restart GL_NV_register_combiners GL_NV_register_combiners2 GL_NV_texgen_reflection GL_NV_texture_compression_vtc GL_NV_texture_env_combine4 GL_NV_texture_expand_normal GL_NV_texture_rectangle GL_NV_texture_shader GL_NV_texture_shader2 GL_NV_texture_shader3 GL_NV_transform_feedback GL_NV_vertex_array_range GL_NV_vertex_array_range2 GL_NV_vertex_program GL_NV_vertex_program1_1 GL_NV_vertex_program2 GL_NV_vertex_program2_option GL_NV_vertex_program3 GL_NVX_conditional_render GL_SGIS_generate_mipmap GL_SGIS_texture_lod GL_SGIX_depth_texture GL_SGIX_shadow GL_SUN_slice_accum GL_WIN_swap_hint WGL_EXT_swap_control 



PTB-INFO: OpenGL-Renderer is NVIDIA Corporation :: Quadro NVS 135M/PCI/SSE2 :: 2.1.1
PTB-Info: VBL startline = 800 , VBL Endline = 800
PTB-Info: Measured monitor refresh interval from beamposition = 16.701330 ms [59.875470 Hz].
PTB-Info: Will use beamposition query for accurate Flip time stamping.
PTB-Info: Measured monitor refresh interval from VBLsync = 16.690741 ms [59.913456 Hz]. (50 valid samples taken, stddev=0.071887 ms.)
PTB-Info: Reported monitor refresh interval from operating system = 16.666667 ms [60.000000 Hz].
PTB-Info: Small deviations between reported values are normal and no reason to worry.

The second argument '0' means open the default screen on your computer. If you have an external monitor (or projector), you can use '1'.

We can put up text in our screen with the Screen function 'DrawText'. These four lines opens the screen, puts up some text, pauses for two seconds and closes it:

windowPtr=Screen('OpenWindow',0);
Screen(windowPtr,'DrawText','Hello World!',500,500);
Screen('Flip',windowPtr);
pause(2)
Screen('CloseAll');
PTB-WARNING: Startup test of beamposition queries for high precision timestamping detected problems on your graphics card + driver combo.
PTB-WARNING: Seems beamposition queries malfunction whenever the display is in a vertical retrace state!
PTB-WARNING: I will enable a work-around which should satisfy the timing needs of most applications, ie.
PTB-WARNING: robust and jitter-free deterministic timestamps. However, all reported timestamps may have a
PTB-WARNING: constant offset of up to the duration of the vertical blanking interval (max 1 msec worst case)
PTB-WARNING: of your display. Read 'help BeampositionQueries' on how you can remove that bias by some manual
PTB-WARNING: intervention, should you need that last bit of accuracy. A second drawback is increased cpu load,
PTB-WARNING: which may cause louder air-fan noise due to heat production and lower battery runtime of laptops.
PTB-WARNING: Check your vendors website for driver updates regularly, so you can get rid of this workaround asap.



PTB-INFO: This is the OpenGL-Psychtoolbox for Microsoft Windows, version 3.0.8. (Build date: Feb  3 2009)
PTB-INFO: Type 'PsychtoolboxVersion' for more detailed version information.
PTB-INFO: Psychtoolbox is licensed to you under terms of the GNU General Public License (GPL). See file 'License.txt' in the
PTB-INFO: Psychtoolbox root folder for a copy of the GPL license.



OpenGL-Extensions are: GL_ARB_color_buffer_float GL_ARB_depth_texture GL_ARB_draw_buffers GL_ARB_fragment_program GL_ARB_fragment_program_shadow GL_ARB_fragment_shader GL_ARB_half_float_pixel GL_ARB_imaging GL_ARB_multisample GL_ARB_multitexture GL_ARB_occlusion_query GL_ARB_pixel_buffer_object GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB_shadow GL_ARB_shader_objects GL_ARB_shading_language_100 GL_ARB_texture_border_clamp GL_ARB_texture_compression GL_ARB_texture_cube_map GL_ARB_texture_env_add GL_ARB_texture_env_combine GL_ARB_texture_env_dot3 GL_ARB_texture_float GL_ARB_texture_mirrored_repeat GL_ARB_texture_non_power_of_two GL_ARB_texture_rectangle GL_ARB_transpose_matrix GL_ARB_vertex_buffer_object GL_ARB_vertex_program GL_ARB_vertex_shader GL_ARB_window_pos GL_ATI_draw_buffers GL_ATI_texture_float GL_ATI_texture_mirror_once GL_S3_s3tc GL_EXT_texture_env_add GL_EXT_abgr GL_EXT_bgra GL_EXT_blend_color GL_EXT_blend_equation_separate GL_EXT_blend_func_separate GL_EXT_blend_minmax GL_EXT_blend_subtract GL_EXT_compiled_vertex_array GL_EXT_Cg_shader GL_EXT_bindable_uniform GL_EXT_depth_bounds_test GL_EXT_draw_buffers2 GL_EXT_draw_instanced GL_EXT_draw_range_elements GL_EXT_fog_coord GL_EXT_framebuffer_blit GL_EXT_framebuffer_multisample GL_EXT_framebuffer_object GL_EXTX_framebuffer_mixed_formats GL_EXT_framebuffer_sRGB GL_EXT_geometry_shader4 GL_EXT_gpu_program_parameters GL_EXT_gpu_shader4 GL_EXT_multi_draw_arrays GL_EXT_packed_depth_stencil GL_EXT_packed_float GL_EXT_packed_pixels GL_EXT_pixel_buffer_object GL_EXT_point_parameters GL_EXT_rescale_normal GL_EXT_secondary_color GL_EXT_separate_specular_color GL_EXT_shadow_funcs GL_EXT_stencil_two_side GL_EXT_stencil_wrap GL_EXT_texture3D GL_EXT_texture_array GL_EXT_texture_buffer_object GL_EXT_texture_compression_latc GL_EXT_texture_compression_rgtc GL_EXT_texture_compression_s3tc GL_EXT_texture_cube_map GL_EXT_texture_edge_clamp GL_EXT_texture_env_combine GL_EXT_texture_env_dot3 GL_EXT_texture_filter_anisotropic GL_EXT_texture_integer GL_EXT_texture_lod GL_EXT_texture_lod_bias GL_EXT_texture_mirror_clamp GL_EXT_texture_object GL_EXT_texture_sRGB GL_EXT_texture_shared_exponent GL_EXT_timer_query GL_EXT_vertex_array GL_IBM_rasterpos_clip GL_IBM_texture_mirrored_repeat GL_KTX_buffer_region GL_NV_blend_square GL_NV_copy_depth_to_color GL_NV_depth_buffer_float GL_NV_depth_clamp GL_NV_fence GL_NV_float_buffer GL_NV_fog_distance GL_NV_fragment_program GL_NV_fragment_program_option GL_NV_fragment_program2 GL_NV_framebuffer_multisample_coverage GL_NV_geometry_shader4 GL_NV_gpu_program4 GL_NV_half_float GL_NV_light_max_exponent GL_NV_multisample_filter_hint GL_NV_occlusion_query GL_NV_packed_depth_stencil GL_NV_parameter_buffer_object GL_NV_pixel_data_range GL_NV_point_sprite GL_NV_primitive_restart GL_NV_register_combiners GL_NV_register_combiners2 GL_NV_texgen_reflection GL_NV_texture_compression_vtc GL_NV_texture_env_combine4 GL_NV_texture_expand_normal GL_NV_texture_rectangle GL_NV_texture_shader GL_NV_texture_shader2 GL_NV_texture_shader3 GL_NV_transform_feedback GL_NV_vertex_array_range GL_NV_vertex_array_range2 GL_NV_vertex_program GL_NV_vertex_program1_1 GL_NV_vertex_program2 GL_NV_vertex_program2_option GL_NV_vertex_program3 GL_NVX_conditional_render GL_SGIS_generate_mipmap GL_SGIS_texture_lod GL_SGIX_depth_texture GL_SGIX_shadow GL_SUN_slice_accum GL_WIN_swap_hint WGL_EXT_swap_control 



PTB-INFO: OpenGL-Renderer is NVIDIA Corporation :: Quadro NVS 135M/PCI/SSE2 :: 2.1.1
PTB-Info: VBL startline = 800 , VBL Endline = 800
PTB-Info: Measured monitor refresh interval from beamposition = 16.701296 ms [59.875593 Hz].
PTB-Info: Will use beamposition query for accurate Flip time stamping.
PTB-Info: Measured monitor refresh interval from VBLsync = 16.701106 ms [59.876275 Hz]. (50 valid samples taken, stddev=0.053903 ms.)
PTB-Info: Reported monitor refresh interval from operating system = 16.666667 ms [60.000000 Hz].
PTB-Info: Small deviations between reported values are normal and no reason to worry.

The variable 'windowPtr' returned by 'Screen' when you open the window is important - it holds a pointer to the memory register for the window which needs to be passed back into 'Screen' every time you use it.

What is this 'Flip' command? This is an important Screen function that waits for a signal that the monitor has refreshed before showing everything that has been shown since the previous 'Flip' command. (Actually it's performing a technique called 'double buffering' which involves flipping between two 'display surfaces', but we don't need to go into that right now.)

'Flip' serves two useful functions. First it ensures that any drawing happpens after the screen refresh to avoid 'tearing' artifacts that occur when a refresh occurs in the middle of putting up graphics. Second, it gives you control over the timing of your animations. As long as all of your drawing occurs in less than it a single frame (usually something like 1/60 of a second), then your animation will be performed at exactly the frame rate of the monitor, which is a very reliable thing.

Try and Catch

It can be inconvenient if you have a bug in your program that causes the program to terminate when the screen is open. To get out of this you have to switch to the command window by going to the task manager, switching to the matlab command window and typing (blindly) "Screen('CloseAll')". A nice way around this by using the 'try' and 'catch' commands (Thanks to Sungjun Joo for this suggestion). 'try' and 'catch' are commands that allow control over how erorrs are handled in Matlab. Here's an example:

try
    windowPtr = Screen('OpenWindow', 0);
    %Place a bad line of code here...
catch ME
    Screen('CloseAll');
    rethrow(ME);
end
Screen('CloseAll');
PTB-WARNING: Startup test of beamposition queries for high precision timestamping detected problems on your graphics card + driver combo.
PTB-WARNING: Seems beamposition queries malfunction whenever the display is in a vertical retrace state!
PTB-WARNING: I will enable a work-around which should satisfy the timing needs of most applications, ie.
PTB-WARNING: robust and jitter-free deterministic timestamps. However, all reported timestamps may have a
PTB-WARNING: constant offset of up to the duration of the vertical blanking interval (max 1 msec worst case)
PTB-WARNING: of your display. Read 'help BeampositionQueries' on how you can remove that bias by some manual
PTB-WARNING: intervention, should you need that last bit of accuracy. A second drawback is increased cpu load,
PTB-WARNING: which may cause louder air-fan noise due to heat production and lower battery runtime of laptops.
PTB-WARNING: Check your vendors website for driver updates regularly, so you can get rid of this workaround asap.



PTB-INFO: This is the OpenGL-Psychtoolbox for Microsoft Windows, version 3.0.8. (Build date: Feb  3 2009)
PTB-INFO: Type 'PsychtoolboxVersion' for more detailed version information.
PTB-INFO: Psychtoolbox is licensed to you under terms of the GNU General Public License (GPL). See file 'License.txt' in the
PTB-INFO: Psychtoolbox root folder for a copy of the GPL license.



OpenGL-Extensions are: GL_ARB_color_buffer_float GL_ARB_depth_texture GL_ARB_draw_buffers GL_ARB_fragment_program GL_ARB_fragment_program_shadow GL_ARB_fragment_shader GL_ARB_half_float_pixel GL_ARB_imaging GL_ARB_multisample GL_ARB_multitexture GL_ARB_occlusion_query GL_ARB_pixel_buffer_object GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB_shadow GL_ARB_shader_objects GL_ARB_shading_language_100 GL_ARB_texture_border_clamp GL_ARB_texture_compression GL_ARB_texture_cube_map GL_ARB_texture_env_add GL_ARB_texture_env_combine GL_ARB_texture_env_dot3 GL_ARB_texture_float GL_ARB_texture_mirrored_repeat GL_ARB_texture_non_power_of_two GL_ARB_texture_rectangle GL_ARB_transpose_matrix GL_ARB_vertex_buffer_object GL_ARB_vertex_program GL_ARB_vertex_shader GL_ARB_window_pos GL_ATI_draw_buffers GL_ATI_texture_float GL_ATI_texture_mirror_once GL_S3_s3tc GL_EXT_texture_env_add GL_EXT_abgr GL_EXT_bgra GL_EXT_blend_color GL_EXT_blend_equation_separate GL_EXT_blend_func_separate GL_EXT_blend_minmax GL_EXT_blend_subtract GL_EXT_compiled_vertex_array GL_EXT_Cg_shader GL_EXT_bindable_uniform GL_EXT_depth_bounds_test GL_EXT_draw_buffers2 GL_EXT_draw_instanced GL_EXT_draw_range_elements GL_EXT_fog_coord GL_EXT_framebuffer_blit GL_EXT_framebuffer_multisample GL_EXT_framebuffer_object GL_EXTX_framebuffer_mixed_formats GL_EXT_framebuffer_sRGB GL_EXT_geometry_shader4 GL_EXT_gpu_program_parameters GL_EXT_gpu_shader4 GL_EXT_multi_draw_arrays GL_EXT_packed_depth_stencil GL_EXT_packed_float GL_EXT_packed_pixels GL_EXT_pixel_buffer_object GL_EXT_point_parameters GL_EXT_rescale_normal GL_EXT_secondary_color GL_EXT_separate_specular_color GL_EXT_shadow_funcs GL_EXT_stencil_two_side GL_EXT_stencil_wrap GL_EXT_texture3D GL_EXT_texture_array GL_EXT_texture_buffer_object GL_EXT_texture_compression_latc GL_EXT_texture_compression_rgtc GL_EXT_texture_compression_s3tc GL_EXT_texture_cube_map GL_EXT_texture_edge_clamp GL_EXT_texture_env_combine GL_EXT_texture_env_dot3 GL_EXT_texture_filter_anisotropic GL_EXT_texture_integer GL_EXT_texture_lod GL_EXT_texture_lod_bias GL_EXT_texture_mirror_clamp GL_EXT_texture_object GL_EXT_texture_sRGB GL_EXT_texture_shared_exponent GL_EXT_timer_query GL_EXT_vertex_array GL_IBM_rasterpos_clip GL_IBM_texture_mirrored_repeat GL_KTX_buffer_region GL_NV_blend_square GL_NV_copy_depth_to_color GL_NV_depth_buffer_float GL_NV_depth_clamp GL_NV_fence GL_NV_float_buffer GL_NV_fog_distance GL_NV_fragment_program GL_NV_fragment_program_option GL_NV_fragment_program2 GL_NV_framebuffer_multisample_coverage GL_NV_geometry_shader4 GL_NV_gpu_program4 GL_NV_half_float GL_NV_light_max_exponent GL_NV_multisample_filter_hint GL_NV_occlusion_query GL_NV_packed_depth_stencil GL_NV_parameter_buffer_object GL_NV_pixel_data_range GL_NV_point_sprite GL_NV_primitive_restart GL_NV_register_combiners GL_NV_register_combiners2 GL_NV_texgen_reflection GL_NV_texture_compression_vtc GL_NV_texture_env_combine4 GL_NV_texture_expand_normal GL_NV_texture_rectangle GL_NV_texture_shader GL_NV_texture_shader2 GL_NV_texture_shader3 GL_NV_transform_feedback GL_NV_vertex_array_range GL_NV_vertex_array_range2 GL_NV_vertex_program GL_NV_vertex_program1_1 GL_NV_vertex_program2 GL_NV_vertex_program2_option GL_NV_vertex_program3 GL_NVX_conditional_render GL_SGIS_generate_mipmap GL_SGIS_texture_lod GL_SGIX_depth_texture GL_SGIX_shadow GL_SUN_slice_accum GL_WIN_swap_hint WGL_EXT_swap_control 



PTB-INFO: OpenGL-Renderer is NVIDIA Corporation :: Quadro NVS 135M/PCI/SSE2 :: 2.1.1
PTB-Info: VBL startline = 800 , VBL Endline = 800
PTB-Info: Measured monitor refresh interval from beamposition = 16.701325 ms [59.875490 Hz].
PTB-Info: Will use beamposition query for accurate Flip time stamping.
PTB-Info: Measured monitor refresh interval from VBLsync = 16.700944 ms [59.876855 Hz]. (50 valid samples taken, stddev=0.021318 ms.)
PTB-Info: Reported monitor refresh interval from operating system = 16.666667 ms [60.000000 Hz].
PTB-Info: Small deviations between reported values are normal and no reason to worry.

This should function normally, but if you add a bad line of code anywherer between 'try' and me', control will be sent to the lines following the 'catch' command. Here, the screen is closes and the error message is displayed in the command window using the 'rethrow' command.

A customized version of OpenWindow

You may get a series of scary warnings both in the command window and on the screen when Screen is used, depending on the computer you're using. When a screen is opened, a variety of checks are made by Screen to determine issues such as the timing of the referesh rate. Don't let the guys who wrote the psychtoolbox know I said this, but I find some of these dire warnings to be not so dire, like the ones about skipping video frames. Fortunately, you can turn these warnings off using the 'Screen('Preference') command.

You can set a variety of screen attributes with the 'Screen('Preference') command. You can get help the usual way:

Screen('Preference?')
Usage:

oldPreferenceValue = Screen('Preference', preferenceName, [newPreferenceValue])

Get or set a Psychtoolbox preference.Preference settings are global - they
affect all operations of a module until changed.
oldBool = Screen('Preference', 'IgnoreCase', [bool]);
tick0Secs = Screen('Preference', 'Tick0Secs', tick0Secs);
psychTableVersion = Screen('Preference', 'PsychTableVersion');
mexFunctionName = Screen('Preference', 'PsychTableCreator');
proc = Screen('Preference', 'Process', signature);
proc = Screen('Preference', 'DebugMakeTexture', enableDebugging);
oldEnableFlag = Screen('Preference', 'TextAlphaBlending', [enableFlag]);
oldEnableFlag = Screen('Preference', 'DefaultTextYPositionIsBaseline',
[enableFlag]);
oldEnableFlag = Screen('Preference', 'TextAntiAliasing', [enableFlag=-1 (System
setting), 0 = Disable, 1 = Enable, 2 = EnableHighQuality]);
oldEnableFlag = Screen('Preference', 'TextRenderer', [enableFlag=0 (Default
OS-specific [fast]), 1 = HighQ OS-specific]);
oldEnableFlag = Screen('Preference', 'SkipSyncTests', [enableFlag]);
oldLevel = Screen('Preference', 'VisualDebugLevel', level);

Workaround flags to work around all kind of deficient drivers and hardware:
See 'help ConserveVRAMSettings' for settings and their effect.

oldMode = Screen('Preference', 'ConserveVRAM', mode);

Activate compatibility mode: Try to behave like the old MacOS-9 Psychtoolbox:
oldEnableFlag = Screen('Preference', 'EmulateOldPTB', [enableFlag]);

oldEnableFlag = Screen('Preference', 'Enable3DGraphics', [enableFlag]);
oldEnableFlag = Screen('Preference', 'SuppressAllWarnings', [enableFlag]);
oldMode = Screen('Preference', 'VBLTimestampingMode', [newmode]);
oldVTOTAL = Screen('Preference', 'VBLEndlineOverride' [, newVTOTAL]);
oldMode = Screen('Preference', 'DefaultVideocaptureEngine', [newmode
(0=Quicktime-SequenceGrabbers, 1=LibDC1394-Firewire)]);
residuals = Screen('Preference', 'SynchronizeDisplays', syncMethod);
oldLevel = Screen('Preference', 'Verbosity' [,level]);

I've written a function called 'OpenWindow' that calls 'OpenScreen' after setting some of the preferences beforehand to avoid warnings (if desired). I find this function useful because it hides a bunch of ugly lines that I used to have to include every time I opened the window. It also opens the screen to a default color of black.

It also introduces a structure called 'display' that contains useful information about the current computer display, such as the 'windowPtr' variable. Later we'll add fields to this structure about the viewing distance that will allow us to define our stimuli in 'real-world' parameters like degrees of visual angle and seconds rather than display-oriented parameters like pixels and frames.

Here's an example of how to use 'OpenWindow'.

try
    display = OpenWindow;
    Screen(display.windowPtr,'DrawText','Psychophysics Rules!',500,500,[255,0,0]);
    Screen('Flip',display.windowPtr);
    pause(2)
catch ME
    Screen('CloseAll');
    rethrow(ME)
end
Screen('CloseAll');
PTB-WARNING: Startup test of beamposition queries for high precision timestamping detected problems on your graphics card + driver combo.
PTB-WARNING: Seems beamposition queries malfunction whenever the display is in a vertical retrace state!
PTB-WARNING: I will enable a work-around which should satisfy the timing needs of most applications, ie.
PTB-WARNING: robust and jitter-free deterministic timestamps. However, all reported timestamps may have a
PTB-WARNING: constant offset of up to the duration of the vertical blanking interval (max 1 msec worst case)
PTB-WARNING: of your display. Read 'help BeampositionQueries' on how you can remove that bias by some manual
PTB-WARNING: intervention, should you need that last bit of accuracy. A second drawback is increased cpu load,
PTB-WARNING: which may cause louder air-fan noise due to heat production and lower battery runtime of laptops.
PTB-WARNING: Check your vendors website for driver updates regularly, so you can get rid of this workaround asap.



PTB-INFO: This is the OpenGL-Psychtoolbox for Microsoft Windows, version 3.0.8. (Build date: Feb  3 2009)
PTB-INFO: Type 'PsychtoolboxVersion' for more detailed version information.
PTB-INFO: Psychtoolbox is licensed to you under terms of the GNU General Public License (GPL). See file 'License.txt' in the
PTB-INFO: Psychtoolbox root folder for a copy of the GPL license.



OpenGL-Extensions are: GL_ARB_color_buffer_float GL_ARB_depth_texture GL_ARB_draw_buffers GL_ARB_fragment_program GL_ARB_fragment_program_shadow GL_ARB_fragment_shader GL_ARB_half_float_pixel GL_ARB_imaging GL_ARB_multisample GL_ARB_multitexture GL_ARB_occlusion_query GL_ARB_pixel_buffer_object GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB_shadow GL_ARB_shader_objects GL_ARB_shading_language_100 GL_ARB_texture_border_clamp GL_ARB_texture_compression GL_ARB_texture_cube_map GL_ARB_texture_env_add GL_ARB_texture_env_combine GL_ARB_texture_env_dot3 GL_ARB_texture_float GL_ARB_texture_mirrored_repeat GL_ARB_texture_non_power_of_two GL_ARB_texture_rectangle GL_ARB_transpose_matrix GL_ARB_vertex_buffer_object GL_ARB_vertex_program GL_ARB_vertex_shader GL_ARB_window_pos GL_ATI_draw_buffers GL_ATI_texture_float GL_ATI_texture_mirror_once GL_S3_s3tc GL_EXT_texture_env_add GL_EXT_abgr GL_EXT_bgra GL_EXT_blend_color GL_EXT_blend_equation_separate GL_EXT_blend_func_separate GL_EXT_blend_minmax GL_EXT_blend_subtract GL_EXT_compiled_vertex_array GL_EXT_Cg_shader GL_EXT_bindable_uniform GL_EXT_depth_bounds_test GL_EXT_draw_buffers2 GL_EXT_draw_instanced GL_EXT_draw_range_elements GL_EXT_fog_coord GL_EXT_framebuffer_blit GL_EXT_framebuffer_multisample GL_EXT_framebuffer_object GL_EXTX_framebuffer_mixed_formats GL_EXT_framebuffer_sRGB GL_EXT_geometry_shader4 GL_EXT_gpu_program_parameters GL_EXT_gpu_shader4 GL_EXT_multi_draw_arrays GL_EXT_packed_depth_stencil GL_EXT_packed_float GL_EXT_packed_pixels GL_EXT_pixel_buffer_object GL_EXT_point_parameters GL_EXT_rescale_normal GL_EXT_secondary_color GL_EXT_separate_specular_color GL_EXT_shadow_funcs GL_EXT_stencil_two_side GL_EXT_stencil_wrap GL_EXT_texture3D GL_EXT_texture_array GL_EXT_texture_buffer_object GL_EXT_texture_compression_latc GL_EXT_texture_compression_rgtc GL_EXT_texture_compression_s3tc GL_EXT_texture_cube_map GL_EXT_texture_edge_clamp GL_EXT_texture_env_combine GL_EXT_texture_env_dot3 GL_EXT_texture_filter_anisotropic GL_EXT_texture_integer GL_EXT_texture_lod GL_EXT_texture_lod_bias GL_EXT_texture_mirror_clamp GL_EXT_texture_object GL_EXT_texture_sRGB GL_EXT_texture_shared_exponent GL_EXT_timer_query GL_EXT_vertex_array GL_IBM_rasterpos_clip GL_IBM_texture_mirrored_repeat GL_KTX_buffer_region GL_NV_blend_square GL_NV_copy_depth_to_color GL_NV_depth_buffer_float GL_NV_depth_clamp GL_NV_fence GL_NV_float_buffer GL_NV_fog_distance GL_NV_fragment_program GL_NV_fragment_program_option GL_NV_fragment_program2 GL_NV_framebuffer_multisample_coverage GL_NV_geometry_shader4 GL_NV_gpu_program4 GL_NV_half_float GL_NV_light_max_exponent GL_NV_multisample_filter_hint GL_NV_occlusion_query GL_NV_packed_depth_stencil GL_NV_parameter_buffer_object GL_NV_pixel_data_range GL_NV_point_sprite GL_NV_primitive_restart GL_NV_register_combiners GL_NV_register_combiners2 GL_NV_texgen_reflection GL_NV_texture_compression_vtc GL_NV_texture_env_combine4 GL_NV_texture_expand_normal GL_NV_texture_rectangle GL_NV_texture_shader GL_NV_texture_shader2 GL_NV_texture_shader3 GL_NV_transform_feedback GL_NV_vertex_array_range GL_NV_vertex_array_range2 GL_NV_vertex_program GL_NV_vertex_program1_1 GL_NV_vertex_program2 GL_NV_vertex_program2_option GL_NV_vertex_program3 GL_NVX_conditional_render GL_SGIS_generate_mipmap GL_SGIS_texture_lod GL_SGIX_depth_texture GL_SGIX_shadow GL_SUN_slice_accum GL_WIN_swap_hint WGL_EXT_swap_control 



PTB-INFO: OpenGL-Renderer is NVIDIA Corporation :: Quadro NVS 135M/PCI/SSE2 :: 2.1.1
PTB-Info: VBL startline = 800 , VBL Endline = 800
PTB-Info: Measured monitor refresh interval from beamposition = 16.701307 ms [59.875552 Hz].
PTB-Info: Will use beamposition query for accurate Flip time stamping.
PTB-Info: Measured monitor refresh interval from VBLsync = 16.701316 ms [59.875522 Hz]. (296 valid samples taken, stddev=0.263041 ms.)
PTB-Info: Reported monitor refresh interval from operating system = 16.666667 ms [60.000000 Hz].
PTB-Info: Small deviations between reported values are normal and no reason to worry.

Note the [255,0,0] which defines the color of the text to be red (r,g,b).

Also check out the display structure:

display
display = 

     screenNum: 0
       bkColor: [0 0 0]
    skipChecks: 0
     windowPtr: 10
     frameRate: 59.8755
    resolution: [1280 800]

(Your results may vary). It has fields with information about the display's frame rate and screen resolution.

You can set some parameters for OpenWindow by passing in an existing 'display' structure. More information about this can be seen by getting help:

help OpenWindow
 display = OpenWindow([display])
 
 Calls the psychtoolbox command "Screen('OpenWindow') using the 'display'
 structure convention.
 
 Inputs:
    display             A structure containing display information with fields:
        screenNum       Screen Number (default is 0)
        bkColor         Background color (default is black: [0,0,0])
        skipChecks      Flag for skpping screen synchronization (default is 0, or don't check)
                        When set to 1, vbl sync check will be skipped,
                        along with the text and annoying visual (!) warning
 
 Outputs:
    display             Same structure, but with additional fields filled in:
        windowPtr       Pointer to window, as returned by 'Screen'
        frameRate       Frame rate in Hz, as determined by Screen('GetFlipInterval')
        resolution      [width,height] of screen in pixels
 
 Note: for full functionality, the additional fields of 'display' should be
 filled in:
 
        dist             distance of viewer from screen (cm)
        width            width of screen (cm)

Exersises

For this week's homework, please use the 'try' and 'catch' commands as described here, and use the OpenWindow function.

  1. Write a script called 'YellowOnBlue.m' that opens the screen with a blue background, puts up yellow letters [255,255,0] saying 'Yellow on Blue', pauses for 5 seconds and closes the window.
  2. Use the 'Flip' command in a loop instead of the 'Pause' command. For example, if your monitor has a frame rate of 60Hz, then a loop with 60 calls to 'Flip' will take exactly one second.