Merge pull request #165 from kleinerm/master

PTB BETA RELEASE "Hammertime!"

* PTB for 32-Bit Matlab on Windows now uses and requires the GStreamer SDK instead of OSSBuilds GStreamer.
* Bugfix for GStreamer on Windows for special pixelformat >= 6.
* Bugfix for Linux + PsychHID.
* Bugfix for OSX crash at window close due to Apple CVDisplayLink bugs on Matlab R2013b.
* OpenGL context sharing support between windowed and fullscreen windows on OSX.
* Improved GUI window support.
* Low-level support for latest AMD GPU's on Linux and with OSX PsychtoolboxKernelDriver.
* WinTabMex support now also for 64-Bit Matlab on Windows.
* And in PlayMoviesDemo's cool section: "Stop! Hammertime!"
Merge pull request #167 from kleinerm/master

Hammertime!
GetEchoString, GetKbChar: Fix for Linux.

Need to leave text user alpha blend setting disabled on Linux, as
opposed to Windows and OSX.

Also add recognition of Backspace key as character delete key, otherwise
we wouldn't have any character delete key on many Apple keyboards.
libptbdrawtext_ftgl: Workaround typo in public api.
Screen/Linux: Implement our own display locking instead of XLib's

This is mostly to protect access to XLib functions (and also GLX functions, as they
are using XLib/X11 as transport), but could also be used to protect access to other
backend libraries for display configuration and stimulus onset control.

We use this as we don't want to rely on XLib's builtin locking and thread-safety.
Why? Because XLib's multi-threading protection must be initialized at application
startup time *before any other XLib calls* via a call to XInitThreads(), and we
do not have any control if or when that XInitThreads() call happens, so it is better
to not rely on Octave, Matlab or other future hosting environments doing the right
thing. Instead we implement our own locking around potentially racy XLib calls.

XLib itself is reentrant, but concurrent access by multiple threads to the same xdisplay
connection handle, and thereby to the same x-windows connection queue is not safe.

We use one shared xdisplay handle for all onscreen windows and screens, across all of
Screen's threads (main thread and async flipper/frame-sequential stereo threads). We
need to use one shared handle because otherwise OpenGL context resource sharing and the
OML_sync_control timing and timestamping functions won't work properly. Therefore we
must lock-protect all calls by all threads to XLib. N.b. PsychHID uses its own private
xdisplay handles for its KbQueue thread and KbCheck, but those handles are really only
used exclusively by one respective thread, so no need to worry about locking PsychHID's
ones.

For now we only maintain a global lock and will extend this into finer-grained locking if
neccessary. Using XCB would be another option, but that would be a huge rewrite with
rather sparse documentation available...

One small problem: GetMouse() is still implemented via Screen('GetMouseHelper') on
the x-display connection of Screen. This means that a very fast polling GetMouse could
in theory cause lock contention on the lock used by async flipper threads and possibly
delay a bufferswap if oml-sync-control is not in use, e.g., on the proprietary Nvidia
and AMD binary blob graphics drivers. Hard to say how serious this problem really
can be in practice.

-> Screen.mex for 64-Bit Octave on Linux rebuilt and lightly tested.
-> Old XInitThreads() call in Screen disabled.
-> Small optimization in GetMouse.m to avoid one redundant call.
GetMouse, mogldrawdots3D: Micro-Optimizations for speed.

GetMouse: Make sure, lazy evaluation in if-statement evaluates
the cheaper condition first, to shove of a few microseconds.

moglDrawDots3D: ismember() is apparently a rather expensive function
in both octave and matlab, so only use it for checking against large
target sets, not for trivial checks for only 2 values, as we did.
This should save significant time in parameter validation and thereby
function execution.
Screen: Improve drawtext plugins for Linux, add font caching.

The drawtext rendering plugins on Linux (and optionally OSX) now
maintain separate sets of OGLT or FTGLES font objects for use in
OpenGL text rendering for each onscreen window. For this purpose,
Screen() now passes the numeric parent onscreen window handle for
each drawingtarget (onscreen/offscreen/texture) as a "contextId"
to the drawtext plugins. The plugins distinguish different windows
and thereby associated OpenGL contexts and maintain settings for
each of them.

This is to allow that OpenGL resources like display lists and glyph
textures or glyph atlas textures are not shared between master OpenGL
contexts, but stored separately. This makes text rendering work if
OpenGL context resource sharing is either disabled by usercode, or
impossible, e.g., because different onscreen windows are located
on different X-Screens and therefore can't share resources.

