1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
|
"""
This module contains the base classes for visual stimuli.
"""
__author__ = 'Florian Krause <florian@expyriment.org>, \
Oliver Lindemann <oliver@expyriment.org>'
__version__ = '0.7.0'
__revision__ = '55a4e7e'
__date__ = 'Wed Mar 26 14:33:37 2014 +0100'
import tempfile
import os
import copy
import random
import types
import pygame
try:
import OpenGL.GLU as oglu
import OpenGL.GL as ogl
except ImportError:
oglu = None
ogl = None
import defaults
import expyriment
from _stimulus import Stimulus
from expyriment.misc import geometry
from expyriment.misc import unicode2str
from expyriment.misc._timer import get_time
random.seed()
class _LaminaPanelSurface(object):
"""A class implementing an OpenGL surface."""
# The following code is based on part of the Lamina module by David Keeney
# (http://pitchersduel.python-hosting.com/file/branches/Lamina/lamina.py)
# with some modifications to fit it into expyriment (e.g. positioning)
def __init__(self, surface, quadDims=(-1, 1, 1, 1),
position=(0, 0)):
"""Initialize new instance.
Parameters
----------
surface : pygame surface
pygame surface to convert
quadDims : (int,int), optional
position : (int,int), optional
"""
self._txtr = Visual._load_texture(surface)
self._winsize = surface.get_size()
self._position = position
left, top, width, height = quadDims
right, bottom = left + width, top - height
self._qdims = quadDims
self.dims = ((left, top, 0), (right, top, 0),
(right, bottom, 0), (left, bottom, 0))
self.refresh_position()
def __del__(self):
"""Call glDeleteTextures when deconstruction the object."""
if self._txtr is not None:
try:
ogl.glDeleteTextures([self._txtr])
except:
pass
def convertMousePos(self, pos):
"""Convert 2d pixel mouse pos to 2d gl units.
Parameters
----------
pos : (int, int)
position of mouse
"""
x0, y0 = pos
x = x0 / self._winsize[0] * self._qdims[2] + self._qdims[0]
y = y0 / self._winsize[1] * self._qdims[3] + self._qdims[1]
return x, y
def refresh_position(self):
"""Recalc where in modelspace quad needs to be to fill screen."""
screensize = pygame.display.get_surface().get_size()
bottomleft = oglu.gluUnProject(screensize[0] / 2 - \
self._winsize[0] / 2 + \
self._position[0],
screensize[1] / 2 - \
self._winsize[1] / 2 + \
self._position[1], 0)
bottomright = oglu.gluUnProject(screensize[0] / 2 + \
self._winsize[0] / 2 + \
self._position[0],
screensize[1] / 2 - \
self._winsize[1] / 2 + \
self._position[1], 0)
topleft = oglu.gluUnProject(screensize[0] / 2 - \
self._winsize[0] / 2 + \
self._position[0],
screensize[1] / 2 + \
self._winsize[1] / 2 + \
self._position[1], 0)
topright = oglu.gluUnProject(screensize[0] / 2 + \
self._winsize[0] / 2 + \
self._position[0],
screensize[1] / 2 + \
self._winsize[1] / 2 + \
self._position[1], 0)
self.dims = topleft, topright, bottomright, bottomleft
width = topright[0] - topleft[0]
height = topright[1] - bottomright[1]
self._qdims = topleft[0], topleft[1], width, height
def display(self):
"""Draw surface to a quad."""
ogl.glEnable(ogl.GL_BLEND)
ogl.glBlendFunc(ogl.GL_SRC_ALPHA, ogl.GL_ONE_MINUS_SRC_ALPHA)
ogl.glEnable(ogl.GL_TEXTURE_2D)
ogl.glBindTexture(ogl.GL_TEXTURE_2D, self._txtr)
ogl.glTexEnvf(ogl.GL_TEXTURE_ENV, ogl.GL_TEXTURE_ENV_MODE,
ogl.GL_REPLACE)
ogl.glTexParameterfv(ogl.GL_TEXTURE_2D, ogl.GL_TEXTURE_MIN_FILTER,
ogl.GL_LINEAR)
ogl.glBegin(ogl.GL_QUADS)
ogl.glTexCoord2f(0.0, 1.0)
ogl.glVertex3f(*self.dims[0])
ogl.glTexCoord2f(1.0, 1.0)
ogl.glVertex3f(*self.dims[1])
ogl.glTexCoord2f(1.0, 0.0)
ogl.glVertex3f(*self.dims[2])
ogl.glTexCoord2f(0.0, 0.0)
ogl.glVertex3f(*self.dims[3])
ogl.glEnd()
ogl.glDisable(ogl.GL_BLEND)
ogl.glDisable(ogl.GL_TEXTURE_2D)
# End of code bsed on Lamina module
class Visual(Stimulus):
"""A class implementing a general visual stimulus.
All other visual stimuli should be subclassed from this class since it
entails code for converting Pygame surfaces into OpenGL textures. This
allows for having hardware acceleration (including waiting for the
vertical retrace) while still being able to manipulate stimuli in an
easy way (based on Pygame surfaces).
"""
# The following code is based on part of the Lamina module by David Keeney
# (http://pitchersduel.python-hosting.com/file/branches/Lamina/lamina.py)
# with some modifications to fit it into expyriment (e.g. positioning)
@staticmethod
def _load_texture(surf):
"""Load surface into texture object.
Returns a texture object.
Parameters
----------
surf : pygame.Surface object
surface to make texture from
"""
txtr = ogl.glGenTextures(1)
textureData = pygame.image.tostring(surf, "RGBA", 1)
ogl.glEnable(ogl.GL_TEXTURE_2D)
ogl.glBindTexture(ogl.GL_TEXTURE_2D, txtr)
width, height = surf.get_size()
ogl.glTexImage2D(ogl.GL_TEXTURE_2D, 0, ogl.GL_RGBA, width, height, 0,
ogl.GL_RGBA, ogl.GL_UNSIGNED_BYTE, textureData)
ogl.glTexParameterf(ogl.GL_TEXTURE_2D,
ogl.GL_TEXTURE_MAG_FILTER,
ogl.GL_NEAREST)
ogl.glTexParameterf(ogl.GL_TEXTURE_2D,
ogl.GL_TEXTURE_MIN_FILTER,
ogl.GL_NEAREST)
ogl.glDisable(ogl.GL_TEXTURE_2D)
return txtr
# End of code bsed on Lamina module
def __init__(self, position=None, log_comment=None):
"""Create a visual stimulus.
Parameters
----------
position : (int,int), optional
position of the stimulus
log_comment : str, optional
comment for the event log file
"""
Stimulus.__init__(self, log_comment)
if position:
self._position = list(position)
else:
self._position = list(defaults.visual_position)
self._surface = None
self._is_preloaded = False
self._parent = None
self._ogl_screen = None
self._is_compressed = False
self._compression_filename = None
self._was_compressed_before_preload = None
_compression_exception_message = "Cannot call {0} on compressed stimuli!"
def __del__(self):
""" Clear surface and ogl_screen when when the objects is deconstructed.
"""
try:
self.clear_surface()
except:
pass
if self._compression_filename is not None:
try:
os.remove(self._compression_filename)
except:
pass
@property
def position(self):
"""Getter for position."""
return self._position
@position.setter
def position(self, value):
"""Setter for position.
When using OpenGL, this can take longer then 1ms!
"""
self._position = list(value)
if self.is_preloaded and self._ogl_screen is not None:
self._ogl_screen.refresh_position()
@property
def absolute_position(self):
"""Getter for absolute_position."""
if self._parent:
return (self._parent.absolute_position[0] + self.position[0],
self._parent.absolute_position[1] + self.position[1])
else:
return self.position
@property
def is_compressed(self):
"""Getter for is_compressed."""
return self._is_compressed
@property
def has_surface(self):
"""Getter for has_surface."""
if self._surface is not None:
return True
else:
return self.is_compressed
@property
def surface_size(self):
""" Getter for surface_size."""
return self._get_surface().get_size()
def _create_surface(self):
"""Get the surface of the stimulus.
This method has to be overwritten for all subclasses individually!
"""
surface = pygame.surface.Surface((0, 0))
return surface
def _set_surface(self, surface):
"""Set the surface.
Parameters
----------
surface : pygame surface
surface to be set
"""
if self.is_compressed:
return False
else:
self._surface = surface
return True
def _get_surface(self):
"""Get the surface."""
if self._surface:
return self._surface
else:
if self.is_compressed:
tmp = pygame.image.load(
self._compression_filename).convert_alpha()
else:
tmp = self._create_surface()
return tmp
def copy(self):
"""Deep copy of the visual stimulus.
Returns
-------
copy : deep copy of self
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
if self.has_surface:
surface_backup = self._get_surface().copy()
surface_copy = self._get_surface().copy()
rtn = Stimulus.copy(self)
if self.has_surface:
self._surface = surface_backup
rtn._surface = surface_copy
rtn._is_preloaded = False
rtn._ogl_screen = None
rtn._is_compressed = False
rtn._compression_filename = None
if self.is_preloaded:
if expyriment._active_exp.screen.open_gl:
self._ogl_screen = _LaminaPanelSurface(
self._get_surface(),
position=self.position)
rtn.preload()
if self.is_compressed:
rtn.compress()
rtn._was_compressed_before_preload = \
self._was_compressed_before_preload
return rtn
def distance(self, other):
"""Surface center distance.
This method computes the distance between the surface center
of this and another visual stimulus.
Parameters
----------
other : stimulus
the other visual stimulus
Returns
-------
dist : float
distance between surface centers
"""
return geometry.XYPoint(
self.position).distance(geometry.XYPoint(other.position))
def move(self, offset):
"""Moves the stimulus in 2D space.
When using OpenGL, this can take longer then 1ms!
Parameters
----------
offset : list, optional
translation along x and y axis
Returns
-------
time : int
the time it took to execute this method
"""
start = get_time()
moved = False
x = offset[0]
y = offset[1]
if x > 0 or x < 0:
self._position[0] = self._position[0] + x
moved = True
if y > 0 or y < 0:
self._position[1] = self._position[1] + y
moved = True
if moved and self._ogl_screen is not None:
self._ogl_screen.refresh_position()
return int((get_time() - start) * 1000)
def inside_stimulus(self, stimulus, mode="visible"):
"""Check if stimulus is inside another stimulus.
Parameters
----------
stimulus : expyriment stimulus
the other stimulus
mode : mode (str), optional
"visible": based on non-transparent pixels or
"rectangle": based on pixels in pygame surface
(default = visible")
Returns
-------
out : bool
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
if mode == "visible":
screen_size = expyriment._active_exp.screen.surface.get_size()
self_size = self.surface_size
other_size = stimulus.surface_size
self_pos = (
self.position[0] + screen_size[0] / 2 - self_size[0] / 2,
- self.position[1] + screen_size[1] / 2 - self_size[1] / 2)
other_pos = (
stimulus.position[0] + screen_size[0] / 2 - other_size[0] / 2,
- stimulus.position[1] + screen_size[1] / 2 - other_size[1] / 2)
offset = (-self_pos[0] + other_pos[0], -self_pos[1] + other_pos[1])
self_mask = pygame.mask.from_surface(self._get_surface())
other_mask = pygame.mask.from_surface(stimulus._get_surface())
overlap = self_mask.overlap_area(other_mask, offset)
if overlap > 0 and overlap == self_mask.count():
return True
else:
return False
elif mode == "surface":
screen_size = expyriment._active_exp.screen.surface.get_size()
sx = self.absolute_position[0] + screen_size[0] / 2
sy = self.absolute_position[1] + screen_size[1] / 2
selfrect = pygame.Rect((0, 0), self.surface_size)
selfrect.center = (sx, sy)
ox = stimulus.absolute_position[0] + screen_size[0] / 2
oy = stimulus.absolute_position[1] + screen_size[1] / 2
stimrect = pygame.Rect((0, 0), stimulus.surface_size)
stimrect.right = stimrect.right + 1
stimrect.bottom = stimrect.bottom + 1
stimrect.center = (ox, oy)
if selfrect.contains(stimrect):
return True
else:
return False
def overlapping_with_stimulus(self, stimulus, mode="visible",
use_absolute_position=True):
"""Check if stimulus is overlapping with another stimulus.
Parameters
----------
stimulus : expyriment stimulus
the other stimulus
mode : mode (str), optional
"visible": based on non-transparent pixels or
"surface": based on pixels in pygame surface
(default = visible")
use_absolute_position : bool, optional
use absolute_position of stimuli (default) instead of position
Returns
-------
overlapping : bool
are stimuli overlapping or not
overlap : (int, int)
the overlap (x, y) in pixels. If mode is 'surface', the argument
will always be None.
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
if mode == "visible":
screen_size = expyriment._active_exp.screen.surface.get_size()
self_size = self.surface_size
other_size = stimulus.surface_size
if use_absolute_position:
self_pos = (self.absolute_position[0] + screen_size[0] / 2 -
self_size[0] / 2,
- self.absolute_position[1] + screen_size[1] / 2 -
self_size[1] / 2)
other_pos = (stimulus.absolute_position[0] + screen_size[0] / 2
- other_size[0] / 2,
- stimulus.absolute_position[1] + screen_size[1] /
2 - other_size[1] / 2)
else:
self_pos = (self.position[0] + screen_size[0] / 2 -
self_size[0] / 2,
- self.position[1] + screen_size[1] / 2 -
self_size[1] / 2)
other_pos = (stimulus.position[0] + screen_size[0] / 2 -
other_size[0] / 2,
- stimulus.position[1] + screen_size[1] / 2 -
other_size[1] / 2)
offset = (-self_pos[0] + other_pos[0], -self_pos[1] + other_pos[1])
self_mask = pygame.mask.from_surface(self._get_surface())
other_mask = pygame.mask.from_surface(stimulus._get_surface())
overlap = self_mask.overlap_area(other_mask, offset)
if overlap > 0:
return True, overlap
else:
return False, overlap
elif mode == "surface":
screen_size = expyriment._active_exp.screen.surface.get_size()
if use_absolute_position:
sx = self.absolute_position[0] + screen_size[0] / 2
sy = self.absolute_position[1] + screen_size[1] / 2
ox = stimulus.absolute_position[0] + screen_size[0] / 2
oy = stimulus.absolute_position[1] + screen_size[1] / 2
else:
sx = self.position[0] + screen_size[0] / 2
sy = self.position[1] + screen_size[1] / 2
ox = stimulus.position[0] + screen_size[0] / 2
oy = stimulus.position[1] + screen_size[1] / 2
selfrect = pygame.Rect((0, 0), self.surface_size)
selfrect.center = (sx, sy)
stimrect = pygame.Rect((0, 0), stimulus.surface_size)
stimrect.right = stimrect.right + 1
stimrect.bottom = stimrect.bottom + 1
stimrect.center = (ox, oy)
if selfrect.colliderect(stimrect):
return True, None
else:
return False, None
def overlapping_with_position(self, position, mode="visible",
use_absolute_position=True):
"""Check if stimulus is overlapping with a certain position.
Parameters
----------
position : (int, int)
position to check for overlapping
mode : mode (str), optional
"visible": based on non-transparent pixels or
"rectangle": based on pixels in pygame surface
(default = visible")
use_absolute_position : bool, optional
use absolute_position of stimulus (default) instead of position
Returns
-------
overlapping : bool
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
if mode == "visible":
screen_size = expyriment._active_exp.screen.surface.get_size()
self_size = self.surface_size
if use_absolute_position:
self_pos = (
(self.absolute_position[0] + screen_size[0] / 2) -
self_size[0] / 2,
(-self.absolute_position[1] + screen_size[1] / 2) -
self_size[1] / 2)
else:
self_pos = (
(self.position[0] + screen_size[0] / 2) - self_size[0] / 2,
(-self.position[1] + screen_size[1] / 2) - self_size[1] /
2)
pos = (position[0] + screen_size[0] / 2,
- position[1] + screen_size[1] / 2)
offset = (int(pos[0] - self_pos[0]), int(pos[1] - self_pos[1]))
self_mask = pygame.mask.from_surface(self._get_surface())
overlap = False
if 0 <= offset[0] < self_size[0] and 0 <= offset[1] < self_size[1]:
overlap = self_mask.get_at(offset)
if overlap > 0:
overlap = True
else:
overlap = False
return overlap
elif mode == "surface":
screen_size = expyriment._active_exp.screen.surface.get_size()
if use_absolute_position:
sx = self.absolute_position[0] + screen_size[0] / 2
sy = self.absolute_position[1] + screen_size[1] / 2
else:
sx = self.position[0] + screen_size[0] / 2
sy = self.position[1] + screen_size[1] / 2
selfrect = pygame.Rect((0, 0), self.surface_size)
selfrect.center = (sx, sy)
p = (position[0] + screen_size[0] / 2,
position[1] + screen_size[1] / 2)
if selfrect.collidepoint(p):
return True
else:
return False
def plot(self, stimulus):
"""Plot the stimulus on the surface of another stimulus.
Use this to plot more than one stimulus and to present them at the
same time afterwards by presenting the stimulus on which they were
plotted on.
Parameters
----------
stimulus : expyriment stimulus
stimulus to whose surface should be plotted
Returns
-------
time : int
the time it took to execute this method
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
start = get_time()
if not stimulus._set_surface(stimulus._get_surface()):
raise RuntimeError(Visual._compression_exception_message.format(
"plot()"))
stimulus.unload(keep_surface=True)
self._parent = stimulus
rect = pygame.Rect((0, 0), self.surface_size)
stimulus_surface_size = stimulus.surface_size
rect.center = [self.position[0] + stimulus_surface_size[0] / 2,
- self.position[1] + stimulus_surface_size[1] / 2]
stimulus._get_surface().blit(self._get_surface(), rect)
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,plotted,{0},{1}".format(self.id, stimulus.id), 2)
return int((get_time() - start) * 1000)
def clear_surface(self):
"""Clear the stimulus surface.
Surfaces are automatically created after any surface operation
(presenting, plotting, rotating, scaling, flipping etc.) and preloading.
If the stimulus was preloaded, this method unloads the stimulus.
This method is functionally equivalent with unload(keep_surface=False).
Returns
-------
time : int
the time it took to execute this method
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
start = get_time()
if self.is_preloaded:
self.unload(keep_surface=False)
self._is_compressed = False
self._set_surface(None)
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,surface cleared,{0}".format(self.id), 2)
return int((get_time() - start) * 1000)
def compress(self):
""""Compress the stimulus.
This will create a temporary file on the disk where the surface of the
stimululs is written to.
The surface will now be read from the disk to free memory.
Compressed stimuli cannot do surface operations!
Preloading comressed stimuli is possible and highly recommended.
Depending on the size of the stimulus, this method may take some time
to compute!
Returns
-------
time : int
the time it took to execute this method
"""
start = get_time()
if self.is_compressed is False:
if self._compression_filename is None:
fid, self._compression_filename = tempfile.mkstemp(
dir=defaults.tempdir, suffix=".tga")
os.close(fid)
pygame.image.save(self._get_surface(), self._compression_filename)
self._is_compressed = True
self._surface = None
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,compressed,{0}".format(self.id), 2)
return int((get_time() - start) * 1000)
def decompress(self):
"""Decompress the stimulus.
This will decompress the stimulus.
The surface will now be read from memory again.
Depending on the size of the stimulus, this method may take some time
to compute!
Returns
-------
time : int
the time it took to execute this method
"""
start = get_time()
if self.is_compressed:
self._surface = pygame.image.load(
self._compression_filename).convert_alpha()
self._is_compressed = False
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,decompressed,{0}".format(self.id), 2)
return int((get_time() - start) * 1000)
def preload(self, inhibit_ogl_compress=False):
"""Preload the stimulus to memory.
This will prepare the stimulus for a fast presentation.
In OpenGL mode this method creates an OpenGL texture based on the
surface of the stimulus.
When OpenGL is switched off, this method will create a surface if it
doesn't exists yet.
If stimuli are not preloaded manually, this will happen
automatically during presentation. However, stimulus presentation will
take some time then!
Always preload your stimuli when a timing acurate presentation is
needed!
Parameters
----------
inhibit_ogl_compress : bool, optional
inhibits OpenGL stimuli to be automatically compressed
(default=False)
Returns
-------
time : int
the time it took to execute this method
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
start = get_time()
if not expyriment._active_exp.is_initialized:
message = "Can't preload stimulus. Expyriment needs to be " + \
"initilized before preloading a stimulus."
raise RuntimeError(message)
self._was_compressed_before_preload = self.is_compressed
if not self.is_preloaded:
if expyriment._active_exp.screen.open_gl:
self._ogl_screen = _LaminaPanelSurface(
self._get_surface(),
position=self.position)
if not inhibit_ogl_compress:
self.compress()
else:
self.decompress()
self._set_surface(self._get_surface())
self._is_preloaded = True
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,preloaded,{0}".format(self.id), 2)
return int((get_time() - start) * 1000)
def unload(self, keep_surface=False):
"""Unload the stimulus from memory.
This will unload preloaded stimuli.
In OpenGL mode, this method will remove the reference to the OpenGL
texture and the surface (when 'keep_surface' is False).
When OpenGL is switched off, the reference to the surface will be
removed (when 'keep_surface' is False).
Parameters
----------
keep_surface : bool, optional
keep the surface after unload (default=False)
Returns
-------
time : int
the time it took to execute this method
See Also
--------
clear_surface.
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
start = get_time()
if expyriment._active_exp.screen.open_gl:
self._ogl_screen = None
if self.is_preloaded and not self._was_compressed_before_preload \
and keep_surface:
self.decompress()
else: # Pygame surface
if self.is_preloaded and self._was_compressed_before_preload \
and keep_surface:
self.compress()
if self.is_preloaded and self._logging:
expyriment._active_exp._event_file_log("Stimulus,unloaded,{0}"\
.format(self.id), 2)
if not keep_surface:
self._is_compressed = False
self._surface = None
if self._logging:
expyriment._active_exp._event_file_log("Stimulus,surface cleared,{0}"\
.format(self.id), 2)
self._is_preloaded = False
return int((get_time() - start) * 1000)
@property
def is_preloaded(self):
"""Getter for is_preloaded."""
return self._is_preloaded
def present(self, clear=True, update=True):
"""Present the stimulus on the screen.
This clears and updates the screen automatically.
When not preloaded, depending on the size of the stimulus, this method
can take some time to compute!
Parameters
----------
clear : bool, optional
if True the screen will be cleared automatically
(default = True)
update : bool, optional
if False the screen will be not be updated automatically
(default = True)
Returns
-------
time : int
the time it took to execute this method
"""
if not expyriment._active_exp.is_initialized or\
expyriment._active_exp.screen is None:
raise RuntimeError("Cannot not find a screen!")
start = get_time()
preloading_required = not(self.is_preloaded)
if clear:
expyriment._active_exp.screen.clear()
if preloading_required:
# Check if stimulus has surface
keep_surface = self.has_surface
self.preload(inhibit_ogl_compress=True)
if expyriment._active_exp.screen.open_gl:
self._ogl_screen.display()
else:
screen = expyriment._active_exp.screen.surface
rect = pygame.Rect((0, 0), self.surface_size)
screen_size = screen.get_size()
rect.center = [self.position[0] + screen_size[0] / 2,
- self.position[1] + screen_size[1] / 2]
screen.blit(self._get_surface(), rect)
if self._logging:
expyriment._active_exp._event_file_log("Stimulus,presented,{0}"\
.format(self.id), 1)
if update:
expyriment._active_exp.screen.update()
if preloading_required:
self.unload(keep_surface=keep_surface)
return int((get_time() - start) * 1000)
def save(self, filename):
"""Save the stimulus as image.
Parameters
----------
filename : str
name of the file to write (possible extensions are BMP, TGA, PNG,
or JPEG with TGA being the default)
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
parts = filename.split(".")
if len(parts) > 1:
parts[-1] = parts[-1].lower()
else:
parts.append("tga")
filename = ".".join(parts)
pygame.image.save(self._get_surface(), unicode2str(filename))
def picture(self):
"""Return the stimulus as Picture stimulus.
This will create a temporary file on the hard disk where the image is
saved to.
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
import _picture
fid, location = tempfile.mkstemp(dir=defaults.tempdir,
suffix=".tga")
os.close(fid)
pygame.image.save(self._get_surface(), location)
return _picture.Picture(filename=location)
def rotate(self, degree):
"""Rotate the stimulus.
This is a surface operation. After this, a surface will be present!
Rotating goes along with a quality loss. Thus, rotating an already
rotated stimulus is not a good idea.
Parameters
----------
degree : int
degree to rotate counterclockwise
Returns
-------
time : int
the time it took to execute this method
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
start = get_time()
if not self._set_surface(self._get_surface()):
raise RuntimeError(Visual._compression_exception_message.format(
"rotate()"))
self.unload(keep_surface=True)
self._set_surface(pygame.transform.rotate(self._get_surface(),
degree))
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,rotated,{0}, degree={1}".format(self.id, degree))
return int((get_time() - start) * 1000)
def scale(self, factors):
"""Scale the stimulus.
This is a surface operation. After this, a surface will be present!
Negative scaling values will flip the stimulus.
Scaling goes along with a quality loss. Thus, scaling an already
scaled stimulus is not a good idea.
Parameters
----------
factors : (int, int) or (float, float)
tuple representing the x and y factors to scale or a single number.
In the case of a single number x and y scaling will be the
identical (i.e., proportional scaling)
Returns
-------
time : int
the time it took to execute this method
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
start = get_time()
if not self._set_surface(self._get_surface()):
raise RuntimeError(Visual._compression_exception_message.format(
"scale()"))
self.unload(keep_surface=True)
flip = [False, False]
if type(factors) in [types.IntType, types.FloatType]:
factors = [factors, factors]
else:
factors = list(factors)
if factors[0] < 0:
flip[0] = True
factors[0] = abs(factors[0])
if factors[1] < 0:
flip[1] = True
factors[1] = abs(factors[1])
self._set_surface(pygame.transform.smoothscale(
self._get_surface(),
(int(round(self.surface_size[0] * factors[0])),
int(round(self.surface_size[1] * factors[1])))))
if True in flip:
self.flip(flip)
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,sclaed,{0}, factors={1}".format(self.id, factors), 2)
return int((get_time() - start) * 1000)
def flip(self, booleans):
"""Flip the stimulus.
This is a surface operation. After this, a surface will be present!
Parameters
----------
booleans : (bool, bool)
booleans to flip or not
Returns
-------
time : int
the time it took to execute this method
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
start = get_time()
if not self._set_surface(self._get_surface()):
raise RuntimeError(Visual._compression_exception_message.format(
"flip()"))
self.unload(keep_surface=True)
self._set_surface(pygame.transform.flip(self._get_surface(),
booleans[0], booleans[1]))
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,flipped,{0}, booleans={1}".format(self.id, booleans), 2)
return int((get_time() - start) * 1000)
def blur(self, level):
"""Blur the stimulus.
This blurs the stimulus, by scaling it down and up by the factor of
'level'.
Parameters
----------
level : int
level of bluring
Returns
-------
time : int
the time it took to execute this method
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
start = get_time()
self.scale((1.0 / level, 1.0 / level))
self.scale((level, level))
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,blured,{0}, level={1}".format(self.id, level), 2)
return int((get_time() - start) * 1000)
def scramble(self, grain_size):
"""Scramble the stimulus.
Attention: If the surface size is not a multiple of the grain size,
you may loose some pixels on the edge.
Parameters
----------
grain_size : int or (int, int)
size of a grain (use tuple of integers for different width & height)
Returns
-------
time : int
the time it took to execute this method
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
start = get_time()
if type(grain_size) is int:
grain_size = [grain_size, grain_size]
# Make Rect list
if not self._set_surface(self._get_surface()):
raise RuntimeError(Visual._compression_exception_message.format(
"scramble()"))
s = self.surface_size
source = []
for r in range(s[1] / int(grain_size[1])):
for c in range(s[0] / int(grain_size[0])):
xy = (c * int(grain_size[0]), r * int(grain_size[1]))
source.append(pygame.Rect(xy, grain_size))
# Make copy and shuffle
dest = copy.deepcopy(source)
random.shuffle(dest)
# Create a new surface
tmp_surface = pygame.surface.Surface(
s, pygame.SRCALPHA).convert_alpha()
for n, s in enumerate(source):
tmp_surface.blit(self._get_surface(), dest[n], s)
self._set_surface(tmp_surface)
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,scrambled,{0}, grain_size={1}".format(
self.id, grain_size), 2)
return int((get_time() - start) * 1000)
def add_noise(self, grain_size, percentage, colour):
"""Add visual noise on top of the stimulus.
This function might take very long for large stimuli.
Parameters
----------
grain_size : int
size of the grains for the noise
percentage : int
percentage of covered area
colour : (int, int, int)
colour (RGB) of the noise
Returns
-------
time : int
the time it took to execute this method
Notes
-----
Depending on the size of the stimulus, this method may take some time
to compute!
"""
import _rectangle
start = get_time()
if not self._set_surface(self._get_surface()):
raise RuntimeError(Visual._compression_exception_message.format(
"add_noise()"))
self.unload(keep_surface=True)
number_of_pixel_x = int(self.surface_size[0] / grain_size) + 1
number_of_pixel_y = int(self.surface_size[1] / grain_size) + 1
seq = range(number_of_pixel_x * number_of_pixel_y)
random.seed()
random.shuffle(seq)
for idx in seq[:int(len(seq) * (percentage) / 100.0)]:
x = (idx % number_of_pixel_x) * grain_size
x = int(self.surface_size[0] / 2 - grain_size / 2 - x)
y = (idx / number_of_pixel_x) * grain_size
y = int(self.surface_size[1] / 2 - grain_size / 2 - y)
dot = _rectangle.Rectangle(size=(grain_size, grain_size),
position=(x, y), colour=colour)
dot.plot(self)
if self._logging:
expyriment._active_exp._event_file_log(
"Stimulus,noise added,{0}, grain_size={1}, percentage={2}"\
.format(self.id, grain_size, percentage))
return int((get_time() - start) * 1000)
|