-> DrawText now works if multiple onscreen windows are opened on
   different X-Screens. Before it malfunctioned for all but the
   first opened window due to the unsatisfiably OpenGL context
   resource sharing requirement.

Additionally, a LRU cache is now implemented for font objects
corresponding to different font settings of a context. The cache can
hold a certain amount of font objects and performs LRU replacement
on each context, if the cache gets full. This way, switching between
different text settings on Linux no longer slows down the succeeding
drawtext call if the font objects are already in the cache.

-> Provides constant speed text rendering when switching text settings,
   wheras before, a slowdown of about 10x - 15x was observed after a
   setting change. Typical numbers from a 2010 MacBookPro with NVidia
   GeForce 330M: About ~0.3 msecs per "Hello World!" text draw with
   constant or switched settings. Before the caching, switching settings
   caused a slowdown to about 3.5 msecs for first draw after switch.

-> Screen() for 64-Bit Octave on Linux rebuilt with new plugin api context
   support and tested.

-> libptbdrawtext_ftgl[es]64.so.1 for 64-Bit Linux with OpenGL / OpenGL-ES
   modified, rebuilt and tested.

A new benchmark DrawTextFontSwitchSpeedTest.m allows to benchmark performance
of text switching on a system.

Additionally the text renderer on Linux now returns the true font family name
aka Screen('TextFont') of a selected font, *after* a Screen('DrawText') call,
so scripts can actually check if they got the font they wanted, or just a
substitute font, because the requested font wasn't installed on the system.

Some robustness improvements were made to FontInfo.m to test and demonstrate
this.

-> All Linux and OSX Screen / drawtextplugin mex files need rebuild before release.
Linux: Rename "Makefiles", clean them up a bit.

-> Shorter names without useless and outdated _ubuntugutsy postfix.
-> Help text describes actual purpose of the files.
-> Better error checking and tidying up.
Screen: Make timestamp check for OpenML/OS-Builtin method slightly more paranoid.

So far we didn't check for swap completion timestamps before swap was scheduled
if the swap was scheduled via normal bufferswap call, instead of osspecific_asyncflip.

Add a check for this as well.

-> Screen for 64-Bit Octave on Linux rebuilt.
Delete old makefiles for 32-Bit OSX, old Windows.

Also delete the 32-Bit drawtext plugin for OSX, now that we don't
support 32-Bit Matlab/Octave on OSX anymore.
Add Super-Joana's SuperShapeDemo :)

A new OpenGL demo, demonstrating rendering of so called Supershapes.
Drawing / rotating the shape is fast. Creation/Updating of the shapes
shape is relatively slow, due to computation on the CPU. This could
only get much faster by use of GLSL Vertex- and Geometryshading on the
GPU.

This demo was contributed by Joana Leitao.

-> PsychDemos/OpenGL4MatlabDemos/SuperShapeDemo.m added.
DaqAInScan: Add the hack used by user masondar for 64-Bit OSX.

64-Bit OSX has problems detecting all Daq interfaces properly.
Add some hack that worked for one user on the forum "masondar123",
e.g., ptb forum message thread from June 7 2013.

If we are on 64-Bit OSX, aka IsOSX(1), we turn detection error()'s
into pure warning()'s and hard-code the 'IndexRange' of interfaces
to scan, instead of using the flawed detection results.

Testing on my USB-1408FS showed that DaqAInScan works reliably
on Linux and Windows, and sort of ok on 32-Bit OSX. On 64-Bit OSX
this hack doesn't help me on 10.5.8 Leopard or 10.7.x Lion, but
masondar reported success on a 10.8 system with USB-1608FS. If this
is due to different devices, or different OS'es, or different
runtimes or just luck, who knows? Anyway, add this hack to make
stuff work at least on the one setup (masondar's) were it apparently
can work. Hopefully this also helps others...

-> DaqAInScan.m modified.
DaqAInScan: Fix interface enumeration again - Code from hell!

If the .product name string is empty in listed AllSNs, then
the following strvcat deletes those slots and the numbering
changes!

Add dummy 'xoxo' strings whenever an empty .product string
is encountered, so this failure is prevented.

-> Makes it work on the other Linux box.
DaqAInScan: More code from hell...

Try to make daq detection more robust on OSX - always choose device
with maximum index. Yes, it is pathetic… …and it still doesn't work on
my 10.7.5 with
64-Bit Matlab.
Revert "DaqAInScan: More code from hell..."

This reverts commit 87fbd7ccdb2f4d98826f27474077c7ce13b9b9af.

The idea is correct, but this must happen outside of this
function, in DaqDeviceIndex, or we'll use inconsistent daq
indices on different calls.
Fix bug in ComputeNakaRushton.  This was not a pretty bug.  Not sure when it was introduced.

The code was dividing the contrast in the numerator by sigma before exponentiation.  This made no sense and is not what the comments said the routine did.  I fixed it to match the comments (which correctly describe the Naka-Rushton.)

If there is code somewhere that counts on this bug, that code will now break.  But it probably should rather than trying to preserve backwards compatibility with what this routine was doing.

Signed-off-by: David Brainard <brainard@psych.upenn.edu>
Remove dependence on degtorad, radtodeg.  These are in a Matlab toolbox that not everyone has.  Didn't actually test, but I think they should be OK.

Signed-off-by: David Brainard <brainard@psych.upenn.edu>
Screen/PsychImaging: Add support for display rotation via panelfitter.

Extend the Screen() panelfitter to handle rotation of the framebuffer:
Imaging pipelines identity blitter now also accepts optional paramters
for rotation of the final image by some 'Rotation:%f' angle around a
'RotCenter:%f:%f' cx,cy center and applies it if a non-zero angle is
specified.

The panelfitter code takes advantage of this rotation. It adds angle,
cx and cy as new optional parameters for the Screen('PanelFitter')
parameter vector to set those params. If a non-zero angle is requested,
the fallback path with texture blitting via kPsychIdentityBlitChain is
used, instead of the faster glFramebufferBlit code, which is incapable
of rotations.

PsychImaging has new high-level setup code for rotation during panel
fitting, as exposed in PsychImaging('UsePanelFitter') via a new
optional 'angle' parameter, and for convenience, via a new
PsychImaging('UseDisplayRotation') function for display rotation only.
The current setup code has bugs or limitations: It only handles either
scaling/fitting or rotation well, and usually also only rotation by 90
degree increments. Iow. it handles the most common use case right, but
fails in various ways for more exotic or complex demands.

-> Screen for 64-Bit Matlab on OSX rebuilt and tested.
-> A new demo PanelFitterDemo.m demonstrates use of the panelfitter for
display rotation, scaling and panel fitting.
Screen: Allow use of multisample textures for multisample anti-aliasing.

If GL_ARB_texture_multisample extension is supported, then preferrably
create and use multisample textures as color attachments for the
imaging pipeline drawBufferFBO's if multisampling is requested. Only
fallback to good ol' multisampled renderbuffers if textures fail or are
unsupported.

Multisample textures have the advantage that they can be used with the
imaging pipelines identity blit chain, and thereby by the panelfitter
fallback code. This should allow to provide framebuffer rotation for
multisampled framebuffers via the panelfitter.

It also provides yet another fallback for multisample resolve if scaled
multisample resolves are not supported.

So far the theory. In practice the code-path is only compile-tested,
because Apple's crappy os doesn't expose the needed extension under
OpenGL 2.1, despite the gpu being perfectly capable of supporting it.
-> Will need reboot to a real os for testing.
Screen: Disable beamposition queries for Intel gpu's under OSX and Linux.

In light of the latest insights about Intel hw design defects and
possible hard lockups/crashes of Intel chipsets if register reads
aren't serialized on the gpu, use of our homegrown beamposition
implementation via MMIO register direct access is no longer safe, as we
can't serialize access with the os kernel graphics driver.

-> Disable use of PsychtoolboxKernelDriver instances for Intel on OSX
and of direct mmap() MMIO mapping on Linux. This can be overriden via
setenv('PSYCH_ALLOW_DANGEROUS', '1') for testing by the really brave.

-> This is no loss on Linux, as the DRI2/Intel-KMS graphics driver
provides high quality OpenML timestamping anyway.
-> This is a kiss of death on OSX for Intel GPU's if precision timing
is needed, as OSX CGDisplayBeamposition() is not and was not ever
supported on Intel IGP's.
-> On MS-Windows we can continue to use DirectDraw GetScanLine() in the
hope that the MS-Windows Intel gpu drivers properly serialize their
accesses. However, the most likely implementation they have chosen will
make beampos queries less robust and accurate, thereby reducing the
effectiveness of beampos timestamping on Windows as well.

-> Linux as the last bastion of Intel graphics for vision science.